/* * Vencord, a Discord client mod * Copyright (c) 2024 Vendicated and contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Logger } from "@utils/Logger"; import { Button, useEffect, UserStore, useState } from "@webpack/common"; import type { User } from "discord-types/general"; import type { Theme, ThemeLikeProps } from "../types"; import { themeRequest } from "./ThemeTab"; const logger = new Logger("ThemeLibrary", "#e5c890"); const fetchLikes = async () => { try { const response = await themeRequest("/likes/get"); const data = await response.json(); return data; } catch (err) { logger.error(err); } }; export const LikesComponent = ({ themeId, likedThemes: initialLikedThemes }: { themeId: Theme["id"], likedThemes: ThemeLikeProps | undefined; }) => { const [likesCount, setLikesCount] = useState(0); const [likedThemes, setLikedThemes] = useState(initialLikedThemes); useEffect(() => { const likes = getThemeLikes(themeId); logger.debug("likes", likes, "for:", themeId); setLikesCount(likes); }, [likedThemes, themeId]); function getThemeLikes(themeId: Theme["id"]): number { const themeLike = likedThemes?.likes.find(like => like.themeId === themeId as unknown as Number); return themeLike ? themeLike.userIds.length : 0; } const likeIcon = (isLiked: boolean) => ( ); const handleLikeClick = async (themeId: Theme["id"]) => { const theme = likedThemes?.likes.find(like => like.themeId === themeId as unknown as Number); const currentUser: User = UserStore.getCurrentUser(); const hasLiked: boolean = theme?.userIds.includes(currentUser.id) ?? false; const endpoint = hasLiked ? "/likes/remove" : "/likes/add"; try { const response = await themeRequest(endpoint, { method: "POST", headers: { "Content-Type": "application/json", }, cache: "no-store", body: JSON.stringify({ userId: currentUser.id, themeId: themeId, }), }); if (!response.ok) return logger.error("Couldnt update likes, res:", response.statusText); const fetchLikes = async () => { try { const response = await themeRequest("/likes/get"); const data = await response.json(); setLikedThemes(data); } catch (err) { logger.error(err); } }; fetchLikes(); // doing it locally isnt the best way probably, but it does the same setLikesCount(likesCount + (hasLiked ? -1 : 1)); } catch (err) { logger.error(err); } }; const hasLiked = likedThemes?.likes.some(like => like.themeId === themeId as unknown as Number && like.userIds.includes(UserStore.getCurrentUser().id)) ?? false; return (
); };