feat: theme-grouped pickers, theme-session content panel, theme/topic naming
All checks were successful
On Push to Main / test (push) Successful in 42s
On Push to Main / publish (push) Successful in 1m17s
On Push to Main / deploy-dev (push) Successful in 1m56s

- Admin Topic Quizzes (was Quizzes): topics are now grouped under
  collapsible theme headers with per-theme counts. Topics without a
  theme fall into a "No theme" bucket rendered last.
- /topic-test picker: eligible topics grouped by theme so learners can
  scan a curriculum theme and drill its topics on demand.
- Fix admin Theme Content panel (was Learning Content): it was empty
  because content moved to the theme_sessions collection in an earlier
  refactor while the panel still queried the legacy per-topic content
  table. Rewrites ContentManager to read db.getAllThemeSessions and
  render the emit_theme_session schema (title, intro, topic sections,
  connections, key takeaways). Adds db.getAllThemeSessions and
  db.deleteThemeSession.
- Disambiguate theme vs topic across the app: the weekly curriculum
  test is now "Theme Test" (nav, page heading, Dashboard card, button,
  explainer); the on-demand bank test stays "Topic Test". Admin nav
  also clarified to "Theme Content" / "Topic Quizzes".

No schema changes. 85/85 tests still pass, build green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
RaymondVerhoef
2026-06-02 16:37:50 +02:00
parent 43a71e2110
commit 218f6e7d64
8 changed files with 336 additions and 205 deletions

View File

@@ -1,214 +1,238 @@
import { useState, useEffect } from 'react';
import {
RefreshCw, Wand2, Trash2, CheckCircle, Loader,
AlertCircle, BookOpen, ArrowLeft, Eye
Trash2, Loader, AlertCircle, BookOpen, ArrowLeft, Eye, Clock, Layers,
} from 'lucide-react';
import { getAllGeneratedContent, generateLearningContent, refineLearningContent, deleteCachedContent } from '../../lib/learningService';
import LearningContentViewer from '../ui/LearningContentViewer';
import * as db from '../../lib/db';
import Card from '../ui/Card';
import Button from '../ui/Button';
import Tag from '../ui/Tag';
// Admin "Learning content" panel.
//
// The Learn flow stores generated content in the `theme_sessions` PB collection
// — one record per (curriculum_version, week_number, theme). The legacy
// per-topic `content` collection is no longer fed by the user-facing flow, so
// this panel surfaces theme sessions instead. View shows the full session,
// Delete removes the record (next visitor to that week will regenerate it).
const ContentManager = () => {
const [items, setItems] = useState([]);
const [selected, setSelected] = useState(null); // { topic, content } — the open detail view
const [actionState, setActionState] = useState({}); // { [topicId]: { loading, error, success } }
const [refineText, setRefineText] = useState('');
const [sessions, setSessions] = useState([]);
const [loading, setLoading] = useState(true);
const [selected, setSelected] = useState(null);
const [busyId, setBusyId] = useState(null);
const [error, setError] = useState(null);
const refresh = async () => {
const fresh = await getAllGeneratedContent();
setItems(fresh);
// Keep detail view in sync if its topic was updated
if (selected) {
const updated = fresh.find(i => i.topic.id === selected.topic.id);
if (updated) setSelected(updated);
setLoading(true);
setError(null);
try {
const fresh = await db.getAllThemeSessions();
setSessions(fresh);
if (selected) {
const updated = fresh.find(s => s.id === selected.id);
if (updated) setSelected(updated);
else setSelected(null);
}
} catch (e) {
setError(e.message);
} finally {
setLoading(false);
}
};
useEffect(() => { refresh(); }, []);
const setTopicState = (id, patch) =>
setActionState(prev => ({ ...prev, [id]: { ...prev[id], ...patch } }));
const handleRegenerate = async (topic) => {
setTopicState(topic.id, { loading: 'regenerating', error: null, success: null });
const handleDelete = async (id) => {
if (!confirm('Delete this theme session? The next learner to open this week will regenerate it with the AI.')) return;
setBusyId(id);
setError(null);
try {
await generateLearningContent(topic, true, 'all');
setTopicState(topic.id, { loading: null, success: 'Content regenerated.' });
refresh();
await db.deleteThemeSession(id);
if (selected?.id === id) setSelected(null);
await refresh();
} catch (e) {
setTopicState(topic.id, { loading: null, error: e.message });
setError(e.message);
} finally {
setBusyId(null);
}
};
const handleRefine = async (topic) => {
const instruction = refineText.trim();
if (!instruction) return;
setTopicState(topic.id, { loading: 'refining', error: null, success: null });
try {
await refineLearningContent(topic, instruction);
setTopicState(topic.id, { loading: null, success: 'Content refined.' });
setRefineText('');
refresh();
} catch (e) {
setTopicState(topic.id, { loading: null, error: e.message });
}
};
// ─── Loading ──────────────────────────────────────────────
if (loading && sessions.length === 0) {
return (
<div className="text-center py-16 text-fg-muted">
<Loader size={36} className="mx-auto mb-3 animate-spin text-teal" />
<p className="text-sm">Loading theme sessions</p>
</div>
);
}
const handleDelete = async (topicId) => {
await deleteCachedContent(topicId);
if (selected?.topic.id === topicId) setSelected(null);
setActionState(prev => { const n = { ...prev }; delete n[topicId]; return n; });
refresh();
};
// ─── Empty state ──────────────────────────────────────────
if (items.length === 0) {
// ─── Empty ────────────────────────────────────────────────
if (!loading && sessions.length === 0) {
return (
<div className="text-center py-16 text-fg-muted">
<BookOpen size={48} className="mx-auto mb-4 text-teal/30" />
<p className="font-medium">No generated content yet.</p>
<p className="text-sm mt-1">Upload sources then visit the Learn page to generate content.</p>
<p className="font-medium">No theme sessions generated yet.</p>
<p className="text-sm mt-1">
When a learner opens the Learn page for a week with an active curriculum,
its theme session is generated and cached here.
</p>
{error && (
<p className="text-sm text-red-600 mt-3 flex items-center gap-1 justify-center">
<AlertCircle size={14} /> {error}
</p>
)}
</div>
);
}
// ─── Detail view ──────────────────────────────────────────
if (selected) {
const { topic, content } = selected;
const state = actionState[topic.id] || {};
const isLoading = !!state.loading;
const content = selected.content || {};
const topicSections = Array.isArray(content.topicSections) ? content.topicSections : [];
const takeaways = Array.isArray(content.keyTakeaways) ? content.keyTakeaways : [];
return (
<div className="animate-in fade-in duration-200">
{/* Back + header */}
<div className="flex items-start justify-between mb-6 gap-4 flex-wrap">
<div>
<button
onClick={() => setSelected(null)}
className="flex items-center gap-2 text-sm text-fg-muted hover:text-teal transition-colors mb-3"
>
<ArrowLeft size={16} /> Back to all content
<ArrowLeft size={16} /> Back to all theme sessions
</button>
<div className="flex items-center gap-2 flex-wrap">
<h2 className="text-2xl font-bold">{topic.label}</h2>
<span className="font-mono text-xs bg-bg-warm px-2 py-0.5 rounded-full text-fg-muted">{topic.type}</span>
<h2 className="text-2xl font-bold">{content.title || selected.theme || 'Untitled theme session'}</h2>
<Tag variant="accent" className="text-xs">Week {selected.week_number}</Tag>
{selected.theme && <Tag variant="dark" className="text-xs">{selected.theme}</Tag>}
</div>
<p className="text-fg-muted text-sm mt-1">{topic.description}</p>
{selected.updated && (
<p className="text-fg-muted text-xs mt-1 flex items-center gap-1">
<Clock size={12} /> Updated {new Date(selected.updated).toLocaleString()}
</p>
)}
</div>
{/* Action buttons */}
<div className="flex gap-2 flex-shrink-0">
<Button
variant="outline"
onClick={() => handleRegenerate(topic)}
disabled={isLoading}
>
{state.loading === 'regenerating'
? <Loader size={16} className="mr-2 animate-spin" />
: <RefreshCw size={16} className="mr-2" />}
Regenerate
</Button>
<Button
variant="outline"
onClick={() => handleDelete(topic.id)}
disabled={isLoading}
className="border-red-200 text-red-600 hover:bg-red-50"
>
<Trash2 size={16} className="mr-2" /> Delete
</Button>
</div>
<Button
variant="outline"
onClick={() => handleDelete(selected.id)}
disabled={busyId === selected.id}
className="border-red-200 text-red-600 hover:bg-red-50"
>
{busyId === selected.id
? <Loader size={16} className="mr-2 animate-spin" />
: <Trash2 size={16} className="mr-2" />}
Delete
</Button>
</div>
{/* Status bar */}
{(state.success || state.error) && (
<div className={`mb-6 p-3 rounded-[var(--r-sm)] text-sm flex items-center gap-2 ${state.error ? 'bg-red-50 text-red-800' : 'bg-teal-50 text-teal-800'}`}>
{state.error ? <AlertCircle size={16} /> : <CheckCircle size={16} />}
{state.error || state.success}
{error && (
<div className="mb-6 p-3 rounded-[var(--r-sm)] bg-red-50 text-red-800 text-sm flex items-center gap-2">
<AlertCircle size={16} /> {error}
</div>
)}
{/* Full content preview */}
<LearningContentViewer content={content} topic={topic} />
{content.intro && (
<Card className="border border-bg-warm mb-6">
<h3 className="font-bold text-base mb-2">Introduction</h3>
<p className="text-sm leading-relaxed text-fg whitespace-pre-line">{content.intro}</p>
</Card>
)}
{/* Refine panel */}
<Card className="border border-teal/30 mt-8">
<h3 className="font-bold text-lg mb-1 flex items-center gap-2">
<Wand2 size={18} className="text-teal" /> Refine with AI
</h3>
<p className="text-sm text-fg-muted mb-4">
Review the content above, then describe what should change. Be specific the AI will apply your instruction and update all content formats.
</p>
<textarea
value={refineText}
onChange={(e) => setRefineText(e.target.value)}
placeholder='e.g. "Make the article more beginner-friendly and add a real-world example to each slide."'
rows={4}
className="w-full p-3 rounded-[var(--r-sm)] border border-bg-warm bg-bg text-sm resize-none focus:outline-none focus:ring-2 focus:ring-teal/30"
disabled={isLoading}
/>
<div className="flex justify-end mt-3">
<Button
onClick={() => handleRefine(topic)}
disabled={isLoading || !refineText.trim()}
>
{state.loading === 'refining'
? <><Loader size={16} className="mr-2 animate-spin" /> Refining...</>
: <><Wand2 size={16} className="mr-2" /> Apply Refinement</>}
</Button>
{topicSections.length > 0 && (
<div className="space-y-3 mb-6">
<h3 className="font-bold">Topics covered</h3>
{topicSections.map((s, i) => (
<Card key={s.topic_id || i} className="border border-bg-warm">
<div className="flex items-center gap-2 mb-2 flex-wrap">
<span className="font-semibold">{s.label}</span>
{s.topic_id && (
<span className="font-mono text-[10px] bg-bg-warm px-1.5 py-0.5 rounded text-fg-muted">{s.topic_id}</span>
)}
</div>
<div
className="text-sm prose prose-sm max-w-none text-fg leading-relaxed"
dangerouslySetInnerHTML={{ __html: s.summary || '' }}
/>
</Card>
))}
</div>
</Card>
)}
{content.connections && (
<Card className="border border-bg-warm mb-6">
<h3 className="font-bold text-base mb-2">How these topics connect</h3>
<div
className="text-sm prose prose-sm max-w-none text-fg leading-relaxed"
dangerouslySetInnerHTML={{ __html: content.connections }}
/>
</Card>
)}
{takeaways.length > 0 && (
<Card className="border border-teal/30 bg-teal/5">
<h3 className="font-bold text-base mb-3">Key takeaways</h3>
<ul className="space-y-2">
{takeaways.map((t, i) => (
<li key={i} className="flex items-start gap-2 text-sm">
<span className="text-teal mt-1"></span>
<span>{t}</span>
</li>
))}
</ul>
</Card>
)}
</div>
);
}
// ─── List view ───────────────────────────────────────────
// ─── List view ───────────────────────────────────────────
return (
<div className="space-y-3">
{items.map(({ topic, content }) => {
const state = actionState[topic.id] || {};
const isLoading = !!state.loading;
{error && (
<div className="mb-2 p-3 rounded-[var(--r-sm)] bg-red-50 text-red-800 text-sm flex items-center gap-2">
<AlertCircle size={16} /> {error}
</div>
)}
{sessions.map(s => {
const c = s.content || {};
const topicCount = Array.isArray(c.topicSections) ? c.topicSections.length : 0;
const isBusy = busyId === s.id;
return (
<Card key={topic.id} className="border border-bg-warm">
<Card key={s.id} className="border border-bg-warm">
<div className="flex items-center gap-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-semibold">{topic.label}</span>
<span className="font-mono text-xs bg-bg-warm px-2 py-0.5 rounded-full text-fg-muted">{topic.type}</span>
<Tag variant="success" className="text-xs">Ready</Tag>
<span className="font-semibold">{c.title || s.theme || 'Untitled'}</span>
<Tag variant="accent" className="text-xs">Week {s.week_number}</Tag>
{s.theme && (
<span className="font-mono text-xs bg-bg-warm px-2 py-0.5 rounded-full text-fg-muted flex items-center gap-1">
<Layers size={11} /> {s.theme}
</span>
)}
<Tag variant="success" className="text-xs">{topicCount} topics</Tag>
</div>
<p className="text-sm text-fg-muted mt-0.5 truncate">{topic.description}</p>
{(state.success || state.error) && (
<p className={`text-xs mt-1 flex items-center gap-1 ${state.error ? 'text-red-600' : 'text-teal-700'}`}>
{state.error ? <AlertCircle size={12} /> : <CheckCircle size={12} />}
{state.error || state.success}
{s.updated && (
<p className="text-xs text-fg-muted mt-1 flex items-center gap-1">
<Clock size={11} /> Updated {new Date(s.updated).toLocaleString()}
</p>
)}
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{/* Quick actions */}
<button
onClick={() => handleRegenerate(topic)}
disabled={isLoading}
title="Regenerate from scratch"
className="p-2 rounded-[var(--r-sm)] hover:bg-bg-warm transition-colors text-fg-muted hover:text-teal disabled:opacity-40"
>
{state.loading === 'regenerating' ? <Loader size={17} className="animate-spin" /> : <RefreshCw size={17} />}
</button>
<button
onClick={() => handleDelete(topic.id)}
disabled={isLoading}
title="Delete cached content"
onClick={() => handleDelete(s.id)}
disabled={isBusy}
title="Delete cached theme session"
className="p-2 rounded-[var(--r-sm)] hover:bg-red-50 transition-colors text-fg-muted hover:text-red-500 disabled:opacity-40"
>
<Trash2 size={17} />
{isBusy ? <Loader size={17} className="animate-spin" /> : <Trash2 size={17} />}
</button>
{/* Review button */}
<Button
onClick={() => setSelected({ topic, content })}
onClick={() => setSelected(s)}
className="flex items-center gap-2"
>
<Eye size={16} /> Review

View File

@@ -1,11 +1,36 @@
import { useState, useEffect } from 'react';
import { RefreshCw, Trash2, CheckCircle, Loader, AlertCircle, HelpCircle, ArrowLeft, Eye } from 'lucide-react';
import { RefreshCw, Trash2, CheckCircle, Loader, AlertCircle, HelpCircle, ArrowLeft, Eye, Layers, ChevronDown, ChevronRight } from 'lucide-react';
import { forceGenerateTopicQuestions, getTopicQuestionBank, deleteQuestion } from '../../lib/testService';
import * as db from '../../lib/db';
import Card from '../ui/Card';
import Button from '../ui/Button';
import Tag from '../ui/Tag';
const NO_THEME_KEY = '__no_theme__';
const NO_THEME_LABEL = 'No theme';
// Pure helper: bucket topics by their `theme` field. Topics without a theme
// land in a single "No theme" group. Returns an array of { theme, topics }
// objects sorted by theme name (No theme last) so the rendering order is
// stable across reloads.
function groupTopicsByTheme(topics) {
const buckets = new Map();
for (const t of topics) {
const key = t.theme ? t.theme : NO_THEME_KEY;
if (!buckets.has(key)) buckets.set(key, []);
buckets.get(key).push(t);
}
const named = [];
let untheme = null;
for (const [key, list] of buckets.entries()) {
list.sort((a, b) => (a.label || '').localeCompare(b.label || ''));
if (key === NO_THEME_KEY) untheme = { theme: NO_THEME_LABEL, topics: list, key };
else named.push({ theme: key, topics: list, key });
}
named.sort((a, b) => a.theme.localeCompare(b.theme));
return untheme ? [...named, untheme] : named;
}
const TestManager = () => {
const [topics, setTopics] = useState([]);
const [questionCounts, setQuestionCounts] = useState({});
@@ -13,6 +38,7 @@ const TestManager = () => {
const [questions, setQuestions] = useState([]);
const [loadingTopicId, setLoadingTopicId] = useState(null);
const [error, setError] = useState(null);
const [collapsed, setCollapsed] = useState({}); // { [themeKey]: true } when collapsed
const loadData = async () => {
const allTopics = await db.getTopics();
@@ -148,8 +174,10 @@ const TestManager = () => {
}
// ── List view ──
const groups = groupTopicsByTheme(topics);
return (
<div className="space-y-3">
<div className="space-y-6">
{topics.length === 0 && (
<div className="text-center py-16 text-fg-muted">
<HelpCircle size={48} className="mx-auto mb-4 text-teal/30" />
@@ -163,40 +191,68 @@ const TestManager = () => {
</div>
)}
{topics.map(topic => {
const count = questionCounts[topic.id] || 0;
const isLoading = loadingTopicId === topic.id;
{groups.map(group => {
const isCollapsed = !!collapsed[group.key];
const totalQuestions = group.topics.reduce((sum, t) => sum + (questionCounts[t.id] || 0), 0);
const topicsWithBank = group.topics.filter(t => (questionCounts[t.id] || 0) > 0).length;
return (
<Card key={topic.id} className="border border-bg-warm flex items-center justify-between">
<div className="flex-1 min-w-0 pr-4">
<div className="flex items-center gap-2 mb-1">
<h3 className="font-semibold truncate">{topic.label}</h3>
<Tag variant={count > 0 ? 'success' : 'dark'} className="text-xs">
{count} {count === 1 ? 'question' : 'questions'}
</Tag>
</div>
<p className="text-sm text-fg-muted truncate">{topic.description}</p>
</div>
<section key={group.key}>
<button
type="button"
onClick={() => setCollapsed(p => ({ ...p, [group.key]: !p[group.key] }))}
className="w-full flex items-center gap-2 mb-3 group"
>
{isCollapsed
? <ChevronRight size={18} className="text-fg-muted group-hover:text-teal transition-colors" />
: <ChevronDown size={18} className="text-fg-muted group-hover:text-teal transition-colors" />}
<Layers size={16} className="text-teal/70" />
<h3 className="text-lg font-bold text-fg group-hover:text-teal transition-colors">{group.theme}</h3>
<span className="font-mono text-[11px] text-fg-muted ml-1">
{topicsWithBank}/{group.topics.length} topics ready · {totalQuestions} questions
</span>
</button>
<div className="flex items-center gap-2 flex-shrink-0">
{count === 0 ? (
<Button
variant="outline"
onClick={() => handleGenerate(topic)}
disabled={isLoading}
className="whitespace-nowrap"
>
{isLoading ? <Loader size={16} className="animate-spin mr-2" /> : <RefreshCw size={16} className="mr-2" />}
Generate
</Button>
) : (
<Button onClick={() => setSelectedTopic(topic)} className="flex items-center gap-2">
<Eye size={16} /> Review
</Button>
)}
</div>
</Card>
{!isCollapsed && (
<div className="space-y-2 pl-1">
{group.topics.map(topic => {
const count = questionCounts[topic.id] || 0;
const isLoading = loadingTopicId === topic.id;
return (
<Card key={topic.id} className="border border-bg-warm flex items-center justify-between">
<div className="flex-1 min-w-0 pr-4">
<div className="flex items-center gap-2 mb-1">
<h4 className="font-semibold truncate">{topic.label}</h4>
<Tag variant={count > 0 ? 'success' : 'dark'} className="text-xs">
{count} {count === 1 ? 'question' : 'questions'}
</Tag>
</div>
<p className="text-sm text-fg-muted truncate">{topic.description}</p>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{count === 0 ? (
<Button
variant="outline"
onClick={() => handleGenerate(topic)}
disabled={isLoading}
className="whitespace-nowrap"
>
{isLoading ? <Loader size={16} className="animate-spin mr-2" /> : <RefreshCw size={16} className="mr-2" />}
Generate
</Button>
) : (
<Button onClick={() => setSelectedTopic(topic)} className="flex items-center gap-2">
<Eye size={16} /> Review
</Button>
)}
</div>
</Card>
);
})}
</div>
)}
</section>
);
})}
</div>