"use client";
import { useReducer, useState } from "react";
import { addAppFlow, type FlowState } from "../lib/add-app-flow.ts";
import type { Snippet } from "../lib/apps.ts";
import { CloseIcon, CopyIcon } from "./Icons.tsx";
export function AddAppView({
state,
remaining,
onAdd,
onName,
onCreate,
onClose,
onCopy,
copied,
}: {
state: FlowState;
remaining: number;
onAdd: () => void;
onName: (name: string) => void;
onCreate: () => void;
onClose: () => void;
onCopy: (text: string) => void;
copied: string | null;
}) {
if (state.step === "list") {
return (
{remaining > 0 ? `${remaining} left on your plan` : "Your plan's apps are all in use"}
);
}
if (state.step === "form" || state.step === "saving") {
return (
);
}
const block = (label: string, text: string) => (
{label}
{text}
{copied === text ?
Copied : null}
);
return (
{state.name} is ready
{block("Deploy", state.snippet.deploy)}
{block("Add to your page", state.snippet.script)}
);
}
export function AddApp({ remaining }: { remaining: number }) {
const [state, dispatch] = useReducer(addAppFlow, { step: "list" } as FlowState);
const [copied, setCopied] = useState(null);
async function create() {
if (state.step !== "form" || !state.name.trim()) return;
const name = state.name;
dispatch({ type: "click_create" });
try {
const res = await fetch("/api/apps", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name }) });
const body = (await res.json()) as { snippet?: Snippet; error?: string };
if (!res.ok || !body.snippet) dispatch({ type: "failed", error: body.error ?? "Could not add the app." });
else dispatch({ type: "created", snippet: body.snippet });
} catch {
dispatch({ type: "failed", error: "Could not reach Railyard. Check your connection." });
}
}
return (
dispatch({ type: "click_add" })}
onName={(name) => dispatch({ type: "type_name", name })}
onCreate={create}
onClose={() => {
dispatch({ type: "click_close" });
if (state.step === "done") window.location.reload();
}}
onCopy={(text) => {
navigator.clipboard?.writeText(text).then(() => setCopied(text), () => setCopied(null));
}}
/>
);
}