FlowWeb / src /features /canvas /components /TaskListView.jsx
danylokhodus's picture
Claude Opus 5.5
feat: quest board — web auto-layout, groups, archive, XP and rewards
2740e39
Raw History Blame Contribute Delete
22.6 kB
import React, { useMemo, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useTranslation } from 'react-i18next';
import {
Search, CheckCircle2, Circle, ChevronRight, Layers, Map as MapIcon, Plus, Crosshair, Sparkles, Gift,
GitFork, ArrowRight, ChevronsDownUp, ChevronsUpDown, X,
} from 'lucide-react';
import { groupOf, getGroupPath } from '../groups';
import { questXp, hasReward } from '../quests';
const initials = (a) => {
const name = (a.displayName || a.email || 'U').trim();
const parts = name.split(/\s+/);
return (parts.length > 1 ? parts[0][0] + parts[1][0] : name.slice(0, 2)).toUpperCase();
};
const isSubgoalEdge = (e) => e.sourceHandle && e.sourceHandle.startsWith('subgoals-source');
const QuestRow = ({ node, depth, canEdit, onToggle, onOpen, onShow }) => {
const { t } = useTranslation();
const d = node.data || {};
const done = d.status === 'Done';
const assignees = Array.isArray(d.assignees) ? d.assignees : [];
return (
<motion.div
layout
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, x: 40, height: 0, marginTop: 0, marginBottom: 0, transition: { duration: 0.25 } }}
transition={{ type: 'spring', stiffness: 320, damping: 28 }}
className={`group flex items-start gap-3 rounded-xl border-2 px-3 py-2.5 bg-surface-container-lowest transition-colors ${
d.isNextStep && !done ? 'border-success/60 shadow-[0_0_0_3px_rgba(34,197,94,0.12)]' : 'border-primary/10 hover:border-primary/30'
}`}
style={{ marginLeft: depth * 22 }}
>
<button
disabled={!canEdit}
onClick={() => onToggle(node)}
className="mt-0.5 shrink-0 cursor-pointer disabled:cursor-default"
title={done ? t('tasks.mark_todo', 'Mark as not done') : t('tasks.mark_done', 'Complete quest')}
>
<AnimatePresence mode="wait" initial={false}>
{done ? (
<motion.span key="done" initial={{ scale: 0, rotate: -90 }} animate={{ scale: 1, rotate: 0 }} exit={{ scale: 0 }} className="block">
<CheckCircle2 size={20} className="text-success fill-success/10" />
</motion.span>
) : (
<motion.span key="todo" initial={{ scale: 0 }} animate={{ scale: 1 }} exit={{ scale: 0 }} className="block">
<Circle size={20} className="text-on-surface-variant/40 group-hover:text-success transition-colors" />
</motion.span>
)}
</AnimatePresence>
</button>
<div className="flex-1 min-w-0 flex flex-col gap-1">
<div className="flex items-center gap-2 min-w-0">
{depth > 0 && <span className="text-yellow-500 text-xs shrink-0">↳</span>}
<button
onClick={() => onOpen(node.id)}
className={`text-left font-bold text-primary leading-tight break-words cursor-pointer hover:underline decoration-secondary decoration-2 ${done ? 'line-through opacity-50' : ''}`}
>
{d.label || t('canvas.new_goal', 'New Goal')}
</button>
{d.isNextStep && !done && (
<span className="flex items-center gap-0.5 text-[9px] font-extrabold uppercase tracking-wider text-success shrink-0">
<ArrowRight size={11} /> {t('quests.next_step', 'Next')}
</span>
)}
</div>
{d.description && <p className="text-xs text-on-surface-variant line-clamp-2">{d.description}</p>}
<div className="flex items-center gap-1.5 flex-wrap">
{(d.status === 'In Progress' || d.status === 'Review') && (
<span className="text-[9px] font-extrabold uppercase tracking-wider px-1.5 py-0.5 rounded-md bg-amber-500/10 text-amber-700 dark:text-amber-300 border border-amber-500/30">
{d.status === 'Review' ? 'Review' : `${d.progress || 0}%`}
</span>
)}
<span className="flex items-center gap-0.5 text-[9px] font-extrabold px-1.5 py-0.5 rounded-md bg-amber-400/10 text-amber-700 dark:text-amber-300 border border-amber-400/30">
<Sparkles size={9} /> {questXp(node)} XP
</span>
{hasReward(node) && (
<span className="flex items-center gap-1 text-[9px] font-extrabold px-1.5 py-0.5 rounded-md bg-pink-500/10 text-pink-700 dark:text-pink-300 border border-pink-400/30 max-w-[220px]">
<Gift size={9} className="shrink-0" /> <span className="truncate">{d.reward}</span>
</span>
)}
{(d.tags || []).map((tag) => (
<span key={tag} className="text-[9px] font-extrabold px-1.5 py-0.5 rounded-md border border-primary/15 bg-secondary/10 text-primary">{tag}</span>
))}
{assignees.length > 0 && (
<span className="flex -space-x-1.5 ml-1" title={assignees.map((a) => a.displayName || a.email).join(', ')}>
{assignees.slice(0, 3).map((a, i) => (
<span key={a.email || i} className="w-5 h-5 rounded-full border border-primary bg-secondary/20 text-[8px] font-extrabold text-primary flex items-center justify-center">
{initials(a)}
</span>
))}
</span>
)}
</div>
</div>
<button
onClick={() => onShow(node.id)}
title={t('tasks.show_on_map', 'Show on the map')}
className="shrink-0 p-1.5 rounded-lg text-primary/50 hover:text-primary hover:bg-primary/5 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
>
<Crosshair size={15} />
</button>
</motion.div>
);
};
const DecisionRow = ({ node, depth, canEdit, onChoose }) => {
const { t } = useTranslation();
const d = node.data || {};
const selected = d.selectedOptions || [];
return (
<motion.div
layout
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, height: 0 }}
className="flex items-center gap-3 rounded-xl border-2 border-dashed border-primary/20 px-3 py-2 bg-secondary/5"
style={{ marginLeft: depth * 22 }}
>
<GitFork size={16} className="text-primary/60 shrink-0" />
<span className="font-bold text-sm text-primary flex-1 min-w-0 break-words">{d.label || t('canvas.condition', 'Condition')}</span>
<div className="flex gap-1 flex-wrap justify-end">
{(d.options || []).map((opt) => {
const on = selected.includes(opt.id);
return (
<button
key={opt.id}
disabled={!canEdit}
onClick={() => onChoose(node, opt.id)}
className={`text-[10px] font-extrabold px-2 py-1 rounded-lg border-2 transition-colors cursor-pointer disabled:cursor-default ${
on ? 'bg-primary text-on-primary border-primary' : 'border-primary/20 text-primary hover:border-primary'
}`}
>
{opt.label}
</button>
);
})}
</div>
</motion.div>
);
};
const AddQuestInline = ({ onAdd }) => {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [value, setValue] = useState('');
const submit = () => {
const label = value.trim();
if (label) onAdd(label);
setValue('');
};
return open ? (
<div className="flex items-center gap-2 rounded-xl border-2 border-primary px-3 py-2 bg-surface-container-lowest">
<Circle size={18} className="text-on-surface-variant/30 shrink-0" />
<input
autoFocus
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); submit(); }
if (e.key === 'Escape') { setOpen(false); setValue(''); }
}}
placeholder={t('tasks.new_quest_placeholder', 'New quest — Enter to add, Esc to close')}
className="flex-1 bg-transparent outline-none text-sm font-bold text-primary"
/>
<button onClick={submit} className="px-2.5 py-1 rounded-lg bg-primary text-on-primary text-xs font-bold cursor-pointer">{t('common.add', 'Add')}</button>
<button onClick={() => { setOpen(false); setValue(''); }} className="p-1 text-primary/50 hover:text-primary cursor-pointer"><X size={14} /></button>
</div>
) : (
<button
onClick={() => setOpen(true)}
className="flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-bold text-primary/50 hover:text-primary hover:bg-secondary/5 cursor-pointer w-full text-left"
>
<Plus size={16} /> {t('tasks.add_quest', 'Add quest')}
</button>
);
};
/**
* The board as a to-do list: one section per group, quests nested under their
* parent goal, quick completion, decisions you can answer in place.
*/
const TaskListView = ({
nodes, edges, permission, collaborators = [], updateNodeData, onOpenSettings, onShowOnMap, onOpenGroup, onAddQuest,
}) => {
const { t } = useTranslation();
const canEdit = permission !== 'Read';
const [query, setQuery] = useState('');
const [statusFilter, setStatusFilter] = useState('active'); // active | all | done
const [tagFilter, setTagFilter] = useState('all');
const [personFilter, setPersonFilter] = useState('all');
const [collapsed, setCollapsed] = useState(() => new Set());
const tasks = useMemo(() => nodes.filter((n) => n.type === 'sketch' || n.type === 'condition'), [nodes]);
const groups = useMemo(() => nodes.filter((n) => n.type === 'cluster'), [nodes]);
const allTags = useMemo(() => [...new Set(tasks.flatMap((n) => n.data?.tags || []))].sort(), [tasks]);
const q = query.trim().toLowerCase();
const matches = (n) => {
if (n.type === 'condition') return statusFilter !== 'done' && (!q || (n.data?.label || '').toLowerCase().includes(q)) && tagFilter === 'all' && personFilter === 'all';
const d = n.data || {};
if (statusFilter === 'active' && d.status === 'Done') return false;
if (statusFilter === 'done' && d.status !== 'Done') return false;
if (tagFilter !== 'all' && !(d.tags || []).includes(tagFilter)) return false;
if (personFilter !== 'all') {
const people = (d.assignees || []).map((a) => a.sharedWithUserId || 'owner');
if (!people.includes(personFilter)) return false;
}
if (q && !`${d.label || ''} ${d.description || ''} ${d.reward || ''}`.toLowerCase().includes(q)) return false;
return true;
};
// Sections in explorer order: the board, then groups depth-first
const sections = useMemo(() => {
const result = [{ id: null, depth: 0 }];
const walk = (parentId, depth) => {
groups
.filter((g) => groupOf(g) === parentId)
.sort((a, b) => (a.position?.y || 0) - (b.position?.y || 0))
.forEach((g) => {
result.push({ id: g.id, depth: depth + 1, node: g });
walk(g.id, depth + 1);
});
};
walk(null, 0);
return result;
}, [groups]);
// Quests nested under the goal they are a subgoal of (within the same section)
const rowsFor = (sectionId) => {
const inSection = tasks.filter((n) => groupOf(n) === sectionId);
const ids = new Set(inSection.map((n) => n.id));
const parentOf = new Map();
edges.filter(isSubgoalEdge).forEach((e) => {
if (ids.has(e.source) && ids.has(e.target) && !parentOf.has(e.target)) parentOf.set(e.target, e.source);
});
const byY = (a, b) => (a.position?.y || 0) - (b.position?.y || 0) || (a.position?.x || 0) - (b.position?.x || 0);
const rows = [];
const visited = new Set();
const visit = (n, depth) => {
if (visited.has(n.id)) return;
visited.add(n.id);
const kids = inSection.filter((c) => parentOf.get(c.id) === n.id).sort(byY);
const kidRows = [];
const before = rows.length;
kids.forEach((k) => visit(k, depth + 1));
kidRows.push(...rows.splice(before));
// A parent stays visible when one of its subgoals matches
if (matches(n) || kidRows.length) rows.push({ node: n, depth }, ...kidRows);
};
inSection.filter((n) => !parentOf.has(n.id)).sort(byY).forEach((n) => visit(n, 0));
return rows;
};
const sectionStats = (sectionId) => {
const quests = tasks.filter((n) => n.type === 'sketch' && (sectionId === null ? groupOf(n) === null : groupOf(n) === sectionId));
const done = quests.filter((n) => n.data?.status === 'Done');
return { total: quests.length, done: done.length, xp: done.reduce((s, n) => s + questXp(n), 0) };
};
const toggle = (node) => {
if (!canEdit) return;
if (node.data?.status !== 'Done' && node.data?.subgoals && node.data.subgoals.done < node.data.subgoals.total) {
alert(t('canvas.subgoal_warning', 'Finish all subgoals first!'));
return;
}
updateNodeData(node.id, { status: node.data?.status === 'Done' ? 'Todo' : 'Done' });
};
const choose = (node, optId) => {
const selected = node.data?.selectedOptions || [];
const next = node.data?.multiSelect
? (selected.includes(optId) ? selected.filter((x) => x !== optId) : [...selected, optId])
: (selected.includes(optId) ? [] : [optId]);
updateNodeData(node.id, { selectedOptions: next });
};
const totals = sectionStatsAll(tasks);
const sectionRows = sections.map((s) => ({ ...s, rows: rowsFor(s.id), stats: sectionStats(s.id) }));
const visibleSections = sectionRows.filter((s) => s.rows.length > 0 || (!q && statusFilter !== 'done' && tagFilter === 'all' && personFilter === 'all'));
const hasAnyRows = sectionRows.some((s) => s.rows.length > 0);
const filtersActive = Boolean(q) || statusFilter === 'done' || tagFilter !== 'all' || personFilter !== 'all';
const allCollapsed = visibleSections.length > 0 && visibleSections.every((s) => collapsed.has(s.id ?? 'root'));
const toggleSection = (key) => setCollapsed((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key); else next.add(key);
return next;
});
return (
<div className="flex-grow overflow-y-auto graph-paper-bg">
<div className="max-w-4xl mx-auto px-6 py-6 flex flex-col gap-5">
{/* Toolbar */}
<div className="sticky top-0 z-10 -mx-2 px-2 pt-1 pb-3 bg-background/90 backdrop-blur flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-3">
<div className="relative flex-1 min-w-[220px]">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-on-surface-variant" />
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('tasks.search', 'Search quests, descriptions, rewards...')}
className="w-full pl-9 pr-3 py-2.5 bg-surface-container-lowest border-2 border-primary rounded-xl text-sm font-bold text-primary outline-none shadow-[2px_2px_0px_0px_var(--color-primary)]"
/>
</div>
<div className="flex bg-surface-container-lowest border-2 border-primary rounded-xl p-1 shadow-[2px_2px_0px_0px_var(--color-primary)]">
{[
['active', t('tasks.filter_active', 'Active')],
['all', t('tasks.filter_all', 'All')],
['done', t('tasks.filter_done', 'Done')],
].map(([key, label]) => (
<button
key={key}
onClick={() => setStatusFilter(key)}
className={`relative px-3.5 py-1.5 rounded-lg text-xs font-extrabold uppercase tracking-wider cursor-pointer ${statusFilter === key ? 'text-on-primary' : 'text-primary'}`}
>
{statusFilter === key && <motion.span layoutId="tasks-status" className="absolute inset-0 bg-primary rounded-lg" transition={{ type: 'spring', stiffness: 400, damping: 32 }} />}
<span className="relative">{label}</span>
</button>
))}
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
{allTags.length > 0 && (
<select
value={tagFilter}
onChange={(e) => setTagFilter(e.target.value)}
className="py-1.5 px-2.5 rounded-lg border-2 border-primary/30 text-xs font-bold text-primary bg-surface-container-lowest cursor-pointer"
>
<option value="all">{t('tasks.all_tags', 'All tags')}</option>
{allTags.map((tag) => <option key={tag} value={tag}>{tag}</option>)}
</select>
)}
{collaborators.length > 0 && (
<select
value={personFilter}
onChange={(e) => setPersonFilter(e.target.value)}
className="py-1.5 px-2.5 rounded-lg border-2 border-primary/30 text-xs font-bold text-primary bg-surface-container-lowest cursor-pointer"
>
<option value="all">{t('tasks.all_people', 'Everyone')}</option>
{collaborators.map((c) => (
<option key={c.sharedWithUserId || 'owner'} value={c.sharedWithUserId || 'owner'}>{c.displayName || c.email}</option>
))}
</select>
)}
<span className="text-xs font-bold text-on-surface-variant ml-auto flex items-center gap-3">
<span>{t('tasks.summary', { done: totals.done, total: totals.total, defaultValue: `${totals.done}/${totals.total} done` })}</span>
<span className="flex items-center gap-1 text-amber-600"><Sparkles size={12} /> {totals.xp} XP</span>
</span>
<button
onClick={() => setCollapsed(allCollapsed ? new Set() : new Set(visibleSections.map((s) => s.id ?? 'root')))}
className="p-1.5 rounded-lg border-2 border-primary/20 hover:border-primary text-primary cursor-pointer"
title={allCollapsed ? t('tasks.expand_all', 'Expand all') : t('tasks.collapse_all', 'Collapse all')}
>
{allCollapsed ? <ChevronsUpDown size={14} /> : <ChevronsDownUp size={14} />}
</button>
</div>
</div>
{!hasAnyRows && (filtersActive || !canEdit) ? (
<div className="text-center py-16 flex flex-col items-center gap-2">
<span className="font-accent-note text-3xl text-secondary">{t('tasks.nothing', 'Nothing here')}</span>
<span className="text-sm text-on-surface-variant">{t('tasks.nothing_hint', 'Change the filters or add quests on the map.')}</span>
</div>
) : (
visibleSections.map((section) => {
const key = section.id ?? 'root';
const isCollapsed = collapsed.has(key);
const path = section.id ? getGroupPath(nodes, section.id).map((g) => g.data?.label || t('groups.untitled', 'New group')).join(' › ') : null;
const { total, done, xp } = section.stats;
return (
<motion.section key={key} layout className="flex flex-col gap-2">
<div className="flex items-center gap-2">
<button onClick={() => toggleSection(key)} className="flex items-center gap-2 flex-1 min-w-0 text-left cursor-pointer">
<motion.span animate={{ rotate: isCollapsed ? 0 : 90 }}><ChevronRight size={16} className="text-primary" /></motion.span>
{section.id ? <Layers size={16} className="text-purple-500 shrink-0" /> : <MapIcon size={16} className="text-primary shrink-0" />}
<span className="font-display-lg text-2xl text-primary truncate">{path || t('tasks.board_section', 'Board')}</span>
</button>
{total > 0 && (
<div className="flex items-center gap-2 shrink-0">
<div className="w-24 h-2 rounded-full bg-primary/10 overflow-hidden">
<motion.div className="h-full bg-success rounded-full" initial={false} animate={{ width: `${(done / total) * 100}%` }} />
</div>
<span className="text-[11px] font-extrabold text-primary/60">{done}/{total}</span>
<span className="text-[11px] font-extrabold text-amber-600">{xp} XP</span>
</div>
)}
{section.id && (
<button onClick={() => onOpenGroup(section.id)} title={t('tasks.open_group', 'Open the group on the map')} className="p-1.5 rounded-lg text-primary/50 hover:text-primary hover:bg-primary/5 cursor-pointer">
<Crosshair size={14} />
</button>
)}
</div>
<AnimatePresence initial={false}>
{!isCollapsed && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ type: 'spring', stiffness: 260, damping: 30 }}
className="overflow-hidden flex flex-col gap-2 pl-6"
>
<AnimatePresence initial={false}>
{section.rows.map(({ node, depth }) => (
node.type === 'condition'
? <DecisionRow key={node.id} node={node} depth={depth} canEdit={canEdit} onChoose={choose} />
: <QuestRow key={node.id} node={node} depth={depth} canEdit={canEdit} onToggle={toggle} onOpen={onOpenSettings} onShow={onShowOnMap} />
))}
</AnimatePresence>
{section.rows.length === 0 && (
<p className="text-xs italic text-on-surface-variant/60 px-3">
{statusFilter === 'active' && total > 0 ? t('tasks.all_done_here', 'Everything here is done 🎉') : t('tasks.empty_section', 'No quests yet')}
</p>
)}
{canEdit && statusFilter !== 'done' && <AddQuestInline onAdd={(label) => onAddQuest(section.id, label)} />}
</motion.div>
)}
</AnimatePresence>
</motion.section>
);
})
)}
</div>
</div>
);
};
function sectionStatsAll(tasks) {
const quests = tasks.filter((n) => n.type === 'sketch');
const done = quests.filter((n) => n.data?.status === 'Done');
return { total: quests.length, done: done.length, xp: done.reduce((s, n) => s + questXp(n), 0) };
}
export default TaskListView;