62 lines
1.6 KiB
TypeScript
62 lines
1.6 KiB
TypeScript
// TreasureForm.tsx
|
|
// Form for adding a new treasure to a session.
|
|
import { useState } from "react";
|
|
import type { CampaignId, Treasure } from "@/lib/types";
|
|
import { pb } from "@/lib/pocketbase";
|
|
import { BaseForm } from "@/components/form/BaseForm";
|
|
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
|
|
|
/**
|
|
* Renders a form to add a new treasure. Calls onCreate with the new treasure document.
|
|
*/
|
|
export const NewTreasureForm = ({
|
|
campaign,
|
|
onCreate,
|
|
}: {
|
|
campaign: CampaignId;
|
|
onCreate: (treasure: Treasure) => Promise<void>;
|
|
}) => {
|
|
const [newTreasure, setNewTreasure] = useState("");
|
|
const [adding, setAdding] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
async function handleSubmit(e: React.FormEvent) {
|
|
e.preventDefault();
|
|
if (!newTreasure.trim()) return;
|
|
setAdding(true);
|
|
setError(null);
|
|
try {
|
|
const treasureDoc: Treasure = await pb.collection("documents").create({
|
|
campaign,
|
|
type: "treasure",
|
|
data: {
|
|
text: newTreasure,
|
|
discovered: false,
|
|
},
|
|
});
|
|
setNewTreasure("");
|
|
await onCreate(treasureDoc);
|
|
} catch (e: any) {
|
|
setError(e?.message || "Failed to add treasure.");
|
|
} finally {
|
|
setAdding(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<BaseForm
|
|
title="Create new treasure"
|
|
isLoading={adding || !newTreasure.trim()}
|
|
onSubmit={handleSubmit}
|
|
error={error}
|
|
content={
|
|
<SingleLineInput
|
|
value={newTreasure}
|
|
onChange={setNewTreasure}
|
|
placeholder="Treasure description"
|
|
/>
|
|
}
|
|
/>
|
|
);
|
|
};
|