Files
MineGeo/components/DraftEditor.tsx

366 lines
12 KiB
TypeScript

"use client";
import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { api } from "./StartGame";
import type { DatasetManifest } from "@/shared/protocol";
import type { ProcessingJob } from "@/shared/processing-progress";
import { ProcessingProgress } from "./ProcessingProgress";
import { PanoramaPreview } from "./PanoramaPreview";
import { OwnerContributions } from "./OwnerContributions";
import Link from "next/link";
import { MapRefresh } from "./MapRefresh";
import { MapAppeal } from "./MapAppeal";
type Draft = {
id: string;
name: string;
description: string;
state: string;
source: string;
rejection_reason: string | null;
map: string | null;
manifest: DatasetManifest;
previews: { id: string; label: string; image: string | null }[];
upload_jobs: ProcessingJob | null;
parent_dataset_id: string | null;
contribution_status: string | null;
allow_contributions: boolean;
contribution_server_address: string | null;
update_state: string | null;
report_strikes: number;
banned_at: string | null;
ban_reason: string | null;
};
export function DraftEditor({ id }: { id: string }) {
const dirty = useRef(false);
const [draft, setDraft] = useState<Draft | null>(null),
[name, setName] = useState(""),
[description, setDescription] = useState(""),
[selected, setSelected] = useState<string[]>([]),
[error, setError] = useState(""),
[message, setMessage] = useState(""),
[busy, setBusy] = useState(false);
const [preview, setPreview] = useState<string | null>(null);
const [version, setVersion] = useState(0);
useEffect(() => {
let disposed = false;
let timer: ReturnType<typeof setTimeout>;
const load = () =>
api<Draft>("datasets/" + id)
.then((d) => {
if (disposed) return;
setError("");
setDraft(d);
if (!dirty.current) {
setName(d.name);
setDescription(d.description);
setSelected(d.manifest.viewpoints.map((p) => p.id));
}
if (
d.banned_at ||
["uploading", "processing"].includes(d.state) ||
["queued", "running"].includes(d.upload_jobs?.state ?? "")
)
timer = setTimeout(load, 5000);
})
.catch((e) => {
if (!disposed) {
setError(e.message);
timer = setTimeout(load, 5000);
}
});
load();
return () => {
disposed = true;
clearTimeout(timer);
};
}, [id, version]);
async function save(submit = false) {
setBusy(true);
setError("");
setMessage("");
try {
await api(
"datasets/" + id,
{ name, description, selectedIds: selected },
"PATCH",
);
dirty.current = false;
if (submit) {
await api("datasets/" + id + "/submit", {});
setVersion((v) => v + 1);
setMessage(
draft?.parent_dataset_id
? "Submitted for map owner approval."
: "Submitted for moderator review.",
);
} else setMessage("Draft saved.");
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
async function cancel() {
setBusy(true);
try {
await api("datasets/" + id + "/cancel", {});
if (draft?.parent_dataset_id) {
setVersion((v) => v + 1);
setMessage("Contribution withdrawn. Its pending quota is released.");
return;
}
setDraft((d) =>
d
? { ...d, state: "failed", rejection_reason: "Processing cancelled" }
: d,
);
setMessage("Processing cancelled.");
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
if (!draft)
return (
<p role={error ? "alert" : undefined}>{error || "Loading your draft…"}</p>
);
const editable =
(["draft", "rejected"].includes(draft.state) ||
draft.state === "published") &&
draft.update_state !== "review" &&
!["submitted", "accepted", "rejected"].includes(
draft.contribution_status ?? "",
);
const refreshing =
draft.upload_jobs?.kind === "map" &&
["queued", "running"].includes(draft.upload_jobs.state);
const minimum = draft.parent_dataset_id ? 1 : 5;
return (
<>
<div className="editor-navigation">
<Link href="/dashboard">← Your maps</Link>
<a href="#locations">Choose locations</a>
{!draft.parent_dataset_id && <a href="#map-tools">Map tools</a>}
</div>
<span className="badge">{draft.state}</span>
{!draft.parent_dataset_id &&
(draft.report_strikes > 0 || draft.banned_at) && (
<MapAppeal
id={id}
strikes={draft.report_strikes}
bannedAt={draft.banned_at}
banReason={draft.ban_reason}
onChange={() => setVersion((v) => v + 1)}
/>
)}
{draft.update_state && (
<span className="badge">Update: {draft.update_state}</span>
)}
{draft.contribution_status && (
<p role="status">
Contribution: {draft.contribution_status}.{" "}
{draft.state === "failed"
? "This contribution no longer reserves panorama slots. Upload a fresh capture to try again."
: draft.contribution_status === "accepted"
? "The owner included your panoramas in the map draft. Map updates become playable after moderator approval."
: draft.contribution_status === "submitted"
? "Waiting for the map owner's approval."
: draft.contribution_status === "rejected"
? "Upload a fresh capture if you want to try again."
: "Choose your locations, then submit them to the map owner."}
</p>
)}
{draft.state === "published" && (
<p className="muted">
The approved version stays playable while you edit and moderators
review your update.
</p>
)}
<ProcessingProgress job={draft.upload_jobs} />
{draft.upload_jobs?.kind === "map" &&
draft.upload_jobs.state === "failed" && (
<p role="alert" className="error-message">
Map refresh failed: {draft.upload_jobs.error}. Your previous map is
still available. Try refreshing again below.
</p>
)}
{refreshing && (
<p role="status" className="success-message">
Refreshing your guessing map. This page updates automatically; the
published version stays playable.
</p>
)}
{["uploading", "processing"].includes(draft.state) && (
<p role="status" className="success-message">
{draft.state === "uploading"
? "Waiting for the capture tool to finish uploading. Retry upload in the tool if the connection was interrupted."
: "Your map and panoramas are being rendered. This page updates automatically."}
</p>
)}
{draft.rejection_reason && (
<p className="error-message" role="alert">
{draft.rejection_reason}
</p>
)}
<p className="muted">
{draft.source === "plugin"
? "Server-generated views use vanilla terrain and simplified lighting. Entities, shaders, custom packs and dynamic sign text are omitted."
: "Player captures show the terrain received by the client. Unexplored map coverage remains blank."}
</p>
{draft.map && (
<div className="detail-map" style={{ maxWidth: 600 }}>
<Image
src={draft.map}
width={1024}
height={1024}
loading="eager"
alt="Draft surface map"
unoptimized
/>
</div>
)}
<section className="editor-panel">
<h2>Map details</h2>
<label className="field">
Map name
<input
value={name}
onChange={(e) => {
dirty.current = true;
setName(e.target.value);
}}
disabled={!editable}
/>
</label>
<label className="field">
Description
<textarea
value={description}
onChange={(e) => {
dirty.current = true;
setDescription(e.target.value);
}}
disabled={!editable}
/>
</label>
</section>
<h2 id="locations">Choose your locations.</h2>
<p className="muted">
Keep at least {minimum} clear, useful panorama{minimum === 1 ? "" : "s"}
. Selected: {selected.length} / 24
</p>
<div className="preview-grid">
{draft.previews.map((p) => (
<div className="preview-tile" key={p.id}>
<label>
<input
type="checkbox"
checked={selected.includes(p.id)}
disabled={!editable || busy}
aria-label={`Keep ${p.label}`}
onChange={(e) => {
dirty.current = true;
setSelected((s) =>
e.target.checked
? [...s, p.id]
: s.filter((id) => id !== p.id),
);
}}
/>
{p.image && (
<Image
src={p.image}
width={512}
height={512}
alt={p.label}
unoptimized
/>
)}
<span>{p.label}</span>
</label>
{p.image && (
<button className="button full" onClick={() => setPreview(p.id)}>
Look around
</button>
)}
</div>
))}
</div>
{preview && (
<PanoramaPreview
endpoint={`datasets/${id}/panoramas`}
initialId={preview}
onClose={() => setPreview(null)}
/>
)}
{editable && (
<div className="inline-actions">
<button
className="button"
disabled={busy || refreshing || selected.length < minimum}
onClick={() => save()}
>
Save draft
</button>
<button
className="button primary"
disabled={busy || refreshing || selected.length < minimum}
onClick={() => save(true)}
>
{draft.parent_dataset_id
? "Submit to map owner →"
: "Submit for review →"}
</button>
</div>
)}
{!draft.parent_dataset_id && (
<div id="map-tools">
<MapRefresh
id={id}
disabled={busy || !editable || refreshing}
onQueued={() => {
setMessage(
"Map refresh queued. Keep this page open to follow progress.",
);
setVersion((v) => v + 1);
}}
/>
</div>
)}
{!draft.parent_dataset_id && (
<OwnerContributions
id={id}
allowed={draft.allow_contributions}
serverAddress={draft.contribution_server_address}
bounds={draft.manifest.bounds}
count={draft.previews.length}
locked={draft.state === "review" || draft.update_state === "review"}
onChange={() => setVersion((v) => v + 1)}
/>
)}
{(["uploading", "processing"].includes(draft.state) ||
(draft.parent_dataset_id &&
["pending", "submitted"].includes(
draft.contribution_status ?? "",
))) && (
<button className="button" disabled={busy} onClick={cancel}>
{draft.parent_dataset_id
? "Withdraw contribution"
: "Cancel processing"}
</button>
)}
{error && (
<p role="alert" className="error-message">
{error}
</p>
)}
{message && (
<p role="status" className="success-message">
{message}
</p>
)}
</>
);
}