iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / src / ErasePage.tsxmain at aacbc74

// ERASE AND REPLACE: what is on a deployment's domain and of its earlier iterate, read from the
// person's own Cloudflare account now, and the question whether all of it goes. The person types
// the domain's name to agree; the deploy run then erases this list and no other (erase.ts).
import { useState } from "react";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { LogOut, RefreshCw, TriangleAlert } from "lucide-react";
import { AppShell, AppShellBrand } from "@iterate-com/ui/components/app-shell";
import { DropdownMenuItem } from "@iterate-com/ui/components/ui/dropdown-menu";
import { Skeleton } from "@iterate-com/ui/components/ui/skeleton";
import { CloudNav } from "./CloudNav.tsx";
import { signOut } from "./api.ts";
import { readEraseList, startErase, type EraseList, type ErasedItem } from "./erase.ts";
import { comeBackToList, useDeployments, useMe } from "./your-deployments.ts";
import { Btn, LinkBtn, Notice, TextField } from "./parts.tsx";

const GROUPS: [ErasedItem["group"], string][] = [
  ["sites", "Websites and apps on this domain"],
  ["mail", "Mail"],
  ["dns", "DNS records"],
  ["rules", "Rules"],
  [
    "iterate",
    "The earlier iterate: its members, passkeys, files, config repo, secrets, logs and traces",
  ],
];
const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

export function Erase() {
  const page = useErasePage();
  const { domain, connected, found, user } = page;
  return (
    <AppShell
      app="iterate Cloud"
      mind={null}
      switcher={<AppShellBrand app="iterate Cloud" />}
      commandPalette={false}
      searchRow={false}
      nav={<CloudNav />}
      account={user ? { actor: user.email, email: user.email } : false}
      accountActions={
        <DropdownMenuItem data-sign-out onClick={signOut}>
          <LogOut />
          Sign out
        </DropdownMenuItem>
      }
      locationKey="/erase"
    >
      <div className="min-h-0 flex-1 overflow-auto bg-page">
        <div
          data-erase-page={domain}
          className="mx-auto flex w-full max-w-3xl flex-col gap-6 px-4 pt-6 pb-16 lg:px-8 lg:pt-12"
        >
          <header className="flex flex-wrap items-end justify-between gap-3">
            <div className="min-w-0">
              <h1 className="text-2xl font-semibold tracking-tight break-words">
                Everything on {domain || "the domain"} will be erased.
              </h1>
              <p className="mt-1 text-sm text-muted-foreground">
                iterate needs the whole domain. Whatever else uses it stops working, and this cannot
                be undone. Then iterate is deployed again, as on an empty domain.
              </p>
            </div>
            {connected && (
              <Btn
                variant="outline"
                size="sm"
                onClick={() => void found.refetch()}
                loading={found.isFetching}
              >
                <RefreshCw />
                Read again
              </Btn>
            )}
          </header>
          <EraseBody page={page} />
        </div>
      </div>
    </AppShell>
  );
}

/** The deployment the address names (`?account=…&domain=…`). */
function useAsked() {
  const search = useRouterState({ select: (state) => state.location.searchStr });
  const asked = new URLSearchParams(search);
  return {
    accountId: asked.get("account") || "",
    domain: (asked.get("domain") || "").toLowerCase(),
  };
}

/** What the page reads: who is signed in, what is on the domain, and the deployment it replaces. */
function useErasePage() {
  const { accountId, domain } = useAsked();
  const { me, asked: known } = useMe();
  const signedIn = me?.connected === true;
  const found = useQuery({
    queryKey: ["quiet", "/api/erase", accountId, domain],
    queryFn: () => readEraseList(accountId, domain),
    enabled: signedIn && !!accountId && !!domain,
    staleTime: 0,
  });
  // the access to Cloudflare can end while the tab still says it is there: the read says so (401)
  const connected = signedIn && found.data?.status !== 401;
  const deployment = useDeployments(connected).data?.deployments.find(
    (d) => d.domain === domain && d.account.id === accountId,
  );
  return { accountId, domain, me, known, found, connected, deployment, user: me?.user };
}

/** Under the heading: what stops the page (nobody known yet, no deployment chosen, no access to
 *  Cloudflare, a read that failed), or the list and its form. */
function EraseBody({ page }: { page: ReturnType<typeof useErasePage> }) {
  const { accountId, domain, me, known, found, connected, deployment, user } = page;
  if (!known) return <Skeleton className="h-24 w-full" />;
  if (!accountId || !domain)
    return (
      <Notice
        title="No deployment was chosen"
        action={<LinkBtn href="/deployments">Your deployments</LinkBtn>}
      />
    );
  if (!connected)
    return (
      <div data-connect>
        <Notice
          title={me ? "Connect Cloudflare again" : "Connect Cloudflare"}
          description="What is on the domain is read from your own Cloudflare account, and the erase is done with your access. Connect, then press “Erase and replace” again."
          action={
            <LinkBtn variant="default" href="/connect?level=full" onClick={comeBackToList}>
              Connect Cloudflare
            </LinkBtn>
          }
        />
      </div>
    );
  if (found.isPending) return <Skeleton className="h-40 w-full" />;
  if (!found.data?.list)
    return (
      <Notice
        variant="destructive"
        title={`We couldn't read what is on ${domain}`}
        description={found.data?.error || "Cloudflare did not answer. Read again in a moment."}
      />
    );
  return (
    <EraseList
      key={found.data.list.digest}
      list={found.data.list}
      account={{ id: accountId, name: accountNameOf(page) }}
      owner={deployment?.owner || user?.email || ""}
      reading={found.isFetching}
    />
  );
}

/** The account's name: as the sign-in lists it, else as the deployment's record has it. */
function accountNameOf({ me, accountId, deployment }: ReturnType<typeof useErasePage>) {
  return me?.accounts.find((a) => a.id === accountId)?.name || deployment?.account.name || "";
}

function EraseList({
  list,
  account,
  owner,
  reading,
}: {
  list: EraseList;
  account: { id: string; name: string };
  /** The address offered as the owner of the new iterate. */
  owner: string;
  reading: boolean;
}) {
  const navigate = useNavigate();
  // What the person typed over the offered address, an empty field too. Until they type, the
  // field follows `owner`, which can arrive after the list does.
  const [edited, setEdited] = useState<{ email: string }>();
  const email = edited ? edited.email : owner;
  const [typed, setTyped] = useState("");
  const [starting, setStarting] = useState(false);
  const [problem, setProblem] = useState<string | null>(null);
  const agreed = typed.trim().toLowerCase() === list.zone;
  const start = async () => {
    setStarting(true);
    const went = await startErase(account, list, email.trim(), typed);
    setStarting(false);
    setProblem(went);
    if (!went) void navigate({ to: "/" });
  };
  if (list.refusals.length > 0)
    return (
      <div data-erase-refused>
        <Notice
          variant="destructive"
          icon={<TriangleAlert />}
          title={`iterate cannot erase ${list.zone}, so nothing is erased`}
          description={
            <ul className="mt-1 list-disc space-y-1 pl-4">
              {list.refusals.map((why) => (
                <li key={why}>{why}</li>
              ))}
            </ul>
          }
          action={<LinkBtn href="/deployments">Your deployments</LinkBtn>}
        />
      </div>
    );
  return (
    <>
      <section data-erase-list className="rounded-lg border bg-card text-sm">
        {list.items.length === 0 ? (
          <p className="p-4" data-erase-empty>
            Nothing is on {list.zone}, and nothing of an earlier iterate is in the account.
          </p>
        ) : (
          GROUPS.map(([group, title]) => {
            const items = list.items.filter((item) => item.group === group);
            if (items.length === 0) return null;
            return (
              <div key={group} data-erase-group={group} className="border-b p-4 last:border-b-0">
                <h2 className="font-medium">
                  {title} <span className="font-normal text-muted-foreground">{items.length}</span>
                </h2>
                <ul className="mt-2 space-y-1 text-muted-foreground">
                  {items.map((item) => (
                    <li key={`${item.kind}:${item.id}`} className="break-words" data-erase-item>
                      {item.text}
                    </li>
                  ))}
                </ul>
              </div>
            );
          })
        )}
      </section>
      {list.unread.length > 0 && (
        <section data-erase-unread className="text-sm text-muted-foreground">
          <h2 className="font-medium text-foreground">Not looked at</h2>
          <ul className="mt-1 space-y-1">
            {list.unread.map((u) => (
              <li key={u.what}>
                Cloudflare did not let iterate read {u.what}. If there are any, they stay.
              </li>
            ))}
          </ul>
        </section>
      )}
      <section data-erase-kept className="text-sm text-muted-foreground">
        <h2 className="font-medium text-foreground">What stays</h2>
        <p className="mt-1">
          The domain itself, its nameservers and its registration. Your other domains. Workers that
          are not iterate's: only their routes and addresses on {list.zone} go. The members and the
          billing of the Cloudflare account {account.name}, and each of its API tokens that the list
          above does not name.
        </p>
      </section>
      <form
        data-erase-form
        className="flex flex-col gap-4 rounded-lg border border-destructive/40 bg-card p-4"
        onSubmit={(event) => {
          event.preventDefault();
          if (agreed && EMAIL.test(email.trim()) && !starting) void start();
        }}
      >
        <TextField
          label="The owner of the new iterate"
          type="email"
          autoComplete="email"
          value={email}
          onChange={(event) => setEdited({ email: event.target.value })}
          data-erase-owner
        />
        <TextField
          label={`Type ${list.zone} to agree`}
          autoComplete="off"
          autoCapitalize="none"
          spellCheck={false}
          value={typed}
          onChange={(event) => setTyped(event.target.value)}
          data-erase-typed
        />
        {problem && (
          <p role="alert" className="text-sm text-destructive" data-erase-problem>
            {problem}
          </p>
        )}
        <div>
          <Btn
            type="submit"
            variant="destructive"
            data-erase-start
            disabled={!agreed || !EMAIL.test(email.trim()) || reading}
            loading={starting}
          >
            Erase everything on {list.zone} and deploy iterate
          </Btn>
        </div>
      </form>
    </>
  );
}