Download web/src/apps/amazon-profit/Projects.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 15.6 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/amazon-profit/Projects.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/apps/amazon-profit/Projects.tsx
-
curl -L -o Projects.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/amazon-profit/Projects.tsx
15.6 kB
| import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; | |
| import { | |
| CenteredPopup, GRAIN_LABEL, LoadingRows, ProjectHeader, call, enc, messageOf, | |
| type Detail, type ProjectGrain, type ProjectList, | |
| } from "./ProjectsShared"; | |
| import ProjectResults from "./ProjectResults"; | |
| import { AddExisting, ProjectBrowser } from "./ProjectsList"; | |
| import ProjectOverview, { ProjectForm, RowScopeChip, inRowScope, type RowScope } from "./ProjectOverview"; | |
| import ProjectActivities from "./ProjectActivities"; | |
| import PdpActivities from "./pdp/PdpActivities"; | |
| import BrandRules from "./pdp/BrandRules"; | |
| import ContinueWorkflow, { useProjectPdp, type PdpProjectNavigation } from "./pdp/ContinueWorkflow"; | |
| import type { PdpProjectPane } from "./pdp/contract"; | |
| export { CenteredPopup, projectsTargetFromRow } from "./ProjectsShared"; | |
| export type { CenteredPopupProps, Project, ProjectGrain, ProjectsTarget } from "./ProjectsShared"; | |
| export { PROJECT_PRIORITIES, PROJECT_STATUSES } from "./ProjectsShared"; | |
| // ---- One project: Overview, Dashboard and Activities ---- | |
| const PROJECT_PANES = [ | |
| { key: "setup", label: "Overview" }, | |
| { key: "results", label: "Dashboard" }, | |
| { key: "log", label: "Activities" }, | |
| ] as const; | |
| type ExtraPane = { key: string; label: string; content: ReactNode }; | |
| type ProjectExtras = { | |
| pdp?: PdpProjectNavigation; backLabel?: string; onBack?: () => void; | |
| initialPane?: PdpProjectPane; | |
| headerExtra?: ReactNode; extraPanes?: ExtraPane[]; | |
| }; | |
| const RESULT_GRAIN = { sku: "sku", asin: "asin", parent_asin: "parent" } as const; | |
| function ProjectDetail({ id, canEdit: mayEdit, rowScope: openedFrom, onChanged, onDeleted, onCancel, | |
| pdp: navigation, headerExtra, extraPanes, initialPane }: { | |
| id: string; canEdit: boolean; rowScope?: RowScope; onChanged: () => void; onDeleted: () => void; onCancel: () => void; | |
| } & ProjectExtras) { | |
| const [detail, setDetail] = useState<Detail | null>(null); | |
| const [error, setError] = useState(""); | |
| const [tick, setTick] = useState(0); | |
| const [pane, setPane] = useState<string>(initialPane ?? "setup"); | |
| const projectChanged = () => { setTick(value => value + 1); onChanged(); }; | |
| const pdp = useProjectPdp(detail?.project, detail?.targets ?? [], tick, mayEdit && Boolean(detail?.canEdit), projectChanged, navigation); | |
| const extras = detail?.project.type === "pdp" ? [ | |
| { key: "brand", label: "Brand and rules", content: <BrandRules key={id} workflowId={id} projectName={detail.project.name} | |
| canEdit={mayEdit && detail.canEdit} active={pane === "brand"} /> }, ...(extraPanes ?? []), | |
| ] : []; | |
| const panes = extras.length ? [...PROJECT_PANES, ...extras] : PROJECT_PANES; | |
| // The row a Projects cell opened from scopes the Overview SKU list and the Dashboard until it is cleared. | |
| const [rowScope, setRowScope] = useState<RowScope | null>(() => openedFrom?.key.trim() | |
| ? { grain: openedFrom.grain, key: openedFrom.grain === "sku" ? openedFrom.key.trim() : openedFrom.key.trim().toUpperCase() } | |
| : null); | |
| const formId = useId(); | |
| const railRef = useRef<HTMLElement>(null); | |
| const panesRef = useRef<HTMLDivElement>(null); | |
| const loaded = detail !== null; | |
| const resultScope = useMemo(() => rowScope ? { grain: RESULT_GRAIN[rowScope.grain], keys: [rowScope.key] } : undefined, | |
| [rowScope]); | |
| const clearRowScope = useCallback(() => { | |
| setRowScope(null); | |
| // The chip leaves with its clear control, so focus moves to the open pane. | |
| requestAnimationFrame(() => panesRef.current | |
| ?.querySelector<HTMLElement>('[role="tabpanel"]:not([hidden])')?.focus({ preventScroll: true })); | |
| }, []); | |
| useEffect(() => { | |
| if (loaded) railRef.current?.querySelector<HTMLButtonElement>('[aria-selected="true"]')?.focus(); | |
| }, [loaded]); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| call<Detail>(`/${enc(id)}`, { signal: controller.signal }, "This project did not load.") | |
| .then((next) => { | |
| if (controller.signal.aborted) return; | |
| setDetail(next); | |
| setError(""); | |
| }, | |
| (reason) => { if (!controller.signal.aborted) setError(messageOf(reason, "This project did not load.")); }); | |
| return () => controller.abort(); | |
| }, [id, tick]); | |
| const rail = <nav className="lp-proj-detail-rail" ref={railRef} aria-label="Project sections"> | |
| <div className="lp-proj-detail-rail-list" role="tablist" aria-label="Project sections" aria-orientation="vertical"> | |
| {panes.map(({ key, label }, index) => <button key={key} type="button" role="tab" | |
| className={`lp-proj-detail-rail-row${pane === key ? " is-on" : ""}`} | |
| id={`${formId}-tab-${key}`} aria-controls={`${formId}-pane-${key}`} | |
| aria-selected={pane === key} tabIndex={pane === key ? 0 : -1} onClick={() => setPane(key)} | |
| onKeyDown={event => { | |
| let next: number; | |
| if (event.key === "ArrowDown" || event.key === "ArrowRight") next = (index + 1) % panes.length; | |
| else if (event.key === "ArrowUp" || event.key === "ArrowLeft") next = (index - 1 + panes.length) % panes.length; | |
| else if (event.key === "Home") next = 0; | |
| else if (event.key === "End") next = panes.length - 1; | |
| else return; | |
| event.preventDefault(); | |
| event.stopPropagation(); | |
| setPane(panes[next].key); | |
| railRef.current?.querySelectorAll<HTMLButtonElement>('[role="tab"]')[next]?.focus(); | |
| }}><span className="lp-proj-detail-rail-label">{label}</span></button>)} | |
| </div> | |
| </nav>; | |
| if (!detail) return <div className="lp-proj-detail-layout"> | |
| {rail} | |
| <div className="lp-proj-panes"> | |
| {PROJECT_PANES.map(({ key }) => <section key={key} className="lp-proj-pane" role="tabpanel" | |
| id={`${formId}-pane-${key}`} aria-labelledby={`${formId}-tab-${key}`} hidden={pane !== key} | |
| tabIndex={0} aria-busy={!error}> | |
| {error ? <div><p className="lp-proj-error" role="alert">{error}</p> | |
| <button type="button" className="lp-proj-btn" onClick={() => { setError(""); setTick(value => value + 1); }}>Retry</button> | |
| </div> : <LoadingRows />} | |
| </section>)} | |
| </div> | |
| </div>; | |
| const { project } = detail; | |
| const canEdit = mayEdit && detail.canEdit; | |
| const scopedAsins = rowScope ? [...new Set(detail.targets.filter(target => inRowScope(target, rowScope)) | |
| .flatMap(target => target.grain === "asin" ? [target.key] : target.asin ? [target.asin] : []))] : []; | |
| return <div className="lp-proj-detail-layout"> | |
| <ProjectHeader>{pdp ? <ContinueWorkflow pdp={pdp} targets={detail.targets} | |
| asin={scopedAsins.length === 1 ? scopedAsins[0] : undefined} /> : null}{headerExtra}</ProjectHeader> | |
| {rail} | |
| <div className="lp-proj-panes" ref={panesRef}> | |
| <section className="lp-proj-pane" role="tabpanel" id={`${formId}-pane-setup`} | |
| aria-labelledby={`${formId}-tab-setup`} hidden={pane !== "setup"} tabIndex={0}> | |
| <ProjectOverview id={id} detail={detail} canEdit={mayEdit} onChanged={onChanged} onDeleted={onDeleted} | |
| onCancel={onCancel} error={error} setError={setError} setDetail={setDetail} setTick={setTick} | |
| formId={formId} active={pane === "setup"} rowScope={rowScope} onClearRowScope={clearRowScope} pdp={pdp} /> | |
| </section> | |
| <section className="lp-proj-pane lp-proj-pane-stack" role="tabpanel" id={`${formId}-pane-results`} | |
| aria-labelledby={`${formId}-tab-results`} hidden={pane !== "results"} tabIndex={0}> | |
| <h2 className="lp-proj-title">{project.name}</h2> | |
| {rowScope ? <RowScopeChip scope={rowScope} onClear={clearRowScope} /> : null} | |
| <ProjectResults projectId={id} configs={project.resultConfigs ?? []} completedOn={project.completedOn} | |
| updatedAt={project.updatedAt} scope={resultScope} canEdit={canEdit} onSaved={() => { setTick(value => value + 1); onChanged(); }} /> | |
| </section> | |
| {project.type === "pdp" | |
| ? <PdpActivities project={project} formId={formId} active={pane === "log"} /> | |
| : <ProjectActivities project={project} entries={detail.activity} formId={formId} active={pane === "log"} />} | |
| {extras.map(extra => <section key={extra.key} className="lp-proj-pane" role="tabpanel" tabIndex={0} | |
| id={`${formId}-pane-${extra.key}`} aria-labelledby={`${formId}-tab-${extra.key}`} hidden={pane !== extra.key}> | |
| {extra.content} | |
| </section>)} | |
| </div> | |
| </div>; | |
| } | |
| // ---- The popup a Projects cell opens ---- | |
| export interface ProjectsPopupProps extends ProjectExtras { | |
| grain: ProjectGrain; | |
| rowKey: string; | |
| title?: string; | |
| selectedProjectId?: string; | |
| onClose: () => void; | |
| onChanged?: () => void; | |
| } | |
| type PopupView = { kind: "list" } | { kind: "detail"; id: string } | { kind: "new" } | { kind: "add" }; | |
| export function ProjectsPopup(props: ProjectsPopupProps) { | |
| return <ProjectsPopupContent key={`${props.grain}:${props.rowKey}:${props.selectedProjectId ?? ""}:${props.initialPane ?? ""}`} {...props} />; | |
| } | |
| function ProjectsPopupContent({ grain, rowKey, title, selectedProjectId, onClose, onChanged, | |
| pdp, backLabel, onBack, headerExtra, extraPanes, initialPane }: ProjectsPopupProps) { | |
| const [view, setView] = useState<PopupView>(() => selectedProjectId | |
| ? { kind: "detail", id: selectedProjectId } : { kind: "list" }); | |
| const [read, setRead] = useState<ProjectList | null>(null); | |
| const [error, setError] = useState(""); | |
| const [tick, setTick] = useState(0); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| call<ProjectList>(`?grain=${enc(grain)}&key=${enc(rowKey)}`, { signal: controller.signal }) | |
| .then((next) => { if (!controller.signal.aborted) { setRead(next); setError(""); } }, | |
| (reason) => { if (!controller.signal.aborted) setError(messageOf(reason, "Projects did not load.")); }); | |
| return () => controller.abort(); | |
| }, [grain, rowKey, tick]); | |
| const changed = useCallback(() => { setTick((value) => value + 1); onChanged?.(); }, [onChanged]); | |
| const onThisRow = useMemo(() => new Set((read?.projects ?? []).map((project) => project.id)), [read]); | |
| const canEdit = Boolean(read?.canEdit); | |
| const summary = read?.summary; | |
| const label = `${GRAIN_LABEL[grain]} ${rowKey}`; | |
| const actions = view.kind === "detail" | |
| ? <button type="button" className="lp-proj-btn lp-proj-btn-quiet" onClick={onBack ?? (() => setView({ kind: "list" }))}>{backLabel ?? "All projects"}</button> | |
| : view.kind === "list" && canEdit | |
| ? <> | |
| <button type="button" className="lp-proj-btn lp-proj-btn-quiet" onClick={() => setView({ kind: "add" })}>Add existing project</button> | |
| <button type="button" className="lp-proj-btn lp-proj-btn-primary" onClick={() => setView({ kind: "new" })}>New project</button> | |
| </> | |
| : null; | |
| return <CenteredPopup className="lp-proj-popup" onClose={onClose} actions={actions} | |
| title={view.kind === "new" ? "New project" : view.kind === "add" ? "Add project" : "Projects"} | |
| subtitle={view.kind === "new" || view.kind === "add" ? undefined : <> | |
| <span>{label}</span> | |
| {title && title !== rowKey ? <span className="lp-proj-clip lp-proj-sub-title">{title}</span> : null} | |
| {summary && summary.total ? <span>{summary.completed} of {summary.total} completed{read?.cause ? " in available projects" : ""}</span> : null} | |
| </>}> | |
| {view.kind === "list" | |
| ? <> | |
| {error ? <p className="lp-proj-error" role="alert">{error}</p> : null} | |
| {read?.cause ? <p className="lp-proj-muted" role="status">{read.cause}</p> : null} | |
| {!read && !error ? <LoadingRows /> : null} | |
| {read | |
| ? <ProjectBrowser read={read} grain={grain} onOpen={(id) => setView({ kind: "detail", id })} /> | |
| : null} | |
| </> | |
| : null} | |
| {view.kind === "detail" | |
| ? <ProjectDetail key={view.id} id={view.id} canEdit={canEdit} rowScope={{ grain, key: rowKey }} | |
| initialPane={view.id === selectedProjectId ? initialPane : undefined} | |
| pdp={pdp} backLabel={backLabel} onBack={onBack} headerExtra={headerExtra} extraPanes={extraPanes} | |
| onChanged={changed} onDeleted={onClose} onCancel={() => setView({ kind: "list" })} /> | |
| : null} | |
| {view.kind === "new" && canEdit | |
| ? <ProjectForm targets={[{ grain, key: rowKey }]} onCancel={() => setView({ kind: "list" })} | |
| onForbidden={() => { changed(); setView({ kind: "list" }); }} | |
| onCreated={(project) => { changed(); setView({ kind: "detail", id: project.id }); }} /> | |
| : null} | |
| {view.kind === "add" && canEdit | |
| ? <AddExisting exclude={onThisRow} onCancel={() => setView({ kind: "list" })} | |
| onPick={async (project) => { | |
| await call(`/${enc(project.id)}/targets`, { method: "POST", body: { targets: [{ grain, key: rowKey }] } }, | |
| "The project was not added."); | |
| changed(); | |
| setView({ kind: "list" }); | |
| }} /> | |
| : null} | |
| </CenteredPopup>; | |
| } | |
| // ---- The Projects tab: every project, the same rows ---- | |
| export function ProjectsPage({ pdp, headerExtra, extraPanes }: ProjectExtras = {}) { | |
| const [read, setRead] = useState<ProjectList | null>(null); | |
| const [error, setError] = useState(""); | |
| const [tick, setTick] = useState(0); | |
| const [open, setOpen] = useState<string | null>(null); | |
| const [creating, setCreating] = useState(false); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| call<ProjectList>("", { signal: controller.signal }) | |
| .then((next) => { if (!controller.signal.aborted) { setRead(next); setError(""); } }, | |
| (reason) => { if (!controller.signal.aborted) setError(messageOf(reason, "Projects did not load.")); }); | |
| return () => controller.abort(); | |
| }, [tick]); | |
| const reload = useCallback(() => setTick((value) => value + 1), []); | |
| const projects = read?.projects ?? []; | |
| const done = projects.filter((project) => project.status === "Completed").length; | |
| const counted = projects.filter((project) => project.status !== "Canceled").length; | |
| return <section className="lp-proj-page" aria-label="Projects"> | |
| <div className="lp-proj-page-bar"> | |
| <span className="lp-proj-page-count"> | |
| {read ? `${projects.length} ${read.cause ? "available " : ""}${projects.length === 1 ? "project" : "projects"}` : "Projects"} | |
| {read && counted ? <span className="lp-proj-muted">{done} of {counted} completed</span> : null} | |
| </span> | |
| {read?.canEdit | |
| ? <button type="button" className="lp-proj-btn lp-proj-btn-primary" onClick={() => setCreating(true)}>New project</button> | |
| : null} | |
| </div> | |
| {error ? <p className="lp-proj-error" role="alert">{error}</p> : null} | |
| {read?.cause ? <p className="lp-proj-muted" role="status">{read.cause}</p> : null} | |
| {!read && !error ? <LoadingRows /> : null} | |
| {read ? <ProjectBrowser read={read} onOpen={setOpen} /> : null} | |
| {open | |
| ? <CenteredPopup className="lp-proj-popup" title="Project" onClose={() => setOpen(null)}> | |
| <ProjectDetail key={open} id={open} canEdit={Boolean(read?.canEdit)} | |
| pdp={pdp} headerExtra={headerExtra} extraPanes={extraPanes} | |
| onChanged={reload} onDeleted={() => { setOpen(null); reload(); }} onCancel={() => setOpen(null)} /> | |
| </CenteredPopup> | |
| : null} | |
| {creating && read?.canEdit | |
| ? <CenteredPopup className="lp-proj-popup" title="New project" onClose={() => setCreating(false)}> | |
| <ProjectForm targets={[]} onCancel={() => setCreating(false)} onForbidden={() => { setCreating(false); reload(); }} | |
| onCreated={(project) => { setCreating(false); reload(); setOpen(project.id); }} /> | |
| </CenteredPopup> | |
| : null} | |
| </section>; | |
| } | |