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
@@ -1,14 +1,6 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
channelTranslator,
|
||||
} from "@/channel-plugins/i18n";
|
||||
import type { ChannelPluginPanelProps } from "@/channel-plugins/types";
|
||||
import { ChannelInstancesPanel } from "@/components/settings/channels/ChannelInstancesPanel";
|
||||
import type {
|
||||
NanobotChannelInstanceInfo,
|
||||
NanobotFeatureInfo,
|
||||
} from "@/lib/types";
|
||||
import { FeishuAssistantsPanelView } from "./FeishuAssistantsPanelView";
|
||||
import { FeishuConnectFlow } from "./FeishuConnectFlow";
|
||||
|
||||
export function FeishuAssistantsPanel({
|
||||
@@ -17,60 +9,17 @@ export function FeishuAssistantsPanel({
|
||||
showBrandLogos,
|
||||
onFeaturesUpdate,
|
||||
}: ChannelPluginPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "feishu");
|
||||
const instances = feature.instances?.length
|
||||
? feature.instances
|
||||
: [defaultFeishuInstance(feature)];
|
||||
|
||||
return (
|
||||
<ChannelInstancesPanel
|
||||
feature={feature}
|
||||
showBrandLogos={showBrandLogos}
|
||||
instances={instances}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
customization={{
|
||||
toggleAriaLabel: (instance) => tx("custom.toggleAssistant", "{{name}} assistant", {
|
||||
name: instanceDisplayName(instance),
|
||||
}),
|
||||
configuredLabel: tx("custom.configured", "Connected"),
|
||||
needsSetupLabel: tx("custom.needsSetup", "Needs authorization"),
|
||||
renderInstanceSummary: () => null,
|
||||
renderInstanceAction: (instance) => instance.configured ? null : (
|
||||
<FeishuConnectFlow
|
||||
key={instance.id}
|
||||
token={token}
|
||||
instanceId={instance.id}
|
||||
mode="replace"
|
||||
idleLabel={t("settings.channels.connect", { defaultValue: "Connect" })}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
/>
|
||||
),
|
||||
footer: instances.some((instance) => instance.configured) ? (
|
||||
<FeishuConnectFlow
|
||||
key={instances.map((instance) => instance.id).join(",")}
|
||||
token={token}
|
||||
mode="create"
|
||||
idleLabel={tx("custom.addAssistant", "Add another assistant")}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
/>
|
||||
) : null,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function defaultFeishuInstance(feature: NanobotFeatureInfo): NanobotChannelInstanceInfo {
|
||||
return {
|
||||
id: "default",
|
||||
name: "nanobot",
|
||||
enabled: feature.enabled,
|
||||
configured: Boolean(feature.configured),
|
||||
config_values: feature.config_values ?? {},
|
||||
configured_fields: feature.configured_fields ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function instanceDisplayName(instance: NanobotChannelInstanceInfo): string {
|
||||
return instance.display_name?.trim() || instance.name.trim() || instance.id;
|
||||
return <ChannelInstancesPanel
|
||||
feature={feature}
|
||||
showBrandLogos={showBrandLogos}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
renderView={(props) => <FeishuAssistantsPanelView
|
||||
{...props}
|
||||
renderConnectFlow={(options) => <FeishuConnectFlow
|
||||
{...options}
|
||||
token={token}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
/>}
|
||||
/>}
|
||||
/>;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Fragment, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { ChannelInstancesPanelView, type ChannelInstancesPanelViewProps } from "@/components/settings/channels/ChannelInstancesPanelView";
|
||||
import type { NanobotChannelInstanceInfo, NanobotFeatureInfo } from "@/lib/types";
|
||||
|
||||
export type FeishuConnectOptions = {
|
||||
instanceId?: string;
|
||||
mode: "replace" | "create";
|
||||
idleLabel: string;
|
||||
};
|
||||
|
||||
export type FeishuAssistantsPanelViewProps = Omit<ChannelInstancesPanelViewProps, "customization"> & {
|
||||
renderConnectFlow: (options: FeishuConnectOptions) => ReactNode;
|
||||
};
|
||||
|
||||
export function FeishuAssistantsPanelView({
|
||||
feature,
|
||||
showBrandLogos,
|
||||
instances: providedInstances,
|
||||
onToggleInstance,
|
||||
onSaveInstance,
|
||||
renderConnectFlow,
|
||||
}: FeishuAssistantsPanelViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "feishu");
|
||||
const instances = providedInstances ?? (feature.instances?.length
|
||||
? feature.instances
|
||||
: [defaultFeishuInstance(feature)]);
|
||||
|
||||
return <ChannelInstancesPanelView
|
||||
feature={feature}
|
||||
showBrandLogos={showBrandLogos}
|
||||
instances={instances}
|
||||
onToggleInstance={onToggleInstance}
|
||||
onSaveInstance={onSaveInstance}
|
||||
customization={{
|
||||
toggleAriaLabel: (instance) => tx("custom.toggleAssistant", "{{name}} assistant", {
|
||||
name: instanceDisplayName(instance),
|
||||
}),
|
||||
configuredLabel: tx("custom.configured", "Connected"),
|
||||
needsSetupLabel: tx("custom.needsSetup", "Needs authorization"),
|
||||
renderInstanceSummary: () => null,
|
||||
renderInstanceAction: (instance) => instance.configured ? null : (
|
||||
<Fragment key={instance.id}>{renderConnectFlow({
|
||||
instanceId: instance.id,
|
||||
mode: "replace",
|
||||
idleLabel: t("settings.channels.connect", { defaultValue: "Connect" }),
|
||||
})}</Fragment>
|
||||
),
|
||||
footer: instances.some((instance) => instance.configured) ? (
|
||||
<Fragment key={instances.map((instance) => instance.id).join(",")}>{renderConnectFlow({
|
||||
mode: "create",
|
||||
idleLabel: tx("custom.addAssistant", "Add another assistant"),
|
||||
})}</Fragment>
|
||||
) : null,
|
||||
}}
|
||||
/>;
|
||||
}
|
||||
|
||||
function defaultFeishuInstance(feature: NanobotFeatureInfo): NanobotChannelInstanceInfo {
|
||||
return {
|
||||
id: "default",
|
||||
name: "nanobot",
|
||||
enabled: feature.enabled,
|
||||
configured: Boolean(feature.configured),
|
||||
config_values: feature.config_values ?? {},
|
||||
configured_fields: feature.configured_fields ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function instanceDisplayName(instance: NanobotChannelInstanceInfo): string {
|
||||
return instance.display_name?.trim() || instance.name.trim() || instance.id;
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
|
||||
import type { NanobotFeaturesPayload } from "@/lib/types";
|
||||
|
||||
import { FeishuConnectFlowView, useFeishuConnectLabels } from "./FeishuConnectFlowView";
|
||||
|
||||
export function FeishuConnectFlow({
|
||||
token,
|
||||
instanceId = "default",
|
||||
@@ -19,8 +18,7 @@ export function FeishuConnectFlow({
|
||||
connectRequestId?: number;
|
||||
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "feishu");
|
||||
const labels = useFeishuConnectLabels();
|
||||
return (
|
||||
<ChannelQrConnectFlow
|
||||
token={token}
|
||||
@@ -29,20 +27,8 @@ export function FeishuConnectFlow({
|
||||
idleLabel={idleLabel}
|
||||
connectRequestId={connectRequestId}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
labels={{
|
||||
qrAlt: tx("custom.qrAlt", "Feishu connection QR code"),
|
||||
scanTitle: tx("custom.scanTitle", "Scan with Feishu"),
|
||||
scanDescription: tx(
|
||||
"custom.scanDescription",
|
||||
"Use Feishu or Lark on your phone to scan this code. nanobot will finish setup automatically after authorization.",
|
||||
),
|
||||
waiting: tx("custom.waiting", "Waiting for authorization..."),
|
||||
connected: tx("custom.connected", "Feishu is connected."),
|
||||
stopped: tx("custom.stopped", "Connection stopped."),
|
||||
connecting: tx("custom.connecting", "Connecting..."),
|
||||
scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }),
|
||||
connect: t("settings.channels.connect", { defaultValue: "Connect" }),
|
||||
}}
|
||||
labels={labels}
|
||||
renderView={(props) => <FeishuConnectFlowView {...props} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { ChannelQrConnectFlowView, type ChannelQrConnectFlowViewProps, type ChannelQrConnectLabels } from "@/components/settings/channels/ChannelQrConnectFlowView";
|
||||
|
||||
export type FeishuConnectFlowViewProps = Omit<ChannelQrConnectFlowViewProps, "labels">;
|
||||
|
||||
export function useFeishuConnectLabels(): ChannelQrConnectLabels {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "feishu");
|
||||
return {
|
||||
qrAlt: tx("custom.qrAlt", "Feishu connection QR code"),
|
||||
scanTitle: tx("custom.scanTitle", "Scan with Feishu"),
|
||||
scanDescription: tx(
|
||||
"custom.scanDescription",
|
||||
"Use Feishu or Lark on your phone to scan this code. nanobot will finish setup automatically after authorization.",
|
||||
),
|
||||
waiting: tx("custom.waiting", "Waiting for authorization..."),
|
||||
connected: tx("custom.connected", "Feishu is connected."),
|
||||
stopped: tx("custom.stopped", "Connection stopped."),
|
||||
connecting: tx("custom.connecting", "Connecting..."),
|
||||
scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }),
|
||||
connect: t("settings.channels.connect", { defaultValue: "Connect" }),
|
||||
};
|
||||
}
|
||||
|
||||
export function FeishuConnectFlowView(props: FeishuConnectFlowViewProps) {
|
||||
const labels = useFeishuConnectLabels();
|
||||
return <ChannelQrConnectFlowView {...props} labels={labels} />;
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useCallback, useRef, type ReactNode } from "react";
|
||||
import { ExternalLink } from "lucide-react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";
|
||||
|
||||
import { LinearConnectFlowView, linearConnectLabels } from "./LinearConnectFlowView";
|
||||
|
||||
export function LinearConnectFlow({
|
||||
token,
|
||||
feature,
|
||||
@@ -23,62 +23,10 @@ export function LinearConnectFlow({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "linear");
|
||||
const flowRef = useRef<HTMLDivElement | null>(null);
|
||||
const revealAuthorization = useCallback((link: HTMLAnchorElement | null) => {
|
||||
if (!link) return;
|
||||
flowRef.current?.scrollIntoView({ block: "nearest" });
|
||||
link.focus({ preventScroll: true });
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div ref={flowRef} className="mt-3 space-y-3">
|
||||
<ChannelQrConnectFlow
|
||||
token={token}
|
||||
channelName="linear"
|
||||
idleLabel={idleLabel}
|
||||
connectRequestId={connectRequestId}
|
||||
startParams={connectRequestId ? { force: true } : undefined}
|
||||
forceOnRepeat
|
||||
showQrCode={false}
|
||||
connected={connected}
|
||||
suppressSucceeded={feature.runtime_status === "running" || feature.runtime_status === "failed"}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
onActiveChange={onActiveChange}
|
||||
renderActions={renderActions}
|
||||
labels={{
|
||||
scanTitle: tx("custom.authorizeTitle", "Authorize in Linear"),
|
||||
scanDescription: tx(
|
||||
"custom.authorizeDescription",
|
||||
"Continue in Linear to choose a workspace and authorize nanobot. Return here when you're done.",
|
||||
),
|
||||
waiting: tx("custom.waiting", "Waiting for Linear authorization..."),
|
||||
connected: tx("custom.connected", "Linear is connected."),
|
||||
stopped: tx("custom.stopped", "Authorization stopped."),
|
||||
connecting: tx("custom.connecting", "Connecting..."),
|
||||
scanAgain: tx("custom.reauthorize", "Reauthorize"),
|
||||
connect: tx("custom.connect", "Connect Linear"),
|
||||
}}
|
||||
renderPending={({ connect }) => (
|
||||
<div className="mt-3 space-y-3">
|
||||
<div className="flex items-center gap-2 text-[12px] text-muted-foreground">
|
||||
<span className="h-2 w-2 animate-pulse rounded-full bg-[#5E6AD2] motion-reduce:animate-none" aria-hidden />
|
||||
{tx("custom.waiting", "Waiting for Linear authorization...")}
|
||||
</div>
|
||||
{connect.qr_url ? (
|
||||
<Button
|
||||
asChild
|
||||
size="sm"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
>
|
||||
<a ref={revealAuthorization} href={connect.qr_url} target="_blank" rel="noreferrer">
|
||||
<ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
{tx("custom.openLinear", "Continue in Linear")}
|
||||
</a>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
return <ChannelQrConnectFlow token={token} channelName="linear" idleLabel={idleLabel}
|
||||
connectRequestId={connectRequestId} startParams={connectRequestId ? { force: true } : undefined}
|
||||
forceOnRepeat showQrCode={false} connected={connected}
|
||||
suppressSucceeded={feature.runtime_status === "running" || feature.runtime_status === "failed"}
|
||||
onFeaturesUpdate={onFeaturesUpdate} onActiveChange={onActiveChange} renderActions={renderActions}
|
||||
labels={linearConnectLabels(tx)} renderView={(props) => <LinearConnectFlowView {...props} />} />;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useCallback, useRef } from "react";
|
||||
import { ExternalLink } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { ChannelQrConnectFlowView, type ChannelQrConnectFlowViewProps, type ChannelQrConnectLabels } from "@/components/settings/channels/ChannelQrConnectFlowView";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export function linearConnectLabels(tx: ReturnType<typeof channelTranslator>): ChannelQrConnectLabels {
|
||||
return {
|
||||
scanTitle: tx("custom.authorizeTitle", "Authorize in Linear"),
|
||||
scanDescription: tx("custom.authorizeDescription", "Continue in Linear to choose a workspace and authorize nanobot. Return here when you're done."),
|
||||
waiting: tx("custom.waiting", "Waiting for Linear authorization..."),
|
||||
connected: tx("custom.connected", "Linear is connected."),
|
||||
stopped: tx("custom.stopped", "Authorization stopped."),
|
||||
connecting: tx("custom.connecting", "Connecting..."),
|
||||
scanAgain: tx("custom.reauthorize", "Reauthorize"),
|
||||
connect: tx("custom.connect", "Connect Linear"),
|
||||
};
|
||||
}
|
||||
|
||||
export function LinearConnectFlowView(props: ChannelQrConnectFlowViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "linear");
|
||||
const flowRef = useRef<HTMLDivElement | null>(null);
|
||||
const revealAuthorization = useCallback((link: HTMLAnchorElement | null) => {
|
||||
if (!link) return;
|
||||
flowRef.current?.scrollIntoView({ block: "nearest" });
|
||||
link.focus({ preventScroll: true });
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div ref={flowRef} className="mt-3 space-y-3">
|
||||
<ChannelQrConnectFlowView {...props} showQrCode={false}
|
||||
renderPending={({ connect }) => (
|
||||
<div className="mt-3 space-y-3">
|
||||
<div className="flex items-center gap-2 text-[12px] text-muted-foreground">
|
||||
<span className="h-2 w-2 animate-pulse rounded-full bg-[#5E6AD2] motion-reduce:animate-none" aria-hidden />
|
||||
{tx("custom.waiting", "Waiting for Linear authorization...")}
|
||||
</div>
|
||||
{connect.qr_url ? (
|
||||
<Button
|
||||
asChild
|
||||
size="sm"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
>
|
||||
<a ref={revealAuthorization} href={connect.qr_url} target="_blank" rel="noreferrer">
|
||||
<ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
{tx("custom.openLinear", "Continue in Linear")}
|
||||
</a>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +1,9 @@
|
||||
import { useEffect, useId, useState, useSyncExternalStore } from "react";
|
||||
import { Check, ChevronDown, Info, RefreshCw, Search } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { SETTINGS_SEARCH_INPUT_CLASS, SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";
|
||||
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DisclosureContent } from "@/components/ui/disclosure";
|
||||
import { SearchInput } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
|
||||
import { linearMemberAccessStore } from "./member-access-store";
|
||||
import { LinearAvatar } from "./LinearAvatar";
|
||||
import { LinearMemberAccessView } from "./LinearMemberAccessView";
|
||||
|
||||
export function LinearMemberAccess({ organizationId, configScope = "", disabled = false }: {
|
||||
organizationId: string;
|
||||
@@ -21,115 +11,8 @@ export function LinearMemberAccess({ organizationId, configScope = "", disabled
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const { client, token } = useClient();
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "linear");
|
||||
const panelId = useId();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
const store = linearMemberAccessStore(client, token, configScope, organizationId);
|
||||
const { payload, loading, error, saves } = useSyncExternalStore(store.subscribe, store.getSnapshot);
|
||||
const members = payload?.members ?? [];
|
||||
const saving = Object.values(saves).some((save) => save.status === "saving");
|
||||
|
||||
useEffect(() => {
|
||||
if (expanded && !disabled) void store.load();
|
||||
}, [store, expanded, disabled]);
|
||||
|
||||
const prefetch = () => { if (!disabled) void store.load(); };
|
||||
const needle = search.trim().toLocaleLowerCase();
|
||||
const visible = members.filter((member) => [member.name, member.id]
|
||||
.some((value) => value.toLocaleLowerCase().includes(needle)));
|
||||
const names = new Set<string>();
|
||||
const duplicateNames = new Set<string>();
|
||||
for (const member of members) {
|
||||
if (names.has(member.name)) duplicateNames.add(member.name);
|
||||
names.add(member.name);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="w-full border-t border-border/50 bg-settings-surface">
|
||||
<button type="button" aria-expanded={expanded} aria-controls={panelId}
|
||||
disabled={disabled} onMouseEnter={prefetch} onFocus={prefetch}
|
||||
className="settings-list-inset flex min-h-12 w-full items-center justify-between gap-3 py-2 text-start text-[12px] font-medium settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"
|
||||
onClick={() => setExpanded(!expanded)}>
|
||||
<span className="shrink-0">{tx("members.title", "Member access")}</span>
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<span role="status" aria-live="polite" className="text-end text-[11px] font-normal text-muted-foreground">
|
||||
{payload ? !expanded ? tx("members.summary", "{{allowed}} enabled", {
|
||||
allowed: members.filter((member) => member.allowed).length,
|
||||
}) : null : loading ? tx("members.loading", "Finding members…") : null}
|
||||
</span>
|
||||
<ChevronDown className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 motion-reduce:transition-none", expanded && "rotate-180")} aria-hidden />
|
||||
</span>
|
||||
</button>
|
||||
<span role="status" aria-live="polite" className="sr-only">
|
||||
{payload && loading ? tx("members.refreshing", "Checking for updates…") : null}
|
||||
</span>
|
||||
<DisclosureContent id={panelId} open={expanded} className="space-y-3 pb-2">
|
||||
{payload?.legacy_allow_all ? <p className="settings-list-inset rounded-control bg-muted py-2 text-[12px] leading-5">
|
||||
{tx("members.allowAll", "Advanced settings currently allow all members (*), including new members. Individual off switches still take precedence. Remove * to require approval for new members.")}
|
||||
</p> : null}
|
||||
<div className="settings-list-inset flex items-center gap-2">
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />
|
||||
<SearchInput value={search} onChange={(event) => setSearch(event.target.value)}
|
||||
aria-label={tx("members.search", "Search members")}
|
||||
placeholder={tx("members.search", "Search members")}
|
||||
className={cn(SETTINGS_SEARCH_INPUT_CLASS, "pl-9 text-[13px]")} />
|
||||
</div>
|
||||
<Button type="button" variant="ghost" size="icon" disabled={disabled || loading || saving}
|
||||
onClick={() => void store.load(true)} aria-label={tx("members.refresh", "Refresh members")}
|
||||
title={tx("members.refresh", "Refresh members")}>
|
||||
<RefreshCw className="h-4 w-4 text-muted-foreground" aria-hidden />
|
||||
</Button>
|
||||
<SettingsHint description={tx("members.help", "Enable members to use nanobot without a pairing code. Linear's existing authorization still applies. This does not grant access to the nanobot admin UI. Turning access off blocks new requests, not tasks already running.")}>
|
||||
<span className="flex h-9 w-9 items-center justify-center text-muted-foreground">
|
||||
<Info className="h-4 w-4" aria-hidden />
|
||||
<span className="sr-only">{tx("members.details", "About member access")}</span>
|
||||
</span>
|
||||
</SettingsHint>
|
||||
</div>
|
||||
{error ? <p role="alert" className="settings-list-inset break-words text-[12px] leading-5 text-destructive">
|
||||
{error} {tx("members.retry", "Refresh members to check the current state and try again.")}
|
||||
</p> : null}
|
||||
{payload && !error && visible.length === 0 ? <p className="settings-list-inset py-3 text-[12px] text-muted-foreground">
|
||||
{tx("members.empty", "No matching active members.")}
|
||||
</p> : null}
|
||||
<SettingsGroup>
|
||||
<ul className="max-h-80 overflow-y-auto" aria-label={tx("members.title", "Member access")}>
|
||||
{visible.map((member) => {
|
||||
const save = saves[member.id];
|
||||
const statusId = `${panelId}-${member.id}-status`;
|
||||
return <li key={member.id}>
|
||||
<SettingsRow title={<div className="flex min-w-0 items-center gap-3">
|
||||
<LinearAvatar name={member.name} url={member.avatar_url} />
|
||||
<div className="min-w-0">
|
||||
<p className="truncate" title={member.id}>{member.name}</p>
|
||||
<div className="flex flex-wrap items-center gap-x-2 text-[12px] font-normal leading-4 text-muted-foreground">
|
||||
<span id={save?.status === "error" ? undefined : statusId} role="status" aria-live="polite" className="inline-flex items-center gap-1">
|
||||
{save?.status === "saving" ? tx("members.working", "Saving…") : null}
|
||||
{save?.status === "saved" ? <><Check className="h-3 w-3" aria-hidden />{tx("members.saved", "Saved")}</> : null}
|
||||
</span>
|
||||
</div>
|
||||
{duplicateNames.has(member.name) ?
|
||||
<p className="break-all text-[11px] font-normal text-muted-foreground">{member.id}</p> : null}
|
||||
</div>
|
||||
</div>}>
|
||||
<ToggleButton checked={member.allowed}
|
||||
disabled={disabled || save?.status === "saving" || save?.status === "error"}
|
||||
aria-describedby={save ? statusId : undefined} aria-invalid={save?.status === "error" || undefined}
|
||||
label={tx("members.allow", "Allow {{name}} to use nanobot", { name: member.name })}
|
||||
onChange={(allowed) => void store.setAllowed(member.id, allowed,
|
||||
tx("members.saveUnconfirmed", "Access was not confirmed. Refresh members before trying again."))} />
|
||||
</SettingsRow>
|
||||
{save?.status === "error" ? <p id={statusId} role="alert" className="settings-list-inset break-words pb-3 text-[12px] leading-5 text-destructive">
|
||||
{save.message} {tx("members.retry", "Refresh members to check the current state and try again.")}
|
||||
</p> : null}
|
||||
</li>;
|
||||
})}
|
||||
</ul>
|
||||
</SettingsGroup>
|
||||
</DisclosureContent>
|
||||
</section>
|
||||
);
|
||||
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot);
|
||||
return <LinearMemberAccessView snapshot={snapshot} disabled={disabled}
|
||||
onLoad={store.load} onSetAllowed={store.setAllowed} />;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import { Check, ChevronDown, Info, RefreshCw, Search } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { SETTINGS_SEARCH_INPUT_CLASS, SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";
|
||||
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DisclosureContent } from "@/components/ui/disclosure";
|
||||
import { SearchInput } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { LinearAvatar } from "./LinearAvatar";
|
||||
|
||||
import type { LinearMembersPayload } from "./types";
|
||||
|
||||
export type LinearMemberSave = { status: "saving" | "saved" } | { status: "error"; message: string };
|
||||
export interface LinearMemberAccessSnapshot {
|
||||
payload: LinearMembersPayload | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
saves: Record<string, LinearMemberSave>;
|
||||
}
|
||||
|
||||
export function LinearMemberAccessView({ snapshot, disabled = false, onLoad, onSetAllowed }: {
|
||||
snapshot: LinearMemberAccessSnapshot;
|
||||
disabled?: boolean;
|
||||
onLoad: (force?: boolean) => void;
|
||||
onSetAllowed: (userId: string, allowed: boolean, unconfirmedMessage: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "linear");
|
||||
const panelId = useId();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
const { payload, loading, error, saves } = snapshot;
|
||||
const members = payload?.members ?? [];
|
||||
const saving = Object.values(saves).some((save) => save.status === "saving");
|
||||
|
||||
useEffect(() => {
|
||||
if (expanded && !disabled) onLoad();
|
||||
}, [onLoad, expanded, disabled]);
|
||||
|
||||
const prefetch = () => { if (!disabled) onLoad(); };
|
||||
const needle = search.trim().toLocaleLowerCase();
|
||||
const visible = members.filter((member) => [member.name, member.id]
|
||||
.some((value) => value.toLocaleLowerCase().includes(needle)));
|
||||
const names = new Set<string>();
|
||||
const duplicateNames = new Set<string>();
|
||||
for (const member of members) {
|
||||
if (names.has(member.name)) duplicateNames.add(member.name);
|
||||
names.add(member.name);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="w-full border-t border-border/50 bg-settings-surface">
|
||||
<button type="button" aria-expanded={expanded} aria-controls={panelId}
|
||||
disabled={disabled} onMouseEnter={prefetch} onFocus={prefetch}
|
||||
className="settings-list-inset flex min-h-12 w-full items-center justify-between gap-3 py-2 text-start text-[12px] font-medium settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"
|
||||
onClick={() => setExpanded(!expanded)}>
|
||||
<span className="shrink-0">{tx("members.title", "Member access")}</span>
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<span role="status" aria-live="polite" className="text-end text-[11px] font-normal text-muted-foreground">
|
||||
{payload ? !expanded ? tx("members.summary", "{{allowed}} enabled", {
|
||||
allowed: members.filter((member) => member.allowed).length,
|
||||
}) : null : loading ? tx("members.loading", "Finding members…") : null}
|
||||
</span>
|
||||
<ChevronDown className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 motion-reduce:transition-none", expanded && "rotate-180")} aria-hidden />
|
||||
</span>
|
||||
</button>
|
||||
<span role="status" aria-live="polite" className="sr-only">
|
||||
{payload && loading ? tx("members.refreshing", "Checking for updates…") : null}
|
||||
</span>
|
||||
<DisclosureContent id={panelId} open={expanded} className="space-y-3 pb-2">
|
||||
{payload?.legacy_allow_all ? <p className="settings-list-inset rounded-control bg-muted py-2 text-[12px] leading-5">
|
||||
{tx("members.allowAll", "Advanced settings currently allow all members (*), including new members. Individual off switches still take precedence. Remove * to require approval for new members.")}
|
||||
</p> : null}
|
||||
<div className="settings-list-inset flex items-center gap-2">
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />
|
||||
<SearchInput value={search} onChange={(event) => setSearch(event.target.value)}
|
||||
aria-label={tx("members.search", "Search members")}
|
||||
placeholder={tx("members.search", "Search members")}
|
||||
className={cn(SETTINGS_SEARCH_INPUT_CLASS, "pl-9 text-[13px]")} />
|
||||
</div>
|
||||
<Button type="button" variant="ghost" size="icon" disabled={disabled || loading || saving}
|
||||
onClick={() => onLoad(true)} aria-label={tx("members.refresh", "Refresh members")}
|
||||
title={tx("members.refresh", "Refresh members")}>
|
||||
<RefreshCw className="h-4 w-4 text-muted-foreground" aria-hidden />
|
||||
</Button>
|
||||
<SettingsHint description={tx("members.help", "Enable members to use nanobot without a pairing code. Linear's existing authorization still applies. This does not grant access to the nanobot admin UI. Turning access off blocks new requests, not tasks already running.")}>
|
||||
<span className="flex h-9 w-9 items-center justify-center text-muted-foreground">
|
||||
<Info className="h-4 w-4" aria-hidden />
|
||||
<span className="sr-only">{tx("members.details", "About member access")}</span>
|
||||
</span>
|
||||
</SettingsHint>
|
||||
</div>
|
||||
{error ? <p role="alert" className="settings-list-inset break-words text-[12px] leading-5 text-destructive">
|
||||
{error} {tx("members.retry", "Refresh members to check the current state and try again.")}
|
||||
</p> : null}
|
||||
{payload && !error && visible.length === 0 ? <p className="settings-list-inset py-3 text-[12px] text-muted-foreground">
|
||||
{tx("members.empty", "No matching active members.")}
|
||||
</p> : null}
|
||||
<SettingsGroup>
|
||||
<ul className="max-h-80 overflow-y-auto" aria-label={tx("members.title", "Member access")}>
|
||||
{visible.map((member) => {
|
||||
const save = saves[member.id];
|
||||
const statusId = `${panelId}-${member.id}-status`;
|
||||
return <li key={member.id}>
|
||||
<SettingsRow title={<div className="flex min-w-0 items-center gap-3">
|
||||
<LinearAvatar name={member.name} url={member.avatar_url} />
|
||||
<div className="min-w-0">
|
||||
<p className="truncate" title={member.id}>{member.name}</p>
|
||||
<div className="flex flex-wrap items-center gap-x-2 text-[12px] font-normal leading-4 text-muted-foreground">
|
||||
<span id={save?.status === "error" ? undefined : statusId} role="status" aria-live="polite" className="inline-flex items-center gap-1">
|
||||
{save?.status === "saving" ? tx("members.working", "Saving…") : null}
|
||||
{save?.status === "saved" ? <><Check className="h-3 w-3" aria-hidden />{tx("members.saved", "Saved")}</> : null}
|
||||
</span>
|
||||
</div>
|
||||
{duplicateNames.has(member.name) ?
|
||||
<p className="break-all text-[11px] font-normal text-muted-foreground">{member.id}</p> : null}
|
||||
</div>
|
||||
</div>}>
|
||||
<ToggleButton checked={member.allowed}
|
||||
disabled={disabled || save?.status === "saving" || save?.status === "error"}
|
||||
aria-describedby={save ? statusId : undefined} aria-invalid={save?.status === "error" || undefined}
|
||||
label={tx("members.allow", "Allow {{name}} to use nanobot", { name: member.name })}
|
||||
onChange={(allowed) => onSetAllowed(member.id, allowed,
|
||||
tx("members.saveUnconfirmed", "Access was not confirmed. Refresh members before trying again."))} />
|
||||
</SettingsRow>
|
||||
{save?.status === "error" ? <p id={statusId} role="alert" className="settings-list-inset break-words pb-3 text-[12px] leading-5 text-destructive">
|
||||
{save.message} {tx("members.retry", "Refresh members to check the current state and try again.")}
|
||||
</p> : null}
|
||||
</li>;
|
||||
})}
|
||||
</ul>
|
||||
</SettingsGroup>
|
||||
</DisclosureContent>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,61 +1,24 @@
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { AlertCircle, Check, ChevronDown, ExternalLink, Info, Loader2, MoreHorizontal, Plus, RefreshCw, Unplug } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import type { ChannelPluginPanelProps } from "@/channel-plugins/types";
|
||||
import {
|
||||
CredentialForm,
|
||||
channelFieldInputId,
|
||||
channelValuesForSubmit,
|
||||
defaultChannelFieldValues,
|
||||
} from "@/components/settings/channels/CredentialForm";
|
||||
import {
|
||||
CHANNEL_SETUP_PANEL_CLASS_NAME,
|
||||
ChannelLogo,
|
||||
ChannelRuntimeError,
|
||||
channelSetup,
|
||||
localizedChannelDisplayName,
|
||||
} from "@/components/settings/channels/ChannelIdentity";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { channelValidationStatusClass } from "@/components/settings/channels/ChannelValidationProgress";
|
||||
import { channelValuesForSubmit, defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";
|
||||
import { channelSetup } from "@/components/settings/channels/ChannelIdentity";
|
||||
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
|
||||
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
|
||||
import { configureChannel, disableNanobotFeature, fetchNanobotFeatures } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
|
||||
import { manageLinearWorkspace } from "./api";
|
||||
import type { LinearInstallationSummary } from "./types";
|
||||
import { LinearConnectFlow } from "./LinearConnectFlow";
|
||||
import { LinearMemberAccess } from "./LinearMemberAccess";
|
||||
import { LinearAvatar } from "./LinearAvatar";
|
||||
import { linearManifestUrl } from "./manifest";
|
||||
import { linearWorkspaceStore } from "./workspace-store";
|
||||
import { linearMemberAccessStore } from "./member-access-store";
|
||||
import { LinearResetConnection } from "./LinearResetConnection";
|
||||
import { LinearSecretField } from "./LinearSecretField";
|
||||
import { LinearPanelView } from "./LinearPanelView";
|
||||
|
||||
const PUBLIC_BASE_URL_KEY = "channels.linear.publicBaseUrl";
|
||||
const WEBHOOK_PATH_KEY = "channels.linear.webhookPath";
|
||||
const CALLBACK_PATH_KEY = "channels.linear.oauthCallbackPath";
|
||||
|
||||
export function LinearPanel({
|
||||
token,
|
||||
feature,
|
||||
@@ -68,7 +31,6 @@ export function LinearPanel({
|
||||
const { client } = useClient();
|
||||
const { t, i18n } = useTranslation();
|
||||
const tx = channelTranslator(t, "linear");
|
||||
const displayName = localizedChannelDisplayName(feature, t);
|
||||
const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);
|
||||
const fields = setup.fields ?? [];
|
||||
const advancedFields = setup.manualFields ?? [];
|
||||
@@ -84,7 +46,6 @@ export function LinearPanel({
|
||||
const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());
|
||||
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
|
||||
const [clearedSecrets, setClearedSecrets] = useState<Set<string>>(() => new Set());
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [resetting, setResetting] = useState(false);
|
||||
const [connecting, setConnecting] = useState(false);
|
||||
@@ -92,7 +53,6 @@ export function LinearPanel({
|
||||
const [connectionGeneration, setConnectionGeneration] = useState(0);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [publicUrlPromptOpen, setPublicUrlPromptOpen] = useState(false);
|
||||
const workspaceStore = linearWorkspaceStore(client, token, JSON.stringify([
|
||||
feature.config_values?.["channels.linear.clientId"],
|
||||
feature.config_values?.[PUBLIC_BASE_URL_KEY],
|
||||
@@ -101,15 +61,10 @@ export function LinearPanel({
|
||||
error: inspectionError } = useSyncExternalStore(workspaceStore.subscribe, workspaceStore.getSnapshot);
|
||||
const installations = cachedInstallations ?? [];
|
||||
const [disconnectingId, setDisconnectingId] = useState<string | null>(null);
|
||||
const [disconnectConfirmId, setDisconnectConfirmId] = useState<string | null>(null);
|
||||
const [workspaceNotice, setWorkspaceNotice] = useState<string | null>(null);
|
||||
const [workspaceError, setWorkspaceError] = useState<string | null>(null);
|
||||
const workspaceActionRef = useRef<HTMLButtonElement | null>(null);
|
||||
const skipMenuRestoreFocus = useRef(false);
|
||||
const disconnectTarget = installations.find(item => item.organization_id === disconnectConfirmId);
|
||||
const savePromiseRef = useRef<Promise<boolean> | null>(null);
|
||||
const secretSavePromiseRef = useRef<Promise<void> | null>(null);
|
||||
const advancedPanelId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
setFieldValues(defaultChannelFieldValues(editableFields, feature.config_values));
|
||||
@@ -127,7 +82,6 @@ export function LinearPanel({
|
||||
const touchedSecret = secretFields.some((field) =>
|
||||
touchedFields.has(field.key) && Boolean(fieldValues[field.key]?.trim()),
|
||||
);
|
||||
const hasSavedSecrets = secretFields.some((field) => configuredFields.has(field.key));
|
||||
const memberConfigScope = JSON.stringify([
|
||||
feature.config_values?.["channels.linear.clientId"],
|
||||
feature.config_values?.["channels.linear.allowFrom"],
|
||||
@@ -135,23 +89,9 @@ export function LinearPanel({
|
||||
const forgetWorkspaceMembers = (organizationId: string) => {
|
||||
linearMemberAccessStore(client, token, memberConfigScope, organizationId).invalidate();
|
||||
};
|
||||
const manifestDirty = [PUBLIC_BASE_URL_KEY, WEBHOOK_PATH_KEY, CALLBACK_PATH_KEY].some(
|
||||
(key) => fieldValues[key] !== savedValues[key],
|
||||
);
|
||||
const credentialsSaved = fields.filter((field) => !field.optional).every((field) =>
|
||||
configuredFields.has(field.key) || Boolean(feature.config_values?.[field.key]?.trim()),
|
||||
);
|
||||
const workspaceActionsDisabled = busy || dirty || connecting || loadingInstallations
|
||||
|| disconnectingId !== null;
|
||||
const savedBaseUrl = feature.config_values?.[PUBLIC_BASE_URL_KEY]?.replace(/\/$/, "");
|
||||
const manifestUrl = savedBaseUrl
|
||||
? linearManifestUrl(
|
||||
savedBaseUrl,
|
||||
feature.config_values?.[WEBHOOK_PATH_KEY] || "/linear/webhook",
|
||||
feature.config_values?.[CALLBACK_PATH_KEY] || "/linear/oauth/callback",
|
||||
)
|
||||
: null;
|
||||
|
||||
const loadInstallations = useCallback(async (force = false) => {
|
||||
if (!credentialsSaved || dirty) return;
|
||||
setWorkspaceNotice(null);
|
||||
@@ -171,7 +111,7 @@ export function LinearPanel({
|
||||
});
|
||||
}, [client, feature.runtime_status, loadInstallations]);
|
||||
|
||||
const disconnectWorkspace = async (installation: LinearInstallationSummary) => {
|
||||
const disconnectWorkspace = async (installation: LinearInstallationSummary, onRemoved: () => void) => {
|
||||
setDisconnectingId(installation.organization_id);
|
||||
setWorkspaceNotice(null);
|
||||
setWorkspaceError(null);
|
||||
@@ -187,7 +127,7 @@ export function LinearPanel({
|
||||
forgetWorkspaceMembers(installation.organization_id);
|
||||
workspaceStore.replace(remaining);
|
||||
setWorkspaceNotice(payload.message ?? null);
|
||||
setDisconnectConfirmId(null);
|
||||
onRemoved();
|
||||
setConnectRequestId(0);
|
||||
setConnectionGeneration(value => value + 1);
|
||||
if (remaining.length === 0) {
|
||||
@@ -303,314 +243,30 @@ export function LinearPanel({
|
||||
compact: true,
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
|
||||
<form className="flex min-w-0 flex-col gap-4" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void saveSettings();
|
||||
}}>
|
||||
<div className="flex min-h-10 flex-wrap items-center justify-between gap-3 pe-20">
|
||||
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
|
||||
<h3 className="sr-only">{displayName}</h3>
|
||||
<span role="status" aria-live="polite" aria-atomic="true"
|
||||
className="min-w-0 flex-1 truncate text-[11px] text-muted-foreground">
|
||||
{saving ? t("settings.actions.saving", { defaultValue: "Saving" })
|
||||
: saved ? t("settings.channels.savedSettings", { defaultValue: "Settings saved." }) : ""}
|
||||
</span>
|
||||
{feature.runtime_status === "running" ? (
|
||||
<span role="status" className={cn(
|
||||
"ms-auto inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[11.5px] font-medium leading-none",
|
||||
channelValidationStatusClass("connected"),
|
||||
)}>
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("custom.channelRunning", "Channel running")}
|
||||
</span>
|
||||
) : null}
|
||||
<button type="button"
|
||||
className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded px-1 text-[12px] leading-none text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
aria-expanded={advancedOpen} aria-controls={advancedPanelId}
|
||||
onClick={() => setAdvancedOpen((current) => !current)}>
|
||||
{t("settings.channels.advanced", { defaultValue: "Advanced" })}
|
||||
<ChevronDown className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
advancedOpen && "rotate-180",
|
||||
)} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
<CredentialForm {...formProps} fields={fields.filter((field) => field.key === PUBLIC_BASE_URL_KEY)} />
|
||||
<div className="grid gap-y-4">
|
||||
{fields.filter(field => field.key !== PUBLIC_BASE_URL_KEY).map(field => field.secret ? (
|
||||
<LinearSecretField key={`${field.key}:${connectionGeneration}`} field={field} configured={configuredFields.has(field.key)}
|
||||
disabled={busy || dirty || connecting} onSave={saveSecret} />
|
||||
) : <CredentialForm key={field.key} {...formProps} fields={[field]} />)}
|
||||
</div>
|
||||
<div id={advancedPanelId} hidden={!advancedOpen}>
|
||||
<CredentialForm {...formProps} fields={advancedFields} />
|
||||
{installations.some(installation => installation.scopes?.length) ? (
|
||||
<div className="mt-3 space-y-2 rounded-control bg-muted/45 p-3 text-[12px] text-muted-foreground">
|
||||
<p className="font-medium">{tx("custom.workspacesTitle", "Authorized workspaces")}</p>
|
||||
{installations.filter(installation => installation.scopes?.length).map(installation => (
|
||||
<p key={installation.organization_id} className="break-words">
|
||||
{installation.organization_name || installation.organization_id}: {installation.scopes?.join(", ")}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<LinearResetConnection fields={editableFields}
|
||||
disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null
|
||||
|| !(hasSavedSecrets || feature.config_values?.["channels.linear.clientId"] || savedBaseUrl)}
|
||||
onBusyChange={setResetting} onWorkspacesChange={workspaceStore.replace}
|
||||
onWorkspaceRemoved={forgetWorkspaceMembers} onFeaturesUpdate={onFeaturesUpdate}
|
||||
onComplete={() => {
|
||||
setConnectRequestId(0);
|
||||
setConnectionGeneration(value => value + 1);
|
||||
setAdvancedOpen(false);
|
||||
setWorkspaceNotice(null);
|
||||
setWorkspaceError(null);
|
||||
}} />
|
||||
</div>
|
||||
{notice ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5">
|
||||
<p role="alert">{notice}</p>
|
||||
<Button type="submit" variant="secondary" size="sm" disabled={busy || connecting}
|
||||
className="min-h-10 rounded-full text-[12px]">
|
||||
{tx("custom.retrySave", "Retry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</form>
|
||||
{credentialsSaved || installations.length > 0 ? (
|
||||
<section className="mt-5 space-y-3" aria-labelledby="linear-workspaces-heading">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 id="linear-workspaces-heading" className="text-[13px] font-semibold text-foreground">
|
||||
{tx("custom.workspacesTitle", "Authorized workspaces")}
|
||||
</h4>
|
||||
<Button type="button" variant="ghost" size="sm"
|
||||
disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null}
|
||||
className="h-8 gap-2 rounded-full text-[12px] text-muted-foreground"
|
||||
onClick={() => void loadInstallations(true)}>
|
||||
<RefreshCw className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("custom.refreshWorkspaces", "Refresh workspaces")}
|
||||
</Button>
|
||||
</div>
|
||||
<div role="status" aria-live="polite" className="sr-only">
|
||||
{loadingInstallations ? tx("custom.loadingWorkspaces", "Loading workspaces") : ""}
|
||||
</div>
|
||||
{loadingInstallations && !cachedInstallations ? (
|
||||
<p className="px-3 py-2.5 text-[12px] text-muted-foreground">
|
||||
{tx("custom.loadingWorkspaces", "Loading workspaces")}
|
||||
</p>
|
||||
) : null}
|
||||
{!loadingInstallations && !workspaceError && !inspectionError && cachedInstallations?.length === 0 ? (
|
||||
<p className="rounded-control bg-muted/45 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground">
|
||||
{tx("custom.noWorkspaces", "No workspaces are authorized. Connect a workspace to receive Linear agent requests.")}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
{installations.map((installation) => {
|
||||
const name = installation.organization_name || installation.organization_id;
|
||||
const needsAuthorization = installation.authorization_status === "missing_scopes"
|
||||
|| installation.authorization_status === "refresh_required";
|
||||
const authorizationWarning = needsAuthorization ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground">
|
||||
<AlertCircle className="h-3 w-3 shrink-0" aria-hidden />
|
||||
{installation.authorization_status === "missing_scopes"
|
||||
? tx("custom.missingScopes", "Reconnect to grant: {{scopes}}", {
|
||||
scopes: installation.missing_scopes?.join(", ") || "required scopes",
|
||||
})
|
||||
: installation.authorization_status === "refresh_required"
|
||||
? tx("custom.refreshRequired", "Authorization refresh required")
|
||||
: tx("custom.authorized", "Authorized")}
|
||||
</span>
|
||||
) : null;
|
||||
return (
|
||||
<article key={installation.organization_id} aria-label={name}
|
||||
className="overflow-hidden rounded-panel border border-border/70 bg-background">
|
||||
<header className="flex flex-wrap items-center justify-between gap-3 p-4">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2.5">
|
||||
<LinearAvatar name={name} url={logos[installation.organization_id]} workspace />
|
||||
<div className="min-w-0">
|
||||
<h5 className="truncate text-[14px] font-semibold text-foreground" title={name}>{name}</h5>
|
||||
{authorizationWarning ? <div className="mt-1">{authorizationWarning}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon"
|
||||
disabled={workspaceActionsDisabled}
|
||||
onPointerDown={event => { workspaceActionRef.current = event.currentTarget; }}
|
||||
onFocus={event => { workspaceActionRef.current = event.currentTarget; }}
|
||||
aria-label={tx("custom.workspaceActions", "Manage {{name}}", { name })}
|
||||
title={tx("custom.workspaceActions", "Manage {{name}}", { name })}
|
||||
className="h-8 w-8 shrink-0 rounded-full text-muted-foreground">
|
||||
<MoreHorizontal className="h-4 w-4" aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" onCloseAutoFocus={event => {
|
||||
if (skipMenuRestoreFocus.current) event.preventDefault();
|
||||
skipMenuRestoreFocus.current = false;
|
||||
}}>
|
||||
<DropdownMenuItem disabled={workspaceActionsDisabled || !credentialsSaved}
|
||||
onSelect={() => {
|
||||
skipMenuRestoreFocus.current = true;
|
||||
setConnectRequestId(id => id + 1);
|
||||
}}>
|
||||
<RefreshCw className="h-4 w-4" aria-hidden />
|
||||
{tx("custom.reauthorize", "Reauthorize")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem tone="destructive" disabled={workspaceActionsDisabled}
|
||||
onSelect={() => {
|
||||
skipMenuRestoreFocus.current = true;
|
||||
setWorkspaceError(null);
|
||||
setDisconnectConfirmId(installation.organization_id);
|
||||
}}>
|
||||
<Unplug className="h-4 w-4" aria-hidden />
|
||||
{tx("custom.disconnect", "Remove workspace")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</header>
|
||||
<LinearMemberAccess organizationId={installation.organization_id}
|
||||
configScope={memberConfigScope}
|
||||
disabled={busy || dirty || connecting || disconnectingId !== null} />
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{installations.length > 0 ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button type="button" variant="ghost" size="sm"
|
||||
disabled={workspaceActionsDisabled || !credentialsSaved}
|
||||
className="h-9 gap-2 rounded-full text-[12px] text-muted-foreground"
|
||||
onClick={() => setConnectRequestId(id => id + 1)}>
|
||||
<Plus className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("custom.addWorkspace", "Connect workspace")}
|
||||
</Button>
|
||||
<SettingsHint description={tx("custom.addWorkspaceHelp", "Uses the current Linear app. To connect another workspace, the app must allow installation in other workspaces; private apps only work in their own workspace. Authorizing an existing workspace updates its connection without creating a duplicate.")}>
|
||||
<span className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground">
|
||||
<Info className="h-3.5 w-3.5" aria-hidden />
|
||||
<span className="sr-only">{tx("custom.addWorkspaceDetails", "About connecting workspaces")}</span>
|
||||
</span>
|
||||
</SettingsHint>
|
||||
</div>
|
||||
) : null}
|
||||
{(workspaceError && !disconnectTarget) || inspectionError ? (
|
||||
<p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError || inspectionError}</p>
|
||||
) : null}
|
||||
{workspaceNotice ? (
|
||||
<p role="status" className="text-[12px] leading-5 text-muted-foreground">
|
||||
{workspaceNotice}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
<LinearConnectFlow key={connectionGeneration} token={token} feature={feature}
|
||||
connectRequestId={connectRequestId}
|
||||
connected={feature.runtime_status === "running" && installations.length > 0}
|
||||
idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={(payload) => {
|
||||
onFeaturesUpdate(payload);
|
||||
void workspaceStore.load(true);
|
||||
}}
|
||||
onActiveChange={setConnecting}
|
||||
renderActions={(connectButton) => (
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 sm:grid sm:grid-cols-[minmax(0,1fr)_auto_auto]">
|
||||
<div className="me-auto flex min-w-0 max-w-full flex-wrap items-center gap-2">
|
||||
<Button type="button" variant="outline" size="sm"
|
||||
className="h-auto min-h-10 whitespace-normal rounded-full px-4 py-2 text-[12px]"
|
||||
disabled={busy || connecting || !onConfigureMcp}
|
||||
onClick={async () => {
|
||||
if (await saveSettings()) onConfigureMcp?.("linear");
|
||||
}}>
|
||||
{tx("custom.configureTools", "Configure Linear MCP")}
|
||||
</Button>
|
||||
{manifestUrl && !manifestDirty ? (
|
||||
<Button asChild variant="outline" size="sm"
|
||||
className="h-auto min-h-10 max-w-full gap-2 whitespace-normal rounded-full px-4 py-2 text-[12px]">
|
||||
<a href={manifestUrl} target="_blank" rel="noreferrer">
|
||||
{tx("custom.createApp", "Create Linear app")}
|
||||
<ExternalLink className="h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
</a>
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="button" variant="outline" size="sm"
|
||||
disabled={Boolean(fieldValues[PUBLIC_BASE_URL_KEY]?.trim())}
|
||||
onClick={() => setPublicUrlPromptOpen(true)}
|
||||
className="h-auto min-h-10 max-w-full whitespace-normal rounded-full px-4 py-2 text-[12px]">
|
||||
{tx("custom.createApp", "Create Linear app")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{installations.length === 0 || feature.runtime_status !== "running" || connecting ? (
|
||||
<fieldset disabled={busy || dirty || !credentialsSaved || loadingInstallations || disconnectingId !== null}
|
||||
className="min-w-0 sm:col-start-3">
|
||||
<legend className="sr-only">{tx("custom.authorizeTitle", "Authorize in Linear")}</legend>
|
||||
{connectButton}
|
||||
</fieldset>
|
||||
) : null}
|
||||
</div>
|
||||
)} />
|
||||
<AlertDialog open={Boolean(disconnectTarget)} onOpenChange={open => {
|
||||
if (!open && !disconnectingId) {
|
||||
setDisconnectConfirmId(null);
|
||||
setWorkspaceError(null);
|
||||
}
|
||||
}}>
|
||||
<AlertDialogContent onEscapeKeyDown={event => {
|
||||
if (disconnectingId) event.preventDefault();
|
||||
}} onCloseAutoFocus={event => {
|
||||
event.preventDefault();
|
||||
if (workspaceActionRef.current?.isConnected) workspaceActionRef.current.focus();
|
||||
else document.getElementById(channelFieldInputId(PUBLIC_BASE_URL_KEY))?.focus();
|
||||
}}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{tx("custom.disconnectTitle", "Remove {{name}}?", {
|
||||
name: disconnectTarget?.organization_name || disconnectTarget?.organization_id || "",
|
||||
})}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{tx("custom.disconnectDescription", "Revoke this workspace's authorization and clear its member access settings in nanobot. Linear issues, comments, and nanobot conversation history will be kept. Other workspaces are not affected. You can authorize this workspace again later.")}
|
||||
{installations.length === 1 ? <> {tx("custom.disconnectLast", "This is the last connected workspace, so the Linear channel will also be turned off.")}</> : null}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{workspaceError ? <p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError}</p> : null}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={disconnectingId !== null}>
|
||||
{t("settings.actions.cancel", { defaultValue: "Cancel" })}
|
||||
</AlertDialogCancel>
|
||||
<Button type="button" variant="destructive"
|
||||
disabled={workspaceActionsDisabled || !disconnectTarget}
|
||||
onClick={() => { if (disconnectTarget) void disconnectWorkspace(disconnectTarget); }}>
|
||||
{disconnectingId ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}
|
||||
{disconnectingId
|
||||
? tx("custom.disconnecting", "Removing…")
|
||||
: tx("custom.confirmDisconnect", "Remove workspace")}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<AlertDialog open={publicUrlPromptOpen} onOpenChange={setPublicUrlPromptOpen}>
|
||||
<AlertDialogContent onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
document.getElementById(channelFieldInputId(PUBLIC_BASE_URL_KEY))?.focus();
|
||||
}}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{tx("setup.fields.publicBaseUrl.label", "Public HTTPS URL")}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{tx("custom.savePublicUrl", "Enter a public HTTPS URL to create a Linear app.")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>
|
||||
{t("common.close", { defaultValue: "Close" })}
|
||||
</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</aside>
|
||||
);
|
||||
return <LinearPanelView feature={feature} showBrandLogos={showBrandLogos} fields={fields}
|
||||
advancedFields={advancedFields} formProps={formProps}
|
||||
state={{ busy, dirty, saving, saved, connecting, credentialsSaved, connectionGeneration, notice }}
|
||||
workspaces={{ installations: cachedInstallations, logos, loading: loadingInstallations, inspectionError,
|
||||
disconnectingId, notice: workspaceNotice, error: workspaceError }}
|
||||
onSave={saveSettings} onSaveSecret={saveSecret} onRefreshWorkspaces={loadInstallations}
|
||||
onDisconnectWorkspace={disconnectWorkspace} onClearWorkspaceError={() => setWorkspaceError(null)}
|
||||
onRequestConnection={() => setConnectRequestId(id => id + 1)} onConfigureMcp={onConfigureMcp}
|
||||
renderMemberAccess={(organizationId, disabled) => <LinearMemberAccess organizationId={organizationId}
|
||||
configScope={memberConfigScope} disabled={disabled} />}
|
||||
renderResetConnection={({ disabled, onComplete }) => <LinearResetConnection fields={editableFields}
|
||||
disabled={disabled} onBusyChange={setResetting} onWorkspacesChange={workspaceStore.replace}
|
||||
onWorkspaceRemoved={forgetWorkspaceMembers} onFeaturesUpdate={onFeaturesUpdate}
|
||||
onComplete={() => {
|
||||
setConnectRequestId(0);
|
||||
setConnectionGeneration(value => value + 1);
|
||||
setWorkspaceNotice(null);
|
||||
setWorkspaceError(null);
|
||||
onComplete();
|
||||
}} />}
|
||||
renderConnectFlow={(renderActions) => <LinearConnectFlow key={connectionGeneration} token={token} feature={feature}
|
||||
connectRequestId={connectRequestId} connected={feature.runtime_status === "running" && installations.length > 0}
|
||||
idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={(payload) => {
|
||||
onFeaturesUpdate(payload);
|
||||
void workspaceStore.load(true);
|
||||
}} onActiveChange={setConnecting} renderActions={renderActions} />} />;
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
import { useId, useRef, useState, type ComponentProps, type ReactNode } from "react";
|
||||
import { AlertCircle, Check, ChevronDown, ExternalLink, Info, Loader2, MoreHorizontal, Plus, RefreshCw, Unplug } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import type { ChannelPluginPanelProps } from "@/channel-plugins/types";
|
||||
import { CredentialForm, channelFieldInputId, defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";
|
||||
import { CHANNEL_SETUP_PANEL_CLASS_NAME, ChannelLogo, ChannelRuntimeError, localizedChannelDisplayName } from "@/components/settings/channels/ChannelIdentity";
|
||||
import type { ChannelConfigField } from "@/channel-plugins/catalog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import { channelValidationStatusClass } from "@/components/settings/channels/ChannelValidationProgress";
|
||||
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { LinearAvatar } from "./LinearAvatar";
|
||||
import { LinearSecretField } from "./LinearSecretField";
|
||||
import type { LinearInstallationSummary } from "./types";
|
||||
import { linearManifestUrl } from "./manifest";
|
||||
|
||||
const PUBLIC_BASE_URL_KEY = "channels.linear.publicBaseUrl";
|
||||
const WEBHOOK_PATH_KEY = "channels.linear.webhookPath";
|
||||
const CALLBACK_PATH_KEY = "channels.linear.oauthCallbackPath";
|
||||
|
||||
export interface LinearPanelState {
|
||||
busy: boolean;
|
||||
dirty: boolean;
|
||||
saving: boolean;
|
||||
saved: boolean;
|
||||
connecting: boolean;
|
||||
credentialsSaved: boolean;
|
||||
connectionGeneration: number;
|
||||
notice: string | null;
|
||||
}
|
||||
|
||||
export interface LinearPanelWorkspaces {
|
||||
installations: LinearInstallationSummary[] | null;
|
||||
logos: Record<string, string | null>;
|
||||
loading: boolean;
|
||||
inspectionError: string | null;
|
||||
disconnectingId: string | null;
|
||||
notice: string | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface LinearPanelViewProps {
|
||||
feature: ChannelPluginPanelProps["feature"];
|
||||
showBrandLogos: boolean;
|
||||
fields: ChannelConfigField[];
|
||||
advancedFields: ChannelConfigField[];
|
||||
formProps: Omit<ComponentProps<typeof CredentialForm>, "fields">;
|
||||
state: LinearPanelState;
|
||||
workspaces: LinearPanelWorkspaces;
|
||||
onSave: () => Promise<boolean>;
|
||||
onSaveSecret: (key: string, value: string) => Promise<void>;
|
||||
onRefreshWorkspaces: (force?: boolean) => Promise<void>;
|
||||
onDisconnectWorkspace: (installation: LinearInstallationSummary, onRemoved: () => void) => Promise<void>;
|
||||
onClearWorkspaceError: () => void;
|
||||
onRequestConnection: () => void;
|
||||
onConfigureMcp?: ChannelPluginPanelProps["onConfigureMcp"];
|
||||
renderMemberAccess: (organizationId: string, disabled: boolean) => ReactNode;
|
||||
renderResetConnection: (props: { disabled: boolean; onComplete: () => void }) => ReactNode;
|
||||
renderConnectFlow: (renderActions: (connectButton: ReactNode) => ReactNode) => ReactNode;
|
||||
}
|
||||
|
||||
export function LinearPanelView({ feature, showBrandLogos, fields, advancedFields, formProps, state, workspaces,
|
||||
onSave: saveSettings, onSaveSecret: saveSecret, onRefreshWorkspaces: loadInstallations,
|
||||
onDisconnectWorkspace: disconnectWorkspace, onClearWorkspaceError, onRequestConnection, onConfigureMcp,
|
||||
renderMemberAccess, renderResetConnection, renderConnectFlow }: LinearPanelViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "linear");
|
||||
const displayName = localizedChannelDisplayName(feature, t);
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
const [publicUrlPromptOpen, setPublicUrlPromptOpen] = useState(false);
|
||||
const [disconnectConfirmId, setDisconnectConfirmId] = useState<string | null>(null);
|
||||
const workspaceActionRef = useRef<HTMLButtonElement | null>(null);
|
||||
const skipMenuRestoreFocus = useRef(false);
|
||||
const advancedPanelId = useId();
|
||||
const { busy, dirty, saving, saved, connecting, credentialsSaved, connectionGeneration, notice } = state;
|
||||
const { installations: cachedInstallations, logos, loading: loadingInstallations, inspectionError,
|
||||
disconnectingId, notice: workspaceNotice, error: workspaceError } = workspaces;
|
||||
const installations = cachedInstallations ?? [];
|
||||
const disconnectTarget = installations.find(item => item.organization_id === disconnectConfirmId);
|
||||
const configuredFields = formProps.configuredFields ?? new Set<string>();
|
||||
const fieldValues = formProps.values;
|
||||
const hasSavedSecrets = [...fields, ...advancedFields].some(field => field.secret && configuredFields.has(field.key));
|
||||
const workspaceActionsDisabled = busy || dirty || connecting || loadingInstallations || disconnectingId !== null;
|
||||
const savedBaseUrl = feature.config_values?.[PUBLIC_BASE_URL_KEY]?.replace(/\/$/, "");
|
||||
const manifestUrl = savedBaseUrl ? linearManifestUrl(savedBaseUrl,
|
||||
feature.config_values?.[WEBHOOK_PATH_KEY] || "/linear/webhook",
|
||||
feature.config_values?.[CALLBACK_PATH_KEY] || "/linear/oauth/callback") : null;
|
||||
const savedValues = defaultChannelFieldValues([...fields, ...advancedFields], feature.config_values);
|
||||
const manifestDirty = [PUBLIC_BASE_URL_KEY, WEBHOOK_PATH_KEY, CALLBACK_PATH_KEY].some(
|
||||
key => fieldValues[key] !== savedValues[key],
|
||||
);
|
||||
return (
|
||||
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
|
||||
<form className="flex min-w-0 flex-col gap-4" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void saveSettings();
|
||||
}}>
|
||||
<div className="flex min-h-10 flex-wrap items-center justify-between gap-3 pe-20">
|
||||
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
|
||||
<h3 className="sr-only">{displayName}</h3>
|
||||
<span role="status" aria-live="polite" aria-atomic="true"
|
||||
className="min-w-0 flex-1 truncate text-[11px] text-muted-foreground">
|
||||
{saving ? t("settings.actions.saving", { defaultValue: "Saving" })
|
||||
: saved ? t("settings.channels.savedSettings", { defaultValue: "Settings saved." }) : ""}
|
||||
</span>
|
||||
{feature.runtime_status === "running" ? (
|
||||
<span role="status" className={cn(
|
||||
"ms-auto inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[11.5px] font-medium leading-none",
|
||||
channelValidationStatusClass("connected"),
|
||||
)}>
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("custom.channelRunning", "Channel running")}
|
||||
</span>
|
||||
) : null}
|
||||
<button type="button"
|
||||
className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded px-1 text-[12px] leading-none text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
aria-expanded={advancedOpen} aria-controls={advancedPanelId}
|
||||
onClick={() => setAdvancedOpen((current) => !current)}>
|
||||
{t("settings.channels.advanced", { defaultValue: "Advanced" })}
|
||||
<ChevronDown className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
advancedOpen && "rotate-180",
|
||||
)} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
<CredentialForm {...formProps} fields={fields.filter((field) => field.key === PUBLIC_BASE_URL_KEY)} />
|
||||
<div className="grid gap-y-4">
|
||||
{fields.filter(field => field.key !== PUBLIC_BASE_URL_KEY).map(field => field.secret ? (
|
||||
<LinearSecretField key={`${field.key}:${connectionGeneration}`} field={field} configured={configuredFields.has(field.key)}
|
||||
disabled={busy || dirty || connecting} onSave={saveSecret} />
|
||||
) : <CredentialForm key={field.key} {...formProps} fields={[field]} />)}
|
||||
</div>
|
||||
<div id={advancedPanelId} hidden={!advancedOpen}>
|
||||
<CredentialForm {...formProps} fields={advancedFields} />
|
||||
{installations.some(installation => installation.scopes?.length) ? (
|
||||
<div className="mt-3 space-y-2 rounded-control bg-muted/45 p-3 text-[12px] text-muted-foreground">
|
||||
<p className="font-medium">{tx("custom.workspacesTitle", "Authorized workspaces")}</p>
|
||||
{installations.filter(installation => installation.scopes?.length).map(installation => (
|
||||
<p key={installation.organization_id} className="break-words">
|
||||
{installation.organization_name || installation.organization_id}: {installation.scopes?.join(", ")}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{renderResetConnection({
|
||||
disabled: busy || dirty || connecting || loadingInstallations || disconnectingId !== null
|
||||
|| !(hasSavedSecrets || feature.config_values?.["channels.linear.clientId"] || savedBaseUrl),
|
||||
onComplete: () => setAdvancedOpen(false),
|
||||
})}
|
||||
</div>
|
||||
{notice ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5">
|
||||
<p role="alert">{notice}</p>
|
||||
<Button type="submit" variant="secondary" size="sm" disabled={busy || connecting}
|
||||
className="min-h-10 rounded-full text-[12px]">
|
||||
{tx("custom.retrySave", "Retry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</form>
|
||||
{credentialsSaved || installations.length > 0 ? (
|
||||
<section className="mt-5 space-y-3" aria-labelledby="linear-workspaces-heading">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 id="linear-workspaces-heading" className="text-[13px] font-semibold text-foreground">
|
||||
{tx("custom.workspacesTitle", "Authorized workspaces")}
|
||||
</h4>
|
||||
<Button type="button" variant="ghost" size="sm"
|
||||
disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null}
|
||||
className="h-8 gap-2 rounded-full text-[12px] text-muted-foreground"
|
||||
onClick={() => void loadInstallations(true)}>
|
||||
<RefreshCw className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("custom.refreshWorkspaces", "Refresh workspaces")}
|
||||
</Button>
|
||||
</div>
|
||||
<div role="status" aria-live="polite" className="sr-only">
|
||||
{loadingInstallations ? tx("custom.loadingWorkspaces", "Loading workspaces") : ""}
|
||||
</div>
|
||||
{loadingInstallations && !cachedInstallations ? (
|
||||
<p className="px-3 py-2.5 text-[12px] text-muted-foreground">
|
||||
{tx("custom.loadingWorkspaces", "Loading workspaces")}
|
||||
</p>
|
||||
) : null}
|
||||
{!loadingInstallations && !workspaceError && !inspectionError && cachedInstallations?.length === 0 ? (
|
||||
<p className="rounded-control bg-muted/45 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground">
|
||||
{tx("custom.noWorkspaces", "No workspaces are authorized. Connect a workspace to receive Linear agent requests.")}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
{installations.map((installation) => {
|
||||
const name = installation.organization_name || installation.organization_id;
|
||||
const needsAuthorization = installation.authorization_status === "missing_scopes"
|
||||
|| installation.authorization_status === "refresh_required";
|
||||
const authorizationWarning = needsAuthorization ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground">
|
||||
<AlertCircle className="h-3 w-3 shrink-0" aria-hidden />
|
||||
{installation.authorization_status === "missing_scopes"
|
||||
? tx("custom.missingScopes", "Reconnect to grant: {{scopes}}", {
|
||||
scopes: installation.missing_scopes?.join(", ") || "required scopes",
|
||||
})
|
||||
: installation.authorization_status === "refresh_required"
|
||||
? tx("custom.refreshRequired", "Authorization refresh required")
|
||||
: tx("custom.authorized", "Authorized")}
|
||||
</span>
|
||||
) : null;
|
||||
return (
|
||||
<article key={installation.organization_id} aria-label={name}
|
||||
className="overflow-hidden rounded-panel border border-border/70 bg-background">
|
||||
<header className="flex flex-wrap items-center justify-between gap-3 p-4">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2.5">
|
||||
<LinearAvatar name={name} url={logos[installation.organization_id]} workspace />
|
||||
<div className="min-w-0">
|
||||
<h5 className="truncate text-[14px] font-semibold text-foreground" title={name}>{name}</h5>
|
||||
{authorizationWarning ? <div className="mt-1">{authorizationWarning}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon"
|
||||
disabled={workspaceActionsDisabled}
|
||||
onPointerDown={event => { workspaceActionRef.current = event.currentTarget; }}
|
||||
onFocus={event => { workspaceActionRef.current = event.currentTarget; }}
|
||||
aria-label={tx("custom.workspaceActions", "Manage {{name}}", { name })}
|
||||
title={tx("custom.workspaceActions", "Manage {{name}}", { name })}
|
||||
className="h-8 w-8 shrink-0 rounded-full text-muted-foreground">
|
||||
<MoreHorizontal className="h-4 w-4" aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" onCloseAutoFocus={event => {
|
||||
if (skipMenuRestoreFocus.current) event.preventDefault();
|
||||
skipMenuRestoreFocus.current = false;
|
||||
}}>
|
||||
<DropdownMenuItem disabled={workspaceActionsDisabled || !credentialsSaved}
|
||||
onSelect={() => {
|
||||
skipMenuRestoreFocus.current = true;
|
||||
onRequestConnection();
|
||||
}}>
|
||||
<RefreshCw className="h-4 w-4" aria-hidden />
|
||||
{tx("custom.reauthorize", "Reauthorize")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem tone="destructive" disabled={workspaceActionsDisabled}
|
||||
onSelect={() => {
|
||||
skipMenuRestoreFocus.current = true;
|
||||
onClearWorkspaceError();
|
||||
setDisconnectConfirmId(installation.organization_id);
|
||||
}}>
|
||||
<Unplug className="h-4 w-4" aria-hidden />
|
||||
{tx("custom.disconnect", "Remove workspace")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</header>
|
||||
{renderMemberAccess(installation.organization_id,
|
||||
busy || dirty || connecting || disconnectingId !== null)}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{installations.length > 0 ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button type="button" variant="ghost" size="sm"
|
||||
disabled={workspaceActionsDisabled || !credentialsSaved}
|
||||
className="h-9 gap-2 rounded-full text-[12px] text-muted-foreground"
|
||||
onClick={() => onRequestConnection()}>
|
||||
<Plus className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("custom.addWorkspace", "Connect workspace")}
|
||||
</Button>
|
||||
<SettingsHint description={tx("custom.addWorkspaceHelp", "Uses the current Linear app. To connect another workspace, the app must allow installation in other workspaces; private apps only work in their own workspace. Authorizing an existing workspace updates its connection without creating a duplicate.")}>
|
||||
<span className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground">
|
||||
<Info className="h-3.5 w-3.5" aria-hidden />
|
||||
<span className="sr-only">{tx("custom.addWorkspaceDetails", "About connecting workspaces")}</span>
|
||||
</span>
|
||||
</SettingsHint>
|
||||
</div>
|
||||
) : null}
|
||||
{(workspaceError && !disconnectTarget) || inspectionError ? (
|
||||
<p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError || inspectionError}</p>
|
||||
) : null}
|
||||
{workspaceNotice ? (
|
||||
<p role="status" className="text-[12px] leading-5 text-muted-foreground">
|
||||
{workspaceNotice}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
{renderConnectFlow((connectButton) => (
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 sm:grid sm:grid-cols-[minmax(0,1fr)_auto_auto]">
|
||||
<div className="me-auto flex min-w-0 max-w-full flex-wrap items-center gap-2">
|
||||
<Button type="button" variant="outline" size="sm"
|
||||
className="h-auto min-h-10 whitespace-normal rounded-full px-4 py-2 text-[12px]"
|
||||
disabled={busy || connecting || !onConfigureMcp}
|
||||
onClick={async () => {
|
||||
if (await saveSettings()) onConfigureMcp?.("linear");
|
||||
}}>
|
||||
{tx("custom.configureTools", "Configure Linear MCP")}
|
||||
</Button>
|
||||
{manifestUrl && !manifestDirty ? (
|
||||
<Button asChild variant="outline" size="sm"
|
||||
className="h-auto min-h-10 max-w-full gap-2 whitespace-normal rounded-full px-4 py-2 text-[12px]">
|
||||
<a href={manifestUrl} target="_blank" rel="noreferrer">
|
||||
{tx("custom.createApp", "Create Linear app")}
|
||||
<ExternalLink className="h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
</a>
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="button" variant="outline" size="sm"
|
||||
disabled={Boolean(fieldValues[PUBLIC_BASE_URL_KEY]?.trim())}
|
||||
onClick={() => setPublicUrlPromptOpen(true)}
|
||||
className="h-auto min-h-10 max-w-full whitespace-normal rounded-full px-4 py-2 text-[12px]">
|
||||
{tx("custom.createApp", "Create Linear app")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{installations.length === 0 || feature.runtime_status !== "running" || connecting ? (
|
||||
<fieldset disabled={busy || dirty || !credentialsSaved || loadingInstallations || disconnectingId !== null}
|
||||
className="min-w-0 sm:col-start-3">
|
||||
<legend className="sr-only">{tx("custom.authorizeTitle", "Authorize in Linear")}</legend>
|
||||
{connectButton}
|
||||
</fieldset>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
<AlertDialog open={Boolean(disconnectTarget)} onOpenChange={open => {
|
||||
if (!open && !disconnectingId) {
|
||||
setDisconnectConfirmId(null);
|
||||
onClearWorkspaceError();
|
||||
}
|
||||
}}>
|
||||
<AlertDialogContent onEscapeKeyDown={event => {
|
||||
if (disconnectingId) event.preventDefault();
|
||||
}} onCloseAutoFocus={event => {
|
||||
event.preventDefault();
|
||||
if (workspaceActionRef.current?.isConnected) workspaceActionRef.current.focus();
|
||||
else document.getElementById(channelFieldInputId(PUBLIC_BASE_URL_KEY))?.focus();
|
||||
}}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{tx("custom.disconnectTitle", "Remove {{name}}?", {
|
||||
name: disconnectTarget?.organization_name || disconnectTarget?.organization_id || "",
|
||||
})}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{tx("custom.disconnectDescription", "Revoke this workspace's authorization and clear its member access settings in nanobot. Linear issues, comments, and nanobot conversation history will be kept. Other workspaces are not affected. You can authorize this workspace again later.")}
|
||||
{installations.length === 1 ? <> {tx("custom.disconnectLast", "This is the last connected workspace, so the Linear channel will also be turned off.")}</> : null}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{workspaceError ? <p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError}</p> : null}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={disconnectingId !== null}>
|
||||
{t("settings.actions.cancel", { defaultValue: "Cancel" })}
|
||||
</AlertDialogCancel>
|
||||
<Button type="button" variant="destructive"
|
||||
disabled={workspaceActionsDisabled || !disconnectTarget}
|
||||
onClick={() => { if (disconnectTarget) void disconnectWorkspace(disconnectTarget, () => setDisconnectConfirmId(null)); }}>
|
||||
{disconnectingId ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}
|
||||
{disconnectingId
|
||||
? tx("custom.disconnecting", "Removing…")
|
||||
: tx("custom.confirmDisconnect", "Remove workspace")}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<AlertDialog open={publicUrlPromptOpen} onOpenChange={setPublicUrlPromptOpen}>
|
||||
<AlertDialogContent onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
document.getElementById(channelFieldInputId(PUBLIC_BASE_URL_KEY))?.focus();
|
||||
}}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{tx("setup.fields.publicBaseUrl.label", "Public HTTPS URL")}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{tx("custom.savePublicUrl", "Enter a public HTTPS URL to create a Linear app.")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>
|
||||
{t("common.close", { defaultValue: "Close" })}
|
||||
</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -1,21 +1,15 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import type { ChannelConfigField } from "@/channel-plugins/catalog";
|
||||
import { channelFieldInputId, defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription,
|
||||
AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";
|
||||
import { configureChannel, disableNanobotFeature } from "@/lib/api";
|
||||
import type { NanobotFeaturesPayload } from "@/lib/types";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
|
||||
import { manageLinearWorkspace } from "./api";
|
||||
import type { LinearInstallationSummary } from "./types";
|
||||
import { LinearResetConnectionView } from "./LinearResetConnectionView";
|
||||
|
||||
/** Keep credentials until every workspace has been revoked and the channel has stopped. */
|
||||
export function LinearResetConnection({
|
||||
@@ -32,18 +26,8 @@ export function LinearResetConnection({
|
||||
const { client } = useClient();
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "linear");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const inFlight = useRef(false);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const reset = async () => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
setBusy(true);
|
||||
onBusyChange(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Inspect even when the channel is stopped or the display cache is empty/stale.
|
||||
const current = await manageLinearWorkspace(client, { operation: "inspect" });
|
||||
@@ -79,59 +63,10 @@ export function LinearResetConnection({
|
||||
if (!result.saved) throw new Error(tx("custom.resetSaveFailed", "Could not clear the app settings. Please retry."));
|
||||
if (result.nanobot_features) onFeaturesUpdate(result.nanobot_features);
|
||||
onComplete?.();
|
||||
setOpen(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setBusy(false);
|
||||
onBusyChange(false);
|
||||
}
|
||||
};
|
||||
|
||||
return <AlertDialog open={open} onOpenChange={value => {
|
||||
if (inFlight.current) return;
|
||||
setOpen(value);
|
||||
setError(null);
|
||||
}}>
|
||||
<div className="mt-4 border-t border-border/60 pt-3">
|
||||
<Button ref={triggerRef} type="button" variant="ghost" size="sm" disabled={disabled || busy}
|
||||
onClick={() => { setError(null); setOpen(true); }}
|
||||
className="h-8 rounded-full text-[12px] text-muted-foreground hover:text-destructive">
|
||||
{tx("custom.resetConnection", "Reset Linear connection")}
|
||||
</Button>
|
||||
</div>
|
||||
<AlertDialogContent className="max-w-md gap-5" onEscapeKeyDown={event => { if (inFlight.current) event.preventDefault(); }}
|
||||
onCloseAutoFocus={event => {
|
||||
event.preventDefault();
|
||||
if (triggerRef.current && !triggerRef.current.disabled) triggerRef.current.focus();
|
||||
else document.getElementById(channelFieldInputId("channels.linear.publicBaseUrl"))?.focus();
|
||||
}}>
|
||||
<AlertDialogHeader className="space-y-3 text-left">
|
||||
<AlertDialogTitle>{tx("custom.resetTitle", "Reset Linear?")}</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-4 text-sm leading-6">
|
||||
<p>{tx("custom.resetDescription", "Disconnect all workspaces linked through this app and stop the channel.")}</p>
|
||||
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-3 rounded-xl bg-muted/40 p-4 text-[13px] leading-5">
|
||||
<dt className="font-medium text-foreground">{tx("custom.resetClears", "Clears")}</dt>
|
||||
<dd>{tx("custom.resetClearsDetail", "Member access settings and this instance’s app configuration, including saved credentials.")}</dd>
|
||||
<dt className="font-medium text-foreground">{tx("custom.resetKeeps", "Keeps")}</dt>
|
||||
<dd>{tx("custom.resetKeepsDetail", "Linear app, issues, comments, chat history and pairing approvals.")}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{error ? <div role="alert" className="space-y-1 text-[12px] leading-5 text-destructive">
|
||||
<p>{tx("custom.resetIncomplete", "Reset is incomplete. Workspaces already removed stay removed; retry to finish the remaining steps.")}</p>
|
||||
<p>{error}</p>
|
||||
</div> : null}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel className="h-9 min-w-20 rounded-full text-[13px]" disabled={busy}>{t("settings.actions.cancel", { defaultValue: "Cancel" })}</AlertDialogCancel>
|
||||
<Button type="button" variant="destructive" size="sm" className="min-w-20 rounded-full px-4 text-[13px]" disabled={busy} onClick={() => void reset()}>
|
||||
{busy ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}
|
||||
{busy ? tx("custom.resetting", "Resetting…") : tx("custom.resetConfirm", "Reset")}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>;
|
||||
return <LinearResetConnectionView disabled={disabled} onReset={reset} />;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { channelFieldInputId } from "@/components/settings/channels/CredentialForm";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription,
|
||||
AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
|
||||
|
||||
export function LinearResetConnectionView({ disabled, onReset }: {
|
||||
disabled: boolean;
|
||||
onReset: () => Promise<void>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "linear");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const inFlight = useRef(false);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const reset = async () => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await onReset();
|
||||
setOpen(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return <AlertDialog open={open} onOpenChange={value => {
|
||||
if (inFlight.current) return;
|
||||
setOpen(value);
|
||||
setError(null);
|
||||
}}>
|
||||
<div className="mt-4 border-t border-border/60 pt-3">
|
||||
<Button ref={triggerRef} type="button" variant="ghost" size="sm" disabled={disabled || busy}
|
||||
onClick={() => { setError(null); setOpen(true); }}
|
||||
className="h-8 rounded-full text-[12px] text-muted-foreground hover:text-destructive">
|
||||
{tx("custom.resetConnection", "Reset Linear connection")}
|
||||
</Button>
|
||||
</div>
|
||||
<AlertDialogContent className="max-w-md gap-5" onEscapeKeyDown={event => { if (inFlight.current) event.preventDefault(); }}
|
||||
onCloseAutoFocus={event => {
|
||||
event.preventDefault();
|
||||
if (triggerRef.current && !triggerRef.current.disabled) triggerRef.current.focus();
|
||||
else document.getElementById(channelFieldInputId("channels.linear.publicBaseUrl"))?.focus();
|
||||
}}>
|
||||
<AlertDialogHeader className="space-y-3 text-left">
|
||||
<AlertDialogTitle>{tx("custom.resetTitle", "Reset Linear?")}</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-4 text-sm leading-6">
|
||||
<p>{tx("custom.resetDescription", "Disconnect all workspaces linked through this app and stop the channel.")}</p>
|
||||
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-3 rounded-xl bg-muted/40 p-4 text-[13px] leading-5">
|
||||
<dt className="font-medium text-foreground">{tx("custom.resetClears", "Clears")}</dt>
|
||||
<dd>{tx("custom.resetClearsDetail", "Member access settings and this instance’s app configuration, including saved credentials.")}</dd>
|
||||
<dt className="font-medium text-foreground">{tx("custom.resetKeeps", "Keeps")}</dt>
|
||||
<dd>{tx("custom.resetKeepsDetail", "Linear app, issues, comments, chat history and pairing approvals.")}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{error ? <div role="alert" className="space-y-1 text-[12px] leading-5 text-destructive">
|
||||
<p>{tx("custom.resetIncomplete", "Reset is incomplete. Workspaces already removed stay removed; retry to finish the remaining steps.")}</p>
|
||||
<p>{error}</p>
|
||||
</div> : null}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel className="h-9 min-w-20 rounded-full text-[13px]" disabled={busy}>{t("settings.actions.cancel", { defaultValue: "Cancel" })}</AlertDialogCancel>
|
||||
<Button type="button" variant="destructive" size="sm" className="min-w-20 rounded-full px-4 text-[13px]" disabled={busy} onClick={() => void reset()}>
|
||||
{busy ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}
|
||||
{busy ? tx("custom.resetting", "Resetting…") : tx("custom.resetConfirm", "Reset")}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>;
|
||||
}
|
||||
@@ -1,70 +1,12 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
channelTranslator,
|
||||
type ChannelTranslator,
|
||||
} from "@/channel-plugins/i18n";
|
||||
import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";
|
||||
import {
|
||||
ChannelQrConnectFlow,
|
||||
type ChannelQrConnectPendingContext,
|
||||
} from "@/components/settings/channels/ChannelQrConnectFlow";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ChannelConnectPayload } from "@/lib/types";
|
||||
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
|
||||
|
||||
type WeixinVerificationPayload = ChannelConnectPayload & {
|
||||
challenge: "verify_code";
|
||||
verification_failed?: boolean;
|
||||
};
|
||||
import { WeixinConnectFlowView, weixinConnectLabels } from "./WeixinConnectFlowView";
|
||||
import { isVerificationChallenge, WEIXIN_AUTH_EXPIRED_MESSAGE } from "./presentation";
|
||||
|
||||
export const WEIXIN_AUTH_EXPIRED_MESSAGE =
|
||||
"WeChat login expired. Scan again to reconnect.";
|
||||
|
||||
function isVerificationChallenge(
|
||||
payload: ChannelConnectPayload,
|
||||
): payload is WeixinVerificationPayload {
|
||||
return (
|
||||
"challenge" in payload
|
||||
&& payload.challenge === "verify_code"
|
||||
&& (
|
||||
!("verification_failed" in payload)
|
||||
|| typeof payload.verification_failed === "boolean"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function weixinConnectMessage(
|
||||
payload: ChannelConnectPayload,
|
||||
tx: ChannelTranslator,
|
||||
): string {
|
||||
if (payload.status === "succeeded") {
|
||||
return tx("custom.connected", "WeChat is connected.");
|
||||
}
|
||||
if (payload.status === "expired") {
|
||||
return tx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE);
|
||||
}
|
||||
if (payload.status === "failed") {
|
||||
return payload.message
|
||||
?? tx("custom.failed", "Unable to connect WeChat. Try again.");
|
||||
}
|
||||
if (payload.status === "cancelled") {
|
||||
return tx("custom.stopped", "WeChat login stopped.");
|
||||
}
|
||||
if (isVerificationChallenge(payload)) {
|
||||
return payload.verification_failed
|
||||
? tx(
|
||||
"custom.verifyMismatch",
|
||||
"That code did not match. Enter the new number shown in WeChat.",
|
||||
)
|
||||
: tx(
|
||||
"custom.verifyDescription",
|
||||
"Enter the number shown in WeChat to continue.",
|
||||
);
|
||||
}
|
||||
return tx("custom.waiting", "Waiting for WeChat scan...");
|
||||
}
|
||||
export { WEIXIN_AUTH_EXPIRED_MESSAGE } from "./presentation";
|
||||
|
||||
export function WeixinConnectFlow({
|
||||
token,
|
||||
@@ -75,8 +17,6 @@ export function WeixinConnectFlow({
|
||||
onFeaturesUpdate,
|
||||
}: ChannelPluginConnectFlowProps & { authRecoveryActive?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "weixin");
|
||||
const [verificationCode, setVerificationCode] = useState("");
|
||||
const authExpired = authRecoveryActive
|
||||
|| feature.runtime_error === WEIXIN_AUTH_EXPIRED_MESSAGE;
|
||||
const scanAgainLabel = t("settings.channels.scanAgain", {
|
||||
@@ -85,55 +25,6 @@ export function WeixinConnectFlow({
|
||||
|
||||
if (feature.configured && !authExpired) return null;
|
||||
|
||||
const renderVerification = ({
|
||||
connect,
|
||||
busy,
|
||||
poll,
|
||||
}: ChannelQrConnectPendingContext) => {
|
||||
if (!isVerificationChallenge(connect)) return null;
|
||||
return (
|
||||
<form
|
||||
className="mt-3 space-y-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const code = verificationCode.trim();
|
||||
if (!code) return;
|
||||
void poll({ verify_code: code }).then((payload) => {
|
||||
if (payload && !isVerificationChallenge(payload)) {
|
||||
setVerificationCode("");
|
||||
}
|
||||
});
|
||||
}}
|
||||
>
|
||||
<div className="text-[12px] font-semibold text-foreground">
|
||||
{tx("custom.verifyTitle", "Verification required")}
|
||||
</div>
|
||||
<p className="text-[12px] leading-5 text-muted-foreground">
|
||||
{weixinConnectMessage(connect, tx)}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={verificationCode}
|
||||
onChange={(event) => setVerificationCode(event.target.value)}
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder={tx("custom.verifyPlaceholder", "Code")}
|
||||
className="h-8 max-w-40"
|
||||
aria-invalid={connect.verification_failed || undefined}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
disabled={busy || !verificationCode.trim()}
|
||||
>
|
||||
{tx("custom.verifySubmit", "Verify")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<ChannelQrConnectFlow
|
||||
token={token}
|
||||
@@ -147,19 +38,8 @@ export function WeixinConnectFlow({
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
pausePolling={isVerificationChallenge}
|
||||
suppressSucceeded={feature.runtime_status === "failed"}
|
||||
renderPending={renderVerification}
|
||||
resolveMessage={(payload) => weixinConnectMessage(payload, tx)}
|
||||
labels={{
|
||||
qrAlt: tx("custom.qrAlt", "WeChat login QR code"),
|
||||
scanTitle: tx("custom.scanTitle", "Scan with WeChat"),
|
||||
scanDescription: "",
|
||||
waiting: tx("custom.waiting", "Waiting for WeChat scan..."),
|
||||
connected: tx("custom.connected", "WeChat is connected."),
|
||||
stopped: tx("custom.stopped", "WeChat login stopped."),
|
||||
connecting: tx("custom.connecting", "Connecting..."),
|
||||
scanAgain: scanAgainLabel,
|
||||
connect: t("settings.channels.connect", { defaultValue: "Connect" }),
|
||||
}}
|
||||
labels={weixinConnectLabels(t)}
|
||||
renderView={(props) => <WeixinConnectFlowView {...props} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useId, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator, type ChannelTranslator } from "@/channel-plugins/i18n";
|
||||
import {
|
||||
ChannelQrConnectFlowView,
|
||||
type ChannelQrConnectFlowViewProps,
|
||||
type ChannelQrConnectLabels,
|
||||
type ChannelQrConnectPendingContext,
|
||||
} from "@/components/settings/channels/ChannelQrConnectFlowView";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ChannelConnectPayload } from "@/lib/types";
|
||||
|
||||
import { isVerificationChallenge, WEIXIN_AUTH_EXPIRED_MESSAGE } from "./presentation";
|
||||
|
||||
function weixinConnectMessage(
|
||||
payload: ChannelConnectPayload,
|
||||
tx: ChannelTranslator,
|
||||
): string {
|
||||
if (payload.status === "succeeded") {
|
||||
return tx("custom.connected", "WeChat is connected.");
|
||||
}
|
||||
if (payload.status === "expired") {
|
||||
return tx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE);
|
||||
}
|
||||
if (payload.status === "failed") {
|
||||
return payload.message
|
||||
?? tx("custom.failed", "Unable to connect WeChat. Try again.");
|
||||
}
|
||||
if (payload.status === "cancelled") {
|
||||
return tx("custom.stopped", "WeChat login stopped.");
|
||||
}
|
||||
if (isVerificationChallenge(payload)) {
|
||||
return payload.verification_failed
|
||||
? tx(
|
||||
"custom.verifyMismatch",
|
||||
"That code did not match. Enter the new number shown in WeChat.",
|
||||
)
|
||||
: tx(
|
||||
"custom.verifyDescription",
|
||||
"Enter the number shown in WeChat to continue.",
|
||||
);
|
||||
}
|
||||
return tx("custom.waiting", "Waiting for WeChat scan...");
|
||||
}
|
||||
|
||||
export function weixinConnectLabels(t: Parameters<typeof channelTranslator>[0]): ChannelQrConnectLabels {
|
||||
const tx = channelTranslator(t, "weixin");
|
||||
return {
|
||||
qrAlt: tx("custom.qrAlt", "WeChat login QR code"),
|
||||
scanTitle: tx("custom.scanTitle", "Scan with WeChat"),
|
||||
scanDescription: "",
|
||||
waiting: tx("custom.waiting", "Waiting for WeChat scan..."),
|
||||
connected: tx("custom.connected", "WeChat is connected."),
|
||||
stopped: tx("custom.stopped", "WeChat login stopped."),
|
||||
connecting: tx("custom.connecting", "Connecting..."),
|
||||
scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }),
|
||||
connect: t("settings.channels.connect", { defaultValue: "Connect" }),
|
||||
};
|
||||
}
|
||||
|
||||
export type WeixinConnectFlowViewProps = Omit<
|
||||
ChannelQrConnectFlowViewProps, "labels" | "renderPending" | "resolveMessage"
|
||||
>;
|
||||
|
||||
export function WeixinConnectFlowView(props: WeixinConnectFlowViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "weixin");
|
||||
const [verificationCode, setVerificationCode] = useState("");
|
||||
const verificationTitleId = useId();
|
||||
const verificationMessageId = useId();
|
||||
|
||||
const renderVerification = ({
|
||||
connect,
|
||||
busy,
|
||||
poll,
|
||||
}: ChannelQrConnectPendingContext) => {
|
||||
if (!isVerificationChallenge(connect)) return null;
|
||||
return (
|
||||
<form
|
||||
className="mt-3 space-y-2"
|
||||
aria-labelledby={verificationTitleId}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const code = verificationCode.trim();
|
||||
if (!code) return;
|
||||
void poll({ verify_code: code }).then((payload) => {
|
||||
if (payload && !isVerificationChallenge(payload)) {
|
||||
setVerificationCode("");
|
||||
}
|
||||
});
|
||||
}}
|
||||
>
|
||||
<div id={verificationTitleId} className="text-[12px] font-semibold text-foreground">
|
||||
{tx("custom.verifyTitle", "Verification required")}
|
||||
</div>
|
||||
<p id={verificationMessageId} role={connect.verification_failed ? "alert" : undefined} className="text-[12px] leading-5 text-muted-foreground">
|
||||
{weixinConnectMessage(connect, tx)}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={verificationCode}
|
||||
onChange={(event) => setVerificationCode(event.target.value)}
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder={tx("custom.verifyPlaceholder", "Code")}
|
||||
aria-label={tx("custom.verifyPlaceholder", "Code")}
|
||||
aria-describedby={verificationMessageId}
|
||||
className="h-8 max-w-40"
|
||||
aria-invalid={connect.verification_failed || undefined}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
disabled={busy || !verificationCode.trim()}
|
||||
>
|
||||
{tx("custom.verifySubmit", "Verify")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
return <ChannelQrConnectFlowView
|
||||
{...props}
|
||||
labels={weixinConnectLabels(t)}
|
||||
renderPending={renderVerification}
|
||||
resolveMessage={(payload) => weixinConnectMessage(payload, tx)}
|
||||
/>;
|
||||
}
|
||||
@@ -1,41 +1,22 @@
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
||||
import { Check, ChevronDown, Loader2, Plus } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelFieldMessageKey, channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { channelLocaleMessages } from "@/channel-plugins/locale-registry";
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import type { ChannelPluginPanelProps } from "@/channel-plugins/types";
|
||||
import {
|
||||
type ChannelConfigField,
|
||||
} from "@/channel-plugins/catalog";
|
||||
import {
|
||||
CredentialForm,
|
||||
channelValuesForSave,
|
||||
defaultChannelFieldValues,
|
||||
} from "@/components/settings/channels/CredentialForm";
|
||||
import {
|
||||
CHANNEL_SETUP_PANEL_CLASS_NAME,
|
||||
ChannelLogo,
|
||||
} from "@/components/settings/channels/ChannelIdentity";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DisclosureContent } from "@/components/ui/disclosure";
|
||||
import { normalizeLocale } from "@/i18n/config";
|
||||
import { configureChannel } from "@/lib/api";
|
||||
import type {
|
||||
ChannelSetupContractField,
|
||||
NanobotFeatureInfo,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
|
||||
import { WeixinConnectFlow } from "./WeixinConnectFlow";
|
||||
import { WeixinPanelView } from "./WeixinPanelView";
|
||||
import {
|
||||
WEIXIN_AUTH_EXPIRED_MESSAGE,
|
||||
WeixinConnectFlow,
|
||||
} from "./WeixinConnectFlow";
|
||||
import {
|
||||
WEIXIN_ADVANCED_FIELD_KEYS,
|
||||
WEIXIN_PRIMARY_FIELD_KEYS,
|
||||
WEIXIN_QR_TOKEN_FIELD_KEY,
|
||||
localizeBooleanFields,
|
||||
weixinRuntimeError,
|
||||
weixinSetupFields,
|
||||
} from "./presentation";
|
||||
|
||||
export function WeixinPanel({
|
||||
@@ -55,12 +36,6 @@ export function WeixinPanel({
|
||||
const [authRecoveryActive, setAuthRecoveryActive] = useState(authExpired);
|
||||
const runtimeError = weixinRuntimeError(feature.runtime_error, channelTx)
|
||||
?? (authRecoveryActive ? channelTx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE) : undefined);
|
||||
const displayName = channelTx("displayName", "WeChat");
|
||||
const enabledBusy = actionKey === `enable:${feature.name}`;
|
||||
const missingSupport = feature.enabled && !feature.installed;
|
||||
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
const advancedPanelId = useId();
|
||||
const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveRevision, setSaveRevision] = useState(0);
|
||||
@@ -115,7 +90,6 @@ export function WeixinPanel({
|
||||
}
|
||||
fieldValuesRef.current = nextValues;
|
||||
setFieldValues(nextValues);
|
||||
setVisibleSecrets({});
|
||||
}, [configValuesKey, setupFieldsKey]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -192,213 +166,29 @@ export function WeixinPanel({
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">
|
||||
<div className="flex min-w-0 max-w-full items-center gap-3">
|
||||
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
|
||||
<h3 className="sr-only">{displayName}</h3>
|
||||
{missingSupport && feature.install_supported ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
disabled={enabledBusy}
|
||||
onClick={() => onAction("enable", feature.name)}
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
>
|
||||
{enabledBusy ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : (
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
)}
|
||||
{tx("settings.nanobotFeatures.installSupport", "Install support")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{advancedFields.length ? (
|
||||
<button
|
||||
type="button"
|
||||
className="ms-auto 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>
|
||||
|
||||
{runtimeError ? (
|
||||
<div className="mt-4 rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{runtimeError}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-4 space-y-4">
|
||||
<WeixinConnectFlow
|
||||
token={token}
|
||||
feature={feature}
|
||||
authRecoveryActive={authRecoveryActive}
|
||||
idleLabel={channelTx("setup.primaryAction", "Connect WeChat")}
|
||||
connectRequestId={connectRequestId}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
/>
|
||||
|
||||
{primaryFields.length ? (
|
||||
<CredentialForm
|
||||
fields={primaryFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onToggleSecret={(key) => {
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));
|
||||
}}
|
||||
compact
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
className={cn(
|
||||
"flex items-center justify-end gap-1.5 text-[11px] leading-4 text-muted-foreground",
|
||||
!saving && saveState !== "saved" && "sr-only",
|
||||
)}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden />
|
||||
{tx("settings.actions.saving", "Saving")}
|
||||
</>
|
||||
) : saveState === "saved" ? (
|
||||
<>
|
||||
<Check className="h-3 w-3" aria-hidden />
|
||||
{tx("settings.channels.savedSettings", "Saved settings.")}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{saveError ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive"
|
||||
>
|
||||
{saveError}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{advancedFields.length ? (
|
||||
<DisclosureContent id={advancedPanelId} open={advancedOpen} className="text-[12px] leading-5 text-muted-foreground">
|
||||
<CredentialForm
|
||||
fields={advancedFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onToggleSecret={(key) => {
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));
|
||||
}}
|
||||
compact
|
||||
/>
|
||||
</DisclosureContent>
|
||||
) : null}
|
||||
|
||||
</div>
|
||||
</aside>
|
||||
<WeixinPanelView
|
||||
feature={feature}
|
||||
actionKey={actionKey}
|
||||
showBrandLogos={showBrandLogos}
|
||||
primaryFields={primaryFields}
|
||||
advancedFields={advancedFields}
|
||||
fieldValues={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
secretVisibilityKey={`${configValuesKey}:${setupFieldsKey}`}
|
||||
runtimeError={runtimeError}
|
||||
saving={saving}
|
||||
saveState={saveState}
|
||||
saveError={saveError}
|
||||
connectFlow={<WeixinConnectFlow
|
||||
token={token}
|
||||
feature={feature}
|
||||
authRecoveryActive={authRecoveryActive}
|
||||
idleLabel={channelTx("setup.primaryAction", "Connect WeChat")}
|
||||
connectRequestId={connectRequestId}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
/>}
|
||||
onInstall={() => onAction("enable", feature.name)}
|
||||
onFieldChange={setFieldValue}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function weixinSetupFields(
|
||||
feature: NanobotFeatureInfo,
|
||||
locale: string,
|
||||
): { primary: ChannelConfigField[]; advanced: ChannelConfigField[] } {
|
||||
const fields = (feature.setup?.fields ?? []).filter(
|
||||
(field) => field.key !== WEIXIN_QR_TOKEN_FIELD_KEY,
|
||||
);
|
||||
const fieldsByKey = new Map(fields.map((field) => [field.key, field]));
|
||||
const messages = channelLocaleMessages("weixin", normalizeLocale(locale))?.setup;
|
||||
const knownKeys = new Set<string>([
|
||||
...WEIXIN_PRIMARY_FIELD_KEYS,
|
||||
...WEIXIN_ADVANCED_FIELD_KEYS,
|
||||
]);
|
||||
const extraKeys = fields
|
||||
.map((field) => field.key)
|
||||
.filter((key) => !knownKeys.has(key));
|
||||
const hydrate = (keys: readonly string[]) => keys.flatMap((key) => {
|
||||
const field = fieldsByKey.get(key);
|
||||
if (!field) return [];
|
||||
const copy = messages?.fields?.[channelFieldMessageKey("weixin", key)];
|
||||
return [weixinConfigField(field, copy)];
|
||||
});
|
||||
|
||||
return {
|
||||
primary: hydrate(WEIXIN_PRIMARY_FIELD_KEYS),
|
||||
advanced: hydrate([...WEIXIN_ADVANCED_FIELD_KEYS, ...extraKeys]),
|
||||
};
|
||||
}
|
||||
|
||||
function weixinConfigField(
|
||||
field: ChannelSetupContractField,
|
||||
copy: { label: string; placeholder?: string; choices?: Record<string, string> }
|
||||
| undefined,
|
||||
): ChannelConfigField {
|
||||
const choices = field.kind === "bool" ? ["true", "false"] : field.choices;
|
||||
return {
|
||||
key: field.key,
|
||||
label: copy?.label ?? fieldLabel(field.field),
|
||||
placeholder: copy?.placeholder,
|
||||
secret: field.kind === "secret",
|
||||
optional: !field.required,
|
||||
inputType: field.kind === "int" ? "number" : undefined,
|
||||
defaultValue: field.default_value,
|
||||
options:
|
||||
field.kind === "enum" || field.kind === "bool"
|
||||
? choices.map((choice) => ({
|
||||
value: choice,
|
||||
label: copy?.choices?.[choice] ?? fieldLabel(choice),
|
||||
}))
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function fieldLabel(value: string): string {
|
||||
const spaced = value
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.replace(/[_-]+/g, " ")
|
||||
.trim();
|
||||
return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : value;
|
||||
}
|
||||
|
||||
function weixinRuntimeError(
|
||||
error: string | undefined,
|
||||
tx: (key: string, fallback: string) => string,
|
||||
): string | undefined {
|
||||
if (error === WEIXIN_AUTH_EXPIRED_MESSAGE) {
|
||||
return tx("custom.expired", error);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
function localizeBooleanFields(
|
||||
fields: ChannelConfigField[],
|
||||
onLabel: string,
|
||||
offLabel: string,
|
||||
): ChannelConfigField[] {
|
||||
return fields.map((field) => {
|
||||
const values = new Set(field.options?.map((option) => option.value));
|
||||
if (values.size !== 2 || !values.has("true") || !values.has("false")) return field;
|
||||
return {
|
||||
...field,
|
||||
options: field.options?.map((option) => ({
|
||||
...option,
|
||||
label: option.value === "true" ? onLabel : offLabel,
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { useEffect, useId, useState, type ReactNode } from "react";
|
||||
import { Check, ChevronDown, Loader2, Plus } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import type { ChannelConfigField } from "@/channel-plugins/catalog";
|
||||
import { CredentialForm } from "@/components/settings/channels/CredentialForm";
|
||||
import { CHANNEL_SETUP_PANEL_CLASS_NAME, ChannelLogo } from "@/components/settings/channels/ChannelIdentity";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DisclosureContent } from "@/components/ui/disclosure";
|
||||
import type { NanobotFeatureInfo } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type WeixinPanelViewProps = {
|
||||
feature: NanobotFeatureInfo;
|
||||
actionKey: string | null;
|
||||
showBrandLogos: boolean;
|
||||
primaryFields: ChannelConfigField[];
|
||||
advancedFields: ChannelConfigField[];
|
||||
fieldValues: Record<string, string>;
|
||||
configuredFields: Set<string>;
|
||||
secretVisibilityKey: string;
|
||||
runtimeError?: string;
|
||||
saving: boolean;
|
||||
saveState: "idle" | "saved";
|
||||
saveError: string | null;
|
||||
connectFlow: ReactNode;
|
||||
onInstall: () => void;
|
||||
onFieldChange: (key: string, value: string) => void;
|
||||
};
|
||||
|
||||
export function WeixinPanelView({
|
||||
feature, actionKey, showBrandLogos, primaryFields, advancedFields, fieldValues,
|
||||
configuredFields, secretVisibilityKey, runtimeError, saving, saveState, saveError,
|
||||
connectFlow, onInstall, onFieldChange,
|
||||
}: WeixinPanelViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const channelTx = channelTranslator(t, "weixin");
|
||||
const displayName = channelTx("displayName", "WeChat");
|
||||
const enabledBusy = actionKey === `enable:${feature.name}`;
|
||||
const missingSupport = feature.enabled && !feature.installed;
|
||||
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
const advancedPanelId = useId();
|
||||
useEffect(() => setVisibleSecrets({}), [secretVisibilityKey]);
|
||||
|
||||
return (
|
||||
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">
|
||||
<div className="flex min-w-0 max-w-full items-center gap-3">
|
||||
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
|
||||
<h3 className="sr-only">{displayName}</h3>
|
||||
{missingSupport && feature.install_supported ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
disabled={enabledBusy}
|
||||
onClick={onInstall}
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
>
|
||||
{enabledBusy ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : (
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
)}
|
||||
{tx("settings.nanobotFeatures.installSupport", "Install support")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{advancedFields.length ? (
|
||||
<button
|
||||
type="button"
|
||||
className="ms-auto 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>
|
||||
|
||||
{runtimeError ? (
|
||||
<div role="alert" className="mt-4 rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{runtimeError}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-4 space-y-4">
|
||||
{connectFlow}
|
||||
|
||||
{primaryFields.length ? (
|
||||
<CredentialForm
|
||||
fields={primaryFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={onFieldChange}
|
||||
onToggleSecret={(key) => {
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));
|
||||
}}
|
||||
compact
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
className={cn(
|
||||
"flex items-center justify-end gap-1.5 text-[11px] leading-4 text-muted-foreground",
|
||||
!saving && saveState !== "saved" && "sr-only",
|
||||
)}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden />
|
||||
{tx("settings.actions.saving", "Saving")}
|
||||
</>
|
||||
) : saveState === "saved" ? (
|
||||
<>
|
||||
<Check className="h-3 w-3" aria-hidden />
|
||||
{tx("settings.channels.savedSettings", "Saved settings.")}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{saveError ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive"
|
||||
>
|
||||
{saveError}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{advancedFields.length ? (
|
||||
<DisclosureContent id={advancedPanelId} open={advancedOpen} className="text-[12px] leading-5 text-muted-foreground">
|
||||
<CredentialForm
|
||||
fields={advancedFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={onFieldChange}
|
||||
onToggleSecret={(key) => {
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));
|
||||
}}
|
||||
compact
|
||||
/>
|
||||
</DisclosureContent>
|
||||
) : null}
|
||||
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,30 @@
|
||||
import { channelFieldMessageKey } from "@/channel-plugins/i18n";
|
||||
import { channelLocaleMessages } from "@/channel-plugins/locale-registry";
|
||||
import type { ChannelConfigField } from "@/channel-plugins/catalog";
|
||||
import { normalizeLocale } from "@/i18n/config";
|
||||
import type { ChannelConnectPayload, ChannelSetupContractField, NanobotFeatureInfo } from "@/lib/types";
|
||||
|
||||
export const WEIXIN_AUTH_EXPIRED_MESSAGE =
|
||||
"WeChat login expired. Scan again to reconnect.";
|
||||
|
||||
export type WeixinVerificationPayload = ChannelConnectPayload & {
|
||||
challenge: "verify_code";
|
||||
verification_failed?: boolean;
|
||||
};
|
||||
|
||||
export function isVerificationChallenge(
|
||||
payload: ChannelConnectPayload,
|
||||
): payload is WeixinVerificationPayload {
|
||||
return (
|
||||
"challenge" in payload
|
||||
&& payload.challenge === "verify_code"
|
||||
&& (
|
||||
!("verification_failed" in payload)
|
||||
|| typeof payload.verification_failed === "boolean"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export const WEIXIN_PRIMARY_FIELD_KEYS = [
|
||||
"channels.weixin.sendProgress",
|
||||
"channels.weixin.sendToolHints",
|
||||
@@ -20,3 +47,92 @@ export const WEIXIN_ADVANCED_FIELD_KEYS = [
|
||||
"channels.weixin.stateDir",
|
||||
"channels.weixin.pollTimeout",
|
||||
] as const;
|
||||
|
||||
export function weixinSetupFields(
|
||||
feature: NanobotFeatureInfo,
|
||||
locale: string,
|
||||
): { primary: ChannelConfigField[]; advanced: ChannelConfigField[] } {
|
||||
const fields = (feature.setup?.fields ?? []).filter(
|
||||
(field) => field.key !== WEIXIN_QR_TOKEN_FIELD_KEY,
|
||||
);
|
||||
const fieldsByKey = new Map(fields.map((field) => [field.key, field]));
|
||||
const messages = channelLocaleMessages("weixin", normalizeLocale(locale))?.setup;
|
||||
const knownKeys = new Set<string>([
|
||||
...WEIXIN_PRIMARY_FIELD_KEYS,
|
||||
...WEIXIN_ADVANCED_FIELD_KEYS,
|
||||
]);
|
||||
const extraKeys = fields
|
||||
.map((field) => field.key)
|
||||
.filter((key) => !knownKeys.has(key));
|
||||
const hydrate = (keys: readonly string[]) => keys.flatMap((key) => {
|
||||
const field = fieldsByKey.get(key);
|
||||
if (!field) return [];
|
||||
const copy = messages?.fields?.[channelFieldMessageKey("weixin", key)];
|
||||
return [weixinConfigField(field, copy)];
|
||||
});
|
||||
|
||||
return {
|
||||
primary: hydrate(WEIXIN_PRIMARY_FIELD_KEYS),
|
||||
advanced: hydrate([...WEIXIN_ADVANCED_FIELD_KEYS, ...extraKeys]),
|
||||
};
|
||||
}
|
||||
|
||||
function weixinConfigField(
|
||||
field: ChannelSetupContractField,
|
||||
copy: { label: string; placeholder?: string; choices?: Record<string, string> }
|
||||
| undefined,
|
||||
): ChannelConfigField {
|
||||
const choices = field.kind === "bool" ? ["true", "false"] : field.choices;
|
||||
return {
|
||||
key: field.key,
|
||||
label: copy?.label ?? fieldLabel(field.field),
|
||||
placeholder: copy?.placeholder,
|
||||
secret: field.kind === "secret",
|
||||
optional: !field.required,
|
||||
inputType: field.kind === "int" ? "number" : undefined,
|
||||
defaultValue: field.default_value,
|
||||
options:
|
||||
field.kind === "enum" || field.kind === "bool"
|
||||
? choices.map((choice) => ({
|
||||
value: choice,
|
||||
label: copy?.choices?.[choice] ?? fieldLabel(choice),
|
||||
}))
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function fieldLabel(value: string): string {
|
||||
const spaced = value
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.replace(/[_-]+/g, " ")
|
||||
.trim();
|
||||
return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : value;
|
||||
}
|
||||
|
||||
export function weixinRuntimeError(
|
||||
error: string | undefined,
|
||||
tx: (key: string, fallback: string) => string,
|
||||
): string | undefined {
|
||||
if (error === WEIXIN_AUTH_EXPIRED_MESSAGE) {
|
||||
return tx("custom.expired", error);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
export function localizeBooleanFields(
|
||||
fields: ChannelConfigField[],
|
||||
onLabel: string,
|
||||
offLabel: string,
|
||||
): ChannelConfigField[] {
|
||||
return fields.map((field) => {
|
||||
const values = new Set(field.options?.map((option) => option.value));
|
||||
if (values.size !== 2 || !values.has("true") || !values.has("false")) return field;
|
||||
return {
|
||||
...field,
|
||||
options: field.options?.map((option) => ({
|
||||
...option,
|
||||
label: option.value === "true" ? onLabel : offLabel,
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1,17 +1,15 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";
|
||||
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
|
||||
|
||||
import { WhatsAppConnectFlowView, useWhatsAppConnectLabels } from "./WhatsAppConnectFlowView";
|
||||
|
||||
export function WhatsAppConnectFlow({
|
||||
token,
|
||||
idleLabel,
|
||||
connectRequestId,
|
||||
onFeaturesUpdate,
|
||||
}: ChannelPluginConnectFlowProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "whatsapp");
|
||||
const labels = useWhatsAppConnectLabels();
|
||||
|
||||
return (
|
||||
<ChannelQrConnectFlow
|
||||
@@ -22,23 +20,8 @@ export function WhatsAppConnectFlow({
|
||||
autoStart
|
||||
minimalPending
|
||||
forceOnRepeat
|
||||
labels={{
|
||||
qrAlt: tx("custom.qrAlt", "WhatsApp linking QR code"),
|
||||
scanTitle: tx("custom.scanTitle", "Link WhatsApp"),
|
||||
scanDescription: tx(
|
||||
"custom.scanDescription",
|
||||
"In WhatsApp, open Linked devices, choose Link a device, then scan this code.",
|
||||
),
|
||||
waiting: tx("custom.waiting", "Waiting for WhatsApp…"),
|
||||
connected: tx("custom.connected", "WhatsApp is connected."),
|
||||
stopped: tx(
|
||||
"custom.stopped",
|
||||
"The WhatsApp connection attempt stopped. Start again to get a new code.",
|
||||
),
|
||||
connecting: tx("custom.connecting", "Connecting…"),
|
||||
scanAgain: tx("custom.scanAgain", "Link another account"),
|
||||
connect: tx("custom.connect", "Link WhatsApp"),
|
||||
}}
|
||||
labels={labels}
|
||||
renderView={(props) => <WhatsAppConnectFlowView {...props} />}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { ChannelQrConnectFlowView, type ChannelQrConnectFlowViewProps, type ChannelQrConnectLabels } from "@/components/settings/channels/ChannelQrConnectFlowView";
|
||||
|
||||
export type WhatsAppConnectFlowViewProps = Omit<ChannelQrConnectFlowViewProps, "labels" | "autoStart" | "minimalPending">;
|
||||
|
||||
export function useWhatsAppConnectLabels(): ChannelQrConnectLabels {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "whatsapp");
|
||||
return {
|
||||
qrAlt: tx("custom.qrAlt", "WhatsApp linking QR code"),
|
||||
scanTitle: tx("custom.scanTitle", "Link WhatsApp"),
|
||||
scanDescription: tx(
|
||||
"custom.scanDescription",
|
||||
"In WhatsApp, open Linked devices, choose Link a device, then scan this code.",
|
||||
),
|
||||
waiting: tx("custom.waiting", "Waiting for WhatsApp…"),
|
||||
connected: tx("custom.connected", "WhatsApp is connected."),
|
||||
stopped: tx(
|
||||
"custom.stopped",
|
||||
"The WhatsApp connection attempt stopped. Start again to get a new code.",
|
||||
),
|
||||
connecting: tx("custom.connecting", "Connecting…"),
|
||||
scanAgain: tx("custom.scanAgain", "Link another account"),
|
||||
connect: tx("custom.connect", "Link WhatsApp"),
|
||||
};
|
||||
}
|
||||
|
||||
export function WhatsAppConnectFlowView(props: WhatsAppConnectFlowViewProps) {
|
||||
const labels = useWhatsAppConnectLabels();
|
||||
return <ChannelQrConnectFlowView {...props} labels={labels} autoStart minimalPending />;
|
||||
}
|
||||
Reference in new issue
Block a user