fix(custom-widgets): isolate workbench typing updates
This commit is contained in:
1 parent
b742840e96
commit
d875fb9a75
15 files changed
+888
-350
No files matched your search
@@ -10,32 +10,48 @@ import { useI18n } from "@homarr/translation/client";
|
|||||||
|
|
||||||
import { useOptionalHomarrAssistant } from "~/components/assistant/assistant-context";
|
import { useOptionalHomarrAssistant } from "~/components/assistant/assistant-context";
|
||||||
|
|
||||||
interface CopyAiPromptButtonProps {
|
interface CopyAiPromptButtonBaseProps {
|
||||||
rawResponse?: string | null;
|
rawResponse?: string | null;
|
||||||
draft: CustomWidgetAiDraft;
|
|
||||||
diagnostics: readonly CustomWidgetAiDiagnostic[];
|
|
||||||
request?: string | null;
|
request?: string | null;
|
||||||
documentationUrl?: string | null;
|
documentationUrl?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CopyAiPromptButtonProps = CopyAiPromptButtonBaseProps &
|
||||||
|
({ draft: CustomWidgetAiDraft; getDraft?: never } | { draft?: never; getDraft(): CustomWidgetAiDraft }) &
|
||||||
|
(
|
||||||
|
| { diagnostics: readonly CustomWidgetAiDiagnostic[]; getDiagnostics?: never }
|
||||||
|
| { diagnostics?: never; getDiagnostics(): readonly CustomWidgetAiDiagnostic[] }
|
||||||
|
);
|
||||||
|
|
||||||
export const CopyAiPromptButton = ({
|
export const CopyAiPromptButton = ({
|
||||||
rawResponse,
|
rawResponse,
|
||||||
draft,
|
draft,
|
||||||
|
getDraft,
|
||||||
diagnostics,
|
diagnostics,
|
||||||
|
getDiagnostics,
|
||||||
request,
|
request,
|
||||||
documentationUrl,
|
documentationUrl,
|
||||||
}: CopyAiPromptButtonProps) => {
|
}: CopyAiPromptButtonProps) => {
|
||||||
const t = useI18n("customWidget");
|
const t = useI18n("customWidget");
|
||||||
const assistant = useOptionalHomarrAssistant();
|
const assistant = useOptionalHomarrAssistant();
|
||||||
|
|
||||||
|
const readDraft = () => {
|
||||||
|
if (getDraft) return getDraft();
|
||||||
|
return draft;
|
||||||
|
};
|
||||||
|
const readDiagnostics = () => {
|
||||||
|
if (getDiagnostics) return getDiagnostics();
|
||||||
|
return diagnostics;
|
||||||
|
};
|
||||||
|
|
||||||
const handleAssistant = () => {
|
const handleAssistant = () => {
|
||||||
const prompt = buildCustomWidgetAssistantPrompt(
|
const prompt = buildCustomWidgetAssistantPrompt(
|
||||||
undefined,
|
undefined,
|
||||||
rawResponse,
|
rawResponse,
|
||||||
draft,
|
readDraft(),
|
||||||
request,
|
request,
|
||||||
documentationUrl,
|
documentationUrl,
|
||||||
diagnostics,
|
readDiagnostics(),
|
||||||
);
|
);
|
||||||
if (!assistant?.enabled || !assistant.sendPrompt(prompt)) return;
|
if (!assistant?.enabled || !assistant.sendPrompt(prompt)) return;
|
||||||
showSuccessNotification({ title: t("action.aiPrompt"), message: t("notification.aiPromptSent") });
|
showSuccessNotification({ title: t("action.aiPrompt"), message: t("notification.aiPromptSent") });
|
||||||
@@ -43,7 +59,14 @@ export const CopyAiPromptButton = ({
|
|||||||
|
|
||||||
const handleCopy = async () => {
|
const handleCopy = async () => {
|
||||||
try {
|
try {
|
||||||
const value = buildCustomWidgetAiPrompt(undefined, rawResponse, draft, request, documentationUrl, diagnostics);
|
const value = buildCustomWidgetAiPrompt(
|
||||||
|
undefined,
|
||||||
|
rawResponse,
|
||||||
|
readDraft(),
|
||||||
|
request,
|
||||||
|
documentationUrl,
|
||||||
|
readDiagnostics(),
|
||||||
|
);
|
||||||
await navigator.clipboard.writeText(value);
|
await navigator.clipboard.writeText(value);
|
||||||
showSuccessNotification({
|
showSuccessNotification({
|
||||||
title: t("action.copyAiPrompt"),
|
title: t("action.copyAiPrompt"),
|
||||||
|
|||||||
+9
-7
@@ -6,6 +6,7 @@ import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
|
|||||||
import { useI18n } from "@homarr/translation/client";
|
import { useI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
import { CodeEditor } from "./_code-editor";
|
import { CodeEditor } from "./_code-editor";
|
||||||
|
import { useDeferredCustomWidgetFormDocumentValues } from "./_custom-widget-form-state";
|
||||||
import { applyDefinition, parseJson } from "./_custom-widget-form-utils";
|
import { applyDefinition, parseJson } from "./_custom-widget-form-utils";
|
||||||
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
|
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
|
||||||
import { LazyOnceAccordion } from "./_lazy-once-accordion";
|
import { LazyOnceAccordion } from "./_lazy-once-accordion";
|
||||||
@@ -21,16 +22,17 @@ export function CustomWidgetAdvancedManifest({ form }: { form: CustomWidgetWorkb
|
|||||||
|
|
||||||
function CustomWidgetManifestEditor({ form }: { form: CustomWidgetWorkbenchForm }) {
|
function CustomWidgetManifestEditor({ form }: { form: CustomWidgetWorkbenchForm }) {
|
||||||
const t = useI18n("customWidget.workbench.builder");
|
const t = useI18n("customWidget.workbench.builder");
|
||||||
|
const values = useDeferredCustomWidgetFormDocumentValues();
|
||||||
const serialized = JSON.stringify(
|
const serialized = JSON.stringify(
|
||||||
{
|
{
|
||||||
$schema: "homarr-custom-widget-v2",
|
$schema: "homarr-custom-widget-v2",
|
||||||
name: form.values.name,
|
name: values.name,
|
||||||
...(form.values.description ? { description: form.values.description } : {}),
|
...(values.description ? { description: values.description } : {}),
|
||||||
...(form.values.iconUrl ? { iconUrl: form.values.iconUrl } : {}),
|
...(values.iconUrl ? { iconUrl: values.iconUrl } : {}),
|
||||||
sources: parseJson(form.values.sources),
|
sources: parseJson(values.sources),
|
||||||
requests: parseJson(form.values.requests),
|
requests: parseJson(values.requests),
|
||||||
options: parseJson(form.values.options),
|
options: parseJson(values.options),
|
||||||
template: form.values.template,
|
template: values.template,
|
||||||
},
|
},
|
||||||
null,
|
null,
|
||||||
2,
|
2,
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ import { useI18n } from "@homarr/translation/client";
|
|||||||
import { CopyAiPromptButton } from "./_copy-ai-prompt-button";
|
import { CopyAiPromptButton } from "./_copy-ai-prompt-button";
|
||||||
|
|
||||||
interface AiCardProps {
|
interface AiCardProps {
|
||||||
draft: CustomWidgetAiDraft;
|
getDraft(): CustomWidgetAiDraft;
|
||||||
diagnostics: readonly CustomWidgetAiDiagnostic[];
|
getDiagnostics(): readonly CustomWidgetAiDiagnostic[];
|
||||||
request: string;
|
request: string;
|
||||||
onRequestChange(value: string): void;
|
onRequestChange(value: string): void;
|
||||||
documentationUrl: string;
|
documentationUrl: string;
|
||||||
@@ -28,8 +28,8 @@ export function CustomWidgetAiCard(props: AiCardProps) {
|
|||||||
{t("title")}
|
{t("title")}
|
||||||
</Accordion.Control>
|
</Accordion.Control>
|
||||||
<CopyAiPromptButton
|
<CopyAiPromptButton
|
||||||
draft={props.draft}
|
getDraft={props.getDraft}
|
||||||
diagnostics={props.diagnostics}
|
getDiagnostics={props.getDiagnostics}
|
||||||
request={props.request}
|
request={props.request}
|
||||||
documentationUrl={props.documentationUrl}
|
documentationUrl={props.documentationUrl}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,14 +1,39 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { ReactNode } from "react";
|
import { useEffect } from "react";
|
||||||
|
import type { Dispatch, ReactNode, SetStateAction } from "react";
|
||||||
import type { Icon } from "@tabler/icons-react";
|
import type { Icon } from "@tabler/icons-react";
|
||||||
import { Button, Card, Group, Stack, Text, ThemeIcon } from "@mantine/core";
|
import { Button, Card, Group, Stack, Text, ThemeIcon } from "@mantine/core";
|
||||||
import { IconAlertTriangle, IconCheck, IconPlayerPlay } from "@tabler/icons-react";
|
import {
|
||||||
|
IconAlertCircle,
|
||||||
|
IconAlertTriangle,
|
||||||
|
IconApi,
|
||||||
|
IconBraces,
|
||||||
|
IconCheck,
|
||||||
|
IconCode,
|
||||||
|
IconDatabase,
|
||||||
|
IconEye,
|
||||||
|
IconPlayerPlay,
|
||||||
|
IconSettings,
|
||||||
|
} from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { getCustomWidgetDefaultOptions } from "@homarr/custom-widgets/core";
|
||||||
import { useI18n } from "@homarr/translation/client";
|
import { useI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
|
import { useCustomWidgetFormDocumentDirty } from "./_custom-widget-form-state";
|
||||||
|
import { useCustomWidgetFormAnalysisField } from "./_use-custom-widget-form-analysis";
|
||||||
|
import { useUnsavedChangesGuard } from "./_use-unsaved-changes-guard";
|
||||||
import classes from "./_custom-widget-form.module.css";
|
import classes from "./_custom-widget-form.module.css";
|
||||||
|
|
||||||
|
const sectionLinks = [
|
||||||
|
["general", "section.general", IconSettings],
|
||||||
|
["sources", "section.sources", IconApi],
|
||||||
|
["requests", "section.requests", IconDatabase],
|
||||||
|
["options", "section.options", IconBraces],
|
||||||
|
["jsx", "section.jsx", IconCode],
|
||||||
|
["preview", "section.preview", IconEye],
|
||||||
|
] as const;
|
||||||
|
|
||||||
export function EditorSection({
|
export function EditorSection({
|
||||||
id,
|
id,
|
||||||
title,
|
title,
|
||||||
@@ -84,3 +109,78 @@ export function SaveActions({
|
|||||||
</Group>
|
</Group>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetSectionNavigation({
|
||||||
|
onSelect,
|
||||||
|
}: {
|
||||||
|
onSelect(section: (typeof sectionLinks)[number][0]): void;
|
||||||
|
}) {
|
||||||
|
const t = useI18n("customWidget.workbench");
|
||||||
|
const invalidSections = useCustomWidgetFormAnalysisField("invalidSections");
|
||||||
|
return (
|
||||||
|
<nav className={classes.sectionNav} aria-label={t("sectionNavigation")}>
|
||||||
|
{sectionLinks.map(([id, key, SectionIcon]) => {
|
||||||
|
const invalid = invalidSections.has(id);
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
key={id}
|
||||||
|
component="a"
|
||||||
|
href={`#${id}`}
|
||||||
|
onClick={() => onSelect(id)}
|
||||||
|
size="compact-sm"
|
||||||
|
variant="subtle"
|
||||||
|
color={invalid ? "red" : undefined}
|
||||||
|
leftSection={<SectionIcon size={14} />}
|
||||||
|
rightSection={invalid ? <IconAlertCircle size={13} aria-label={t("status.invalid")} /> : undefined}
|
||||||
|
>
|
||||||
|
{t(key)}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetSaveActions({
|
||||||
|
mode,
|
||||||
|
savePending,
|
||||||
|
previewPending,
|
||||||
|
onPreview,
|
||||||
|
}: {
|
||||||
|
mode: "create" | "edit";
|
||||||
|
savePending: boolean;
|
||||||
|
previewPending: boolean;
|
||||||
|
onPreview(): void;
|
||||||
|
}) {
|
||||||
|
const dirty = useCustomWidgetFormDocumentDirty();
|
||||||
|
const candidateValid = useCustomWidgetFormAnalysisField("candidateValid");
|
||||||
|
const hasDiagnostics = useCustomWidgetFormAnalysisField("hasDiagnostics");
|
||||||
|
return (
|
||||||
|
<SaveActions
|
||||||
|
dirty={dirty}
|
||||||
|
savePending={savePending}
|
||||||
|
previewPending={previewPending}
|
||||||
|
invalid={hasDiagnostics || !candidateValid}
|
||||||
|
mode={mode}
|
||||||
|
onPreview={onPreview}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetUnsavedChangesGuard() {
|
||||||
|
const dirty = useCustomWidgetFormDocumentDirty();
|
||||||
|
useUnsavedChangesGuard(dirty);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetOptionsSnapshotSync({
|
||||||
|
setOptionsSnapshot,
|
||||||
|
}: {
|
||||||
|
setOptionsSnapshot: Dispatch<SetStateAction<Record<string, unknown>>>;
|
||||||
|
}) {
|
||||||
|
const parsedOptions = useCustomWidgetFormAnalysisField("parsedOptions");
|
||||||
|
useEffect(() => {
|
||||||
|
if (parsedOptions.success) setOptionsSnapshot(getCustomWidgetDefaultOptions(parsedOptions.data));
|
||||||
|
}, [parsedOptions, setOptionsSnapshot]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import type { Dispatch, SetStateAction } from "react";
|
||||||
|
import { TextInput, Textarea } from "@mantine/core";
|
||||||
|
import { IconApi, IconBraces, IconCode, IconDatabase, IconSettings } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import type { CustomWidgetAiDiagnostic, CustomWidgetAiDraft } from "@homarr/custom-widgets/authoring-prompt";
|
||||||
|
import { IconPicker } from "@homarr/forms-collection";
|
||||||
|
import { useI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
|
import { CodeEditor } from "./_code-editor";
|
||||||
|
import { CustomWidgetAiCard } from "./_custom-widget-ai-card";
|
||||||
|
import { EditorSection } from "./_custom-widget-form-layout";
|
||||||
|
import { customWidgetOptionsSchemaReference, customWidgetRequestReference } from "./_custom-widget-form-references";
|
||||||
|
import { useCustomWidgetFormDocumentField } from "./_custom-widget-form-state";
|
||||||
|
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
|
||||||
|
import { CustomWidgetOptionsEditor } from "./_custom-widget-options-editor";
|
||||||
|
import { CustomWidgetPreviewPanel } from "./_custom-widget-preview-panel";
|
||||||
|
import type { PreviewState } from "./_custom-widget-preview-panel";
|
||||||
|
import { CustomWidgetRequestsEditor } from "./_custom-widget-requests-editor";
|
||||||
|
import { CustomWidgetSourcesEditor } from "./_custom-widget-sources-editor";
|
||||||
|
import { LazyOnceAccordion } from "./_lazy-once-accordion";
|
||||||
|
import { useCustomWidgetFormAnalysisField } from "./_use-custom-widget-form-analysis";
|
||||||
|
|
||||||
|
export function CustomWidgetAiSection({
|
||||||
|
getDraft,
|
||||||
|
getDiagnostics,
|
||||||
|
onPaste,
|
||||||
|
}: {
|
||||||
|
getDraft(): CustomWidgetAiDraft;
|
||||||
|
getDiagnostics(): readonly CustomWidgetAiDiagnostic[];
|
||||||
|
onPaste(): void;
|
||||||
|
}) {
|
||||||
|
const [request, setRequest] = useState("");
|
||||||
|
const [documentationUrl, setDocumentationUrl] = useState("");
|
||||||
|
return (
|
||||||
|
<CustomWidgetAiCard
|
||||||
|
getDraft={getDraft}
|
||||||
|
getDiagnostics={getDiagnostics}
|
||||||
|
request={request}
|
||||||
|
onRequestChange={setRequest}
|
||||||
|
documentationUrl={documentationUrl}
|
||||||
|
onDocumentationUrlChange={setDocumentationUrl}
|
||||||
|
onPaste={onPaste}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetGeneralSection({
|
||||||
|
form,
|
||||||
|
formRevision,
|
||||||
|
mode,
|
||||||
|
}: {
|
||||||
|
form: CustomWidgetWorkbenchForm;
|
||||||
|
formRevision: string;
|
||||||
|
mode: "create" | "edit";
|
||||||
|
}) {
|
||||||
|
const t = useI18n("customWidget");
|
||||||
|
const tCommon = useI18n("common");
|
||||||
|
const w = useI18n("customWidget.workbench");
|
||||||
|
const [suggestedIconSearch, setSuggestedIconSearch] = useState(() => form.getValues().name);
|
||||||
|
const iconUrl = useCustomWidgetFormDocumentField("iconUrl");
|
||||||
|
const nameInputProps = form.getInputProps("name");
|
||||||
|
useEffect(() => setSuggestedIconSearch(form.getValues().name), [form, formRevision]);
|
||||||
|
return (
|
||||||
|
<EditorSection id="general" title={w("generalInformation")} icon={IconSettings}>
|
||||||
|
<TextInput
|
||||||
|
key={form.key("name")}
|
||||||
|
label={tCommon("field.name")}
|
||||||
|
required
|
||||||
|
{...nameInputProps}
|
||||||
|
onBlur={(event) => {
|
||||||
|
nameInputProps.onBlur?.(event);
|
||||||
|
setSuggestedIconSearch(form.getValues().name);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Textarea
|
||||||
|
key={form.key("description")}
|
||||||
|
label={t("field.description")}
|
||||||
|
autosize
|
||||||
|
minRows={2}
|
||||||
|
{...form.getInputProps("description")}
|
||||||
|
/>
|
||||||
|
<IconPicker
|
||||||
|
key={form.key("iconUrl")}
|
||||||
|
withAsterisk={false}
|
||||||
|
suggestedSearch={mode === "create" ? suggestedIconSearch : undefined}
|
||||||
|
{...form.getInputProps("iconUrl")}
|
||||||
|
value={iconUrl}
|
||||||
|
/>
|
||||||
|
</EditorSection>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetSourcesSection({
|
||||||
|
form,
|
||||||
|
definitionId,
|
||||||
|
}: {
|
||||||
|
form: CustomWidgetWorkbenchForm;
|
||||||
|
definitionId?: string;
|
||||||
|
}) {
|
||||||
|
const w = useI18n("customWidget.workbench");
|
||||||
|
useCustomWidgetFormDocumentField("sources");
|
||||||
|
useCustomWidgetFormDocumentField("requests");
|
||||||
|
useCustomWidgetFormDocumentField("secrets");
|
||||||
|
return (
|
||||||
|
<EditorSection id="sources" title={w("sources.title")} icon={IconApi}>
|
||||||
|
<CustomWidgetSourcesEditor form={form} definitionId={definitionId} />
|
||||||
|
</EditorSection>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetRequestsSection({
|
||||||
|
form,
|
||||||
|
onRename,
|
||||||
|
}: {
|
||||||
|
form: CustomWidgetWorkbenchForm;
|
||||||
|
onRename(currentId: string, nextId: string): void;
|
||||||
|
}) {
|
||||||
|
const w = useI18n("customWidget.workbench");
|
||||||
|
const requests = useCustomWidgetFormDocumentField("requests");
|
||||||
|
useCustomWidgetFormDocumentField("sources");
|
||||||
|
useCustomWidgetFormDocumentField("options");
|
||||||
|
const requestDiagnostics = useCustomWidgetFormAnalysisField("requestDiagnostics");
|
||||||
|
return (
|
||||||
|
<EditorSection id="requests" title={w("requests.title")} icon={IconDatabase}>
|
||||||
|
<CustomWidgetRequestsEditor form={form} onRename={onRename} />
|
||||||
|
<LazyOnceAccordion label={w("builder.advancedJson")}>
|
||||||
|
<CodeEditor
|
||||||
|
id="requests-editor"
|
||||||
|
label={w("requests.label")}
|
||||||
|
description={w("requests.description")}
|
||||||
|
language="json"
|
||||||
|
value={requests}
|
||||||
|
onChange={(value) => form.setFieldValue("requests", value, { forceUpdate: false })}
|
||||||
|
diagnostics={requestDiagnostics}
|
||||||
|
error={form.errors.requests}
|
||||||
|
reference={customWidgetRequestReference}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</LazyOnceAccordion>
|
||||||
|
</EditorSection>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetOptionsSection({
|
||||||
|
form,
|
||||||
|
onRename,
|
||||||
|
}: {
|
||||||
|
form: CustomWidgetWorkbenchForm;
|
||||||
|
onRename(currentName: string, nextName: string): void;
|
||||||
|
}) {
|
||||||
|
const w = useI18n("customWidget.workbench");
|
||||||
|
const options = useCustomWidgetFormDocumentField("options");
|
||||||
|
useCustomWidgetFormDocumentField("requests");
|
||||||
|
return (
|
||||||
|
<EditorSection id="options" title={w("options.title")} icon={IconBraces}>
|
||||||
|
<CustomWidgetOptionsEditor form={form} onRename={onRename} />
|
||||||
|
<LazyOnceAccordion label={w("builder.advancedJson")}>
|
||||||
|
<CodeEditor
|
||||||
|
id="options-editor"
|
||||||
|
label={w("options.title")}
|
||||||
|
language="json"
|
||||||
|
value={options}
|
||||||
|
onChange={(value) => form.setFieldValue("options", value, { forceUpdate: false })}
|
||||||
|
error={form.errors.options}
|
||||||
|
reference={customWidgetOptionsSchemaReference}
|
||||||
|
/>
|
||||||
|
</LazyOnceAccordion>
|
||||||
|
</EditorSection>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetTemplateSection({ form }: { form: CustomWidgetWorkbenchForm }) {
|
||||||
|
const w = useI18n("customWidget.workbench");
|
||||||
|
const template = useCustomWidgetFormDocumentField("template");
|
||||||
|
const jsxCompletions = useCustomWidgetFormAnalysisField("jsxCompletions");
|
||||||
|
const templateDiagnostics = useCustomWidgetFormAnalysisField("templateDiagnostics");
|
||||||
|
return (
|
||||||
|
<EditorSection id="jsx" title={w("jsx.title")} icon={IconCode}>
|
||||||
|
<CodeEditor
|
||||||
|
id="jsx-editor"
|
||||||
|
label={w("jsx.label")}
|
||||||
|
language="jsx"
|
||||||
|
value={template}
|
||||||
|
onChange={(value) => form.setFieldValue("template", value, { forceUpdate: false })}
|
||||||
|
diagnostics={templateDiagnostics}
|
||||||
|
completions={jsxCompletions}
|
||||||
|
error={form.errors.template}
|
||||||
|
required
|
||||||
|
maxLength={50_000}
|
||||||
|
/>
|
||||||
|
</EditorSection>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CustomWidgetPreviewSectionProps {
|
||||||
|
preview: PreviewState;
|
||||||
|
size: string;
|
||||||
|
onSizeChange(size: string): void;
|
||||||
|
optionsSnapshot: Record<string, unknown>;
|
||||||
|
onOptionsChange: Dispatch<SetStateAction<Record<string, unknown>>>;
|
||||||
|
onLiveActionsChange(enabled: boolean): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomWidgetPreviewSection(props: CustomWidgetPreviewSectionProps) {
|
||||||
|
const previewCandidate = useCustomWidgetFormAnalysisField("previewCandidate");
|
||||||
|
const previewValidationIssues = useCustomWidgetFormAnalysisField("previewValidationIssues");
|
||||||
|
return (
|
||||||
|
<CustomWidgetPreviewPanel
|
||||||
|
candidate={previewCandidate}
|
||||||
|
validationIssues={previewValidationIssues}
|
||||||
|
preview={props.preview}
|
||||||
|
size={props.size}
|
||||||
|
onSizeChange={props.onSizeChange}
|
||||||
|
optionsSnapshot={props.optionsSnapshot}
|
||||||
|
onOptionsChange={props.onOptionsChange}
|
||||||
|
onLiveActionsChange={props.onLiveActionsChange}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
startTransition,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
useSyncExternalStore,
|
||||||
|
} from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import type { UseFormReturnType } from "@mantine/form";
|
||||||
|
|
||||||
|
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
|
||||||
|
|
||||||
|
export interface CustomWidgetFormDocumentStore {
|
||||||
|
getValues(): CustomWidgetFormValues;
|
||||||
|
setValues(values: CustomWidgetFormValues): void;
|
||||||
|
getDirty(): boolean;
|
||||||
|
subscribe(listener: () => void): () => void;
|
||||||
|
markSaved(values: CustomWidgetFormValues): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function areDocumentValuesEqual(left: CustomWidgetFormValues, right: CustomWidgetFormValues) {
|
||||||
|
const secretsEqual =
|
||||||
|
left.secrets.length === right.secrets.length &&
|
||||||
|
left.secrets.every((secret, index) => {
|
||||||
|
const other = right.secrets[index];
|
||||||
|
return (
|
||||||
|
other !== undefined &&
|
||||||
|
secret.sourceId === other.sourceId &&
|
||||||
|
secret.kind === other.kind &&
|
||||||
|
secret.value === other.value &&
|
||||||
|
secret.hasValue === other.hasValue
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
left.name === right.name &&
|
||||||
|
left.description === right.description &&
|
||||||
|
left.iconUrl === right.iconUrl &&
|
||||||
|
left.sources === right.sources &&
|
||||||
|
left.requests === right.requests &&
|
||||||
|
left.options === right.options &&
|
||||||
|
left.template === right.template &&
|
||||||
|
secretsEqual
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCustomWidgetFormDocumentStore(
|
||||||
|
initialValues: CustomWidgetFormValues,
|
||||||
|
): CustomWidgetFormDocumentStore {
|
||||||
|
let values = initialValues;
|
||||||
|
let persistedValues = initialValues;
|
||||||
|
let dirty = false;
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
const notify = () => listeners.forEach((listener) => listener());
|
||||||
|
|
||||||
|
return {
|
||||||
|
getValues: () => values,
|
||||||
|
setValues: (nextValues) => {
|
||||||
|
if (Object.is(values, nextValues)) return;
|
||||||
|
values = nextValues;
|
||||||
|
dirty = !areDocumentValuesEqual(nextValues, persistedValues);
|
||||||
|
notify();
|
||||||
|
},
|
||||||
|
getDirty: () => dirty,
|
||||||
|
subscribe: (listener) => {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => listeners.delete(listener);
|
||||||
|
},
|
||||||
|
markSaved: (savedValues) => {
|
||||||
|
const wasDirty = dirty;
|
||||||
|
persistedValues = savedValues;
|
||||||
|
dirty = !areDocumentValuesEqual(values, persistedValues);
|
||||||
|
if (wasDirty !== dirty) notify();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const CustomWidgetFormDocumentContext = createContext<CustomWidgetFormDocumentStore | null>(null);
|
||||||
|
|
||||||
|
export function CustomWidgetFormDocumentProvider({
|
||||||
|
store,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
store: CustomWidgetFormDocumentStore;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
return <CustomWidgetFormDocumentContext.Provider value={store}>{children}</CustomWidgetFormDocumentContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCustomWidgetFormDocumentStore() {
|
||||||
|
const store = useContext(CustomWidgetFormDocumentContext);
|
||||||
|
if (!store) throw new Error("Custom widget form document provider is missing");
|
||||||
|
return store;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeferredCustomWidgetFormDocumentValues() {
|
||||||
|
const store = useCustomWidgetFormDocumentStore();
|
||||||
|
const [values, setValues] = useState(() => store.getValues());
|
||||||
|
useEffect(() => {
|
||||||
|
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
const scheduleUpdate = () => {
|
||||||
|
const nextValues = store.getValues();
|
||||||
|
clearTimeout(timeout);
|
||||||
|
timeout = setTimeout(() => {
|
||||||
|
startTransition(() => {
|
||||||
|
setValues((currentValues) => {
|
||||||
|
if (!Object.is(store.getValues(), nextValues)) return currentValues;
|
||||||
|
return nextValues;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, 150);
|
||||||
|
};
|
||||||
|
const unsubscribe = store.subscribe(scheduleUpdate);
|
||||||
|
return () => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
unsubscribe();
|
||||||
|
};
|
||||||
|
}, [store]);
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCustomWidgetFormDocumentField<Key extends keyof CustomWidgetFormValues>(field: Key) {
|
||||||
|
const store = useCustomWidgetFormDocumentStore();
|
||||||
|
const getSnapshot = () => store.getValues()[field];
|
||||||
|
return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCustomWidgetFormDocumentDirty() {
|
||||||
|
const store = useCustomWidgetFormDocumentStore();
|
||||||
|
return useSyncExternalStore(store.subscribe, store.getDirty, store.getDirty);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCustomWidgetFormDocumentBridge(
|
||||||
|
form: UseFormReturnType<CustomWidgetFormValues>,
|
||||||
|
store: CustomWidgetFormDocumentStore,
|
||||||
|
) {
|
||||||
|
const formRef = useRef(form);
|
||||||
|
formRef.current = form;
|
||||||
|
return useMemo(
|
||||||
|
() =>
|
||||||
|
new Proxy({} as UseFormReturnType<CustomWidgetFormValues>, {
|
||||||
|
get: (_target, property) => {
|
||||||
|
if (property === "values") return store.getValues();
|
||||||
|
return Reflect.get(formRef.current, property);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
[store],
|
||||||
|
);
|
||||||
|
}
|
||||||
+2
-2
@@ -28,7 +28,7 @@ describe("Custom Widget workbench preview options", () => {
|
|||||||
const setValues = vi.fn();
|
const setValues = vi.fn();
|
||||||
const result = applyCustomWidgetAiResponse(
|
const result = applyCustomWidgetAiResponse(
|
||||||
{
|
{
|
||||||
values: {
|
getValues: () => ({
|
||||||
name: "",
|
name: "",
|
||||||
description: "",
|
description: "",
|
||||||
iconUrl: "",
|
iconUrl: "",
|
||||||
@@ -37,7 +37,7 @@ describe("Custom Widget workbench preview options", () => {
|
|||||||
options: "{}",
|
options: "{}",
|
||||||
template: "",
|
template: "",
|
||||||
secrets: [],
|
secrets: [],
|
||||||
},
|
}),
|
||||||
setValues,
|
setValues,
|
||||||
} as never,
|
} as never,
|
||||||
`\`\`\`json\n${JSON.stringify(definition)}\n\`\`\``,
|
`\`\`\`json\n${JSON.stringify(definition)}\n\`\`\``,
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export function filterSecretsForSourceAuthentication(
|
|||||||
|
|
||||||
export function applyDefinition(form: CustomWidgetWorkbenchForm, widget: HomarrCustomWidgetV2) {
|
export function applyDefinition(form: CustomWidgetWorkbenchForm, widget: HomarrCustomWidgetV2) {
|
||||||
form.setValues({
|
form.setValues({
|
||||||
...form.values,
|
...form.getValues(),
|
||||||
name: widget.name,
|
name: widget.name,
|
||||||
description: widget.description ?? "",
|
description: widget.description ?? "",
|
||||||
iconUrl: widget.iconUrl ?? "",
|
iconUrl: widget.iconUrl ?? "",
|
||||||
|
|||||||
@@ -1,41 +1,45 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { memo, useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Box, Button, Paper, SegmentedControl, Stack, TextInput, Textarea } from "@mantine/core";
|
import type { Dispatch, FormEventHandler, SetStateAction } from "react";
|
||||||
import {
|
import { Box, Paper, SegmentedControl, Stack } from "@mantine/core";
|
||||||
IconAlertCircle,
|
|
||||||
IconApi,
|
|
||||||
IconBraces,
|
|
||||||
IconCode,
|
|
||||||
IconDatabase,
|
|
||||||
IconEye,
|
|
||||||
IconSettings,
|
|
||||||
} from "@tabler/icons-react";
|
|
||||||
|
|
||||||
import { getCustomWidgetDefaultOptions } from "@homarr/custom-widgets/core";
|
import type { CustomWidgetAiDraft } from "@homarr/custom-widgets/authoring-prompt";
|
||||||
import { customWidgetFormSchema, DEFAULT_CUSTOM_WIDGET_FORM_VALUES } from "@homarr/custom-widgets/workbench";
|
import { customWidgetFormSchema, DEFAULT_CUSTOM_WIDGET_FORM_VALUES } from "@homarr/custom-widgets/workbench";
|
||||||
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
|
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
|
||||||
import { useZodForm } from "@homarr/form";
|
import { useZodForm } from "@homarr/form";
|
||||||
import { IconPicker } from "@homarr/forms-collection";
|
|
||||||
import { useI18n } from "@homarr/translation/client";
|
import { useI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
import { CodeEditor } from "./_code-editor";
|
|
||||||
import { CustomWidgetAiCard } from "./_custom-widget-ai-card";
|
|
||||||
import { CustomWidgetAdvancedManifest } from "./_custom-widget-advanced-manifest";
|
import { CustomWidgetAdvancedManifest } from "./_custom-widget-advanced-manifest";
|
||||||
import { EditorSection, SaveActions } from "./_custom-widget-form-layout";
|
import {
|
||||||
import { customWidgetOptionsSchemaReference, customWidgetRequestReference } from "./_custom-widget-form-references";
|
CustomWidgetOptionsSnapshotSync,
|
||||||
|
CustomWidgetSaveActions,
|
||||||
|
CustomWidgetSectionNavigation,
|
||||||
|
CustomWidgetUnsavedChangesGuard,
|
||||||
|
} from "./_custom-widget-form-layout";
|
||||||
|
import {
|
||||||
|
CustomWidgetAiSection,
|
||||||
|
CustomWidgetGeneralSection,
|
||||||
|
CustomWidgetOptionsSection,
|
||||||
|
CustomWidgetPreviewSection,
|
||||||
|
CustomWidgetRequestsSection,
|
||||||
|
CustomWidgetSourcesSection,
|
||||||
|
CustomWidgetTemplateSection,
|
||||||
|
} from "./_custom-widget-form-sections";
|
||||||
|
import {
|
||||||
|
createCustomWidgetFormDocumentStore,
|
||||||
|
CustomWidgetFormDocumentProvider,
|
||||||
|
useCustomWidgetFormDocumentBridge,
|
||||||
|
} from "./_custom-widget-form-state";
|
||||||
|
import type { CustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
|
||||||
import { buildDefinition, getDefinitionDefaults } from "./_custom-widget-form-utils";
|
import { buildDefinition, getDefinitionDefaults } from "./_custom-widget-form-utils";
|
||||||
import { CustomWidgetOptionsEditor } from "./_custom-widget-options-editor";
|
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
|
||||||
import { CustomWidgetPreviewPanel } from "./_custom-widget-preview-panel";
|
|
||||||
import type { PreviewState } from "./_custom-widget-preview-panel";
|
import type { PreviewState } from "./_custom-widget-preview-panel";
|
||||||
import { CustomWidgetRequestsEditor } from "./_custom-widget-requests-editor";
|
|
||||||
import { createCustomWidgetRenameHandlers } from "./_custom-widget-rename-handlers";
|
import { createCustomWidgetRenameHandlers } from "./_custom-widget-rename-handlers";
|
||||||
|
import type { CustomWidgetSaveIssue } from "./_custom-widget-save-errors";
|
||||||
import { CustomWidgetSaveIssuesAlert } from "./_custom-widget-save-issues-alert";
|
import { CustomWidgetSaveIssuesAlert } from "./_custom-widget-save-issues-alert";
|
||||||
import { CustomWidgetSourcesEditor } from "./_custom-widget-sources-editor";
|
|
||||||
import { LazyOnceAccordion } from "./_lazy-once-accordion";
|
|
||||||
import { useCustomWidgetFormActions } from "./_use-custom-widget-form-actions";
|
import { useCustomWidgetFormActions } from "./_use-custom-widget-form-actions";
|
||||||
import { useCustomWidgetFormAnalysis } from "./_use-custom-widget-form-analysis";
|
import { analyzeCustomWidgetAiDiagnostics, CustomWidgetFormAnalysisProvider } from "./_use-custom-widget-form-analysis";
|
||||||
import { useUnsavedChangesGuard } from "./_use-unsaved-changes-guard";
|
|
||||||
import classes from "./_custom-widget-form.module.css";
|
import classes from "./_custom-widget-form.module.css";
|
||||||
|
|
||||||
interface CustomWidgetFormProps {
|
interface CustomWidgetFormProps {
|
||||||
@@ -43,206 +47,204 @@ interface CustomWidgetFormProps {
|
|||||||
initialValues?: Partial<CustomWidgetFormValues>;
|
initialValues?: Partial<CustomWidgetFormValues>;
|
||||||
definitionId?: string;
|
definitionId?: string;
|
||||||
}
|
}
|
||||||
const sectionLinks = [
|
|
||||||
["general", "section.general", IconSettings],
|
|
||||||
["sources", "section.sources", IconApi],
|
|
||||||
["requests", "section.requests", IconDatabase],
|
|
||||||
["options", "section.options", IconBraces],
|
|
||||||
["jsx", "section.jsx", IconCode],
|
|
||||||
["preview", "section.preview", IconEye],
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWidgetFormProps) {
|
type MobilePane = "configure" | "preview";
|
||||||
const t = useI18n("customWidget");
|
|
||||||
const tCommon = useI18n("common");
|
interface CustomWidgetFormViewProps {
|
||||||
|
mode: "create" | "edit";
|
||||||
|
definitionId?: string;
|
||||||
|
form: CustomWidgetWorkbenchForm;
|
||||||
|
formErrors: CustomWidgetWorkbenchForm["errors"];
|
||||||
|
formRevision: string;
|
||||||
|
documentStore: CustomWidgetFormDocumentStore;
|
||||||
|
mobilePane: MobilePane;
|
||||||
|
setMobilePane: Dispatch<SetStateAction<MobilePane>>;
|
||||||
|
preview: PreviewState;
|
||||||
|
setPreview: Dispatch<SetStateAction<PreviewState>>;
|
||||||
|
previewSize: string;
|
||||||
|
setPreviewSize: Dispatch<SetStateAction<string>>;
|
||||||
|
optionsSnapshot: Record<string, unknown>;
|
||||||
|
setOptionsSnapshot: Dispatch<SetStateAction<Record<string, unknown>>>;
|
||||||
|
saveIssues: CustomWidgetSaveIssue[];
|
||||||
|
savePending: boolean;
|
||||||
|
previewPending: boolean;
|
||||||
|
onSubmit: FormEventHandler<HTMLFormElement>;
|
||||||
|
onPreview(): void;
|
||||||
|
onPasteAiResponse(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAiDraft(values: CustomWidgetFormValues): CustomWidgetAiDraft {
|
||||||
|
return {
|
||||||
|
name: values.name,
|
||||||
|
description: values.description,
|
||||||
|
iconUrl: values.iconUrl,
|
||||||
|
sources: values.sources,
|
||||||
|
requests: values.requests,
|
||||||
|
options: values.options,
|
||||||
|
template: values.template,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const CustomWidgetFormView = memo(function CustomWidgetFormView(props: CustomWidgetFormViewProps) {
|
||||||
const w = useI18n("customWidget.workbench");
|
const w = useI18n("customWidget.workbench");
|
||||||
const formInitialValues: CustomWidgetFormValues = { ...DEFAULT_CUSTOM_WIDGET_FORM_VALUES, ...initialValues };
|
const documentStore = props.documentStore;
|
||||||
const form = useZodForm(customWidgetFormSchema, { initialValues: formInitialValues });
|
const form = props.form;
|
||||||
const [mobilePane, setMobilePane] = useState<"configure" | "preview">("configure");
|
const setMobilePane = props.setMobilePane;
|
||||||
const [request, setRequest] = useState("");
|
const setPreview = props.setPreview;
|
||||||
const [documentationUrl, setDocumentationUrl] = useState("");
|
const { renameRequest, renameOption } = useMemo(
|
||||||
const [preview, setPreview] = useState<PreviewState>({ data: {}, status: {}, session: null, outcome: "idle" });
|
() =>
|
||||||
const [previewSize, setPreviewSize] = useState("standard");
|
createCustomWidgetRenameHandlers({
|
||||||
const [optionsSnapshot, setOptionsSnapshot] = useState<Record<string, unknown>>(() => {
|
form,
|
||||||
const initialDefinition = buildDefinition(formInitialValues);
|
invalidWidgetMessage: w("invalidWidget"),
|
||||||
return initialDefinition.success ? getDefinitionDefaults(initialDefinition.data) : {};
|
}),
|
||||||
});
|
[form, w],
|
||||||
useUnsavedChangesGuard(form.isDirty());
|
);
|
||||||
|
const readAiDraft = useCallback(() => getAiDraft(documentStore.getValues()), [documentStore]);
|
||||||
const {
|
const readAiDiagnostics = useCallback(
|
||||||
candidate,
|
() => analyzeCustomWidgetAiDiagnostics(documentStore.getValues()),
|
||||||
parsedOptions,
|
[documentStore],
|
||||||
jsxCompletions,
|
);
|
||||||
templateDiagnostics,
|
const handleSectionSelect = useCallback(
|
||||||
requestDiagnostics,
|
(section: string) => {
|
||||||
hasDiagnostics,
|
setMobilePane(section === "preview" ? "preview" : "configure");
|
||||||
invalidSections,
|
},
|
||||||
aiDraft,
|
[setMobilePane],
|
||||||
aiDiagnostics,
|
);
|
||||||
previewValidationIssues,
|
|
||||||
} = useCustomWidgetFormAnalysis(form.values);
|
|
||||||
|
|
||||||
const { save, runPreview, pasteAiResponse, saveIssues, savePending, previewPending } = useCustomWidgetFormActions({
|
|
||||||
mode,
|
|
||||||
definitionId,
|
|
||||||
form,
|
|
||||||
setPreview,
|
|
||||||
setMobilePane,
|
|
||||||
optionsSnapshot,
|
|
||||||
setOptionsSnapshot,
|
|
||||||
});
|
|
||||||
useEffect(() => {
|
|
||||||
if (parsedOptions.success) setOptionsSnapshot(getCustomWidgetDefaultOptions(parsedOptions.data));
|
|
||||||
}, [parsedOptions]);
|
|
||||||
|
|
||||||
const invalid = hasDiagnostics || !candidate.success;
|
|
||||||
const { renameRequest, renameOption } = createCustomWidgetRenameHandlers({
|
|
||||||
form,
|
|
||||||
invalidWidgetMessage: w("invalidWidget"),
|
|
||||||
});
|
|
||||||
const handleLiveActionsChange = useCallback(
|
const handleLiveActionsChange = useCallback(
|
||||||
(enabled: boolean) =>
|
(enabled: boolean) =>
|
||||||
setPreview((current) => ({
|
setPreview((current) => ({
|
||||||
...current,
|
...current,
|
||||||
session: current.session ? { ...current.session, liveActions: enabled } : null,
|
session: current.session ? { ...current.session, liveActions: enabled } : null,
|
||||||
})),
|
})),
|
||||||
[],
|
[setPreview],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={save} className={classes.form}>
|
<CustomWidgetFormDocumentProvider store={documentStore}>
|
||||||
<SegmentedControl
|
<CustomWidgetFormAnalysisProvider>
|
||||||
className={classes.paneSwitcher}
|
<form onSubmit={props.onSubmit} className={classes.form}>
|
||||||
fullWidth
|
<CustomWidgetUnsavedChangesGuard />
|
||||||
value={mobilePane}
|
<CustomWidgetOptionsSnapshotSync setOptionsSnapshot={props.setOptionsSnapshot} />
|
||||||
onChange={(value) => setMobilePane(value as typeof mobilePane)}
|
<SegmentedControl
|
||||||
data={[
|
className={classes.paneSwitcher}
|
||||||
{ value: "configure", label: w("configure") },
|
fullWidth
|
||||||
{ value: "preview", label: w("section.preview") },
|
value={props.mobilePane}
|
||||||
]}
|
onChange={(value) => props.setMobilePane(value as MobilePane)}
|
||||||
/>
|
data={[
|
||||||
<CustomWidgetSaveIssuesAlert issues={saveIssues} />
|
{ value: "configure", label: w("configure") },
|
||||||
<nav className={classes.sectionNav} aria-label={w("sectionNavigation")}>
|
{ value: "preview", label: w("section.preview") },
|
||||||
{sectionLinks.map(([id, key, SectionIcon]) => (
|
]}
|
||||||
<Button
|
|
||||||
key={id}
|
|
||||||
component="a"
|
|
||||||
href={`#${id}`}
|
|
||||||
onClick={() => setMobilePane(id === "preview" ? "preview" : "configure")}
|
|
||||||
size="compact-sm"
|
|
||||||
variant="subtle"
|
|
||||||
color={invalidSections.has(id) ? "red" : undefined}
|
|
||||||
leftSection={<SectionIcon size={14} />}
|
|
||||||
rightSection={
|
|
||||||
invalidSections.has(id) ? <IconAlertCircle size={13} aria-label={w("status.invalid")} /> : undefined
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{w(key)}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
</nav>
|
|
||||||
<div className={classes.workbench} data-mobile-pane={mobilePane}>
|
|
||||||
<Stack gap="lg" className={classes.configuration}>
|
|
||||||
<CustomWidgetAiCard
|
|
||||||
draft={aiDraft}
|
|
||||||
diagnostics={aiDiagnostics}
|
|
||||||
request={request}
|
|
||||||
onRequestChange={setRequest}
|
|
||||||
documentationUrl={documentationUrl}
|
|
||||||
onDocumentationUrlChange={setDocumentationUrl}
|
|
||||||
onPaste={() => void pasteAiResponse()}
|
|
||||||
/>
|
/>
|
||||||
<CustomWidgetAdvancedManifest form={form} />
|
<CustomWidgetSaveIssuesAlert issues={props.saveIssues} />
|
||||||
<EditorSection id="general" title={w("generalInformation")} icon={IconSettings}>
|
<CustomWidgetSectionNavigation onSelect={handleSectionSelect} />
|
||||||
<TextInput label={tCommon("field.name")} required {...form.getInputProps("name")} />
|
<div className={classes.workbench} data-mobile-pane={props.mobilePane}>
|
||||||
<Textarea label={t("field.description")} autosize minRows={2} {...form.getInputProps("description")} />
|
<Stack gap="lg" className={classes.configuration}>
|
||||||
<IconPicker
|
<CustomWidgetAiSection
|
||||||
withAsterisk={false}
|
getDraft={readAiDraft}
|
||||||
suggestedSearch={mode === "create" ? form.values.name : undefined}
|
getDiagnostics={readAiDiagnostics}
|
||||||
{...form.getInputProps("iconUrl")}
|
onPaste={props.onPasteAiResponse}
|
||||||
/>
|
|
||||||
</EditorSection>
|
|
||||||
<EditorSection id="sources" title={w("sources.title")} icon={IconApi}>
|
|
||||||
<CustomWidgetSourcesEditor form={form} definitionId={definitionId} />
|
|
||||||
</EditorSection>
|
|
||||||
<EditorSection id="requests" title={w("requests.title")} icon={IconDatabase}>
|
|
||||||
<CustomWidgetRequestsEditor form={form} onRename={renameRequest} />
|
|
||||||
<LazyOnceAccordion label={w("builder.advancedJson")}>
|
|
||||||
<CodeEditor
|
|
||||||
id="requests-editor"
|
|
||||||
label={w("requests.label")}
|
|
||||||
description={w("requests.description")}
|
|
||||||
language="json"
|
|
||||||
value={form.values.requests}
|
|
||||||
onChange={(value) => form.setFieldValue("requests", value)}
|
|
||||||
diagnostics={requestDiagnostics}
|
|
||||||
error={form.errors.requests}
|
|
||||||
reference={customWidgetRequestReference}
|
|
||||||
required
|
|
||||||
/>
|
/>
|
||||||
</LazyOnceAccordion>
|
<CustomWidgetAdvancedManifest form={form} />
|
||||||
</EditorSection>
|
<CustomWidgetGeneralSection form={form} formRevision={props.formRevision} mode={props.mode} />
|
||||||
<EditorSection id="options" title={w("options.title")} icon={IconBraces}>
|
<CustomWidgetSourcesSection form={form} definitionId={props.definitionId} />
|
||||||
<CustomWidgetOptionsEditor form={form} onRename={renameOption} />
|
<CustomWidgetRequestsSection form={form} onRename={renameRequest} />
|
||||||
<LazyOnceAccordion label={w("builder.advancedJson")}>
|
<CustomWidgetOptionsSection form={form} onRename={renameOption} />
|
||||||
<CodeEditor
|
<CustomWidgetTemplateSection form={form} />
|
||||||
id="options-editor"
|
<Paper p="md" className={classes.mobileSaveBar} shadow="sm">
|
||||||
label={w("options.title")}
|
<CustomWidgetSaveActions
|
||||||
language="json"
|
mode={props.mode}
|
||||||
value={form.values.options}
|
savePending={props.savePending}
|
||||||
onChange={(value) => form.setFieldValue("options", value)}
|
previewPending={props.previewPending}
|
||||||
error={form.errors.options}
|
onPreview={props.onPreview}
|
||||||
reference={customWidgetOptionsSchemaReference}
|
/>
|
||||||
|
</Paper>
|
||||||
|
</Stack>
|
||||||
|
<Box id="preview" component="aside" className={classes.previewPane} aria-label={w("widgetPreview")}>
|
||||||
|
<Paper p="md" className={classes.actionBar} shadow="sm">
|
||||||
|
<CustomWidgetSaveActions
|
||||||
|
mode={props.mode}
|
||||||
|
savePending={props.savePending}
|
||||||
|
previewPending={props.previewPending}
|
||||||
|
onPreview={props.onPreview}
|
||||||
|
/>
|
||||||
|
</Paper>
|
||||||
|
<CustomWidgetPreviewSection
|
||||||
|
preview={props.preview}
|
||||||
|
size={props.previewSize}
|
||||||
|
onSizeChange={props.setPreviewSize}
|
||||||
|
optionsSnapshot={props.optionsSnapshot}
|
||||||
|
onOptionsChange={props.setOptionsSnapshot}
|
||||||
|
onLiveActionsChange={handleLiveActionsChange}
|
||||||
/>
|
/>
|
||||||
</LazyOnceAccordion>
|
</Box>
|
||||||
</EditorSection>
|
</div>
|
||||||
<EditorSection id="jsx" title={w("jsx.title")} icon={IconCode}>
|
</form>
|
||||||
<CodeEditor
|
</CustomWidgetFormAnalysisProvider>
|
||||||
id="jsx-editor"
|
</CustomWidgetFormDocumentProvider>
|
||||||
label={w("jsx.label")}
|
);
|
||||||
language="jsx"
|
});
|
||||||
value={form.values.template}
|
|
||||||
onChange={(value) => form.setFieldValue("template", value)}
|
export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWidgetFormProps) {
|
||||||
diagnostics={templateDiagnostics}
|
const [formInitialValues] = useState<CustomWidgetFormValues>(() => ({
|
||||||
completions={jsxCompletions}
|
...DEFAULT_CUSTOM_WIDGET_FORM_VALUES,
|
||||||
error={form.errors.template}
|
...initialValues,
|
||||||
required
|
}));
|
||||||
maxLength={50_000}
|
const [documentStore] = useState(() => createCustomWidgetFormDocumentStore(formInitialValues));
|
||||||
/>
|
const mantineForm = useZodForm(customWidgetFormSchema, {
|
||||||
</EditorSection>
|
initialValues: formInitialValues,
|
||||||
<Paper p="md" className={classes.mobileSaveBar} shadow="sm">
|
mode: "uncontrolled",
|
||||||
<SaveActions
|
validateDebounce: 300,
|
||||||
dirty={form.isDirty()}
|
validateInputOnChange: false,
|
||||||
savePending={savePending}
|
onValuesChange: documentStore.setValues,
|
||||||
previewPending={previewPending}
|
});
|
||||||
invalid={invalid}
|
const form = useCustomWidgetFormDocumentBridge(mantineForm, documentStore);
|
||||||
mode={mode}
|
const [mobilePane, setMobilePane] = useState<MobilePane>("configure");
|
||||||
onPreview={() => void runPreview()}
|
const [preview, setPreview] = useState<PreviewState>({ data: {}, status: {}, session: null, outcome: "idle" });
|
||||||
/>
|
const [previewSize, setPreviewSize] = useState("standard");
|
||||||
</Paper>
|
const [optionsSnapshot, setOptionsSnapshot] = useState<Record<string, unknown>>(() => {
|
||||||
</Stack>
|
const initialDefinition = buildDefinition(formInitialValues);
|
||||||
<Box id="preview" component="aside" className={classes.previewPane} aria-label={w("widgetPreview")}>
|
return initialDefinition.success ? getDefinitionDefaults(initialDefinition.data) : {};
|
||||||
<Paper p="md" className={classes.actionBar} shadow="sm">
|
});
|
||||||
<SaveActions
|
const actions = useCustomWidgetFormActions({
|
||||||
dirty={form.isDirty()}
|
mode,
|
||||||
savePending={savePending}
|
definitionId,
|
||||||
previewPending={previewPending}
|
form,
|
||||||
invalid={invalid}
|
documentStore,
|
||||||
mode={mode}
|
setPreview,
|
||||||
onPreview={() => void runPreview()}
|
setMobilePane,
|
||||||
/>
|
optionsSnapshot,
|
||||||
</Paper>
|
setOptionsSnapshot,
|
||||||
<CustomWidgetPreviewPanel
|
});
|
||||||
candidate={candidate.success ? candidate.data : null}
|
const latestActions = useRef(actions);
|
||||||
validationIssues={previewValidationIssues}
|
useLayoutEffect(() => {
|
||||||
preview={preview}
|
latestActions.current = actions;
|
||||||
size={previewSize}
|
}, [actions]);
|
||||||
onSizeChange={setPreviewSize}
|
const handleSubmit = useCallback<FormEventHandler<HTMLFormElement>>((event) => latestActions.current.save(event), []);
|
||||||
optionsSnapshot={optionsSnapshot}
|
const handlePreview = useCallback(() => void latestActions.current.runPreview(), []);
|
||||||
onOptionsChange={setOptionsSnapshot}
|
const handlePasteAiResponse = useCallback(() => void latestActions.current.pasteAiResponse(), []);
|
||||||
onLiveActionsChange={handleLiveActionsChange}
|
|
||||||
/>
|
return (
|
||||||
</Box>
|
<CustomWidgetFormView
|
||||||
</div>
|
mode={mode}
|
||||||
</form>
|
definitionId={definitionId}
|
||||||
|
form={form}
|
||||||
|
formErrors={mantineForm.errors}
|
||||||
|
formRevision={mantineForm.key("name")}
|
||||||
|
documentStore={documentStore}
|
||||||
|
mobilePane={mobilePane}
|
||||||
|
setMobilePane={setMobilePane}
|
||||||
|
preview={preview}
|
||||||
|
setPreview={setPreview}
|
||||||
|
previewSize={previewSize}
|
||||||
|
setPreviewSize={setPreviewSize}
|
||||||
|
optionsSnapshot={optionsSnapshot}
|
||||||
|
setOptionsSnapshot={setOptionsSnapshot}
|
||||||
|
saveIssues={actions.saveIssues}
|
||||||
|
savePending={actions.savePending}
|
||||||
|
previewPending={actions.previewPending}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
onPreview={handlePreview}
|
||||||
|
onPasteAiResponse={handlePasteAiResponse}
|
||||||
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+2
-2
@@ -10,7 +10,7 @@ interface RenameHandlersInput {
|
|||||||
|
|
||||||
export function createCustomWidgetRenameHandlers(input: RenameHandlersInput) {
|
export function createCustomWidgetRenameHandlers(input: RenameHandlersInput) {
|
||||||
const renameRequest = (currentId: string, nextId: string) => {
|
const renameRequest = (currentId: string, nextId: string) => {
|
||||||
const candidate = buildDefinition(input.form.values);
|
const candidate = buildDefinition(input.form.getValues());
|
||||||
if (!candidate.success) {
|
if (!candidate.success) {
|
||||||
input.form.setFieldError("requests", input.invalidWidgetMessage);
|
input.form.setFieldError("requests", input.invalidWidgetMessage);
|
||||||
return;
|
return;
|
||||||
@@ -23,7 +23,7 @@ export function createCustomWidgetRenameHandlers(input: RenameHandlersInput) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const renameOption = (currentName: string, nextName: string) => {
|
const renameOption = (currentName: string, nextName: string) => {
|
||||||
const candidate = buildDefinition(input.form.values);
|
const candidate = buildDefinition(input.form.getValues());
|
||||||
if (!candidate.success) {
|
if (!candidate.success) {
|
||||||
input.form.setFieldError("options", input.invalidWidgetMessage);
|
input.form.setFieldError("options", input.invalidWidgetMessage);
|
||||||
return;
|
return;
|
||||||
|
|||||||
+17
-62
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||||
import type { Dispatch, SetStateAction } from "react";
|
import type { Dispatch, SetStateAction } from "react";
|
||||||
import type { UseFormReturnType } from "@mantine/form";
|
import type { UseFormReturnType } from "@mantine/form";
|
||||||
|
|
||||||
@@ -23,11 +23,13 @@ import type { PreviewState } from "./_custom-widget-preview-panel";
|
|||||||
import { extractCustomWidgetSaveIssues } from "./_custom-widget-save-errors";
|
import { extractCustomWidgetSaveIssues } from "./_custom-widget-save-errors";
|
||||||
import type { CustomWidgetSaveIssue } from "./_custom-widget-save-errors";
|
import type { CustomWidgetSaveIssue } from "./_custom-widget-save-errors";
|
||||||
import { clearSaveIssues, reportSaveIssues } from "./_custom-widget-save-issue-utils";
|
import { clearSaveIssues, reportSaveIssues } from "./_custom-widget-save-issue-utils";
|
||||||
|
import type { CustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
|
||||||
|
|
||||||
interface FormActionsInput {
|
interface FormActionsInput {
|
||||||
mode: "create" | "edit";
|
mode: "create" | "edit";
|
||||||
definitionId?: string;
|
definitionId?: string;
|
||||||
form: UseFormReturnType<CustomWidgetFormValues>;
|
form: UseFormReturnType<CustomWidgetFormValues>;
|
||||||
|
documentStore: CustomWidgetFormDocumentStore;
|
||||||
setPreview: Dispatch<SetStateAction<PreviewState>>;
|
setPreview: Dispatch<SetStateAction<PreviewState>>;
|
||||||
setMobilePane: Dispatch<SetStateAction<"configure" | "preview">>;
|
setMobilePane: Dispatch<SetStateAction<"configure" | "preview">>;
|
||||||
optionsSnapshot: Record<string, unknown>;
|
optionsSnapshot: Record<string, unknown>;
|
||||||
@@ -44,52 +46,9 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
|||||||
const previewMutation = clientApi.customWidget.previewCreate.useMutation();
|
const previewMutation = clientApi.customWidget.previewCreate.useMutation();
|
||||||
const [saveIssues, setSaveIssues] = useState<CustomWidgetSaveIssue[]>([]);
|
const [saveIssues, setSaveIssues] = useState<CustomWidgetSaveIssue[]>([]);
|
||||||
const [previewPending, setPreviewPending] = useState(false);
|
const [previewPending, setPreviewPending] = useState(false);
|
||||||
const previewOptions = input.optionsSnapshot;
|
|
||||||
const previewOptionsFingerprint = useMemo(() => JSON.stringify(previewOptions), [previewOptions]);
|
|
||||||
const previewSecretValues = input.form.values.secrets;
|
|
||||||
const previewSecrets = useMemo(() => getChangedSecrets({ secrets: previewSecretValues }), [previewSecretValues]);
|
|
||||||
const previewSecretsFingerprint = useMemo(() => JSON.stringify(previewSecrets), [previewSecrets]);
|
|
||||||
const previewDefinitionValues = useMemo(
|
|
||||||
() => ({
|
|
||||||
name: input.form.values.name,
|
|
||||||
description: input.form.values.description,
|
|
||||||
iconUrl: input.form.values.iconUrl,
|
|
||||||
sources: input.form.values.sources,
|
|
||||||
requests: input.form.values.requests,
|
|
||||||
options: input.form.values.options,
|
|
||||||
template: input.form.values.template,
|
|
||||||
}),
|
|
||||||
[
|
|
||||||
input.form.values.description,
|
|
||||||
input.form.values.iconUrl,
|
|
||||||
input.form.values.name,
|
|
||||||
input.form.values.options,
|
|
||||||
input.form.values.requests,
|
|
||||||
input.form.values.sources,
|
|
||||||
input.form.values.template,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
const setPreview = input.setPreview;
|
const setPreview = input.setPreview;
|
||||||
const previewGeneration = useRef(0);
|
const previewGeneration = useRef(0);
|
||||||
const latestPreviewInput = useRef({
|
const invalidatePreview = useCallback(() => {
|
||||||
definitionValues: previewDefinitionValues,
|
|
||||||
optionsFingerprint: previewOptionsFingerprint,
|
|
||||||
secretsFingerprint: previewSecretsFingerprint,
|
|
||||||
});
|
|
||||||
useLayoutEffect(() => {
|
|
||||||
const previous = latestPreviewInput.current;
|
|
||||||
const current = {
|
|
||||||
definitionValues: previewDefinitionValues,
|
|
||||||
optionsFingerprint: previewOptionsFingerprint,
|
|
||||||
secretsFingerprint: previewSecretsFingerprint,
|
|
||||||
};
|
|
||||||
latestPreviewInput.current = current;
|
|
||||||
if (
|
|
||||||
previous.definitionValues === current.definitionValues &&
|
|
||||||
previous.optionsFingerprint === current.optionsFingerprint &&
|
|
||||||
previous.secretsFingerprint === current.secretsFingerprint
|
|
||||||
)
|
|
||||||
return;
|
|
||||||
previewGeneration.current += 1;
|
previewGeneration.current += 1;
|
||||||
setPreview((preview) => {
|
setPreview((preview) => {
|
||||||
if (
|
if (
|
||||||
@@ -102,7 +61,11 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
|||||||
return { data: {}, status: {}, session: null, outcome: "idle" };
|
return { data: {}, status: {}, session: null, outcome: "idle" };
|
||||||
});
|
});
|
||||||
setPreviewPending(false);
|
setPreviewPending(false);
|
||||||
}, [previewDefinitionValues, previewOptionsFingerprint, previewSecretsFingerprint, setPreview]);
|
}, [setPreview]);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
invalidatePreview();
|
||||||
|
}, [input.optionsSnapshot, invalidatePreview]);
|
||||||
|
useEffect(() => input.documentStore.subscribe(invalidatePreview), [input.documentStore, invalidatePreview]);
|
||||||
useEffect(
|
useEffect(
|
||||||
() => () => {
|
() => () => {
|
||||||
previewGeneration.current += 1;
|
previewGeneration.current += 1;
|
||||||
@@ -137,6 +100,7 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
|||||||
});
|
});
|
||||||
input.form.setInitialValues(values);
|
input.form.setInitialValues(values);
|
||||||
input.form.resetDirty();
|
input.form.resetDirty();
|
||||||
|
input.documentStore.markSaved(values);
|
||||||
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
||||||
window.location.assign(result.managementPath);
|
window.location.assign(result.managementPath);
|
||||||
} else if (input.definitionId) {
|
} else if (input.definitionId) {
|
||||||
@@ -152,6 +116,7 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
|||||||
]);
|
]);
|
||||||
input.form.setInitialValues(values);
|
input.form.setInitialValues(values);
|
||||||
input.form.resetDirty();
|
input.form.resetDirty();
|
||||||
|
input.documentStore.markSaved(values);
|
||||||
showSuccessNotification({
|
showSuccessNotification({
|
||||||
title: tCommon("action.save"),
|
title: tCommon("action.save"),
|
||||||
message: t("notification.updated", { name: values.name }),
|
message: t("notification.updated", { name: values.name }),
|
||||||
@@ -169,7 +134,8 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
|||||||
|
|
||||||
const runPreview = async () => {
|
const runPreview = async () => {
|
||||||
if (previewPending) return;
|
if (previewPending) return;
|
||||||
const candidateAtStart = buildDefinition(input.form.values);
|
const valuesAtStart = input.documentStore.getValues();
|
||||||
|
const candidateAtStart = buildDefinition(valuesAtStart);
|
||||||
if (!candidateAtStart.success) {
|
if (!candidateAtStart.success) {
|
||||||
showErrorNotification({
|
showErrorNotification({
|
||||||
title: w("section.preview"),
|
title: w("section.preview"),
|
||||||
@@ -177,7 +143,8 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const optionIssues = getCustomWidgetPreviewOptionIssues(candidateAtStart.data, input.optionsSnapshot);
|
const optionsAtStart = input.optionsSnapshot;
|
||||||
|
const optionIssues = getCustomWidgetPreviewOptionIssues(candidateAtStart.data, optionsAtStart);
|
||||||
if (optionIssues.length > 0) {
|
if (optionIssues.length > 0) {
|
||||||
const issue = optionIssues[0];
|
const issue = optionIssues[0];
|
||||||
showErrorNotification({
|
showErrorNotification({
|
||||||
@@ -186,22 +153,10 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const definitionValuesAtStart = previewDefinitionValues;
|
const secretsAtStart = getChangedSecrets(valuesAtStart);
|
||||||
const optionsAtStart = input.optionsSnapshot;
|
|
||||||
const optionsFingerprintAtStart = previewOptionsFingerprint;
|
|
||||||
const secretsAtStart = previewSecrets;
|
|
||||||
const secretsFingerprintAtStart = previewSecretsFingerprint;
|
|
||||||
const generation = previewGeneration.current + 1;
|
const generation = previewGeneration.current + 1;
|
||||||
previewGeneration.current = generation;
|
previewGeneration.current = generation;
|
||||||
const isCurrent = () => {
|
const isCurrent = () => previewGeneration.current === generation;
|
||||||
const latest = latestPreviewInput.current;
|
|
||||||
return (
|
|
||||||
previewGeneration.current === generation &&
|
|
||||||
latest.definitionValues === definitionValuesAtStart &&
|
|
||||||
latest.optionsFingerprint === optionsFingerprintAtStart &&
|
|
||||||
latest.secretsFingerprint === secretsFingerprintAtStart
|
|
||||||
);
|
|
||||||
};
|
|
||||||
input.setMobilePane("preview");
|
input.setMobilePane("preview");
|
||||||
input.setPreview({ data: {}, status: {}, session: null, outcome: "loading" });
|
input.setPreview({ data: {}, status: {}, session: null, outcome: "loading" });
|
||||||
setPreviewPending(true);
|
setPreviewPending(true);
|
||||||
|
|||||||
+122
-47
@@ -1,14 +1,29 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useDeferredValue, useMemo } from "react";
|
import {
|
||||||
|
createContext,
|
||||||
|
createElement,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useDeferredValue,
|
||||||
|
useLayoutEffect,
|
||||||
|
useMemo,
|
||||||
|
useState,
|
||||||
|
useSyncExternalStore,
|
||||||
|
} from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
import type { CustomWidgetAiDiagnostic, CustomWidgetAiDraft } from "@homarr/custom-widgets/authoring-prompt";
|
import type { CustomWidgetAiDiagnostic } from "@homarr/custom-widgets/authoring-prompt";
|
||||||
import { customWidgetOptionsSchema } from "@homarr/custom-widgets/core";
|
import { customWidgetOptionsSchema } from "@homarr/custom-widgets/core";
|
||||||
import { analyzeJsxTemplate, analyzeRequestManifest } from "@homarr/custom-widgets/workbench";
|
import { analyzeJsxTemplate, analyzeRequestManifest } from "@homarr/custom-widgets/workbench";
|
||||||
import type { CustomWidgetFormValues, EditorDiagnostic } from "@homarr/custom-widgets/workbench";
|
import type { CustomWidgetFormValues, EditorDiagnostic } from "@homarr/custom-widgets/workbench";
|
||||||
|
|
||||||
import { createCustomWidgetCompletions, getInvalidCustomWidgetSections } from "./_custom-widget-form-analysis";
|
import { createCustomWidgetCompletions, getInvalidCustomWidgetSections } from "./_custom-widget-form-analysis";
|
||||||
import { buildDefinition, isRecord, parseJson } from "./_custom-widget-form-utils";
|
import { buildDefinition, isRecord, parseJson } from "./_custom-widget-form-utils";
|
||||||
|
import { useDeferredCustomWidgetFormDocumentValues } from "./_custom-widget-form-state";
|
||||||
|
|
||||||
|
const emptyPreviewValidationIssues: Array<{ path?: string; message: string }> = [];
|
||||||
|
const emptyCandidateIssues: Array<{ path: PropertyKey[] }> = [];
|
||||||
|
|
||||||
function normalizeEditorDiagnostics(
|
function normalizeEditorDiagnostics(
|
||||||
section: "requests" | "template",
|
section: "requests" | "template",
|
||||||
@@ -24,6 +39,37 @@ function normalizeEditorDiagnostics(
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createAiDiagnostics(
|
||||||
|
candidate: ReturnType<typeof buildDefinition>,
|
||||||
|
requestDiagnostics: readonly EditorDiagnostic[],
|
||||||
|
templateDiagnostics: readonly EditorDiagnostic[],
|
||||||
|
) {
|
||||||
|
const editorDiagnostics = [
|
||||||
|
...normalizeEditorDiagnostics("requests", requestDiagnostics),
|
||||||
|
...normalizeEditorDiagnostics("template", templateDiagnostics),
|
||||||
|
];
|
||||||
|
if (candidate.success) return editorDiagnostics;
|
||||||
|
return [
|
||||||
|
...candidate.error.issues.map((issue) => ({
|
||||||
|
section: String(issue.path[0] ?? "definition"),
|
||||||
|
severity: "error" as const,
|
||||||
|
path: issue.path.map(String).join(".") || undefined,
|
||||||
|
message: issue.message,
|
||||||
|
})),
|
||||||
|
...editorDiagnostics,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function analyzeCustomWidgetAiDiagnostics(values: CustomWidgetFormValues): CustomWidgetAiDiagnostic[] {
|
||||||
|
const parsedRequests = parseJson(values.requests);
|
||||||
|
const requestIds = isRecord(parsedRequests) ? Object.keys(parsedRequests) : [];
|
||||||
|
return createAiDiagnostics(
|
||||||
|
buildDefinition(values),
|
||||||
|
analyzeRequestManifest(values.requests),
|
||||||
|
analyzeJsxTemplate(values.template, { requestIds }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function useCustomWidgetFormAnalysis(values: CustomWidgetFormValues) {
|
export function useCustomWidgetFormAnalysis(values: CustomWidgetFormValues) {
|
||||||
const analysisValues = useDeferredValue(values);
|
const analysisValues = useDeferredValue(values);
|
||||||
const candidate = useMemo(() => buildDefinition(analysisValues), [analysisValues]);
|
const candidate = useMemo(() => buildDefinition(analysisValues), [analysisValues]);
|
||||||
@@ -50,47 +96,21 @@ export function useCustomWidgetFormAnalysis(values: CustomWidgetFormValues) {
|
|||||||
);
|
);
|
||||||
const requestDiagnostics = useMemo(() => analyzeRequestManifest(analysisValues.requests), [analysisValues.requests]);
|
const requestDiagnostics = useMemo(() => analyzeRequestManifest(analysisValues.requests), [analysisValues.requests]);
|
||||||
const hasDiagnostics = [...templateDiagnostics, ...requestDiagnostics].some((entry) => entry.severity === "error");
|
const hasDiagnostics = [...templateDiagnostics, ...requestDiagnostics].some((entry) => entry.severity === "error");
|
||||||
|
const candidateIssues = candidate.success ? emptyCandidateIssues : candidate.error.issues;
|
||||||
const invalidSections = useMemo(
|
const invalidSections = useMemo(
|
||||||
() =>
|
() => getInvalidCustomWidgetSections(candidateIssues, requestDiagnostics, templateDiagnostics),
|
||||||
getInvalidCustomWidgetSections(
|
[candidateIssues, requestDiagnostics, templateDiagnostics],
|
||||||
candidate.success ? [] : candidate.error.issues,
|
|
||||||
requestDiagnostics,
|
|
||||||
templateDiagnostics,
|
|
||||||
),
|
|
||||||
[candidate, requestDiagnostics, templateDiagnostics],
|
|
||||||
);
|
);
|
||||||
const aiDraft = useMemo<CustomWidgetAiDraft>(
|
const previewCandidate = useMemo(
|
||||||
() => ({
|
() => (candidate.success ? candidate.data : null),
|
||||||
name: values.name,
|
// The preview renderer consumes only these definition fields; other fields affect the validity boolean below.
|
||||||
description: values.description,
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
iconUrl: values.iconUrl,
|
[analysisValues.requests, analysisValues.template, candidate.success],
|
||||||
sources: values.sources,
|
|
||||||
requests: values.requests,
|
|
||||||
options: values.options,
|
|
||||||
template: values.template,
|
|
||||||
}),
|
|
||||||
[values.description, values.iconUrl, values.name, values.options, values.requests, values.sources, values.template],
|
|
||||||
);
|
);
|
||||||
const aiDiagnostics = useMemo<CustomWidgetAiDiagnostic[]>(() => {
|
|
||||||
const diagnostics = [
|
|
||||||
...normalizeEditorDiagnostics("requests", requestDiagnostics),
|
|
||||||
...normalizeEditorDiagnostics("template", templateDiagnostics),
|
|
||||||
];
|
|
||||||
if (candidate.success) return diagnostics;
|
|
||||||
return [
|
|
||||||
...candidate.error.issues.map((issue) => ({
|
|
||||||
section: String(issue.path[0] ?? "definition"),
|
|
||||||
severity: "error" as const,
|
|
||||||
path: issue.path.map(String).join(".") || undefined,
|
|
||||||
message: issue.message,
|
|
||||||
})),
|
|
||||||
...diagnostics,
|
|
||||||
];
|
|
||||||
}, [candidate, requestDiagnostics, templateDiagnostics]);
|
|
||||||
const previewValidationIssues = useMemo(
|
const previewValidationIssues = useMemo(
|
||||||
() =>
|
() =>
|
||||||
candidate.success
|
candidate.success
|
||||||
? []
|
? emptyPreviewValidationIssues
|
||||||
: candidate.error.issues.map((issue) => ({
|
: candidate.error.issues.map((issue) => ({
|
||||||
path: issue.path.map(String).join(".") || undefined,
|
path: issue.path.map(String).join(".") || undefined,
|
||||||
message: issue.message,
|
message: issue.message,
|
||||||
@@ -98,16 +118,71 @@ export function useCustomWidgetFormAnalysis(values: CustomWidgetFormValues) {
|
|||||||
[candidate],
|
[candidate],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
return useMemo(
|
||||||
|
() => ({
|
||||||
|
candidate,
|
||||||
|
candidateValid: candidate.success,
|
||||||
|
parsedOptions,
|
||||||
|
jsxCompletions,
|
||||||
|
templateDiagnostics,
|
||||||
|
requestDiagnostics,
|
||||||
|
hasDiagnostics,
|
||||||
|
invalidSections,
|
||||||
|
previewCandidate,
|
||||||
|
previewValidationIssues,
|
||||||
|
}),
|
||||||
|
[
|
||||||
|
candidate,
|
||||||
|
hasDiagnostics,
|
||||||
|
invalidSections,
|
||||||
|
jsxCompletions,
|
||||||
|
parsedOptions,
|
||||||
|
previewCandidate,
|
||||||
|
previewValidationIssues,
|
||||||
|
requestDiagnostics,
|
||||||
|
templateDiagnostics,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type CustomWidgetFormAnalysis = ReturnType<typeof useCustomWidgetFormAnalysis>;
|
||||||
|
|
||||||
|
interface CustomWidgetFormAnalysisStore {
|
||||||
|
getAnalysis(): CustomWidgetFormAnalysis;
|
||||||
|
setAnalysis(analysis: CustomWidgetFormAnalysis): void;
|
||||||
|
subscribe(listener: () => void): () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createCustomWidgetFormAnalysisStore(initialAnalysis: CustomWidgetFormAnalysis): CustomWidgetFormAnalysisStore {
|
||||||
|
let analysis = initialAnalysis;
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
return {
|
return {
|
||||||
candidate,
|
getAnalysis: () => analysis,
|
||||||
parsedOptions,
|
setAnalysis: (nextAnalysis) => {
|
||||||
jsxCompletions,
|
if (Object.is(analysis, nextAnalysis)) return;
|
||||||
templateDiagnostics,
|
analysis = nextAnalysis;
|
||||||
requestDiagnostics,
|
listeners.forEach((listener) => listener());
|
||||||
hasDiagnostics,
|
},
|
||||||
invalidSections,
|
subscribe: (listener) => {
|
||||||
aiDraft,
|
listeners.add(listener);
|
||||||
aiDiagnostics,
|
return () => listeners.delete(listener);
|
||||||
previewValidationIssues,
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CustomWidgetFormAnalysisContext = createContext<CustomWidgetFormAnalysisStore | null>(null);
|
||||||
|
|
||||||
|
export function CustomWidgetFormAnalysisProvider({ children }: { children: ReactNode }) {
|
||||||
|
const values = useDeferredCustomWidgetFormDocumentValues();
|
||||||
|
const analysis = useCustomWidgetFormAnalysis(values);
|
||||||
|
const [store] = useState(() => createCustomWidgetFormAnalysisStore(analysis));
|
||||||
|
useLayoutEffect(() => store.setAnalysis(analysis), [analysis, store]);
|
||||||
|
return createElement(CustomWidgetFormAnalysisContext.Provider, { value: store }, children);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCustomWidgetFormAnalysisField<Key extends keyof CustomWidgetFormAnalysis>(field: Key) {
|
||||||
|
const store = useContext(CustomWidgetFormAnalysisContext);
|
||||||
|
if (!store) throw new Error("Custom widget form analysis provider is missing");
|
||||||
|
const getSnapshot = useCallback(() => store.getAnalysis()[field], [field, store]);
|
||||||
|
return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
|
||||||
|
}
|
||||||
@@ -144,11 +144,15 @@ function getInitialInputValue(type: WidgetInputType | null, props: Record<string
|
|||||||
if (!type) return "";
|
if (!type) return "";
|
||||||
const candidate = type === "boolean" ? props.defaultChecked : props.defaultValue;
|
const candidate = type === "boolean" ? props.defaultChecked : props.defaultValue;
|
||||||
if (type === "boolean" && typeof candidate === "boolean") return candidate;
|
if (type === "boolean" && typeof candidate === "boolean") return candidate;
|
||||||
if (type === "number" && typeof candidate === "number") return candidate;
|
if (type === "number" && typeof candidate === "number" && Number.isFinite(candidate)) return candidate;
|
||||||
if (type === "string" && typeof candidate === "string") return candidate;
|
if (type === "string" && typeof candidate === "string") return candidate;
|
||||||
if (type === "string[]" && Array.isArray(candidate) && candidate.every((item) => typeof item === "string"))
|
if (type === "string[]" && Array.isArray(candidate) && candidate.every((item) => typeof item === "string"))
|
||||||
return candidate;
|
return candidate;
|
||||||
if (type === "number[]" && Array.isArray(candidate) && candidate.every((item) => typeof item === "number"))
|
if (
|
||||||
|
type === "number[]" &&
|
||||||
|
Array.isArray(candidate) &&
|
||||||
|
candidate.every((item) => typeof item === "number" && Number.isFinite(item))
|
||||||
|
)
|
||||||
return candidate;
|
return candidate;
|
||||||
return emptyInputValue(type);
|
return emptyInputValue(type);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
|
|||||||
const errorCount = diagnostics.filter(({ severity }) => severity === "error").length;
|
const errorCount = diagnostics.filter(({ severity }) => severity === "error").length;
|
||||||
const warningCount = diagnostics.length - errorCount;
|
const warningCount = diagnostics.length - errorCount;
|
||||||
const isCharacterLimitExceeded = props.maxLength !== undefined && props.value.length > props.maxLength;
|
const isCharacterLimitExceeded = props.maxLength !== undefined && props.value.length > props.maxLength;
|
||||||
|
const isEditorInvalid = Boolean(props.error) || errorCount > 0 || isCharacterLimitExceeded;
|
||||||
const copy = async () => {
|
const copy = async () => {
|
||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(props.value);
|
await navigator.clipboard.writeText(props.value);
|
||||||
@@ -176,7 +177,7 @@ export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
|
|||||||
label={props.label}
|
label={props.label}
|
||||||
placeholder={props.placeholder}
|
placeholder={props.placeholder}
|
||||||
theme={colorScheme}
|
theme={colorScheme}
|
||||||
invalid={isCharacterLimitExceeded}
|
invalid={isEditorInvalid}
|
||||||
height={props.height ?? (props.language === "jsx" ? "320px" : "220px")}
|
height={props.height ?? (props.language === "jsx" ? "320px" : "220px")}
|
||||||
readOnly={props.readOnly ?? false}
|
readOnly={props.readOnly ?? false}
|
||||||
diagnosticMessage={props.messages.diagnostic}
|
diagnosticMessage={props.messages.diagnostic}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ export const useZodForm = <
|
|||||||
schema: TSchema,
|
schema: TSchema,
|
||||||
options: Omit<
|
options: Omit<
|
||||||
Exclude<Parameters<typeof useForm<inferPossibleSchema<TSchema>>>[0], undefined>,
|
Exclude<Parameters<typeof useForm<inferPossibleSchema<TSchema>>>[0], undefined>,
|
||||||
"validate" | "validateInputOnBlur" | "validateInputOnChange"
|
"validate" | "validateInputOnBlur"
|
||||||
>,
|
>,
|
||||||
) => {
|
) => {
|
||||||
const t = useI18n();
|
const t = useI18n();
|
||||||
@@ -32,7 +32,7 @@ export const useZodForm = <
|
|||||||
return useForm<inferPossibleSchema<TSchema>>({
|
return useForm<inferPossibleSchema<TSchema>>({
|
||||||
...options,
|
...options,
|
||||||
validateInputOnBlur: true,
|
validateInputOnBlur: true,
|
||||||
validateInputOnChange: true,
|
validateInputOnChange: options.validateInputOnChange ?? true,
|
||||||
validate: schemaResolver(schema, { sync: true }),
|
validate: schemaResolver(schema, { sync: true }),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
Reference in new issue
Block a user