All files / src/features/sessions KeepSortingButton.tsx

92.3% Statements 12/13
91.66% Branches 11/12
100% Functions 2/2
100% Lines 11/11

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 463x                                       25x 25x           6x 1x 1x 5x 4x         4x   5x   5x          
"use client";
 
import { useRouter } from "next/navigation";
import { AsyncActionButton } from "@/features/sorting/AsyncActionButton";
import { patchSessionStatus } from "@/features/sorting/sessionStatusPatch";
 
interface KeepSortingButtonProps {
  /** ULID collection.id (the sessions API never takes the slug). */
  collectionId: string;
  curatorId: string;
  sortHref: string;
  session: { id: string; status: "active" | "paused" } | null;
  /** Full width on phone, so the one primary action is never the smallest thing there. */
  fullWidth?: boolean;
}
 
// The collection's one sort action (spec §4.1): "Keep sorting" resumes the open
// sort (reactivating a paused one); otherwise "Start sorting" opens a new one with
// the server's defaults. A 409 means a sort was opened elsewhere — just join it.
export function KeepSortingButton({ collectionId, curatorId, sortHref, session, fullWidth }: KeepSortingButtonProps) {
  const router = useRouter();
  return (
    <AsyncActionButton
      fullWidth={fullWidth}
      label={session ? "Keep sorting" : "Start sorting"}
      variant="primary"
      action={async () => {
        if (session?.status === "paused") {
          const res = await patchSessionStatus({ curatorId, sessionId: session.id }, "active");
          Iif (!res.ok) throw new Error("resume");
        } else if (session === null) {
          const res = await fetch("/api/sessions", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ collectionId }),
          });
          if (!res.ok && res.status !== 409) throw new Error("start");
        }
        router.push(sortHref); // stays busy through the navigation
        // Start sorting sits on the sort URL itself; a same-URL push may not re-render it.
        router.refresh();
      }}
    />
  );
}