All files / src/components/lists TaskList.tsx

75.57% Statements 99/131
73.68% Branches 70/95
72.09% Functions 31/43
74.38% Lines 90/121

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                        12x           12x   12x               12x       156x 156x               59x 59x                                                             90x                 12x 12x 12x                                                             85x 85x   85x     85x     7x                                                                                                                                           211x   211x   211x 211x 211x 211x 211x   211x     211x                                                                                                                         2x                                                                         1x                                                                   243x 243x 243x 243x 243x 243x     243x 243x   243x   243x 78x         243x 59x 59x 59x 59x 51x 51x         243x 32x 32x 32x 32x 32x         243x 90x         243x                                     243x 121x 78x 1x 1x 1x 1x 1x     1x           243x   243x 144x 81x           63x 75x   63x 63x 75x 75x 75x         63x 116x 63x 75x 75x           63x             243x 243x         243x   243x   243x                                                                 66x                   90x       32x               210x                                              
import { useEffect, useMemo, useState, type CSSProperties, type JSX } from "react";
import { ChevronRight, List } from "lucide-react";
import { useMatch } from "react-router";
import { AnimatePresence, motion } from "motion/react";
import type { Workspace, TaskData } from "../../hooks/types.js";
import { MAX_TASK_DEPTH, fuzzySearch, type FuzzyKey, type MatchIndex } from "@grackle-ai/common";
import { ICON_SM, ICON_MD } from "../../utils/iconSize.js";
import { taskUrl, newTaskUrl, useAppNavigate } from "../../utils/navigation.js";
import { getStatusStyle, resolveStatus } from "../../utils/taskStatus.js";
import { Tooltip } from "../display/Tooltip.js";
import {
  HighlightedText,
  buildTaskTree,
  groupTasksByStatus,
  type TaskNode,
  type StatusGroup,
} from "./listHelpers.js";
import styles from "./TaskList.module.scss";
 
/** Fuzzy search keys for task matching. */
const TASK_SEARCH_KEYS: FuzzyKey[] = [
  { name: "title", weight: 2 },
  { name: "description", weight: 1 },
];
 
/** Base left-padding for task rows. */
const TASK_BASE_INDENT_PX: number = 16;
/** Additional left-padding per depth level. */
const TASK_DEPTH_INDENT_PX: number = 16;
 
// ---------------------------------------------------------------------------
// Group-by-status toggle persistence
// ---------------------------------------------------------------------------
 
/** localStorage key for the group-by-status toggle (separate from WorkspaceList's
 *  "grackle-group-by-status" key — each view has its own grouping preference). */
const STORAGE_KEY_GROUP_BY_STATUS: string = "grackle-task-group-by-status";
 
/** Read the persisted group-by-status preference. */
function getGroupByStatus(): boolean {
  try {
    return localStorage.getItem(STORAGE_KEY_GROUP_BY_STATUS) === "true";
  } catch {
    return false;
  }
}
 
/** Persist the group-by-status preference. */
function saveGroupByStatus(value: boolean): void {
  try {
    localStorage.setItem(STORAGE_KEY_GROUP_BY_STATUS, String(value));
  } catch {
    /* localStorage unavailable */
  }
}
 
// ---------------------------------------------------------------------------
// StatusGroupAccordion
// ---------------------------------------------------------------------------
 
/** Props for the StatusGroupAccordion component. */
interface StatusGroupAccordionProps {
  group: StatusGroup;
  isExpanded: boolean;
  onToggle: () => void;
  selectedTaskId: string | undefined;
  navigate: ReturnType<typeof useAppNavigate>;
  titleHighlights: Map<string, readonly MatchIndex[]>;
  workspaceNames: Map<string, string>;
}
 
/** Collapsible accordion for a status group. */
function StatusGroupAccordion({
  group,
  isExpanded,
  onToggle,
  selectedTaskId,
  navigate,
  titleHighlights,
  workspaceNames,
}: StatusGroupAccordionProps): JSX.Element {
  return (
    <div data-testid={`status-group-${group.status}`}>
      <div
        className={styles.statusGroupHeader}
        role="button"
        tabIndex={0}
        aria-expanded={isExpanded}
        onClick={onToggle}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            onToggle();
          }
        }}
      >
        <span
          className={`${styles.expandArrow} ${isExpanded ? styles.expanded : ""}`}
          aria-hidden="true"
        >
          <ChevronRight size={ICON_SM} />
        </span>
        <span
          className={styles.statusGroupIcon}
          style={{ color: group.style.color }}
          aria-hidden="true"
        >
          {group.style.icon}
        </span>
        <span className={styles.statusGroupLabel}>{group.label}</span>
        <span className={styles.statusGroupCount}>{group.tasks.length}</span>
      </div>
 
      <AnimatePresence>
        {isExpanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.2 }}
            style={{ overflow: "hidden" }}
          >
            {group.tasks.map((task) => {
              const statusStyle = getStatusStyle(task.status);
              const isSelected = selectedTaskId === task.id;
              const wsName =
                task.parentTaskId || !task.workspaceId
                  ? undefined
                  : workspaceNames.get(task.workspaceId);
              return (
                <div
                  key={task.id}
                  onClick={() => navigate(taskUrl(task.id))}
                  role="button"
                  tabIndex={0}
                  aria-label={task.title}
                  onKeyDown={(e) => {
                    Iif (e.currentTarget === e.target && (e.key === "Enter" || e.key === " ")) {
                      e.preventDefault();
                      navigate(taskUrl(task.id));
                    }
                  }}
                  className={`${styles.taskRow} ${isSelected ? styles.selected : ""}`}
                  style={{ "--task-indent": `${TASK_BASE_INDENT_PX}px` } as CSSProperties}
                  data-task-id={task.id}
                >
                  <span className={styles.leafSpacer} />
                  <span
                    className={styles.taskStatusIcon}
                    style={{ color: statusStyle.color }}
                    aria-hidden="true"
                    data-testid={`task-status-${resolveStatus(task.status)}`}
                  >
                    {statusStyle.icon}
                  </span>
                  <span className={styles.taskTitle} title={task.title}>
                    <HighlightedText
                      text={task.title}
                      indices={titleHighlights.get(task.id)}
                      highlightClass={styles.searchHighlight}
                    />
                  </span>
                  {wsName && (
                    <span className={styles.workspaceBadge} title={wsName}>
                      {wsName}
                    </span>
                  )}
                </div>
              );
            })}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
 
/** Props for the recursive TaskTreeNode component. */
interface TaskTreeNodeProps {
  node: TaskNode;
  depth: number;
  expandedTasks: Set<string>;
  toggleTask: (taskId: string) => void;
  selectedTaskId: string | undefined;
  navigate: ReturnType<typeof useAppNavigate>;
  taskStatusById: Map<string, string>;
  titleHighlights: Map<string, readonly MatchIndex[]>;
  workspaceNames: Map<string, string>;
}
 
/** Renders a single task tree node with optional children. */
function TaskTreeNode({
  node,
  depth,
  expandedTasks,
  toggleTask,
  selectedTaskId,
  navigate,
  taskStatusById,
  titleHighlights,
  workspaceNames,
}: TaskTreeNodeProps): JSX.Element {
  const statusStyle = getStatusStyle(node.status);
  const isBlocked =
    node.dependsOn.length > 0 &&
    node.dependsOn.some((depId) => taskStatusById.get(depId) !== "complete");
  const isExpanded = expandedTasks.has(node.id);
  const hasChildren = node.children.length > 0;
  const isSelected = selectedTaskId === node.id;
  const indent = TASK_BASE_INDENT_PX + depth * TASK_DEPTH_INDENT_PX;
  const isRoot = depth === 0;
  const wsName =
    isRoot && !node.parentTaskId && node.workspaceId
      ? workspaceNames.get(node.workspaceId)
      : undefined;
  return (
    <>
      <div
        onClick={() => navigate(taskUrl(node.id))}
        role="button"
        tabIndex={0}
        aria-label={node.title}
        onKeyDown={(e) => {
          Iif (e.currentTarget === e.target && (e.key === "Enter" || e.key === " ")) {
            e.preventDefault();
            navigate(taskUrl(node.id));
          }
        }}
        className={`${styles.taskRow} ${isSelected ? styles.selected : ""}`}
        style={{ "--task-indent": `${indent}px` } as CSSProperties}
        data-task-id={node.id}
      >
        {hasChildren && (
          <span
            className={`${styles.expandArrow} ${isExpanded ? styles.expanded : ""}`}
            role="button"
            tabIndex={0}
            aria-label={isExpanded ? "Collapse task" : "Expand task"}
            onClick={(e) => {
              e.stopPropagation();
              toggleTask(node.id);
            }}
            onKeyDown={(e) => {
              Iif (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                e.stopPropagation();
                toggleTask(node.id);
              }
            }}
          >
            <ChevronRight size={ICON_SM} aria-hidden="true" />
          </span>
        )}
        {!hasChildren && <span className={styles.leafSpacer} />}
        <span
          className={styles.taskStatusIcon}
          style={{ color: statusStyle.color }}
          aria-hidden="true"
          data-testid={`task-status-${resolveStatus(node.status)}`}
        >
          {statusStyle.icon}
        </span>
        <span className={styles.taskTitle} title={node.title}>
          <HighlightedText
            text={node.title}
            indices={titleHighlights.get(node.id)}
            highlightClass={styles.searchHighlight}
          />
        </span>
        {wsName && (
          <span className={styles.workspaceBadge} title={wsName}>
            {wsName}
          </span>
        )}
        {hasChildren && (
          <span className={styles.childCountBadge}>
            {node.children.filter((c) => c.status === "complete").length}/{node.children.length}
          </span>
        )}
        {node.dependsOn.length > 0 && (
          <span
            className={`${styles.dependencyBadge} ${isBlocked ? styles.blockedBadge : ""}`}
            title={`Depends on: ${node.dependsOn.join(", ")}`}
          >
            {isBlocked ? "blocked" : "dep"}
          </span>
        )}
        {depth < MAX_TASK_DEPTH && (
          <Tooltip text="Add child task">
            <button
              onClick={(e) => {
                e.stopPropagation();
                navigate(newTaskUrl(node.workspaceId, node.id));
              }}
              aria-label="Add child task"
              className={styles.addChildButton}
            >
              +
            </button>
          </Tooltip>
        )}
      </div>
 
      <AnimatePresence>
        {hasChildren && isExpanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.15 }}
            style={{ overflow: "hidden" }}
          >
            {node.children.map((child) => (
              <TaskTreeNode
                key={child.id}
                node={child}
                depth={depth + 1}
                expandedTasks={expandedTasks}
                toggleTask={toggleTask}
                selectedTaskId={selectedTaskId}
                navigate={navigate}
                taskStatusById={taskStatusById}
                titleHighlights={titleHighlights}
                workspaceNames={workspaceNames}
              />
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
 
// ---------------------------------------------------------------------------
// TaskList (main export)
// ---------------------------------------------------------------------------
 
/** Props for the TaskList component. */
interface TaskListProps {
  /** All workspaces (used for workspace name lookup). */
  workspaces: Workspace[];
  /** All tasks to display. */
  tasks: TaskData[];
}
 
/** Global task tree sidebar view — shows all tasks across all workspaces. */
export function TaskList({ workspaces, tasks }: TaskListProps): JSX.Element {
  const navigate = useAppNavigate();
  const [expandedTasks, setExpandedTasks] = useState<Set<string>>(new Set());
  const [manuallyCollapsed, setManuallyCollapsed] = useState<Set<string>>(new Set());
  const [groupByStatus, setGroupByStatusState] = useState(getGroupByStatus);
  const [groupExpandDefault, setGroupExpandDefault] = useState(getGroupByStatus);
  const [groupExpandOverrides, setGroupExpandOverrides] = useState<Map<string, boolean>>(new Map());
 
  // Derive selected state from router
  const taskMatch = useMatch("/tasks/:taskId/*");
  const selectedTaskId = taskMatch?.params.taskId !== "new" ? taskMatch?.params.taskId : undefined;
 
  const taskStatusById = useMemo(() => new Map(tasks.map((t) => [t.id, t.status])), [tasks]);
 
  const workspaceNames = useMemo(
    () => new Map(workspaces.map((w) => [w.id, w.name])),
    [workspaces],
  );
 
  /** Toggle group-by-status mode. */
  const toggleGroupByStatus = (): void => {
    const next = !groupByStatus;
    saveGroupByStatus(next);
    setGroupByStatusState(next);
    if (next) {
      setGroupExpandDefault(true);
      setGroupExpandOverrides(new Map());
    }
  };
 
  /** Toggle a single status group accordion. */
  const toggleStatusGroup = (status: string): void => {
    setGroupExpandOverrides((prev) => {
      const next = new Map(prev);
      const current = next.has(status) ? next.get(status)! : groupExpandDefault;
      next.set(status, !current);
      return next;
    });
  };
 
  /** Check if a status group is expanded. */
  const isGroupExpanded = (status: string): boolean => {
    return groupExpandOverrides.has(status)
      ? groupExpandOverrides.get(status)!
      : groupExpandDefault;
  };
 
  const toggleTask = (tid: string): void => {
    setExpandedTasks((prev) => {
      const next = new Set(prev);
      if (next.has(tid)) {
        next.delete(tid);
        setManuallyCollapsed((mc) => new Set(mc).add(tid));
      } else {
        next.add(tid);
        setManuallyCollapsed((mc) => {
          const updated = new Set(mc);
          updated.delete(tid);
          return updated;
        });
      }
      return next;
    });
  };
 
  // Auto-expand parent tasks that have children (skip manually collapsed ones)
  useEffect(() => {
    const parentIds = new Set(tasks.filter((t) => t.parentTaskId).map((t) => t.parentTaskId));
    if (parentIds.size > 0) {
      setExpandedTasks((prev) => {
        const next = new Set(prev);
        for (const pid of parentIds) {
          if (!manuallyCollapsed.has(pid)) {
            next.add(pid);
          }
        }
        return next;
      });
    }
  }, [tasks, manuallyCollapsed]);
 
  // ── Search / filter state ──────────────────────────────────────
  const [searchQuery, setSearchQuery] = useState("");
 
  const { directMatchTaskIds, treeMatchTaskIds, titleHighlights } = useMemo(() => {
    if (!searchQuery.trim()) {
      return {
        directMatchTaskIds: null,
        treeMatchTaskIds: null,
        titleHighlights: new Map<string, readonly MatchIndex[]>(),
      };
    }
    const taskResults = fuzzySearch(tasks, searchQuery, TASK_SEARCH_KEYS);
    const directIds = new Set(taskResults.map((r) => r.item.id));
 
    const highlights = new Map<string, readonly MatchIndex[]>();
    for (const r of taskResults) {
      const titleMatch = r.matches.find((m) => m.key === "title");
      if (titleMatch) {
        highlights.set(r.item.id, titleMatch.indices);
      }
    }
 
    // Include ancestor tasks for tree structure
    const treeIds = new Set(directIds);
    const taskById = new Map(tasks.map((t) => [t.id, t]));
    for (const taskId of [...directIds]) {
      let current = taskById.get(taskId);
      while (current?.parentTaskId) {
        treeIds.add(current.parentTaskId);
        current = taskById.get(current.parentTaskId);
      }
    }
 
    return {
      directMatchTaskIds: directIds,
      treeMatchTaskIds: treeIds,
      titleHighlights: highlights,
    };
  }, [searchQuery, tasks]);
 
  const isSearching = directMatchTaskIds !== null;
  const activeMatchIds = isSearching
    ? groupByStatus
      ? directMatchTaskIds
      : treeMatchTaskIds
    : null;
  const visibleTasks = activeMatchIds ? tasks.filter((t) => activeMatchIds.has(t.id)) : tasks;
 
  const tree = !groupByStatus ? buildTaskTree(visibleTasks) : [];
 
  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <span>Tasks</span>
        <div className={styles.headerActions}>
          <Tooltip text={groupByStatus ? "Switch to tree view" : "Group tasks by status"}>
            <button
              className={`${styles.groupToggle} ${groupByStatus ? styles.groupToggleActive : ""}`}
              onClick={toggleGroupByStatus}
              aria-label={groupByStatus ? "Switch to tree view" : "Group tasks by status"}
              aria-pressed={groupByStatus}
              data-testid="task-group-by-status-toggle"
            >
              <List size={ICON_MD} />
            </button>
          </Tooltip>
          <Tooltip text="New task">
            <button
              className={styles.addButton}
              onClick={() => navigate(newTaskUrl())}
              aria-label="New task"
              data-testid="new-task-button"
            >
              +
            </button>
          </Tooltip>
        </div>
      </div>
 
      {tasks.length > 0 && (
        <input
          type="text"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          placeholder="Filter..."
          aria-label="Filter tasks"
          className={styles.searchInput}
          data-testid="sidebar-search"
        />
      )}
 
      {groupByStatus
        ? groupTasksByStatus(visibleTasks, taskStatusById).map((group) => (
            <StatusGroupAccordion
              key={group.status}
              group={group}
              isExpanded={isGroupExpanded(group.status)}
              onToggle={() => toggleStatusGroup(group.status)}
              selectedTaskId={selectedTaskId}
              navigate={navigate}
              titleHighlights={titleHighlights}
              workspaceNames={workspaceNames}
            />
          ))
        : tree.map((node) => (
            <TaskTreeNode
              key={node.id}
              node={node}
              depth={0}
              expandedTasks={expandedTasks}
              toggleTask={toggleTask}
              selectedTaskId={selectedTaskId}
              navigate={navigate}
              taskStatusById={taskStatusById}
              titleHighlights={titleHighlights}
              workspaceNames={workspaceNames}
            />
          ))}
 
      {visibleTasks.length === 0 && !isSearching && (
        <div className={styles.emptyState}>No tasks yet. Click + to create one.</div>
      )}
      {visibleTasks.length === 0 && isSearching && (
        <div className={styles.emptyState}>No matching tasks</div>
      )}
    </div>
  );
}