Download web/src/apps/amazon-profit/ProjectsList.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 49.7 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/amazon-profit/ProjectsList.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/apps/amazon-profit/ProjectsList.tsx
-
curl -L -o ProjectsList.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/amazon-profit/ProjectsList.tsx
49.7 kB
| import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; | |
| import { ArrowsDownUp } from "@phosphor-icons/react/dist/csr/ArrowsDownUp"; | |
| import { CaretDown } from "@phosphor-icons/react/dist/csr/CaretDown"; | |
| import { Cube } from "@phosphor-icons/react/dist/csr/Cube"; | |
| import { DotsThree } from "@phosphor-icons/react/dist/csr/DotsThree"; | |
| import { Funnel } from "@phosphor-icons/react/dist/csr/Funnel"; | |
| import { MagnifyingGlass } from "@phosphor-icons/react/dist/csr/MagnifyingGlass"; | |
| import { SlidersHorizontal } from "@phosphor-icons/react/dist/csr/SlidersHorizontal"; | |
| import { SidebarSimple } from "@phosphor-icons/react/dist/csr/SidebarSimple"; | |
| import { X } from "@phosphor-icons/react/dist/csr/X"; | |
| import { API_V1, CREDENTIALS, TOAST_EVENT, signal } from "../../apiContract"; | |
| import { | |
| FieldsHidePanel, FilterBuilderPanel, Popover, SortBuilder, countConditions, | |
| type FilterBuilderPanelProps, type FieldsHidePanelProps, type SortBuilderProps, | |
| } from "../../filter-kit"; | |
| // The one operator-label map; index.ts does not re-export it yet. | |
| import { opLabel } from "../../filter-kit/ops"; | |
| import { useEscapeClose } from "../../ui/useEscapeClose"; | |
| import { ProjectResultPreview } from "./ProjectResults"; | |
| import { | |
| GRAIN_LABEL, PROJECT_PRIORITIES, PROJECT_STATUSES, HealthChip, LoadingRows, Owner, | |
| PriorityGlyph, ProjectRequestError, StatusRing, call, enc, formatDay, messageOf, text, | |
| type Project, type ProjectGrain, type ProjectList, type ProjectListFigure, type ProjectListFigures, | |
| } from "./ProjectsShared"; | |
| import "../../styles/sdlc85/project-list.css"; | |
| // ---- The list: Name, Health, Priority, Owner, Target date, Status, the reference's order ---- | |
| const money = (value: number | null | undefined) => value == null ? "Unknown" : | |
| value.toLocaleString("en-US", { style: "currency", currency: "USD" }); | |
| const units = (value: number | null | undefined) => value == null ? "Unknown" : value.toLocaleString("en-US"); | |
| // Sales and Units come from the project Dashboard's tied default series, never the stored rollup cells. | |
| function dashboardValue(figure: ProjectListFigure | undefined, format: (value: number) => string) { | |
| return figure?.total == null ? figure?.reason ?? "Unknown" : format(figure.total); | |
| } | |
| type ProjectFigureMap = Record<string, ProjectListFigures>; | |
| const FIGURES_UNREAD = "Sales and units did not load."; | |
| // A failed read withholds every row with its reason. The next list load reads again. | |
| function withheldFigures(projects: Project[], reason: string): ProjectFigureMap { | |
| const figure = { total: null, reason }; | |
| return Object.fromEntries(projects.map(project => [project.id, { from: null, to: null, sales: figure, units: figure }])); | |
| } | |
| function dashboardTitle(figures: ProjectListFigures | null | undefined, figure?: ProjectListFigure) { | |
| const span = figures?.from && figures.to ? `${formatDay(figures.from)} to ${formatDay(figures.to)}` : ""; | |
| return [span, figure?.total != null ? figure.reason : null].filter(Boolean).join(". ") || undefined; | |
| } | |
| // The stored rollup's net profit is never shown beside window figures. The Dashboard has no profit figure. | |
| function ProjectFigures({ project, compact = false, loading = false }: { project: Project; compact?: boolean; loading?: boolean }) { | |
| const { impact, figures } = project; | |
| if (!loading && !impact && !figures) return null; | |
| const sales = figures?.sales; | |
| const sold = figures?.units; | |
| // One shared withhold reason prints once in place of both numbers. | |
| const withheld = sales?.total == null && sold?.total == null && sales?.reason && sales.reason === sold?.reason | |
| ? sales.reason : null; | |
| if (compact) return <div className="lp-proj-row-figures"> | |
| <div> | |
| {loading ? <span className="lp-proj-muted" aria-busy="true">Loading sales and units</span> | |
| : withheld ? <span title={dashboardTitle(figures)}>{withheld}</span> | |
| : <span title={dashboardTitle(figures, sales)}>Sales {dashboardValue(sales, value => money(value))}</span>} | |
| {loading || withheld ? null : <span title={dashboardTitle(figures, sold)}>Units {dashboardValue(sold, value => units(value))}</span>} | |
| </div> | |
| {project.status === "Completed" && project.completedOn ? <div title="Compared with the same days one year earlier"> | |
| <span>Impact since {formatDay(project.completedOn)}</span> | |
| <span>Sales {money(impact?.netSales)} vs {money(impact?.priorNetSales)}</span> | |
| <span>Units {units(impact?.units)} vs {units(impact?.priorUnits)}</span> | |
| </div> : null} | |
| </div>; | |
| return <section className="lp-proj-section" aria-label="Project figures" style={{ fontVariantNumeric: "tabular-nums" }}> | |
| <h4 className="lp-proj-section-title" title={dashboardTitle(figures)}>Totals</h4> | |
| <dl className="lp-proj-facts"> | |
| <div><dt>Net sales</dt><dd title={dashboardTitle(figures, sales)}>{dashboardValue(sales, value => money(value))}</dd></div> | |
| <div><dt>Units</dt><dd title={dashboardTitle(figures, sold)}>{dashboardValue(sold, value => units(value))}</dd></div> | |
| </dl> | |
| <h4 className="lp-proj-section-title">Impact{project.completedOn ? ` since ${formatDay(project.completedOn)}` : ""}</h4> | |
| <dl className="lp-proj-facts"> | |
| <div><dt>Net sales</dt><dd>{money(impact?.netSales)}</dd></div> | |
| <div><dt>Prior year</dt><dd>{money(impact?.priorNetSales)}</dd></div> | |
| <div><dt>Units</dt><dd>{units(impact?.units)} vs {units(impact?.priorUnits)}</dd></div> | |
| </dl> | |
| </section>; | |
| } | |
| const PROJECT_COLUMNS = [ | |
| ["health", "Health"], ["priority", "Priority"], ["owner", "Owner"], ["targetOn", "Target date"], | |
| ["status", "Status"], ["startOn", "Start date"], ["completedOn", "Completed"], ["createdAt", "Created"], ["results", "Results"], | |
| ] as const; | |
| const DEFAULT_PROJECT_FIELDS = ["health", "priority", "owner", "targetOn", "status", "results"]; | |
| type ProjectFilter = FilterBuilderPanelProps["filters"]; | |
| type ProjectFilterNode = ProjectFilter["nodes"][number]; | |
| type ProjectFilterRule = Extract<ProjectFilterNode, { colId: string }>; | |
| type ProjectField = FilterBuilderPanelProps["fields"][number]; | |
| type ProjectDateRange = [string | null, string | null]; | |
| type ProjectSortSpec = SortBuilderProps["sorts"]; | |
| type ProjectSortField = SortBuilderProps["fields"][number]; | |
| type ProjectRankTree = SortBuilderProps["filters"]; | |
| type ProjectRankNode = ProjectRankTree["nodes"][number]; | |
| type ProjectTopN = { n: number; scope: "global" | "group" }; | |
| type ProjectSortPref = { sorts: ProjectSortSpec; topN: ProjectTopN | null }; | |
| type ProjectGroupKey = "status" | "priority" | "owner" | "health"; | |
| type ProjectGroup = { key: string; value: string | null; projects: Project[] }; | |
| const EMPTY_PROJECT_FILTER: ProjectFilter = { conj: "and", nodes: [] }; | |
| const FIELDS_PREF = "amazon-projects.fields"; | |
| const SORT_PREF = "amazon-projects.sort"; | |
| const GROUP_PREF = "amazon-projects.group"; | |
| const EMPTY_SORT_PREF: ProjectSortPref = { sorts: [], topN: null }; | |
| const TOP_N_MAX = 10000; | |
| const DATE_KEYS = ["startOn", "targetOn", "completedOn", "createdAt"]; | |
| const SORT_FIELDS: ProjectSortField[] = [ | |
| { key: "name", label: "Project", type: "text", source: "overlay" }, | |
| ...PROJECT_COLUMNS.filter(([key]) => key !== "results").map(([key, label]): ProjectSortField => ({ | |
| key, label, source: "overlay", type: DATE_KEYS.includes(key) ? "date" : "select", | |
| })), | |
| // Numeric, so Top N always has a rank key even before a sort exists. | |
| { key: "progress", label: "Progress", type: "pct", source: "overlay" }, | |
| ]; | |
| const SORT_FIELD_BY_KEY = new Map(SORT_FIELDS.map(field => [field.key, field])); | |
| const GROUP_OPTIONS: ReadonlyArray<readonly [ProjectGroupKey, string]> = [ | |
| ["status", "Status"], ["priority", "Priority"], ["owner", "Owner"], ["health", "Health"], | |
| ]; | |
| const PRIORITY_ORDER: readonly string[] = ["Urgent", "High", "Medium", "Low"]; | |
| const HEALTH_ORDER: readonly string[] = ["On track", "At risk", "Off track"]; | |
| // One chain for every list preference, so writes land in order and reads wait for them. | |
| let pendingPrefWrite = Promise.resolve(); | |
| function writePref(key: string, value: unknown, failure: string) { | |
| pendingPrefWrite = pendingPrefWrite.then(async () => { | |
| const response = await fetch(`${API_V1}/nav/prefs/${key}`, { method: "PUT", credentials: CREDENTIALS, | |
| headers: { "Content-Type": "application/json" }, body: JSON.stringify({ value }), keepalive: true }); | |
| if (!response.ok) throw new Error("preference refused"); | |
| }).catch(() => { signal(TOAST_EVENT, failure); }); | |
| } | |
| function groupText(by: ProjectGroupKey, value: string | null): string { | |
| if (value !== null) return value; | |
| return by === "owner" ? "No owner" : by === "health" ? "No health" : "None"; | |
| } | |
| function ProjectGroupLabel({ by, value }: { by: ProjectGroupKey; value: string | null }) { | |
| if (by === "status") return <span className="lp-proj-status lp-proj-accent" data-status={value ?? undefined}> | |
| <span className="lp-proj-status-dot" aria-hidden="true" />{groupText(by, value)}</span>; | |
| if (by === "priority") return <span className="lp-proj-cell"> | |
| <PriorityGlyph priority={value as Project["priority"]} /><span>{groupText(by, value)}</span></span>; | |
| if (by === "health") return value ? <HealthChip health={value as Project["health"]} /> : <span className="lp-proj-muted">No health</span>; | |
| return <Owner name={value} />; | |
| } | |
| export function ProjectTable({ projects, grain, onOpen, empty, visible = DEFAULT_PROJECT_FIELDS, | |
| groups, groupBy, collapsed, onToggleGroup, figures }: { | |
| projects: Project[]; grain?: ProjectGrain; onOpen: (id: string) => void; empty: ReactNode; visible?: string[]; | |
| groups?: ProjectGroup[] | null; groupBy?: ProjectGroupKey | null; collapsed?: ReadonlySet<string>; | |
| onToggleGroup?: (key: string) => void; | |
| /** Sales and Units by project id from GET /figures. Null while that read runs. */ | |
| figures?: ProjectFigureMap | null; | |
| }) { | |
| if (!projects.length) return <div className="lp-proj-empty">{empty}</div>; | |
| const columns = [...new Set(visible)].flatMap(key => { | |
| const column = PROJECT_COLUMNS.find(([field]) => field === key); | |
| return column ? [column] : []; | |
| }); | |
| const projectRow = (project: Project) => { | |
| const via = project.via && grain && (project.via.grain !== grain) ? project.via : null; | |
| return <tr key={project.id} className="lp-proj-row lp-proj-accent" data-status={project.status} | |
| data-project-id={project.id} onClick={() => onOpen(project.id)}> | |
| <td><div className="lp-proj-name-wrap"> | |
| <button type="button" className="lp-proj-name" onClick={(event) => { event.stopPropagation(); onOpen(project.id); }}> | |
| <Cube className="lp-proj-name-glyph" size={14} aria-hidden="true" /> | |
| <span className="lp-proj-clip">{project.name}</span> | |
| </button> | |
| {via ? <span className="lp-proj-via lp-proj-clip">From {GRAIN_LABEL[via.grain]} {via.key}</span> : null} | |
| </div><ProjectFigures project={figures ? { ...project, figures: figures[project.id] ?? null } : project} | |
| loading={figures === null} compact /></td> | |
| {columns.map(([key]) => { | |
| let cell: ReactNode; | |
| switch (key) { | |
| case "health": | |
| cell = project.health ? <HealthChip health={project.health} /> : <span className="lp-proj-muted">No health</span>; | |
| break; | |
| case "priority": | |
| cell = <span className="lp-proj-cell"><PriorityGlyph priority={project.priority} /> | |
| <span className={project.priority === "No priority" ? "lp-proj-muted" : undefined}>{project.priority}</span></span>; | |
| break; | |
| case "owner": | |
| cell = <Owner name={project.owner} />; | |
| break; | |
| case "targetOn": | |
| case "startOn": | |
| case "completedOn": | |
| case "createdAt": | |
| cell = formatDay(project[key]) || <span className="lp-proj-muted">No date</span>; | |
| break; | |
| case "status": | |
| cell = <span className="lp-proj-status lp-proj-accent" data-status={project.status}> | |
| <span className="lp-proj-status-dot" aria-hidden="true" />{project.status}</span>; | |
| break; | |
| case "results": | |
| cell = <ProjectResultPreview projectId={project.id} configs={project.resultConfigs ?? []} | |
| revision={`${project.updatedAt}:${project.status}:${project.completedOn}`} completedOn={project.completedOn} | |
| onOpen={() => onOpen(project.id)} />; | |
| break; | |
| } | |
| return <td key={key}>{cell}</td>; | |
| })} | |
| </tr>; | |
| }; | |
| return <div className="lp-proj-table-scroll"><table className="lp-proj-table" aria-label="Projects"> | |
| <thead> | |
| <tr><th scope="col">Project</th>{columns.map(([key, label]) => | |
| <th key={key} scope="col" data-field={key}>{label}</th>)}</tr> | |
| </thead> | |
| {groups && groupBy ? groups.map(group => { | |
| const open = !collapsed?.has(group.key); | |
| const count = group.projects.length; | |
| return <tbody key={group.key} className="lp-proj-group"> | |
| <tr><th scope="rowgroup" colSpan={columns.length + 1} className="lp-proj-group-head"> | |
| <button type="button" className="lp-proj-group-toggle" aria-expanded={open} | |
| aria-label={`${groupText(groupBy, group.value)}, ${count} ${count === 1 ? "project" : "projects"}`} | |
| onClick={() => onToggleGroup?.(group.key)}> | |
| <CaretDown className="lp-proj-group-caret" size={14} aria-hidden="true" /> | |
| <ProjectGroupLabel by={groupBy} value={group.value} /> | |
| <span className="lp-proj-group-count">{count}</span> | |
| </button> | |
| </th></tr> | |
| {open ? group.projects.map(projectRow) : null} | |
| </tbody>; | |
| }) : <tbody>{projects.map(projectRow)}</tbody>} | |
| </table></div>; | |
| } | |
| const PROJECT_HEALTH = ["On track", "At risk", "Off track", "No health"] as const; | |
| const healthLabel = (project: Project) => project.health ?? "No health"; | |
| function projectDay(value: string | undefined): string | null { | |
| if (!value || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value)) return null; | |
| const date = new Date(`${value}T00:00:00Z`); | |
| return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value ? value : null; | |
| } | |
| function shiftProjectDay(day: string, days = 0, months = 0): string { | |
| const date = new Date(`${day}T00:00:00Z`); | |
| if (months) { | |
| const originalDay = date.getUTCDate(); | |
| date.setUTCDate(1); | |
| date.setUTCMonth(date.getUTCMonth() + months); | |
| const end = new Date(date); | |
| end.setUTCMonth(end.getUTCMonth() + 1, 0); | |
| date.setUTCDate(Math.min(originalDay, end.getUTCDate())); | |
| } | |
| date.setUTCDate(date.getUTCDate() + days); | |
| return date.toISOString().slice(0, 10); | |
| } | |
| // Only the date windows offered by this panel need local resolution until runPipeline is public. | |
| function projectDateRange(window: ProjectFilterRule["dateWindow"], today?: string): ProjectDateRange | null | undefined { | |
| if (!window) return undefined; | |
| let from: string | null = null, to: string | null = null; | |
| if (window.kind === "custom") { | |
| from = projectDay(window.from); | |
| to = projectDay(window.to); | |
| if (!from && !to) return undefined; | |
| if (from && to && from > to) [from, to] = [to, from]; | |
| } | |
| if (window.kind === "last_n_days" | |
| && (window.n == null || !Number.isInteger(window.n) || window.n < 1 || window.n > 3650)) return undefined; | |
| const day = projectDay(today); | |
| if (!day) return null; | |
| switch (window.kind) { | |
| case "custom": return [from, to]; | |
| case "last_n_days": return [shiftProjectDay(day, -(window.n! - 1)), day]; | |
| case "past_week": return [shiftProjectDay(day, -6), day]; | |
| case "past_month": return [shiftProjectDay(day, 1, -1), day]; | |
| case "past_year": return [shiftProjectDay(day, 1, -12), day]; | |
| case "this_week": { | |
| const weekday = (new Date(`${day}T00:00:00Z`).getUTCDay() + 6) % 7; | |
| return [shiftProjectDay(day, -weekday), shiftProjectDay(day, 6 - weekday)]; | |
| } | |
| case "this_month": { | |
| const start = `${day.slice(0, 7)}-01`; | |
| return [start, shiftProjectDay(start, -1, 1)]; | |
| } | |
| case "this_year": return [`${day.slice(0, 4)}-01-01`, `${day.slice(0, 4)}-12-31`]; | |
| default: return null; | |
| } | |
| } | |
| function projectDateAnchor(rule: ProjectFilterRule, today?: string): string | null { | |
| const mode = rule.dateMode || "exact"; | |
| if (mode === "exact") return projectDay(rule.value); | |
| const day = projectDay(today); | |
| if (!day) return null; | |
| switch (mode) { | |
| case "today": return day; | |
| case "yesterday": return shiftProjectDay(day, -1); | |
| case "one_week_ago": return shiftProjectDay(day, -7); | |
| case "one_month_ago": return shiftProjectDay(day, 0, -1); | |
| case "n_days_ago": { | |
| const value = rule.value.trim(); | |
| return /^[0-9]+$/.test(value) && Number(value) <= 3650 ? shiftProjectDay(day, -Number(value)) : null; | |
| } | |
| default: return null; | |
| } | |
| } | |
| // Ignore incomplete conditions within OR groups instead of treating them as a match. | |
| function matchProjectNode(node: ProjectFilterNode, project: Project, fields: ProjectField[], today?: string): boolean | null { | |
| if ("children" in node) { | |
| const answers = node.children.map(child => matchProjectNode(child, project, fields, today)) | |
| .filter((answer): answer is boolean => answer !== null); | |
| return !answers.length ? null : node.conj === "or" ? answers.some(Boolean) : answers.every(Boolean); | |
| } | |
| const field = fields.find(candidate => candidate.key === node.colId && candidate.filterable !== false); | |
| if (!field) return null; | |
| const raw = project[field.key as keyof Project]; | |
| const left = String(raw ?? "").toLowerCase(); | |
| const blank = raw == null || left.trim() === "" || left === "(none)"; | |
| if (node.op === "isEmpty") return blank; | |
| if (node.op === "isNotEmpty") return !blank; | |
| if (node.op === "isAnyOf" || node.op === "isNoneOf") { | |
| const values = (node.values ?? []).map(value => value.trim().toLowerCase()).filter(Boolean); | |
| if (!values.length) return null; | |
| const hit = values.includes(left); | |
| return node.op === "isAnyOf" ? hit : !hit; | |
| } | |
| const dateField = field.type === "date"; | |
| if (dateField && node.op === "within") { | |
| const bounds = projectDateRange(node.dateWindow, today); | |
| if (bounds === undefined) return null; | |
| const value = String(raw ?? "").slice(0, 10); | |
| return !!bounds && !!value && (!bounds[0] || value >= bounds[0]) && (!bounds[1] || value <= bounds[1]); | |
| } | |
| let right: string; | |
| const rhs = node.rhs; | |
| if (rhs) { | |
| if (rhs.kind !== "field" || !rhs.colId || !fields.some(candidate => candidate.key === rhs.colId)) return null; | |
| right = String(project[rhs.colId as keyof Project] ?? "").toLowerCase(); | |
| } else { | |
| if (node.op === "between") { | |
| if (!node.value || !node.value2) return null; | |
| const bounds = [node.value, node.value2].sort(); | |
| const value = dateField ? String(raw ?? "").slice(0, 10) : left; | |
| return value >= bounds[0] && value <= bounds[1]; | |
| } | |
| const valueFreeDate = dateField && node.dateMode && ["today", "yesterday", "one_week_ago", "one_month_ago"].includes(node.dateMode); | |
| if (!node.value && !valueFreeDate) return null; | |
| const anchor = dateField ? projectDateAnchor(node, today) : node.value.toLowerCase(); | |
| if (anchor == null) return false; | |
| right = anchor; | |
| } | |
| const value = dateField ? String(raw ?? "").slice(0, 10) : left; | |
| if (dateField) right = right.slice(0, 10); | |
| switch (node.op) { | |
| case "eq": return value === right; | |
| case "neq": return value !== right; | |
| case "contains": return value.includes(right); | |
| case "doesNotContain": return !value.includes(right); | |
| case "lt": return value < right; | |
| case "lte": return value <= right; | |
| case "gt": return value > right; | |
| case "gte": return value >= right; | |
| default: return false; | |
| } | |
| } | |
| function withoutSummaryRule(nodes: ProjectFilterNode[], ruleId: string): ProjectFilterNode[] { | |
| return nodes.flatMap<ProjectFilterNode>(node => { | |
| if ("children" in node) { | |
| const children = withoutSummaryRule(node.children, ruleId); | |
| return children.length ? [{ ...node, children }] : []; | |
| } | |
| return node.id === ruleId ? [] : [node]; | |
| }); | |
| } | |
| function hasProjectComparand(nodes: ProjectFilterNode[]): boolean { | |
| return nodes.some(node => "children" in node ? hasProjectComparand(node.children) | |
| : node.rhs != null && node.rhs.kind !== "stat"); | |
| } | |
| function summaryRule(nodes: ProjectFilterNode[], ruleId: string): ProjectFilterNode | undefined { | |
| for (const node of nodes) { | |
| if ("children" in node) { | |
| const found = summaryRule(node.children, ruleId); | |
| if (found) return found; | |
| } else if (node.id === ruleId) return node; | |
| } | |
| } | |
| // Blanks sort last in both directions, as Table does. Closed vocabularies sort in their own order. | |
| function projectSortValue(project: Project, colId: string): string | number | null { | |
| switch (colId) { | |
| case "status": { | |
| const at = (PROJECT_STATUSES as readonly string[]).indexOf(project.status); | |
| return at < 0 ? null : at; | |
| } | |
| case "priority": { | |
| const at = PRIORITY_ORDER.indexOf(project.priority); | |
| return at < 0 ? null : at; | |
| } | |
| case "health": { | |
| const at = project.health ? HEALTH_ORDER.indexOf(project.health) : -1; | |
| return at < 0 ? null : at; | |
| } | |
| case "progress": return Number.isFinite(project.progress) ? project.progress : null; | |
| case "name": case "owner": case "targetOn": case "startOn": case "completedOn": case "createdAt": | |
| return text(project[colId]) || null; | |
| default: return null; | |
| } | |
| } | |
| function sortProjects(projects: Project[], sorts: ProjectSortSpec): Project[] { | |
| if (!sorts.length) return projects; | |
| return [...projects].sort((a, b) => { | |
| for (const rule of sorts) { | |
| const left = projectSortValue(a, rule.colId), right = projectSortValue(b, rule.colId); | |
| if ((left === null) !== (right === null)) return left === null ? 1 : -1; | |
| if (left === null || right === null) continue; | |
| const order = typeof left === "number" && typeof right === "number" ? left - right : String(left).localeCompare(String(right)); | |
| if (order) return rule.dir === "asc" ? order : -order; | |
| } | |
| return 0; | |
| }); | |
| } | |
| function projectGroupValue(project: Project, by: ProjectGroupKey): string | null { | |
| switch (by) { | |
| case "status": return project.status; | |
| case "priority": return project.priority; | |
| case "owner": return project.owner ?? null; | |
| case "health": return project.health ?? null; | |
| } | |
| } | |
| // Sections follow the vocabulary order, reversed when the first sort key is the group key descending. | |
| function groupProjects(projects: Project[], by: ProjectGroupKey, descending: boolean): ProjectGroup[] { | |
| const buckets = new Map<string, ProjectGroup>(); | |
| for (const project of projects) { | |
| const value = projectGroupValue(project, by); | |
| const key = JSON.stringify(value); | |
| const group = buckets.get(key) ?? { key, value, projects: [] }; | |
| group.projects.push(project); | |
| buckets.set(key, group); | |
| } | |
| const order: readonly (string | null)[] = by === "status" ? PROJECT_STATUSES | |
| : by === "priority" ? PRIORITY_ORDER : by === "health" ? HEALTH_ORDER : []; | |
| const blank = (group: ProjectGroup) => group.value === null || group.value === "No priority"; | |
| const rank = (group: ProjectGroup) => { | |
| const at = order.indexOf(group.value); | |
| return at < 0 ? order.length : at; | |
| }; | |
| return [...buckets.values()].sort((a, b) => { | |
| if (blank(a) !== blank(b)) return blank(a) ? 1 : -1; | |
| const result = by === "owner" ? (a.value ?? "").localeCompare(b.value ?? "") : rank(a) - rank(b); | |
| return descending ? -result : result; | |
| }); | |
| } | |
| function readSortPref(value: unknown): ProjectSortPref { | |
| if (!value || typeof value !== "object" || Array.isArray(value)) return EMPTY_SORT_PREF; | |
| const raw = value as { sorts?: unknown; topN?: unknown }; | |
| const sorts = (Array.isArray(raw.sorts) ? raw.sorts : []).slice(0, 50).flatMap((rule): ProjectSortSpec => { | |
| if (!rule || typeof rule !== "object") return []; | |
| const { colId, dir } = rule as { colId?: unknown; dir?: unknown }; | |
| return typeof colId === "string" && SORT_FIELD_BY_KEY.has(colId) && (dir === "asc" || dir === "desc") | |
| ? [{ colId, dir }] : []; | |
| }); | |
| const top = raw.topN && typeof raw.topN === "object" ? raw.topN as { n?: unknown; scope?: unknown } : null; | |
| const n = top?.n; | |
| const topN = typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= TOP_N_MAX | |
| ? { n, scope: top?.scope === "group" ? "group" as const : "global" as const } : null; | |
| return { sorts, topN }; | |
| } | |
| function readGroupPref(value: unknown): ProjectGroupKey | null { | |
| if (!value || typeof value !== "object" || Array.isArray(value)) return null; | |
| const by = (value as { by?: unknown }).by; | |
| return GROUP_OPTIONS.find(([key]) => key === by)?.[0] ?? null; | |
| } | |
| const ANCHOR_WORDS: Record<string, string> = { | |
| today: "today", yesterday: "yesterday", one_week_ago: "one week ago", one_month_ago: "one month ago", | |
| }; | |
| const WINDOW_WORDS: Record<string, string> = { | |
| past_week: "the past week", past_month: "the past month", past_year: "the past year", | |
| this_week: "this week", this_month: "this month", this_year: "this year", | |
| }; | |
| /** One chip's words for a top-level condition, such as "Status is Planned". */ | |
| function conditionText(node: ProjectFilterNode, fields: ProjectField[]): string { | |
| if ("children" in node) { | |
| const count = countConditions(node.children); | |
| return `${node.conj === "or" ? "Any" : "All"} of ${count} ${count === 1 ? "condition" : "conditions"}`; | |
| } | |
| const field = fields.find(candidate => candidate.key === node.colId); | |
| const label = field?.label ?? node.colId; | |
| const type = field?.type ?? "text"; | |
| const subject = `${label} ${opLabel(node.op as Parameters<typeof opLabel>[0], type)}`; | |
| const date = type === "date"; | |
| const shown = (value: string | undefined) => (date ? formatDay(value) : "") || value || ""; | |
| if (node.op === "isEmpty" || node.op === "isNotEmpty") return subject; | |
| if (node.rhs) { | |
| const rhs = node.rhs; | |
| const other = rhs.kind === "field" ? fields.find(candidate => candidate.key === rhs.colId) : undefined; | |
| return other ? `${subject} ${other.label}` : subject; | |
| } | |
| if (node.op === "isAnyOf" || node.op === "isNoneOf") { | |
| const values = (node.values ?? []).filter(value => value.trim()); | |
| return values.length ? `${subject} ${values.join(", ")}` : subject; | |
| } | |
| if (date && node.op === "within") { | |
| const window = node.dateWindow; | |
| if (window?.kind === "custom") { | |
| const from = formatDay(window.from), to = formatDay(window.to); | |
| if (from && to) return `${subject} ${from} to ${to}`; | |
| if (from || to) return `${label} is on or ${from ? `after ${from}` : `before ${to}`}`; | |
| return subject; | |
| } | |
| if (window?.kind === "last_n_days") return window.n ? `${subject} the last ${window.n} days` : subject; | |
| return window && WINDOW_WORDS[window.kind] ? `${subject} ${WINDOW_WORDS[window.kind]}` : subject; | |
| } | |
| if (node.op === "between") return node.value && node.value2 ? `${subject} ${shown(node.value)} and ${shown(node.value2)}` : subject; | |
| if (date && node.dateMode && node.dateMode !== "exact") { | |
| if (node.dateMode === "n_days_ago") return node.value.trim() ? `${subject} ${node.value.trim()} days ago` : subject; | |
| return ANCHOR_WORDS[node.dateMode] ? `${subject} ${ANCHOR_WORDS[node.dateMode]}` : subject; | |
| } | |
| return node.value ? `${subject} ${shown(node.value)}` : subject; | |
| } | |
| function listWords(words: string[]): string { | |
| return words.length < 2 ? words.join("") : `${words.slice(0, -1).join(", ")} and ${words[words.length - 1]}`; | |
| } | |
| /** Both list surfaces filter only the complete admitted collection already returned by their read. */ | |
| export function ProjectBrowser({ read, grain, onOpen }: { | |
| read: ProjectList & { today?: string }; grain?: ProjectGrain; onOpen: (id: string) => void; | |
| }) { | |
| const [filters, setFilters] = useState<ProjectFilter>(EMPTY_PROJECT_FILTER); | |
| const [sortPref, setSortPref] = useState<ProjectSortPref>(EMPTY_SORT_PREF); | |
| const sortPrefRef = useRef<ProjectSortPref>(EMPTY_SORT_PREF); | |
| const [sortReady, setSortReady] = useState(false); | |
| const [groupBy, setGroupBy] = useState<ProjectGroupKey | null>(null); | |
| const [groupReady, setGroupReady] = useState(false); | |
| const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set()); | |
| const [search, setSearch] = useState(""); | |
| const [searchOpen, setSearchOpen] = useState(false); | |
| const searchButtonRef = useRef<HTMLButtonElement>(null); | |
| const restoreSearchFocus = useRef(false); | |
| const chipsRef = useRef<HTMLUListElement>(null); | |
| const [visible, setVisible] = useState<string[]>(DEFAULT_PROJECT_FIELDS); | |
| const visibleRef = useRef<string[]>(DEFAULT_PROJECT_FIELDS); | |
| const [fieldsReady, setFieldsReady] = useState(false); | |
| const [summary, setSummary] = useState(false); | |
| const [tab, setTab] = useState<"Health" | "Owners">("Health"); | |
| const id = useId(); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| const load = async (key: string): Promise<unknown> => { | |
| const response = await fetch(`${API_V1}/nav/prefs/${key}`, { credentials: CREDENTIALS, signal: controller.signal }); | |
| if (!response.ok) throw new Error("preferences refused"); | |
| return (await response.json() as { value?: unknown }).value; | |
| }; | |
| void pendingPrefWrite.then(() => Promise.allSettled([load(FIELDS_PREF), load(SORT_PREF), load(GROUP_PREF)])) | |
| .then(([fieldsRead, sortRead, groupRead]) => { | |
| if (controller.signal.aborted) return; | |
| const failed: string[] = []; | |
| if (fieldsRead.status === "fulfilled") { | |
| if (Array.isArray(fieldsRead.value)) { | |
| const saved = fieldsRead.value.filter((key): key is string => | |
| typeof key === "string" && PROJECT_COLUMNS.some(([field]) => field === key)); | |
| visibleRef.current = saved; | |
| setVisible(saved); | |
| } | |
| setFieldsReady(true); | |
| } else failed.push("fields"); | |
| if (sortRead.status === "fulfilled") { | |
| const saved = readSortPref(sortRead.value); | |
| sortPrefRef.current = saved; | |
| setSortPref(saved); | |
| setSortReady(true); | |
| } else failed.push("sort"); | |
| if (groupRead.status === "fulfilled") { | |
| setGroupBy(readGroupPref(groupRead.value)); | |
| setGroupReady(true); | |
| } else failed.push("grouping"); | |
| if (failed.length) signal(TOAST_EVENT, `Your saved ${listWords(failed)} could not be loaded. Reopen Projects to retry.`); | |
| }); | |
| return () => controller.abort(); | |
| }, []); | |
| // Rows paint from the list at once. Sales and Units fill in from one GET /figures per list read. | |
| const [figureRead, setFigureRead] = useState<{ of: ProjectList; byId: ProjectFigureMap } | null>(null); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| const query = read.grain && read.key ? `?grain=${enc(read.grain)}&key=${enc(read.key)}` : ""; | |
| call<{ figures?: ProjectFigureMap }>(`/figures${query}`, { signal: controller.signal }, FIGURES_UNREAD) | |
| .then(next => { if (!controller.signal.aborted) setFigureRead({ of: read, byId: next.figures ?? {} }); }, | |
| reason => { | |
| if (!controller.signal.aborted) { | |
| setFigureRead({ of: read, byId: withheldFigures(read.projects, messageOf(reason, FIGURES_UNREAD)) }); | |
| } | |
| }); | |
| return () => controller.abort(); | |
| }, [read]); | |
| const figures = figureRead?.of === read ? figureRead.byId : null; | |
| const closeSearch = () => { | |
| restoreSearchFocus.current = true; | |
| setSearch(""); | |
| setSearchOpen(false); | |
| }; | |
| useEscapeClose(searchOpen, closeSearch); | |
| useEffect(() => { | |
| if (searchOpen || !restoreSearchFocus.current) return; | |
| restoreSearchFocus.current = false; | |
| searchButtonRef.current?.focus(); | |
| }, [searchOpen]); | |
| const saveFields = (keys: string[]) => { | |
| if (!fieldsReady) return; | |
| const next = [...new Set(keys)].filter(key => PROJECT_COLUMNS.some(([field]) => field === key)); | |
| visibleRef.current = next; | |
| setVisible(next); | |
| writePref(FIELDS_PREF, next, "Your fields could not be saved. Change Fields to retry."); | |
| }; | |
| const toggleField = (key: string) => { | |
| const current = visibleRef.current; | |
| saveFields(current.includes(key) ? current.filter(field => field !== key) : [...current, key]); | |
| }; | |
| const saveSort = (next: ProjectSortPref) => { | |
| if (!sortReady) return; | |
| sortPrefRef.current = next; | |
| setSortPref(next); | |
| writePref(SORT_PREF, next, "Your sort could not be saved. Change Sort to retry."); | |
| }; | |
| const changeRank = (tree: ProjectRankTree) => { | |
| const node = tree.nodes.find(candidate => "op" in candidate && candidate.op === "topN") as | |
| (ProjectRankNode & { value?: string; rankScope?: string }) | undefined; | |
| const n = Math.floor(Number(node?.value)); | |
| saveSort({ sorts: sortPrefRef.current.sorts, topN: node && Number.isFinite(n) && n >= 1 | |
| ? { n: Math.min(n, TOP_N_MAX), scope: node.rankScope === "group" ? "group" : "global" } : null }); | |
| }; | |
| const saveGroup = (by: ProjectGroupKey | null) => { | |
| if (!groupReady) return; | |
| setGroupBy(by); | |
| setCollapsed(new Set()); | |
| writePref(GROUP_PREF, { by }, "Your grouping could not be saved. Change Group to retry."); | |
| }; | |
| const owners = useMemo(() => [...new Set(read.projects.map(project => project.owner))] | |
| .sort((a, b) => (a ?? "").localeCompare(b ?? "")), [read.projects]); | |
| const fields = useMemo<ProjectField[]>(() => [ | |
| { key: "name", label: "Project", type: "text", source: "overlay" }, | |
| ...PROJECT_COLUMNS.map(([key, label]): ProjectField => ({ | |
| key, label, source: "overlay", | |
| type: ["startOn", "targetOn", "completedOn", "createdAt"].includes(key) ? "date" | |
| : ["health", "priority", "status", "owner"].includes(key) ? "select" : "text", | |
| filterable: key !== "results", | |
| options: key === "health" ? PROJECT_HEALTH.filter(value => value !== "No health") | |
| : key === "priority" ? [...PROJECT_PRIORITIES] : key === "status" ? [...PROJECT_STATUSES] | |
| : key === "owner" ? owners.filter((value): value is string => value !== null) : undefined, | |
| })), | |
| { key: "notes", label: "Notes", type: "long_text", source: "overlay" }, | |
| ], [owners]); | |
| const panelFields = useMemo<FieldsHidePanelProps["fields"]>(() => fields.filter(field => field.key !== "notes"), [fields]); | |
| const hiddenFields = new Set(PROJECT_COLUMNS.filter(([key]) => !visible.includes(key)).map(([key]) => key)); | |
| const term = search.trim().toLowerCase(); | |
| const filteredProjects = (tree: ProjectFilter) => read.projects.filter(project => | |
| matchProjectNode({ conj: tree.conj ?? "and", children: tree.nodes }, project, fields, read.today) !== false | |
| && (!term || project.name.toLowerCase().includes(term))); | |
| const healthRuleId = `${id}-summary-health`; | |
| const ownerRuleId = `${id}-summary-owner`; | |
| const healthRule = summaryRule(filters.nodes, healthRuleId); | |
| const ownerRule = summaryRule(filters.nodes, ownerRuleId); | |
| const toggleSummary = (ruleId: string, colId: "health" | "owner", value: string | null, selected: boolean) => { | |
| setFilters(current => { | |
| const nodes = withoutSummaryRule(current.nodes, ruleId); | |
| if (selected) return { ...current, nodes }; | |
| const children: ProjectFilterNode[] = nodes.length && current.conj === "or" | |
| ? [{ conj: "or", children: nodes }] : nodes; | |
| const rule: ProjectFilterNode = { id: ruleId, colId, op: value === null ? "isEmpty" : "eq", value: value ?? "" }; | |
| return { conj: "and", nodes: [...children, rule] }; | |
| }); | |
| }; | |
| const summarySelected = (node: ProjectFilterNode | undefined, colId: string, value: string | null) => | |
| !!node && "colId" in node && !node.rhs && node.colId === colId | |
| && (value === null ? node.op === "isEmpty" : node.op === "eq" && node.value === value); | |
| // Null is an explicit filter value, distinct from any owner's name. | |
| const ownerKey = (value: string | null) => JSON.stringify(value); | |
| const { sorts, topN } = sortPref; | |
| // Top N is a user choice only. Without it every matching project shows. | |
| const rankScope = topN && groupBy !== null ? topN.scope : "global"; | |
| const sorted = sortProjects(filteredProjects(filters), sorts); | |
| const limited = topN && rankScope === "global" ? sorted.slice(0, topN.n) : sorted; | |
| const groups = groupBy === null ? null | |
| : groupProjects(limited, groupBy, sorts[0]?.colId === groupBy && sorts[0].dir === "desc") | |
| .map(group => topN && rankScope === "group" ? { ...group, projects: group.projects.slice(0, topN.n) } : group); | |
| const rows = groups ? groups.flatMap(group => group.projects) : limited; | |
| const rankTree: ProjectRankTree = { conj: "and", nodes: topN ? [{ colId: sorts[0]?.colId ?? "progress", op: "topN", | |
| value: String(topN.n), rankScope } as ProjectRankNode] : [] }; | |
| const toggleGroup = (key: string) => setCollapsed(current => { | |
| const next = new Set(current); | |
| if (!next.delete(key)) next.add(key); | |
| return next; | |
| }); | |
| const conditionCount = countConditions(filters.nodes); | |
| const narrowed = Boolean(conditionCount || term); | |
| const clearFilters = () => { setFilters(EMPTY_PROJECT_FILTER); setSearch(""); setSearchOpen(false); }; | |
| const removeCondition = (index: number) => { | |
| setFilters(current => ({ ...current, nodes: current.nodes.filter((_, at) => at !== index) })); | |
| requestAnimationFrame(() => { | |
| const buttons = chipsRef.current?.querySelectorAll<HTMLButtonElement>(".lp-proj-filter-chip-x"); | |
| if (buttons?.length) buttons[Math.min(index, buttons.length - 1)].focus(); | |
| }); | |
| }; | |
| const prefsReady = fieldsReady && sortReady && groupReady; | |
| const viewIsDefault = !filters.nodes.length && !sorts.length && !topN && groupBy === null && !search && !searchOpen | |
| && visible.length === DEFAULT_PROJECT_FIELDS.length && visible.every((key, at) => key === DEFAULT_PROJECT_FIELDS[at]); | |
| const resetView = () => { | |
| clearFilters(); | |
| saveFields([...DEFAULT_PROJECT_FIELDS]); | |
| saveSort(EMPTY_SORT_PREF); | |
| saveGroup(null); | |
| }; | |
| const healthRows = summary ? filteredProjects({ ...filters, nodes: withoutSummaryRule(filters.nodes, healthRuleId) }) : []; | |
| const ownerRows = summary ? filteredProjects({ ...filters, nodes: withoutSummaryRule(filters.nodes, ownerRuleId) }) : []; | |
| const healthCounts = PROJECT_HEALTH.map(label => ({ label, count: healthRows.filter(project => healthLabel(project) === label).length })); | |
| const ownerCounts = owners.map(value => ({ value, count: ownerRows.filter(project => project.owner === value).length })); | |
| const groupLabel = GROUP_OPTIONS.find(([key]) => key === groupBy)?.[1]; | |
| return <section className="lp-proj-browser" aria-label="Project list controls"> | |
| <div className="lp-proj-controls"> | |
| <span className="lp-proj-result-count" role="status">{rows.length} of {read.projects.length}{read.cause ? " available" : " projects"}</span> | |
| {filters.nodes.length ? <ul ref={chipsRef} className="lp-proj-filter-chips" aria-label="Applied filters"> | |
| {filters.nodes.map((node, index) => { | |
| const words = conditionText(node, fields); | |
| return <li key={!("children" in node) && node.id ? node.id : `at-${index}`} className="lp-proj-filter-chip" title={words}> | |
| <span className="lp-proj-clip">{words}</span> | |
| <button type="button" className="lp-proj-filter-chip-x" aria-label={`Remove ${words}`} onClick={() => removeCondition(index)}> | |
| <X size={12} aria-hidden="true" /> | |
| </button> | |
| </li>; | |
| })} | |
| </ul> : null} | |
| <div className="lp-proj-control-actions"> | |
| <fieldset className="lp-proj-control-set" aria-label="Project fields" disabled={!fieldsReady}> | |
| <Popover label="Fields" icon={<SlidersHorizontal size={16} aria-hidden="true" />} active={hiddenFields.size > 0}> | |
| {() => <FieldsHidePanel fields={panelFields} hidden={hiddenFields} lockedKey="name" | |
| manager={false} sharedSections={false} onToggle={toggleField} | |
| onShowAll={() => saveFields([...visibleRef.current, ...PROJECT_COLUMNS.map(([key]) => key)])} | |
| onHideAll={() => saveFields([])} />} | |
| </Popover> | |
| </fieldset> | |
| <Popover label={conditionCount ? `Filter · ${conditionCount}` : "Filter"} | |
| icon={<Funnel size={16} aria-hidden="true" />} active={conditionCount > 0} tone="filter" wide | |
| pairWide={hasProjectComparand(filters.nodes)}> | |
| {() => <FilterBuilderPanel fields={fields} filters={filters} onChange={setFilters} today={read.today} database={null} />} | |
| </Popover> | |
| <fieldset className="lp-proj-control-set" aria-label="Project sort" disabled={!sortReady}> | |
| <Popover label={sorts.length ? `Sort · ${sorts.length}` : "Sort"} icon={<ArrowsDownUp size={16} aria-hidden="true" />} | |
| active={sorts.length > 0 || topN !== null} tone="sort" wide> | |
| {() => <SortBuilder fields={SORT_FIELDS} fieldByKey={SORT_FIELD_BY_KEY} sorts={sorts} | |
| onSorts={next => saveSort({ sorts: next, topN: sortPrefRef.current.topN })} | |
| filters={rankTree} onFilters={changeRank} grouped={groupBy !== null} />} | |
| </Popover> | |
| </fieldset> | |
| <fieldset className="lp-proj-control-set" aria-label="Project grouping" disabled={!groupReady}> | |
| <Popover label={groupLabel ? `Group: ${groupLabel}` : "Group"} active={groupBy !== null} tone="group" | |
| icon={<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"> | |
| <path d="M2.5 4h11M5.5 8h8M5.5 12h8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /> | |
| </svg>}> | |
| {() => <div className="cg-pop-body"> | |
| <div className="cg-pop-title">Group by</div> | |
| {groups ? <div className="cg-pop-footer cg-fields-footer"> | |
| <button type="button" className="cg-link-btn" onClick={() => setCollapsed(new Set(groups.map(group => group.key)))}> | |
| Collapse all | |
| </button> | |
| <button type="button" className="cg-link-btn" onClick={() => setCollapsed(new Set())}>Expand all</button> | |
| </div> : null} | |
| <label className="cg-radio-row"> | |
| <input type="radio" name={`${id}-group`} checked={groupBy === null} onChange={() => saveGroup(null)} /> | |
| <span>No grouping</span> | |
| </label> | |
| {GROUP_OPTIONS.map(([key, label]) => <label key={key} className="cg-radio-row"> | |
| <input type="radio" name={`${id}-group`} checked={groupBy === key} onChange={() => saveGroup(key)} /> | |
| <span>{label}</span> | |
| </label>)} | |
| </div>} | |
| </Popover> | |
| </fieldset> | |
| <span className="lp-proj-divider" aria-hidden="true" /> | |
| <fieldset className="lp-proj-control-set" aria-label="Project view options" disabled={!prefsReady}> | |
| <Popover label="Options" icon={<DotsThree size={16} aria-hidden="true" />}> | |
| {close => <div className="cg-pop-body"> | |
| <button type="button" className="lp-proj-menu-item" disabled={viewIsDefault} | |
| onClick={() => { resetView(); close(); }}>Reset view</button> | |
| </div>} | |
| </Popover> | |
| </fieldset> | |
| <button type="button" className="lp-proj-tool" aria-label="Project summary" title={summary ? "Hide summary" : "Show summary"} aria-pressed={summary} | |
| onClick={() => setSummary(!summary)}><SidebarSimple size={16} aria-hidden="true" /></button> | |
| {searchOpen ? <span className="lp-proj-search-box"> | |
| <MagnifyingGlass size={16} aria-hidden="true" /> | |
| <input className="lp-proj-input" type="search" aria-label="Search projects" placeholder="Search projects" autoFocus | |
| value={search} onChange={event => setSearch(event.target.value)} | |
| onBlur={event => { if (!event.currentTarget.value.trim()) setSearchOpen(false); }} /> | |
| </span> : <button ref={searchButtonRef} type="button" className="lp-proj-tool" aria-label="Search projects" | |
| title="Search projects" aria-expanded={false} onClick={() => setSearchOpen(true)}> | |
| <MagnifyingGlass size={16} aria-hidden="true" /> | |
| </button>} | |
| </div> | |
| </div> | |
| <div className="lp-proj-list-layout" data-summary={summary}> | |
| <ProjectTable projects={rows} grain={grain} onOpen={onOpen} visible={visible} figures={figures} | |
| groups={groups} groupBy={groupBy} collapsed={collapsed} onToggleGroup={toggleGroup} | |
| empty={<span>{read.projects.length ? "No projects match" : "No projects yet"}{narrowed ? <button type="button" className="lp-proj-tool" onClick={clearFilters}>Reset filters</button> : null}</span>} /> | |
| {summary ? <aside className="lp-proj-summary" aria-label="Project summary"> | |
| <div className="lp-proj-summary-tabs" role="tablist" aria-label="Project summary categories"> | |
| {(["Health", "Owners"] as const).map(value => <button type="button" key={value} className="lp-proj-tool" role="tab" | |
| id={`${id}-${value}`} aria-controls={`${id}-summary`} aria-selected={tab === value} tabIndex={tab === value ? 0 : -1} | |
| onKeyDown={event => { if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) { | |
| event.preventDefault(); const next = event.key === "Home" ? "Health" : event.key === "End" ? "Owners" : tab === "Health" ? "Owners" : "Health"; | |
| setTab(next); document.getElementById(`${id}-${next}`)?.focus(); | |
| } }} onClick={() => setTab(value)}>{value}</button>)} | |
| </div> | |
| <p className="lp-proj-summary-scope">{read.cause ? `Available projects: ${read.projects.length}` : `All projects: ${read.projects.length}`}</p> | |
| <div id={`${id}-summary`} role="tabpanel" aria-labelledby={`${id}-${tab}`} title="Counts follow the other filters"> | |
| {tab === "Health" ? healthCounts.map(({ label, count }) => <button type="button" className="lp-proj-summary-row" key={label} | |
| aria-pressed={summarySelected(healthRule, "health", label === "No health" ? null : label)} | |
| onClick={() => toggleSummary(healthRuleId, "health", label === "No health" ? null : label, | |
| summarySelected(healthRule, "health", label === "No health" ? null : label))}> | |
| <span>{label === "No health" ? label : <HealthChip health={label} />}</span><span>{count}</span> | |
| </button>) : ownerCounts.map(({ value, count }) => <button type="button" className="lp-proj-summary-row" key={ownerKey(value)} | |
| aria-pressed={summarySelected(ownerRule, "owner", value)} | |
| onClick={() => toggleSummary(ownerRuleId, "owner", value, summarySelected(ownerRule, "owner", value))}> | |
| <Owner name={value} /><span>{count}</span> | |
| </button>)} | |
| {!read.projects.length ? <p className="lp-proj-muted">No projects to summarize</p> : null} | |
| </div> | |
| </aside> : null} | |
| </div> | |
| </section>; | |
| } | |
| export function AddExisting({ exclude, onPick, onCancel }: { | |
| exclude: Set<string>; onPick: (project: Project) => Promise<void>; onCancel: () => void; | |
| }) { | |
| const [all, setAll] = useState<Project[] | null>(null); | |
| const [query, setQuery] = useState(""); | |
| const [error, setError] = useState(""); | |
| const [busy, setBusy] = useState(false); | |
| const [canEdit, setCanEdit] = useState(true); | |
| const picking = useRef(false); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| call<ProjectList>("", { signal: controller.signal }) | |
| .then((next) => { | |
| if (!controller.signal.aborted) { setAll(next.projects); setCanEdit(next.canEdit); } | |
| }, | |
| (reason) => { if (!controller.signal.aborted) setError(messageOf(reason, "Projects did not load.")); }); | |
| return () => controller.abort(); | |
| }, []); | |
| const term = query.trim().toLowerCase(); | |
| const choices = (all ?? []).filter((project) => !exclude.has(project.id) && (!term || project.name.toLowerCase().includes(term))); | |
| if (!canEdit) return <p className="lp-proj-muted" role="status">Only an editor of Project manager can change projects.</p>; | |
| return <div className="lp-proj-search"> | |
| <div className="lp-proj-search-bar"> | |
| <input type="search" className="lp-proj-input" aria-label="Find a project by name" placeholder="Find a project by name" | |
| value={query} onChange={(event) => setQuery(event.target.value)} autoFocus /> | |
| <button type="button" className="lp-proj-btn lp-proj-btn-quiet" onClick={onCancel}>Cancel</button> | |
| </div> | |
| {error ? <p className="lp-proj-error" role="alert">{error}</p> : null} | |
| {!all && !error ? <LoadingRows /> : null} | |
| {all && !choices.length ? <p className="lp-proj-muted">No other projects</p> : null} | |
| {choices.length | |
| ? <ul className="lp-proj-targets" aria-label="Projects"> | |
| {choices.map((project) => <li key={project.id} className="lp-proj-target"> | |
| <span className="lp-proj-cell"><StatusRing status={project.status} progress={project.progress} /> | |
| <span className="lp-proj-clip">{project.name}</span></span> | |
| <button type="button" className="lp-proj-btn" disabled={busy} | |
| onClick={() => { | |
| if (picking.current) return; | |
| picking.current = true; | |
| setBusy(true); | |
| onPick(project).catch((reason) => { | |
| setError(messageOf(reason, "The project was not added.")); | |
| setBusy(false); | |
| picking.current = false; | |
| if (reason instanceof ProjectRequestError && reason.status === 403) setCanEdit(false); | |
| }); | |
| }}> | |
| Add | |
| </button> | |
| </li>)} | |
| </ul> | |
| : null} | |
| </div>; | |
| } | |