File size: 32,888 Bytes
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import {
  useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState,
  type CSSProperties, type KeyboardEvent, type ReactNode,
} from "react";
import { ArrowRight } from "@phosphor-icons/react/dist/csr/ArrowRight";
import { CalendarBlank } from "@phosphor-icons/react/dist/csr/CalendarBlank";
import { CaretRight } from "@phosphor-icons/react/dist/csr/CaretRight";
import { Check } from "@phosphor-icons/react/dist/csr/Check";
import { Circle } from "@phosphor-icons/react/dist/csr/Circle";
import { DotsThree } from "@phosphor-icons/react/dist/csr/DotsThree";
import { Plus } from "@phosphor-icons/react/dist/csr/Plus";
import { useEscapeClose } from "../../ui/useEscapeClose";
import ProjectGantt from "./ProjectGantt";
import { SkuPicker, number, type TaskGrain, type TaskTargetChange, type TaskTargetPair } from "./ProjectSkuPicker";
import { CenteredPopup, GRAIN_LABEL, Owner, ProjectRequestError, call, enc, formatDay, messageOf,
  type Project } from "./ProjectsShared";
import "../../styles/sdlc85/project-tasks.css";

type FilterStatus = { met: number; total: number; message?: string; evaluated_on?: string };

export interface ProjectTask {
  id: string; projectId: string; parentId: string | null; position: string; name: string;
  assignee: string | null; startOn: string | null; dueOn: string | null; done: boolean;
  doneAt: string | null; contingencyFor: string | null; active: boolean;
  /** Present only when the task has targets. The server owns filterStatus and filterClosedAt (R15). */
  targets?: TaskTargetPair[] | null; targetFilter?: { grain: TaskGrain; filter: unknown } | null;
  completionFilter?: unknown; filterStatus?: FilterStatus | null; filterClosedAt?: string | null;
}

type TaskAction = "edit" | "assign" | "reopen" | "add" | "backup" | "activate" | "indent" | "outdent" | "delete";
const isFilterTask = (task: ProjectTask) => task.completionFilter !== null && task.completionFilter !== undefined;

/** The server's met count as sent, or null when it is absent or malformed. */
function filterCount(task: ProjectTask): FilterStatus | null {
  const status = task.filterStatus;
  if (!isFilterTask(task) || !status || !Number.isSafeInteger(status.met) || !Number.isSafeInteger(status.total)
    || status.met < 0 || status.met > status.total) return null;
  return status;
}

function targetLabel(task: ProjectTask) {
  const saved = task.targetFilter;
  if (saved && GRAIN_LABEL[saved.grain]) return `${GRAIN_LABEL[saved.grain]}s by filter`;
  const counts = new Map<TaskGrain, number>();
  for (const pair of Array.isArray(task.targets) ? task.targets : []) {
    if (GRAIN_LABEL[pair.grain]) counts.set(pair.grain, (counts.get(pair.grain) ?? 0) + 1);
  }
  return Array.from(counts, ([grain, count]) => `${number(count)} ${GRAIN_LABEL[grain]}${count === 1 ? "" : "s"}`).join(", ");
}

type Person = { username: string; name: string };
type TaskFields = { name: string; assignee: string | null; startOn: string | null; dueOn: string | null };
type Editor = { kind: "add" | "edit" | "backup"; task?: ProjectTask; parentId: string | null };
type TaskStatus = "Done" | "In progress" | "Planned" | "Backup";
type TaskAnswer = { task?: ProjectTask; project?: Project; progress?: number };
type Send = (path: string, method: string, body?: unknown) => Promise<TaskAnswer>;
export type TaskRow = { task: ProjectTask; depth: number; active: boolean; done: boolean; status: TaskStatus };
type TaskSummary = { count: number; progress: number | null };

function taskTree(tasks: ProjectTask[]) {
  const byId = new Map(tasks.map(task => [task.id, task]));
  const children = new Map<string | null, ProjectTask[]>();
  for (const task of tasks) {
    const parent = task.parentId && byId.has(task.parentId) ? task.parentId : null;
    const siblings = children.get(parent) ?? [];
    siblings.push(task);
    children.set(parent, siblings);
  }
  // The API orders exact fractional positions. Keep that order without rounding them in JavaScript.
  const stack = [...(children.get(null) ?? [])].reverse().map(task => ({ task, depth: 0, active: true }));
  const seen = new Set<string>();
  const rows: TaskRow[] = [];
  const now = new Date();
  const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
  while (stack.length) {
    const entry = stack.pop()!;
    if (seen.has(entry.task.id)) continue;
    seen.add(entry.task.id);
    const active = entry.active && entry.task.active;
    rows.push({ ...entry, active, done: entry.task.done, status: "Planned" });
    const nested = children.get(entry.task.id) ?? [];
    for (let i = nested.length - 1; i >= 0; i--) {
      stack.push({ task: nested[i], depth: entry.depth + 1, active });
    }
  }
  const byRow = new Map(rows.map(row => [row.task.id, row]));
  for (let i = rows.length - 1; i >= 0; i--) {
    const row = rows[i];
    const nested = (children.get(row.task.id) ?? []).map(task => byRow.get(task.id)).filter(child => child?.active);
    if (nested.length) row.done = nested.every(child => child!.done);
    row.status = !row.active ? "Backup" : row.done ? "Done"
      : row.task.startOn && row.task.startOn <= today ? "In progress" : "Planned";
  }
  const leaves = rows.filter(row => row.active && !(children.get(row.task.id) ?? []).some(task => task.active));
  const done = leaves.filter(row => row.done).length;
  const total = leaves.length;
  // Match the core's nearest-even rounding when the percentage ends in one half.
  const whole = total ? Math.floor(100 * done / total) : 0;
  const remainder = total ? (100 * done) % total : 0;
  const progress = total ? whole + (remainder * 2 > total ? 1 : remainder * 2 === total ? whole % 2 : 0) : 0;
  return { byId, children, rows, leaves, done, total, progress };
}

function dateLabel(value: string) {
  return new Date(`${value}T00:00:00`).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

function TaskDates({ task }: { task: ProjectTask }) {
  return <span className="lp-proj-task-dates">
    <CalendarBlank size={14} aria-hidden="true" />
    {task.startOn ? <time dateTime={task.startOn}>{dateLabel(task.startOn)}</time> : null}
    {task.startOn && task.dueOn ? <ArrowRight size={12} aria-label="to" /> : null}
    {task.dueOn ? <time dateTime={task.dueOn}>{dateLabel(task.dueOn)}</time>
      : <span className="lp-proj-muted">No due date</span>}
  </span>;
}

function TaskMenu({ task, active, disabled, canIndent, canOutdent, onAction }: {
  task: ProjectTask; active: boolean; disabled: boolean; canIndent: boolean; canOutdent: boolean;
  onAction: (action: TaskAction) => void;
}) {
  const [open, setOpen] = useState(false);
  const trigger = useRef<HTMLButtonElement>(null);
  const menuId = useId();
  useEffect(() => { if (!active) setOpen(false); }, [active]);
  const visible = open && active;
  // The server refuses target changes on a closed filter task until Reopen and reset.
  const latched = !!task.filterClosedAt;
  return <div className="lp-proj-task-actions">
    <button ref={trigger} type="button" className="lp-proj-task-icon" disabled={disabled}
      aria-label={`Actions for ${task.name}`} aria-haspopup="menu" aria-expanded={visible}
      aria-controls={visible ? menuId : undefined} onClick={() => setOpen(value => !value)}>
      <DotsThree size={20} aria-hidden="true" />
    </button>
    {visible ? <TaskMenuOptions id={menuId} trigger={trigger.current} onClose={() => setOpen(false)}>
      {([
        ["edit", "Edit task", false], ["assign", "Assign SKUs", latched],
        ...(latched ? [["reopen", "Reopen and reset", false] as const] : []),
        ["add", "Add sub-task", false], ["backup", "Add backup task", false],
        ...(!task.active ? [["activate", "Activate backup", false] as const] : []),
        ["indent", "Indent", !canIndent], ["outdent", "Outdent", !canOutdent], ["delete", "Delete task", false],
      ] as const).map(([action, label, unavailable]) => <button key={action} type="button" role="menuitem"
        className="lp-proj-task-menu-item" data-danger={action === "delete" || undefined}
        title={action === "assign" && latched ? "Reopen and reset first" : undefined}
        disabled={disabled || unavailable} onClick={() => {
          trigger.current?.focus(); setOpen(false); onAction(action);
        }}>{label}</button>)}
    </TaskMenuOptions> : null}
  </div>;
}

function TaskMenuOptions({ id, trigger, onClose, children }: {
  id: string; trigger: HTMLButtonElement | null; onClose: () => void; children: ReactNode;
}) {
  const panel = useRef<HTMLDivElement>(null);
  const restoreFocus = useRef(true);
  useEscapeClose(true, onClose, { container: () => panel.current });
  useLayoutEffect(() => {
    panel.current?.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus({ preventScroll: true });
    panel.current?.scrollIntoView({ block: "nearest" });
    return () => { if (restoreFocus.current && trigger?.isConnected) trigger.focus({ preventScroll: true }); };
  }, [trigger]);
  useEffect(() => {
    const outside = (event: PointerEvent) => {
      if (event.target instanceof Node && !panel.current?.contains(event.target) && !trigger?.contains(event.target)) {
        restoreFocus.current = false; onClose();
      }
    };
    document.addEventListener("pointerdown", outside, true);
    return () => document.removeEventListener("pointerdown", outside, true);
  }, [onClose, trigger]);
  return <div ref={panel} id={id} className="lp-proj-task-menu" role="menu" aria-label="Task actions"
    onKeyDown={event => {
      if (event.key === "Tab") { event.preventDefault(); event.stopPropagation(); onClose(); return; }
      const buttons = [...(panel.current?.querySelectorAll<HTMLButtonElement>("button:not(:disabled)") ?? [])];
      const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
      const next = event.key === "ArrowDown" ? (index + 1) % buttons.length
        : event.key === "ArrowUp" ? (index - 1 + buttons.length) % buttons.length
          : event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 : null;
      if (next !== null) { event.preventDefault(); event.stopPropagation(); buttons[next]?.focus(); }
    }}>{children}</div>;
}

function TaskEditor({ editor, people, peopleLoading, peopleError, busy, error, onRetryPeople, onClose, onSave }: {
  editor: Editor; people: Person[]; peopleLoading: boolean; peopleError: string; busy: boolean; error: string;
  onRetryPeople: () => void; onClose: () => void; onSave: (values: TaskFields) => Promise<boolean>;
}) {
  const task = editor.kind === "edit" ? editor.task : undefined;
  const [values, setValues] = useState<TaskFields>({ name: task?.name ?? "", assignee: task?.assignee ?? null,
    startOn: task?.startOn ?? null, dueOn: task?.dueOn ?? null });
  const [invalid, setInvalid] = useState("");
  const formId = useId();
  const heading = editor.kind === "edit" ? "Edit task" : editor.kind === "backup" ? "Backup task" : "Add task";
  const set = <K extends keyof TaskFields>(key: K, value: TaskFields[K]) => {
    setInvalid(""); setValues(current => ({ ...current, [key]: value }));
  };
  return <CenteredPopup title={heading} size="narrow" className="lp-proj-task-editor" onClose={() => { if (!busy) onClose(); }}>
    <form id={formId} className="lp-proj-task-form" aria-label={heading} aria-busy={busy}
      onSubmit={event => {
        event.preventDefault(); event.stopPropagation();
        if (!values.name.trim()) { setInvalid("Name the task."); return; }
        if (values.startOn && values.dueOn && values.dueOn < values.startOn) {
          setInvalid("Due date must be on or after the start date."); return;
        }
        void onSave({ ...values, name: values.name.trim() }).then(saved => { if (saved) onClose(); });
      }}>
      {editor.task && editor.kind !== "edit" ? <p className="lp-proj-muted">{editor.kind === "backup"
        ? `Backup for ${editor.task.name}` : `Sub-task of ${editor.task.name}`}</p> : null}
      <label className="lp-proj-field"><span>Task name</span>
        <input className="lp-proj-input" value={values.name} required disabled={busy}
          onChange={event => set("name", event.target.value)} /></label>
      <label className="lp-proj-field"><span>Assignee</span>
        <select className="lp-proj-input" value={values.assignee ?? ""} disabled={busy || peopleLoading || !!peopleError}
          aria-busy={peopleLoading} onChange={event => set("assignee", event.target.value || null)}>
          <option value="">{peopleLoading ? "Loading people…" : "Unassigned"}</option>
          {values.assignee && !people.some(person => person.username === values.assignee)
            ? <option value={values.assignee}>{values.assignee}</option> : null}
          {people.map(person => <option key={person.username} value={person.username}>{person.name}</option>)}
        </select>
      </label>
      {peopleError ? <div className="lp-proj-task-error"><p className="lp-proj-error" role="alert">{peopleError}</p>
        <button type="button" className="lp-proj-task-link" disabled={busy} onClick={onRetryPeople}>Retry people</button></div> : null}
      <div className="lp-proj-task-date-inputs">
        <label className="lp-proj-field"><span>Start date</span>
          <input className="lp-proj-input" type="date" value={values.startOn ?? ""} disabled={busy}
            max={values.dueOn ?? undefined} onChange={event => set("startOn", event.target.value || null)} /></label>
        <label className="lp-proj-field"><span>Due date</span>
          <input className="lp-proj-input" type="date" value={values.dueOn ?? ""} disabled={busy}
            min={values.startOn ?? undefined} onChange={event => set("dueOn", event.target.value || null)} /></label>
      </div>
      {invalid || error ? <p className="lp-proj-error" role="alert">{invalid || error}</p> : null}
      <div className="lp-proj-task-form-actions">
        <button type="button" className="lp-proj-btn lp-proj-btn-quiet" disabled={busy} onClick={onClose}>Cancel</button>
        <button type="submit" className="lp-proj-btn lp-proj-btn-primary" disabled={busy}>
          {editor.kind === "edit" ? "Save task" : "Add task"}
        </button>
      </div>
    </form>
  </CenteredPopup>;
}

export default function ProjectTasks({ projectId, canEdit, active, disabled, people, peopleLoading, peopleError,
  onRetryPeople, onTasksLoaded, onProjectChanged, onChanged, onForbidden }: {
  projectId: string; canEdit: boolean; active: boolean; disabled: boolean; people: Person[];
  peopleLoading: boolean; peopleError: string; onRetryPeople: () => void;
  onTasksLoaded: (summary: TaskSummary) => void; onProjectChanged: (project: Partial<Project>) => void;
  onChanged: () => void; onForbidden: () => void;
}) {
  const [tasks, setTasks] = useState<ProjectTask[] | null>(null);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState("");
  const [writeError, setWriteError] = useState("");
  const [attempt, setAttempt] = useState(0);
  const [busy, setBusy] = useState(false);
  const [denied, setDenied] = useState(false);
  const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());
  const [view, setView] = useState<"list" | "timeline">("list");
  const [editor, setEditor] = useState<Editor | null>(null);
  const [assigning, setAssigning] = useState<string | null>(null);
  const writing = useRef(false);
  const mounted = useRef(true);
  const readRequest = useRef<AbortController | null>(null);
  const section = useRef<HTMLElement>(null);
  const editorOpener = useRef<HTMLElement | null>(null);
  const headingId = useId();
  const callbacks = useRef({ onTasksLoaded, onProjectChanged, onChanged, onForbidden });
  callbacks.current = { onTasksLoaded, onProjectChanged, onChanged, onForbidden };
  const editable = canEdit && !denied;
  const locked = busy || disabled;
  const base = `/${enc(projectId)}/tasks`;
  const tree = useMemo(() => taskTree(tasks ?? []), [tasks]);
  const visible = useMemo(() => {
    let hiddenBelow = Infinity;
    return tree.rows.filter(row => {
      if (row.depth > hiddenBelow) return false;
      hiddenBelow = collapsed.has(row.task.id) ? row.depth : Infinity;
      return true;
    });
  }, [tree.rows, collapsed]);

  useEffect(() => {
    mounted.current = true;
    return () => { mounted.current = false; readRequest.current?.abort(); };
  }, []);

  const reload = useCallback(async () => {
    readRequest.current?.abort();
    const controller = new AbortController();
    readRequest.current = controller;
    setLoading(true); setLoadError("");
    try {
      const answer = await call<{ tasks: ProjectTask[] }>(`/${enc(projectId)}/tasks`, { signal: controller.signal },
        "Tasks did not load.");
      if (!mounted.current || controller.signal.aborted) return;
      setTasks(answer.tasks);
      const model = taskTree(answer.tasks);
      callbacks.current.onTasksLoaded({ count: answer.tasks.length, progress: answer.tasks.length ? model.progress : null });
    } catch (reason) {
      if (!mounted.current || controller.signal.aborted) return;
      setLoadError(messageOf(reason, "Tasks did not load."));
      if (reason instanceof ProjectRequestError && reason.status === 403) {
        setDenied(true); callbacks.current.onForbidden();
      }
    } finally {
      if (mounted.current && !controller.signal.aborted) setLoading(false);
    }
  }, [projectId]);

  useEffect(() => {
    if (active) void reload();
    return () => readRequest.current?.abort();
  }, [active, attempt, reload]);

  useEffect(() => { if (!editable || !active) setEditor(null); }, [editable, active]);
  // The picker stays open on a refusal to name it, and closes when its task is gone.
  useEffect(() => {
    if (!active || assigning && tasks && !tasks.some(task => task.id === assigning)) setAssigning(null);
  }, [active, assigning, tasks]);

  const perform = async (operation: (send: Send) => Promise<unknown>) => {
    if (writing.current || !editable || !active || disabled || loading || !!loadError) return false;
    writing.current = true; setBusy(true); setWriteError("");
    readRequest.current?.abort();
    let wrote = false;
    let succeeded = false;
    const send: Send = async (path, method, body) => {
      const answer = await call<TaskAnswer>(path, { method, body }, "The task change was refused.");
      wrote = true;
      if (mounted.current) {
        if (answer.project) callbacks.current.onProjectChanged(answer.project);
        else if (typeof answer.progress === "number") callbacks.current.onProjectChanged({ progress: answer.progress });
      }
      return answer;
    };
    try { await operation(send); succeeded = true; }
    catch (reason) {
      if (mounted.current) {
        setWriteError(messageOf(reason, "The task change was refused."));
        if (reason instanceof ProjectRequestError && reason.status === 403) {
          setDenied(true); callbacks.current.onForbidden();
        }
      }
    } finally {
      if (mounted.current && wrote) {
        await reload();
        callbacks.current.onChanged();
      }
      writing.current = false;
      if (mounted.current) setBusy(false);
    }
    return succeeded;
  };

  const openEditor = (next: Editor) => {
    editorOpener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    setWriteError(""); setEditor(next);
  };
  const closeEditor = () => {
    setEditor(null);
    window.requestAnimationFrame(() => {
      if (editorOpener.current?.isConnected) editorOpener.current.focus({ preventScroll: true });
    });
  };
  const toggle = (id: string) => setCollapsed(current => {
    const next = new Set(current);
    if (next.has(id)) next.delete(id); else next.add(id);
    return next;
  });
  const expand = (id: string) => setCollapsed(current => {
    const next = new Set(current); next.delete(id); return next;
  });
  const previousSibling = (task: ProjectTask) => {
    const siblings = tree.children.get(task.parentId) ?? [];
    return siblings[siblings.findIndex(sibling => sibling.id === task.id) - 1];
  };
  const focusTask = (taskId: string, selector = "[data-task-name]") => {
    window.requestAnimationFrame(() => {
      if (!mounted.current) return;
      const row = [...(section.current?.querySelectorAll<HTMLElement>("[data-task-id]") ?? [])]
        .find(element => element.dataset.taskId === taskId);
      const target = row?.querySelector<HTMLElement>(selector)
        ?? section.current?.querySelector<HTMLElement>("[data-task-name], .lp-proj-task-add");
      target?.focus({ preventScroll: true });
    });
  };
  const move = (task: ProjectTask, outdent: boolean) => {
    const parent = task.parentId ? tree.byId.get(task.parentId) : undefined;
    const previous = previousSibling(task);
    if (outdent ? !parent : !previous) return;
    const parentId = outdent ? parent!.parentId : previous.id;
    void perform(send => send(`${base}/${enc(task.id)}/move`, "POST", { parentId })).then(saved => {
      if (saved && parentId) expand(parentId);
      focusTask(task.id);
    });
  };
  const rowKey = (event: KeyboardEvent<HTMLButtonElement>, task: ProjectTask) => {
    if (event.key === "Tab" && editable && !locked && !loading && !loadError
        && (event.shiftKey ? !!task.parentId : !!previousSibling(task))) {
      event.preventDefault(); event.stopPropagation(); move(task, event.shiftKey);
    } else if (event.key === "ArrowRight" && tree.children.has(task.id) && collapsed.has(task.id)) {
      event.preventDefault(); expand(task.id);
    } else if (event.key === "ArrowLeft" && tree.children.has(task.id) && !collapsed.has(task.id)) {
      event.preventDefault(); toggle(task.id);
    }
  };
  const complete = (row: TaskRow) => {
    const index = tree.rows.indexOf(row);
    const subtree = [row];
    for (let i = index + 1; i < tree.rows.length && tree.rows[i].depth > row.depth; i++) subtree.push(tree.rows[i]);
    void perform(async send => {
      for (const entry of subtree) {
        // A filter task's done state belongs to the server (R15).
        if (entry.active && entry.task.done === row.done && !isFilterTask(entry.task)) {
          await send(`${base}/${enc(entry.task.id)}`, "PATCH", { done: !row.done });
        }
      }
    }).then(() => focusTask(row.task.id, ".lp-proj-task-check"));
  };
  // R15: only this explicit action clears the server's closed filter state.
  const reopen = (task: ProjectTask) => {
    void perform(send => send(`${base}/${enc(task.id)}`, "PATCH", { done: false })).then(() => focusTask(task.id));
  };
  const assign = (taskId: string, change: TaskTargetChange) => new Promise<void>((resolve, reject) => {
    let failure: unknown = new Error("The targets were not saved. Try again.");
    void perform(async send => {
      try { await send(`${base}/${enc(taskId)}`, "PATCH", change); }
      catch (reason) { failure = reason; throw reason; }
    }).then(saved => {
      if (saved) { resolve(); return; }
      // The picker names the refusal, so the list does not repeat it.
      if (mounted.current) setWriteError("");
      reject(failure);
    });
  });
  const rowAction = (task: ProjectTask, action: TaskAction) => {
    if (action === "edit" || action === "add" || action === "backup") {
      openEditor({ kind: action, task, parentId: action === "add" ? task.id : task.parentId });
    } else if (action === "assign") { setWriteError(""); setAssigning(task.id); }
    else if (action === "reopen") reopen(task);
    else if (action === "indent" || action === "outdent") move(task, action === "outdent");
    else void perform(send => send(`${base}/${enc(task.id)}`, action === "delete" ? "DELETE" : "POST"))
      .then(() => focusTask(task.id));
  };
  const saveTask = (values: TaskFields) => {
    if (!editor) return Promise.resolve(false);
    const current = editor;
    return perform(send => current.kind === "edit"
      ? send(`${base}/${enc(current.task!.id)}`, "PATCH", values)
      : send(base, "POST", { ...values, parentId: current.parentId,
        ...(current.kind === "backup" ? { contingencyFor: current.task!.id } : {}) })).then(saved => {
      if (saved && current.parentId) expand(current.parentId);
      return saved;
    });
  };
  const identities = new Map(people.map(person => [person.username, person.name]));
  const statuses = ["Done", "In progress", "Planned"] as const;
  // The timeline row is one fixed height, so it omits the target and filter lines.
  const renderName = (row: TaskRow, detail = true) => {
    const { task } = row;
    const backup = task.contingencyFor ? tree.byId.get(task.contingencyFor) : null;
    const filtered = isFilterTask(task);
    const targets = detail ? targetLabel(task) : "";
    const count = detail ? filterCount(task) : null;
    const closedAt = detail && task.filterClosedAt ? task.filterClosedAt : null;
    const closedDay = closedAt ? formatDay(closedAt) : "";
    return <div className="lp-proj-task-name-cell" role="cell" style={{ "--task-depth": row.depth } as CSSProperties}>
      {tree.children.has(task.id) ? <button type="button" className="lp-proj-task-icon lp-proj-task-caret"
        data-expanded={!collapsed.has(task.id)} aria-label={`${collapsed.has(task.id) ? "Expand" : "Collapse"} ${task.name}`}
        aria-expanded={!collapsed.has(task.id)} onClick={() => toggle(task.id)}>
        <CaretRight size={14} aria-hidden="true" />
      </button> : <span className="lp-proj-task-caret-space" aria-hidden="true" />}
      {editable && row.active && !filtered ? <input type="checkbox" className="lp-proj-task-check" checked={row.done}
        disabled={locked || loading || !!loadError} aria-label={`${row.done ? "Reopen" : "Complete"} ${task.name}`}
        onChange={() => complete(row)} /> : <span className="lp-proj-task-state-icon"
          aria-label={filtered ? `${row.status}, set by filter` : row.status}>
          {row.done ? <Check size={16} aria-hidden="true" /> : <Circle size={16} aria-hidden="true" />}
        </span>}
      <div className="lp-proj-task-name-text" id={`${headingId}-${task.id}`}>
        {editable ? <button type="button" className="lp-proj-task-name" data-task-name={task.id}
          title="Tab to indent, Shift+Tab to outdent" disabled={locked || loading || !!loadError}
          onKeyDown={event => rowKey(event, task)}
          onClick={() => openEditor({ kind: "edit", task, parentId: task.parentId })}>{task.name}</button>
          : <span className="lp-proj-task-name">{task.name}</span>}
        {task.contingencyFor ? <span className="lp-proj-task-backup">Backup for {backup?.name || "deleted task"}</span> : null}
        {targets || count || closedAt ? <span className="lp-proj-task-targets">
          {targets ? <span>{targets}</span> : null}
          {closedAt ? <span className="lp-proj-task-filter" data-closed>Done by filter{closedDay
            ? <> on <time dateTime={closedAt}>{closedDay}</time></> : null}</span> : null}
          {count ? <span className="lp-proj-task-filter"
            title={count.evaluated_on && formatDay(count.evaluated_on) ? `Checked ${formatDay(count.evaluated_on)}` : undefined}>
            {`${number(count.met)} of ${number(count.total)} meet the filter`}</span> : null}
          {closedAt && editable ? <button type="button" className="lp-proj-task-link" disabled={locked || loading || !!loadError}
            onClick={() => reopen(task)}>Reopen and reset</button> : null}
        </span> : null}
      </div>
    </div>;
  };
  const assignTask = assigning ? tree.byId.get(assigning) : undefined;

  return <section ref={section} className="lp-proj-tasks" aria-labelledby={headingId} aria-busy={loading || busy}>
    <div className="lp-proj-tasks-heading">
      <h3 id={headingId}>Tasks</h3>
      {tasks !== null ? <span className="lp-proj-task-count" title="Completed active leaf tasks. Dormant backups are excluded.">
        {tree.done} of {tree.total}
      </span> : null}
      <div className="lp-proj-task-view" role="group" aria-label="Tasks view">
        {(["list", "timeline"] as const).map(value => <button key={value} type="button"
          className="lp-proj-task-view-button" aria-pressed={view === value}
          onClick={() => {
            setView(value);
            // Opening the timeline brings the whole section into the dialog view, scale and scrollbar included.
            if (value === "timeline" && view !== "timeline") window.requestAnimationFrame(() => section.current?.scrollIntoView({
              block: "nearest", behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" }));
          }}>{value === "list" ? "List" : "Timeline"}</button>)}
      </div>
    </div>
    {tasks?.length ? <div className="lp-proj-task-progress">
      <div className="lp-proj-task-segments" role="progressbar" aria-label="Task progress"
        aria-valuemin={0} aria-valuemax={100} aria-valuenow={tree.progress}
        aria-valuetext={`${tree.done} of ${tree.total} done. ${statuses.map(status =>
          `${tree.leaves.filter(row => row.status === status).length} ${status.toLowerCase()}`).join(", ")}`}>
        {statuses.map(status => {
          const count = tree.leaves.filter(row => row.status === status).length;
          return count ? <span key={status} data-status={status} style={{ flexGrow: count }} title={`${status}: ${count}`} /> : null;
        })}
      </div>
      <span className="lp-proj-task-count">{tree.progress}% done</span>
    </div> : null}
    {loading && tasks === null ? <div className="lp-proj-task-skeleton" role="status" aria-label="Loading tasks">
      <span /><span /><span />
    </div> : null}
    {loadError ? <div className="lp-proj-task-error"><p className="lp-proj-error" role="alert">{loadError}</p>
      <button type="button" className="lp-proj-task-link" disabled={loading || busy}
        onClick={() => setAttempt(value => value + 1)}>Retry</button></div> : null}
    {writeError && !editor && !assignTask ? <p className="lp-proj-error" role="alert">{writeError}</p> : null}
    {tasks && !tasks.length ? <p className="lp-proj-task-empty">No tasks</p> : null}
    {tasks?.length && view === "timeline" ? <ProjectGantt allRows={tree.rows} rows={visible}
      identities={identities} renderName={row => renderName(row, false)} projectId={projectId} canEdit={editable} active={active}
      disabled={locked || loading || !!loadError} perform={perform} writeError={writeError} /> : null}
    {tasks?.length && view === "list" ? <div className="lp-proj-task-list" role="table" aria-label="Project tasks" aria-rowcount={visible.length + 1}>
      <div className="lp-proj-task-row lp-proj-task-columns" role="row">
        <span role="columnheader">Name</span><span role="columnheader">Status</span>
        <span role="columnheader">Assignee</span><span role="columnheader">Dates</span>
        {editable ? <span role="columnheader" aria-label="Actions" /> : null}
      </div>
      {visible.map(row => {
        const { task } = row;
        const assignee = task.assignee ? identities.get(task.assignee) || task.assignee : null;
        return <div key={task.id} className="lp-proj-task-row" role="row" data-task-id={task.id}
          data-done={row.done || undefined} data-read-only={!editable || undefined}>
          {renderName(row)}
          <div role="cell"><span className="lp-proj-task-status" data-status={row.status}>{row.status}</span></div>
          <div className="lp-proj-task-assignee" role="cell" title={assignee || "Unassigned"}>
            <Owner name={assignee} compact /><span>{assignee || "Unassigned"}</span>
          </div>
          <div role="cell"><TaskDates task={task} /></div>
          {editable ? <div role="cell"><TaskMenu task={task} active={active} disabled={locked || loading || !!loadError}
            canIndent={!!previousSibling(task)} canOutdent={!!task.parentId} onAction={action => rowAction(task, action)} /></div> : null}
        </div>;
      })}
    </div> : null}
    {editable && tasks !== null ? <button type="button" className="lp-proj-task-add" disabled={locked || loading || !!loadError}
      onClick={() => openEditor({ kind: "add", parentId: null })}><Plus size={16} aria-hidden="true" />Add task</button> : null}
    {editor && editable && active ? <TaskEditor editor={editor} people={people} peopleLoading={peopleLoading}
      peopleError={peopleError} onRetryPeople={onRetryPeople} busy={busy} error={writeError}
      onClose={closeEditor} onSave={saveTask} /> : null}
    {assignTask && active ? <SkuPicker mode="task" key={assignTask.id} projectId={projectId} canEdit={editable}
      task={assignTask} onAssign={change => assign(assignTask.id, change)} onClose={() => setAssigning(null)} /> : null}
  </section>;
}