"use client"; import { createElement, useCallback, useEffect, useMemo, useState } from "react"; import { Trans, useTranslation } from "react-i18next"; import { IconPlus, IconRefresh, IconTrash } from "@tabler/icons-react"; import { Button } from "@kandev/ui/button"; import { CardContent } from "@kandev/ui/card"; import { Input } from "@kandev/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@kandev/ui/tabs"; import { SettingsPromptEditor } from "@/components/settings/settings-prompt-editor"; import type { ScriptPlaceholder } from "@/components/settings/profile-edit/script-editor-completions"; import { ACTION_PRESET_ICON_CHOICES, iconForActionPreset, } from "@/components/integrations/action-preset-icons"; import { SettingsCard } from "@/components/settings/settings-card"; import { SettingsSection } from "@/components/settings/settings-section"; import { useSettingsSaveContributor } from "@/components/settings/settings-save-provider"; import { useToast } from "@/components/toast-provider"; import { getAzureDevOpsWorkspaceSettings, updateAzureDevOpsWorkspaceSettings, } from "@/lib/api/domains/azure-devops-api"; import type { AzureDevOpsActionPreset } from "@/lib/types/azure-devops"; import { DEFAULT_AZURE_PULL_REQUEST_ACTIONS, DEFAULT_AZURE_WORK_ITEM_ACTIONS, } from "./azure-devops-workspace-defaults"; type Translate = (key: string, values?: Record) => string; /** * Prompt-template placeholders offered by the ScriptEditor completions. * * A function rather than a module-scope constant: `t()` at module scope would * freeze the descriptions at the boot locale. `key` is the placeholder token * the backend substitutes and `example` is sample data — neither is copy. * Memoize at every call site so the shared editor does not rebuild the * completion provider on every keystroke. */ function actionPromptPlaceholders(t: Translate): ScriptPlaceholder[] { return [ { key: "url", description: t("azuredevops:placeholderUrlDescription"), example: "https://dev.azure.com/acme/Platform/_workitems/edit/42", executor_types: [], }, { key: "title", description: t("azuredevops:placeholderTitleDescription"), example: "Rotate integration credentials", executor_types: [], }, ]; } /** * Wire discriminant for the two action kinds. These used to be the English * phrases "Work item" / "Pull request", which made the same value both a * `===` comparand and display copy; they are now identifiers, and the labels * resolve through the key maps below. */ type ActionKind = "work-item" | "pull-request"; /** Title-cased kind noun, e.g. "Work item action label 1". */ const KIND_TITLE_KEYS: Record = { "work-item": "azuredevops:workItemKindTitle", "pull-request": "azuredevops:pullRequestKindTitle", }; /** Lower-cased kind noun for mid-sentence use, e.g. "Remove work item action 1". */ const KIND_LOWER_KEYS: Record = { "work-item": "azuredevops:workItemKindLower", "pull-request": "azuredevops:pullRequestKindLower", }; /** Route these presets drive; a path, so it is interpolated rather than translated. */ const AZURE_DEVOPS_ROUTE = "/azure-devops"; /** Prompt-template tokens, shown verbatim in the hint below the editor. */ const PROMPT_OPEN_BRACES = "{{"; const PROMPT_URL_TOKEN = "{{url}}"; const PROMPT_TITLE_TOKEN = "{{title}}"; // `label` is PERSISTED as part of `AzureDevOpsActionPreset` and is editable in // the row below, so it must stay locale-neutral — the same contract as // `newPreset` in components/github/action-presets-section.tsx. function newAction(): AzureDevOpsActionPreset { // i18n-exempt: persisted, editable preset label. See the comment above. return { id: `preset_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`, label: "New action", hint: "", icon: "sparkle", promptTemplate: "", }; } function ActionIconSelect({ value, dirty, onChange, }: { value: string; dirty: boolean; onChange: (value: string) => void; }) { const { t } = useTranslation(); return ( ); } function Field({ label, className, children, }: { label: string; className?: string; children: React.ReactNode; }) { return ( ); } function ActionPromptPanel({ action, baseline, onPatch, }: { action: AzureDevOpsActionPreset; baseline?: AzureDevOpsActionPreset; onPatch: (patch: Partial) => void; }) { const { t } = useTranslation(); const placeholders = useMemo(() => actionPromptPlaceholders(t), [t]); return (
onPatch({ promptTemplate })} placeholders={placeholders} promptReferences isDirty={action.promptTemplate !== baseline?.promptTemplate} testId={`azure-action-prompt-editor-${action.id}`} help={

{/* The three tokens are prompt syntax, passed as values so neither i18next interpolation nor the pseudo-locale rewrites them. */} Type {PROMPT_OPEN_BRACES} to see available placeholders.{" "} {PROMPT_URL_TOKEN} and {PROMPT_TITLE_TOKEN} are substituted when the action runs.

} />
); } function ActionRow({ kind, index, action, baseline, expanded, onToggle, onPatch, onRemove, }: { kind: ActionKind; index: number; action: AzureDevOpsActionPreset; baseline?: AzureDevOpsActionPreset; expanded: boolean; onToggle: () => void; onPatch: (patch: Partial) => void; onRemove: () => void; }) { const { t } = useTranslation(); const kindTitle = t(KIND_TITLE_KEYS[kind]); return (
onPatch({ icon })} /> onPatch({ label: event.target.value })} /> onPatch({ hint: event.target.value })} />
{expanded && }
); } function ActionEditor({ kind, actions, baseline, onChange, }: { kind: ActionKind; actions: AzureDevOpsActionPreset[]; baseline: AzureDevOpsActionPreset[]; onChange: (actions: AzureDevOpsActionPreset[]) => void; }) { const { t } = useTranslation(); const [expandedId, setExpandedId] = useState(null); const patch = (index: number, values: Partial) => onChange( actions.map((action, current) => (current === index ? { ...action, ...values } : action)), ); const add = () => { const action = newAction(); onChange([...actions, action]); setExpandedId(action.id); }; return (
{actions.map((action, index) => ( candidate.id === action.id)} expanded={expandedId === action.id} onToggle={() => setExpandedId((id) => (id === action.id ? null : action.id))} onPatch={(values) => patch(index, values)} onRemove={() => onChange(actions.filter((_, current) => current !== index))} /> ))}
); } function useActionDrafts(workspaceId: string, t: Translate) { const [workItems, setWorkItems] = useState(DEFAULT_AZURE_WORK_ITEM_ACTIONS); const [pullRequests, setPullRequests] = useState(DEFAULT_AZURE_PULL_REQUEST_ACTIONS); const [baseline, setBaseline] = useState({ workItems, pullRequests }); const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState(null); const [resetRequested, setResetRequested] = useState(false); const dirty = useMemo( () => resetRequested || JSON.stringify({ workItems, pullRequests }) !== JSON.stringify(baseline), [baseline, pullRequests, resetRequested, workItems], ); useEffect(() => { let current = true; setLoading(true); setLoadError(null); void getAzureDevOpsWorkspaceSettings(workspaceId) .then((settings) => { if (!current) return; setWorkItems(settings.workItemActions); setPullRequests(settings.pullRequestActions); setBaseline({ workItems: settings.workItemActions, pullRequests: settings.pullRequestActions, }); }) .catch((error: unknown) => { if (!current) return; setLoadError( error instanceof Error ? error.message : t("azuredevops:failedToLoadQuickActions"), ); }) .finally(() => current && setLoading(false)); return () => { current = false; }; }, [t, workspaceId]); const save = useCallback(async () => { const response = await updateAzureDevOpsWorkspaceSettings( workspaceId, resetRequested ? { workItemActions: null, pullRequestActions: null } : { workItemActions: workItems, pullRequestActions: pullRequests }, ); setWorkItems(response.workItemActions); setPullRequests(response.pullRequestActions); setBaseline({ workItems: response.workItemActions, pullRequests: response.pullRequestActions, }); setResetRequested(false); }, [pullRequests, resetRequested, workItems, workspaceId]); const reset = useCallback(() => { setWorkItems(DEFAULT_AZURE_WORK_ITEM_ACTIONS); setPullRequests(DEFAULT_AZURE_PULL_REQUEST_ACTIONS); setResetRequested(true); }, []); const discard = useCallback(() => { setWorkItems(baseline.workItems); setPullRequests(baseline.pullRequests); setResetRequested(false); }, [baseline]); return { workItems, pullRequests, setWorkItems, setPullRequests, baseline, loading, loadError, dirty, save, reset, discard, }; } function validActions(actions: AzureDevOpsActionPreset[]): boolean { return ( actions.length > 0 && actions.every((action) => action.label.trim() && action.promptTemplate.trim()) ); } export function AzureDevOpsQuickActionsSection({ workspaceId }: { workspaceId: string }) { const { t } = useTranslation(); const drafts = useActionDrafts(workspaceId, t); const { toast } = useToast(); const valid = validActions(drafts.workItems) && validActions(drafts.pullRequests); const save = useCallback(async () => { try { await drafts.save(); toast({ description: t("azuredevops:quickActionsSaved"), variant: "success" }); } catch (error) { toast({ description: error instanceof Error ? error.message : t("azuredevops:failedToSaveQuickActions"), variant: "error", }); throw error; } }, [drafts, t, toast]); useSettingsSaveContributor({ id: `azure-devops-actions:${workspaceId}`, revision: JSON.stringify([drafts.workItems, drafts.pullRequests]), isDirty: drafts.dirty, canSave: !drafts.loading && !drafts.loadError && valid, invalidReason: drafts.loadError ?? (valid ? undefined : t("azuredevops:quickActionInvalid")), save, discard: drafts.discard, }); return ( {t("common:reset")} } > {drafts.loadError && (

{t("azuredevops:couldNotLoadQuickActions", { error: drafts.loadError })}

)}
{t("azuredevops:pullRequestsTab")} {t("azuredevops:workItemsTab")}
); }