refactor(webui): separate presentation views and expand component gallery (#6179)
* refactor(webui): organize shared components with an internal gallery * refactor(webui): decouple views and expand component gallery * fix(docker): include channel sources in WebUI build * refactor(webui): cover all channel interfaces in gallery * docs(webui): remove manual paragraph wrapping
This commit is contained in:
1 parent
db804ef94a
commit
30e43aec82
109 files changed
+7874
-3459
No files matched your search
@@ -3,7 +3,7 @@ import { Download, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { ChannelFeatureAction } from "@/channel-plugins/types";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import {
|
||||
ChannelLogo,
|
||||
ChannelStatusBadge,
|
||||
|
||||
@@ -1,421 +1,54 @@
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import { ChevronDown, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { channelUiPresentation } from "@/channel-plugins/registry";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import type { ChannelConfigField } from "@/channel-plugins/catalog";
|
||||
import {
|
||||
CredentialForm,
|
||||
channelValuesForSave,
|
||||
defaultChannelFieldValues,
|
||||
} from "@/components/settings/channels/CredentialForm";
|
||||
import {
|
||||
channelValidationStatusClass,
|
||||
channelValidationStatusIcon,
|
||||
} from "@/components/settings/channels/ChannelValidationProgress";
|
||||
import {
|
||||
CHANNEL_SETUP_PANEL_CLASS_NAME,
|
||||
ChannelLogo,
|
||||
ChannelRuntimeError,
|
||||
channelSetup,
|
||||
localizedChannelDisplayName,
|
||||
} from "@/components/settings/channels/ChannelIdentity";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import {
|
||||
configureChannel,
|
||||
disableNanobotFeature,
|
||||
enableNanobotFeature,
|
||||
} from "@/lib/api";
|
||||
import { logoFallbackUrls } from "@/lib/provider-brand";
|
||||
import type {
|
||||
NanobotChannelInstanceInfo,
|
||||
NanobotFeatureInfo,
|
||||
NanobotFeaturesPayload,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { NanobotChannelInstanceInfo, NanobotFeatureInfo, NanobotFeaturesPayload } from "@/lib/types";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
import {
|
||||
ChannelInstancesPanelView,
|
||||
type ChannelInstancesPanelCustomization,
|
||||
type ChannelInstancesPanelViewProps,
|
||||
} from "./ChannelInstancesPanelView";
|
||||
|
||||
export type ChannelInstancesPanelCustomization = {
|
||||
toggleAriaLabel?: (instance: NanobotChannelInstanceInfo) => string;
|
||||
configuredLabel?: string;
|
||||
needsSetupLabel?: string;
|
||||
renderInstanceSummary?: (instance: NanobotChannelInstanceInfo) => ReactNode;
|
||||
renderInstanceAction?: (instance: NanobotChannelInstanceInfo) => ReactNode;
|
||||
footer?: ReactNode;
|
||||
};
|
||||
export type { ChannelInstancesPanelCustomization } from "./ChannelInstancesPanelView";
|
||||
|
||||
export function ChannelInstancesPanel({
|
||||
feature,
|
||||
showBrandLogos,
|
||||
instances: providedInstances,
|
||||
instances,
|
||||
onFeaturesUpdate,
|
||||
customization = {},
|
||||
customization,
|
||||
renderView,
|
||||
}: {
|
||||
feature: NanobotFeatureInfo;
|
||||
showBrandLogos: boolean;
|
||||
instances?: NanobotChannelInstanceInfo[];
|
||||
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
|
||||
customization?: ChannelInstancesPanelCustomization;
|
||||
renderView?: (props: ChannelInstancesPanelViewProps) => ReactNode;
|
||||
}) {
|
||||
const { client } = useClient();
|
||||
const { t, i18n } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const displayName = localizedChannelDisplayName(feature, t);
|
||||
const instances = providedInstances ?? feature.instances ?? [];
|
||||
const [editor, setEditor] = useState<{ id: string; expanded: boolean } | null>(null);
|
||||
const selectedId = editor?.id;
|
||||
const [pendingToggle, setPendingToggle] = useState<{ id: string; checked: boolean } | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const selected = selectedId ? instances.find((instance) => instance.id === selectedId) : undefined;
|
||||
const setup = useMemo(
|
||||
() => channelSetup(feature, i18n.resolvedLanguage ?? i18n.language),
|
||||
[feature.name, feature.setup, i18n.language, i18n.resolvedLanguage],
|
||||
);
|
||||
const instanceFields = useMemo(
|
||||
() => channelInstanceFields(feature, setup.fields, setup.manualFields),
|
||||
[feature, setup.fields, setup.manualFields],
|
||||
);
|
||||
const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
|
||||
defaultChannelFieldValues(instanceFields, selected?.config_values),
|
||||
);
|
||||
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
|
||||
const [savingFields, setSavingFields] = useState(false);
|
||||
const selectedValuesKey = JSON.stringify(
|
||||
defaultChannelFieldValues(instanceFields, selected?.config_values),
|
||||
);
|
||||
const selectedConfiguredFields = useMemo(
|
||||
() => new Set(selected?.configured_fields ?? []),
|
||||
[selected?.configured_fields],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedId && !instances.some((instance) => instance.id === selectedId)) {
|
||||
setEditor(null);
|
||||
}
|
||||
}, [instances, selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
setFieldValues(defaultChannelFieldValues(instanceFields, selected?.config_values));
|
||||
setVisibleSecrets({});
|
||||
}, [selected?.id, selectedValuesKey]);
|
||||
|
||||
const toggleInstance = async (instance: NanobotChannelInstanceInfo, checked: boolean) => {
|
||||
if (pendingToggle || savingFields) return;
|
||||
setPendingToggle({ id: instance.id, checked });
|
||||
setNotice(null);
|
||||
try {
|
||||
const viewProps: ChannelInstancesPanelViewProps = {
|
||||
feature,
|
||||
showBrandLogos,
|
||||
instances,
|
||||
customization,
|
||||
onToggleInstance: async (instance, checked) => {
|
||||
const payload = checked
|
||||
? await enableNanobotFeature(client, feature.name, { instanceId: instance.id })
|
||||
: await disableNanobotFeature(client, feature.name, { instanceId: instance.id });
|
||||
onFeaturesUpdate(payload);
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
} finally {
|
||||
setPendingToggle(null);
|
||||
}
|
||||
},
|
||||
onSaveInstance: async (instance, values) => {
|
||||
const payload = await configureChannel(client, feature.name, values, {
|
||||
enable: instance.enabled,
|
||||
instanceId: instance.id,
|
||||
});
|
||||
if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features);
|
||||
},
|
||||
};
|
||||
|
||||
const saveSelectedInstanceSettings = async () => {
|
||||
if (!selected || pendingToggle || savingFields) return;
|
||||
setSavingFields(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
const payload = await configureChannel(
|
||||
client,
|
||||
feature.name,
|
||||
channelValuesForSave(instanceFields, fieldValues),
|
||||
{ enable: selected.enabled, instanceId: selected.id },
|
||||
);
|
||||
if (payload.nanobot_features) {
|
||||
onFeaturesUpdate(payload.nanobot_features);
|
||||
}
|
||||
setNotice(tx("settings.channels.savedSettings", "Settings saved."));
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
} finally {
|
||||
setSavingFields(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
|
||||
<div className="pe-20">
|
||||
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
|
||||
<h3 className="sr-only">{displayName}</h3>
|
||||
</div>
|
||||
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
|
||||
<div className="mt-5 space-y-3">
|
||||
{instances.map((instance) => {
|
||||
const expanded = selected?.id === instance.id && editor?.expanded === true;
|
||||
const toggling = pendingToggle?.id === instance.id;
|
||||
const checked = toggling ? pendingToggle.checked : instanceToggleChecked(instance);
|
||||
const instanceSummary = customization.renderInstanceSummary
|
||||
? customization.renderInstanceSummary(instance)
|
||||
: instance.id;
|
||||
const instanceAction = customization.renderInstanceAction?.(instance);
|
||||
const hasInstanceOverview = Boolean(instanceSummary || instanceAction);
|
||||
return (
|
||||
<article
|
||||
key={instance.id}
|
||||
className={cn(
|
||||
"overflow-hidden rounded-floating transition-colors",
|
||||
expanded
|
||||
? "bg-background"
|
||||
: "bg-background/70",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-3">
|
||||
<div className="flex min-w-0 flex-[1_1_12rem] items-center gap-3">
|
||||
<ChannelInstanceAvatar
|
||||
feature={feature}
|
||||
instance={instance}
|
||||
showBrandLogos={showBrandLogos}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-foreground">
|
||||
{channelInstanceDisplayName(instance)}
|
||||
</span>
|
||||
<ChannelInstanceStatusBadge
|
||||
instance={instance}
|
||||
configuredLabel={customization.configuredLabel}
|
||||
needsSetupLabel={customization.needsSetupLabel}
|
||||
/>
|
||||
</div>
|
||||
<div className="ms-auto flex shrink-0 items-center gap-3">
|
||||
{instanceFields.length ? (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
onClick={() =>
|
||||
setEditor((current) => ({
|
||||
id: instance.id,
|
||||
expanded: current?.id !== instance.id || !current.expanded,
|
||||
}))
|
||||
}
|
||||
aria-expanded={expanded}
|
||||
>
|
||||
{tx("settings.channels.advanced", "Advanced")}
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
expanded && "rotate-180",
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
</button>
|
||||
) : null}
|
||||
{toggling ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
|
||||
) : null}
|
||||
<ToggleButton
|
||||
checked={checked}
|
||||
disabled={
|
||||
Boolean(pendingToggle)
|
||||
|| savingFields
|
||||
|| !instance.configured
|
||||
}
|
||||
ariaLabel={customization.toggleAriaLabel?.(instance)
|
||||
?? t("settings.channels.toggleInstance", {
|
||||
name: channelInstanceDisplayName(instance),
|
||||
defaultValue: "{{name}} instance",
|
||||
})}
|
||||
label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
|
||||
onChange={(checked) => void toggleInstance(instance, checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasInstanceOverview || (expanded && instanceFields.length > 0) ? (
|
||||
<div className="space-y-3 px-4 pb-4 pt-1">
|
||||
{hasInstanceOverview ? <section className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
{instanceSummary ? (
|
||||
<p className="min-w-0 flex-1 truncate font-mono text-[11.5px] leading-6 text-muted-foreground">
|
||||
{instanceSummary}
|
||||
</p>
|
||||
) : <span className="flex-1" />}
|
||||
{instanceAction}
|
||||
</section> : null}
|
||||
{expanded && instanceFields.length > 0 ? (
|
||||
<div className={cn(
|
||||
"text-[12px] leading-5 text-muted-foreground",
|
||||
hasInstanceOverview && "border-t border-border/50 pt-3",
|
||||
)}>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void saveSelectedInstanceSettings();
|
||||
}}
|
||||
>
|
||||
<CredentialForm
|
||||
fields={instanceFields}
|
||||
values={fieldValues}
|
||||
configuredFields={selectedConfiguredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={(key, value) =>
|
||||
setFieldValues((current) => ({ ...current, [key]: value }))
|
||||
}
|
||||
onToggleSecret={(key) =>
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }))
|
||||
}
|
||||
compact
|
||||
/>
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full bg-muted/70 px-3 text-[12px] font-semibold settings-hover"
|
||||
disabled={savingFields || Boolean(pendingToggle)}
|
||||
>
|
||||
{savingFields ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : null}
|
||||
{tx("settings.channels.saveSettings", "Save settings")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{customization.footer}
|
||||
|
||||
{notice ? (
|
||||
<div className="mt-3 rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{notice}
|
||||
</div>
|
||||
) : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function channelInstanceDisplayName(instance: NanobotChannelInstanceInfo): string {
|
||||
const displayName = instance.display_name?.trim();
|
||||
if (displayName) return displayName;
|
||||
const localName = instance.name?.trim();
|
||||
if (localName) return localName;
|
||||
return instance.id;
|
||||
}
|
||||
|
||||
function instanceToggleChecked(instance: NanobotChannelInstanceInfo): boolean {
|
||||
return instance.runtime_status === "running" || instance.runtime_status === "starting";
|
||||
}
|
||||
|
||||
function ChannelInstanceStatusBadge({
|
||||
instance,
|
||||
configuredLabel,
|
||||
needsSetupLabel,
|
||||
}: {
|
||||
instance: NanobotChannelInstanceInfo;
|
||||
configuredLabel?: string;
|
||||
needsSetupLabel?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
let status = instance.configured ? "configured" : "needs_setup";
|
||||
let label = instance.configured
|
||||
? t("settings.channels.instanceConfigured", { defaultValue: "Configured" })
|
||||
: needsSetupLabel ?? t("settings.channels.instanceNeedsSetup", { defaultValue: "Needs setup" });
|
||||
if (instance.runtime_status === "failed") {
|
||||
status = "invalid";
|
||||
label = t("settings.channels.runtimeFailed", { defaultValue: "Failed" });
|
||||
} else if (instance.runtime_status === "starting") {
|
||||
label = t("settings.channels.runtimeStarting", { defaultValue: "Starting" });
|
||||
} else if (instance.enabled && instance.runtime_status !== "running") {
|
||||
label = t("settings.channels.runtimeStopped", { defaultValue: "Not running" });
|
||||
} else if (instance.runtime_status === "running") {
|
||||
status = "connected";
|
||||
label = configuredLabel
|
||||
?? t("settings.channels.validation.connected", { defaultValue: "Connected" });
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-[11.5px] font-medium",
|
||||
channelValidationStatusClass(status),
|
||||
)}
|
||||
>
|
||||
{channelValidationStatusIcon(status)}
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ChannelInstanceAvatar({
|
||||
feature,
|
||||
instance,
|
||||
showBrandLogos,
|
||||
}: {
|
||||
feature: NanobotFeatureInfo;
|
||||
instance: NanobotChannelInstanceInfo;
|
||||
showBrandLogos: boolean;
|
||||
}) {
|
||||
const presentation = channelUiPresentation(feature.name, feature.webui);
|
||||
const [avatarFailed, setAvatarFailed] = useState(false);
|
||||
const fallbackLogoUrls = useMemo(() => logoFallbackUrls(presentation?.logoUrl), [presentation?.logoUrl]);
|
||||
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(fallbackLogoUrls);
|
||||
const remoteAvatarUrl = !avatarFailed ? instance.avatar_url?.trim() : "";
|
||||
const imageUrl = remoteAvatarUrl || (showBrandLogos ? logoUrl : "");
|
||||
const Icon = presentation?.icon;
|
||||
const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();
|
||||
const color = presentation?.color ?? "#3370FF";
|
||||
|
||||
useEffect(() => {
|
||||
setAvatarFailed(false);
|
||||
}, [instance.avatar_url]);
|
||||
|
||||
return (
|
||||
<span
|
||||
className="grid h-11 w-11 shrink-0 place-items-center overflow-hidden rounded-full bg-background text-[10px] font-bold"
|
||||
style={{ color }}
|
||||
aria-hidden
|
||||
>
|
||||
{remoteAvatarUrl ? (
|
||||
<img
|
||||
src={remoteAvatarUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
onError={() => setAvatarFailed(true)}
|
||||
/>
|
||||
) : imageUrl ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-6 w-6 object-contain"
|
||||
onLoad={onLogoLoad}
|
||||
onError={onLogoError}
|
||||
/>
|
||||
) : Icon ? (
|
||||
<Icon className="h-5 w-5" strokeWidth={2.25} />
|
||||
) : (
|
||||
initials
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function channelInstanceFields(
|
||||
feature: NanobotFeatureInfo,
|
||||
fields: ChannelConfigField[] | undefined,
|
||||
manualFields: ChannelConfigField[] | undefined,
|
||||
): ChannelConfigField[] {
|
||||
const available = new Map(
|
||||
[...(fields ?? []), ...(manualFields ?? [])].map((field) => [field.key, field]),
|
||||
);
|
||||
if (!feature.setup) return [...available.values()];
|
||||
return feature.setup.fields.flatMap((field) => {
|
||||
const resolved = available.get(field.key);
|
||||
return resolved ? [resolved] : [];
|
||||
});
|
||||
return renderView ? renderView(viewProps) : <ChannelInstancesPanelView {...viewProps} />;
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import { ChevronDown, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelUiPresentation } from "@/channel-plugins/registry";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import type { ChannelConfigField } from "@/channel-plugins/catalog";
|
||||
import {
|
||||
CredentialForm,
|
||||
channelValuesForSave,
|
||||
defaultChannelFieldValues,
|
||||
} from "@/components/settings/channels/CredentialForm";
|
||||
import {
|
||||
channelValidationStatusClass,
|
||||
channelValidationStatusIcon,
|
||||
} from "@/components/settings/channels/ChannelValidationProgress";
|
||||
import {
|
||||
CHANNEL_SETUP_PANEL_CLASS_NAME,
|
||||
ChannelLogo,
|
||||
ChannelRuntimeError,
|
||||
channelSetup,
|
||||
localizedChannelDisplayName,
|
||||
} from "@/components/settings/channels/ChannelIdentity";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { logoFallbackUrls } from "@/lib/provider-brand";
|
||||
import type {
|
||||
NanobotChannelInstanceInfo,
|
||||
NanobotFeatureInfo,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ChannelInstancesPanelCustomization = {
|
||||
toggleAriaLabel?: (instance: NanobotChannelInstanceInfo) => string;
|
||||
configuredLabel?: string;
|
||||
needsSetupLabel?: string;
|
||||
renderInstanceSummary?: (instance: NanobotChannelInstanceInfo) => ReactNode;
|
||||
renderInstanceAction?: (instance: NanobotChannelInstanceInfo) => ReactNode;
|
||||
footer?: ReactNode;
|
||||
};
|
||||
|
||||
export type ChannelInstancesPanelViewProps = {
|
||||
feature: NanobotFeatureInfo;
|
||||
showBrandLogos: boolean;
|
||||
instances?: NanobotChannelInstanceInfo[];
|
||||
onToggleInstance: (instance: NanobotChannelInstanceInfo, checked: boolean) => void | Promise<void>;
|
||||
onSaveInstance: (instance: NanobotChannelInstanceInfo, values: Record<string, string>) => void | Promise<void>;
|
||||
customization?: ChannelInstancesPanelCustomization;
|
||||
};
|
||||
|
||||
export function ChannelInstancesPanelView({
|
||||
feature,
|
||||
showBrandLogos,
|
||||
instances: providedInstances,
|
||||
onToggleInstance,
|
||||
onSaveInstance,
|
||||
customization = {},
|
||||
}: ChannelInstancesPanelViewProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const displayName = localizedChannelDisplayName(feature, t);
|
||||
const instances = providedInstances ?? feature.instances ?? [];
|
||||
const [editor, setEditor] = useState<{ id: string; expanded: boolean } | null>(null);
|
||||
const selectedId = editor?.id;
|
||||
const [pendingToggle, setPendingToggle] = useState<{ id: string; checked: boolean } | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const selected = selectedId ? instances.find((instance) => instance.id === selectedId) : undefined;
|
||||
const setup = useMemo(
|
||||
() => channelSetup(feature, i18n.resolvedLanguage ?? i18n.language),
|
||||
[feature.name, feature.setup, i18n.language, i18n.resolvedLanguage],
|
||||
);
|
||||
const instanceFields = useMemo(
|
||||
() => channelInstanceFields(feature, setup.fields, setup.manualFields),
|
||||
[feature, setup.fields, setup.manualFields],
|
||||
);
|
||||
const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
|
||||
defaultChannelFieldValues(instanceFields, selected?.config_values),
|
||||
);
|
||||
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
|
||||
const [savingFields, setSavingFields] = useState(false);
|
||||
const selectedValuesKey = JSON.stringify(
|
||||
defaultChannelFieldValues(instanceFields, selected?.config_values),
|
||||
);
|
||||
const selectedConfiguredFields = useMemo(
|
||||
() => new Set(selected?.configured_fields ?? []),
|
||||
[selected?.configured_fields],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedId && !instances.some((instance) => instance.id === selectedId)) {
|
||||
setEditor(null);
|
||||
}
|
||||
}, [instances, selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
setFieldValues(defaultChannelFieldValues(instanceFields, selected?.config_values));
|
||||
setVisibleSecrets({});
|
||||
}, [selected?.id, selectedValuesKey]);
|
||||
|
||||
const toggleInstance = async (instance: NanobotChannelInstanceInfo, checked: boolean) => {
|
||||
if (pendingToggle || savingFields) return;
|
||||
setPendingToggle({ id: instance.id, checked });
|
||||
setNotice(null);
|
||||
try {
|
||||
await onToggleInstance(instance, checked);
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
} finally {
|
||||
setPendingToggle(null);
|
||||
}
|
||||
};
|
||||
|
||||
const saveSelectedInstanceSettings = async () => {
|
||||
if (!selected || pendingToggle || savingFields) return;
|
||||
setSavingFields(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
await onSaveInstance(selected, channelValuesForSave(instanceFields, fieldValues));
|
||||
setNotice(tx("settings.channels.savedSettings", "Settings saved."));
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
} finally {
|
||||
setSavingFields(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
|
||||
<div className="pe-20">
|
||||
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
|
||||
<h3 className="sr-only">{displayName}</h3>
|
||||
</div>
|
||||
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
|
||||
<div className="mt-5 space-y-3">
|
||||
{instances.map((instance) => {
|
||||
const expanded = selected?.id === instance.id && editor?.expanded === true;
|
||||
const toggling = pendingToggle?.id === instance.id;
|
||||
const checked = toggling ? pendingToggle.checked : instanceToggleChecked(instance);
|
||||
const instanceSummary = customization.renderInstanceSummary
|
||||
? customization.renderInstanceSummary(instance)
|
||||
: instance.id;
|
||||
const instanceAction = customization.renderInstanceAction?.(instance);
|
||||
const hasInstanceOverview = Boolean(instanceSummary || instanceAction);
|
||||
return (
|
||||
<article
|
||||
key={instance.id}
|
||||
className={cn(
|
||||
"overflow-hidden rounded-floating transition-colors",
|
||||
expanded
|
||||
? "bg-background"
|
||||
: "bg-background/70",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-3">
|
||||
<div className="flex min-w-0 flex-[1_1_12rem] items-center gap-3">
|
||||
<ChannelInstanceAvatar
|
||||
feature={feature}
|
||||
instance={instance}
|
||||
showBrandLogos={showBrandLogos}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-foreground">
|
||||
{channelInstanceDisplayName(instance)}
|
||||
</span>
|
||||
<ChannelInstanceStatusBadge
|
||||
instance={instance}
|
||||
configuredLabel={customization.configuredLabel}
|
||||
needsSetupLabel={customization.needsSetupLabel}
|
||||
/>
|
||||
</div>
|
||||
<div className="ms-auto flex shrink-0 items-center gap-3">
|
||||
{instanceFields.length ? (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
onClick={() =>
|
||||
setEditor((current) => ({
|
||||
id: instance.id,
|
||||
expanded: current?.id !== instance.id || !current.expanded,
|
||||
}))
|
||||
}
|
||||
aria-expanded={expanded}
|
||||
>
|
||||
{tx("settings.channels.advanced", "Advanced")}
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
expanded && "rotate-180",
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
</button>
|
||||
) : null}
|
||||
{toggling ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
|
||||
) : null}
|
||||
<ToggleButton
|
||||
checked={checked}
|
||||
disabled={
|
||||
Boolean(pendingToggle)
|
||||
|| savingFields
|
||||
|| !instance.configured
|
||||
}
|
||||
ariaLabel={customization.toggleAriaLabel?.(instance)
|
||||
?? t("settings.channels.toggleInstance", {
|
||||
name: channelInstanceDisplayName(instance),
|
||||
defaultValue: "{{name}} instance",
|
||||
})}
|
||||
label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
|
||||
onChange={(checked) => void toggleInstance(instance, checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasInstanceOverview || (expanded && instanceFields.length > 0) ? (
|
||||
<div className="space-y-3 px-4 pb-4 pt-1">
|
||||
{hasInstanceOverview ? <section className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
{instanceSummary ? (
|
||||
<p className="min-w-0 flex-1 truncate font-mono text-[11.5px] leading-6 text-muted-foreground">
|
||||
{instanceSummary}
|
||||
</p>
|
||||
) : <span className="flex-1" />}
|
||||
{instanceAction}
|
||||
</section> : null}
|
||||
{expanded && instanceFields.length > 0 ? (
|
||||
<div className={cn(
|
||||
"text-[12px] leading-5 text-muted-foreground",
|
||||
hasInstanceOverview && "border-t border-border/50 pt-3",
|
||||
)}>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void saveSelectedInstanceSettings();
|
||||
}}
|
||||
>
|
||||
<CredentialForm
|
||||
fields={instanceFields}
|
||||
values={fieldValues}
|
||||
configuredFields={selectedConfiguredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={(key, value) =>
|
||||
setFieldValues((current) => ({ ...current, [key]: value }))
|
||||
}
|
||||
onToggleSecret={(key) =>
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }))
|
||||
}
|
||||
compact
|
||||
/>
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full bg-muted/70 px-3 text-[12px] font-semibold settings-hover"
|
||||
disabled={savingFields || Boolean(pendingToggle)}
|
||||
>
|
||||
{savingFields ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : null}
|
||||
{tx("settings.channels.saveSettings", "Save settings")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{customization.footer}
|
||||
|
||||
{notice ? (
|
||||
<div className="mt-3 rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{notice}
|
||||
</div>
|
||||
) : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function channelInstanceDisplayName(instance: NanobotChannelInstanceInfo): string {
|
||||
const displayName = instance.display_name?.trim();
|
||||
if (displayName) return displayName;
|
||||
const localName = instance.name?.trim();
|
||||
if (localName) return localName;
|
||||
return instance.id;
|
||||
}
|
||||
|
||||
function instanceToggleChecked(instance: NanobotChannelInstanceInfo): boolean {
|
||||
return instance.runtime_status === "running" || instance.runtime_status === "starting";
|
||||
}
|
||||
|
||||
function ChannelInstanceStatusBadge({
|
||||
instance,
|
||||
configuredLabel,
|
||||
needsSetupLabel,
|
||||
}: {
|
||||
instance: NanobotChannelInstanceInfo;
|
||||
configuredLabel?: string;
|
||||
needsSetupLabel?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
let status = instance.configured ? "configured" : "needs_setup";
|
||||
let label = instance.configured
|
||||
? t("settings.channels.instanceConfigured", { defaultValue: "Configured" })
|
||||
: needsSetupLabel ?? t("settings.channels.instanceNeedsSetup", { defaultValue: "Needs setup" });
|
||||
if (instance.runtime_status === "failed") {
|
||||
status = "invalid";
|
||||
label = t("settings.channels.runtimeFailed", { defaultValue: "Failed" });
|
||||
} else if (instance.runtime_status === "starting") {
|
||||
label = t("settings.channels.runtimeStarting", { defaultValue: "Starting" });
|
||||
} else if (instance.enabled && instance.runtime_status !== "running") {
|
||||
label = t("settings.channels.runtimeStopped", { defaultValue: "Not running" });
|
||||
} else if (instance.runtime_status === "running") {
|
||||
status = "connected";
|
||||
label = configuredLabel
|
||||
?? t("settings.channels.validation.connected", { defaultValue: "Connected" });
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-[11.5px] font-medium",
|
||||
channelValidationStatusClass(status),
|
||||
)}
|
||||
>
|
||||
{channelValidationStatusIcon(status)}
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ChannelInstanceAvatar({
|
||||
feature,
|
||||
instance,
|
||||
showBrandLogos,
|
||||
}: {
|
||||
feature: NanobotFeatureInfo;
|
||||
instance: NanobotChannelInstanceInfo;
|
||||
showBrandLogos: boolean;
|
||||
}) {
|
||||
const presentation = channelUiPresentation(feature.name, feature.webui);
|
||||
const [avatarFailed, setAvatarFailed] = useState(false);
|
||||
const fallbackLogoUrls = useMemo(() => logoFallbackUrls(presentation?.logoUrl), [presentation?.logoUrl]);
|
||||
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(fallbackLogoUrls);
|
||||
const remoteAvatarUrl = !avatarFailed ? instance.avatar_url?.trim() : "";
|
||||
const imageUrl = remoteAvatarUrl || (showBrandLogos ? logoUrl : "");
|
||||
const Icon = presentation?.icon;
|
||||
const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();
|
||||
const color = presentation?.color ?? "#3370FF";
|
||||
|
||||
useEffect(() => {
|
||||
setAvatarFailed(false);
|
||||
}, [instance.avatar_url]);
|
||||
|
||||
return (
|
||||
<span
|
||||
className="grid h-11 w-11 shrink-0 place-items-center overflow-hidden rounded-full bg-background text-[10px] font-bold"
|
||||
style={{ color }}
|
||||
aria-hidden
|
||||
>
|
||||
{remoteAvatarUrl ? (
|
||||
<img
|
||||
src={remoteAvatarUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
onError={() => setAvatarFailed(true)}
|
||||
/>
|
||||
) : imageUrl ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-6 w-6 object-contain"
|
||||
onLoad={onLogoLoad}
|
||||
onError={onLogoError}
|
||||
/>
|
||||
) : Icon ? (
|
||||
<Icon className="h-5 w-5" strokeWidth={2.25} />
|
||||
) : (
|
||||
initials
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function channelInstanceFields(
|
||||
feature: NanobotFeatureInfo,
|
||||
fields: ChannelConfigField[] | undefined,
|
||||
manualFields: ChannelConfigField[] | undefined,
|
||||
): ChannelConfigField[] {
|
||||
const available = new Map(
|
||||
[...(fields ?? []), ...(manualFields ?? [])].map((field) => [field.key, field]),
|
||||
);
|
||||
if (!feature.setup) return [...available.values()];
|
||||
return feature.setup.fields.flatMap((field) => {
|
||||
const resolved = available.get(field.key);
|
||||
return resolved ? [resolved] : [];
|
||||
});
|
||||
}
|
||||
@@ -1,10 +1,5 @@
|
||||
import { channelValidationMessage } from "./validationMessages";
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Check, Loader2, RotateCcw } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
||||
import {
|
||||
cancelChannelConnect,
|
||||
@@ -17,25 +12,14 @@ import type {
|
||||
} from "@/lib/types";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
|
||||
export type ChannelQrConnectLabels = {
|
||||
qrAlt?: string;
|
||||
scanTitle: string;
|
||||
scanDescription: string;
|
||||
waiting: string;
|
||||
connected: string;
|
||||
stopped: string;
|
||||
connecting: string;
|
||||
scanAgain: string;
|
||||
connect: string;
|
||||
};
|
||||
import {
|
||||
ChannelQrConnectFlowView,
|
||||
type ChannelQrConnectFlowViewProps,
|
||||
type ChannelQrConnectLabels,
|
||||
type ChannelQrConnectPendingContext,
|
||||
} from "./ChannelQrConnectFlowView";
|
||||
|
||||
export type ChannelQrConnectPendingContext = {
|
||||
connect: ChannelConnectPayload;
|
||||
busy: boolean;
|
||||
poll: (
|
||||
params?: Readonly<Record<string, string>>,
|
||||
) => Promise<ChannelConnectPayload | null>;
|
||||
};
|
||||
export type { ChannelQrConnectLabels, ChannelQrConnectPendingContext } from "./ChannelQrConnectFlowView";
|
||||
|
||||
export function ChannelQrConnectFlow({
|
||||
channelName,
|
||||
@@ -55,6 +39,7 @@ export function ChannelQrConnectFlow({
|
||||
suppressSucceeded = false,
|
||||
onActiveChange,
|
||||
renderActions,
|
||||
renderView,
|
||||
}: {
|
||||
token: string;
|
||||
channelName: string;
|
||||
@@ -75,13 +60,11 @@ export function ChannelQrConnectFlow({
|
||||
suppressSucceeded?: boolean;
|
||||
onActiveChange?: (active: boolean) => void;
|
||||
renderActions?: (connectButton: ReactNode) => ReactNode;
|
||||
renderView?: (props: ChannelQrConnectFlowViewProps) => ReactNode;
|
||||
}) {
|
||||
const { client } = useClient();
|
||||
const pageVisible = usePageVisibility();
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const [connect, setConnect] = useState<ChannelConnectPayload | null>(null);
|
||||
const [qrDataUrl, setQrDataUrl] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const handledRequestId = useRef(0);
|
||||
@@ -89,38 +72,10 @@ export function ChannelQrConnectFlow({
|
||||
const pollInFlight = useRef(false);
|
||||
|
||||
const pending = connect?.status === "pending";
|
||||
const succeeded = !pending && (connected || connect?.status === "succeeded");
|
||||
const canStart = !pending && !busy;
|
||||
useEffect(() => {
|
||||
onActiveChange?.(pending || busy);
|
||||
}, [pending, busy, onActiveChange]);
|
||||
const pollingPaused = Boolean(connect && pausePolling?.(connect));
|
||||
const displayMessage = connect
|
||||
? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined)
|
||||
: undefined;
|
||||
|
||||
useEffect(() => {
|
||||
if (!showQrCode || !connect?.qr_url) {
|
||||
setQrDataUrl("");
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void QRCode.toDataURL(connect.qr_url, {
|
||||
width: 184,
|
||||
margin: 1,
|
||||
color: { dark: "#111827", light: "#ffffff" },
|
||||
})
|
||||
.then((url) => {
|
||||
if (!cancelled) setQrDataUrl(url);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setQrDataUrl("");
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [connect?.qr_url, showQrCode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!connect?.session_id
|
||||
@@ -258,116 +213,23 @@ export function ChannelQrConnectFlow({
|
||||
}
|
||||
};
|
||||
|
||||
const renderActionRow = renderActions ?? ((connectButton: ReactNode) => (
|
||||
<div className="flex flex-wrap justify-end gap-2">{connectButton}</div>
|
||||
));
|
||||
|
||||
return (
|
||||
<div className="mt-3 space-y-3">
|
||||
{autoStart && busy && !connect ? (
|
||||
<div role="status" className="grid min-h-[228px] place-items-center">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
<span className="sr-only">{labels.connecting}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{pending && minimalPending && showQrCode ? (
|
||||
<div className="flex min-h-[228px] flex-col items-center justify-center gap-4 py-4">
|
||||
<div className="grid h-[196px] w-[196px] place-items-center rounded-control bg-background shadow-[inset_0_0_0_1px_oklch(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_oklch(1_0_0/0.1)]">
|
||||
{qrDataUrl ? (
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt={labels.qrAlt ?? labels.scanTitle}
|
||||
className="h-[184px] w-[184px]"
|
||||
/>
|
||||
) : (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
</div>
|
||||
{renderPending?.({ connect, busy, poll: submitPoll })}
|
||||
</div>
|
||||
) : pending ? (
|
||||
<div className={`grid gap-4 rounded-control border border-border/70 p-4 ${showQrCode ? "sm:grid-cols-[auto_minmax(0,1fr)]" : ""}`}>
|
||||
{showQrCode ? <div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">
|
||||
{qrDataUrl ? (
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt={labels.qrAlt ?? labels.scanTitle}
|
||||
className="h-[184px] w-[184px]"
|
||||
/>
|
||||
) : (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
</div> : null}
|
||||
<div className="flex min-w-0 flex-col justify-center">
|
||||
<div className="text-[13px] font-semibold text-foreground">
|
||||
{labels.scanTitle}
|
||||
</div>
|
||||
<p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">
|
||||
{!showQrCode || qrDataUrl ? labels.scanDescription : null}
|
||||
</p>
|
||||
{renderPending?.({ connect, busy, poll: submitPoll }) ?? (
|
||||
<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
{!showQrCode || qrDataUrl ? labels.waiting : labels.connecting}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
onClick={() => void cancel()}
|
||||
disabled={busy}
|
||||
>
|
||||
{tx("settings.actions.cancel", "Cancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{succeeded && !suppressSucceeded ? (
|
||||
<div className="flex items-center gap-2 rounded-control border border-emerald-500/20 px-3 py-2 text-[12px] font-medium text-emerald-700 dark:text-emerald-200">
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{displayMessage ?? labels.connected}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{connect && ["expired", "failed", "cancelled"].includes(connect.status)
|
||||
&& !(connected && connect.status === "cancelled") ? (
|
||||
<div className="rounded-control border border-border/60 px-3 py-2 text-[12px] leading-5 text-muted-foreground">
|
||||
{displayMessage || labels.stopped}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<div className="rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!pending && !(autoStart && busy && !connect) ? renderActionRow(
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 rounded-full border-border/65 bg-background/80 px-3 text-[12px] font-semibold settings-hover"
|
||||
onClick={() => void start(forceOnRepeat && succeeded)}
|
||||
disabled={!canStart}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : succeeded ? (
|
||||
<RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
) : null}
|
||||
{pending
|
||||
? labels.connecting
|
||||
: succeeded
|
||||
? labels.scanAgain
|
||||
: idleLabel ?? labels.connect}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
const viewProps: ChannelQrConnectFlowViewProps = {
|
||||
connect,
|
||||
busy,
|
||||
error,
|
||||
onStart: () => void start(forceOnRepeat && !pending && (connected || connect?.status === "succeeded")),
|
||||
onCancel: () => void cancel(),
|
||||
onPoll: submitPoll,
|
||||
idleLabel,
|
||||
connected,
|
||||
autoStart,
|
||||
minimalPending,
|
||||
showQrCode,
|
||||
labels,
|
||||
renderPending,
|
||||
resolveMessage,
|
||||
suppressSucceeded,
|
||||
renderActions,
|
||||
};
|
||||
return renderView ? renderView(viewProps) : <ChannelQrConnectFlowView {...viewProps} />;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Check, Loader2, RotateCcw } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { ChannelConnectPayload } from "@/lib/types";
|
||||
import { channelValidationMessage } from "./validationMessages";
|
||||
|
||||
export type ChannelQrConnectLabels = {
|
||||
qrAlt?: string;
|
||||
scanTitle: string;
|
||||
scanDescription: string;
|
||||
waiting: string;
|
||||
connected: string;
|
||||
stopped: string;
|
||||
connecting: string;
|
||||
scanAgain: string;
|
||||
connect: string;
|
||||
};
|
||||
|
||||
export type ChannelQrConnectPendingContext = {
|
||||
connect: ChannelConnectPayload;
|
||||
busy: boolean;
|
||||
poll: (
|
||||
params?: Readonly<Record<string, string>>,
|
||||
) => Promise<ChannelConnectPayload | null>;
|
||||
};
|
||||
|
||||
export type ChannelQrConnectFlowViewProps = {
|
||||
connect: ChannelConnectPayload | null;
|
||||
busy: boolean;
|
||||
error: string | null;
|
||||
onStart: () => void;
|
||||
onCancel: () => void;
|
||||
onPoll: ChannelQrConnectPendingContext["poll"];
|
||||
idleLabel?: string;
|
||||
connected?: boolean;
|
||||
autoStart?: boolean;
|
||||
minimalPending?: boolean;
|
||||
showQrCode?: boolean;
|
||||
labels: ChannelQrConnectLabels;
|
||||
renderPending?: (context: ChannelQrConnectPendingContext) => ReactNode;
|
||||
resolveMessage?: (payload: ChannelConnectPayload) => string | undefined;
|
||||
suppressSucceeded?: boolean;
|
||||
renderActions?: (connectButton: ReactNode) => ReactNode;
|
||||
};
|
||||
|
||||
export function ChannelQrConnectFlowView({
|
||||
connect,
|
||||
busy,
|
||||
error,
|
||||
onStart,
|
||||
onCancel,
|
||||
onPoll,
|
||||
idleLabel,
|
||||
connected = false,
|
||||
autoStart = false,
|
||||
minimalPending = false,
|
||||
showQrCode = true,
|
||||
labels,
|
||||
renderPending,
|
||||
resolveMessage,
|
||||
suppressSucceeded = false,
|
||||
renderActions,
|
||||
}: ChannelQrConnectFlowViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const [qrDataUrl, setQrDataUrl] = useState("");
|
||||
const pending = connect?.status === "pending";
|
||||
const succeeded = !pending && (connected || connect?.status === "succeeded");
|
||||
const canStart = !pending && !busy;
|
||||
const displayMessage = connect
|
||||
? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined)
|
||||
: undefined;
|
||||
|
||||
useEffect(() => {
|
||||
if (!showQrCode || !connect?.qr_url) {
|
||||
setQrDataUrl("");
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void QRCode.toDataURL(connect.qr_url, {
|
||||
width: 184,
|
||||
margin: 1,
|
||||
color: { dark: "#111827", light: "#ffffff" },
|
||||
})
|
||||
.then((url) => {
|
||||
if (!cancelled) setQrDataUrl(url);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setQrDataUrl("");
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [connect?.qr_url, showQrCode]);
|
||||
|
||||
const renderActionRow = renderActions ?? ((connectButton: ReactNode) => (
|
||||
<div className="flex flex-wrap justify-end gap-2">{connectButton}</div>
|
||||
));
|
||||
|
||||
return (
|
||||
<div className="mt-3 space-y-3">
|
||||
{autoStart && busy && !connect ? (
|
||||
<div role="status" className="grid min-h-[228px] place-items-center">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
<span className="sr-only">{labels.connecting}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{pending && minimalPending && showQrCode ? (
|
||||
<div className="flex min-h-[228px] flex-col items-center justify-center gap-4 py-4">
|
||||
<div className="grid h-[196px] w-[196px] place-items-center rounded-control bg-background shadow-[inset_0_0_0_1px_oklch(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_oklch(1_0_0/0.1)]">
|
||||
{qrDataUrl ? (
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt={labels.qrAlt ?? labels.scanTitle}
|
||||
className="h-[184px] w-[184px]"
|
||||
/>
|
||||
) : (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
</div>
|
||||
{renderPending?.({ connect, busy, poll: onPoll })}
|
||||
</div>
|
||||
) : pending ? (
|
||||
<div className={`grid gap-4 rounded-control border border-border/70 p-4 ${showQrCode ? "sm:grid-cols-[auto_minmax(0,1fr)]" : ""}`}>
|
||||
{showQrCode ? <div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">
|
||||
{qrDataUrl ? (
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt={labels.qrAlt ?? labels.scanTitle}
|
||||
className="h-[184px] w-[184px]"
|
||||
/>
|
||||
) : (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
</div> : null}
|
||||
<div className="flex min-w-0 flex-col justify-center">
|
||||
<div className="text-[13px] font-semibold text-foreground">
|
||||
{labels.scanTitle}
|
||||
</div>
|
||||
<p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">
|
||||
{!showQrCode || qrDataUrl ? labels.scanDescription : null}
|
||||
</p>
|
||||
{renderPending?.({ connect, busy, poll: onPoll }) ?? (
|
||||
<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
{!showQrCode || qrDataUrl ? labels.waiting : labels.connecting}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
onClick={() => onCancel()}
|
||||
disabled={busy}
|
||||
>
|
||||
{tx("settings.actions.cancel", "Cancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{succeeded && !suppressSucceeded ? (
|
||||
<div className="flex items-center gap-2 rounded-control border border-emerald-500/20 px-3 py-2 text-[12px] font-medium text-emerald-700 dark:text-emerald-200">
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{displayMessage ?? labels.connected}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{connect && ["expired", "failed", "cancelled"].includes(connect.status)
|
||||
&& !(connected && connect.status === "cancelled") ? (
|
||||
<div className="rounded-control border border-border/60 px-3 py-2 text-[12px] leading-5 text-muted-foreground">
|
||||
{displayMessage || labels.stopped}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<div className="rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!pending && !(autoStart && busy && !connect) ? renderActionRow(
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 rounded-full border-border/65 bg-background/80 px-3 text-[12px] font-semibold settings-hover"
|
||||
onClick={() => onStart()}
|
||||
disabled={!canStart}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : succeeded ? (
|
||||
<RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
) : null}
|
||||
{pending
|
||||
? labels.connecting
|
||||
: succeeded
|
||||
? labels.scanAgain
|
||||
: idleLabel ?? labels.connect}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,9 +11,6 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import {
|
||||
Check,
|
||||
ChevronDown,
|
||||
Clipboard,
|
||||
Loader2,
|
||||
Plus,
|
||||
} from "lucide-react";
|
||||
@@ -24,20 +21,17 @@ import type {
|
||||
ChannelFeatureAction,
|
||||
ChannelPluginConnectFlowProps,
|
||||
} from "@/channel-plugins/types";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
|
||||
import {
|
||||
type ChannelProviderPreset,
|
||||
type ChannelSetupPresentation,
|
||||
} from "@/channel-plugins/catalog";
|
||||
import {
|
||||
ChannelFieldGroups,
|
||||
channelRequirementErrors,
|
||||
channelServerValidationErrors,
|
||||
focusFirstChannelFieldError,
|
||||
} from "@/components/settings/channels/ChannelCredentialFields";
|
||||
import {
|
||||
CredentialForm,
|
||||
channelValuesForSubmit,
|
||||
defaultChannelFieldValues,
|
||||
} from "@/components/settings/channels/CredentialForm";
|
||||
@@ -49,11 +43,7 @@ import {
|
||||
channelToggleChecked,
|
||||
localizedChannelDisplayName,
|
||||
} from "@/components/settings/channels/ChannelIdentity";
|
||||
import {
|
||||
ChannelProviderPresets,
|
||||
ChannelSetupActions,
|
||||
} from "@/components/settings/channels/ChannelSetupParts";
|
||||
import { ChannelValidationProgress } from "@/components/settings/channels/ChannelValidationProgress";
|
||||
import { ChannelSetupSurfaceView } from "@/components/settings/channels/ChannelSetupSurfaceView";
|
||||
import { ChannelInstancesPanel } from "@/components/settings/channels/ChannelInstancesPanel";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -235,9 +225,6 @@ function ChannelSetupSurface({
|
||||
(field) => field.secret && configuredFields.has(field.key),
|
||||
);
|
||||
const availablePresets = feature.configured ? [] : setup.presets ?? [];
|
||||
const hasAdvanced = advancedFields.length > 0
|
||||
|| savedSecretFields.length > 0
|
||||
|| availablePresets.length > 0;
|
||||
const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
|
||||
defaultChannelFieldValues(editableFields, feature.config_values),
|
||||
);
|
||||
@@ -507,230 +494,23 @@ function ChannelSetupSurface({
|
||||
}
|
||||
};
|
||||
|
||||
const inlineActions = mode === "credentials" && primaryFields.length === 1
|
||||
&& !advancedOpen && !setup.presets?.length && !setup.actions?.length;
|
||||
const credentialActions = mode === "credentials" ? (
|
||||
<div className="ms-auto flex min-h-10 flex-wrap items-center justify-end gap-x-3 gap-y-2 sm:min-h-9">
|
||||
{feature.setup?.verifies_connection ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-10 rounded-full px-3 text-[12px] font-semibold sm:h-9"
|
||||
onClick={() => void checkCurrentSettings()}
|
||||
disabled={actionPending}
|
||||
>
|
||||
{tx("settings.channels.checkConnection", "Check connection")}
|
||||
</Button>
|
||||
) : null}
|
||||
<ToggleButton checked={enabled} disabled={actionPending}
|
||||
label={tx("settings.channels.enable", "Enable")}
|
||||
onChange={(next) => void toggleEnabled(next)} />
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (mode === "credentials") void saveCredentialSettings();
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">
|
||||
{header}
|
||||
<div className="ms-auto flex min-h-8 items-center gap-2">
|
||||
<span
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground",
|
||||
!autoSaving && autoSaveState !== "saved" && "sr-only",
|
||||
)}
|
||||
>
|
||||
{autoSaving ? (
|
||||
<>
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden />
|
||||
{tx("settings.actions.saving", "Saving")}
|
||||
</>
|
||||
) : autoSaveState === "saved" ? (
|
||||
<>
|
||||
<Check className="h-3 w-3" aria-hidden />
|
||||
{tx("settings.channels.savedSettings", "Settings saved.")}
|
||||
</>
|
||||
) : null}
|
||||
</span>
|
||||
{hasAdvanced ? (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
aria-expanded={advancedOpen}
|
||||
aria-controls={advancedPanelId}
|
||||
onClick={() => setAdvancedOpen((current) => !current)}
|
||||
>
|
||||
{tx("settings.channels.advanced", "Advanced")}
|
||||
<ChevronDown className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
advancedOpen && "rotate-180",
|
||||
)} aria-hidden />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<section className={cn("min-w-0", inlineActions ? "flex-[1_1_20rem]" : "w-full")}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex max-w-full flex-wrap justify-end gap-2">
|
||||
{mode === "webui" ? (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11.5px] font-medium text-emerald-700 dark:text-emerald-200">
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.channels.managedByWebui", "Managed by WebUI")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<ChannelSetupActions feature={feature} setup={setup} onNotice={setNotice} />
|
||||
|
||||
{mode === "connect" && ConnectFlow ? (
|
||||
<Suspense fallback={<ChannelPluginLoading compact />}>
|
||||
<ConnectFlow
|
||||
token={token}
|
||||
feature={feature}
|
||||
idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
|
||||
connectRequestId={connectRequestId}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
/>
|
||||
</Suspense>
|
||||
) : mode === "connect" ? (
|
||||
<>
|
||||
<div className="mt-3 flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"
|
||||
onClick={() =>
|
||||
setNotice(
|
||||
tx(
|
||||
"settings.channels.connectPreview",
|
||||
"Run the command below in your terminal to connect.",
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
{setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
|
||||
</Button>
|
||||
{setup.command ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
onClick={copyCommand}
|
||||
>
|
||||
<Clipboard className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.channels.copyCommand", "Copy command")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{setup.command ? (
|
||||
<code className="mt-3 block rounded-control border border-border/50 bg-muted/45 px-2.5 py-2 font-mono text-[11px] leading-5 text-foreground">
|
||||
{setup.command}
|
||||
</code>
|
||||
) : null}
|
||||
</>
|
||||
) : mode === "credentials" ? (
|
||||
<>
|
||||
{primaryFields.length ? (
|
||||
<ChannelFieldGroups
|
||||
fields={primaryFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret}
|
||||
errors={fieldErrors}
|
||||
clearedSecrets={clearedSecrets}
|
||||
onClearSecret={setSecretCleared}
|
||||
requirements={setup.requirements ?? []}
|
||||
sectionLabels={setup.sectionLabels}
|
||||
disabled={actionPending}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{hasAdvanced ? (
|
||||
<div id={advancedPanelId} hidden={!advancedOpen} className="min-w-0 w-full space-y-3 text-[12px] leading-5 text-muted-foreground">
|
||||
{availablePresets.length ? (
|
||||
<ChannelProviderPresets
|
||||
presets={availablePresets}
|
||||
onApply={applyPreset}
|
||||
label={setup.presetLabel}
|
||||
disabled={actionPending}
|
||||
/>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
{savedSecretFields.filter((field) => !(fieldValues[field.key] ?? "").trim()).map((field) => (
|
||||
<div key={field.key} className="flex min-h-9 flex-wrap items-center justify-between gap-x-4 gap-y-1">
|
||||
<span>{field.label}</span>
|
||||
<button type="button" className="min-h-8 text-[12px] hover:text-foreground"
|
||||
onClick={() => setSecretCleared(field.key, !clearedSecrets.has(field.key))}>
|
||||
{clearedSecrets.has(field.key)
|
||||
? tx("settings.channels.keepSavedSecret", "Keep saved credential")
|
||||
: tx("settings.channels.removeSavedSecret", "Remove saved credential")}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{advancedFields.length ? (
|
||||
<div onBlur={() => void saveConnectionSettings()}>
|
||||
<CredentialForm
|
||||
fields={advancedFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret}
|
||||
errors={fieldErrors}
|
||||
clearedSecrets={clearedSecrets}
|
||||
onClearSecret={setSecretCleared}
|
||||
compact
|
||||
disabled={actionPending}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{credentialActions}
|
||||
</div>
|
||||
{mode === "credentials" && feature.setup?.verifies_connection
|
||||
&& (validation || validating) ? (
|
||||
<div>
|
||||
<ChannelValidationProgress
|
||||
validation={validation}
|
||||
validating={validating}
|
||||
feature={feature}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={cn(
|
||||
"rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground",
|
||||
!notice && "sr-only",
|
||||
)}
|
||||
>
|
||||
{notice ?? ""}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
return <ChannelSetupSurfaceView
|
||||
header={header} feature={feature} setup={setup}
|
||||
primaryFields={primaryFields} advancedFields={advancedFields} savedSecretFields={savedSecretFields}
|
||||
availablePresets={availablePresets} configuredFields={configuredFields}
|
||||
fieldValues={fieldValues} visibleSecrets={visibleSecrets} clearedSecrets={clearedSecrets} fieldErrors={fieldErrors}
|
||||
actionPending={actionPending} enabled={enabled} autoSaving={autoSaving} autoSaveState={autoSaveState}
|
||||
advancedOpen={advancedOpen} advancedPanelId={advancedPanelId} validation={validation} validating={validating} notice={notice}
|
||||
onAdvancedOpenChange={setAdvancedOpen} onChangeField={setFieldValue} onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret} onClearSecret={setSecretCleared} onApplyPreset={applyPreset}
|
||||
onSubmit={saveCredentialSettings} onCheckConnection={checkCurrentSettings} onToggleEnabled={toggleEnabled}
|
||||
onSaveConnectionSettings={saveConnectionSettings} onCopyCommand={copyCommand} onNotice={setNotice}
|
||||
connectFlow={mode === "connect" && ConnectFlow ? <Suspense fallback={<ChannelPluginLoading compact />}>
|
||||
<ConnectFlow token={token} feature={feature}
|
||||
idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
|
||||
connectRequestId={connectRequestId} onFeaturesUpdate={onFeaturesUpdate} />
|
||||
</Suspense> : undefined}
|
||||
/>;
|
||||
}
|
||||
|
||||
function ChannelPluginLoading({ compact = false }: { compact?: boolean }) {
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Check, ChevronDown, Clipboard, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import type { ChannelConfigField, ChannelProviderPreset, ChannelSetupPresentation } from "@/channel-plugins/catalog";
|
||||
import { ChannelFieldGroups } from "./ChannelCredentialFields";
|
||||
import { CredentialForm } from "./CredentialForm";
|
||||
import { ChannelRuntimeError } from "./ChannelIdentity";
|
||||
import { ChannelProviderPresets, ChannelSetupActions } from "./ChannelSetupParts";
|
||||
import { ChannelValidationProgress } from "./ChannelValidationProgress";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { ChannelValidationPayload, NanobotFeatureInfo } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface ChannelSetupSurfaceViewProps {
|
||||
header: ReactNode;
|
||||
feature: NanobotFeatureInfo;
|
||||
setup: ChannelSetupPresentation;
|
||||
primaryFields: ChannelConfigField[];
|
||||
advancedFields: ChannelConfigField[];
|
||||
savedSecretFields: ChannelConfigField[];
|
||||
availablePresets: ChannelProviderPreset[];
|
||||
configuredFields: Set<string>;
|
||||
fieldValues: Record<string, string>;
|
||||
visibleSecrets: Record<string, boolean>;
|
||||
clearedSecrets: Set<string>;
|
||||
fieldErrors: Record<string, string>;
|
||||
actionPending: boolean;
|
||||
enabled: boolean;
|
||||
autoSaving: boolean;
|
||||
autoSaveState: "idle" | "saved";
|
||||
advancedOpen: boolean;
|
||||
advancedPanelId: string;
|
||||
validation: ChannelValidationPayload | null;
|
||||
validating: boolean;
|
||||
notice: string | null;
|
||||
connectFlow?: ReactNode;
|
||||
onAdvancedOpenChange: (open: boolean) => void;
|
||||
onChangeField: (key: string, value: string) => void;
|
||||
onFieldBlur: (key: string) => void;
|
||||
onToggleSecret: (key: string) => void;
|
||||
onClearSecret: (key: string, clear: boolean) => void;
|
||||
onApplyPreset: (preset: ChannelProviderPreset) => void;
|
||||
onSubmit: () => void;
|
||||
onCheckConnection: () => void;
|
||||
onToggleEnabled: (enabled: boolean) => void;
|
||||
onSaveConnectionSettings: () => void;
|
||||
onCopyCommand: () => void;
|
||||
onNotice: (notice: string | null) => void;
|
||||
}
|
||||
|
||||
export function ChannelSetupSurfaceView({
|
||||
header, feature, setup, primaryFields, advancedFields, savedSecretFields, availablePresets,
|
||||
configuredFields, fieldValues, visibleSecrets, clearedSecrets, fieldErrors, actionPending,
|
||||
enabled, autoSaving, autoSaveState, advancedOpen, advancedPanelId, validation, validating,
|
||||
notice, connectFlow, onAdvancedOpenChange,
|
||||
onChangeField: setFieldValue, onFieldBlur: saveSecretOnBlur, onToggleSecret: toggleSecret,
|
||||
onClearSecret: setSecretCleared, onApplyPreset: applyPreset, onSubmit: saveCredentialSettings,
|
||||
onCheckConnection: checkCurrentSettings, onToggleEnabled: toggleEnabled,
|
||||
onSaveConnectionSettings: saveConnectionSettings, onCopyCommand: copyCommand, onNotice: setNotice,
|
||||
}: ChannelSetupSurfaceViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const mode = setup.mode ?? "credentials";
|
||||
const hasAdvanced = advancedFields.length > 0 || savedSecretFields.length > 0 || availablePresets.length > 0;
|
||||
const inlineActions = mode === "credentials" && primaryFields.length === 1
|
||||
&& !advancedOpen && !setup.presets?.length && !setup.actions?.length;
|
||||
const credentialActions = mode === "credentials" ? (
|
||||
<div className="ms-auto flex min-h-10 flex-wrap items-center justify-end gap-x-3 gap-y-2 sm:min-h-9">
|
||||
{feature.setup?.verifies_connection ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-10 rounded-full px-3 text-[12px] font-semibold sm:h-9"
|
||||
onClick={() => void checkCurrentSettings()}
|
||||
disabled={actionPending}
|
||||
>
|
||||
{tx("settings.channels.checkConnection", "Check connection")}
|
||||
</Button>
|
||||
) : null}
|
||||
<ToggleButton checked={enabled} disabled={actionPending}
|
||||
label={tx("settings.channels.enable", "Enable")}
|
||||
onChange={(next) => void toggleEnabled(next)} />
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (mode === "credentials") void saveCredentialSettings();
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">
|
||||
{header}
|
||||
<div className="ms-auto flex min-h-8 items-center gap-2">
|
||||
<span
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground",
|
||||
!autoSaving && autoSaveState !== "saved" && "sr-only",
|
||||
)}
|
||||
>
|
||||
{autoSaving ? (
|
||||
<>
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden />
|
||||
{tx("settings.actions.saving", "Saving")}
|
||||
</>
|
||||
) : autoSaveState === "saved" ? (
|
||||
<>
|
||||
<Check className="h-3 w-3" aria-hidden />
|
||||
{tx("settings.channels.savedSettings", "Settings saved.")}
|
||||
</>
|
||||
) : null}
|
||||
</span>
|
||||
{hasAdvanced ? (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
aria-expanded={advancedOpen}
|
||||
aria-controls={advancedPanelId}
|
||||
onClick={() => onAdvancedOpenChange(!advancedOpen)}
|
||||
>
|
||||
{tx("settings.channels.advanced", "Advanced")}
|
||||
<ChevronDown className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
advancedOpen && "rotate-180",
|
||||
)} aria-hidden />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<section className={cn("min-w-0", inlineActions ? "flex-[1_1_20rem]" : "w-full")}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex max-w-full flex-wrap justify-end gap-2">
|
||||
{mode === "webui" ? (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11.5px] font-medium text-emerald-700 dark:text-emerald-200">
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.channels.managedByWebui", "Managed by WebUI")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<ChannelSetupActions feature={feature} setup={setup} onNotice={setNotice} />
|
||||
|
||||
{mode === "connect" && connectFlow ? (
|
||||
connectFlow
|
||||
) : mode === "connect" ? (
|
||||
<>
|
||||
<div className="mt-3 flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"
|
||||
onClick={() =>
|
||||
setNotice(
|
||||
tx(
|
||||
"settings.channels.connectPreview",
|
||||
"Run the command below in your terminal to connect.",
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
{setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
|
||||
</Button>
|
||||
{setup.command ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
onClick={copyCommand}
|
||||
>
|
||||
<Clipboard className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.channels.copyCommand", "Copy command")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{setup.command ? (
|
||||
<code className="mt-3 block rounded-control border border-border/50 bg-muted/45 px-2.5 py-2 font-mono text-[11px] leading-5 text-foreground">
|
||||
{setup.command}
|
||||
</code>
|
||||
) : null}
|
||||
</>
|
||||
) : mode === "credentials" ? (
|
||||
<>
|
||||
{primaryFields.length ? (
|
||||
<ChannelFieldGroups
|
||||
fields={primaryFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret}
|
||||
errors={fieldErrors}
|
||||
clearedSecrets={clearedSecrets}
|
||||
onClearSecret={setSecretCleared}
|
||||
requirements={setup.requirements ?? []}
|
||||
sectionLabels={setup.sectionLabels}
|
||||
disabled={actionPending}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{hasAdvanced ? (
|
||||
<div id={advancedPanelId} hidden={!advancedOpen} className="min-w-0 w-full space-y-3 text-[12px] leading-5 text-muted-foreground">
|
||||
{availablePresets.length ? (
|
||||
<ChannelProviderPresets
|
||||
presets={availablePresets}
|
||||
onApply={applyPreset}
|
||||
label={setup.presetLabel}
|
||||
disabled={actionPending}
|
||||
/>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
{savedSecretFields.filter((field) => !(fieldValues[field.key] ?? "").trim()).map((field) => (
|
||||
<div key={field.key} className="flex min-h-9 flex-wrap items-center justify-between gap-x-4 gap-y-1">
|
||||
<span>{field.label}</span>
|
||||
<button type="button" className="min-h-8 text-[12px] hover:text-foreground"
|
||||
onClick={() => setSecretCleared(field.key, !clearedSecrets.has(field.key))}>
|
||||
{clearedSecrets.has(field.key)
|
||||
? tx("settings.channels.keepSavedSecret", "Keep saved credential")
|
||||
: tx("settings.channels.removeSavedSecret", "Remove saved credential")}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{advancedFields.length ? (
|
||||
<div onBlur={() => void saveConnectionSettings()}>
|
||||
<CredentialForm
|
||||
fields={advancedFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret}
|
||||
errors={fieldErrors}
|
||||
clearedSecrets={clearedSecrets}
|
||||
onClearSecret={setSecretCleared}
|
||||
compact
|
||||
disabled={actionPending}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{credentialActions}
|
||||
</div>
|
||||
{mode === "credentials" && feature.setup?.verifies_connection
|
||||
&& (validation || validating) ? (
|
||||
<div>
|
||||
<ChannelValidationProgress
|
||||
validation={validation}
|
||||
validating={validating}
|
||||
feature={feature}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={cn(
|
||||
"rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground",
|
||||
!notice && "sr-only",
|
||||
)}
|
||||
>
|
||||
{notice ?? ""}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user