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(); 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; 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(); 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(); 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 ; } 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(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
{visible ? 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]) => )} : null}
; } function TaskMenuOptions({ id, trigger, onClose, children }: { id: string; trigger: HTMLButtonElement | null; onClose: () => void; children: ReactNode; }) { const panel = useRef(null); const restoreFocus = useRef(true); useEscapeClose(true, onClose, { container: () => panel.current }); useLayoutEffect(() => { panel.current?.querySelector("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 ; } 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; }) { const task = editor.kind === "edit" ? editor.task : undefined; const [values, setValues] = useState({ 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 = (key: K, value: TaskFields[K]) => { setInvalid(""); setValues(current => ({ ...current, [key]: value })); }; return { if (!busy) onClose(); }}>
{ 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" ?

{editor.kind === "backup" ? `Backup for ${editor.task.name}` : `Sub-task of ${editor.task.name}`}

: null} {peopleError ?

{peopleError}

: null}
{invalid || error ?

{invalid || error}

: null}
; } 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) => void; onChanged: () => void; onForbidden: () => void; }) { const [tasks, setTasks] = useState(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>(() => new Set()); const [view, setView] = useState<"list" | "timeline">("list"); const [editor, setEditor] = useState(null); const [assigning, setAssigning] = useState(null); const writing = useRef(false); const mounted = useRef(true); const readRequest = useRef(null); const section = useRef(null); const editorOpener = useRef(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) => { 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(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("[data-task-id]") ?? [])] .find(element => element.dataset.taskId === taskId); const target = row?.querySelector(selector) ?? section.current?.querySelector("[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, 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((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
{tree.children.has(task.id) ? :
; }; const assignTask = assigning ? tree.byId.get(assigning) : undefined; return

Tasks

{tasks !== null ? {tree.done} of {tree.total} : null}
{(["list", "timeline"] as const).map(value => )}
{tasks?.length ?
`${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 ? : null; })}
{tree.progress}% done
: null} {loading && tasks === null ?
: null} {loadError ?

{loadError}

: null} {writeError && !editor && !assignTask ?

{writeError}

: null} {tasks && !tasks.length ?

No tasks

: null} {tasks?.length && view === "timeline" ? renderName(row, false)} projectId={projectId} canEdit={editable} active={active} disabled={locked || loading || !!loadError} perform={perform} writeError={writeError} /> : null} {tasks?.length && view === "list" ?
NameStatus AssigneeDates {editable ? : null}
{visible.map(row => { const { task } = row; const assignee = task.assignee ? identities.get(task.assignee) || task.assignee : null; return
{renderName(row)}
{row.status}
{assignee || "Unassigned"}
{editable ?
rowAction(task, action)} />
: null}
; })}
: null} {editable && tasks !== null ? : null} {editor && editable && active ? : null} {assignTask && active ? assign(assignTask.id, change)} onClose={() => setAssigning(null)} /> : null}
; }