import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import BrowserOnly from "@docusaurus/BrowserOnly"; import Link from "@docusaurus/Link"; import { useLocation } from "@docusaurus/router"; import useDocusaurusContext from "@docusaurus/useDocusaurusContext"; import { useColorMode } from "@docusaurus/theme-common"; import Layout from "@theme/Layout"; import { IconArrowBigDown, IconArrowBigUp, IconArrowLeft, IconCheck, IconChevronLeft, IconChevronRight, IconCopy, IconDownload, IconEdit, IconSend, IconTrash, IconX, } from "@tabler/icons-react"; import { Highlight, themes } from "prism-react-renderer"; import type { ClientResponseError } from "pocketbase"; import type { StoreComment, StoreSubmission, StoreVote } from "@site/src/lib/pocketbase"; import { getPocketBase, getSubmissionFileUrl } from "@site/src/lib/pocketbase"; import type { SubmissionType } from "@site/src/lib/store-schema"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { cn, errorMessage } from "@/lib/utils"; const typeLabels: Record = { css: "CSS", widget: "Widget" }; const typeDotColors: Record = { css: "bg-blue-500", widget: "bg-yellow-500" }; const contentLanguages: Record = { css: "css", widget: "json" }; const prismThemes = { light: themes.github, dark: themes.dracula } as const; const copyState = [ { Icon: IconCopy, label: "Copy", iconClass: "" }, { Icon: IconCheck, label: "Copied!", iconClass: "text-green-500" }, ] as const; const scoreClassBySign = { positive: "text-foreground", negative: "text-destructive", neutral: "" } as const; const dotClass = ["bg-white/40", "bg-white"]; const commentAuthorName = (c: StoreComment) => c.expand?.author?.name || c.expand?.author?.username || "unknown"; const relativeTime = (date: string) => { const minutes = Math.floor((Date.now() - new Date(date).getTime()) / 60000); if (minutes < 1) return "just now"; if (minutes < 60) return `${minutes}m ago`; const hours = Math.floor(minutes / 60); if (hours < 24) return `${hours}h ago`; return `${Math.floor(hours / 24)}d ago`; }; const scoreSign = (score: number): keyof typeof scoreClassBySign => { if (score > 0) return "positive"; if (score < 0) return "negative"; return "neutral"; }; const parseSubmissionId = (pathname: string) => { const segments = pathname.split("/").filter(Boolean); const last = segments[segments.length - 1]; if (!last || last === "workshop") return null; return last; }; const downloadJson = (s: StoreSubmission) => { const url = URL.createObjectURL(new Blob([s.content], { type: "application/json" })); Object.assign(document.createElement("a"), { href: url, download: `${s.title.replace(/[^a-z0-9-_]+/gi, "-").toLowerCase()}.json`, }).click(); URL.revokeObjectURL(url); }; const voteDelta = (prev: 1 | -1 | undefined, next: 1 | -1): [up: number, down: number] => { if (!prev) return next === 1 ? [1, 0] : [0, 1]; if (prev === next) return next === 1 ? [-1, 0] : [0, -1]; return next === 1 ? [1, -1] : [-1, 1]; }; const isNotFound = (caught: unknown) => typeof caught === "object" && caught !== null && "status" in caught && (caught as ClientResponseError).status === 404; const DetailSkeleton = () => (
); const ScreenshotGallery = ({ urls, title }: { urls: string[]; title: string }) => { const [idx, setIdx] = useState(0); return (
{`${title}
{urls.length > 1 && ( <>
{urls.map((_, i) => (
)}
); }; const colorModeKeys = { dark: "dark", light: "light" } as const; const CodeBlock = ({ content, language }: { content: string; language: string }) => { const { colorMode } = useColorMode(); const theme = prismThemes[colorModeKeys[colorMode as keyof typeof colorModeKeys] ?? "light"]; return ( {({ className, style, tokens, getLineProps, getTokenProps }) => (
          {tokens.map((line, i) => (
            
{line.map((token, key) => ( ))}
))}
)}
); }; const CommentsSection = ({ submissionId, pb, currentUserId, onRequireAuth, onError, }: { submissionId: string; pb: ReturnType; currentUserId?: string; onRequireAuth: (action: string) => Promise; onError: (message: string) => void; }) => { const [rows, setRows] = useState([]); const [loading, setLoading] = useState(true); const [fetchError, setFetchError] = useState(false); const [newComment, setNewComment] = useState(""); const [editingId, setEditingId] = useState(null); const [editContent, setEditContent] = useState(""); useEffect(() => { let cancelled = false; setLoading(true); setFetchError(false); pb.collection("comments") .getFullList({ filter: pb.filter("submission = {:id}", { id: submissionId }), sort: "-created", expand: "author", }) .then((data) => { if (!cancelled) setRows(data); }) .catch(() => { if (!cancelled) setFetchError(true); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; }, [pb, submissionId]); const handleAdd = async () => { const trimmed = newComment.trim(); if (!trimmed) return; const userId = await onRequireAuth("comment"); if (!userId) return; try { const created = await pb .collection("comments") .create({ submission: submissionId, content: trimmed, author: userId }, { expand: "author" }); setRows((prev) => [created, ...prev]); setNewComment(""); } catch (caught) { onError(errorMessage(caught, "Failed to post comment")); } }; const handleUpdate = async (id: string) => { const trimmed = editContent.trim(); if (!trimmed) return; try { const updated = await pb .collection("comments") .update(id, { content: trimmed }, { expand: "author" }); setRows((prev) => prev.map((c) => (c.id === id ? updated : c))); setEditingId(null); } catch (caught) { onError(errorMessage(caught, "Failed to update comment")); } }; const handleDelete = async (id: string) => { try { await pb.collection("comments").delete(id); setRows((prev) => prev.filter((c) => c.id !== id)); } catch (caught) { onError(errorMessage(caught, "Failed to delete comment")); } }; return (

Comments

setNewComment(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") void handleAdd(); }} />
{loading &&

Loading comments…

} {!loading && fetchError &&

Failed to load comments

} {!loading && !fetchError && rows.length === 0 && (

No comments yet

)}
{rows.map((comment) => { const isOwner = currentUserId === comment.author; const isEditing = editingId === comment.id; return (
{commentAuthorName(comment)} {relativeTime(comment.created)} {isOwner && !isEditing && (
)}
{isEditing ? (
setEditContent(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") void handleUpdate(comment.id); }} />
) : (

{comment.content}

)}
); })}
); }; const DeleteConfirmButton = ({ onConfirm }: { onConfirm: () => void }) => { const [pending, setPending] = useState(false); const timer = useRef>(null); useEffect( () => () => { if (timer.current) clearTimeout(timer.current); }, [], ); const handleClick = () => { if (!pending) { setPending(true); timer.current = setTimeout(() => setPending(false), 3000); return; } setPending(false); onConfirm(); }; return ( ); }; const MarketplaceDetail = ({ storeUrl }: { storeUrl: string }) => { const location = useLocation(); const submissionId = parseSubmissionId(location.pathname); const pb = useMemo(() => getPocketBase(storeUrl), [storeUrl]); const [submission, setSubmission] = useState(null); const [userVote, setUserVote] = useState(); const [user, setUser] = useState(pb.authStore.record); const [loading, setLoading] = useState(true); const [notFound, setNotFound] = useState(false); const [error, setError] = useState(null); const [copied, setCopied] = useState(false); const [copyFailed, setCopyFailed] = useState(false); const copyTimer = useRef>(null); const voting = useRef(false); const requireUserId = useCallback( async (action: string) => { if (!pb.authStore.isValid) { try { await pb.collection("users").authWithOAuth2({ provider: "github" }); } catch (caught) { setError(errorMessage(caught, "Sign in failed")); return null; } } const userId = pb.authStore.record?.id; if (!userId) { setError(`Sign in to ${action}`); return null; } return userId; }, [pb], ); useEffect(() => { if (pb.authStore.isValid) pb.collection("users") .authRefresh() .catch(() => pb.authStore.clear()); return pb.authStore.onChange(() => setUser(pb.authStore.record)); }, [pb]); useEffect( () => () => { if (copyTimer.current) clearTimeout(copyTimer.current); }, [], ); useEffect(() => { if (!submissionId) { setNotFound(true); setLoading(false); return; } let cancelled = false; setLoading(true); setNotFound(false); setError(null); const load = async () => { try { const record = await pb.collection("marketplace").getOne(submissionId); if (cancelled) return; setSubmission(record); if (pb.authStore.isValid && pb.authStore.record) { const votes = await pb.collection("votes").getFullList({ filter: pb.filter("user = {:uid} && submission = {:sid}", { uid: pb.authStore.record.id, sid: submissionId, }), }); if (!cancelled) setUserVote(votes[0]); } } catch (caught) { if (cancelled) return; if (isNotFound(caught)) setNotFound(true); else setError(errorMessage(caught, "Failed to load submission")); } finally { if (!cancelled) setLoading(false); } }; void load(); return () => { cancelled = true; }; }, [pb, submissionId]); const screenshotUrls = useMemo( () => submission?.screenshots?.map((f) => getSubmissionFileUrl(pb.baseURL, submission.id, f)) ?? [], [submission, pb], ); const handleVote = async (value: 1 | -1) => { if (!submission || voting.current) return; voting.current = true; const userId = await requireUserId("vote"); if (!userId) { voting.current = false; return; } const prev = userVote; const isToggleOff = prev?.value === value; const [upD, downD] = voteDelta(prev?.value, value); setUserVote( isToggleOff ? undefined : ({ ...(prev ?? { id: "", submission: submission.id, user: userId }), value } as StoreVote), ); setSubmission((s) => (s ? { ...s, upvotes: s.upvotes + upD, downvotes: s.downvotes + downD } : s)); try { if (!prev) { await pb.collection("votes").create({ submission: submission.id, value, user: userId }); const votes = await pb.collection("votes").getFullList({ filter: pb.filter("user = {:uid} && submission = {:sid}", { uid: userId, sid: submission.id }), }); setUserVote(votes[0]); } else if (isToggleOff) { await pb.collection("votes").delete(prev.id); } else { await pb.collection("votes").update(prev.id, { value }); } } catch (caught) { setUserVote(prev); setSubmission((s) => (s ? { ...s, upvotes: s.upvotes - upD, downvotes: s.downvotes - downD } : s)); setError(errorMessage(caught, "Failed to register your vote")); } finally { voting.current = false; } }; const handleDelete = async () => { if (!submission) return; try { await pb.collection("submissions").delete(submission.id); window.location.href = "/workshop/"; } catch (caught) { setError(errorMessage(caught, "Failed to delete submission")); } }; const handleCopy = async () => { if (!submission) return; try { await navigator.clipboard.writeText(submission.content); setCopied(true); setCopyFailed(false); if (copyTimer.current) clearTimeout(copyTimer.current); copyTimer.current = setTimeout(() => setCopied(false), 1500); } catch { setCopyFailed(true); setTimeout(() => setCopyFailed(false), 2000); } }; if (loading) return ; if (notFound || !submission) { return (

Submission not found

This listing may have been removed or the link is invalid.

Back to Workshop
); } const score = submission.upvotes - submission.downvotes; const { Icon: CopyIcon, label: copyLabel, iconClass: copyIconClass } = copyState[Number(copied)]; return (
Back to Workshop {error && (
{error}
)} {screenshotUrls.length > 0 && (
)}

{submission.title}

{typeLabels[submission.type]}

{submission.authorName} · v{submission.version} · {relativeTime(submission.created)}

{score}
{submission.description && (

{submission.description}

)}
{submission.type === "widget" && ( )} {user?.id === submission.author && }
); }; export default function MarketplaceDetailPage() { const { siteConfig } = useDocusaurusContext(); const storeUrl = (siteConfig.customFields?.storeUrl as string | undefined) ?? "http://localhost:8090"; return (
}>{() => }
); }