loopable / web /src /apps /amazon-profit /ProjectActivities.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
85f794d verified
Raw History Blame Contribute Delete
33.3 kB
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { ArrowRight } from "@phosphor-icons/react/dist/csr/ArrowRight";
import { Funnel } from "@phosphor-icons/react/dist/csr/Funnel";
import { UserCircle } from "@phosphor-icons/react/dist/csr/UserCircle";
import { Popover } from "../../filter-kit";
import {
GRAIN_LABEL, Owner, ProjectRequestError, call, enc, messageOf,
type Activity, type Project,
} from "./ProjectsShared";
import "../../styles/sdlc85/project-activities.css";
interface ActivityEntry extends Activity {
id?: string;
byUsername?: string;
byName?: string;
source?: string;
attribute?: string;
before?: unknown;
after?: unknown;
detectionSource?: string;
sku?: string;
asin?: string;
}
interface ActivityPage { activity: ActivityEntry[]; nextCursor: string | null }
interface ActivityRead extends ActivityPage {
initialized: boolean;
loading: boolean;
error: string;
blocked: "denied" | "deleted" | null;
}
type ActivityKind = "Project" | "Tasks" | "SKUs" | "Amazon";
const KINDS: ActivityKind[] = ["Project", "Tasks", "SKUs", "Amazon"];
// Insertion order is the order field lines show in. Unknown keys follow, labelled from the key.
const FIELD_LABEL: Record<string, string> = {
name: "Name", done: "Status", status: "Status", priority: "Priority", health: "Health",
assignee: "Assignee", owner: "Owner", startOn: "Start", start_on: "Start", dueOn: "Due", due_on: "Due",
targetOn: "Target", target_on: "Target", completedOn: "Completed", completed_on: "Completed",
progress: "Progress", targets: "Targets", targetFilter: "Target filter", target_filter: "Target filter",
completionFilter: "Done when", completion_filter: "Done when", filterStatus: "Filter", filter_status: "Filter",
active: "Included", type: "Type", lagDays: "Lag", lag_days: "Lag", notes: "Notes",
resultConfigs: "Results", result_configs: "Results", sku: "SKU", asin: "ASIN", parentAsin: "Parent ASIN",
};
const FIELD_RANK = new Map(Object.keys(FIELD_LABEL).map((key, index) => [key, index]));
// Bookkeeping a person never edits: ids, ordering, timestamps and filter internals.
const HIDDEN_FIELDS = new Set(["id", "position", "created_by", "createdBy", "contingency_for", "contingencyFor",
"closed_targets", "closedTargets", "filter_missing", "filterMissing", "task", "shifted", "target"]);
const MOVE_FIELDS = new Set(["parent_id", "parentId", "position"]);
const FILTER_FIELDS = new Set(["completionFilter", "completion_filter", "targetFilter", "target_filter"]);
const PERSON_FIELDS = new Set(["assignee", "owner", "username", "by"]);
const ID_LIKE = /^(?:[0-9a-f]{24,}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
const ACTION_VERB: Record<string, string> = {
created: "Created project", deleted: "Deleted project", changed: "Changed project",
"added task": "Added task", "removed task": "Removed task", "changed task": "Changed task",
"added dependency": "Added dependency", "removed dependency": "Removed dependency",
"changed dependency": "Changed dependency", "added contributor": "Added contributor",
"removed contributor": "Removed contributor", "added targets": "Added targets",
"removed targets": "Removed targets", "changed targets": "Changed targets",
};
type Rec = Record<string, unknown>;
type Names = ReadonlyMap<string, string>;
const actorName = (entry: ActivityEntry) => entry.byName || entry.by || "Someone";
const actorKey = (entry: ActivityEntry) => entry.byUsername || entry.by || "";
const isFilterText = (value: unknown): value is string => typeof value === "string"
&& (value === "Done by filter" || value.endsWith("no longer meets the filter"));
// The server names a filter transition in the action. Older rows carry it in the field.
const filterTransition = (entry: ActivityEntry): string => entry.source === "amazon" ? ""
: isFilterText(entry.action) ? entry.action : isFilterText(entry.field) ? entry.field : "";
function activityKind(entry: ActivityEntry): ActivityKind {
if (entry.source === "amazon") return "Amazon";
if (filterTransition(entry)) return "Tasks";
if (entry.field === "targets" || entry.action.endsWith(" targets")) return "SKUs";
if (entry.field === "tasks" || entry.field === "dependencies") return "Tasks";
return "Project";
}
function keyedEntries(entries: ActivityEntry[]): Array<[string, ActivityEntry]> {
const occurrences = new Map<string, number>();
return entries.map(entry => {
if (entry.id) return [entry.id, entry];
const signature = JSON.stringify(entry);
const occurrence = (occurrences.get(signature) ?? 0) + 1;
occurrences.set(signature, occurrence);
return [`legacy:${signature}:${occurrence}`, entry];
});
}
function mergeActivity(...pages: ActivityEntry[][]): ActivityEntry[] {
const unique = new Map<string, ActivityEntry>();
for (const page of pages) for (const [key, entry] of keyedEntries(page)) {
if (!unique.has(key)) unique.set(key, entry);
}
return [...unique.values()].sort((a, b) =>
(Date.parse(b.at) || 0) - (Date.parse(a.at) || 0));
}
function dayGroups(entries: ActivityEntry[], now: number) {
const today = new Date(now);
const yesterday = new Date(now);
yesterday.setDate(yesterday.getDate() - 1);
const groups = new Map<string, ActivityEntry[]>();
for (const entry of entries) {
const at = new Date(entry.at);
const label = Number.isNaN(at.getTime()) ? "Date unavailable"
: at.toDateString() === today.toDateString() ? "Today"
: at.toDateString() === yesterday.toDateString() ? "Yesterday"
: at.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
const group = groups.get(label) ?? [];
group.push(entry);
groups.set(label, group);
}
return [...groups];
}
function relativeTime(iso: string, now: number): string {
const elapsed = Date.parse(iso) - now;
if (!Number.isFinite(elapsed)) return "Time unavailable";
if (Math.abs(elapsed) < 60000) return "Just now";
const unit = Math.abs(elapsed) < 3600000 ? "minute" : Math.abs(elapsed) < 86400000 ? "hour" : "day";
const divisor = unit === "minute" ? 60000 : unit === "hour" ? 3600000 : 86400000;
return new Intl.RelativeTimeFormat("en-US", { style: "short" }).format(Math.trunc(elapsed / divisor), unit);
}
function exactTime(iso: string): string {
const at = new Date(iso);
return Number.isNaN(at.getTime()) ? iso : at.toLocaleString("en-US", {
month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit",
second: "2-digit", timeZoneName: "short",
});
}
const TRUNCATED = " [truncated]";
// Strings, structure, other runs, then an unterminated quote that ends a clipped dump.
const DUMP_PART = /"(?:[^"\\]|\\.)*"|[{}[\]]|[^"{}[\]]+|"/g;
const DUMP_SCALAR = /^\s*:\s*(-?\d+(?:\.\d+)?|true|false|null)\s*,/;
// A clipped JSON record: keep top-level values that end before the cut, never guess the cut tail.
function clippedRecord(dump: string): Rec {
const out: Rec = {};
let depth = 0;
let key: string | null = null;
let start = -1;
for (const match of dump.matchAll(DUMP_PART)) {
const part = match[0];
const at = match.index ?? 0;
if (part === "\"") break;
if (part === "{" || part === "[") {
if (depth === 1) start = at;
depth += 1;
} else if (part === "}" || part === "]") {
depth -= 1;
if (depth !== 1) continue;
if (key !== null && start >= 0) {
try { out[key] = JSON.parse(dump.slice(start, at + 1)); } catch { /* incomplete value */ }
}
key = null;
start = -1;
} else if (depth === 1 && part.startsWith("\"")) {
let decoded: string;
try { decoded = JSON.parse(part) as string; } catch { break; }
if (key === null) key = decoded;
else { out[key] = decoded; key = null; }
} else if (depth === 1 && part.includes(",")) {
// A number, boolean or null counts only when its comma shows the cut came after it.
const scalar = key === null ? null : DUMP_SCALAR.exec(part);
if (key !== null && scalar) out[key] = JSON.parse(scalar[1]);
key = null;
}
}
return out;
}
// A stored record arrives as an object or as its JSON dump, whole or clipped by the activity log.
function recordOf(value: unknown): Rec | unknown[] | null {
if (value && typeof value === "object") return value as Rec | unknown[];
if (typeof value !== "string") return null;
const dump = value.trim();
if (!dump.startsWith("{") && !dump.startsWith("[")) return null;
const clipped = dump.endsWith(TRUNCATED);
const body = clipped ? dump.slice(0, -TRUNCATED.length) : dump;
try {
const parsed: unknown = JSON.parse(body);
if (parsed && typeof parsed === "object") return parsed as Rec | unknown[];
} catch { /* clipped or plain text */ }
if (!clipped) return null;
return body.startsWith("{") ? clippedRecord(body) : {};
}
// An email address shows only as a known actor's display name.
function personSafe(value: string, names: Names): string {
if (!value.includes("@")) return value;
return names.get(value) || ([...names.values()].includes(value) ? value : "A person");
}
const idLike = (value: unknown) => typeof value === "string" && ID_LIKE.test(value.trim());
const hiddenField = (key: string) => HIDDEN_FIELDS.has(key) || /(?:_id|Id|_at|At)$/.test(key);
const sentenceCase = (text: string) => text ? text[0].toUpperCase() + text.slice(1) : text;
function labelOf(key: string): string {
if (FIELD_LABEL[key]) return FIELD_LABEL[key];
const words = key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_\s]+/g, " ").trim().toLowerCase();
return words ? sentenceCase(words) : "Field";
}
// Sorted keys, so two equal records compare equal whatever order the server wrote them in.
function stable(value: unknown): string {
return JSON.stringify(value, (_key, item: unknown) => item && typeof item === "object" && !Array.isArray(item)
? Object.fromEntries(Object.entries(item as Rec).sort(([a], [b]) => a.localeCompare(b))) : item) ?? "";
}
function joinShort(items: string[]): string {
if (!items.length) return "None";
return items.length <= 3 ? items.join(", ")
: `${items.slice(0, 3).join(", ")} and ${(items.length - 3).toLocaleString()} more`;
}
const countText = (met: number, total: number) =>
`${met.toLocaleString()} of ${total.toLocaleString()} meet the filter`;
function statusText(record: Rec): string {
const { met, total, message } = record;
if (Number.isSafeInteger(met) && Number.isSafeInteger(total)) return countText(met as number, total as number);
const counts = typeof message === "string" ? /^met (\d+) of (\d+)$/.exec(message.trim()) : null;
return counts ? countText(Number(counts[1]), Number(counts[2])) : "";
}
function conditionCount(tree: unknown): number {
const nodes = Array.isArray(tree) ? tree : tree && typeof tree === "object" ? (tree as Rec).nodes : null;
if (!Array.isArray(nodes)) return 0;
return nodes.reduce<number>((sum, node) => sum
+ (node && typeof node === "object" && Array.isArray((node as Rec).nodes) ? conditionCount(node) : 1), 0);
}
function dayText(text: string): string {
const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(text);
if (!match) return text;
const day = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])));
return day.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" });
}
// A record as one readable phrase, or null when it has nothing a person would recognise.
function objectText(record: Rec, names: Names): string | null {
const status = statusText(record);
if (status) return status;
const { grain, key, username, name, metric } = record;
if (typeof grain === "string" && (typeof key === "string" || typeof key === "number")) {
return `${(GRAIN_LABEL as Record<string, string>)[grain] ?? "Target"} ${key}`;
}
if (typeof username === "string") {
return typeof name === "string" && name.trim() ? personSafe(name.trim(), names) : names.get(username) || "A person";
}
if (typeof metric === "string" && metric.trim()) return metric.trim();
const label = [record.name, record.title, record.label, record.sku].find(item => typeof item === "string" && item.trim());
return typeof label === "string" ? personSafe(label.trim(), names) : null;
}
function listText(items: unknown[], names: Names): string | null {
const shown = items.map(item => typeof item === "number" ? item.toLocaleString()
: typeof item === "string" ? (idLike(item) ? null : personSafe(item.trim(), names))
: item && typeof item === "object" && !Array.isArray(item) ? objectText(item as Rec, names) : null);
if (shown.every((item): item is string => item !== null)) return joinShort(shown);
return `${items.length.toLocaleString()} items`;
}
// One field value as text. Null means the value has no readable form, so the line reads Updated.
function fieldValue(key: string, value: unknown, names: Names): string | null {
if (value === null || value === undefined || value === "") return "None";
if (typeof value === "boolean") return key === "done" ? (value ? "Done" : "Not done") : value ? "Yes" : "No";
if (typeof value === "number") return key === "progress" ? `${value}%` : value.toLocaleString();
const record = recordOf(value);
if (FILTER_FIELDS.has(key)) {
if (!record) return null;
const count = conditionCount(Array.isArray(record) || !/^target_?[fF]ilter$/.test(key) ? record : record.filter);
return count === 0 ? "No conditions" : count === 1 ? "1 condition" : `${count.toLocaleString()} conditions`;
}
if (record) return Array.isArray(record) ? listText(record, names) : objectText(record, names);
if (typeof value !== "string" || idLike(value)) return null;
const text = value.trim();
if (key === "progress") return `${text}%`;
if (/(?:_on|On)$/.test(key) || /^\d{4}-\d{2}-\d{2}$/.test(text)) return dayText(text);
return (PERSON_FIELDS.has(key) && names.get(text)) || personSafe(text, names);
}
interface FieldChange { key: string; label: string; before: string; after: string; updated: boolean; title?: string }
interface RowNote { text: string; muted?: boolean }
interface RowView { verb: string; item: ReactNode; changes: FieldChange[]; notes: RowNote[] }
const fieldChange = (key: string, label: string, before: string | null, after: string | null): FieldChange =>
({ key, label, before: before ?? "", after: after ?? "", updated: before === null || after === null || before === after });
const NO_CHANGE: RowNote = { text: "No visible change", muted: true };
const NO_DETAIL: RowNote = { text: "Field details unavailable", muted: true };
// Only fields whose before and after differ, in FIELD_LABEL order. A clipped side compares shared keys only.
function fieldChanges(before: Rec, after: Rec, partial: boolean, names: Names) {
const keys = [...new Set([...Object.keys(before), ...Object.keys(after)])]
.filter(key => !partial || (key in before && key in after));
const differs = (key: string) => stable(before[key]) !== stable(after[key]);
const moved = keys.some(key => MOVE_FIELDS.has(key) && differs(key));
const changes = keys.filter(key => !hiddenField(key) && differs(key)
&& !idLike(before[key]) && !idLike(after[key])).flatMap(key => {
const was = fieldValue(key, before[key], names);
const now = fieldValue(key, after[key], names);
return was !== null && was === now && !FILTER_FIELDS.has(key) ? [] : [fieldChange(key, labelOf(key), was, now)];
}).filter((change, index, all) => all.findIndex(other => other.label === change.label) === index)
.sort((a, b) => (FIELD_RANK.get(a.key) ?? FIELD_RANK.size) - (FIELD_RANK.get(b.key) ?? FIELD_RANK.size));
return { changes, moved };
}
function taskRecord(value: unknown): { record: Rec | null; clipped: boolean } {
const record = recordOf(value);
if (!record || Array.isArray(record)) return { record: null, clipped: false };
// A reschedule logs its result, which nests the task beside the shifted dependents.
const task = !("name" in record) && record.task && typeof record.task === "object" && !Array.isArray(record.task)
? record.task as Rec : record;
return { record: task, clipped: typeof value === "string" && value.trim().endsWith(TRUNCATED) };
}
function taskName(value: unknown, names: Names): string {
const { record } = taskRecord(value);
if (record) return typeof record.name === "string" && record.name.trim() ? personSafe(record.name.trim(), names) : "";
if (typeof value !== "string" || /^\s*[{[]/.test(value) || idLike(value)) return "";
return personSafe(value.trim(), names);
}
function taskView(entry: ActivityEntry, verb: string, names: Names): RowView {
const was = taskName(entry.from, names);
const now = taskName(entry.to, names);
const item = (entry.action === "removed task" ? was || now : now || was) || "A task";
if (entry.action !== "changed task") return { verb, item, changes: [], notes: [] };
// Each side is the task name plus its changed readable fields. A clipped side ends in the marker.
const before = taskRecord(entry.from);
const after = taskRecord(entry.to);
if (!before.record || !after.record) return { verb, item, changes: [], notes: [NO_DETAIL] };
const partial = before.clipped || after.clipped;
const { changes, moved } = fieldChanges(before.record, after.record, partial, names);
const note = moved ? { text: "Moved to a new position" } : partial ? NO_DETAIL : NO_CHANGE;
return { verb, item, changes, notes: changes.length ? [] : [note] };
}
function filterCount(value: unknown, done: boolean): string {
const { record } = taskRecord(value);
if (!record) return "";
const status = record.filter_status ?? record.filterStatus;
const shown = status && typeof status === "object" && !Array.isArray(status) ? statusText(status as Rec) : "";
if (shown || !done) return shown;
// Done by filter closes only when every target meets it, so a complete target list gives the count.
const filtered = record.target_filter ?? record.targetFilter;
const pairs = [record.closed_targets, record.closedTargets, filtered ? null : record.targets].find(Array.isArray);
return pairs?.length ? countText(pairs.length, pairs.length) : "";
}
function dependencyItem(value: unknown, names: Names): ReactNode {
const record = recordOf(value);
const ends = record && !Array.isArray(record) ? [record.from_name ?? record.fromName, record.to_name ?? record.toName]
: typeof value === "string" ? value.split(" -> ") : [];
if (ends.length !== 2 || !ends.every(end => typeof end === "string" && end.trim())) return "A dependency";
const [from, to] = (ends as string[]).map(end => idLike(end) ? "A deleted task" : personSafe(end.trim(), names));
return <>{from} <ArrowRight className="lp-proj-activity-link" size={12} aria-label="to" /> {to}</>;
}
function targetText(value: unknown): { text: string; title?: string } {
if (value === null || value === undefined || value === "") return { text: "None" };
const full = typeof value === "string" ? value.trim() : String(value);
const [list, ...rest] = full.split(". ");
const parts = list.split(", ");
return parts.length <= 3 ? { text: full } : { text: [joinShort(parts), ...rest].join(". "), title: full };
}
function amazonView(entry: ActivityEntry, names: Names): RowView {
const key = entry.attribute || entry.field || "listing";
const was = fieldValue(key, entry.before, names);
const now = fieldValue(key, entry.after, names);
const same = was !== null && was === now;
return { verb: "Changed on Amazon", item: entry.sku ? `SKU ${entry.sku}` : entry.asin ? `ASIN ${entry.asin}` : "Listing",
changes: same ? [] : [fieldChange(key, entry.field || labelOf(key), was, now)], notes: same ? [NO_CHANGE] : [] };
}
function rowView(entry: ActivityEntry, projectName: string, names: Names): RowView {
if (entry.source === "amazon") return amazonView(entry, names);
const transition = filterTransition(entry);
if (transition) {
const done = transition === "Done by filter";
const item = taskName(entry.to, names) || taskName(entry.from, names) || "A task";
const count = filterCount(entry.to, done) || (done ? "All targets meet the filter" : "");
const notes = [done ? "" : personSafe(transition, names), count].filter(Boolean).map(text => ({ text }));
return { verb: done ? "Done by filter" : "Filter check", item, changes: [], notes };
}
const verb = ACTION_VERB[entry.action] ?? sentenceCase(entry.action);
if (entry.action.endsWith(" task")) return taskView(entry, verb, names);
if (entry.action.endsWith(" dependency")) {
return { verb, item: dependencyItem(entry.action.startsWith("removed") ? entry.from ?? entry.to : entry.to ?? entry.from, names),
changes: [], notes: [] };
}
if (entry.action.endsWith(" contributor")) {
const person = fieldValue("contributors", entry.action.startsWith("removed") ? entry.from ?? entry.to : entry.to ?? entry.from, names);
return { verb, item: person && person !== "None" ? person : "A person", changes: [], notes: [] };
}
if (entry.action.endsWith(" targets")) {
const removed = entry.action === "removed targets";
const before = targetText(removed ? entry.from ?? entry.to : entry.from);
const after = targetText(removed ? null : entry.to);
const change = fieldChange("targets", "Targets", before.text, after.text);
return { verb, item: projectName, changes: [{ ...change, title: before.title || after.title }], notes: [] };
}
if (entry.action === "created" || entry.action === "deleted") {
const { record } = taskRecord(entry.action === "created" ? entry.to : entry.from);
const name = record && typeof record.name === "string" && record.name.trim() ? personSafe(record.name.trim(), names) : projectName;
return { verb, item: name, changes: [], notes: [] };
}
if (!entry.field) return { verb, item: projectName, changes: [], notes: [] };
const was = fieldValue(entry.field, entry.from, names);
const now = fieldValue(entry.field, entry.to, names);
const same = was !== null && was === now;
return { verb, item: projectName, changes: same ? [] : [fieldChange(entry.field, labelOf(entry.field), was, now)],
notes: same ? [NO_CHANGE] : [] };
}
function ActivityRow({ entry, now, names, projectName }: {
entry: ActivityEntry; now: number; names: Names; projectName: string;
}) {
const amazon = entry.source === "amazon";
const name = actorName(entry);
const view = rowView(entry, projectName, names);
return <li className="lp-proj-activity-row" data-kind={activityKind(entry)}>
<time className="lp-proj-activity-time" dateTime={entry.at} title={exactTime(entry.at)}
aria-label={exactTime(entry.at)} tabIndex={0}>{relativeTime(entry.at, now)}</time>
<div className="lp-proj-activity-person"><Owner name={name} compact /><span>{name}</span></div>
<div className="lp-proj-activity-change">
<p className="lp-proj-activity-action">
<span className="lp-proj-activity-verb">{view.verb}</span> <strong>{view.item}</strong>
</p>
{view.changes.length || view.notes.length ? <div className="lp-proj-activity-detail">
{view.changes.length ? <dl className="lp-proj-activity-fields">
{view.changes.map(change => <div className="lp-proj-activity-field" key={change.key} title={change.title}>
<dt>{change.label}</dt>
<dd>{change.updated ? <span>Updated</span> : <>
<span className="lp-proj-activity-before"><span className="lp-proj-activity-sr">From </span>{change.before}</span>
<ArrowRight size={14} aria-hidden="true" />
<span><span className="lp-proj-activity-sr">to </span>{change.after}</span>
</>}</dd>
</div>)}
</dl> : null}
{view.notes.map(note => <p className="lp-proj-activity-note" data-muted={note.muted || undefined}
key={note.text}>{note.text}</p>)}
</div> : null}
{amazon ? <div className="lp-proj-activity-meta">
{entry.sku && entry.asin ? <span>ASIN {entry.asin}</span> : null}
<span>Source: {entry.detectionSource || "unavailable"}</span>
</div> : null}
</div>
</li>;
}
interface ProjectActivitiesProps {
project: Project; entries: Activity[]; formId: string; active: boolean;
}
async function readActivity(projectId: string, cursor: string | null, signal: AbortSignal): Promise<ActivityPage> {
const query = cursor === null ? "" : `?${new URLSearchParams({ cursor })}`;
const page = await call<ActivityPage>(`/${enc(projectId)}/activity${query}`, { signal }, "Activity did not load.");
if (!page || !Array.isArray(page.activity) || (page.nextCursor !== null && typeof page.nextCursor !== "string")) {
throw new Error("Activity did not load.");
}
return page;
}
function failedRead(current: ActivityRead, reason: unknown): ActivityRead {
const status = reason instanceof ProjectRequestError ? reason.status : 0;
const blocked = status === 401 || status === 403 ? "denied" : status === 404 ? "deleted" : null;
return { ...current, loading: false, blocked,
activity: blocked ? [] : current.activity, nextCursor: blocked || status === 400 ? null : current.nextCursor,
initialized: status === 400 ? false : current.initialized,
error: blocked === "denied" ? "You do not have access to this activity."
: blocked === "deleted" ? "This project is no longer available."
: messageOf(reason, "Activity did not load."),
};
}
function ActivityTimeline({ project, entries, formId, active }: ProjectActivitiesProps) {
const [read, setRead] = useState<ActivityRead>(() => ({ activity: mergeActivity(entries), nextCursor: null,
initialized: false, loading: true, error: "", blocked: null }));
const [person, setPerson] = useState("");
const [kind, setKind] = useState<ActivityKind | "">("");
const [revision, setRevision] = useState(0);
const [now, setNow] = useState(Date.now);
const request = useRef<AbortController | null>(null);
const cursors = useRef(new Set<string>());
useEffect(() => {
if (!active) return;
setNow(Date.now());
const timer = window.setInterval(() => setNow(Date.now()), 60000);
return () => window.clearInterval(timer);
}, [active]);
useEffect(() => {
request.current?.abort();
const controller = new AbortController();
request.current = controller;
cursors.current.clear();
const initial = mergeActivity(entries);
setRead({ activity: initial, nextCursor: null, initialized: false, loading: true, error: "", blocked: null });
// Detail has no cursor. Establish the snapshot at the paged door before loading older rows.
void readActivity(project.id, null, controller.signal).then(page => {
if (!controller.signal.aborted) setRead({ ...page, activity: mergeActivity(page.activity, initial),
initialized: true, loading: false, error: "", blocked: null });
}).catch(reason => {
if (!controller.signal.aborted) setRead(current => failedRead(current, reason));
}).finally(() => { if (request.current === controller) request.current = null; });
return () => { controller.abort(); request.current?.abort(); };
}, [project.id, entries, revision]);
async function loadOlder() {
if (request.current || !read.initialized || !read.nextCursor || read.blocked) return;
const cursor = read.nextCursor;
const controller = new AbortController();
request.current = controller;
setRead(current => ({ ...current, loading: true, error: "" }));
try {
const page = await readActivity(project.id, cursor, controller.signal);
if (controller.signal.aborted) return;
if (page.nextCursor === cursor || (page.nextCursor && cursors.current.has(page.nextCursor))) {
throw new ProjectRequestError("Activity did not advance. Reload activity.", 400);
}
cursors.current.add(cursor);
setRead(current => ({ ...current, ...page, activity: mergeActivity(current.activity, page.activity), loading: false }));
} catch (reason) {
if (!controller.signal.aborted) setRead(current => failedRead(current, reason));
} finally { if (request.current === controller) request.current = null; }
}
const people = useMemo(() => {
const names = new Map<string, string>();
for (const entry of read.activity) names.set(actorKey(entry), actorName(entry));
return [...names].sort((a, b) => a[1].localeCompare(b[1]));
}, [read.activity]);
const names = useMemo<Names>(() => {
const known = new Map(people);
if (project.ownerUsername && project.owner && !known.has(project.ownerUsername)) {
known.set(project.ownerUsername, project.owner);
}
return known;
}, [people, project.ownerUsername, project.owner]);
const activity = useMemo(() => read.activity.filter(entry => (!person || actorKey(entry) === person)
&& (!kind || activityKind(entry) === kind)), [read.activity, person, kind]);
const groups = dayGroups(activity, now);
const filtered = Boolean(person || kind);
const clearFilters = () => { setPerson(""); setKind(""); };
return <section className="lp-proj-pane lp-proj-pane-stack lp-proj-log" role="tabpanel" id={`${formId}-pane-log`}
aria-labelledby={`${formId}-tab-log`} hidden={!active} tabIndex={0}>
<h2 className="lp-proj-title">{project.name}</h2>
{!read.blocked ? <div className="lp-proj-activity-tools" role="group" aria-label="Activity filters">
<Popover label={kind ? `Kind: ${kind}` : "Kind"} icon={<Funnel size={16} aria-hidden="true" />}
active={!!kind} tone="filter">
{() => <div className="cg-pop-body"><div className="cg-pop-title">Kind</div>
<div role="radiogroup" aria-label="Activity kind">
{["", ...KINDS].map(value => <label className="cg-radio-row" key={value}>
<input type="radio" name={`${formId}-activity-kind`} checked={kind === value}
onChange={() => setKind(value as ActivityKind | "")} /><span>{value || "All kinds"}</span>
</label>)}
</div>
</div>}
</Popover>
<Popover label={person ? `Person: ${people.find(([key]) => key === person)?.[1] || person}` : "Person"}
icon={<UserCircle size={16} aria-hidden="true" />} active={!!person} tone="filter">
{() => <div className="cg-pop-body"><div className="cg-pop-title">Person</div>
<div className="cg-pop-list" role="radiogroup" aria-label="Activity person">
<label className="cg-radio-row"><input type="radio" name={`${formId}-activity-person`} checked={!person}
onChange={() => setPerson("")} /><span>Everyone</span></label>
{people.map(([key, name]) => <label className="cg-radio-row" key={key}>
<input type="radio" name={`${formId}-activity-person`} checked={person === key}
onChange={() => setPerson(key)} /><span>{name}</span>
</label>)}
</div>
</div>}
</Popover>
{filtered ? <button type="button" className="cg-tb-btn" onClick={clearFilters}>Clear</button> : null}
<span className="lp-proj-muted" title="Filters apply to loaded activity. Load older to include earlier entries.">
{read.activity.length.toLocaleString()} loaded</span>
</div> : null}
{read.error ? <div className="lp-proj-activity-problem" role={read.blocked ? "status" : "alert"}>
<span className={read.blocked ? "lp-proj-muted" : "lp-proj-error"}>{read.error}</span>
{!read.blocked ? <button type="button" className="lp-proj-btn" disabled={read.loading}
onClick={() => { if (read.initialized && read.nextCursor) void loadOlder(); else setRevision(value => value + 1); }}>Retry</button> : null}
</div> : null}
<div className="lp-proj-activity-groups" aria-busy={read.loading}>
{groups.map(([label, rows]) => <section className="lp-proj-activity-day" key={label} aria-label={label}>
<h3>{label}</h3>
<ol className="lp-proj-activity" aria-label={`${label} activity`}>
{keyedEntries(rows).map(([key, entry]) => <ActivityRow key={key} entry={entry} now={now} names={names}
projectName={project.name} />)}
</ol>
</section>)}
{!read.loading && !read.error && !activity.length ? <p className="lp-proj-muted" role="status">
{filtered ? "No matching activity loaded" : "No activity yet"}</p> : null}
{read.loading ? <div className="lp-proj-loading" role="status" aria-label="Loading activity">
{[0, 1, 2].map(row => <div key={row} className="lp-proj-skeleton" aria-hidden="true" />)}
</div> : null}
</div>
{read.nextCursor && !read.blocked ? <div className="lp-proj-activity-footer">
<button type="button" className="lp-proj-btn" disabled={read.loading} onClick={() => void loadOlder()}>Load older</button>
</div> : null}
</section>;
}
export default function ProjectActivities(props: ProjectActivitiesProps) {
return <ActivityTimeline key={props.project.id} {...props} />;
}