From 84469cd59a9a07275d0d9ac903f894c7a29e1b46 Mon Sep 17 00:00:00 2001 From: UnknownDev303 Date: Thu, 16 Jan 2025 13:22:38 +0530 Subject: [PATCH] bug: fixed author and label filter on devops forum --- website3.0/pages/ForumPage.js | 1373 +++++++++++++++++++++------------ 1 file changed, 864 insertions(+), 509 deletions(-) diff --git a/website3.0/pages/ForumPage.js b/website3.0/pages/ForumPage.js index 7297cd49..fb1529fc 100644 --- a/website3.0/pages/ForumPage.js +++ b/website3.0/pages/ForumPage.js @@ -24,7 +24,7 @@ import { } from "@fortawesome/free-regular-svg-icons"; import { faGithub, faLinkedin } from "@fortawesome/free-brands-svg-icons"; import { useRouter } from "next/navigation"; -import styles from '../stylesheets/forumanimation.css' +import styles from "../stylesheets/forumanimation.css"; const Sidebar01Item = ({ title, isActive, onClick, icon, theme }) => { return ( @@ -42,11 +42,18 @@ const Sidebar01Item = ({ title, isActive, onClick, icon, theme }) => { }; const Tag = ({ name }) => ( -
{ - if(selectedTags.includes(name)){let arr=selectedTags; - arr=arr.filter((data)=>data!==name) - setSelectedTags([...arr]) - }else{setSelectedTags(prev=>[...prev,name])}}} className="bg-gray-200 px-4 py-1 text-gray-700 cursor-pointer hover:bg-[#deecf5] hover:text-[#6089a4] transition-all duration-200"> +
{ + if (selectedTags.includes(name)) { + let arr = selectedTags; + arr = arr.filter((data) => data !== name); + setSelectedTags([...arr]); + } else { + setSelectedTags((prev) => [...prev, name]); + } + }} + className="bg-gray-200 px-4 py-1 text-gray-700 cursor-pointer hover:bg-[#deecf5] hover:text-[#6089a4] transition-all duration-200" + > {name}
); @@ -59,10 +66,23 @@ const RecentTopics = ({ topic, img, user, theme }) => ( > {topic} -
+ +
Question By - - {e.target.src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQw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X/wALQAAAAAA15FbtpnBPRyi1qcudRfPs6pz+GLZy65AAAAAAHQ7KeuDX5ar92SyFsj7jD1l82TQDObzo7mZcusm/14nSFHtmvdyoz904/uv+oCvAAAAAbsXJljW78Fr1XVHSVy34RkuTWpyp0OzLVZhV9Yrdf5ASwAADBh8gKja+VLeljJLTROT6lWb82xW5Vk1yb4ei4GgAAAABmMXOSiubeiA6LZsd3CqT56a/qSTzXFQhGK5JaHoAQdr09rjby8Vb3vy95OMNJrRgcoCRm47xsiUNO6+MX5EcAAe4VzselcJS9FqB5LjYXsbfxfQi07Kvn7TdrXm9WWmFiRxYSUZOW89W2BJAAA8W8Kp/hZ7MTW9FxfvWgHKLkgWl2yJLV02J+Ul9SFbi30+0qkl1S1QGgAACdsmntMpTfhr4v19xC58lqzodn432bHUX43xl6gSgAAAAEXOxVk06LxrjFlXibOd7lvW7m69JR04oviLlY8t9X4+iuXPXlNdGB4p2Zj18XFzfWX8CXCMYLSMVFdEtDVjZMb1po42R8UHzTN4AAAAAAAAAAAR78Oi7x1LXquDIN+yYqLlXbolx7/L9S0nOMIuU2lFc2yF3s+SfGOKn6Oz+QEXZOFvS7ezjFPuefmXJiKUUkuCXJGQAAAAAAAAI+RjRuanFuFq5TjzNSyrKHu5kNF7rYrWL9ehNMNJrRrVdAMQnGcVKMk0/enqeiJLBgnvY85US/wAj4P8AIxrnVc1XdHye6wJgIazJx9piXx9FvGf6QrXOu9f7TAlgifb4vwY+RL0r0+Zjtsuz2eMoLrZL6ICYRrsyuEtyvW234IcX+fQ8fZbrfvORJr4K+6iRTTXStKoRivJARo41mRJWZjTS4xqXJevUmLkZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH//2Q=="}} alt="User" className="rounded-full w-5 h-5" /> + { + e.target.src = + "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3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XYlT7929w8O7p6Mtyr2HPWu2vpJS/X/wALQAAAAAA15FbtpnBPRyi1qcudRfPs6pz+GLZy65AAAAAAHQ7KeuDX5ar92SyFsj7jD1l82TQDObzo7mZcusm/14nSFHtmvdyoz904/uv+oCvAAAAAbsXJljW78Fr1XVHSVy34RkuTWpyp0OzLVZhV9Yrdf5ASwAADBh8gKja+VLeljJLTROT6lWb82xW5Vk1yb4ei4GgAAAABmMXOSiubeiA6LZsd3CqT56a/qSTzXFQhGK5JaHoAQdr09rjby8Vb3vy95OMNJrRgcoCRm47xsiUNO6+MX5EcAAe4VzselcJS9FqB5LjYXsbfxfQi07Kvn7TdrXm9WWmFiRxYSUZOW89W2BJAAA8W8Kp/hZ7MTW9FxfvWgHKLkgWl2yJLV02J+Ul9SFbi30+0qkl1S1QGgAACdsmntMpTfhr4v19xC58lqzodn432bHUX43xl6gSgAAAAEXOxVk06LxrjFlXibOd7lvW7m69JR04oviLlY8t9X4+iuXPXlNdGB4p2Zj18XFzfWX8CXCMYLSMVFdEtDVjZMb1po42R8UHzTN4AAAAAAAAAAAR78Oi7x1LXquDIN+yYqLlXbolx7/L9S0nOMIuU2lFc2yF3s+SfGOKn6Oz+QEXZOFvS7ezjFPuefmXJiKUUkuCXJGQAAAAAAAAI+RjRuanFuFq5TjzNSyrKHu5kNF7rYrWL9ehNMNJrRrVdAMQnGcVKMk0/enqeiJLBgnvY85US/wAj4P8AIxrnVc1XdHye6wJgIazJx9piXx9FvGf6QrXOu9f7TAlgifb4vwY+RL0r0+Zjtsuz2eMoLrZL6ICYRrsyuEtyvW234IcX+fQ8fZbrfvORJr4K+6iRTTXStKoRivJARo41mRJWZjTS4xqXJevUmLkZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH//2Q=="; + }} + alt="User" + className="rounded-full w-5 h-5" + /> {user}
@@ -70,32 +90,37 @@ const RecentTopics = ({ topic, img, user, theme }) => ( ); const HelpfulUser = ({ user }) => { -return
-
-
- User -
{user.name}
-
-
- - {user.answers} + return ( +
+
+
+ User +
{user.name}
+
+
+ + {user.answers} +
+
-
-
+ ); }; const TopIssue = ({ title, index }) => (
{index + 1 < 10 ? `0${index + 1}` : index + 1} - + {title}
); -function ForumPage({ theme,finalUser,setIsPopup,setMsg }) { +function ForumPage({ theme, finalUser, setIsPopup, setMsg }) { const [activeMenuItem, setActiveMenuItem] = useState("View All"); // Tracks the currently selected menu item const router = useRouter(); // Provides access to router functions and properties const [hoveredUser, setHoveredUser] = useState(null); // Stores the user being hovered over for displaying additional info @@ -107,56 +132,60 @@ function ForumPage({ theme,finalUser,setIsPopup,setMsg }) { const [sortedArray, setSortedArray] = useState([]); // Stores an array of sorted data const [mostHelpful, setMostHelpful] = useState([]); // Holds the most helpful data or users const [selectedTags, setSelectedTags] = useState([]); // Stores the tags that have been selected by the user - const [openCount,setOpenCount]=useState(0) + const [openCount, setOpenCount] = useState(0); + const [showAuthorDropdown, setShowAuthorDropdown] = useState(false); + const [showLabelDropdown, setShowLabelDropdown] = useState(false); + const [selectedAuthor, setSelectedAuthor] = useState(null); + const [selectedLabel, setSelectedLabel] = useState(null); // Function to handle mouse entering an element (e.g., user profile) const handleMouseEnter = async (event, userImg) => { - // Update cursor position for positioning additional info display - setCursorPosition({ x: event.clientX, y: event.clientY }); - - // Create a copy of the user image object - let obj = { ...userImg }; - console.log(userImg); // Debugging: Log the user image object - - // Fetch user details by user ID from the API - let u = await fetch("/api/getuserbyid", { - method: "POST", - body: JSON.stringify({ id: userImg.authorId }), // Send user ID to fetch details - }); - u = await u.json(); - u = u.msg; // Extract the user details from the response - console.log(u, "user"); // Debugging: Log the fetched user details - - // Update the user object with additional information - obj = { - ...obj, - count: Object.keys(u.followers).length, // Count of followers - questions: u.questions, // User's questions - answers: u.answers, // User's answers - }; - setHoveredUser(obj); // Update the state to display user info + // Update cursor position for positioning additional info display + setCursorPosition({ x: event.clientX, y: event.clientY }); + + // Create a copy of the user image object + let obj = { ...userImg }; + console.log(userImg); // Debugging: Log the user image object + + // Fetch user details by user ID from the API + let u = await fetch("/api/getuserbyid", { + method: "POST", + body: JSON.stringify({ id: userImg.authorId }), // Send user ID to fetch details + }); + u = await u.json(); + u = u.msg; // Extract the user details from the response + console.log(u, "user"); // Debugging: Log the fetched user details + + // Update the user object with additional information + obj = { + ...obj, + count: Object.keys(u.followers).length, // Count of followers + questions: u.questions, // User's questions + answers: u.answers, // User's answers + }; + setHoveredUser(obj); // Update the state to display user info }; - + // Function to handle mouse leaving the element const handleMouseLeave = () => { - setHoveredUser(null); // Clear the hovered user info + setHoveredUser(null); // Clear the hovered user info }; - + // Function to handle sidebar menu item clicks const handleSidebar01 = (title) => { - setActiveMenuItem(title); // Update the active menu item - - if (title === "View All") { - // If "View All" is selected, reset to the original issues list - setIssues([...originalIssues]); - return; - } - - // Filter the issues based on the selected title/type - let arr = [...originalIssues]; - arr = arr.filter((data) => data.type === title); - setIssues([...arr]); // Update the issues state with the filtered list + setActiveMenuItem(title); // Update the active menu item + + if (title === "View All") { + // If "View All" is selected, reset to the original issues list + setIssues([...originalIssues]); + return; + } + + // Filter the issues based on the selected title/type + let arr = [...originalIssues]; + arr = arr.filter((data) => data.type === title); + setIssues([...arr]); // Update the issues state with the filtered list }; - + // State and variables related to issues const [issues, setIssues] = useState([]); // Stores the list of issues to display const [originalIssues, setOriginalIssues] = useState([]); // Holds the original list of issues for resetting @@ -171,75 +200,84 @@ function ForumPage({ theme,finalUser,setIsPopup,setMsg }) { "AWS", "Kubernetes", ]; - useEffect(()=>{ - fetchData() - },[]) + useEffect(() => { + fetchData(); + }, []); async function fetchData() { try { - // Fetch initial data - let response = await fetch("/api/createquestion", { method: "GET" }); - let data = await response.json(); - data = data.data; - let count=0 - data.map((d)=>{ - if(!d.isCLose){ - count++ - } - }) - setOpenCount(count) - // Filter out items without 'createdAt' - let arr = data.filter(item => item.createdAt !== undefined); + // Fetch initial data + let response = await fetch("/api/createquestion", { method: "GET" }); + let data = await response.json(); + data = data.data; + let count = 0; + data.map((d) => { + if (!d.isCLose) { + count++; + } + }); + setOpenCount(count); + // Filter out items without 'createdAt' + let arr = data.filter((item) => item.createdAt !== undefined); - // Create an empty object to store user messages - let obj1 = []; + // Create an empty object to store user messages + let obj1 = []; - // Collect all user IDs to fetch in parallel - let userPromises = data.flatMap(item => - item.relatedUser.map(async (userRef) => { - setUsers(prev=>[...prev,userRef.authorId]) - - }) - ); - // Sort and update state - arr = arr.sort((a, b) => a.createdAt - b.createdAt); - setSortedArray([...arr]); + // Collect all user IDs to fetch in parallel + let userPromises = data.flatMap((item) => + item.relatedUser.map(async (userRef) => { + setUsers((prev) => [...prev, userRef.authorId]); + }) + ); + // Sort and update state + arr = arr.sort((a, b) => a.createdAt - b.createdAt); + setSortedArray([...arr]); - let arr1 = [...arr].sort((a, b) => b.views - a.views); - setTop([...arr1]); + let arr1 = [...arr].sort((a, b) => b.views - a.views); + setTop([...arr1]); - // Reverse the data and update state - data.reverse(); - let a1=[...data] - a1=a1.filter((data)=>!data.isCLose) - console.log("A!!!!!!!!!!!!!!!!",a1) - setIssues([...a1]); - setOriginalIssues([...data]); - let a=data.sort((c,b)=>b.solutions.length-c.solutions.length) - let ar=[] - for(let i=0;i !data.isCLose); + console.log("A!!!!!!!!!!!!!!!!", a1); + setIssues([...a1]); + setOriginalIssues([...data]); + let a = data.sort((c, b) => b.solutions.length - c.solutions.length); + let ar = []; + for (let i = 0; i < a.length; i++) { + ar.push({ + image1: a[i].authorImage, + name: a[i].authorName, + answers: a[i].solutions.length, + }); + } + setMostHelpful([...ar]); + setLoading(false); } catch (error) { - console.error("Error fetching data:", error); + console.error("Error fetching data:", error); } -} + } - let search=useRef() -function handleSearch(){ - let arr=originalIssues - let value=search.current.value - if(value.length==0){ - setIssues([...originalIssues]) + let search = useRef(); + function handleSearch() { + let arr = originalIssues; + let value = search.current.value; + if (value.length == 0) { + setIssues([...originalIssues]); } - value=value.toLowerCase() - arr=arr.filter((data)=>data.title.toLowerCase().includes(value)) - setIssues([...arr]) -} - let sortLabels=[ - 'Newest','Oldest','Most liked','Most Viewed','Most Commented','Recently Updated','Least Commented'] - + value = value.toLowerCase(); + arr = arr.filter((data) => data.title.toLowerCase().includes(value)); + setIssues([...arr]); + } + let sortLabels = [ + "Newest", + "Oldest", + "Most liked", + "Most Viewed", + "Most Commented", + "Recently Updated", + "Least Commented", + ]; const recent = [ { @@ -259,7 +297,7 @@ function handleSearch(){ }, ]; -const helpfulUsers = [ + const helpfulUsers = [ { name: "cleo-parra", img: "https://randomuser.me/api/portraits/men/13.jpg", @@ -281,163 +319,217 @@ const helpfulUsers = [ issuesSolved: 3, }, ]; -// State and variables initialization -const [currentPage, setCurrentPage] = useState(1); // Tracks the current page for pagination -let [sortModal, setShowSortModal] = useState(false); // Manages the visibility of the sort modal -const issuesPerPage = 10; // Number of issues displayed per page -const totalPages = Math.ceil(issues.length / issuesPerPage); // Total number of pages based on issues count + // State and variables initialization + const [currentPage, setCurrentPage] = useState(1); // Tracks the current page for pagination + let [sortModal, setShowSortModal] = useState(false); // Manages the visibility of the sort modal + const issuesPerPage = 10; // Number of issues displayed per page + const totalPages = Math.ceil(issues.length / issuesPerPage); // Total number of pages based on issues count -// State to manage current issues being displayed based on pagination -let [currentIssues, setCurrentIssues] = useState([]); + // State to manage current issues being displayed based on pagination + let [currentIssues, setCurrentIssues] = useState([]); -// Effect to update current issues when issues list or current page changes -useEffect(() => { - setCurrentIssues(issues.slice( + // Effect to update current issues when issues list or current page changes + useEffect(() => { + setCurrentIssues( + issues.slice( (currentPage - 1) * issuesPerPage, // Start index of issues for current page currentPage * issuesPerPage // End index (exclusive) for current page - )); -}, [issues, currentPage]); + ) + ); + }, [issues, currentPage]); -// Function to handle page changes -const handlePageChange = (page) => { + // Function to handle page changes + const handlePageChange = (page) => { if (page < 1 || page > totalPages) return; // Prevent invalid page numbers setCurrentPage(page); // Update current page -}; + }; -// Array of sample DevOps issues for demonstration or testing -const devopsIssues = [ + // Array of sample DevOps issues for demonstration or testing + const devopsIssues = [ "Issue with Kubernetes Pod Scaling", "Troubleshooting Docker Container Networking", "Configuring AWS IAM Roles for EKS", "Azure DevOps Pipeline Failure", "Docker Compose Not Starting Services", "Kubernetes Cluster Authentication Issue", -]; + ]; -// Function to handle click event on a question -function handleOnClick(id) { + // Function to handle click event on a question + function handleOnClick(id) { // Redirects to the DevOps forum page with the question ID window.location.href = `/devopsforum?id=${id}`; -} + } -// Function to reset issues to the original list -function handleReset() { + // Function to reset issues to the original list + function handleReset() { setIssues([...originalIssues]); -} + } -// Function to handle sorting of issues based on various criteria -const handleSortClick = (title) => { + // Function to handle sorting of issues based on various criteria + const handleSortClick = (title) => { let arr = [...issues]; // Create a copy of the issues array to sort switch (title) { - case 'Most Commented': - arr.sort((a, b) => b.reactions.comments - a.reactions.comments); // Sort by most comments - break; - case 'Least Commented': - arr.sort((a, b) => a.reactions.comments - b.reactions.comments); // Sort by least comments - break; - case 'Most liked': - arr.sort((a, b) => b.reactions.likes - a.reactions.likes); // Sort by most likes - break; - case 'Least liked': - arr.sort((a, b) => a.reactions.likes - b.reactions.likes); // Sort by least likes - break; - case 'Most Viewed': - arr.sort((a, b) => b.reactions.views - a.reactions.views); // Sort by most views - break; - case 'Least Viewed': - arr.sort((a, b) => a.reactions.views - b.reactions.views); // Sort by least views - break; - case 'Oldest': - arr.sort((a, b) => new Date(a.date) - new Date(b.date)); // Sort by oldest date - break; - case 'Recently Updated': - arr.sort((a, b) => new Date(b.updatedDate) - new Date(a.updatedDate)); // Sort by most recent update - break; - default: - break; + case "Most Commented": + arr.sort((a, b) => b.reactions.comments - a.reactions.comments); // Sort by most comments + break; + case "Least Commented": + arr.sort((a, b) => a.reactions.comments - b.reactions.comments); // Sort by least comments + break; + case "Most liked": + arr.sort((a, b) => b.reactions.likes - a.reactions.likes); // Sort by most likes + break; + case "Least liked": + arr.sort((a, b) => a.reactions.likes - b.reactions.likes); // Sort by least likes + break; + case "Most Viewed": + arr.sort((a, b) => b.reactions.views - a.reactions.views); // Sort by most views + break; + case "Least Viewed": + arr.sort((a, b) => a.reactions.views - b.reactions.views); // Sort by least views + break; + case "Oldest": + arr.sort((a, b) => new Date(a.date) - new Date(b.date)); // Sort by oldest date + break; + case "Recently Updated": + arr.sort((a, b) => new Date(b.updatedDate) - new Date(a.updatedDate)); // Sort by most recent update + break; + default: + break; } setIssues(arr); // Update issues with sorted array // Update currentIssues based on the new sorted order // setCurrentIssues(arr.slice((currentPage - 1) * issuesPerPage, currentPage * issuesPerPage)); -}; + }; -// Function to handle asking a question -function handleAskQuestion() { - if (!finalUser || !localStorage.getItem('finalUser')) { - setIsPopup(true); - setMsg("Please Login to Ask Question"); - setTimeout(() => { - setIsPopup(false); - setMsg(''); - }, 3000); - return; + // Function to handle asking a question + function handleAskQuestion() { + if (!finalUser || !localStorage.getItem("finalUser")) { + setIsPopup(true); + setMsg("Please Login to Ask Question"); + setTimeout(() => { + setIsPopup(false); + setMsg(""); + }, 3000); + return; } router.push("/createforum"); // Redirect to the forum creation page -} + } -// Function to handle liking a question -async function handleLike(e, question) { + // Function to handle liking a question + async function handleLike(e, question) { e.preventDefault(); // Prevent default link behavior if (!finalUser) return; // If no user is logged in, do nothing // Send like data to the server let data = await fetch("/api/questionlikes", { - method: "POST", - body: JSON.stringify({ - id: question._id, // Question ID - user_id: finalUser._id // Logged-in user ID - }), + method: "POST", + body: JSON.stringify({ + id: question._id, // Question ID + user_id: finalUser._id, // Logged-in user ID + }), }); let arr = issues; arr.map((data) => { - if (data._id === question._id) { - // Toggle like status - if (data.likes.includes(finalUser._id)) { - data.likes = data.likes.filter((d) => d !== finalUser._id); - } else { - data.likes.push(finalUser._id); - } + if (data._id === question._id) { + // Toggle like status + if (data.likes.includes(finalUser._id)) { + data.likes = data.likes.filter((d) => d !== finalUser._id); + } else { + data.likes.push(finalUser._id); } - return data; + } + return data; }); setIssues([...arr]); // Update issues with new like status setOriginalIssues([...arr]); // Also update original issues list -} + } -// Effect to filter issues based on selected tags -useEffect(() => { + // Effect to filter issues based on selected tags + useEffect(() => { let arr = []; if (selectedTags.length === 0) { - setIssues([...originalIssues]); // Reset issues if no tags are selected - return; + setIssues([...originalIssues]); // Reset issues if no tags are selected + return; } // Filter issues based on selected tags originalIssues.forEach((data) => { - let ans = false; - data.tags.forEach((name) => { - if (selectedTags.includes(name)) { - ans = true; - } - }); - if (ans) { - arr.push(data); + let ans = false; + data.tags.forEach((name) => { + if (selectedTags.includes(name)) { + ans = true; } + }); + if (ans) { + arr.push(data); + } }); setIssues([...arr]); // Update issues with filtered data -}, [selectedTags]); // Re-run effect when selectedTags changes -useEffect(()=>{ -if(isClosed){ - let arr=originalIssues - arr=arr.filter((data)=>data.isCLose) - setCurrentIssues([...arr]) -}else{ + }, [selectedTags]); // Re-run effect when selectedTags changes + useEffect(() => { + if (isClosed) { + let arr = originalIssues; + arr = arr.filter((data) => data.isCLose); + setCurrentIssues([...arr]); + } else { + let arr = originalIssues; + arr = arr.filter((data) => !data.isCLose); + setCurrentIssues([...arr]); + } + }, [isClosed]); - let arr=originalIssues - arr=arr.filter((data)=>!data.isCLose) - setCurrentIssues([...arr]) -} -},[isClosed]) + const authors = Array.from( + new Set(originalIssues.map((issue) => issue.authorName)) + ); + const labels = Array.from( + new Set(originalIssues.flatMap((issue) => issue.tags)) + ); + const toggleAuthorDropdown = () => { + setShowAuthorDropdown(!showAuthorDropdown); + setShowLabelDropdown(false); + }; + + const toggleLabelDropdown = () => { + setShowLabelDropdown(!showLabelDropdown); + setShowAuthorDropdown(false); + }; + + const handleAuthorSelect = (author) => { + if (selectedAuthor === author) { + setSelectedAuthor(null); + setCurrentIssues(originalIssues); + } else { + setSelectedAuthor(author); + filterIssuesByAuthor(author); + } + setShowAuthorDropdown(false); + }; + + const handleLabelSelect = (label) => { + if (selectedLabel === label) { + setSelectedLabel(null); + setCurrentIssues(originalIssues); + } else { + setSelectedLabel(label); + filterIssuesByLabel(label); + } + setShowLabelDropdown(false); + }; + + const filterIssuesByAuthor = (author) => { + const filteredIssues = originalIssues.filter( + (issue) => issue.authorName === author + ); + setCurrentIssues(filteredIssues); + }; + + // Filter issues based on selected label + const filterIssuesByLabel = (label) => { + const filteredIssues = originalIssues.filter((issue) => + issue.tags.includes(label) + ); + setCurrentIssues(filteredIssues); // Update issues based on selected label + }; return (
@@ -458,7 +550,11 @@ if(isClosed){ Popular Searches: Docker, Azure, CI/CD
- img + img
{tags.map((name, index) => ( -
{ - if(selectedTags.includes(name)){let arr=selectedTags; - arr=arr.filter((data)=>data!==name) - setSelectedTags([...arr]) - }else{ - setSelectedTags(prev=>[...prev,name])} - } - } className={` ${selectedTags.includes(name)?"bg-gray-400":"bg-gray-200"} px-4 py-1 text-gray-700 cursor-pointer hover:bg-[#deecf5] hover:text-[#6089a4] transition-all duration-200`}> - {name} -
+
{ + if (selectedTags.includes(name)) { + let arr = selectedTags; + arr = arr.filter((data) => data !== name); + setSelectedTags([...arr]); + } else { + setSelectedTags((prev) => [...prev, name]); + } + }} + className={` ${ + selectedTags.includes(name) + ? "bg-gray-400" + : "bg-gray-200" + } px-4 py-1 text-gray-700 cursor-pointer hover:bg-[#deecf5] hover:text-[#6089a4] transition-all duration-200`} + > + {name} +
))} -
@@ -542,7 +647,7 @@ if(isClosed){ theme ? "" : "text-white" } flex flex-wrap mt-5 gap-4 cursor-pointer`} > - {sortedArray.slice(0,4).map((item, index) => ( + {sortedArray.slice(0, 4).map((item, index) => ( - ))} {sortedArray.length<4&&recent.map((item, index) => { - if(index<4-sortedArray.length){ - - return - } -})} + ))}{" "} + {sortedArray.length < 4 && + recent.map((item, index) => { + if (index < 4 - sortedArray.length) { + return ( + + ); + } + })}
@@ -571,15 +679,24 @@ if(isClosed){
-
setIsClosed(false)}className="flex items-center gap-2 max-sm:text-[14px] cursor-pointer"> +
setIsClosed(false)} + className="flex items-center gap-2 max-sm:text-[14px] cursor-pointer" + > {openCount} Open
-
setIsClosed(true)} className="flex items-center gap-2 max-sm:text-[14px] cursor-pointer"> +
setIsClosed(true)} + className="flex items-center gap-2 max-sm:text-[14px] cursor-pointer" + > - {originalIssues.length-openCount} Closed + {originalIssues.length - openCount} Closed
-
+
Reset
@@ -589,250 +706,411 @@ if(isClosed){ theme ? "max-sm:bg-white max-sm:text-black" : "max-sm:bg-black max-sm:text-white" - } max-sm:h-[41px] max-sm:top-1 max-sm:border-b-[1px] max-sm:border-t-[1px] max-sm:relative max-sm:w-[100%] max-sm:px-2 gap-12 items-center`} + } max-sm:h-[41px] relative max-sm:top-1 max-sm:border-b-[1px] max-sm:border-t-[1px] max-sm:relative max-sm:w-[100%] max-sm:px-2 gap-12 items-center`} > -
+
toggleAuthorDropdown()} + className="flex gap-2 items-center cursor-pointer" + > Author{" "}
-
- Label -
-
sortModal?setShowSortModal(false):setShowSortModal(true)} className="flex gap-2 relative items-center cursor-pointer"> - Sort - {sortModal && -
- { - sortLabels.map((data)=>{ - return

handleSortClick(data)} className="p-2 hover:bg-gray-200 text-sm border-t-gray-500 border-t-[1px] w-[100%]">{data}

- }) - } + + {showAuthorDropdown && ( +
+ {authors.map((author, index) => ( +
handleAuthorSelect(author)} + > + {author} +
+ ))}
- }
-
-
-
-
- { - loading?Array.from({ length: 10 }).map((_, index) => ( -
-
-
-
- -
- - - + )} + +
toggleLabelDropdown()} + > + Label
-
- -
- -
-
-
- )): - - currentIssues.map((issue, index) => ( - (!isClosed&& - !issue.isCLose)||(issue.discussionUsers)? -
-
-
handleOnClick(issue._id)} - className="flex items-center gap-4"> - { - e.target.src=issue.userImage - }} - className="rounded-full w-10 h-10" - /> -
+ + {showLabelDropdown && ( +
+ {labels.map((label, index) => (
handleLabelSelect(label)} > - {issue.title} -
-
- { - issue.tags.slice(0,tags.length>4?4:tags.length).map((data)=>{ - return {data} - }) - } -
-
- {issue.type} • {issue.dateTime} + {label}
-
+ ))}
+ )} -
-
- { - issue?.relatedUser.length>4&&+ {issue?.relatedUser.length-4} - } - {issue?.relatedUser.slice(0,issue?.relatedUser.length>4?4:issue?.relatedUser.length).map((user, idx) => { - return router.push(`/profile?id=${user.authorId}`)} - src={user.authorImage} - id="img" - alt="Discussion User" - className="rounded-full w-5 h-5" - onMouseEnter={(event) => handleMouseEnter(event, user)} - onMouseLeave={handleMouseLeave} - /> -})} -
-
handleLike(e,issue)} className=" flex items-center gap-2 max-sm:text-[11px]"> - - {issue?.likes?.length} -
-
- - {issue?.comments?.length} +
+ sortModal + ? setShowSortModal(false) + : setShowSortModal(true) + } + className="flex gap-2 relative items-center cursor-pointer" + > + Sort + {sortModal && ( +
+ {sortLabels.map((data) => { + return ( +

handleSortClick(data)} + className="p-2 hover:bg-gray-200 text-sm border-t-gray-500 border-t-[1px] w-[100%]" + > + {data} +

+ ); + })}
-
- - {issue&&issue.views?(Math.ceil(issue?.views/2)):0} - + )} +
+
+
+
+
+ {loading + ? Array.from({ length: 10 }).map((_, index) => ( +
+
+
+
+ +
+ + + +
+
+
+
-
-
: - - issue.isCLose&&
-
-
handleOnClick(issue._id)} -className="flex items-center gap-4"> - { - e.target.src=issue.userImage - }} - className="rounded-full w-10 h-10" - /> -
+ )) + : currentIssues.map((issue, index) => + (!isClosed && !issue.isCLose) || + issue.discussionUsers ? (
- {issue.title} -
-
- {issue.type} • {issue.dateTime} +
+
handleOnClick(issue._id)} + className="flex items-center gap-4" + > + { + e.target.src = issue.userImage; + }} + className="rounded-full w-10 h-10" + /> +
+
+ {issue.title} +
+
+ {issue.tags + .slice( + 0, + tags.length > 4 ? 4 : tags.length + ) + .map((data) => { + return {data}; + })} +
+
+ {issue.type} • {issue.dateTime} +
+
+
+ +
+
+ {issue?.relatedUser.length > 4 && ( + + + {issue?.relatedUser.length - 4} + + )} + {issue?.relatedUser + .slice( + 0, + issue?.relatedUser.length > 4 + ? 4 + : issue?.relatedUser.length + ) + .map((user, idx) => { + return ( + + router.push( + `/profile?id=${user.authorId}` + ) + } + src={user.authorImage} + id="img" + alt="Discussion User" + className="rounded-full w-5 h-5" + onMouseEnter={(event) => + handleMouseEnter(event, user) + } + onMouseLeave={handleMouseLeave} + /> + ); + })} +
+
handleLike(e, issue)} + className=" flex items-center gap-2 max-sm:text-[11px]" + > + + {issue?.likes?.length} +
+
+ + {issue?.comments?.length} +
+
+ + + {issue && issue.views + ? Math.ceil(issue?.views / 2) + : 0} + +
+
+
-
-
+ ) : ( + issue.isCLose && ( +
+
+
handleOnClick(issue._id)} + className="flex items-center gap-4" + > + { + e.target.src = issue.userImage; + }} + className="rounded-full w-10 h-10" + /> +
+
+ {issue.title} +
+
+ {issue.type} • {issue.dateTime} +
+
+
-
-
- {issue?.relatedUser.map((user, idx) => { - return Discussion User handleMouseEnter(event, user)} - onMouseLeave={handleMouseLeave} - /> -})} -
-
handleLike(e,issue)} className=" flex items-center gap-2 max-sm:text-[11px]"> - - {issue?.likes?.length} -
-
- - {issue?.comments?.length} +
+
+ {issue?.relatedUser.map((user, idx) => { + return ( + Discussion User + handleMouseEnter(event, user) + } + onMouseLeave={handleMouseLeave} + /> + ); + })} +
+
handleLike(e, issue)} + className=" flex items-center gap-2 max-sm:text-[11px]" + > + + {issue?.likes?.length} +
+
+ + {issue?.comments?.length} +
+
+ + + {issue && issue.views + ? Math.ceil(issue?.views / 2) + : 0} + +
+
+
+
+ ) + ) + )} + {hoveredUser && ( +
- ))} - {hoveredUser && ( - - )} + + )}
-
- Total: {issues.length} -
-
- -
- {currentPage} -
- { - - currentPage -
{currentPage + 1}
-
......
- - } - { - - !(currentPage==totalPages) &&
{totalPages}
- } - -
-
setCurrentPage(totalPages)} className={`cursor-pointer max-md:text-center ${theme ? "" : "text-white"}`}> - Go {"->"} -
-
+
+ Total: {issues.length} +
+
+ +
+ {currentPage} +
+ {currentPage < totalPages - 1 && ( + <> +
{currentPage + 1}
+
......
+ + )} + {!(currentPage == totalPages) &&
{totalPages}
} + +
+
setCurrentPage(totalPages)} + className={`cursor-pointer max-md:text-center ${ + theme ? "" : "text-white" + }`} + > + Go {"->"} +
+
-
+
Ask Question{" "}
@@ -845,9 +1123,11 @@ className="flex items-center gap-4"> theme ? "" : "text-[#c4bbbb]" }`} > - {mostHelpful.slice(0,mostHelpful.length>=4?4:mostHelpful.length).map((user, index) => ( - - ))} + {mostHelpful + .slice(0, mostHelpful.length >= 4 ? 4 : mostHelpful.length) + .map((user, index) => ( + + ))}
@@ -857,16 +1137,18 @@ className="flex items-center gap-4"> theme ? "" : "text-[#c4bbbb]" }`} > - {top.slice(0,6).map((issue, index) => ( + {top.slice(0, 6).map((issue, index) => ( ))} - - {top.length<6&&devopsIssues.map((issue, index) => { - if(index<6-top.length){ - - return - } -})} + + {top.length < 6 && + devopsIssues.map((issue, index) => { + if (index < 6 - top.length) { + return ( + + ); + } + })}
@@ -896,7 +1178,7 @@ className="flex items-center gap-4"> theme ? "" : "text-white" } flex flex-wrap mt-5 gap-4 cursor-pointer`} > - {sortedArray.slice(0,4).map((item, index) => ( + {sortedArray.slice(0, 4).map((item, index) => (
-