75 lines
2.1 KiB
TypeScript
75 lines
2.1 KiB
TypeScript
// TreasureRow.tsx
|
|
// Displays a single treasure with discovered checkbox and text.
|
|
import type { Treasure, Session } from "@/lib/types";
|
|
import { pb } from "@/lib/pocketbase";
|
|
import { useState } from "react";
|
|
|
|
/**
|
|
* Renders a treasure row with a discovered checkbox and treasure text.
|
|
* Handles updating the discovered state and discoveredIn relationship.
|
|
*/
|
|
export const TreasureToggleRow = ({
|
|
treasure,
|
|
session,
|
|
}: {
|
|
treasure: Treasure;
|
|
session?: Session;
|
|
}) => {
|
|
const [checked, setChecked] = useState(
|
|
!!(treasure.data as any)?.treasure?.discovered,
|
|
);
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
|
const newChecked = e.target.checked;
|
|
setLoading(true);
|
|
setChecked(newChecked);
|
|
try {
|
|
await pb.collection("documents").update(treasure.id, {
|
|
data: {
|
|
...treasure.data,
|
|
treasure: {
|
|
...(treasure.data as any).treasure,
|
|
discovered: newChecked,
|
|
},
|
|
},
|
|
});
|
|
if (session || !newChecked) {
|
|
// If the session exists or the element is being unchecked, remove any
|
|
// existing discoveredIn relationship
|
|
const rels = await pb.collection("relationships").getList(1, 1, {
|
|
filter: `primary = "${treasure.id}" && type = "discoveredIn"`,
|
|
});
|
|
if (rels.items.length > 0) {
|
|
await pb.collection("relationships").delete(rels.items[0].id);
|
|
}
|
|
}
|
|
if (session) {
|
|
if (newChecked) {
|
|
await pb.collection("relationships").create({
|
|
primary: treasure.id,
|
|
secondary: [session.id],
|
|
type: "discoveredIn",
|
|
});
|
|
}
|
|
}
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="flex items-center gap-3">
|
|
<input
|
|
type="checkbox"
|
|
checked={checked}
|
|
onChange={handleChange}
|
|
className="accent-emerald-500 w-5 h-5"
|
|
aria-label="Discovered"
|
|
disabled={loading}
|
|
/>
|
|
<span>{treasure.data.text}</span>
|
|
</div>
|
|
);
|
|
};
|