"use client"; import { useEffect, useState } from "react"; import Link from "next/link"; import { ThumbsUp, ThumbsDown, Trash2 } from "lucide-react"; import { api } from "@/lib/client-api"; import type { MapCommunityView } from "@/shared/community"; import { useI18n } from "./I18nProvider"; import { Username } from "./Username"; import { ReportCommunity } from "./ReportCommunity"; export function MapCommunity({ datasetId, ownerId, }: { datasetId: string; ownerId: string | null; }) { const { t, locale } = useI18n(); const [data, setData] = useState(null); const [body, setBody] = useState(""); const [error, setError] = useState(""); const [message, setMessage] = useState(""); const [busy, setBusy] = useState(false); async function refresh() { const result = await api(`maps/${datasetId}/community`); setData(result); } useEffect(() => { let active = true; api(`maps/${datasetId}/community`) .then((result) => { if (active) { setData(result); setError(""); } }) .catch((e) => { if (active) setError(e.message); }); return () => { active = false; }; }, [datasetId]); async function act(action: () => Promise, success?: string) { setBusy(true); setError(""); setMessage(""); try { await action(); if (success) setMessage(success); await refresh(); } catch (e) { setError((e as Error).message); } finally { setBusy(false); } } async function more() { if (data?.nextCursor == null) return; setBusy(true); setError(""); try { const next = await api( `maps/${datasetId}/community?cursor=${encodeURIComponent(data.nextCursor)}`, ); setData((current) => current ? { ...next, comments: [ ...current.comments, ...next.comments.filter( (c) => !current.comments.some((existing) => existing.id === c.id), ), ], } : next, ); } catch (e) { setError((e as Error).message); } finally { setBusy(false); } } return (

{t("Map community")}

{error && (

{t(error)}{" "}

)} {!data && !error &&

{t("Loading comments…")}

} {data && ( <>
{data.viewer && ownerId && ownerId !== data.viewer.id && ( )}
{!data.viewer && (

{t("Sign in to react, comment, or report.")}

)}

{t("Comments")}

{data.viewer && (
{ e.preventDefault(); act(async () => { await api(`maps/${datasetId}/comments`, { body }); setBody(""); }, "Comment published."); }} >