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,
} from "./workflow-utils"
export type SelectedWorkflowBranch = {
nodeId: string
branchId: string
}
export function useFlowgramEditorProps({
definition,
nodeSpecs,
selectedBranch,
readonly = false,
onDefinitionChange,
onSelectBranch,
}: {
definition: AIWorkflowDefinition
nodeSpecs: AIWorkflowNodeSpec[]
selectedBranch?: SelectedWorkflowBranch | null
readonly?: boolean
onDefinitionChange?: (definition: AIWorkflowDefinition) => void
onSelectBranch?: (branch: SelectedWorkflowBranch | null) => void
}) {
return useMemo<FreeLayoutProps>(
() => {
@@ -41,7 +50,6 @@ export function useFlowgramEditorProps({
disableScrollBar: true,
},
initialData: initialData as WorkflowJSON,
nodeRegistries: buildFlowgramNodeRegistries(nodeSpecs),
fromNodeJSON(_node, json) {
return json
},
@@ -51,6 +59,7 @@ export function useFlowgramEditorProps({
materials: {
renderDefaultNode: FlowgramNodeRenderer,
},
nodeRegistries: buildFlowgramNodeRegistries(nodeSpecs, selectedBranch, onSelectBranch),
nodeEngine: {
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 { Button } from "@/components/ui/button"
@@ -8,8 +8,13 @@ import {
normalizeNodeConfig,
type WorkflowConditionBranch,
} 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 specs = nodeSpecs.length > 0
? nodeSpecs
@@ -36,7 +41,14 @@ export function buildFlowgramNodeRegistries(nodeSpecs: AIWorkflowNodeSpec[]): Wo
defaultPorts: defaultPortsForNodeType(spec.type),
},
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({
nodeType,
fallbackTitle,
selectedBranch,
onSelectBranch,
}: {
nodeType: string
fallbackTitle: string
selectedBranch?: SelectedWorkflowBranch | null
onSelectBranch?: (branch: SelectedWorkflowBranch | null) => void
}) {
const { node } = useNodeRender()
const nodeId = String(node.id ?? "")
if (nodeType === "condition") {
return <ConditionNodeForm fallbackTitle={fallbackTitle} />
return (
<ConditionNodeForm
fallbackTitle={fallbackTitle}
nodeId={nodeId}
selectedBranch={selectedBranch}
onSelectBranch={onSelectBranch}
/>
)
}
return (
@@ -79,7 +105,17 @@ function defaultPortsForNodeType(type: string) {
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 (
<div className="flex w-full flex-col">
<Field<string> name="title">
@@ -101,6 +137,9 @@ function ConditionNodeForm({ fallbackTitle }: { fallbackTitle: string }) {
}
const deleteBranch = (branchId: string) => {
updateBranches(branches.filter((branch) => branch.id !== branchId))
if (selectedBranch?.nodeId === nodeId && selectedBranch.branchId === branchId) {
onSelectBranch?.(null)
}
}
return (
@@ -109,7 +148,16 @@ function ConditionNodeForm({ fallbackTitle }: { fallbackTitle: string }) {
{branches.map((branch, index) => (
<div
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">
{branch.name || (branch.default ? "默认分支" : branch.id)}
@@ -26,12 +26,27 @@ export type WorkflowBranchSummary = {
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({
node,
nodeSpec,
nodes,
availableVariables,
showHeader = true,
showConditionBranches = true,
showConfigJSON = true,
onChange,
onDelete,
}: {
@@ -41,6 +56,8 @@ export function NodeConfigPanel({
availableVariables?: WorkflowVariableRef[]
branchSummaries?: WorkflowBranchSummary[]
showHeader?: boolean
showConditionBranches?: boolean
showConfigJSON?: boolean
onChange: (nodeId: string, data: AIWorkflowDefinition["nodes"][number]["data"]) => void
onDelete?: (nodeId: string) => void
}) {
@@ -174,7 +191,7 @@ export function NodeConfigPanel({
</div>
) : null}
{node.type === "condition" || branches.length > 0 ? (
{showConditionBranches && (node.type === "condition" || branches.length > 0) ? (
<ConditionBranchesEditor
branches={branches}
nodes={nodes}
@@ -186,33 +203,136 @@ export function NodeConfigPanel({
/>
) : null}
<div className="space-y-2">
<Label htmlFor={`node-config-${node.id}`}> JSON</Label>
<Textarea
id={`node-config-${node.id}`}
value={configText}
className="min-h-36 font-mono text-xs"
spellCheck={false}
onChange={(event) => {
const next = event.target.value
setConfigText(next)
try {
const parsed = JSON.parse(next || "{}")
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
updateData({ config: parsed as Record<string, unknown> })
{showConfigJSON ? (
<div className="space-y-2">
<Label htmlFor={`node-config-${node.id}`}> JSON</Label>
<Textarea
id={`node-config-${node.id}`}
value={configText}
className="min-h-36 font-mono text-xs"
spellCheck={false}
onChange={(event) => {
const next = event.target.value
setConfigText(next)
try {
const parsed = JSON.parse(next || "{}")
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>
}}
/>
{configError ? <div className="text-xs text-destructive">{configError}</div> : null}
</div>
) : null}
</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({
branches,
nodes,
@@ -230,24 +350,7 @@ function ConditionBranchesEditor({
onChange: (branch: WorkflowConditionBranch) => void
onDelete: (branchId: string) => void
}) {
const targetOptions = nodes
.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: "为空" },
]
const targetOptions = buildTargetOptions(nodes, currentNodeId)
return (
<div className="space-y-3">
@@ -264,7 +367,6 @@ function ConditionBranchesEditor({
) : null}
<div className="space-y-3">
{branches.map((branch) => {
const condition = branch.condition ?? {}
return (
<div key={branch.id} className="space-y-3 rounded-md border p-3">
<div className="flex items-center justify-between gap-2">
@@ -312,45 +414,7 @@ function ConditionBranchesEditor({
</label>
{branch.default ? null : (
<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={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>
<ConditionFields branch={branch} variables={variables} onChange={onChange} />
)}
</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) {
if (value === undefined || value === null) {
return ""
@@ -5,9 +5,11 @@ import { XIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
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 {
getAvailableVariables,
normalizeNodeConfig,
type WorkflowNodeData,
} from "./workflow-utils"
@@ -15,14 +17,18 @@ export function WorkflowConfigPanel({
definition,
nodeSpecs,
selectedNodeId,
selectedBranch,
onClose,
onSelectBranch,
onChangeNodeData,
onDeleteNode,
}: {
definition: AIWorkflowDefinition
nodeSpecs: AIWorkflowNodeSpec[]
selectedNodeId: string
selectedBranch: SelectedWorkflowBranch | null
onClose: () => void
onSelectBranch: (branch: SelectedWorkflowBranch | null) => void
onChangeNodeData: (nodeId: string, data: WorkflowNodeData) => void
onDeleteNode: (nodeId: string) => void
}) {
@@ -33,19 +39,36 @@ export function WorkflowConfigPanel({
const availableVariables = selectedNode
? 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) {
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 (
<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">
<div className="flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3">
<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">
{selectedNode.data?.title || selectedNodeSpec?.title || selectedNode.type}
{selectedBranchItem
? selectedBranchItem.name || selectedBranchItem.id
: selectedNode.data?.title || selectedNodeSpec?.title || selectedNode.type}
</div>
</div>
<Button
@@ -60,15 +83,28 @@ export function WorkflowConfigPanel({
</Button>
</div>
<div className="min-h-0 flex-1">
<NodeConfigPanel
node={selectedNode}
nodeSpec={selectedNodeSpec}
nodes={definition.nodes}
availableVariables={availableVariables}
showHeader={false}
onChange={onChangeNodeData}
onDelete={onDeleteNode}
/>
{selectedBranchItem && selectedBranch ? (
<ConditionBranchConfigPanel
node={selectedNode}
nodes={definition.nodes}
branchId={selectedBranch.branchId}
variables={availableVariables}
onChange={onChangeNodeData}
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>
</section>
</div>
@@ -16,7 +16,7 @@ import {
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 { WorkflowEditorToolbar } from "./workflow-editor-toolbar"
import { WorkflowNodePalette } from "./workflow-node-palette"
@@ -65,6 +65,7 @@ export function WorkflowEditor({
}) {
const [localDefinition, setLocalDefinition] = useState(definition)
const [selectedNodeId, setSelectedNodeId] = useState("")
const [selectedBranch, setSelectedBranch] = useState<SelectedWorkflowBranch | null>(null)
const validation = useMemo(
() => validateWorkflowDefinition(localDefinition, nodeSpecs),
@@ -74,10 +75,19 @@ export function WorkflowEditor({
const editorProps = useFlowgramEditorProps({
definition: localDefinition,
nodeSpecs,
selectedBranch,
onDefinitionChange: (next) => {
setLocalDefinition(next)
onDefinitionChange(next)
},
onSelectBranch: (branch) => {
if (!branch) {
setSelectedBranch(null)
return
}
setSelectedNodeId(branch.nodeId)
setSelectedBranch(branch)
},
})
return (
@@ -86,13 +96,18 @@ export function WorkflowEditor({
definition={localDefinition}
nodeSpecs={nodeSpecs}
selectedNodeId={selectedNodeId}
selectedBranch={selectedBranch}
validation={validation}
toolbarExtra={toolbarExtra}
onDefinitionChange={(next) => {
setLocalDefinition(next)
onDefinitionChange(next)
}}
onSelectNode={setSelectedNodeId}
onSelectNode={(nodeId) => {
setSelectedNodeId(nodeId)
setSelectedBranch(null)
}}
onSelectBranch={setSelectedBranch}
onUndo={onUndo}
undoDisabled={undoDisabled}
onRedo={onRedo}
@@ -114,10 +129,12 @@ function WorkflowEditorInner({
definition,
nodeSpecs,
selectedNodeId,
selectedBranch,
validation,
toolbarExtra,
onDefinitionChange,
onSelectNode,
onSelectBranch,
onUndo,
undoDisabled,
onRedo,
@@ -134,10 +151,12 @@ function WorkflowEditorInner({
definition: AIWorkflowDefinition
nodeSpecs: AIWorkflowNodeSpec[]
selectedNodeId: string
selectedBranch: SelectedWorkflowBranch | null
validation: ReturnType<typeof validateWorkflowDefinition>
toolbarExtra?: ReactNode
onDefinitionChange: (definition: AIWorkflowDefinition) => void
onSelectNode: (nodeId: string) => void
onSelectBranch: (branch: SelectedWorkflowBranch | null) => void
onUndo?: () => void
undoDisabled?: boolean
onRedo?: () => void
@@ -216,6 +235,7 @@ function WorkflowEditorInner({
const closeConfigPanel = () => {
selectService.clear()
onSelectNode("")
onSelectBranch(null)
}
return (
@@ -255,7 +275,9 @@ function WorkflowEditorInner({
definition={definition}
nodeSpecs={nodeSpecs}
selectedNodeId={selectedNodeId}
selectedBranch={selectedBranch}
onClose={closeConfigPanel}
onSelectBranch={onSelectBranch}
onChangeNodeData={updateNodeData}
onDeleteNode={removeNode}
/>
@@ -284,7 +284,9 @@ describe("workflow definition mutations", () => {
}),
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", {
@@ -300,8 +302,11 @@ describe("workflow definition mutations", () => {
assert.deepEqual(plain(updated.nodes[0].data.config.branches.map((branch) => branch.id)), ["default", "vip"])
const deleted = deleteConditionBranch(updated, "condition_1", "default")
assert.deepEqual(plain(deleted.nodes[0].data.config.branches.map((branch) => branch.id)), ["vip"])
updated.edges.push(workflowEdge("condition_1", "end_1", { sourcePortID: "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 () => {