okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Task board: Schedule | Board view on Tasks, derivation with tests, loop record, sidebar count, all 8 localesdca9770ef

main
6.2 KiB85 linesraw
1import { tr } from '../lib/i18n';
2import { useEffect, useRef, useState } from 'react';
3import { Btn, Dialog, Icon, IconBtn } from '../components/ui';
4import { api } from '../lib/client';
5import { navigate, href, useLocation } from '../lib/router';
6import { blankTask, type Task } from '../lib/tasks';
7import { TaskEditor } from '../components/TaskEditor';
8import { pushToast, setNavOpen } from '../lib/store';
9import { useBoard } from '../lib/use-board';
10type TaskLeaf = Task & {
11    id: string;
12};
13export function TaskTree({ collapsed }: {
14    collapsed: boolean;
15}) {
16    const [editor, setEditor] = useState<Task | null>(null);
17    const location = useLocation();
18    const { board } = useBoard();
19    const [open, setOpen] = useState(() => localStorage.getItem('strata.tasks-open') !== 'false');
20    const [tasks, setTasks] = useState<TaskLeaf[]>([]), [remove, setRemove] = useState<TaskLeaf | null>(null), [error, setError] = useState(''), [busy, setBusy] = useState(false);
21    const [leaving, setLeaving] = useState<string | null>(null);
22    const leavingRef = useRef<string | null>(null), animationTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
23    useEffect(() => {
24        let alive = true;
25        const refresh = () => {
26            void api.get<{
27                tasks: TaskLeaf[];
28            }>('/api/tasks').then(r => {
29                if (alive && !leavingRef.current) {
30                    setTasks(r.tasks.filter(t => !t.archived));
31                    setError('');
32                }
33            }).catch(e => {
34                if (alive)
35                    setError(e.message);
36            });
37        };
38        refresh();
39        const timer = setInterval(refresh, 5000);
40        window.addEventListener('strata:tasks', refresh);
41        return () => {
42            alive = false;
43            clearInterval(timer);
44            if (animationTimer.current)
45                clearTimeout(animationTimer.current);
46            window.removeEventListener('strata:tasks', refresh);
47        };
48    }, []);
49    async function deleteTask() {
50        if (!remove)
51            return;
52        const task = remove;
53        setBusy(true);
54        setError('');
55        try {
56            await api.patch(`/api/tasks/${task.id}`, { archived: true, enabled: false });
57            leavingRef.current = task.id;
58            setLeaving(task.id);
59            setRemove(null);
60            pushToast('success', 'Task removed');
61            if (location.param === task.id)
62                navigate('tasks');
63            animationTimer.current = setTimeout(() => { setTasks(ts => ts.filter(t => t.id !== task.id)); leavingRef.current = null; setLeaving(null); window.dispatchEvent(new Event('strata:tasks')); }, 240);
64        }
65        catch (e) {
66            setError(e instanceof Error ? e.message : String(e));
67        }
68        finally {
69            setBusy(false);
70        }
71    }
72    // A dialog opened from the narrow-window menu closes the menu first (QA F03: the form opened behind it and the keyboard stayed there). The dialogs
73    // live here, so they stay mounted while the menu is closed.
74    const dialogs = <>
75    {tr(editor ? <TaskEditor task={editor} onClose={() => setEditor(null)}/> : null)}
76    <Dialog open={!!remove} compact title={tr("Remove this task?")} onClose={() => !busy && setRemove(null)} actions={<><Btn disabled={busy} onClick={() => setRemove(null)}>{tr("Keep task")}</Btn><Btn variant="danger" disabled={busy} onClick={() => void deleteTask()}>{tr(busy ? 'Removing…' : 'Remove task')}</Btn></>}><div className="stack stack--sm"><p><strong>“{remove?.title}”</strong>{tr(" will stop running and be removed.")}</p></div>{tr(error ? <p className="inline-error" role="alert">{tr(error)}</p> : null)}</Dialog>
77  </>;
78    if (collapsed)
79        return dialogs;
80    return <section className="task-tree" aria-label={tr("Scheduled tasks")}>
81    <div className="ws__head"><button className="navgroup__label task-tree__heading" aria-expanded={open} onClick={() => { setOpen(!open); localStorage.setItem('strata.tasks-open', String(!open)); }}>{tr("Tasks")}{tr(board.need ? <span className="navcount" title={tr("{0} need your attention", [board.need])}><span className="sr-only">{tr("{0} need your attention", [board.need])}</span><span aria-hidden="true">{board.need}</span></span> : null)}<Icon name="chevron" size={12} className={`ws__chev ${open ? 'is-open' : ''}`}/></button><div className="ws__tools"><IconBtn name="plus" title={tr("Add a task")} onClick={() => { setNavOpen(false); setEditor(blankTask()); }}/></div></div>
82    {tr(open ? <div className="navsessions"><div className="ws__session row task-tree-row"><a className="navsession" href="#/tasks?view=board" aria-current={location.route === 'tasks' && !location.param && location.query.get('view') === 'board' ? 'page' : undefined} onClick={() => setNavOpen(false)}><span className="navsession__title">{tr("Task board")}</span></a></div>{tr(tasks.map(t => <div className="ws__session row task-tree-row" data-leaving={leaving === t.id || undefined} key={t.id}><a className="navsession" href={href('tasks', t.id)} aria-current={location.route === 'tasks' && location.param === t.id ? 'page' : undefined} title={t.title}><span className="navsession__title">{t.title}</span>{tr(board.problemTasks.includes(t.id) ? <span className="navsession__dot navsession__dot--warn" role="img" aria-label={tr("Needs attention")} title={tr("Needs attention")}/> : null)}{tr(!t.enabled ? <Icon name="clock" size={12}/> : null)}</a><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Edit task {0}", [t.title])} title={tr("Edit {0}", [t.title])} disabled={t.status === 'running'} onClick={() => { setNavOpen(false); setEditor({ ...t }); }}><Icon name="pencil" size={15}/></button><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Delete task {0}", [t.title])} disabled={t.status === 'running'} title={tr(t.status === 'running' ? 'Stop this task before deleting' : `Delete ${t.title}`)} onClick={() => { setNavOpen(false); setRemove(t); setError(''); }}><Icon name="trash" size={15}/></button></div>))}{tr(!tasks.length ? <p className="small muted ws__empty">{tr("No tasks yet")}</p> : null)}{tr(error && !remove ? <p className="xs inline-error">{tr("Couldn\u2019t load tasks.")}</p> : null)}</div> : null)}
83    {dialogs}
84  </section>;
85}