Compare commits

...

8 commits

Author SHA1 Message Date
Ategon
6791e36401 Fix empty sticky post buffer 2025-01-22 22:16:38 -05:00
Ategon
63d7cd49d2 Fix text when no stickied posts 2025-01-22 22:12:25 -05:00
Ategon
42c730e073 Add stickied posts 2025-01-22 22:08:09 -05:00
Ategon
94a3d31e8d Fix prod link for getCurrentJam 2025-01-22 20:44:05 -05:00
Ategon
5462af1a5a Fix build errors 2025-01-22 20:27:17 -05:00
Ategon
a2307ec34e Fix linting issues 2025-01-22 20:12:54 -05:00
Ategon
0807ce5a67 Merge branch 'main' of https://github.com/Ategon/Jamjar 2025-01-22 19:50:28 -05:00
Ategon
3b4f1f0476 Add post get route 2025-01-22 19:50:08 -05:00
17 changed files with 1489 additions and 805 deletions

View file

@ -2,7 +2,14 @@
import Editor from "@/components/editor"; import Editor from "@/components/editor";
import { getCookie, hasCookie } from "@/helpers/cookie"; import { getCookie, hasCookie } from "@/helpers/cookie";
import { Avatar, Button, Form, Input, Spacer } from "@nextui-org/react"; import {
Avatar,
Button,
Checkbox,
Form,
Input,
Spacer,
} from "@nextui-org/react";
import { LoaderCircle } from "lucide-react"; import { LoaderCircle } from "lucide-react";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { ReactNode, useEffect, useState } from "react"; import { ReactNode, useEffect, useState } from "react";
@ -10,6 +17,7 @@ import { toast } from "react-toastify";
import sanitizeHtml from "sanitize-html"; import sanitizeHtml from "sanitize-html";
import Select, { MultiValue, StylesConfig } from "react-select"; import Select, { MultiValue, StylesConfig } from "react-select";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
import { UserType } from "@/types/UserType";
export default function CreatePostPage() { export default function CreatePostPage() {
const [title, setTitle] = useState(""); const [title, setTitle] = useState("");
@ -31,6 +39,8 @@ export default function CreatePostPage() {
}[] }[]
>(); >();
const { theme } = useTheme(); const { theme } = useTheme();
const [user, setUser] = useState<UserType>();
const [sticky, setSticky] = useState(false);
useEffect(() => { useEffect(() => {
setMounted(true); setMounted(true);
@ -46,7 +56,8 @@ export default function CreatePostPage() {
} }
); );
const user = await response.json(); const localuser = await response.json();
setUser(localuser);
const tagResponse = await fetch( const tagResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD" process.env.NEXT_PUBLIC_MODE === "PROD"
@ -63,7 +74,7 @@ export default function CreatePostPage() {
}[] = []; }[] = [];
for (const tag of await tagResponse.json()) { for (const tag of await tagResponse.json()) {
if (tag.modOnly && !user.mod) { if (tag.modOnly && !localuser.mod) {
continue; continue;
} }
newoptions.push({ newoptions.push({
@ -90,7 +101,6 @@ export default function CreatePostPage() {
} }
setOptions(newoptions); setOptions(newoptions);
setSelectedTags(newoptions.filter((tag) => tag.isFixed));
} }
}; };
load(); load();
@ -211,8 +221,14 @@ export default function CreatePostPage() {
body: JSON.stringify({ body: JSON.stringify({
title: title, title: title,
content: sanitizedHtml, content: sanitizedHtml,
sticky,
username: getCookie("user"), username: getCookie("user"),
tags, tags: [
...tags,
...(options
? options.filter((tag) => tag.isFixed).map((tag) => tag.id)
: []),
],
}), }),
method: "POST", method: "POST",
headers: { headers: {
@ -268,6 +284,15 @@ export default function CreatePostPage() {
/> />
)} )}
{user && user.mod && (
<div>
<Spacer />
<Checkbox isSelected={sticky} onValueChange={setSticky}>
Sticky
</Checkbox>
</div>
)}
<Spacer /> <Spacer />
<div className="flex gap-2"> <div className="flex gap-2">

425
src/app/p/[slug]/page.tsx Normal file
View file

@ -0,0 +1,425 @@
"use client";
import LikeButton from "@/components/posts/LikeButton";
import { getCookie } from "@/helpers/cookie";
import { PostType } from "@/types/PostType";
import { TagType } from "@/types/TagType";
import { UserType } from "@/types/UserType";
import Link from "next/link";
import {
Avatar,
Button,
Card,
CardBody,
Chip,
Dropdown,
DropdownItem,
DropdownMenu,
DropdownSection,
DropdownTrigger,
Spacer,
} from "@nextui-org/react";
import { formatDistance } from "date-fns";
import {
Flag,
LoaderCircle,
MessageCircle,
MoreVertical,
Shield,
ShieldAlert,
ShieldX,
Star,
StarOff,
Trash,
X,
} from "lucide-react";
import { redirect, useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "react-toastify";
export default function PostPage() {
const [post, setPost] = useState<PostType>();
const { slug } = useParams();
const [reduceMotion, setReduceMotion] = useState<boolean>(false);
const [user, setUser] = useState<UserType>();
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
setReduceMotion(mediaQuery.matches);
const handleChange = (event: MediaQueryListEvent) => {
setReduceMotion(event.matches);
};
mediaQuery.addEventListener("change", handleChange);
return () => {
mediaQuery.removeEventListener("change", handleChange);
};
}, []);
useEffect(() => {
const loadUserAndPosts = async () => {
setLoading(true);
// Fetch the user
const userResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
if (userResponse.ok) {
const userData = await userResponse.json();
setUser(userData);
const postResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/post?slug=${slug}&user=${userData.slug}`
: `http://localhost:3005/api/v1/post?slug=${slug}&user=${userData.slug}`
);
setPost(await postResponse.json());
setLoading(false);
} else {
setUser(undefined);
const postResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/post?slug=${slug}`
: `http://localhost:3005/api/v1/post?slug=${slug}`
);
setPost(await postResponse.json());
setLoading(false);
}
};
loadUserAndPosts();
}, [slug]);
return (
<>
{loading ? (
<div className="flex justify-center p-6">
<LoaderCircle
className="animate-spin text-[#333] dark:text-[#999]"
size={24}
/>
</div>
) : (
<Card className="bg-opacity-60 !duration-250 !ease-linear !transition-all">
<CardBody className="p-5">
<div>
{post && (
<div>
<Link href={`/p/${post.slug}`}>
<p className="text-2xl">{post.title}</p>
</Link>
<div className="flex items-center gap-3 text-xs text-default-500 pt-1">
<p>By</p>
<Link
href={`/u/${post.author.slug}`}
className="flex items-center gap-2"
>
<Avatar
size="sm"
className="w-6 h-6"
src={post.author.profilePicture}
classNames={{
base: "bg-transparent",
}}
/>
<p>{post.author.name}</p>
</Link>
<p>
{formatDistance(new Date(post.createdAt), new Date(), {
addSuffix: true,
})}
</p>
</div>
<Spacer y={4} />
<div
className="prose dark:prose-invert !duration-250 !ease-linear !transition-all"
dangerouslySetInnerHTML={{ __html: post.content }}
/>
<Spacer y={4} />
{post.tags.filter((tag) => tag.name != "D2Jam").length > 0 ? (
<div className="flex gap-1">
{post.tags
.filter((tag) => tag.name != "D2Jam")
.map((tag: TagType) => (
<Link
href="/"
key={tag.id}
className={`transition-all transform duration-500 ease-in-out ${
!reduceMotion ? "hover:scale-110" : ""
}`}
>
<Chip
radius="sm"
size="sm"
className="!duration-250 !ease-linear !transition-all"
variant="faded"
avatar={
tag.icon && (
<Avatar
src={tag.icon}
classNames={{ base: "bg-transparent" }}
/>
)
}
>
{tag.name}
</Chip>
</Link>
))}
</div>
) : (
<></>
)}
{post.tags.length > 0 && <Spacer y={4} />}
<div className="flex gap-3">
<LikeButton post={post} />
<Button
size="sm"
variant="bordered"
onPress={() => {
toast.warning("Comment functionality coming soon");
}}
>
<MessageCircle size={16} /> {0}
</Button>
<Dropdown backdrop="opaque">
<DropdownTrigger>
<Button size="sm" variant="bordered" isIconOnly>
<MoreVertical size={16} />
</Button>
</DropdownTrigger>
<DropdownMenu className="text-[#333] dark:text-white">
<DropdownSection
showDivider={user?.mod}
title="Actions"
>
<DropdownItem
key="report"
startContent={<Flag />}
description="Report this post to moderators to handle"
onPress={() => {
toast.warning("Report functionality coming soon");
}}
>
Create Report
</DropdownItem>
{user?.slug == post.author.slug ? (
<DropdownItem
key="delete"
startContent={<Trash />}
description="Delete your post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post"
: "http://localhost:3005/api/v1/post",
{
body: JSON.stringify({
postId: post.id,
username: getCookie("user"),
}),
method: "DELETE",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
if (response.ok) {
toast.success("Deleted post");
redirect("/");
} else {
toast.error("Error while deleting post");
}
}}
>
Delete
</DropdownItem>
) : (
<></>
)}
</DropdownSection>
{user?.mod ? (
<DropdownSection title="Mod Zone">
<DropdownItem
key="remove"
startContent={<X />}
description="Remove this post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post"
: "http://localhost:3005/api/v1/post",
{
body: JSON.stringify({
postId: post.id,
username: getCookie("user"),
}),
method: "DELETE",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
if (response.ok) {
toast.success("Removed post");
redirect("/");
} else {
toast.error("Error while removing post");
}
}}
>
Remove
</DropdownItem>
{post.sticky ? (
<DropdownItem
key="unsticky"
startContent={<StarOff />}
description="Unsticky post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post/sticky"
: "http://localhost:3005/api/v1/post/sticky",
{
body: JSON.stringify({
postId: post.id,
sticky: false,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
if (response.ok) {
toast.success("Unsticked post");
redirect("/");
} else {
toast.error("Error while removing post");
}
}}
>
Unsticky
</DropdownItem>
) : (
<DropdownItem
key="sticky"
startContent={<Star />}
description="Sticky post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post/sticky"
: "http://localhost:3005/api/v1/post/sticky",
{
body: JSON.stringify({
postId: post.id,
sticky: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
if (response.ok) {
toast.success("Unsticked post");
redirect("/");
} else {
toast.error("Error while removing post");
}
}}
>
Sticky
</DropdownItem>
)}
{user?.admin && !post.author.mod ? (
<DropdownItem
key="promote-mod"
startContent={<Shield />}
description="Promote user to Mod"
>
Appoint as mod
</DropdownItem>
) : (
<></>
)}
{user?.admin &&
post.author.mod &&
post.author.id !== user.id ? (
<DropdownItem
key="demote-mod"
startContent={<ShieldX />}
description="Demote user from Mod"
>
Remove as mod
</DropdownItem>
) : (
<></>
)}
{user?.admin && !post.author.admin ? (
<DropdownItem
key="promote-admin"
startContent={<ShieldAlert />}
description="Promote user to Admin"
>
Appoint as admin
</DropdownItem>
) : (
<></>
)}
</DropdownSection>
) : (
<></>
)}
</DropdownMenu>
</Dropdown>
</div>
</div>
)}
</div>
</CardBody>
</Card>
)}
</>
);
}

View file

@ -1,6 +1,5 @@
import Timers from "@/components/timers"; import Timers from "@/components/timers";
import Streams from "@/components/streams"; import Streams from "@/components/streams";
import JamHeader from "@/components/jam-header";
import ThemeSlaughter from "@/components/themes/theme-slaughter"; import ThemeSlaughter from "@/components/themes/theme-slaughter";
export default async function Home() { export default async function Home() {

View file

@ -1,6 +1,5 @@
import Timers from "@/components/timers"; import Timers from "@/components/timers";
import Streams from "@/components/streams"; import Streams from "@/components/streams";
import JamHeader from "@/components/jam-header";
import ThemeSuggestions from "@/components/themes/theme-suggest"; import ThemeSuggestions from "@/components/themes/theme-suggest";
export default async function Home() { export default async function Home() {

View file

@ -1,6 +1,5 @@
import Timers from "@/components/timers"; import Timers from "@/components/timers";
import Streams from "@/components/streams"; import Streams from "@/components/streams";
import JamHeader from "@/components/jam-header";
import ThemeVoting from "@/components/themes/theme-vote"; import ThemeVoting from "@/components/themes/theme-vote";
export default async function Home() { export default async function Home() {

View file

@ -5,7 +5,8 @@ import { useEffect, useState } from "react";
import { getCurrentJam, ActiveJamResponse } from "../../helpers/jam"; import { getCurrentJam, ActiveJamResponse } from "../../helpers/jam";
export default function JamHeader() { export default function JamHeader() {
const [activeJamResponse, setActiveJamResponse] = useState<ActiveJamResponse | null>(null); const [activeJamResponse, setActiveJamResponse] =
useState<ActiveJamResponse | null>(null);
const [topTheme, setTopTheme] = useState<string | null>(null); const [topTheme, setTopTheme] = useState<string | null>(null);
// Fetch active jam details // Fetch active jam details
@ -40,15 +41,18 @@ export default function JamHeader() {
fetchData(); fetchData();
}, []); }, []);
// Helper function to get ordinal suffix // Helper function to get ordinal suffix
const getOrdinalSuffix = (day: number): string => { const getOrdinalSuffix = (day: number): string => {
if (day > 3 && day < 21) return "th"; if (day > 3 && day < 21) return "th";
switch (day % 10) { switch (day % 10) {
case 1: return "st"; case 1:
case 2: return "nd"; return "st";
case 3: return "rd"; case 2:
default: return "th"; return "nd";
case 3:
return "rd";
default:
return "th";
} }
}; };
@ -72,18 +76,33 @@ export default function JamHeader() {
<p> <p>
{activeJamResponse?.jam ? ( {activeJamResponse?.jam ? (
<> <>
{new Date(activeJamResponse.jam.startTime).toLocaleDateString('en-US', { {new Date(activeJamResponse.jam.startTime).toLocaleDateString(
month: 'long', "en-US",
})} {new Date(activeJamResponse.jam.startTime).getDate()} {
{getOrdinalSuffix(new Date(activeJamResponse.jam.startTime).getDate())} month: "long",
}
)}{" "}
{new Date(activeJamResponse.jam.startTime).getDate()}
{getOrdinalSuffix(
new Date(activeJamResponse.jam.startTime).getDate()
)}
{" - "} {" - "}
{new Date(new Date(activeJamResponse.jam.startTime).getTime() + {new Date(
(activeJamResponse.jam.jammingHours * 60 * 60 * 1000)).toLocaleDateString('en-US', { new Date(activeJamResponse.jam.startTime).getTime() +
month: 'long', activeJamResponse.jam.jammingHours * 60 * 60 * 1000
})} {new Date(new Date(activeJamResponse.jam.startTime).getTime() + ).toLocaleDateString("en-US", {
(activeJamResponse.jam.jammingHours * 60 * 60 * 1000)).getDate()} month: "long",
{getOrdinalSuffix(new Date(new Date(activeJamResponse.jam.startTime).getTime() + })}{" "}
(activeJamResponse.jam.jammingHours * 60 * 60 * 1000)).getDate())} {new Date(
new Date(activeJamResponse.jam.startTime).getTime() +
activeJamResponse.jam.jammingHours * 60 * 60 * 1000
).getDate()}
{getOrdinalSuffix(
new Date(
new Date(activeJamResponse.jam.startTime).getTime() +
activeJamResponse.jam.jammingHours * 60 * 60 * 1000
).getDate()
)}
</> </>
) : ( ) : (
"Dates TBA" "Dates TBA"
@ -96,7 +115,7 @@ export default function JamHeader() {
{activeJamResponse?.phase === "Suggestion" && ( {activeJamResponse?.phase === "Suggestion" && (
<div className="bg-gray-100 dark:bg-gray-800 p-4 text-center rounded-b-2x"> <div className="bg-gray-100 dark:bg-gray-800 p-4 text-center rounded-b-2x">
<a <a
href="/theme-suggestions" // href="/theme-suggestions"
className="text-blue-300 dark:text-blue-500 hover:underline font-semibold" className="text-blue-300 dark:text-blue-500 hover:underline font-semibold"
> >
Go to Theme Suggestion Go to Theme Suggestion
@ -107,7 +126,7 @@ export default function JamHeader() {
{activeJamResponse?.phase === "Survival" && ( {activeJamResponse?.phase === "Survival" && (
<div className="bg-gray-100 dark:bg-gray-800 p-4 text-center rounded-b-2x"> <div className="bg-gray-100 dark:bg-gray-800 p-4 text-center rounded-b-2x">
<a <a
href="/theme-slaughter" // href="/theme-slaughter"
className="text-blue-300 dark:text-blue-500 hover:underline font-semibold" className="text-blue-300 dark:text-blue-500 hover:underline font-semibold"
> >
Go to Theme Survival Go to Theme Survival
@ -118,7 +137,7 @@ export default function JamHeader() {
{activeJamResponse?.phase === "Voting" && ( {activeJamResponse?.phase === "Voting" && (
<div className="bg-gray-100 dark:bg-gray-800 p-4 text-center rounded-b-2x"> <div className="bg-gray-100 dark:bg-gray-800 p-4 text-center rounded-b-2x">
<a <a
href="/theme-voting" // href="/theme-voting"
className="text-blue-300 dark:text-blue-500 hover:underline font-semibold" className="text-blue-300 dark:text-blue-500 hover:underline font-semibold"
> >
Go to Theme Voting Go to Theme Voting
@ -139,7 +158,9 @@ export default function JamHeader() {
{activeJamResponse?.phase === "Rating" && ( {activeJamResponse?.phase === "Rating" && (
<div className="bg-gray-100 dark:bg-gray-800 p-4 text-center rounded-b-2x"> <div className="bg-gray-100 dark:bg-gray-800 p-4 text-center rounded-b-2x">
{topTheme ? ( {topTheme ? (
<p className="text-xl font-bold text-blue-500">THEME: {topTheme} RESULTS</p> <p className="text-xl font-bold text-blue-500">
THEME: {topTheme} RESULTS
</p>
) : ( ) : (
<p>No top-scoring theme available.</p> <p>No top-scoring theme available.</p>
)} )}

View file

@ -19,7 +19,7 @@ interface NavbarUserProps {
isInJam?: boolean; isInJam?: boolean;
} }
export default function MobileNavbarUser({ export default async function MobileNavbarUser({
user, user,
jam, jam,
setIsInJam, setIsInJam,
@ -38,7 +38,7 @@ export default function MobileNavbarUser({
/> />
</DropdownTrigger> </DropdownTrigger>
<DropdownMenu> <DropdownMenu>
{jam && isInJam ? ( {jam && (await getCurrentJam())?.jam && isInJam ? (
<DropdownItem <DropdownItem
key="create-game" key="create-game"
href="/create-game" href="/create-game"
@ -47,7 +47,7 @@ export default function MobileNavbarUser({
Create Game Create Game
</DropdownItem> </DropdownItem>
) : null} ) : null}
{jam && !isInJam ? ( {jam && (await getCurrentJam())?.jam && !isInJam ? (
<DropdownItem <DropdownItem
key="join-event" key="join-event"
className="text-black" className="text-black"
@ -55,12 +55,12 @@ export default function MobileNavbarUser({
try { try {
const currentJam = await getCurrentJam(); const currentJam = await getCurrentJam();
if (!currentJam) { if (!currentJam || !currentJam.jam) {
toast.error("There is no jam to join"); toast.error("There is no jam to join");
return; return;
} }
if (await joinJam(currentJam.id)) { if (await joinJam(currentJam.jam.id)) {
setIsInJam(true); setIsInJam(true);
} }
} catch (error) { } catch (error) {

View file

@ -24,7 +24,7 @@ import NextImage from "next/image";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { getCookie, hasCookie } from "@/helpers/cookie"; import { getCookie, hasCookie } from "@/helpers/cookie";
import { getCurrentJam, joinJam, ActiveJamResponse } from "@/helpers/jam"; import { getCurrentJam, joinJam } from "@/helpers/jam";
import { JamType } from "@/types/JamType"; import { JamType } from "@/types/JamType";
import { UserType } from "@/types/UserType"; import { UserType } from "@/types/UserType";
import NavbarUser from "./PCNavbarUser"; import NavbarUser from "./PCNavbarUser";

View file

@ -25,6 +25,8 @@ import {
Shield, Shield,
ShieldAlert, ShieldAlert,
ShieldX, ShieldX,
Star,
StarOff,
Trash, Trash,
X, X,
} from "lucide-react"; } from "lucide-react";
@ -73,7 +75,9 @@ export default function PostCard({
(minimized ? ( (minimized ? (
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Link href={`/p/${post.slug}`}>
<p>{post.title}</p> <p>{post.title}</p>
</Link>
<div className="flex items-center gap-3 text-xs text-default-500 pt-1"> <div className="flex items-center gap-3 text-xs text-default-500 pt-1">
<p>By</p> <p>By</p>
@ -110,7 +114,9 @@ export default function PostCard({
) : ( ) : (
<div> <div>
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<Link href={`/p/${post.slug}`}>
<p className="text-2xl">{post.title}</p> <p className="text-2xl">{post.title}</p>
</Link>
<Button <Button
size="sm" size="sm"
variant="light" variant="light"
@ -292,6 +298,81 @@ export default function PostCard({
> >
Remove Remove
</DropdownItem> </DropdownItem>
{post.sticky ? (
<DropdownItem
key="unsticky"
startContent={<StarOff />}
description="Unsticky post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post/sticky"
: "http://localhost:3005/api/v1/post/sticky",
{
body: JSON.stringify({
postId: post.id,
sticky: false,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
if (response.ok) {
toast.success("Unsticked post");
window.location.reload();
} else {
toast.error("Error while removing post");
}
}}
>
Unsticky
</DropdownItem>
) : (
<DropdownItem
key="sticky"
startContent={<Star />}
description="Sticky post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post/sticky"
: "http://localhost:3005/api/v1/post/sticky",
{
body: JSON.stringify({
postId: post.id,
sticky: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
if (response.ok) {
toast.success("Stickied post");
window.location.reload();
} else {
toast.error("Error while removing post");
}
}}
>
Sticky
</DropdownItem>
)}
{user?.admin && !post.author.mod ? ( {user?.admin && !post.author.mod ? (
<DropdownItem <DropdownItem
key="promote-mod" key="promote-mod"
@ -338,7 +419,9 @@ export default function PostCard({
))} ))}
{style == "compact" && ( {style == "compact" && (
<div> <div>
<Link href={`/p/${post.slug}`}>
<p className="text-2xl">{post.title}</p> <p className="text-2xl">{post.title}</p>
</Link>
<div className="flex items-center gap-3 text-xs text-default-500 pt-1"> <div className="flex items-center gap-3 text-xs text-default-500 pt-1">
<p>By</p> <p>By</p>
@ -366,7 +449,9 @@ export default function PostCard({
)} )}
{style == "ultra" && ( {style == "ultra" && (
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Link href={`/p/${post.slug}`}>
<p>{post.title}</p> <p>{post.title}</p>
</Link>
<div className="flex items-center gap-3 text-xs text-default-500 pt-1"> <div className="flex items-center gap-3 text-xs text-default-500 pt-1">
<p>By</p> <p>By</p>

View file

@ -0,0 +1,54 @@
"use client";
import { Avatar, Card, CardBody } from "@nextui-org/react";
import { formatDistance } from "date-fns";
import Link from "next/link";
import { PostType } from "@/types/PostType";
import { Megaphone, NotebookText } from "lucide-react";
export default function StickyPostCard({ post }: { post: PostType }) {
return (
<Card className="bg-opacity-60 !duration-250 !ease-linear !transition-all flex">
<CardBody className="p-5">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="flex gap-4 items-center text-blue-600 dark:text-blue-400 transition-all duration-250 ease-linear">
{post.tags.filter((tag) => tag.name === "Changelog").length >
0 ? (
<NotebookText />
) : (
<Megaphone />
)}
<Link href={`/p/${post.slug}`}>
<p>{post.title}</p>
</Link>
</div>
<div className="flex items-center gap-3 text-xs text-default-500 pt-1">
<p>By</p>
<Link
href={`/u/${post.author.slug}`}
className="flex items-center gap-2"
>
<Avatar
size="sm"
className="w-6 h-6"
src={post.author.profilePicture}
classNames={{
base: "bg-transparent",
}}
/>
<p>{post.author.name}</p>
</Link>
<p>
{formatDistance(new Date(post.createdAt), new Date(), {
addSuffix: true,
})}
</p>
</div>
</div>
</div>
</CardBody>
</Card>
);
}

View file

@ -42,9 +42,11 @@ import {
import { PostTime } from "@/types/PostTimes"; import { PostTime } from "@/types/PostTimes";
import { TagType } from "@/types/TagType"; import { TagType } from "@/types/TagType";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
import StickyPostCard from "./StickyPostCard";
export default function Posts() { export default function Posts() {
const [posts, setPosts] = useState<PostType[]>(); const [posts, setPosts] = useState<PostType[]>();
const [stickyPosts, setStickyPosts] = useState<PostType[]>();
const [sort, setSort] = useState<PostSort>("newest"); const [sort, setSort] = useState<PostSort>("newest");
const [time, setTime] = useState<PostTime>("all"); const [time, setTime] = useState<PostTime>("all");
const [style, setStyle] = useState<PostStyle>("cozy"); const [style, setStyle] = useState<PostStyle>("cozy");
@ -144,6 +146,31 @@ export default function Posts() {
}` }`
); );
setPosts(await postsResponse.json()); setPosts(await postsResponse.json());
// Sticky posts
// Fetch posts with userSlug if user is available
const stickyPostsResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/posts?sort=${sort}&user=${
userData.slug
}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}&sticky=true`
: `http://localhost:3005/api/v1/posts?sort=${sort}&user=${
userData.slug
}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}&sticky=true`
);
setStickyPosts(await stickyPostsResponse.json());
setLoading(false); setLoading(false);
} else { } else {
setUser(undefined); setUser(undefined);
@ -167,6 +194,26 @@ export default function Posts() {
}` }`
); );
setPosts(await postsResponse.json()); setPosts(await postsResponse.json());
// Fetch posts without userSlug if user is not available
const stickyPostsResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/posts?sort=${sort}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key, value) => `${key}-${value}`)
.join("_")
: ""
}&sticky=true`
: `http://localhost:3005/api/v1/posts?sort=${sort}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key, value) => `${key}-${value}`)
.join("_")
: ""
}&sticky=true`
);
setStickyPosts(await stickyPostsResponse.json());
setLoading(false); setLoading(false);
} }
}; };
@ -263,6 +310,24 @@ export default function Posts() {
return ( return (
<div> <div>
{loading ? (
<div className="flex justify-center p-6">
<LoaderCircle
className="animate-spin text-[#333] dark:text-[#999]"
size={24}
/>
</div>
) : (
stickyPosts &&
stickyPosts.length > 0 && (
<div className="flex flex-col gap-3 p-4">
{stickyPosts.map((post) => (
<StickyPostCard key={post.id} post={post} />
))}
</div>
)
)}
<div className="flex justify-between p-4 pb-0"> <div className="flex justify-between p-4 pb-0">
<div className="flex gap-2"> <div className="flex gap-2">
<Dropdown backdrop="opaque"> <Dropdown backdrop="opaque">

View file

@ -1,279 +1,286 @@
"use client"; "use client";
import React, { useState, useEffect } from "react"; // import React, { useState, useEffect, useCallback } from "react";
import { getCookie } from "@/helpers/cookie"; // import { getCookie } from "@/helpers/cookie";
import { getCurrentJam, hasJoinedCurrentJam, ActiveJamResponse } from "@/helpers/jam"; // import {
// getCurrentJam,
// hasJoinedCurrentJam,
// ActiveJamResponse,
// } from "@/helpers/jam";
export default function ThemeSlaughter() { export default function ThemeSlaughter() {
// const [randomTheme, setRandomTheme] = useState(null);
// const [votedThemes, setVotedThemes] = useState([]);
// const [loading, setLoading] = useState(false);
// const [token, setToken] = useState<string | null>(null);
// const [hasJoined, setHasJoined] = useState<boolean>(false);
// const [activeJamResponse, setActiveJam] = useState<ActiveJamResponse | null>(
// null
// );
// const [phaseLoading, setPhaseLoading] = useState(true);
const [randomTheme, setRandomTheme] = useState(null); // // Fetch token on the client side
const [votedThemes, setVotedThemes] = useState([]); // useEffect(() => {
const [loading, setLoading] = useState(false); // const fetchedToken = getCookie("token");
const [token, setToken] = useState(null); // setToken(fetchedToken);
const [hasJoined, setHasJoined] = useState<boolean>(false); // }, []);
const [activeJamResponse, setActiveJam] = useState<ActiveJamResponse | null>(null);
const [phaseLoading, setPhaseLoading] = useState(true);
// Fetch token on the client side // // Fetch the current jam phase using helpers/jam
useEffect(() => { // useEffect(() => {
const fetchedToken = getCookie("token"); // const fetchCurrentJamPhase = async () => {
setToken(fetchedToken); // try {
}, []); // const activeJam = await getCurrentJam();
// setActiveJam(activeJam); // Set active jam details
// } catch (error) {
// console.error("Error fetching current jam:", error);
// } finally {
// setPhaseLoading(false); // Stop loading when phase is fetched
// }
// };
// Fetch the current jam phase using helpers/jam // fetchCurrentJamPhase();
useEffect(() => { // }, []);
const fetchCurrentJamPhase = async () => {
try { // // Fetch a random theme
const activeJam = await getCurrentJam(); // const fetchRandomTheme = useCallback(async () => {
setActiveJam(activeJam); // Set active jam details // if (!token) return; // Wait until token is available
} catch (error) { // if (!activeJamResponse) return;
console.error("Error fetching current jam:", error); // if (
} finally { // activeJamResponse &&
setPhaseLoading(false); // Stop loading when phase is fetched // activeJamResponse.jam &&
} // activeJamResponse.phase != "Survival"
}; // ) {
// return (
fetchCurrentJamPhase(); // <div>
}, []); // <h1>It&apos;s not Theme Survival phase.</h1>
// </div>
// );
// Fetch a random theme // }
const fetchRandomTheme = async () => {
if (!token) return; // Wait until token is available // try {
if( !activeJamResponse) return; // const response = await fetch(
if(activeJamResponse && activeJamResponse.jam && activeJamResponse.phase != "Survival") // process.env.NEXT_PUBLIC_MODE === "PROD"
{ // ? "https://d2jam.com/api/v1/themes/random"
return ( // : "http://localhost:3005/api/v1/themes/random",
<div> // {
<h1>It's not Theme Survival phase.</h1> // headers: { Authorization: `Bearer ${token}` },
</div> // credentials: "include",
); // }
} // );
// if (response.ok) {
try { // const data = await response.json();
const response = await fetch( // setRandomTheme(data);
process.env.NEXT_PUBLIC_MODE === "PROD" // } else {
? "https://d2jam.com/api/v1/themes/random" // console.error("Failed to fetch random theme.");
: "http://localhost:3005/api/v1/themes/random", // }
{ // } catch (error) {
headers: { Authorization: `Bearer ${token}` }, // console.error("Error fetching random theme:", error);
credentials: "include", // }
} // }, [activeJamResponse, token]);
);
if (response.ok) { // // Fetch voted themes
const data = await response.json(); // const fetchVotedThemes = useCallback(async () => {
setRandomTheme(data); // if (!token) return; // Wait until token is available
} else {
console.error("Failed to fetch random theme."); // try {
} // const response = await fetch(
} catch (error) { // process.env.NEXT_PUBLIC_MODE === "PROD"
console.error("Error fetching random theme:", error); // ? "https://d2jam.com/api/v1/themes/voteSlaughter"
} // : "http://localhost:3005/api/v1/themes/voteSlaughter",
}; // {
// headers: { Authorization: `Bearer ${token}` },
// Fetch voted themes // credentials: "include",
const fetchVotedThemes = async () => { // }
if (!token) return; // Wait until token is available // );
// if (response.ok) {
try { // const data = await response.json();
const response = await fetch( // setVotedThemes(data);
process.env.NEXT_PUBLIC_MODE === "PROD" // } else {
? "https://d2jam.com/api/v1/themes/voteSlaughter" // console.error("Failed to fetch voted themes.");
: "http://localhost:3005/api/v1/themes/voteSlaughter", // }
{ // } catch (error) {
headers: { Authorization: `Bearer ${token}` }, // console.error("Error fetching voted themes:", error);
credentials: "include", // }
} // }, [token]);
);
if (response.ok) { // // Handle voting
const data = await response.json(); // const handleVote = async (voteType: string) => {
setVotedThemes(data); // if (!randomTheme) return;
} else {
console.error("Failed to fetch voted themes."); // setLoading(true);
} // try {
} catch (error) { // const response = await fetch(
console.error("Error fetching voted themes:", error); // process.env.NEXT_PUBLIC_MODE === "PROD"
} // ? "https://d2jam.com/api/v1/themes/voteSlaughter"
}; // : "http://localhost:3005/api/v1/themes/voteSlaughter",
// {
// Handle voting // method: "POST",
const handleVote = async (voteType) => { // headers: {
if (!randomTheme) return; // "Content-Type": "application/json",
// Authorization: `Bearer ${token}`,
setLoading(true); // },
try { // credentials: "include",
const response = await fetch( // body: JSON.stringify({
process.env.NEXT_PUBLIC_MODE === "PROD" // suggestionId: randomTheme.id,
? "https://d2jam.com/api/v1/themes/voteSlaughter" // voteType,
: "http://localhost:3005/api/v1/themes/voteSlaughter", // }),
{ // }
method: "POST", // );
headers: {
"Content-Type": "application/json", // if (response.ok) {
Authorization: `Bearer ${token}`, // // Refresh data after voting
}, // fetchRandomTheme();
credentials: "include", // fetchVotedThemes();
body: JSON.stringify({ // } else {
suggestionId: randomTheme.id, // console.error("Failed to submit vote.");
voteType, // }
}), // } catch (error) {
} // console.error("Error submitting vote:", error);
); // } finally {
// setLoading(false);
if (response.ok) { // }
// Refresh data after voting // };
fetchRandomTheme();
fetchVotedThemes(); // // Handle resetting a vote from the grid
} else { // const handleResetVote = async (themeId: number) => {
console.error("Failed to submit vote."); // try {
} // setRandomTheme(votedThemes.find((theme) => theme.id === themeId));
} catch (error) { // setVotedThemes((prev) =>
console.error("Error submitting vote:", error); // prev.map((theme) =>
} finally { // theme.id === themeId ? { ...theme, slaughterScore: 0 } : theme
setLoading(false); // )
} // );
}; // } catch (error) {
// console.error("Error resetting vote:", error);
// Handle resetting a vote from the grid // }
const handleResetVote = async (themeId) => { // };
try {
setRandomTheme(votedThemes.find((theme) => theme.id === themeId)); // useEffect(() => {
setVotedThemes((prev) => // if (token && activeJamResponse?.phase === "Survival") {
prev.map((theme) => // fetchRandomTheme();
theme.id === themeId ? { ...theme, slaughterScore: 0 } : theme // fetchVotedThemes();
) // }
); // }, [token, activeJamResponse, fetchRandomTheme, fetchVotedThemes]);
} catch (error) {
console.error("Error resetting vote:", error); // useEffect(() => {
} // const init = async () => {
}; // const joined = await hasJoinedCurrentJam();
// setHasJoined(joined);
// setLoading(false);
useEffect(() => { // };
if (token && activeJamResponse?.phase === "Survival") {
fetchRandomTheme(); // init();
fetchVotedThemes(); // }, []);
}
}, [token, activeJamResponse]); // if (phaseLoading || loading) {
// return <div>Loading...</div>;
// }
useEffect(() => {
const init = async () => { // if (!hasJoined) {
const joined = await hasJoinedCurrentJam(); // return (
setHasJoined(joined); // <div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen">
setLoading(false); // <h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6">
}; // Join the Jam First
// </h1>
init(); // <p className="text-gray-600 dark:text-gray-400">
}, []); // You need to join the current jam before you can join Theme Survival.
// </p>
if (phaseLoading || loading) { // <button
return <div>Loading...</div>; // onClick={() => joinJam(activeJamResponse?.jam?.id)}
} // className="mt-4 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
// >
if (!hasJoined) { // Join Jam
return ( // </button>
<div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen"> // </div>
<h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6"> // );
Join the Jam First // }
</h1>
<p className="text-gray-600 dark:text-gray-400"> // // Render message if not in Theme Slaughter phase
You need to join the current jam before you can join Theme Survival. // if (activeJamResponse?.phase !== "Survival") {
</p> // return (
<button // <div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen">
onClick={() => joinJam(activeJamResponse?.jam?.id)} // <h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6">
className="mt-4 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600" // Not in Theme Slaughter Phase
> // </h1>
Join Jam // <p className="text-gray-600 dark:text-gray-400">
</button> // The current phase is{" "}
</div> // <strong>{activeJamResponse?.phase || "Unknown"}</strong>. Please come
); // back during the Theme Slaughter phase.
} // </p>
// </div>
// Render message if not in Theme Slaughter phase // );
if (activeJamResponse?.phase !== "Survival") { // }
return (
<div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen"> // const loggedIn = getCookie("token");
<h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6">
Not in Theme Slaughter Phase // if (!loggedIn) {
</h1> // return <div>Sign in to be able to join the Theme Survival</div>;
<p className="text-gray-600 dark:text-gray-400"> // }
The current phase is <strong>{activeJamResponse?.phase || "Unknown"}</strong>. Please come back during the Theme Slaughter phase.
</p> // return (
</div> // <div className="flex h-screen">
); // {/* Left Side */}
} // <div className="w-1/2 p-6 bg-gray-100 dark:bg-gray-800 flex flex-col justify-start items-center">
// {randomTheme ? (
const loggedIn = getCookie("token"); // <>
// <h2 className="text-2xl font-bold text-gray-800 dark:text-white mb-4">
if (!loggedIn) { // {randomTheme.suggestion}
return ( // </h2>
<div>Sign in to be able to join the Theme Survival</div> // <div className="flex gap-4">
); // <button
} // onClick={() => handleVote("YES")}
// className="px-6 py-3 bg-green-500 text-white font-bold rounded-lg hover:bg-green-600"
// disabled={loading}
return ( // >
<div className="flex h-screen"> // YES
{/* Left Side */} // </button>
<div className="w-1/2 p-6 bg-gray-100 dark:bg-gray-800 flex flex-col justify-start items-center"> // <button
{randomTheme ? ( // onClick={() => handleVote("NO")}
<> // className="px-6 py-3 bg-red-500 text-white font-bold rounded-lg hover:bg-red-600"
<h2 className="text-2xl font-bold text-gray-800 dark:text-white mb-4"> // disabled={loading}
{randomTheme.suggestion} // >
</h2> // NO
<div className="flex gap-4"> // </button>
<button // <button
onClick={() => handleVote("YES")} // onClick={() => handleVote("SKIP")}
className="px-6 py-3 bg-green-500 text-white font-bold rounded-lg hover:bg-green-600" // className="px-6 py-3 bg-gray-500 text-white font-bold rounded-lg hover:bg-gray-600"
disabled={loading} // disabled={loading}
> // >
YES // SKIP
</button> // </button>
<button // </div>
onClick={() => handleVote("NO")} // </>
className="px-6 py-3 bg-red-500 text-white font-bold rounded-lg hover:bg-red-600" // ) : (
disabled={loading} // <p className="text-gray-600 dark:text-gray-400">
> // No themes available.
NO // </p>
</button> // )}
<button // </div>
onClick={() => handleVote("SKIP")}
className="px-6 py-3 bg-gray-500 text-white font-bold rounded-lg hover:bg-gray-600" // {/* Right Side */}
disabled={loading} // <div className="w-1/2 p-6 bg-white dark:bg-gray-900 overflow-y-auto">
> // <h3 className="text-xl font-bold text-gray-800 dark:text-white mb-4">
SKIP // Your Votes
</button> // </h3>
</div> // <div className="grid grid-cols-4 gap-4">
</> // {votedThemes.map((theme) => (
) : ( // <div
<p className="text-gray-600 dark:text-gray-400">No themes available.</p> // key={theme.id}
)} // onClick={() => handleResetVote(theme.id)}
</div> // className={`p-4 rounded-lg cursor-pointer ${
// theme.slaughterScore > 0
{/* Right Side */} // ? "bg-green-500 text-white"
<div className="w-1/2 p-6 bg-white dark:bg-gray-900 overflow-y-auto"> // : theme.slaughterScore < 0
<h3 className="text-xl font-bold text-gray-800 dark:text-white mb-4"> // ? "bg-red-500 text-white"
Your Votes // : "bg-gray-300 text-black"
</h3> // }`}
<div className="grid grid-cols-4 gap-4"> // >
{votedThemes.map((theme) => ( // {theme.suggestion}
<div // </div>
key={theme.id} // ))}
onClick={() => handleResetVote(theme.id)} // </div>
className={`p-4 rounded-lg cursor-pointer ${ // </div>
theme.slaughterScore > 0 // </div>
? "bg-green-500 text-white" // );
: theme.slaughterScore < 0 return <></>;
? "bg-red-500 text-white"
: "bg-gray-300 text-black"
}`}
>
{theme.suggestion}
</div>
))}
</div>
</div>
</div>
);
} }

View file

@ -1,271 +1,282 @@
"use client"; "use client";
import React, { useState, useEffect } from "react"; // import React, { useState, useEffect } from "react";
import { getCookie } from "@/helpers/cookie"; // import { getCookie } from "@/helpers/cookie";
import { getCurrentJam, hasJoinedCurrentJam , ActiveJamResponse } from "@/helpers/jam"; // import {
// getCurrentJam,
// hasJoinedCurrentJam,
// ActiveJamResponse,
// } from "@/helpers/jam";
export default function ThemeSuggestions() { export default function ThemeSuggestions() {
const [suggestion, setSuggestion] = useState(""); // const [suggestion, setSuggestion] = useState("");
const [loading, setLoading] = useState(false); // const [loading, setLoading] = useState(false);
const [successMessage, setSuccessMessage] = useState(""); // const [successMessage, setSuccessMessage] = useState("");
const [errorMessage, setErrorMessage] = useState(""); // const [errorMessage, setErrorMessage] = useState("");
const [userSuggestions, setUserSuggestions] = useState([]); // const [userSuggestions, setUserSuggestions] = useState([]);
const [themeLimit, setThemeLimit] = useState(0); // const [themeLimit, setThemeLimit] = useState(0);
const [hasJoined, setHasJoined] = useState<boolean>(false); // const [hasJoined, setHasJoined] = useState<boolean>(false);
const [activeJamResponse, setActiveJamResponse] = useState<ActiveJamResponse | null>(null); // const [activeJamResponse, setActiveJamResponse] =
const [phaseLoading, setPhaseLoading] = useState(true); // Loading state for fetching phase // useState<ActiveJamResponse | null>(null);
// const [phaseLoading, setPhaseLoading] = useState(true); // Loading state for fetching phase
// Fetch the current jam phase using helpers/jam // // Fetch the current jam phase using helpers/jam
useEffect(() => { // useEffect(() => {
const fetchCurrentJamPhase = async () => { // const fetchCurrentJamPhase = async () => {
try { // try {
const activeJam = await getCurrentJam(); // const activeJam = await getCurrentJam();
setActiveJamResponse(activeJam); // Set active jam details // setActiveJamResponse(activeJam); // Set active jam details
if (activeJam?.jam) { // if (activeJam?.jam) {
setThemeLimit(activeJam.jam.themePerUser || Infinity); // Set theme limit // setThemeLimit(activeJam.jam.themePerUser || Infinity); // Set theme limit
} // }
} catch (error) { // } catch (error) {
console.error("Error fetching current jam:", error); // console.error("Error fetching current jam:", error);
} finally { // } finally {
setPhaseLoading(false); // Stop loading when phase is fetched // setPhaseLoading(false); // Stop loading when phase is fetched
} // }
}; // };
fetchCurrentJamPhase(); // fetchCurrentJamPhase();
}, []); // }, []);
// Fetch all suggestions for the logged-in user // // Fetch all suggestions for the logged-in user
const fetchSuggestions = async () => { // const fetchSuggestions = async () => {
try { // try {
const response = await fetch( // const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD" // process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/suggestion" // ? "https://d2jam.com/api/v1/themes/suggestion"
: "http://localhost:3005/api/v1/themes/suggestion", // : "http://localhost:3005/api/v1/themes/suggestion",
{ // {
headers: { Authorization: `Bearer ${getCookie("token")}` }, // headers: { Authorization: `Bearer ${getCookie("token")}` },
credentials: "include", // credentials: "include",
} // }
); // );
if (response.ok) { // if (response.ok) {
const data = await response.json(); // const data = await response.json();
setUserSuggestions(data); // setUserSuggestions(data);
} // }
} catch (error) { // } catch (error) {
console.error("Error fetching suggestions:", error); // console.error("Error fetching suggestions:", error);
} // }
}; // };
// Fetch suggestions only when phase is "Suggestion" // // Fetch suggestions only when phase is "Suggestion"
useEffect(() => { // useEffect(() => {
if (activeJamResponse?.phase === "Suggestion") { // if (activeJamResponse?.phase === "Suggestion") {
fetchSuggestions(); // fetchSuggestions();
} // }
}, [activeJamResponse]); // }, [activeJamResponse]);
// Handle form submission to add a new suggestion // // Handle form submission to add a new suggestion
const handleSubmit = async (e: React.FormEvent) => { // const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); // e.preventDefault();
setLoading(true); // setLoading(true);
setSuccessMessage(""); // setSuccessMessage("");
setErrorMessage(""); // setErrorMessage("");
if (!suggestion.trim()) { // if (!suggestion.trim()) {
setErrorMessage("Suggestion cannot be empty."); // setErrorMessage("Suggestion cannot be empty.");
setLoading(false); // setLoading(false);
return; // return;
} // }
try { // try {
const token = getCookie("token"); // const token = getCookie("token");
if (!token) { // if (!token) {
throw new Error("User is not authenticated. Please log in."); // throw new Error("User is not authenticated. Please log in.");
} // }
const response = await fetch( // const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD" // process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/suggestion" // ? "https://d2jam.com/api/v1/themes/suggestion"
: "http://localhost:3005/api/v1/themes/suggestion", // : "http://localhost:3005/api/v1/themes/suggestion",
{ // {
method: "POST", // method: "POST",
headers: { // headers: {
"Content-Type": "application/json", // "Content-Type": "application/json",
Authorization: `Bearer ${token}`, // Authorization: `Bearer ${token}`,
}, // },
credentials: "include", // credentials: "include",
body: JSON.stringify({ suggestionText: suggestion }), // body: JSON.stringify({ suggestionText: suggestion }),
} // }
); // );
if (!response.ok) { // if (!response.ok) {
const errorData = await response.json(); // const errorData = await response.json();
throw new Error(errorData.error || "Failed to submit suggestion."); // throw new Error(errorData.error || "Failed to submit suggestion.");
} // }
setSuccessMessage("Suggestion added successfully!"); // setSuccessMessage("Suggestion added successfully!");
setSuggestion(""); // Clear input field // setSuggestion(""); // Clear input field
fetchSuggestions(); // Refresh suggestions list // fetchSuggestions(); // Refresh suggestions list
} catch (error: any) { // } catch (error) {
console.error("Error submitting suggestion:", error.message); // if (error instanceof Error) {
setErrorMessage(error.message || "An unexpected error occurred."); // console.error("Error submitting suggestion:", error.message);
} finally { // setErrorMessage(error.message || "An unexpected error occurred.");
setLoading(false); // } else {
} // console.error("Unknown error:", error);
}; // setErrorMessage("An unexpected error occurred.");
// }
// Handle deleting a suggestion // } finally {
const handleDelete = async (id: number) => { // setLoading(false);
try { // }
const token = getCookie("token"); // };
const response = await fetch( // // Handle deleting a suggestion
process.env.NEXT_PUBLIC_MODE === "PROD" // const handleDelete = async (id: number) => {
? `https://d2jam.com/api/v1/themes/suggestion/${id}` // try {
: `http://localhost:3005/api/v1/themes/suggestion/${id}`, // const token = getCookie("token");
{
method: "DELETE", // const response = await fetch(
headers: { Authorization: `Bearer ${token}` }, // process.env.NEXT_PUBLIC_MODE === "PROD"
credentials: "include", // ? `https://d2jam.com/api/v1/themes/suggestion/${id}`
} // : `http://localhost:3005/api/v1/themes/suggestion/${id}`,
); // {
// method: "DELETE",
if (!response.ok) { // headers: { Authorization: `Bearer ${token}` },
throw new Error("Failed to delete suggestion."); // credentials: "include",
} // }
// );
fetchSuggestions(); // Refresh suggestions list
} catch (error) { // if (!response.ok) {
console.error("Error deleting suggestion:", error); // throw new Error("Failed to delete suggestion.");
} // }
};
// fetchSuggestions(); // Refresh suggestions list
useEffect(() => { // } catch (error) {
const init = async () => { // console.error("Error deleting suggestion:", error);
const joined = await hasJoinedCurrentJam(); // }
setHasJoined(joined); // };
setLoading(false);
}; // useEffect(() => {
// const init = async () => {
init(); // const joined = await hasJoinedCurrentJam();
}, []); // setHasJoined(joined);
// setLoading(false);
// Render loading state while fetching phase // };
if (phaseLoading || loading) {
return <div>Loading...</div>; // init();
} // }, []);
if (!hasJoined) { // // Render loading state while fetching phase
return ( // if (phaseLoading || loading) {
<div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen"> // return <div>Loading...</div>;
<h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6"> // }
Join the Jam First
</h1> // if (!hasJoined) {
<p className="text-gray-600 dark:text-gray-400"> // return (
You need to join the current jam before you can suggest themes. // <div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen">
</p> // <h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6">
<button // Join the Jam First
onClick={() => joinJam(activeJamResponse?.jam?.id)} // </h1>
className="mt-4 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600" // <p className="text-gray-600 dark:text-gray-400">
> // You need to join the current jam before you can suggest themes.
Join Jam // </p>
</button> // <button
</div> // onClick={() => joinJam(activeJamResponse?.jam?.id)}
); // className="mt-4 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
} // >
// Join Jam
const token = getCookie("token"); // </button>
// </div>
if (!token) { // );
return ( // }
<div>Sign in to be able to suggest themes</div>
); // const token = getCookie("token");
}
// if (!token) {
// Render message if not in Suggestion phase // return <div>Sign in to be able to suggest themes</div>;
if (activeJamResponse?.phase !== "Suggestion") { // }
return (
<div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen"> // // Render message if not in Suggestion phase
<h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6"> // if (activeJamResponse?.phase !== "Suggestion") {
Not in Suggestion Phase // return (
</h1> // <div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen">
<p className="text-gray-600 dark:text-gray-400"> // <h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6">
The current phase is <strong>{activeJamResponse?.phase || "Unknown"}</strong>. Please come back during the Suggestion phase. // Not in Suggestion Phase
</p> // </h1>
</div> // <p className="text-gray-600 dark:text-gray-400">
); // The current phase is{" "}
} // <strong>{activeJamResponse?.phase || "Unknown"}</strong>. Please come
// back during the Suggestion phase.
return ( // </p>
<div className="max-w-md mx-auto mt-8 p-6 bg-white dark:bg-gray-800 rounded-lg shadow-md"> // </div>
<h2 className="text-xl font-bold text-gray-800 dark:text-white mb-4"> // );
Submit Your Theme Suggestion // }
</h2>
// return (
{/* Hide form if user has reached their limit */} // <div className="max-w-md mx-auto mt-8 p-6 bg-white dark:bg-gray-800 rounded-lg shadow-md">
{userSuggestions.length < themeLimit ? ( // <h2 className="text-xl font-bold text-gray-800 dark:text-white mb-4">
<form onSubmit={handleSubmit} className="flex flex-col gap-4"> // Submit Your Theme Suggestion
<textarea // </h2>
className="w-full p-3 border rounded-lg focus:outline-none text-gray-600 focus:ring focus:ring-blue-300 dark:bg-gray-700 dark:text-white"
placeholder="Enter your theme suggestion..." // {/* Hide form if user has reached their limit */}
value={suggestion} // {userSuggestions.length < themeLimit ? (
onChange={(e) => { // <form onSubmit={handleSubmit} className="flex flex-col gap-4">
if (e.target.value.length <= 32) { // <textarea
setSuggestion(e.target.value); // className="w-full p-3 border rounded-lg focus:outline-none text-gray-600 focus:ring focus:ring-blue-300 dark:bg-gray-700 dark:text-white"
} // placeholder="Enter your theme suggestion..."
}} // value={suggestion}
rows={1} // onChange={(e) => {
maxLength={32} // if (e.target.value.length <= 32) {
></textarea> // setSuggestion(e.target.value);
{errorMessage && ( // }
<p className="text-red-500 text-sm">{errorMessage}</p> // }}
)} // rows={1}
{successMessage && ( // maxLength={32}
<p className="text-green-500 text-sm">{successMessage}</p> // ></textarea>
)} // {errorMessage && (
<button // <p className="text-red-500 text-sm">{errorMessage}</p>
type="submit" // )}
className={`w-full py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-600 focus:outline-none focus:ring focus:ring-blue-300 ${ // {successMessage && (
loading ? "opacity-50 cursor-not-allowed" : "" // <p className="text-green-500 text-sm">{successMessage}</p>
}`} // )}
disabled={loading} // <button
> // type="submit"
{loading ? "Submitting..." : "Submit Suggestion"} // className={`w-full py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-600 focus:outline-none focus:ring focus:ring-blue-300 ${
</button> // loading ? "opacity-50 cursor-not-allowed" : ""
</form> // }`}
) : ( // disabled={loading}
<p className="text-yellow-500 text-sm"> // >
You've reached your theme suggestion limit for this jam! // {loading ? "Submitting..." : "Submit Suggestion"}
</p> // </button>
)} // </form>
// ) : (
{/* List of user's suggestions */} // <p className="text-yellow-500 text-sm">
<div className="mt-6"> // You&apos;ve reached your theme suggestion limit for this jam!
<h3 className="text-lg font-semibold text-gray-800 dark:text-white mb-4"> // </p>
Your Suggestions // )}
</h3>
{userSuggestions.length > 0 ? ( // {/* List of user's suggestions */}
<ul className="space-y-4"> // <div className="mt-6">
{userSuggestions.map((suggestion) => ( // <h3 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">
<li // Your Suggestions
key={suggestion.id} // </h3>
className="flex justify-between items-center text-gray-400 bg-gray-100 dark:bg-gray-700 p-3 rounded-lg shadow-sm" // {userSuggestions.length > 0 ? (
> // <ul className="space-y-4">
<span>{suggestion.suggestion}</span> // {userSuggestions.map((suggestion) => (
<button // <li
onClick={() => handleDelete(suggestion.id)} // key={suggestion.id}
className="text-red-500 hover:text-red-700 font-semibold" // className="flex justify-between items-center text-gray-400 bg-gray-100 dark:bg-gray-700 p-3 rounded-lg shadow-sm"
> // >
Delete // <span>{suggestion.suggestion}</span>
</button> // <button
</li> // onClick={() => handleDelete(suggestion.id)}
))} // className="text-red-500 hover:text-red-700 font-semibold"
</ul> // >
) : ( // Delete
<p className="text-gray-600 dark:text-gray-400"> // </button>
You haven't submitted any suggestions yet. // </li>
</p> // ))}
)} // </ul>
</div> // ) : (
</div> // <p className="text-gray-600 dark:text-gray-400">
); // You haven&apos;t submitted any suggestions yet.
// </p>
// )}
// </div>
// </div>
// );
return <></>;
} }

View file

@ -1,242 +1,245 @@
"use client"; "use client";
import React, { useState, useEffect } from "react"; // import React, { useState, useEffect } from "react";
import { getCookie } from "@/helpers/cookie"; // import { getCookie } from "@/helpers/cookie";
import { getCurrentJam, hasJoinedCurrentJam , ActiveJamResponse } from "@/helpers/jam"; // import {
// getCurrentJam,
// hasJoinedCurrentJam,
// ActiveJamResponse,
// } from "@/helpers/jam";
export default function VotingPage() { export default function VotingPage() {
const [themes, setThemes] = useState([]); return <></>;
const [loading, setLoading] = useState(false); // const [themes, setThemes] = useState([]);
const [activeJamResponse, setActiveJamResponse] = useState<ActiveJamResponse | null>(null); // const [loading, setLoading] = useState(false);
const [hasJoined, setHasJoined] = useState<boolean>(false); // const [activeJamResponse, setActiveJamResponse] =
const [phaseLoading, setPhaseLoading] = useState(true); // Loading state for fetching phase // useState<ActiveJamResponse | null>(null);
const token = getCookie("token"); // const [hasJoined, setHasJoined] = useState<boolean>(false);
// const [phaseLoading, setPhaseLoading] = useState(true); // Loading state for fetching phase
// const token = getCookie("token");
// Fetch the current jam phase using helpers/jam // // Fetch the current jam phase using helpers/jam
useEffect(() => { // useEffect(() => {
const fetchCurrentJamPhase = async () => { // const fetchCurrentJamPhase = async () => {
try { // try {
const activeJam = await getCurrentJam(); // const activeJam = await getCurrentJam();
setActiveJamResponse(activeJam); // Set active jam details // setActiveJamResponse(activeJam); // Set active jam details
} catch (error) { // } catch (error) {
console.error("Error fetching current jam:", error); // console.error("Error fetching current jam:", error);
} finally { // } finally {
setPhaseLoading(false); // Stop loading when phase is fetched // setPhaseLoading(false); // Stop loading when phase is fetched
} // }
}; // };
fetchCurrentJamPhase(); // fetchCurrentJamPhase();
}, []); // }, []);
// Fetch top N themes with voting scores // // Fetch themes only when phase is "Voting"
const fetchThemes = async () => { // useEffect(() => {
if (!token || !activeJamResponse) return; // // Fetch top N themes with voting scores
// async function fetchThemes() {
try { // if (!token || !activeJamResponse) return;
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD" // try {
? "https://d2jam.com/api/v1/themes/top-themes" // const response = await fetch(
: "http://localhost:3005/api/v1/themes/top-themes", // process.env.NEXT_PUBLIC_MODE === "PROD"
{ // ? "https://d2jam.com/api/v1/themes/top-themes"
headers: { Authorization: `Bearer ${token}` }, // : "http://localhost:3005/api/v1/themes/top-themes",
credentials: "include", // {
} // headers: { Authorization: `Bearer ${token}` },
); // credentials: "include",
if (response.ok) { // }
const themes = await response.json(); // );
console.log("Fetched themes:", themes); // Debug log // if (response.ok) {
// const themes = await response.json();
// Fetch user's votes for these themes // console.log("Fetched themes:", themes); // Debug log
const votesResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD" // // Fetch user's votes for these themes
? "https://d2jam.com/api/v1/themes/votes" // const votesResponse = await fetch(
: "http://localhost:3005/api/v1/themes/votes", // process.env.NEXT_PUBLIC_MODE === "PROD"
{ // ? "https://d2jam.com/api/v1/themes/votes"
headers: { Authorization: `Bearer ${token}` }, // : "http://localhost:3005/api/v1/themes/votes",
credentials: "include", // {
} // headers: { Authorization: `Bearer ${token}` },
); // credentials: "include",
// }
if (votesResponse.ok) { // );
const votes = await votesResponse.json();
console.log("Fetched votes:", votes); // Debug log // if (votesResponse.ok) {
// const votes = await votesResponse.json();
// Merge themes with user's votes // console.log("Fetched votes:", votes); // Debug log
const themesWithVotes = themes.map(theme => {
const vote = votes.find(v => v.themeSuggestionId === theme.id); // // Merge themes with user's votes
console.log(`Theme ${theme.id} vote:`, vote); // Debug log // const themesWithVotes = themes.map((theme) => {
return { // const vote = votes.find((v) => v.themeSuggestionId === theme.id);
...theme, // console.log(`Theme ${theme.id} vote:`, vote); // Debug log
votingScore: vote ? vote.votingScore : null // return {
}; // ...theme,
}); // votingScore: vote ? vote.votingScore : null,
// };
console.log("Themes with votes:", themesWithVotes); // Debug log // });
setThemes(themesWithVotes);
} // console.log("Themes with votes:", themesWithVotes); // Debug log
} else { // setThemes(themesWithVotes);
console.error("Failed to fetch themes."); // }
} // } else {
} catch (error) { // console.error("Failed to fetch themes.");
console.error("Error fetching themes:", error); // }
} // } catch (error) {
}; // console.error("Error fetching themes:", error);
// }
// }
// Fetch themes only when phase is "Voting"
useEffect(() => { // if (activeJamResponse?.phase === "Voting") {
if (activeJamResponse?.phase === "Voting") { // fetchThemes();
fetchThemes(); // }
} // }, [activeJamResponse, token]);
}, [activeJamResponse]);
// // Handle voting
// Handle voting // const handleVote = async (themeId, votingScore) => {
const handleVote = async (themeId, votingScore) => { // setLoading(true);
setLoading(true); // try {
try { // const response = await fetch(
const response = await fetch( // process.env.NEXT_PUBLIC_MODE === "PROD"
process.env.NEXT_PUBLIC_MODE === "PROD" // ? "https://d2jam.com/api/v1/themes/vote"
? "https://d2jam.com/api/v1/themes/vote" // : "http://localhost:3005/api/v1/themes/vote",
: "http://localhost:3005/api/v1/themes/vote", // {
{ // method: "POST",
method: "POST", // headers: {
headers: { // "Content-Type": "application/json",
"Content-Type": "application/json", // Authorization: `Bearer ${token}`,
Authorization: `Bearer ${token}`, // },
}, // credentials: "include",
credentials: "include", // body: JSON.stringify({ suggestionId: themeId, votingScore }),
body: JSON.stringify({ suggestionId: themeId, votingScore }), // }
} // );
);
// if (response.ok) {
if (response.ok) { // // Just update the local state instead of re-fetching all themes
// Just update the local state instead of re-fetching all themes // setThemes((prevThemes) =>
setThemes((prevThemes) => // prevThemes.map((theme) =>
prevThemes.map((theme) => // theme.id === themeId ? { ...theme, votingScore } : theme
theme.id === themeId // )
? { ...theme, votingScore } // );
: theme // } else {
) // console.error("Failed to submit vote.");
); // }
} else { // } catch (error) {
console.error("Failed to submit vote."); // console.error("Error submitting vote:", error);
} // } finally {
} catch (error) { // setLoading(false);
console.error("Error submitting vote:", error); // }
} finally { // };
setLoading(false);
} // useEffect(() => {
}; // const init = async () => {
// const joined = await hasJoinedCurrentJam();
useEffect(() => { // setHasJoined(joined);
const init = async () => { // setLoading(false);
const joined = await hasJoinedCurrentJam(); // };
setHasJoined(joined);
setLoading(false); // init();
}; // }, []);
init(); // if (phaseLoading || loading) {
}, []); // return <div>Loading...</div>;
// }
if (phaseLoading || loading) { // if (!hasJoined) {
return <div>Loading...</div>; // return (
} // <div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen">
// <h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6">
if (!hasJoined) { // Join the Jam First
return ( // </h1>
<div className="p-6 bg-gray-100 dark:bg-gray-800 min-h-screen"> // <p className="text-gray-600 dark:text-gray-400">
<h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-6"> // You need to join the current jam before you can vote themes.
Join the Jam First // </p>
</h1> // <button
<p className="text-gray-600 dark:text-gray-400"> // onClick={() => joinJam(activeJamResponse?.jam?.id)}
You need to join the current jam before you can vote themes. // className="mt-4 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
</p> // >
<button // Join Jam
onClick={() => joinJam(activeJamResponse?.jam?.id)} // </button>
className="mt-4 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600" // </div>
> // );
Join Jam // }
</button>
</div> // if (activeJamResponse?.phase !== "Voting") {
); // return (
} // <div className="p-4 bg-gray-100 dark:bg-gray-800 min-h-screen">
// <h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-4">
// Not in Voting Phase
if (activeJamResponse?.phase !== "Voting") { // </h1>
return ( // <p className="text-gray-600 dark:text-gray-400">
<div className="p-4 bg-gray-100 dark:bg-gray-800 min-h-screen"> // The current phase is{" "}
<h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-4"> // <strong>{activeJamResponse?.phase || "Unknown"}</strong>. Please come
Not in Voting Phase // back during the Voting phase.
</h1> // </p>
<p className="text-gray-600 dark:text-gray-400"> // </div>
The current phase is <strong>{activeJamResponse?.phase || "Unknown"}</strong>. Please come back during the Voting phase. // );
</p> // }
</div>
); // const loggedIn = getCookie("token");
}
// if (!loggedIn) {
const loggedIn = getCookie("token"); // return <div>Sign in to be able to vote</div>;
// }
if (!loggedIn) {
return ( // return (
<div>Sign in to be able to vote</div> // <div className="p-3 bg-gray-100 dark:bg-gray-800 min-h-screen">
); // <h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-4">
} // Voting Phase
// </h1>
return ( // <div className="space-y-2">
<div className="p-3 bg-gray-100 dark:bg-gray-800 min-h-screen"> // {themes.map((theme) => (
<h1 className="text-2xl font-bold text-gray-800 dark:text-white mb-4"> // <div
Voting Phase // key={theme.id}
</h1> // className="p-3 bg-white dark:bg-gray-900 rounded-lg shadow-md flex items-center"
<div className="space-y-2"> // >
{themes.map((theme) => ( // {/* Voting Buttons */}
<div // <div className="flex gap-1 mr-4">
key={theme.id} // <button
className="p-3 bg-white dark:bg-gray-900 rounded-lg shadow-md flex items-center" // onClick={() => handleVote(theme.id, -1)}
> // className={`px-3 py-2 rounded-lg ${
{/* Voting Buttons */} // theme.votingScore === -1
<div className="flex gap-1 mr-4"> // ? "bg-red-500 text-white"
<button // : "bg-gray-300 text-black hover:bg-red-500 hover:text-white"
onClick={() => handleVote(theme.id, -1)} // }`}
className={`px-3 py-2 rounded-lg ${ // disabled={loading}
theme.votingScore === -1 // >
? "bg-red-500 text-white" // -1
: "bg-gray-300 text-black hover:bg-red-500 hover:text-white" // </button>
}`} // <button
disabled={loading} // onClick={() => handleVote(theme.id, 0)}
> // className={`px-3 py-2 rounded-lg ${
-1 // theme.votingScore === 0
</button> // ? "bg-gray-500 text-white"
<button // : "bg-gray-300 text-black hover:bg-gray-500 hover:text-white"
onClick={() => handleVote(theme.id, 0)} // }`}
className={`px-3 py-2 rounded-lg ${ // disabled={loading}
theme.votingScore === 0 // >
? "bg-gray-500 text-white" // 0
: "bg-gray-300 text-black hover:bg-gray-500 hover:text-white" // </button>
}`} // <button
disabled={loading} // onClick={() => handleVote(theme.id, +1)}
> // className={`px-3 py-2 rounded-lg ${
0 // theme.votingScore === +1
</button> // ? "bg-green-500 text-white"
<button // : "bg-gray-300 text-black hover:bg-green-500 hover:text-white"
onClick={() => handleVote(theme.id, +1)} // }`}
className={`px-3 py-2 rounded-lg ${ // disabled={loading}
theme.votingScore === +1 // >
? "bg-green-500 text-white" // +1
: "bg-gray-300 text-black hover:bg-green-500 hover:text-white" // </button>
}`} // </div>
disabled={loading}
> // {/* Theme Suggestion */}
+1 // <div className="text-gray-800 dark:text-white">
</button> // {theme.suggestion}
</div> // </div>
// </div>
{/* Theme Suggestion */} // ))}
<div className="text-gray-800 dark:text-white">{theme.suggestion}</div> // </div>
</div> // </div>
))} // );
</div>
</div>
);
} }

View file

@ -1,15 +1,12 @@
"use client" "use client";
import { Spacer } from "@nextui-org/react"; import { Spacer } from "@nextui-org/react";
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import Timer from "./Timer"; import Timer from "./Timer";
import { getCurrentJam, ActiveJamResponse } from "@/helpers/jam"; import { getCurrentJam, ActiveJamResponse } from "@/helpers/jam";
export default function Timers() { export default function Timers() {
const [activeJamResponse, setActiveJamResponse] =
const [activeJamResponse, setActiveJamResponse] = useState<ActiveJamResponse | null>(null); useState<ActiveJamResponse | null>(null);
const [phaseLoading, setPhaseLoading] = useState(true); // Loading state for fetching phase
// Fetch the current jam phase using helpers/jam // Fetch the current jam phase using helpers/jam
useEffect(() => { useEffect(() => {
@ -20,15 +17,13 @@ export default function Timers() {
} catch (error) { } catch (error) {
console.error("Error fetching current jam:", error); console.error("Error fetching current jam:", error);
} finally { } finally {
setPhaseLoading(false); // Stop loading when phase is fetched
} }
}; };
fetchCurrentJamPhase(); fetchCurrentJamPhase();
}, []); }, []);
if(activeJamResponse && activeJamResponse.jam) if (activeJamResponse && activeJamResponse.jam) {
{
return ( return (
<div className="text-[#333] dark:text-white transition-color duration-250"> <div className="text-[#333] dark:text-white transition-color duration-250">
<Timer <Timer
@ -39,16 +34,13 @@ export default function Timers() {
<p>Site under construction</p> <p>Site under construction</p>
</div> </div>
); );
} } else {
else
{
return ( return (
<div className="text-[#333] dark:text-white transition-color duration-250"> <div className="text-[#333] dark:text-white transition-color duration-250">
No upcoming jams No upcoming jams
<Spacer y={8} /> <Spacer y={8} />
<p>Site under construction</p> <p>Site under construction</p>
</div> </div>
) );
} }
} }

View file

@ -18,11 +18,10 @@ export async function getJams(): Promise<JamType[]> {
} }
export async function getCurrentJam(): Promise<ActiveJamResponse | null> { export async function getCurrentJam(): Promise<ActiveJamResponse | null> {
try { try {
const response = await fetch( const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD" process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/jams" ? "https://d2jam.com/api/v1/jams/active"
: "http://localhost:3005/api/v1/jams/active" : "http://localhost:3005/api/v1/jams/active"
); );
@ -34,12 +33,10 @@ export async function getCurrentJam(): Promise<ActiveJamResponse | null> {
phase: data.phase, phase: data.phase,
jam: data.jam, jam: data.jam,
}; };
} catch (error) { } catch (error) {
console.error("Error fetching active jam:", error); console.error("Error fetching active jam:", error);
return null; return null;
} }
} }
export async function joinJam(jamId: number) { export async function joinJam(jamId: number) {
@ -53,7 +50,7 @@ export async function joinJam(jamId: number) {
userSlug: getCookie("user"), userSlug: getCookie("user"),
}), }),
method: "POST", method: "POST",
credentials: 'include', credentials: "include",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`, authorization: `Bearer ${getCookie("token")}`,
@ -80,7 +77,7 @@ export async function hasJoinedCurrentJam(): Promise<boolean> {
? "https://d2jam.com/api/v1/participation" ? "https://d2jam.com/api/v1/participation"
: "http://localhost:3005/api/v1/participation", : "http://localhost:3005/api/v1/participation",
{ {
credentials: 'include', credentials: "include",
headers: { headers: {
Authorization: `Bearer ${getCookie("token")}`, Authorization: `Bearer ${getCookie("token")}`,
}, },

View file

@ -3,7 +3,9 @@ import { UserType } from "./UserType";
export interface PostType { export interface PostType {
id: number; id: number;
slug: string;
title: string; title: string;
sticky: boolean;
content: string; content: string;
author: UserType; author: UserType;
createdAt: Date; createdAt: Date;