File size: 8,106 Bytes
9e15897 | 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 | import { useCallback, useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { ConfirmDialog } from "../../ui/ConfirmDialog";
import { Busy } from "../../ui/Busy";
import { ActionsError, completeAction, deleteAction, listActions, subscribeActions } from "./actionsApi";
import type { ActionGrain, ActionPage, ActionStatus, SkuAction } from "./actionsApi";
import "../../styles/sdlc81/sku-actions.css";
export interface ActionListProps {
appId: string;
canEdit?: boolean;
canRead?: boolean;
grain?: ActionGrain;
entityKey?: string;
pageSize?: number;
onOpenEntity?: (action: SkuAction) => void;
onSelectCompleted?: (action: SkuAction) => void;
onPermissionsChange?: (canEdit: boolean) => void;
toolbar?: ReactNode;
children?: ReactNode;
}
type Load = { phase: "loading" } | { phase: "error"; error: unknown } | { phase: "ready"; page: ActionPage };
const STATUSES: [ActionStatus, string][] = [["open", "Open"], ["due", "Due"], ["overdue", "Overdue"], ["done", "Completed"]];
export function actionDate(value: string | null): string {
return value ? new Date(`${value}T00:00:00Z`).toLocaleDateString(undefined,
{ day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }) : "Not set";
}
export function ActionList(props: ActionListProps) {
return <ActionListPage key={JSON.stringify([props.appId, props.grain, props.entityKey, props.canRead])} {...props} />;
}
function ActionListPage({ appId, canEdit = false, canRead = true, grain, entityKey, pageSize = 20,
onOpenEntity, onSelectCompleted, onPermissionsChange, toolbar, children }: ActionListProps) {
const [status, setStatus] = useState<ActionStatus>("open");
const [cursors, setCursors] = useState<(string | null)[]>([null]);
const [attempt, setAttempt] = useState(0);
const [load, setLoad] = useState<{ key: string; value: Load }>({ key: "", value: { phase: "loading" } });
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState("");
const [deleting, setDeleting] = useState<SkuAction | null>(null);
const mutation = useRef(false);
const permissions = useRef(onPermissionsChange);
permissions.current = onPermissionsChange;
const cursor = cursors.at(-1);
const requestKey = JSON.stringify([appId, grain, entityKey, status, cursor, pageSize, attempt]);
const state = load.key === requestKey ? load.value : { phase: "loading" } as Load;
const editable = canEdit && state.phase === "ready" && state.page.canEdit;
const reload = useCallback(() => { setCursors([null]); setAttempt(n => n + 1); }, []);
useEffect(() => subscribeActions(appId, reload), [appId, reload]);
useEffect(() => {
permissions.current?.(false);
if (!canRead) return;
const controller = new AbortController();
void listActions({ appId, grain, entityKey, status, cursor, limit: pageSize }, controller.signal)
.then(page => {
if (controller.signal.aborted) return;
setLoad({ key: requestKey, value: { phase: "ready", page } });
permissions.current?.(page.canEdit);
}).catch(reason => {
if (!controller.signal.aborted) setLoad({ key: requestKey, value: { phase: "error", error: reason } });
});
return () => controller.abort();
}, [appId, grain, entityKey, status, cursor, pageSize, attempt, requestKey, canRead]);
const change = async (row: SkuAction, remove: boolean) => {
if (!editable || mutation.current) return;
mutation.current = true;
setBusy(row.id);
setError("");
try {
if (remove) await deleteAction(appId, row.id);
else await completeAction(appId, row.id);
setDeleting(null);
} catch (reason) {
if (reason instanceof ActionsError && [401, 403, 404].includes(reason.status)) reload();
setError(reason instanceof ActionsError && reason.status === 403
? "You can view actions but cannot change them" : remove ? "Could not delete this action" : "Could not complete this action");
setDeleting(null);
} finally { mutation.current = false; setBusy(null); }
};
return <section className="sku-action-list" aria-label="Actions">
<header className="sku-actions-head"><h3>Actions</h3>
{toolbar}
<label className="sku-actions-field"><span className="sku-actions-sr">Action status</span>
<select aria-label="Action status" value={status} disabled={!canRead || !!busy} onChange={event => {
setStatus(event.target.value as ActionStatus); setCursors([null]); setError("");
}}>{STATUSES.map(([value, label]) => <option value={value} key={value}>{label}</option>)}</select>
</label>
</header>
{children}
{!canRead ? <p role="status">You do not have access to these actions</p>
: state.phase === "loading" ? <div className="sku-actions-loading" role="status" aria-label="Loading actions" aria-busy="true">
<span /><span /><span />
</div>
: state.phase === "error" ? <p className="sku-actions-error" role="alert">
{state.error instanceof ActionsError ? state.error.message : "Could not load actions"}{" "}
<button className="sku-actions-button" type="button" onClick={reload}>Retry</button>
</p> : <>
{!editable && <p className="sku-actions-muted" role="status">View only</p>}
{state.page.records.length === 0 ? <p role="status">{status === "done" ? "No completed actions" : `No ${status} actions`}</p>
: <ul className="sku-actions-rows">{state.page.records.map(row => <li key={row.id} data-action-id={row.id}>
<div className="sku-actions-row-head"><span className="sku-actions-title">{row.title}</span>
<span className={`sku-actions-status is-${status}`}>{row.status === "done" ? "Completed" : STATUSES.find(([value]) => value === status)?.[1]}</span>
</div>
{entityKey === undefined && (onOpenEntity
? <button type="button" className="sku-actions-button is-link" onClick={() => onOpenEntity(row)}>{row.key}</button>
: <span className="sku-actions-muted">{row.key}</span>)}
<dl className="sku-actions-facts"><div><dt>Owner</dt><dd>{row.owner || "Unassigned"}</dd></div>
<div><dt>Start date</dt><dd>{actionDate(row.start_on)}</dd></div>
<div><dt>Deadline</dt><dd>{actionDate(row.deadline_on)}</dd></div>
{row.completed_on && <div><dt>Completed</dt><dd>{actionDate(row.completed_on)}</dd></div>}
</dl>
{row.status === "done" && onSelectCompleted && <button type="button" className="sku-actions-button is-link"
onClick={() => onSelectCompleted(row)}>View results</button>}
{editable && <div className="sku-actions-row-buttons">
{row.status !== "done" && <button type="button" className="sku-actions-button" disabled={!!busy}
onClick={() => void change(row, false)}><Busy busy={busy === row.id} idle="Mark complete" doing="Completing" /></button>}
<button type="button" className="sku-actions-button is-danger" disabled={!!busy}
onClick={() => setDeleting(row)}>Delete</button>
</div>}
</li>)}</ul>}
<nav className="sku-actions-pager" aria-label="Action pages">
<button type="button" className="sku-actions-button" disabled={cursors.length === 1 || !!busy}
onClick={() => setCursors(values => values.slice(0, -1))}>Previous</button>
<span>Page {cursors.length.toLocaleString()}</span>
<button type="button" className="sku-actions-button" disabled={!state.page.next_cursor || !!busy}
onClick={() => setCursors(values => [...values, state.page.next_cursor])}>Next</button>
</nav>
</>}
{error && <p className="sku-actions-error" role="alert">{error}</p>}
<ConfirmDialog open={!!deleting} title="Delete action" body={deleting?.title} confirmLabel="Delete"
tone="destructive" busy={!!busy} onCancel={() => setDeleting(null)}
onConfirm={() => { if (deleting) void change(deleting, true); }} />
</section>;
}
|