Files
mitai-jinkendo/frontend/src/components/PromptEditModal.jsx
T
LarsandClaude Opus 4.6 5e7ef718e0
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
fix: placeholder picker improvements + insight display names (Issue #28)
Backend:
- get_placeholder_catalog(): grouped placeholders with descriptions
- Returns {category: [{key, description, example}]} format
- Categories: Profil, Körper, Ernährung, Training, Schlaf, Vitalwerte, Zeitraum

Frontend - Placeholder Picker:
- Grouped by category with visual separation
- Search/filter across keys and descriptions
- Hover effects for better UX
- Insert at cursor position (not at end)
- Shows: key + description + example value
- 'Keine Platzhalter gefunden' message when filtered

Frontend - Insight Display Names:
- InsightCard receives prompts array
- Finds matching prompt by scope/slug
- Shows prompt.display_name instead of hardcoded SLUG_LABELS
- History tab also shows display_name in group headers
- Fallback chain: display_name → SLUG_LABELS → scope

User-facing improvements:
✓ Platzhalter zeigen echte Daten statt Zahlen
✓ Durchsuchbar + filterbar
✓ Einfügen an Cursor-Position
✓ Insights zeigen custom Namen (z.B. '🍽️ Meine Ernährung')

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 06:44:22 +01:00

565 lines
19 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState, useEffect } from 'react'
import { api } from '../utils/api'
import PromptGenerator from './PromptGenerator'
export default function PromptEditModal({ prompt, onSave, onClose }) {
const [name, setName] = useState('')
const [slug, setSlug] = useState('')
const [displayName, setDisplayName] = useState('')
const [description, setDescription] = useState('')
const [category, setCategory] = useState('ganzheitlich')
const [template, setTemplate] = useState('')
const [active, setActive] = useState(true)
const [preview, setPreview] = useState(null)
const [unknownPlaceholders, setUnknownPlaceholders] = useState([])
const [showGenerator, setShowGenerator] = useState(false)
const [showPlaceholders, setShowPlaceholders] = useState(false)
const [placeholders, setPlaceholders] = useState({})
const [placeholderFilter, setPlaceholderFilter] = useState('')
const [templateRef, setTemplateRef] = useState(null)
const [optimization, setOptimization] = useState(null)
const [loading, setLoading] = useState(false)
const [saving, setSaving] = useState(false)
const categories = [
{ id: 'körper', label: 'Körper' },
{ id: 'ernährung', label: 'Ernährung' },
{ id: 'training', label: 'Training' },
{ id: 'schlaf', label: 'Schlaf' },
{ id: 'vitalwerte', label: 'Vitalwerte' },
{ id: 'ziele', label: 'Ziele' },
{ id: 'ganzheitlich', label: 'Ganzheitlich' }
]
useEffect(() => {
if (prompt) {
setName(prompt.name || '')
setSlug(prompt.slug || '')
setDisplayName(prompt.display_name || '')
setDescription(prompt.description || '')
setCategory(prompt.category || 'ganzheitlich')
setTemplate(prompt.template || '')
setActive(prompt.active ?? true)
}
}, [prompt])
const handlePreview = async () => {
try {
setLoading(true)
const result = await api.previewPrompt(template)
setPreview(result.resolved)
setUnknownPlaceholders(result.unknown_placeholders || [])
} catch (e) {
alert('Fehler bei Vorschau: ' + e.message)
} finally {
setLoading(false)
}
}
const handleOptimize = async () => {
if (!prompt?.id) {
alert('Prompt muss erst gespeichert werden bevor er optimiert werden kann')
return
}
try {
setLoading(true)
const result = await api.optimizePrompt(prompt.id)
setOptimization(result)
} catch (e) {
alert('Fehler bei Optimierung: ' + e.message)
} finally {
setLoading(false)
}
}
const handleApplyOptimized = () => {
if (optimization?.optimized_prompt) {
setTemplate(optimization.optimized_prompt)
setOptimization(null)
}
}
const handleSave = async () => {
if (!name.trim()) {
alert('Bitte Titel eingeben')
return
}
if (!template.trim()) {
alert('Bitte Template eingeben')
return
}
try {
setSaving(true)
if (prompt?.id) {
// Update existing
await api.updatePrompt(prompt.id, {
name,
display_name: displayName || null,
description,
category,
template,
active
})
} else {
// Create new
if (!slug.trim()) {
alert('Bitte Slug eingeben')
return
}
await api.createPrompt({
name,
slug,
display_name: displayName || null,
description,
category,
template,
active
})
}
onSave()
} catch (e) {
alert('Fehler beim Speichern: ' + e.message)
} finally {
setSaving(false)
}
}
const handleGeneratorResult = (generated) => {
setName(generated.suggested_title)
setCategory(generated.suggested_category)
setTemplate(generated.template)
setShowGenerator(false)
// Auto-generate slug if new prompt
if (!prompt?.id) {
const autoSlug = generated.suggested_title
.toLowerCase()
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
setSlug(autoSlug)
}
}
const loadPlaceholders = async () => {
try {
const data = await api.listPlaceholders()
setPlaceholders(data)
setShowPlaceholders(true)
setPlaceholderFilter('')
} catch (e) {
alert('Fehler beim Laden der Platzhalter: ' + e.message)
}
}
const insertPlaceholder = (key) => {
if (!templateRef) {
// Fallback: append at end
setTemplate(prev => prev + ` {{${key}}}`)
} else {
// Insert at cursor position
const start = templateRef.selectionStart
const end = templateRef.selectionEnd
const text = template
const before = text.substring(0, start)
const after = text.substring(end)
const inserted = `{{${key}}}`
setTemplate(before + inserted + after)
// Set cursor position after inserted placeholder
setTimeout(() => {
templateRef.selectionStart = templateRef.selectionEnd = start + inserted.length
templateRef.focus()
}, 0)
}
setShowPlaceholders(false)
}
return (
<div style={{
position:'fixed', inset:0, background:'rgba(0,0,0,0.5)',
display:'flex', alignItems:'center', justifyContent:'center',
zIndex:1000, padding:20
}}>
<div style={{
background:'var(--bg)', borderRadius:12, maxWidth:900, width:'100%',
maxHeight:'90vh', overflow:'auto', padding:24
}}>
<h2 style={{margin:'0 0 24px 0', fontSize:20, fontWeight:600}}>
{prompt ? 'Prompt bearbeiten' : 'Neuer Prompt'}
</h2>
{/* Action Buttons */}
<div style={{display:'flex', gap:8, marginBottom:24, flexWrap:'wrap'}}>
<button
className="btn"
onClick={() => setShowGenerator(true)}
style={{fontSize:13}}
>
🤖 Von KI erstellen lassen
</button>
{prompt?.id && (
<button
className="btn"
onClick={handleOptimize}
disabled={loading}
style={{fontSize:13}}
>
✨ Von KI optimieren lassen
</button>
)}
<button
className="btn"
onClick={handlePreview}
disabled={loading || !template.trim()}
style={{fontSize:13}}
>
👁️ Vorschau
</button>
</div>
{/* Form Fields */}
<div style={{display:'grid', gap:20, marginBottom:24}}>
<div>
<label className="form-label" style={{display:'block', marginBottom:6}}>Titel *</label>
<input
className="form-input"
value={name}
onChange={e => setName(e.target.value)}
placeholder="z.B. Protein-Analyse"
style={{width:'100%', textAlign:'left'}}
/>
</div>
{!prompt?.id && (
<div>
<label className="form-label" style={{display:'block', marginBottom:6}}>
Slug * (eindeutig, keine Leerzeichen)
</label>
<input
className="form-input"
value={slug}
onChange={e => setSlug(e.target.value)}
placeholder="z.B. protein_analyse"
style={{width:'100%', textAlign:'left'}}
/>
</div>
)}
<div>
<label className="form-label" style={{display:'block', marginBottom:6}}>
Anzeigename (in der Anwendung sichtbar)
</label>
<input
className="form-input"
value={displayName}
onChange={e => setDisplayName(e.target.value)}
placeholder="z.B. 🍽️ Protein-Analyse"
style={{width:'100%', textAlign:'left'}}
/>
<div style={{fontSize:11, color:'var(--text3)', marginTop:4}}>
Leer lassen = Titel wird verwendet
</div>
</div>
<div>
<label className="form-label" style={{display:'block', marginBottom:6}}>Beschreibung</label>
<textarea
className="form-input"
value={description}
onChange={e => setDescription(e.target.value)}
rows={2}
placeholder="Wofür ist dieser Prompt? (für Admin sichtbar)"
style={{width:'100%', textAlign:'left', resize:'vertical'}}
/>
</div>
<div>
<label className="form-label" style={{display:'block', marginBottom:6}}>Kategorie</label>
<select
className="form-select"
value={category}
onChange={e => setCategory(e.target.value)}
style={{width:'100%'}}
>
{categories.map(cat => (
<option key={cat.id} value={cat.id}>{cat.label}</option>
))}
</select>
</div>
<div>
<label className="form-label" style={{display:'block', marginBottom:6}}>Template *</label>
<textarea
ref={el => setTemplateRef(el)}
className="form-input"
value={template}
onChange={e => setTemplate(e.target.value)}
rows={15}
placeholder="Du bist ein Ernährungsexperte. Analysiere folgende Daten: {{nutrition_summary}}"
style={{width:'100%', textAlign:'left', fontFamily:'monospace', fontSize:12, resize:'vertical'}}
/>
<div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:6}}>
<div style={{fontSize:11, color:'var(--text3)'}}>
Nutze Platzhalter wie {`{{weight_aktuell}}`}, {`{{protein_avg}}`}, etc.
</div>
<button
className="btn"
onClick={loadPlaceholders}
type="button"
style={{fontSize:12, padding:'4px 10px'}}
>
📋 Platzhalter einfügen
</button>
</div>
{/* Placeholders Dropdown */}
{showPlaceholders && Object.keys(placeholders).length > 0 && (
<div style={{
marginTop:8, padding:16, background:'var(--surface)',
border:'1px solid var(--border)', borderRadius:8,
maxHeight:400, overflow:'auto'
}}>
<div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:12}}>
<strong style={{fontSize:14}}>Platzhalter einfügen</strong>
<button
onClick={() => setShowPlaceholders(false)}
style={{
background:'none', border:'none', cursor:'pointer',
fontSize:20, color:'var(--text3)', padding:0
}}
>
×
</button>
</div>
{/* Search Filter */}
<input
type="text"
placeholder="Suchen..."
value={placeholderFilter}
onChange={e => setPlaceholderFilter(e.target.value)}
style={{
width:'100%', padding:'6px 10px', marginBottom:12,
background:'var(--surface2)', border:'1px solid var(--border)',
borderRadius:6, fontSize:12
}}
/>
{/* Grouped Placeholders */}
{Object.entries(placeholders).map(([category, items]) => {
// Filter items
const filteredItems = items.filter(p =>
placeholderFilter === '' ||
p.key.toLowerCase().includes(placeholderFilter.toLowerCase()) ||
p.description.toLowerCase().includes(placeholderFilter.toLowerCase())
)
if (filteredItems.length === 0) return null
return (
<div key={category} style={{marginBottom:16}}>
<div style={{
fontSize:11, fontWeight:600, color:'var(--text3)',
textTransform:'uppercase', letterSpacing:'0.5px',
marginBottom:6
}}>
{category}
</div>
<div style={{display:'grid', gap:6}}>
{filteredItems.map((p, i) => (
<button
key={i}
onClick={() => insertPlaceholder(p.key)}
style={{
textAlign:'left', padding:'8px 10px',
background:'var(--surface2)', border:'1px solid var(--border)',
borderRadius:6, cursor:'pointer',
transition:'all 0.15s'
}}
onMouseEnter={e => {
e.currentTarget.style.background = 'var(--accent-light)'
e.currentTarget.style.borderColor = 'var(--accent)'
}}
onMouseLeave={e => {
e.currentTarget.style.background = 'var(--surface2)'
e.currentTarget.style.borderColor = 'var(--border)'
}}
>
<div style={{
fontWeight:600, fontSize:12, fontFamily:'monospace',
color:'var(--accent)', marginBottom:2
}}>
{`{{${p.key}}}`}
</div>
<div style={{fontSize:11, color:'var(--text2)', marginBottom:2}}>
{p.description}
</div>
<div style={{fontSize:10, color:'var(--text3)', fontStyle:'italic'}}>
Beispiel: {p.example}
</div>
</button>
))}
</div>
</div>
)
})}
{/* No results */}
{placeholderFilter && Object.values(placeholders).every(items =>
items.filter(p =>
p.key.toLowerCase().includes(placeholderFilter.toLowerCase()) ||
p.description.toLowerCase().includes(placeholderFilter.toLowerCase())
).length === 0
) && (
<div style={{textAlign:'center', padding:20, color:'var(--text3)', fontSize:12}}>
Keine Platzhalter gefunden für "{placeholderFilter}"
</div>
)}
</div>
)}
</div>
<div style={{display:'flex', alignItems:'center', gap:8}}>
<input
type="checkbox"
checked={active}
onChange={e => setActive(e.target.checked)}
id="active-checkbox"
/>
<label htmlFor="active-checkbox" style={{margin:0, cursor:'pointer'}}>
Prompt ist aktiv (für Nutzer sichtbar)
</label>
</div>
</div>
{/* Unknown Placeholders Warning */}
{unknownPlaceholders.length > 0 && (
<div style={{
padding:12, background:'#fff3cd', border:'1px solid #ffc107',
borderRadius:8, marginBottom:16, fontSize:12
}}>
<strong>⚠️ Unbekannte Platzhalter:</strong> {unknownPlaceholders.join(', ')}
</div>
)}
{/* Preview */}
{preview && (
<div style={{marginBottom:24}}>
<h3 style={{fontSize:14, fontWeight:600, marginBottom:8}}>
Vorschau (mit echten Daten):
</h3>
<pre style={{
background:'var(--surface2)', padding:16, borderRadius:8,
fontSize:12, lineHeight:1.6, whiteSpace:'pre-wrap',
maxHeight:300, overflow:'auto'
}}>
{preview}
</pre>
</div>
)}
{/* Optimization Results */}
{optimization && (
<div style={{
marginBottom:24, padding:16, background:'var(--surface)',
border:'1px solid var(--border)', borderRadius:8
}}>
<h3 style={{fontSize:16, fontWeight:600, marginBottom:12}}>
✨ Optimierungsvorschläge
</h3>
<div style={{display:'grid', gap:12, fontSize:13}}>
<div>
<strong>Score:</strong> {optimization.score}/100
</div>
<div>
<strong>✅ Stärken:</strong>
<ul style={{marginTop:4, paddingLeft:20}}>
{optimization.strengths?.map((s, i) => (
<li key={i}>{s}</li>
))}
</ul>
</div>
<div>
<strong>⚠️ Verbesserungspotenzial:</strong>
<ul style={{marginTop:4, paddingLeft:20}}>
{optimization.weaknesses?.map((w, i) => (
<li key={i}>{w}</li>
))}
</ul>
</div>
<div>
<strong>Änderungen:</strong>
<p style={{marginTop:4}}>{optimization.changes_summary}</p>
</div>
{/* Side-by-side comparison */}
<div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
<div>
<strong>Original:</strong>
<pre style={{
marginTop:4, padding:12, background:'var(--surface2)',
borderRadius:8, fontSize:11, maxHeight:200, overflow:'auto',
whiteSpace:'pre-wrap', wordBreak:'break-word'
}}>
{template}
</pre>
</div>
<div>
<strong>Optimiert:</strong>
<pre style={{
marginTop:4, padding:12, background:'#d4edda',
borderRadius:8, fontSize:11, maxHeight:200, overflow:'auto',
whiteSpace:'pre-wrap', wordBreak:'break-word'
}}>
{optimization.optimized_prompt}
</pre>
</div>
</div>
<button
className="btn btn-primary"
onClick={handleApplyOptimized}
>
✅ Optimierte Version übernehmen
</button>
</div>
</div>
)}
{/* Actions */}
<div style={{display:'flex', gap:12, justifyContent:'flex-end'}}>
<button className="btn" onClick={onClose}>
Abbrechen
</button>
<button
className="btn btn-primary"
onClick={handleSave}
disabled={saving}
>
{saving ? 'Speichern...' : 'Speichern'}
</button>
</div>
{/* Generator Modal */}
{showGenerator && (
<PromptGenerator
onGenerated={handleGeneratorResult}
onClose={() => setShowGenerator(false)}
/>
)}
</div>
</div>
)
}