feat: implement condition branch selection and configuration in workflow editor

This commit is contained in:
mlogclub
2026-06-28 10:29:53 +08:00
parent 33c6647375
commit 64c10ba6dd
6 changed files with 352 additions and 105 deletions
@@ -20,16 +20,25 @@ import {
syncConditionBranchTargetsFromEdges, syncConditionBranchTargetsFromEdges,
} from "./workflow-utils" } from "./workflow-utils"
export type SelectedWorkflowBranch = {
nodeId: string
branchId: string
}
export function useFlowgramEditorProps({ export function useFlowgramEditorProps({
definition, definition,
nodeSpecs, nodeSpecs,
selectedBranch,
readonly = false, readonly = false,
onDefinitionChange, onDefinitionChange,
onSelectBranch,
}: { }: {
definition: AIWorkflowDefinition definition: AIWorkflowDefinition
nodeSpecs: AIWorkflowNodeSpec[] nodeSpecs: AIWorkflowNodeSpec[]
selectedBranch?: SelectedWorkflowBranch | null
readonly?: boolean readonly?: boolean
onDefinitionChange?: (definition: AIWorkflowDefinition) => void onDefinitionChange?: (definition: AIWorkflowDefinition) => void
onSelectBranch?: (branch: SelectedWorkflowBranch | null) => void
}) { }) {
return useMemo<FreeLayoutProps>( return useMemo<FreeLayoutProps>(
() => { () => {
@@ -41,7 +50,6 @@ export function useFlowgramEditorProps({
disableScrollBar: true, disableScrollBar: true,
}, },
initialData: initialData as WorkflowJSON, initialData: initialData as WorkflowJSON,
nodeRegistries: buildFlowgramNodeRegistries(nodeSpecs),
fromNodeJSON(_node, json) { fromNodeJSON(_node, json) {
return json return json
}, },
@@ -51,6 +59,7 @@ export function useFlowgramEditorProps({
materials: { materials: {
renderDefaultNode: FlowgramNodeRenderer, renderDefaultNode: FlowgramNodeRenderer,
}, },
nodeRegistries: buildFlowgramNodeRegistries(nodeSpecs, selectedBranch, onSelectBranch),
nodeEngine: { nodeEngine: {
enable: true, enable: true,
}, },
@@ -114,7 +123,7 @@ export function useFlowgramEditorProps({
], ],
} }
}, },
[definition, nodeSpecs, onDefinitionChange, readonly] [definition, nodeSpecs, onDefinitionChange, onSelectBranch, readonly, selectedBranch]
) )
} }
@@ -1,4 +1,4 @@
import { Field, type WorkflowNodeRegistry } from "@flowgram.ai/free-layout-editor" import { Field, type WorkflowNodeRegistry, useNodeRender } from "@flowgram.ai/free-layout-editor"
import { PlusIcon, XIcon } from "lucide-react" import { PlusIcon, XIcon } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
@@ -8,8 +8,13 @@ import {
normalizeNodeConfig, normalizeNodeConfig,
type WorkflowConditionBranch, type WorkflowConditionBranch,
} from "./workflow-utils" } from "./workflow-utils"
import type { SelectedWorkflowBranch } from "./flowgram-editor-provider"
export function buildFlowgramNodeRegistries(nodeSpecs: AIWorkflowNodeSpec[]): WorkflowNodeRegistry[] { export function buildFlowgramNodeRegistries(
nodeSpecs: AIWorkflowNodeSpec[],
selectedBranch?: SelectedWorkflowBranch | null,
onSelectBranch?: (branch: SelectedWorkflowBranch | null) => void
): WorkflowNodeRegistry[] {
const seen = new Set<string>() const seen = new Set<string>()
const specs = nodeSpecs.length > 0 const specs = nodeSpecs.length > 0
? nodeSpecs ? nodeSpecs
@@ -36,7 +41,14 @@ export function buildFlowgramNodeRegistries(nodeSpecs: AIWorkflowNodeSpec[]): Wo
defaultPorts: defaultPortsForNodeType(spec.type), defaultPorts: defaultPortsForNodeType(spec.type),
}, },
formMeta: { formMeta: {
render: () => <FlowgramNodeForm nodeType={spec.type} fallbackTitle={spec.title || spec.type} />, render: () => (
<FlowgramNodeForm
nodeType={spec.type}
fallbackTitle={spec.title || spec.type}
selectedBranch={selectedBranch}
onSelectBranch={onSelectBranch}
/>
),
}, },
})) }))
} }
@@ -44,12 +56,26 @@ export function buildFlowgramNodeRegistries(nodeSpecs: AIWorkflowNodeSpec[]): Wo
function FlowgramNodeForm({ function FlowgramNodeForm({
nodeType, nodeType,
fallbackTitle, fallbackTitle,
selectedBranch,
onSelectBranch,
}: { }: {
nodeType: string nodeType: string
fallbackTitle: string fallbackTitle: string
selectedBranch?: SelectedWorkflowBranch | null
onSelectBranch?: (branch: SelectedWorkflowBranch | null) => void
}) { }) {
const { node } = useNodeRender()
const nodeId = String(node.id ?? "")
if (nodeType === "condition") { if (nodeType === "condition") {
return <ConditionNodeForm fallbackTitle={fallbackTitle} /> return (
<ConditionNodeForm
fallbackTitle={fallbackTitle}
nodeId={nodeId}
selectedBranch={selectedBranch}
onSelectBranch={onSelectBranch}
/>
)
} }
return ( return (
@@ -79,7 +105,17 @@ function defaultPortsForNodeType(type: string) {
return [{ type: "input" as const }, { type: "output" as const }] return [{ type: "input" as const }, { type: "output" as const }]
} }
function ConditionNodeForm({ fallbackTitle }: { fallbackTitle: string }) { function ConditionNodeForm({
fallbackTitle,
nodeId,
selectedBranch,
onSelectBranch,
}: {
fallbackTitle: string
nodeId: string
selectedBranch?: SelectedWorkflowBranch | null
onSelectBranch?: (branch: SelectedWorkflowBranch | null) => void
}) {
return ( return (
<div className="flex w-full flex-col"> <div className="flex w-full flex-col">
<Field<string> name="title"> <Field<string> name="title">
@@ -101,6 +137,9 @@ function ConditionNodeForm({ fallbackTitle }: { fallbackTitle: string }) {
} }
const deleteBranch = (branchId: string) => { const deleteBranch = (branchId: string) => {
updateBranches(branches.filter((branch) => branch.id !== branchId)) updateBranches(branches.filter((branch) => branch.id !== branchId))
if (selectedBranch?.nodeId === nodeId && selectedBranch.branchId === branchId) {
onSelectBranch?.(null)
}
} }
return ( return (
@@ -109,7 +148,16 @@ function ConditionNodeForm({ fallbackTitle }: { fallbackTitle: string }) {
{branches.map((branch, index) => ( {branches.map((branch, index) => (
<div <div
key={branch.id} key={branch.id}
className="relative flex min-h-10 items-center gap-2 rounded-md bg-[#eef1f7] px-3 text-xs transition-colors before:absolute before:bottom-2 before:left-0 before:top-2 before:w-0.5 before:rounded-full before:bg-[#4e40e5] hover:bg-[#e6eaff]" className={[
"relative flex min-h-10 cursor-pointer items-center gap-2 rounded-md px-3 text-xs transition-colors before:absolute before:bottom-2 before:left-0 before:top-2 before:w-0.5 before:rounded-full before:bg-[#4e40e5]",
selectedBranch?.nodeId === nodeId && selectedBranch.branchId === branch.id
? "bg-[#dfe4ff] text-[#3327b9] ring-1 ring-inset ring-[#4e40e5]/45 before:w-1"
: "bg-[#eef1f7] hover:bg-[#e6eaff]",
].join(" ")}
onClick={(event) => {
event.stopPropagation()
onSelectBranch?.({ nodeId, branchId: branch.id })
}}
> >
<span className="min-w-0 flex-1 truncate font-medium text-foreground/90"> <span className="min-w-0 flex-1 truncate font-medium text-foreground/90">
{branch.name || (branch.default ? "默认分支" : branch.id)} {branch.name || (branch.default ? "默认分支" : branch.id)}
@@ -26,12 +26,27 @@ export type WorkflowBranchSummary = {
targetName?: string targetName?: string
} }
const CONDITION_OPERATOR_OPTIONS = [
{ value: "eq", label: "等于" },
{ value: "neq", label: "不等于" },
{ value: "contains", label: "包含" },
{ value: "not_contains", label: "不包含" },
{ value: "gt", label: "大于" },
{ value: "gte", label: "大于等于" },
{ value: "lt", label: "小于" },
{ value: "lte", label: "小于等于" },
{ value: "exists", label: "存在" },
{ value: "empty", label: "为空" },
]
export function NodeConfigPanel({ export function NodeConfigPanel({
node, node,
nodeSpec, nodeSpec,
nodes, nodes,
availableVariables, availableVariables,
showHeader = true, showHeader = true,
showConditionBranches = true,
showConfigJSON = true,
onChange, onChange,
onDelete, onDelete,
}: { }: {
@@ -41,6 +56,8 @@ export function NodeConfigPanel({
availableVariables?: WorkflowVariableRef[] availableVariables?: WorkflowVariableRef[]
branchSummaries?: WorkflowBranchSummary[] branchSummaries?: WorkflowBranchSummary[]
showHeader?: boolean showHeader?: boolean
showConditionBranches?: boolean
showConfigJSON?: boolean
onChange: (nodeId: string, data: AIWorkflowDefinition["nodes"][number]["data"]) => void onChange: (nodeId: string, data: AIWorkflowDefinition["nodes"][number]["data"]) => void
onDelete?: (nodeId: string) => void onDelete?: (nodeId: string) => void
}) { }) {
@@ -174,7 +191,7 @@ export function NodeConfigPanel({
</div> </div>
) : null} ) : null}
{node.type === "condition" || branches.length > 0 ? ( {showConditionBranches && (node.type === "condition" || branches.length > 0) ? (
<ConditionBranchesEditor <ConditionBranchesEditor
branches={branches} branches={branches}
nodes={nodes} nodes={nodes}
@@ -186,33 +203,136 @@ export function NodeConfigPanel({
/> />
) : null} ) : null}
<div className="space-y-2"> {showConfigJSON ? (
<Label htmlFor={`node-config-${node.id}`}> JSON</Label> <div className="space-y-2">
<Textarea <Label htmlFor={`node-config-${node.id}`}> JSON</Label>
id={`node-config-${node.id}`} <Textarea
value={configText} id={`node-config-${node.id}`}
className="min-h-36 font-mono text-xs" value={configText}
spellCheck={false} className="min-h-36 font-mono text-xs"
onChange={(event) => { spellCheck={false}
const next = event.target.value onChange={(event) => {
setConfigText(next) const next = event.target.value
try { setConfigText(next)
const parsed = JSON.parse(next || "{}") try {
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { const parsed = JSON.parse(next || "{}")
updateData({ config: parsed as Record<string, unknown> }) if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
updateData({ config: parsed as Record<string, unknown> })
}
} catch {
// The textarea keeps the draft while the user fixes invalid JSON.
} }
} catch { }}
// The textarea keeps the draft while the user fixes invalid JSON. />
} {configError ? <div className="text-xs text-destructive">{configError}</div> : null}
}} </div>
/> ) : null}
{configError ? <div className="text-xs text-destructive">{configError}</div> : null}
</div>
</div> </div>
</div> </div>
) )
} }
export function ConditionBranchConfigPanel({
node,
nodes,
branchId,
variables,
onChange,
onDelete,
}: {
node: AIWorkflowDefinition["nodes"][number]
nodes: AIWorkflowDefinition["nodes"]
branchId: string
variables: WorkflowVariableRef[]
onChange: (nodeId: string, data: AIWorkflowDefinition["nodes"][number]["data"]) => void
onDelete: (branchId: string) => void
}) {
const config = normalizeNodeConfig(node.data?.config)
const branches = config.branches ?? []
const branch = branches.find((item) => item.id === branchId)
const targetOptions = buildTargetOptions(nodes, node.id)
if (!branch) {
return (
<div className="flex h-full items-center justify-center p-6 text-sm text-muted-foreground">
</div>
)
}
const updateBranch = (nextBranch: WorkflowConditionBranch) => {
onChange(node.id, {
...(node.data ?? {}),
config: {
...config,
branches: branches.map((item) => (item.id === nextBranch.id ? nextBranch : item)),
},
})
}
return (
<div className="min-h-0 flex-1 space-y-5 overflow-y-auto p-4">
<div className="space-y-2">
<Label htmlFor={`condition-branch-name-${node.id}-${branch.id}`}></Label>
<Input
id={`condition-branch-name-${node.id}-${branch.id}`}
value={branch.name ?? ""}
placeholder={branch.id}
onChange={(event) => updateBranch({ ...branch, name: event.target.value })}
/>
</div>
<div className="space-y-2">
<Label></Label>
<OptionCombobox
value={branch.targetNodeId}
options={targetOptions}
placeholder="选择目标节点"
onChange={(targetNodeId) => updateBranch({ ...branch, targetNodeId })}
/>
</div>
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={branch.default === true}
className="size-4"
onChange={(event) => updateBranch({
...branch,
default: event.target.checked,
condition: event.target.checked ? undefined : branch.condition,
})}
/>
</label>
{branch.default ? (
<div className="rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground">
</div>
) : (
<ConditionFields
branch={branch}
variables={variables}
onChange={updateBranch}
/>
)}
{branch.default ? null : (
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 px-2 text-xs text-muted-foreground hover:text-destructive"
onClick={() => onDelete(branch.id)}
>
</Button>
)}
</div>
)
}
function ConditionBranchesEditor({ function ConditionBranchesEditor({
branches, branches,
nodes, nodes,
@@ -230,24 +350,7 @@ function ConditionBranchesEditor({
onChange: (branch: WorkflowConditionBranch) => void onChange: (branch: WorkflowConditionBranch) => void
onDelete: (branchId: string) => void onDelete: (branchId: string) => void
}) { }) {
const targetOptions = nodes const targetOptions = buildTargetOptions(nodes, currentNodeId)
.filter((node) => node.id !== currentNodeId && node.type !== "start")
.map((node) => ({
value: node.id,
label: node.data?.title || node.type || node.id,
}))
const operatorOptions = [
{ value: "eq", label: "等于" },
{ value: "neq", label: "不等于" },
{ value: "contains", label: "包含" },
{ value: "not_contains", label: "不包含" },
{ value: "gt", label: "大于" },
{ value: "gte", label: "大于等于" },
{ value: "lt", label: "小于" },
{ value: "lte", label: "小于等于" },
{ value: "exists", label: "存在" },
{ value: "empty", label: "为空" },
]
return ( return (
<div className="space-y-3"> <div className="space-y-3">
@@ -264,7 +367,6 @@ function ConditionBranchesEditor({
) : null} ) : null}
<div className="space-y-3"> <div className="space-y-3">
{branches.map((branch) => { {branches.map((branch) => {
const condition = branch.condition ?? {}
return ( return (
<div key={branch.id} className="space-y-3 rounded-md border p-3"> <div key={branch.id} className="space-y-3 rounded-md border p-3">
<div className="flex items-center justify-between gap-2"> <div className="flex items-center justify-between gap-2">
@@ -312,45 +414,7 @@ function ConditionBranchesEditor({
</label> </label>
{branch.default ? null : ( {branch.default ? null : (
<div className="space-y-3"> <ConditionFields branch={branch} variables={variables} onChange={onChange} />
<div className="space-y-1.5">
<Label></Label>
<VariableSelector
value={isRefValue(condition.left) ? condition.left : undefined}
variables={variables}
placeholder="选择变量"
onChange={(left) => onChange({
...branch,
condition: { ...condition, left },
})}
/>
</div>
<div className="grid grid-cols-[1fr_1fr] gap-2">
<div className="space-y-1.5">
<Label></Label>
<OptionCombobox
value={condition.operator ?? ""}
options={operatorOptions}
placeholder="选择操作符"
onChange={(operator) => onChange({
...branch,
condition: { ...condition, operator },
})}
/>
</div>
<div className={cn("space-y-1.5", ["exists", "empty"].includes(condition.operator ?? "") && "opacity-50")}>
<Label></Label>
<Input
value={stringifyConditionRight(condition.right)}
disabled={["exists", "empty"].includes(condition.operator ?? "")}
onChange={(event) => onChange({
...branch,
condition: { ...condition, right: event.target.value },
})}
/>
</div>
</div>
</div>
)} )}
</div> </div>
) )
@@ -360,6 +424,69 @@ function ConditionBranchesEditor({
) )
} }
function ConditionFields({
branch,
variables,
onChange,
}: {
branch: WorkflowConditionBranch
variables: WorkflowVariableRef[]
onChange: (branch: WorkflowConditionBranch) => void
}) {
const condition = branch.condition ?? {}
return (
<div className="space-y-3">
<div className="space-y-1.5">
<Label></Label>
<VariableSelector
value={isRefValue(condition.left) ? condition.left : undefined}
variables={variables}
placeholder="选择变量"
onChange={(left) => onChange({
...branch,
condition: { ...condition, left },
})}
/>
</div>
<div className="grid grid-cols-[1fr_1fr] gap-2">
<div className="space-y-1.5">
<Label></Label>
<OptionCombobox
value={condition.operator ?? ""}
options={CONDITION_OPERATOR_OPTIONS}
placeholder="选择操作符"
onChange={(operator) => onChange({
...branch,
condition: { ...condition, operator },
})}
/>
</div>
<div className={cn("space-y-1.5", ["exists", "empty"].includes(condition.operator ?? "") && "opacity-50")}>
<Label></Label>
<Input
value={stringifyConditionRight(condition.right)}
disabled={["exists", "empty"].includes(condition.operator ?? "")}
onChange={(event) => onChange({
...branch,
condition: { ...condition, right: event.target.value },
})}
/>
</div>
</div>
</div>
)
}
function buildTargetOptions(nodes: AIWorkflowDefinition["nodes"], currentNodeId: string) {
return nodes
.filter((node) => node.id !== currentNodeId && node.type !== "start")
.map((node) => ({
value: node.id,
label: node.data?.title || node.type || node.id,
}))
}
function stringifyConditionRight(value: unknown) { function stringifyConditionRight(value: unknown) {
if (value === undefined || value === null) { if (value === undefined || value === null) {
return "" return ""
@@ -5,9 +5,11 @@ import { XIcon } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import type { AIWorkflowDefinition, AIWorkflowNodeSpec } from "@/lib/api/admin" import type { AIWorkflowDefinition, AIWorkflowNodeSpec } from "@/lib/api/admin"
import { NodeConfigPanel } from "./node-config-panel" import type { SelectedWorkflowBranch } from "./flowgram-editor-provider"
import { ConditionBranchConfigPanel, NodeConfigPanel } from "./node-config-panel"
import { import {
getAvailableVariables, getAvailableVariables,
normalizeNodeConfig,
type WorkflowNodeData, type WorkflowNodeData,
} from "./workflow-utils" } from "./workflow-utils"
@@ -15,14 +17,18 @@ export function WorkflowConfigPanel({
definition, definition,
nodeSpecs, nodeSpecs,
selectedNodeId, selectedNodeId,
selectedBranch,
onClose, onClose,
onSelectBranch,
onChangeNodeData, onChangeNodeData,
onDeleteNode, onDeleteNode,
}: { }: {
definition: AIWorkflowDefinition definition: AIWorkflowDefinition
nodeSpecs: AIWorkflowNodeSpec[] nodeSpecs: AIWorkflowNodeSpec[]
selectedNodeId: string selectedNodeId: string
selectedBranch: SelectedWorkflowBranch | null
onClose: () => void onClose: () => void
onSelectBranch: (branch: SelectedWorkflowBranch | null) => void
onChangeNodeData: (nodeId: string, data: WorkflowNodeData) => void onChangeNodeData: (nodeId: string, data: WorkflowNodeData) => void
onDeleteNode: (nodeId: string) => void onDeleteNode: (nodeId: string) => void
}) { }) {
@@ -33,19 +39,36 @@ export function WorkflowConfigPanel({
const availableVariables = selectedNode const availableVariables = selectedNode
? getAvailableVariables(definition, selectedNode.id, nodeSpecs) ? getAvailableVariables(definition, selectedNode.id, nodeSpecs)
: [] : []
const selectedBranchItem = selectedNode && selectedBranch?.nodeId === selectedNode.id
? normalizeNodeConfig(selectedNode.data?.config).branches?.find((branch) => branch.id === selectedBranch.branchId) ?? null
: null
if (!selectedNode) { if (!selectedNode) {
return null return null
} }
const deleteSelectedBranch = (branchId: string) => {
const config = normalizeNodeConfig(selectedNode.data?.config)
onChangeNodeData(selectedNode.id, {
...(selectedNode.data ?? {}),
config: {
...config,
branches: (config.branches ?? []).filter((branch) => branch.id !== branchId),
},
})
onSelectBranch(null)
}
return ( return (
<div className="pointer-events-none absolute inset-y-3 right-3 z-50 flex w-[360px] max-w-[calc(100%-1.5rem)]"> <div className="pointer-events-none absolute inset-y-3 right-3 z-50 flex w-[360px] max-w-[calc(100%-1.5rem)]">
<section className="pointer-events-auto flex min-h-0 w-full flex-col overflow-hidden rounded-lg border bg-background shadow-2xl"> <section className="pointer-events-auto flex min-h-0 w-full flex-col overflow-hidden rounded-lg border bg-background shadow-2xl">
<div className="flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3"> <div className="flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3">
<div className="min-w-0"> <div className="min-w-0">
<div className="text-sm font-medium"></div> <div className="text-sm font-medium">{selectedBranchItem ? "条件属性" : "属性"}</div>
<div className="mt-0.5 truncate text-xs text-muted-foreground"> <div className="mt-0.5 truncate text-xs text-muted-foreground">
{selectedNode.data?.title || selectedNodeSpec?.title || selectedNode.type} {selectedBranchItem
? selectedBranchItem.name || selectedBranchItem.id
: selectedNode.data?.title || selectedNodeSpec?.title || selectedNode.type}
</div> </div>
</div> </div>
<Button <Button
@@ -60,15 +83,28 @@ export function WorkflowConfigPanel({
</Button> </Button>
</div> </div>
<div className="min-h-0 flex-1"> <div className="min-h-0 flex-1">
<NodeConfigPanel {selectedBranchItem && selectedBranch ? (
node={selectedNode} <ConditionBranchConfigPanel
nodeSpec={selectedNodeSpec} node={selectedNode}
nodes={definition.nodes} nodes={definition.nodes}
availableVariables={availableVariables} branchId={selectedBranch.branchId}
showHeader={false} variables={availableVariables}
onChange={onChangeNodeData} onChange={onChangeNodeData}
onDelete={onDeleteNode} onDelete={deleteSelectedBranch}
/> />
) : (
<NodeConfigPanel
node={selectedNode}
nodeSpec={selectedNodeSpec}
nodes={definition.nodes}
availableVariables={availableVariables}
showHeader={false}
showConditionBranches={selectedNode.type !== "condition"}
showConfigJSON={selectedNode.type !== "condition"}
onChange={onChangeNodeData}
onDelete={onDeleteNode}
/>
)}
</div> </div>
</section> </section>
</div> </div>
@@ -16,7 +16,7 @@ import {
import type { AIWorkflowDefinition, AIWorkflowNodeSpec } from "@/lib/api/admin" import type { AIWorkflowDefinition, AIWorkflowNodeSpec } from "@/lib/api/admin"
import { useFlowgramEditorProps } from "./flowgram-editor-provider" import { useFlowgramEditorProps, type SelectedWorkflowBranch } from "./flowgram-editor-provider"
import { WorkflowConfigPanel } from "./workflow-config-sidebar" import { WorkflowConfigPanel } from "./workflow-config-sidebar"
import { WorkflowEditorToolbar } from "./workflow-editor-toolbar" import { WorkflowEditorToolbar } from "./workflow-editor-toolbar"
import { WorkflowNodePalette } from "./workflow-node-palette" import { WorkflowNodePalette } from "./workflow-node-palette"
@@ -65,6 +65,7 @@ export function WorkflowEditor({
}) { }) {
const [localDefinition, setLocalDefinition] = useState(definition) const [localDefinition, setLocalDefinition] = useState(definition)
const [selectedNodeId, setSelectedNodeId] = useState("") const [selectedNodeId, setSelectedNodeId] = useState("")
const [selectedBranch, setSelectedBranch] = useState<SelectedWorkflowBranch | null>(null)
const validation = useMemo( const validation = useMemo(
() => validateWorkflowDefinition(localDefinition, nodeSpecs), () => validateWorkflowDefinition(localDefinition, nodeSpecs),
@@ -74,10 +75,19 @@ export function WorkflowEditor({
const editorProps = useFlowgramEditorProps({ const editorProps = useFlowgramEditorProps({
definition: localDefinition, definition: localDefinition,
nodeSpecs, nodeSpecs,
selectedBranch,
onDefinitionChange: (next) => { onDefinitionChange: (next) => {
setLocalDefinition(next) setLocalDefinition(next)
onDefinitionChange(next) onDefinitionChange(next)
}, },
onSelectBranch: (branch) => {
if (!branch) {
setSelectedBranch(null)
return
}
setSelectedNodeId(branch.nodeId)
setSelectedBranch(branch)
},
}) })
return ( return (
@@ -86,13 +96,18 @@ export function WorkflowEditor({
definition={localDefinition} definition={localDefinition}
nodeSpecs={nodeSpecs} nodeSpecs={nodeSpecs}
selectedNodeId={selectedNodeId} selectedNodeId={selectedNodeId}
selectedBranch={selectedBranch}
validation={validation} validation={validation}
toolbarExtra={toolbarExtra} toolbarExtra={toolbarExtra}
onDefinitionChange={(next) => { onDefinitionChange={(next) => {
setLocalDefinition(next) setLocalDefinition(next)
onDefinitionChange(next) onDefinitionChange(next)
}} }}
onSelectNode={setSelectedNodeId} onSelectNode={(nodeId) => {
setSelectedNodeId(nodeId)
setSelectedBranch(null)
}}
onSelectBranch={setSelectedBranch}
onUndo={onUndo} onUndo={onUndo}
undoDisabled={undoDisabled} undoDisabled={undoDisabled}
onRedo={onRedo} onRedo={onRedo}
@@ -114,10 +129,12 @@ function WorkflowEditorInner({
definition, definition,
nodeSpecs, nodeSpecs,
selectedNodeId, selectedNodeId,
selectedBranch,
validation, validation,
toolbarExtra, toolbarExtra,
onDefinitionChange, onDefinitionChange,
onSelectNode, onSelectNode,
onSelectBranch,
onUndo, onUndo,
undoDisabled, undoDisabled,
onRedo, onRedo,
@@ -134,10 +151,12 @@ function WorkflowEditorInner({
definition: AIWorkflowDefinition definition: AIWorkflowDefinition
nodeSpecs: AIWorkflowNodeSpec[] nodeSpecs: AIWorkflowNodeSpec[]
selectedNodeId: string selectedNodeId: string
selectedBranch: SelectedWorkflowBranch | null
validation: ReturnType<typeof validateWorkflowDefinition> validation: ReturnType<typeof validateWorkflowDefinition>
toolbarExtra?: ReactNode toolbarExtra?: ReactNode
onDefinitionChange: (definition: AIWorkflowDefinition) => void onDefinitionChange: (definition: AIWorkflowDefinition) => void
onSelectNode: (nodeId: string) => void onSelectNode: (nodeId: string) => void
onSelectBranch: (branch: SelectedWorkflowBranch | null) => void
onUndo?: () => void onUndo?: () => void
undoDisabled?: boolean undoDisabled?: boolean
onRedo?: () => void onRedo?: () => void
@@ -216,6 +235,7 @@ function WorkflowEditorInner({
const closeConfigPanel = () => { const closeConfigPanel = () => {
selectService.clear() selectService.clear()
onSelectNode("") onSelectNode("")
onSelectBranch(null)
} }
return ( return (
@@ -255,7 +275,9 @@ function WorkflowEditorInner({
definition={definition} definition={definition}
nodeSpecs={nodeSpecs} nodeSpecs={nodeSpecs}
selectedNodeId={selectedNodeId} selectedNodeId={selectedNodeId}
selectedBranch={selectedBranch}
onClose={closeConfigPanel} onClose={closeConfigPanel}
onSelectBranch={onSelectBranch}
onChangeNodeData={updateNodeData} onChangeNodeData={updateNodeData}
onDeleteNode={removeNode} onDeleteNode={removeNode}
/> />
@@ -284,7 +284,9 @@ describe("workflow definition mutations", () => {
}), }),
workflowNode("end_1", "end", { x: 480, y: 0 }), workflowNode("end_1", "end", { x: 480, y: 0 }),
], ],
edges: [workflowEdge("condition_1", "end_1")], edges: [
workflowEdge("condition_1", "end_1", { sourcePortID: "default" }),
],
} }
const updated = upsertConditionBranch(definition, "condition_1", { const updated = upsertConditionBranch(definition, "condition_1", {
@@ -300,8 +302,11 @@ describe("workflow definition mutations", () => {
assert.deepEqual(plain(updated.nodes[0].data.config.branches.map((branch) => branch.id)), ["default", "vip"]) assert.deepEqual(plain(updated.nodes[0].data.config.branches.map((branch) => branch.id)), ["default", "vip"])
const deleted = deleteConditionBranch(updated, "condition_1", "default") updated.edges.push(workflowEdge("condition_1", "end_1", { sourcePortID: "vip" }))
assert.deepEqual(plain(deleted.nodes[0].data.config.branches.map((branch) => branch.id)), ["vip"])
const deleted = deleteConditionBranch(updated, "condition_1", "vip")
assert.deepEqual(plain(deleted.nodes[0].data.config.branches.map((branch) => branch.id)), ["default"])
assert.deepEqual(plain(deleted.edges.map((edge) => edge.sourcePortID)), ["default"])
}) })
it("adds FlowGram source ports for condition edges without removing existing lines", async () => { it("adds FlowGram source ports for condition edges without removing existing lines", async () => {