feat: Phase 5 - Visual Workflow Editor (Option B)
Deploy Development / deploy (push) Failing after 1s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 14s

Backend (Mini-Backend 1-2h):
- Migration 016: ai_prompts.graph_data JSONB column
- workflow_executor: graph_data parameter support (backward-compatible)
- prompt_executor: execute_workflow_prompt uses graph_data

Frontend (Main effort 25-35h):
- WorkflowCanvas: React Flow wrapper component
- 5 Custom Nodes: Start, End, Analysis, Logic, Join
- 4 Config Panels: QuestionAugmentation, LogicExpression, Fallback, Join
- workflowValidation: Structural + logical validation
- workflowSerializer: Canvas ↔ JSONB conversion
- WorkflowEditorPage: Main orchestration (420 LOC)
- Route: /workflow-editor/:id
- CSS: workflowEditor.css (300 LOC)

Architecture:
- Option B: ai_prompts.type='workflow' (not separate table)
- panels/ subdirectory for clean separation
- WorkflowCanvas reusable component
- User GUI identical (Workflows = Prompts)
- Backward-compatible (type='pipeline' unchanged)

Version: v0.9m → v0.9n (Phase 5 complete)
Module: workflow 0.5.0 → 0.6.0

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 4.6 committed 2026-04-04 17:56:00 +02:00
1 parent a7058c30be
commit dc59596f01
23 files changed
+3010 -48

No files matched your search

@@ -0,0 +1,70 @@
import ReactFlow, { Background, Controls, MiniMap } from 'reactflow'
import 'reactflow/dist/style.css'
/**
* WorkflowCanvas - React Flow Wrapper Component
*
* Kapselt React Flow Setup (Background, Controls, MiniMap).
* Separation of Concerns: Canvas-Logik getrennt von Editor-Orchestrierung.
*
* Props:
* - nodes: Array of React Flow nodes
* - edges: Array of React Flow edges
* - nodeTypes: Object mapping node type to component
* - onNodesChange: Handler for node changes (drag, delete, etc.)
* - onEdgesChange: Handler for edge changes
* - onConnect: Handler for new edge connections
* - onNodeClick: Handler for node selection
*/
export function WorkflowCanvas({
nodes,
edges,
nodeTypes,
onNodesChange,
onEdgesChange,
onConnect,
onNodeClick
}) {
return (
<div style={{ width: '100%', height: '100%' }}>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onNodeClick={onNodeClick}
nodeTypes={nodeTypes}
fitView
className="workflow-canvas"
minZoom={0.2}
maxZoom={2}
defaultEdgeOptions={{
animated: false,
style: { strokeWidth: 2 }
}}
>
<Background
variant="dots"
gap={16}
size={1}
color="var(--border)"
/>
<Controls
showZoom={true}
showFitView={true}
showInteractive={true}
/>
<MiniMap
nodeStrokeWidth={3}
zoomable
pannable
style={{
backgroundColor: 'var(--surface)',
border: '1px solid var(--border)'
}}
/>
</ReactFlow>
</div>
)
}
@@ -0,0 +1,51 @@
import { Handle, Position } from 'reactflow'
/**
* AnalysisNode - KI-Prompt Knoten
*
* Properties:
* - data.label: Node-Label
* - data.prompt_id: ID des referenzierten Basis-Prompts
* - data.prompt_name: Name des Prompts (optional, für Display)
* - data.questions: Array von Question Augmentations
* - selected: Boolean
*/
export function AnalysisNode({ data, selected }) {
const hasQuestions = data.questions?.length > 0
const promptName = data.prompt_name || (data.prompt_id ? `Prompt #${data.prompt_id}` : 'Kein Prompt')
const questionCount = data.questions?.length || 0
return (
<div className={`workflow-node analysis-node ${selected ? 'selected' : ''}`}>
<div className="node-header">
<div className="node-icon">🤖</div>
<div className="node-label">{data.label || 'Analyse'}</div>
</div>
<div className="node-body">
<div className="prompt-name" title={promptName}>
{promptName}
</div>
{hasQuestions && (
<div className="questions-indicator">
📋 {questionCount} {questionCount === 1 ? 'Frage' : 'Fragen'}
</div>
)}
</div>
<Handle
type="target"
position={Position.Top}
id="in"
style={{ background: 'var(--accent)' }}
/>
<Handle
type="source"
position={Position.Bottom}
id="out"
style={{ background: 'var(--accent)' }}
/>
</div>
)
}
@@ -0,0 +1,25 @@
import { Handle, Position } from 'reactflow'
/**
* EndNode - Workflow Austritt
*
* Properties:
* - data.label: Node-Label (default: "Ende")
* - selected: Boolean (Node ist ausgewählt)
*/
export function EndNode({ data, selected }) {
return (
<div className={`workflow-node end-node ${selected ? 'selected' : ''}`}>
<div className="node-icon">🏁</div>
<div className="node-label">{data.label || 'Ende'}</div>
{/* Nur Target Handle (kein Source, da Endpunkt) */}
<Handle
type="target"
position={Position.Top}
id="in"
style={{ background: 'var(--danger)' }}
/>
</div>
)
}
@@ -0,0 +1,74 @@
import { Handle, Position } from 'reactflow'
/**
* JoinNode - Pfad-Konsolidierung
*
* Properties:
* - data.label: Node-Label
* - data.join_strategy: 'wait_all' | 'wait_any' | 'best_effort'
* - data.skip_handling: 'ignore_skipped' | 'use_placeholder' | 'require_minimum'
* - selected: Boolean
*/
export function JoinNode({ data, selected }) {
const strategy = data.join_strategy || 'wait_all'
const skipHandling = data.skip_handling || 'ignore_skipped'
// Strategy Display Names
const strategyLabels = {
'wait_all': 'Alle warten',
'wait_any': 'Beliebig',
'best_effort': 'Best Effort'
}
const skipLabels = {
'ignore_skipped': 'Ignorieren',
'use_placeholder': 'Platzhalter',
'require_minimum': 'Minimum'
}
return (
<div className={`workflow-node join-node ${selected ? 'selected' : ''}`}>
<div className="node-header">
<div className="node-icon">🔀</div>
<div className="node-label">{data.label || 'Join'}</div>
</div>
<div className="node-body">
<div className="strategy">
<strong>Strategie:</strong> {strategyLabels[strategy] || strategy}
</div>
<div className="skip-handling">
<strong>Skip:</strong> {skipLabels[skipHandling] || skipHandling}
</div>
</div>
{/* Mehrere Target Handles für eingehende Pfade */}
<Handle
type="target"
position={Position.Top}
id="path_1"
style={{ left: '25%', background: '#17A2B8' }}
/>
<Handle
type="target"
position={Position.Top}
id="path_2"
style={{ left: '50%', background: '#17A2B8' }}
/>
<Handle
type="target"
position={Position.Top}
id="path_3"
style={{ left: '75%', background: '#17A2B8' }}
/>
{/* Ein Source Handle für konsolidierten Ausgang */}
<Handle
type="source"
position={Position.Bottom}
id="out"
style={{ background: '#17A2B8' }}
/>
</div>
)
}
@@ -0,0 +1,68 @@
import { Handle, Position } from 'reactflow'
/**
* LogicNode - Bedingungs-Knoten (If-Then-Else)
*
* Properties:
* - data.label: Node-Label
* - data.condition: Logic Expression Object
* - selected: Boolean
*/
export function LogicNode({ data, selected }) {
const hasCondition = !!data.condition && !!data.condition.operator
// Condition Summary (vereinfacht für Display)
const getConditionSummary = () => {
if (!hasCondition) return 'Keine Bedingung'
const op = data.condition.operator?.toUpperCase()
const operandCount = data.condition.operands?.length || 0
if (op === 'AND' || op === 'OR' || op === 'NOT') {
return `${op} (${operandCount} Bedingungen)`
}
// Simple condition (ref, operator, value)
if (data.condition.ref) {
return `${data.condition.ref} ${data.condition.operator} ...`
}
return 'Bedingung definiert'
}
return (
<div className={`workflow-node logic-node ${selected ? 'selected' : ''}`}>
<div className="node-header">
<div className="node-icon">⚡</div>
<div className="node-label">{data.label || 'Logik'}</div>
</div>
<div className="node-body">
<div className={`condition-summary ${hasCondition ? 'has-condition' : 'no-condition'}`}>
{getConditionSummary()}
</div>
</div>
<Handle
type="target"
position={Position.Top}
id="in"
style={{ background: '#FFC107' }}
/>
{/* Zwei Source Handles für True/False Pfade */}
<Handle
type="source"
position={Position.Bottom}
id="true"
style={{ left: '33%', background: '#4CAF50' }}
/>
<Handle
type="source"
position={Position.Bottom}
id="false"
style={{ left: '66%', background: '#F44336' }}
/>
</div>
)
}
@@ -0,0 +1,25 @@
import { Handle, Position } from 'reactflow'
/**
* StartNode - Workflow Einstiegspunkt
*
* Properties:
* - data.label: Node-Label (default: "Start")
* - selected: Boolean (Node ist ausgewählt)
*/
export function StartNode({ data, selected }) {
return (
<div className={`workflow-node start-node ${selected ? 'selected' : ''}`}>
<div className="node-icon">🚀</div>
<div className="node-label">{data.label || 'Start'}</div>
{/* Nur Source Handle (kein Target, da Einstiegspunkt) */}
<Handle
type="source"
position={Position.Bottom}
id="out"
style={{ background: 'var(--accent)' }}
/>
</div>
)
}
@@ -0,0 +1,70 @@
/**
* FallbackConfig - Fallback-Strategie Konfiguration
*
* Props:
* - node: React Flow Node object
* - edges: Array of React Flow edges
* - onChange: (nodeId, updates) => void
*/
export function FallbackConfig({ node, edges, onChange }) {
const fallbackStrategy = node.data.fallback_strategy || 'conservative_skip'
const fallbackEdge = node.data.fallback_edge || null
// Outgoing Edges von diesem Node
const outgoingEdges = edges.filter(e => e.source === node.id)
const handleStrategyChange = (e) => {
const strategy = e.target.value
onChange(node.id, { fallback_strategy: strategy })
// Reset fallback_edge wenn strategy geändert wird
if (strategy === 'conservative_skip' || strategy === 'document_only') {
onChange(node.id, { fallback_edge: null })
}
}
const handleEdgeChange = (e) => {
onChange(node.id, { fallback_edge: e.target.value || null })
}
return (
<div className="config-section">
<h3>Fallback-Strategie</h3>
<label>Strategie bei unklaren Signalen</label>
<select value={fallbackStrategy} onChange={handleStrategyChange}>
<option value="conservative_skip">Konservativ überspringen</option>
<option value="default_path">Standardpfad ausführen</option>
<option value="uncertainty_path">Unsicherheits-Pfad</option>
<option value="document_only">Nur dokumentieren</option>
</select>
<div className="help-text">
{fallbackStrategy === 'conservative_skip' && 'Bei Unklarheit: Pfad nicht routen.'}
{fallbackStrategy === 'default_path' && 'Bei Unklarheit: Definierter Standardpfad wird ausgeführt.'}
{fallbackStrategy === 'uncertainty_path' && 'Bei Unklarheit: Expliziter Klärungspfad.'}
{fallbackStrategy === 'document_only' && 'Unklarheit dokumentieren, aber kein Routing.'}
</div>
{(fallbackStrategy === 'default_path' || fallbackStrategy === 'uncertainty_path') && (
<>
<label style={{ marginTop: '16px' }}>Ziel-Edge</label>
<select value={fallbackEdge || ''} onChange={handleEdgeChange}>
<option value="">-- Kante wählen --</option>
{outgoingEdges.map(e => (
<option key={e.id} value={e.id}>
{e.data?.label || `Edge → ${e.target}`}
</option>
))}
</select>
{outgoingEdges.length === 0 && (
<div className="help-text" style={{ color: 'var(--danger)' }}>
⚠️ Keine ausgehenden Kanten gefunden. Bitte verbinden Sie diesen Node zuerst.
</div>
)}
</>
)}
</div>
)
}
@@ -0,0 +1,67 @@
/**
* JoinConfig - Konfiguration für Join Nodes
*
* Props:
* - node: React Flow Node object (type='join')
* - onChange: (nodeId, updates) => void
*/
export function JoinConfig({ node, onChange }) {
const joinStrategy = node.data.join_strategy || 'wait_all'
const skipHandling = node.data.skip_handling || 'ignore_skipped'
const minPaths = node.data.min_paths || 2
const handleStrategyChange = (e) => {
onChange(node.id, { join_strategy: e.target.value })
}
const handleSkipChange = (e) => {
onChange(node.id, { skip_handling: e.target.value })
}
const handleMinPathsChange = (e) => {
const value = parseInt(e.target.value) || 2
onChange(node.id, { min_paths: value })
}
return (
<div className="config-section">
<h3>Join-Konfiguration</h3>
<label>Join-Strategie</label>
<select value={joinStrategy} onChange={handleStrategyChange}>
<option value="wait_all">Alle Pfade warten (wait_all)</option>
<option value="wait_any">Mindestens ein Pfad (wait_any)</option>
<option value="best_effort">Verfügbare nutzen (best_effort)</option>
</select>
<div className="help-text">
{joinStrategy === 'wait_all' && 'Wartet auf alle eingehenden Pfade. Fehler wenn einer fehlt.'}
{joinStrategy === 'wait_any' && 'Wartet auf mindestens einen Pfad. Erste verfügbare Ausführung.'}
{joinStrategy === 'best_effort' && 'Fehlertoleranz: Nutzt verfügbare Pfade, auch wenn nicht alle da sind.'}
</div>
<label style={{ marginTop: '16px' }}>Skip-Handling</label>
<select value={skipHandling} onChange={handleSkipChange}>
<option value="ignore_skipped">Übersprungene ignorieren</option>
<option value="use_placeholder">Platzhalter verwenden</option>
<option value="require_minimum">Mindestanzahl erforderlich</option>
</select>
{skipHandling === 'require_minimum' && (
<>
<label style={{ marginTop: '12px' }}>Mindestanzahl Pfade</label>
<input
type="number"
min="1"
value={minPaths}
onChange={handleMinPathsChange}
/>
</>
)}
<div className="help-text" style={{ marginTop: '8px', fontSize: '11px', color: 'var(--text3)' }}>
💡 Phase 4: Path Consolidation
</div>
</div>
)
}
@@ -0,0 +1,353 @@
import { useState, useEffect, useMemo } from 'react'
/**
* LogicExpressionEditor - Visueller Baukasten für Logik-Bedingungen
*
* KEIN JSON-Editor! Visuelles Drag & Drop Interface.
*
* Props:
* - node: React Flow Node object (type='logic')
* - nodes: Array of all nodes (for signal reference lookup)
* - edges: Array of all edges (for topological sort)
* - onChange: (nodeId, updates) => void
*/
export function LogicExpressionEditor({ node, nodes, edges, onChange }) {
const [expression, setExpression] = useState(node.data.condition || {
operator: 'and',
operands: []
})
// Verfügbare Signale aus vorangegangenen Nodes
const availableSignals = useMemo(() => {
return getAvailableSignals(node.id, nodes, edges)
}, [node.id, nodes, edges])
// Sync to parent when expression changes
useEffect(() => {
onChange(node.id, { condition: expression })
}, [expression])
const handleOperatorChange = (e) => {
setExpression({ ...expression, operator: e.target.value })
}
const handleAddCondition = () => {
setExpression({
...expression,
operands: [...(expression.operands || []), {
ref: '',
operator: 'eq',
value: ''
}]
})
}
const handleAddGroup = () => {
setExpression({
...expression,
operands: [...(expression.operands || []), {
operator: 'and',
operands: []
}]
})
}
const handleOperandChange = (index, updates) => {
const updated = [...(expression.operands || [])]
updated[index] = { ...updated[index], ...updates }
setExpression({ ...expression, operands: updated })
}
const handleRemoveOperand = (index) => {
setExpression({
...expression,
operands: (expression.operands || []).filter((_, i) => i !== index)
})
}
return (
<div className="config-section">
<h3>Logik-Bedingung</h3>
{availableSignals.length === 0 && (
<div className="help-text" style={{ color: 'var(--danger)', marginBottom: '12px' }}>
⚠️ Keine Signale verfügbar. Fügen Sie zuerst einen Analysis-Node VOR diesem Node hinzu.
</div>
)}
<div className="logic-root">
<label>Verknüpfung (Root-Operator)</label>
<select value={expression.operator || 'and'} onChange={handleOperatorChange}>
<option value="and">UND (alle müssen zutreffen)</option>
<option value="or">ODER (mind. eine muss zutreffen)</option>
<option value="not">NICHT (umkehren)</option>
</select>
</div>
<div className="logic-operands">
{(expression.operands || []).map((operand, idx) => (
<ConditionBlock
key={idx}
operand={operand}
availableSignals={availableSignals}
onChange={(updates) => handleOperandChange(idx, updates)}
onRemove={() => handleRemoveOperand(idx)}
/>
))}
{(!expression.operands || expression.operands.length === 0) && (
<div className="help-text" style={{ marginBottom: '12px' }}>
Keine Bedingungen definiert. Fügen Sie Bedingungen oder Gruppen hinzu.
</div>
)}
</div>
<div className="logic-actions">
<button className="btn-secondary" onClick={handleAddCondition}>
+ Bedingung
</button>
<button className="btn-secondary" onClick={handleAddGroup}>
+ Gruppe (AND/OR)
</button>
</div>
<div className="help-text" style={{ marginTop: '12px', fontSize: '11px', color: 'var(--text3)' }}>
💡 Signale: {availableSignals.length} verfügbar
</div>
</div>
)
}
/**
* ConditionBlock - Einzelne Bedingung oder Gruppe (rekursiv)
*/
function ConditionBlock({ operand, availableSignals, onChange, onRemove }) {
// Verschachtelte Gruppe? (AND/OR/NOT)
const isGroup = operand.operator === 'and' || operand.operator === 'or' || operand.operator === 'not'
if (isGroup) {
return (
<div className="condition-group">
<div className="group-header">
<select
value={operand.operator}
onChange={(e) => onChange({ operator: e.target.value })}
style={{ flex: 1 }}
>
<option value="and">UND</option>
<option value="or">ODER</option>
<option value="not">NICHT</option>
</select>
<button className="btn-icon" onClick={onRemove}>🗑️</button>
</div>
{/* Rekursiv: Nested operands */}
<div style={{ paddingLeft: '12px', borderLeft: '3px solid var(--accent)' }}>
{(operand.operands || []).map((subOp, idx) => (
<ConditionBlock
key={idx}
operand={subOp}
availableSignals={availableSignals}
onChange={(updates) => {
const updated = [...(operand.operands || [])]
updated[idx] = { ...updated[idx], ...updates }
onChange({ operands: updated })
}}
onRemove={() => {
onChange({ operands: (operand.operands || []).filter((_, i) => i !== idx) })
}}
/>
))}
<button
className="btn-secondary"
onClick={() => {
onChange({
operands: [...(operand.operands || []), { ref: '', operator: 'eq', value: '' }]
})
}}
style={{ marginTop: '8px', fontSize: '12px' }}
>
+ Bedingung
</button>
</div>
</div>
)
}
// Einfache Bedingung
const selectedSignal = availableSignals.find(s => s.ref === operand.ref)
return (
<div className="condition-simple">
{/* Signal-Referenz (Dropdown) */}
<select
value={operand.ref || ''}
onChange={(e) => onChange({ ref: e.target.value })}
className="signal-select"
style={{ flex: 2 }}
>
<option value="">-- Signal wählen --</option>
{availableSignals.map(sig => (
<option key={sig.ref} value={sig.ref}>
{sig.label}
</option>
))}
</select>
{/* Operator */}
<select
value={operand.operator || 'eq'}
onChange={(e) => onChange({ operator: e.target.value })}
className="operator-select"
style={{ flex: 1 }}
>
<option value="eq">==</option>
<option value="neq">!=</option>
<option value="in">IN</option>
<option value="not_in">NOT IN</option>
<option value="gt">&gt;</option>
<option value="lt">&lt;</option>
<option value="gte">&gt;=</option>
<option value="lte">&lt;=</option>
<option value="contains">CONTAINS</option>
</select>
{/* Wert (abhängig von Operator) */}
{(operand.operator === 'in' || operand.operator === 'not_in') ? (
<MultiSelect
options={selectedSignal?.spectrum || []}
value={operand.value || []}
onChange={(val) => onChange({ value: val })}
placeholder="Werte wählen"
/>
) : (
<input
type="text"
value={operand.value || ''}
onChange={(e) => onChange({ value: e.target.value })}
placeholder="Wert"
className="value-input"
style={{ flex: 1 }}
/>
)}
<button className="btn-icon" onClick={onRemove}>🗑️</button>
</div>
)
}
/**
* MultiSelect - Multi-Auswahl für IN/NOT_IN Operatoren
*/
function MultiSelect({ options, value, onChange, placeholder }) {
const [isOpen, setIsOpen] = useState(false)
const selected = Array.isArray(value) ? value : []
const handleToggle = (option) => {
if (selected.includes(option)) {
onChange(selected.filter(v => v !== option))
} else {
onChange([...selected, option])
}
}
return (
<div className="multi-select" style={{ flex: 1, position: 'relative' }}>
<div
className="multi-select-display"
onClick={() => setIsOpen(!isOpen)}
style={{
padding: '6px',
border: '1px solid var(--border)',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '12px',
background: 'var(--bg)'
}}
>
{selected.length > 0 ? selected.join(', ') : placeholder}
</div>
{isOpen && (
<div
className="multi-select-dropdown"
style={{
position: 'absolute',
top: '100%',
left: 0,
right: 0,
background: 'var(--surface)',
border: '1px solid var(--border)',
borderRadius: '4px',
marginTop: '4px',
maxHeight: '200px',
overflowY: 'auto',
zIndex: 1000
}}
>
{options.map((option, i) => (
<div
key={i}
onClick={() => handleToggle(option)}
style={{
padding: '8px',
cursor: 'pointer',
fontSize: '12px',
background: selected.includes(option) ? 'var(--accent)' : 'transparent',
color: selected.includes(option) ? 'white' : 'var(--text1)'
}}
>
{selected.includes(option) && '✓ '}
{option}
</div>
))}
{options.length === 0 && (
<div style={{ padding: '8px', fontSize: '12px', color: 'var(--text3)' }}>
Keine Optionen verfügbar
</div>
)}
</div>
)}
</div>
)
}
/**
* Helper: Verfügbare Signale aus vorangegangenen Nodes extrahieren
*/
function getAvailableSignals(nodeId, nodes, edges) {
// Topologische Sortierung: Alle Nodes VOR diesem Node
const predecessors = new Set()
function collectPredecessors(currentId) {
const incoming = edges.filter(e => e.target === currentId)
for (const edge of incoming) {
if (!predecessors.has(edge.source)) {
predecessors.add(edge.source)
collectPredecessors(edge.source)
}
}
}
collectPredecessors(nodeId)
// Signale extrahieren (nur von ANALYSIS Nodes)
const signals = []
for (const predId of predecessors) {
const predNode = nodes.find(n => n.id === predId)
if (predNode && predNode.type === 'analysis') {
const questions = predNode.data.questions || []
for (const q of questions) {
signals.push({
ref: `${predId}.${q.id}`,
label: `${predNode.data.label} → ${q.question || q.id}`,
spectrum: q.answer_spectrum || []
})
}
}
}
return signals
}
@@ -0,0 +1,218 @@
import { useState, useEffect } from 'react'
/**
* QuestionAugmentationPanel - Fragenergänzungs-Konfiguration
*
* Props:
* - node: React Flow Node object (type='analysis')
* - onChange: (nodeId, updates) => void
*/
export function QuestionAugmentationPanel({ node, onChange }) {
const [questions, setQuestions] = useState(node.data.questions || [])
// Sync to parent when questions change
useEffect(() => {
onChange(node.id, { questions })
}, [questions])
const handleAddQuestion = () => {
const newQuestion = {
id: `q${Date.now()}`,
type: 'relevanz',
question: '',
answer_spectrum: []
}
setQuestions([...questions, newQuestion])
}
const handleRemoveQuestion = (index) => {
setQuestions(questions.filter((_, i) => i !== index))
}
const handleQuestionChange = (index, field, value) => {
const updated = [...questions]
updated[index] = { ...updated[index], [field]: value }
setQuestions(updated)
}
return (
<div className="config-section">
<h3>Fragenergänzung</h3>
{questions.length === 0 && (
<div className="help-text" style={{ marginBottom: '12px' }}>
Keine Fragen definiert. Fügen Sie Fragen hinzu, um Signale für Logik-Knoten zu erzeugen.
</div>
)}
{questions.map((q, idx) => (
<QuestionEditor
key={q.id}
question={q}
index={idx}
onChange={(field, value) => handleQuestionChange(idx, field, value)}
onRemove={() => handleRemoveQuestion(idx)}
/>
))}
<button className="btn-secondary btn-full" onClick={handleAddQuestion}>
+ Frage hinzufügen
</button>
</div>
)
}
/**
* QuestionEditor - Einzelne Frage editieren
*/
function QuestionEditor({ question, index, onChange, onRemove }) {
const [spectrumInput, setSpectrumInput] = useState('')
const handleAddAnswer = () => {
if (!spectrumInput.trim()) return
const newSpectrum = [...(question.answer_spectrum || []), spectrumInput.trim()]
onChange('answer_spectrum', newSpectrum)
setSpectrumInput('')
}
const handleRemoveAnswer = (answer) => {
const newSpectrum = question.answer_spectrum.filter(a => a !== answer)
onChange('answer_spectrum', newSpectrum)
}
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
e.preventDefault()
handleAddAnswer()
}
}
return (
<div className="question-editor">
<div className="question-header">
<span>Frage {index + 1}</span>
<button className="btn-icon" onClick={onRemove} title="Frage löschen">
🗑️
</button>
</div>
<label>Frage-ID</label>
<input
type="text"
value={question.id || ''}
onChange={(e) => onChange('id', e.target.value)}
placeholder="z.B. relevanz"
/>
<label>Fragetyp</label>
<select
value={question.type || 'relevanz'}
onChange={(e) => onChange('type', e.target.value)}
>
<option value="relevanz">Relevanz</option>
<option value="prioritaet">Priorität</option>
<option value="selektion">Selektion</option>
<option value="ausschluss">Ausschluss</option>
<option value="eskalation">Eskalation</option>
<option value="unsicherheit">Unsicherheit</option>
</select>
<label>Fragetext</label>
<textarea
value={question.question || ''}
onChange={(e) => onChange('question', e.target.value)}
placeholder="z.B. Ist diese Analyse relevant für den Nutzer?"
rows={3}
/>
<label>Antwortmöglichkeiten (mind. 2)</label>
<div className="tag-input-container">
<div className="tags">
{(question.answer_spectrum || []).map((answer, i) => (
<span key={i} className="tag">
{answer}
<button
onClick={() => handleRemoveAnswer(answer)}
className="tag-remove"
title="Entfernen"
>
×
</button>
</span>
))}
</div>
<div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
<input
type="text"
value={spectrumInput}
onChange={(e) => setSpectrumInput(e.target.value)}
onKeyPress={handleKeyPress}
placeholder="z.B. ja, nein, unklar"
style={{ flex: 1 }}
/>
<button className="btn-secondary" onClick={handleAddAnswer}>
+
</button>
</div>
</div>
{question.answer_spectrum && question.answer_spectrum.length < 2 && (
<div className="help-text" style={{ color: 'var(--danger)' }}>
⚠️ Mindestens 2 Antworten erforderlich
</div>
)}
</div>
)
}
// Zusätzliches CSS für Tags (inline styles)
const tagStyles = `
.tag-input-container {
margin-bottom: 8px;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 8px;
}
.tag {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 4px 8px;
background: var(--accent);
color: white;
border-radius: 4px;
font-size: 12px;
font-weight: 500;
}
.tag-remove {
background: none;
border: none;
color: white;
cursor: pointer;
font-size: 16px;
line-height: 1;
padding: 0;
margin-left: 2px;
opacity: 0.8;
}
.tag-remove:hover {
opacity: 1;
}
`
// Inject styles (nur einmal)
if (typeof document !== 'undefined' && !document.getElementById('question-panel-styles')) {
const styleEl = document.createElement('style')
styleEl.id = 'question-panel-styles'
styleEl.textContent = tagStyles
document.head.appendChild(styleEl)
}