diff --git a/src/__tests__/services-fetch.test.tsx b/src/__tests__/services-fetch.test.tsx new file mode 100644 index 0000000..74a8572 --- /dev/null +++ b/src/__tests__/services-fetch.test.tsx @@ -0,0 +1,118 @@ +import { render, screen, waitFor } from "@testing-library/react"; +import { describe, it, expect, vi, afterEach } from "vitest"; +import { deleteCookie, setCookie } from "cookies-next"; +import Services from "@/app/(routes)/(website)/components/services/services"; + +const dict = { + website: { homePage: { services: { title: "S", description: "D" } } }, +}; + +const requestedUrls: string[] = []; + +const stubFetch = (impl: (url: string) => Promise) => { + vi.stubGlobal( + "fetch", + vi.fn((url: string) => { + requestedUrls.push(url); + return impl(url); + }), + ); +}; + +afterEach(() => { + deleteCookie("selectedLocale"); + deleteCookie("defaultLocale"); + requestedUrls.length = 0; + vi.unstubAllGlobals(); +}); + +describe("Services locale resolution", () => { + it("falls back to en when no locale cookie exists", async () => { + stubFetch(async () => ({ ok: true, json: async () => [] })); + + render(); + + await waitFor(() => expect(requestedUrls).toHaveLength(1)); + expect(requestedUrls[0]).toBe("/api/website/services/en"); + }); + + it("requests the explicitly selected locale", async () => { + setCookie("selectedLocale", "fa"); + stubFetch(async () => ({ ok: true, json: async () => [] })); + + render(); + + await waitFor(() => expect(requestedUrls).toHaveLength(1)); + expect(requestedUrls[0]).toBe("/api/website/services/fa"); + }); + + it("falls back to the default locale cookie", async () => { + setCookie("defaultLocale", "fa"); + stubFetch(async () => ({ ok: true, json: async () => [] })); + + render(); + + await waitFor(() => expect(requestedUrls).toHaveLength(1)); + expect(requestedUrls[0]).toBe("/api/website/services/fa"); + }); + + it("never forwards an unsupported cookie value to the API", async () => { + setCookie("selectedLocale", "de"); + stubFetch(async () => ({ ok: true, json: async () => [] })); + + render(); + + await waitFor(() => expect(requestedUrls).toHaveLength(1)); + expect(requestedUrls[0]).toBe("/api/website/services/en"); + }); +}); + +describe("Services failure handling", () => { + it("renders the empty state when the request throws", async () => { + stubFetch(async () => { + throw new TypeError("network down"); + }); + + render(); + + expect(await screen.findByText("No services found")).toBeInTheDocument(); + }); + + it("renders the empty state on a non-2xx response", async () => { + stubFetch(async () => ({ ok: false, status: 500 })); + + render(); + + expect(await screen.findByText("No services found")).toBeInTheDocument(); + }); + + it("renders the empty state on a non-array payload", async () => { + stubFetch(async () => ({ + ok: true, + json: async () => ({ message: "unauthorized" }), + })); + + render(); + + expect(await screen.findByText("No services found")).toBeInTheDocument(); + }); + + it("renders the service list on success", async () => { + stubFetch(async () => ({ + ok: true, + json: async () => [ + { + id: 1, + title: "Next.js", + description: "Server components", + imageSrc: "/images/logo.svg", + altText: "Next.js logo", + }, + ], + })); + + render(); + + expect(await screen.findByText("Next.js")).toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/__tests__/setup.ts b/src/__tests__/setup.ts index 7b0828b..e7b4e68 100644 --- a/src/__tests__/setup.ts +++ b/src/__tests__/setup.ts @@ -1 +1,77 @@ import '@testing-library/jest-dom'; + +/** + * jsdom does not implement `IntersectionObserver`, which framer-motion's + * `whileInView` / `viewport` animations require at mount time. Without it every + * component test blows up with `ReferenceError: IntersectionObserver is not + * defined` before a single assertion runs. + * + * The stub below reports every observed element as immediately intersecting, so + * in-view content settles in its visible end state instead of staying at the + * `initial` opacity. No assertion is relaxed by this: it only supplies a browser + * API that jsdom is missing. + */ +class IntersectionObserverStub implements IntersectionObserver { + readonly root: Element | Document | null; + readonly rootMargin: string; + readonly thresholds: ReadonlyArray; + + private readonly callback: IntersectionObserverCallback; + private readonly targets = new Set(); + + constructor( + callback: IntersectionObserverCallback, + options: IntersectionObserverInit = {}, + ) { + this.callback = callback; + this.root = options.root ?? null; + this.rootMargin = options.rootMargin ?? '0px'; + this.thresholds = Array.isArray(options.threshold) + ? options.threshold + : [options.threshold ?? 0]; + } + + private static createEntry(target: Element): IntersectionObserverEntry { + const rect = { + x: 0, + y: 0, + top: 0, + left: 0, + right: 0, + bottom: 0, + width: 0, + height: 0, + toJSON: () => ({}), + } as DOMRectReadOnly; + + return { + boundingClientRect: rect, + intersectionRect: rect, + rootBounds: rect, + isIntersecting: true, + intersectionRatio: 1, + target, + time: 0, + } as IntersectionObserverEntry; + } + + observe(target: Element): void { + this.targets.add(target); + this.callback([IntersectionObserverStub.createEntry(target)], this); + } + + unobserve(target: Element): void { + this.targets.delete(target); + } + + disconnect(): void { + this.targets.clear(); + } + + takeRecords(): IntersectionObserverEntry[] { + return []; + } +} + +globalThis.IntersectionObserver = + IntersectionObserverStub as unknown as typeof IntersectionObserver; \ No newline at end of file diff --git a/src/app/(routes)/(website)/[...notFound]/page.tsx b/src/app/(routes)/(website)/[...notFound]/page.tsx index 8e58ef4..a4c5db4 100644 --- a/src/app/(routes)/(website)/[...notFound]/page.tsx +++ b/src/app/(routes)/(website)/[...notFound]/page.tsx @@ -1,6 +1,10 @@ import Image from "next/image"; import Link from "next/link"; +import { pickStableIndex } from "@/app/lib/functions/client-utils"; + +const NOT_FOUND_ILLUSTRATIONS = 5; + interface PropsType { params: Promise<{ notFound: string[]; @@ -9,7 +13,8 @@ interface PropsType { export default async function NotFound(props: PropsType) { const params = await props.params; - const imageUrl = `/images/404/${Math.floor(Math.random() * 5) + 1}.jpg`; + const requestedPath = params.notFound.join("/"); + const imageUrl = `/images/404/${pickStableIndex(requestedPath, NOT_FOUND_ILLUSTRATIONS) + 1}.jpg`; return (
@@ -18,7 +23,7 @@ export default async function NotFound(props: PropsType) {

Could not find{" "} - /blog/{params.notFound.join("/")} + /blog/{requestedPath} {" "} !

diff --git a/src/app/(routes)/(website)/components/header/header.tsx b/src/app/(routes)/(website)/components/header/header.tsx index 1eb0c91..c235ba9 100644 --- a/src/app/(routes)/(website)/components/header/header.tsx +++ b/src/app/(routes)/(website)/components/header/header.tsx @@ -7,9 +7,10 @@ import SelectLanguage from "../selectLanguage/selectLanguage"; import { ThemeToggle } from "../theme-toggle/theme-toggle"; import { getCookie } from "cookies-next"; import { getDictionary } from "@/app/lib/functions/dictionaries"; +import { Dictionary } from "@/app/types/types"; export default function Header() { - const [dict, setDict] = useState(null); + const [dict, setDict] = useState(null); const [scrolled, setScrolled] = useState(false); const selectedLocale = getCookie("selectedLocale") || getCookie("defaultLocale") || "en"; diff --git a/src/app/(routes)/(website)/components/hero/hero.tsx b/src/app/(routes)/(website)/components/hero/hero.tsx index 81034d1..e990860 100644 --- a/src/app/(routes)/(website)/components/hero/hero.tsx +++ b/src/app/(routes)/(website)/components/hero/hero.tsx @@ -3,8 +3,10 @@ import Image from "next/image"; import { motion } from "framer-motion"; +import { Dictionary } from "@/app/types/types"; + interface HeroProps { - dict: any; + dict: Dictionary; } export default function Hero({ dict }: HeroProps) { diff --git a/src/app/(routes)/(website)/components/mobile-menu/mobileMenu.tsx b/src/app/(routes)/(website)/components/mobile-menu/mobileMenu.tsx index dcbed86..42fa60c 100644 --- a/src/app/(routes)/(website)/components/mobile-menu/mobileMenu.tsx +++ b/src/app/(routes)/(website)/components/mobile-menu/mobileMenu.tsx @@ -1,9 +1,12 @@ -import { useEffect, useState } from "react"; -import { getCookie, setCookie } from "cookies-next"; import { useRouter } from "next/navigation"; import { Dictionary } from "@/app/types/types"; import Link from "next/link"; +import { + setSelectedLocale, + useSelectedLocale, +} from "@/app/lib/hooks/use-selected-locale"; + type propsType = { clicked: boolean; setClicked: React.Dispatch>; @@ -12,24 +15,33 @@ type propsType = { export default function MobileMenu({ clicked, setClicked, dict }: propsType) { const router = useRouter(); - const [selectedLocale, setSelectedLocale] = useState("en"); + const selectedLocale = useSelectedLocale(); - useEffect(() => { - const locale = getCookie("selectedLocale") as string | null; + const handleLocaleChange = (locale: "fa" | "en") => { setSelectedLocale(locale); - }, [clicked]); - - const handleLocaleChange = (locale: string) => { - setCookie("selectedLocale", locale); router.refresh(); setClicked(false); }; + const closeMenu = () => setClicked(false); + + const navClassName = + "block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"; + + const navLinks = [ + { href: "/#home", label: dict.website.homePage.nav.home }, + { href: "/#about-me", label: dict.website.homePage.nav.aboutMe }, + { href: "/#services", label: dict.website.homePage.nav.services }, + { href: "/#projects", label: dict.website.homePage.nav.projects }, + { href: "/#testimonials", label: dict.website.homePage.nav.testimonials }, + { href: "/#contact", label: dict.website.homePage.nav.contact }, + ]; + return (
setClicked(false)} + onClick={closeMenu} >
- {selectedLocale === "fa" ? ( - { - e.preventDefault(); - handleLocaleChange("en"); - }} - > - English - - ) : ( - { - e.preventDefault(); - handleLocaleChange("fa"); - }} - > - فارسی - - )} + { + e.preventDefault(); + handleLocaleChange(selectedLocale === "fa" ? "en" : "fa"); + }} + > + {selectedLocale === "fa" ? "English" : "فارسی"} +
); -} +} \ No newline at end of file diff --git a/src/app/(routes)/(website)/components/projects/projects.tsx b/src/app/(routes)/(website)/components/projects/projects.tsx index f2cdb79..f0f124e 100644 --- a/src/app/(routes)/(website)/components/projects/projects.tsx +++ b/src/app/(routes)/(website)/components/projects/projects.tsx @@ -6,7 +6,6 @@ import { ProjectCategory, ProjectResponse, } from "@/app/types/types"; -import { getCookie } from "cookies-next"; import React, { useEffect, useState, useMemo, useCallback } from "react"; import Skeleton from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; @@ -14,7 +13,7 @@ import { motion, AnimatePresence } from "framer-motion"; import Image from "next/image"; import { X, ChevronLeft, ChevronRight } from "lucide-react"; -import { toPersianDigits, getCleanImgSrc } from "@/app/lib/functions/client-utils"; +import { toPersianDigits, getCleanImgSrc, resolveLocale } from "@/app/lib/functions/client-utils"; interface MyProjectsProps { dict: { @@ -35,16 +34,15 @@ const MAX_CATEGORIES = 5; export default function Projects({ dict }: MyProjectsProps) { const [categories, setCategories] = useState([]); const [projects, setProjects] = useState([]); - const [selectedCategory, setSelectedCategory] = useState(""); + const [selectedCategory, setSelectedCategory] = useState(null); const [loading, setLoading] = useState(true); const [selectedProject, setSelectedProject] = useState(null); - const locale = (getCookie("selectedLocale") || getCookie("defaultLocale") || "en") as string; + const locale = resolveLocale(); const isRTL = locale === "fa"; - useEffect(() => { - const initialCategory = locale === "fa" ? "جدیدترین‌ها" : "Newest"; - setSelectedCategory(initialCategory); + const newestLabel = locale === "fa" ? "جدیدترین‌ها" : "Newest"; + useEffect(() => { const fetchProjects = async () => { setLoading(true); try { @@ -60,7 +58,7 @@ export default function Projects({ dict }: MyProjectsProps) { const uniqueCategories: ProjectCategory[] = [ { - label: initialCategory, + label: newestLabel, active: true, }, ...resCategories @@ -79,7 +77,17 @@ export default function Projects({ dict }: MyProjectsProps) { }; fetchProjects(); - }, [locale]); + }, [locale, newestLabel]); + + /** + * The selection is derived rather than reset from an effect: whenever the + * categories list is rebuilt (locale switch, refetch) a selection that is no + * longer present falls back to the first category, which is always "newest". + */ + const activeCategory = + selectedCategory && categories.some((c) => c.label === selectedCategory) + ? selectedCategory + : (categories[0]?.label ?? ""); const groupedProjects = useMemo( () => projects.reduce>((acc, project) => { @@ -94,12 +102,11 @@ export default function Projects({ dict }: MyProjectsProps) { ); const filteredProjects: Project[] = useMemo(() => { - const newestLabel = locale === "fa" ? "جدیدترین‌ها" : "Newest"; - if (selectedCategory === newestLabel) { + if (activeCategory === newestLabel) { return projects.slice(0, MAX_PROJECTS); } - return groupedProjects[selectedCategory]?.slice(0, MAX_PROJECTS) || []; - }, [selectedCategory, projects, groupedProjects, locale]); + return groupedProjects[activeCategory]?.slice(0, MAX_PROJECTS) || []; + }, [activeCategory, projects, groupedProjects, newestLabel]); const currentModalIndex = useMemo( () => filteredProjects.findIndex((p) => p.id === selectedProject?.id), @@ -170,8 +177,9 @@ export default function Projects({ dict }: MyProjectsProps) { whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} onClick={() => setSelectedCategory(category.label)} + aria-pressed={category.label === activeCategory} className={`px-5 py-2 rounded-full text-sm font-medium transition-all duration-300 ${ - selectedCategory === category.label + category.label === activeCategory ? "bg-primary text-primary-foreground shadow-lg shadow-primary/30" : "bg-muted text-muted-foreground hover:bg-muted-foreground/20" }`} diff --git a/src/app/(routes)/(website)/components/selectLanguage/selectLanguage.tsx b/src/app/(routes)/(website)/components/selectLanguage/selectLanguage.tsx index 48390f2..a554e6a 100644 --- a/src/app/(routes)/(website)/components/selectLanguage/selectLanguage.tsx +++ b/src/app/(routes)/(website)/components/selectLanguage/selectLanguage.tsx @@ -1,20 +1,27 @@ "use client"; -import { getCookie, setCookie } from "cookies-next"; import { useRouter } from "next/navigation"; -import { useState, useEffect } from "react"; +import { useState } from "react"; import Link from "next/link"; +import { + setSelectedLocale, + useSelectedLocale, +} from "@/app/lib/hooks/use-selected-locale"; + export default function SelectLanguage() { const router = useRouter(); const [isOpen, setisOpen] = useState(false); - const [currentLocale, setCurrentLocale] = useState(""); + const currentLocale = useSelectedLocale(); - useEffect(() => { - const sl = getCookie("selectedLocale"); - const dl = getCookie("defaultLocale"); - setCurrentLocale(sl || dl || "en"); - }, []); + const changeLocale = (locale: "fa" | "en") => { + setSelectedLocale(locale); + router.refresh(); + setisOpen(false); + }; + + const optionClassName = + "w-[70%] border-b-2 border-[rgba(0,0,0,0)] dark:text-white text-black pb-1 text-center hover:cursor-pointer hover:border-[#FD6F00] dark:hover:text-[#FD6F00]"; return (
@@ -30,22 +37,20 @@ export default function SelectLanguage() { > { e.preventDefault(); - setCookie("selectedLocale", "fa"), router.refresh(); - setisOpen(false); + changeLocale("fa"); }} > فارسی { e.preventDefault(); - setCookie("selectedLocale", "en"), router.refresh(); - setisOpen(false); + changeLocale("en"); }} > English @@ -53,4 +58,4 @@ export default function SelectLanguage() {
); -} +} \ No newline at end of file diff --git a/src/app/(routes)/(website)/components/services/services.tsx b/src/app/(routes)/(website)/components/services/services.tsx index 30d4038..9e1270a 100644 --- a/src/app/(routes)/(website)/components/services/services.tsx +++ b/src/app/(routes)/(website)/components/services/services.tsx @@ -1,12 +1,12 @@ "use client"; import { Service } from "@/app/types/types"; -import { getCookie } from "cookies-next"; import { useEffect, useState } from "react"; import Skeleton from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; import { motion } from "framer-motion"; -import Image from "next/image"; + +import { resolveLocale } from "@/app/lib/functions/client-utils"; interface ServicesProps { dict: { @@ -24,66 +24,93 @@ interface ServicesProps { export default function Services({ dict }: ServicesProps) { const [services, setServices] = useState([]); const [loading, setLoading] = useState(true); + const locale = resolveLocale(); useEffect(() => { - const fetchServices = async () => { - setLoading(true); - const response = await fetch( - `/api/website/services/${getCookie("selectedLocale") !== undefined ? getCookie("selectedLocale") : getCookie("defaultLocale")}`, - ).then((res) => res.json()); + let cancelled = false; - setServices(response); - setLoading(false); + const fetchServices = async () => { + setLoading(true); + + try { + const response = await fetch(`/api/website/services/${locale}`); + + if (!response.ok) { + throw new Error(`Services request failed: ${response.status}`); + } + + const data: unknown = await response.json(); + + if (!cancelled) { + setServices(Array.isArray(data) ? (data as Service[]) : []); + } + } catch { + // A failed or malformed response must degrade to the empty state + // instead of propagating an unhandled rejection out of the effect. + if (!cancelled) { + setServices([]); + } + } finally { + if (!cancelled) { + setLoading(false); + } + } }; fetchServices(); - }, [getCookie("selectedLocale")]); - const renderServiceCard = (service?: Service, index?: number) => ( + return () => { + cancelled = true; + }; + }, [locale]); + + const renderServiceCard = (service: Service | null, index: number) => (
- {loading ? ( + {loading || !service ? ( ) : ( - {service!.altText} )}

- {loading ? ( + {loading || !service ? ( ) : ( - service!.title + service.title )}

- {loading ? ( + {loading || !service ? ( ) : ( - service!.description + service.description )}

); + const isEmpty = !loading && services.length === 0; + return (
- {dict.website.homePage.services.title} - {loading ? Array.from({ length: 3 }).map((_, index) => - renderServiceCard(undefined, index), + renderServiceCard(null, index), ) - : services.map((service, index) => renderServiceCard(service, index))} + : isEmpty + ? null + : services.map((service, index) => renderServiceCard(service, index))}
+ + {isEmpty && ( +
+
+ + + +
+

+ {locale === "fa" ? "خدمتی یافت نشد" : "No services found"} +

+

+ {locale === "fa" + ? "در حال حاضر خدمتی برای نمایش وجود ندارد. لطفاً بعداً دوباره تلاش کنید." + : "No services to show right now. Please try again later."} +

+
+ )}
); -} +} \ No newline at end of file diff --git a/src/app/(routes)/(website)/components/testimonials/testimonials.tsx b/src/app/(routes)/(website)/components/testimonials/testimonials.tsx index 886a10f..fb44e59 100644 --- a/src/app/(routes)/(website)/components/testimonials/testimonials.tsx +++ b/src/app/(routes)/(website)/components/testimonials/testimonials.tsx @@ -1,12 +1,10 @@ "use client"; -import React, { useState, useRef, useEffect } from "react"; +import React, { useState, useRef } from "react"; import { motion } from "framer-motion"; import { Quote, ChevronLeft, ChevronRight } from "lucide-react"; import Image from "next/image"; -import { getCookie } from "cookies-next"; - -import { getCleanImgSrc } from "@/app/lib/functions/client-utils"; +import { getCleanImgSrc, resolveLocale } from "@/app/lib/functions/client-utils"; interface TestimonialData { name: string; @@ -35,7 +33,7 @@ export default function Testimonials({ dict }: TestimonialsProps) { const [currentIndex, setCurrentIndex] = useState(0); const scrollRef = useRef(null); - const locale = getCookie("selectedLocale") || getCookie("defaultLocale") || "en"; + const locale = resolveLocale(); const isRTL = locale === "fa"; const tData = dict.website.homePage.testimonials.data || []; const maxIndex = Math.max(0, tData.length - 3); @@ -100,7 +98,7 @@ export default function Testimonials({ dict }: TestimonialsProps) {

- "{testimonial.quote}" + “{testimonial.quote}”

diff --git a/src/app/(routes)/(website)/components/theme-toggle/theme-toggle.tsx b/src/app/(routes)/(website)/components/theme-toggle/theme-toggle.tsx index 613bd3d..db4da0f 100644 --- a/src/app/(routes)/(website)/components/theme-toggle/theme-toggle.tsx +++ b/src/app/(routes)/(website)/components/theme-toggle/theme-toggle.tsx @@ -5,13 +5,22 @@ import { Moon, Sun } from "lucide-react"; import { useTheme } from "next-themes"; import { motion } from "framer-motion"; +// The snapshot flips from "server" to "client" exactly once, so the store never +// emits a change and the subscription is a no-op. +const subscribeToHydration = () => () => {}; +const getHydratedSnapshot = () => true; +const getServerSnapshot = () => false; + export function ThemeToggle() { const { theme, setTheme } = useTheme(); - const [mounted, setMounted] = React.useState(false); - - React.useEffect(() => { - setMounted(true); - }, []); + // next-themes cannot know the resolved theme on the server, so the real button + // is only swapped in after hydration. `useSyncExternalStore` reports that + // without the extra render pass an effect-based `mounted` flag caused. + const mounted = React.useSyncExternalStore( + subscribeToHydration, + getHydratedSnapshot, + getServerSnapshot, + ); if (!mounted) { return
; diff --git a/src/app/(routes)/(website)/layout.tsx b/src/app/(routes)/(website)/layout.tsx index d641b6c..126440f 100644 --- a/src/app/(routes)/(website)/layout.tsx +++ b/src/app/(routes)/(website)/layout.tsx @@ -1,4 +1,5 @@ import type { Metadata } from "next"; +import Link from "next/link"; import Header from "./components/header/header"; import Footer from "./components/footer/footer"; import NextTopLoader from "nextjs-toploader"; @@ -158,7 +159,7 @@ export default function RootLayout({
{children}
- - +
diff --git a/src/app/(routes)/blog/[...notFound]/page.tsx b/src/app/(routes)/blog/[...notFound]/page.tsx index 96009c0..53f6b0b 100644 --- a/src/app/(routes)/blog/[...notFound]/page.tsx +++ b/src/app/(routes)/blog/[...notFound]/page.tsx @@ -1,6 +1,10 @@ import Image from "next/image"; import Link from "next/link"; +import { pickStableIndex } from "@/app/lib/functions/client-utils"; + +const NOT_FOUND_ILLUSTRATIONS = 5; + interface PropsType { params: Promise<{ notFound: string[]; @@ -9,7 +13,8 @@ interface PropsType { export default async function NotFound(props: PropsType) { const params = await props.params; - const imageUrl = `/images/404/${Math.floor(Math.random() * 5) + 1}.jpg`; + const requestedPath = params.notFound.join("/"); + const imageUrl = `/images/404/${pickStableIndex(requestedPath, NOT_FOUND_ILLUSTRATIONS) + 1}.jpg`; return (
@@ -24,7 +29,7 @@ export default async function NotFound(props: PropsType) {

Could not find{" "} - /blog/{params.notFound.join("/")} + /blog/{requestedPath} {" "} !

diff --git a/src/app/(routes)/blog/categories/[categorySlug]/page.tsx b/src/app/(routes)/blog/categories/[categorySlug]/page.tsx index 071c430..c8e63fd 100644 --- a/src/app/(routes)/blog/categories/[categorySlug]/page.tsx +++ b/src/app/(routes)/blog/categories/[categorySlug]/page.tsx @@ -146,7 +146,7 @@ export default async function SingleCategory(props: categorySlugPropsType) {
)) ) : ( - + )}
{categoryData.posts.length > 0 && categoryData.meta.last_page > 1 && ( diff --git a/src/app/(routes)/blog/categories/page.tsx b/src/app/(routes)/blog/categories/page.tsx index e4854e9..0c67ff5 100644 --- a/src/app/(routes)/blog/categories/page.tsx +++ b/src/app/(routes)/blog/categories/page.tsx @@ -98,7 +98,7 @@ export default async function Categories(props: categoryPropsType) { )) ) : ( - + )} {CategoriesData.data.length > 0 && diff --git a/src/app/(routes)/blog/components/mobile-menu/mobileMenu.tsx b/src/app/(routes)/blog/components/mobile-menu/mobileMenu.tsx index dff878b..fcfcaf1 100644 --- a/src/app/(routes)/blog/components/mobile-menu/mobileMenu.tsx +++ b/src/app/(routes)/blog/components/mobile-menu/mobileMenu.tsx @@ -1,8 +1,11 @@ -import { getCookie, setCookie } from "cookies-next"; import Image from "next/image"; import Link from "next/link"; import { usePathname, useRouter } from "next/navigation"; -import { useEffect, useState } from "react"; + +import { + setSelectedLocale, + useSelectedLocale, +} from "@/app/lib/hooks/use-selected-locale"; type propsType = { clicked: boolean; @@ -11,14 +14,10 @@ type propsType = { export default function MobileMenu({ clicked, setClicked }: propsType) { const pathname = usePathname(); const router = useRouter(); - const [selectedLocale, setSelectedLocale] = useState("en"); - useEffect(() => { - const locale = getCookie("selectedLocale") as string | null; - setSelectedLocale(locale); - }, [clicked]); + const selectedLocale = useSelectedLocale(); - const handleLocaleChange = (locale: string) => { - setCookie("selectedLocale", locale); + const handleLocaleChange = (locale: "fa" | "en") => { + setSelectedLocale(locale); router.refresh(); setClicked(false); }; @@ -80,29 +79,16 @@ export default function MobileMenu({ clicked, setClicked }: propsType) { Categories - {selectedLocale === "fa" ? ( - { - e.preventDefault(); - handleLocaleChange("en"); - }} - > - English - - ) : ( - { - e.preventDefault(); - handleLocaleChange("fa"); - }} - > - فارسی - - )} + { + e.preventDefault(); + handleLocaleChange(selectedLocale === "fa" ? "en" : "fa"); + }} + > + {selectedLocale === "fa" ? "English" : "فارسی"} + diff --git a/src/app/(routes)/blog/components/no-data-founded/noDataFounded.tsx b/src/app/(routes)/blog/components/no-data-founded/noDataFounded.tsx index ecdeae4..460891e 100644 --- a/src/app/(routes)/blog/components/no-data-founded/noDataFounded.tsx +++ b/src/app/(routes)/blog/components/no-data-founded/noDataFounded.tsx @@ -1,7 +1,19 @@ import Image from "next/image"; -export default function NoDataFounded() { - const imageUrl = `/images/no-data-founded/${Math.floor(Math.random() * 6) + 1}.jpg`; +import { pickStableIndex } from "@/app/lib/functions/client-utils"; + +const NO_DATA_ILLUSTRATIONS = 6; + +/** Keeps a fixed pick when no caller supplies a seed. */ +const DEFAULT_SEED = "no-data-founded"; + +interface PropsType { + /** Any stable string identifying the empty list, e.g. a category slug. */ + seed?: string; +} + +export default function NoDataFounded({ seed = DEFAULT_SEED }: PropsType) { + const imageUrl = `/images/no-data-founded/${pickStableIndex(seed, NO_DATA_ILLUSTRATIONS) + 1}.jpg`; return (
@@ -15,4 +27,4 @@ export default function NoDataFounded() {

No Data founded!

); -} +} \ No newline at end of file diff --git a/src/app/(routes)/blog/components/selectLanguage/selectLanguage.tsx b/src/app/(routes)/blog/components/selectLanguage/selectLanguage.tsx index 21a024b..d4535c8 100644 --- a/src/app/(routes)/blog/components/selectLanguage/selectLanguage.tsx +++ b/src/app/(routes)/blog/components/selectLanguage/selectLanguage.tsx @@ -1,10 +1,11 @@ "use client"; -import { setCookie } from "cookies-next"; import { LocaleCookieType } from "@/app/types/types"; import { useRouter } from "next/navigation"; import { useState } from "react"; +import { setSelectedLocale } from "@/app/lib/hooks/use-selected-locale"; + interface SelectLanguageProps { selectedLocale: LocaleCookieType | undefined; defaultLocale: LocaleCookieType | undefined; @@ -19,6 +20,12 @@ export default function SelectLanguage({ const router = useRouter(); const [isOpen, setisOpen] = useState(false); + const changeLocale = (locale: "fa" | "en") => { + setSelectedLocale(locale); + router.refresh(); + setisOpen(false); + }; + return (
{selectedLocale ? ( @@ -42,19 +49,13 @@ export default function SelectLanguage({ >
  • { - setCookie("selectedLocale", "fa"), router.refresh(); - setisOpen(false); - }} + onClick={() => changeLocale("fa")} > فارسی
  • { - setCookie("selectedLocale", "en"), router.refresh(); - setisOpen(false); - }} + onClick={() => changeLocale("en")} > English
  • diff --git a/src/app/(routes)/blog/filtered-posts/[filter]/page.tsx b/src/app/(routes)/blog/filtered-posts/[filter]/page.tsx index 4a48221..46e1dd8 100644 --- a/src/app/(routes)/blog/filtered-posts/[filter]/page.tsx +++ b/src/app/(routes)/blog/filtered-posts/[filter]/page.tsx @@ -11,65 +11,79 @@ import { Metadata } from "next"; import { getDictionary } from "@/app/lib/functions/dictionaries"; import { getDefaultLocale } from "@/app/lib/functions/utils"; -export const metadata: Metadata = { - title: "", - description: "", - openGraph: { - title: "", - description: "", - images: [ - `${process.env.NEXT_PUBLIC_FRONT_URL}/og-image?text=filtered posts`, - ], +type FilterKey = "new" | "popular"; + +type FilterConfig = { + apiUrl: string; + title: string; + description: string; +}; + +/** + * The original implementation exported a single module-level `metadata` object + * and rewrote its fields from inside the page component. That object is shared by + * every request handled by the server process, so the last render to finish won: + * two concurrent (or interleaved) visits to `/blog/filtered-posts/new` and + * `/blog/filtered-posts/popular` could serve each other's title, description and + * OG image. Each filter now owns its config, and `generateMetadata` builds a + * fresh object per request instead of mutating shared state. + */ +const FILTERS: Record = { + new: { + apiUrl: "/posts?sort_field=published_at&sort_direction=desc", + title: "All New Posts List", + description: + "New Browse through our collection of categories to find posts on your favorite topics. Whether you`re looking for insightful articles, how-tos, or the latest trends, our categories make it easy to discover content tailored to your interests.", + }, + popular: { + apiUrl: "/posts?sort_field=views&sort_direction=desc", + title: "All Popular Posts List", + description: + "Popular Browse through our collection of categories to find posts on your favorite topics. Whether you`re looking for insightful articles, how-tos, or the latest trends, our categories make it easy to discover content tailored to your interests.", }, }; +const normalizeFilter = (filter: string) => + filter.replaceAll(/%20|-|_/g, " ").toLowerCase(); + +/** Unknown filters stay `null` so they keep rendering the empty state. */ +const getFilterKey = (filter: string): FilterKey | null => { + const normalized = normalizeFilter(filter); + + return normalized in FILTERS ? (normalized as FilterKey) : null; +}; + +const ogImage = (text: string) => + `${process.env.NEXT_PUBLIC_FRONT_URL}/og-image?text=${encodeURIComponent(text)}`; + +export async function generateMetadata( + props: FilteredPostsPagepropsType, +): Promise { + const params = await props.params; + const filterKey = getFilterKey(params.filter); + const { title, description } = filterKey + ? FILTERS[filterKey] + : { title: "", description: "" }; + + return { + title, + description, + openGraph: { + title, + description, + images: [ogImage(title || "filtered posts")], + }, + }; +} + export default async function FilteredPosts(props: FilteredPostsPagepropsType) { const searchParams = await props.searchParams; const params = await props.params; - let filteredPostApiUrl: string; + const filterKey = getFilterKey(params.filter); + const filteredPostApiUrl = filterKey ? FILTERS[filterKey].apiUrl : ""; const dict = await getDictionary(await getDefaultLocale()); - switch (params.filter.replaceAll(/%20|-|_/g, " ").toLowerCase()) { - case "new": - filteredPostApiUrl = "/posts?sort_field=published_at&sort_direction=desc"; - metadata.title = "All New Posts List"; - metadata.description = - "New Browse through our collection of categories to find posts on your favorite topics. Whether you`re looking for insightful articles, how-tos, or the latest trends, our categories make it easy to discover content tailored to your interests."; - metadata.openGraph - ? (metadata.openGraph.title = "All New Posts List") - : ""; - metadata.openGraph - ? (metadata.openGraph.description = - "New Browse through our collection of categories to find posts on your favorite topics. Whether you`re looking for insightful articles, how-tos, or the latest trends, our categories make it easy to discover content tailored to your interests.") - : ""; - metadata.openGraph - ? (metadata.openGraph.images = ["/og-image?text=All New Posts List"]) - : []; - break; - case "popular": - filteredPostApiUrl = "/posts?sort_field=views&sort_direction=desc"; - metadata.title = "All Popular Posts List"; - metadata.description = - "Popular Browse through our collection of categories to find posts on your favorite topics. Whether you`re looking for insightful articles, how-tos, or the latest trends, our categories make it easy to discover content tailored to your interests."; - metadata.openGraph - ? (metadata.openGraph.title = "All Popular Posts List") - : ""; - metadata.openGraph - ? (metadata.openGraph.description = - "Popular Browse through our collection of categories to find posts on your favorite topics. Whether you`re looking for insightful articles, how-tos, or the latest trends, our categories make it easy to discover content tailored to your interests.") - : ""; - metadata.openGraph - ? (metadata.openGraph.images = [ - "/og-image?text=All Popular Posts List", - ]) - : []; - break; - default: - // code block - filteredPostApiUrl = ""; - } - let FilteredPostsData: FilteredPostsDataType; if (filteredPostApiUrl !== "") { @@ -100,18 +114,16 @@ export default async function FilteredPosts(props: FilteredPostsPagepropsType) {

    - {params.filter.replaceAll(/%20|-|_/g, " ").toLowerCase() === "new" + {filterKey === "new" ? dict.blog.filteredPostsPage.newTitle - : params.filter.replaceAll(/%20|-|_/g, " ").toLowerCase() === - "popular" + : filterKey === "popular" ? dict.blog.filteredPostsPage.popularTitle : ""}

    - {params.filter.replaceAll(/%20|-|_/g, " ").toLowerCase() === "new" + {filterKey === "new" ? dict.blog.filteredPostsPage.newDescription - : params.filter.replaceAll(/%20|-|_/g, " ").toLowerCase() === - "popular" + : filterKey === "popular" ? dict.blog.filteredPostsPage.popularDescription : ""}

    @@ -131,10 +143,9 @@ export default async function FilteredPosts(props: FilteredPostsPagepropsType) {
  • - {params.filter.replaceAll(/%20|-|_/g, " ").toLowerCase() === "new" + {filterKey === "new" ? dict.blog.filteredPostsPage.newTitle - : params.filter.replaceAll(/%20|-|_/g, " ").toLowerCase() === - "popular" + : filterKey === "popular" ? dict.blog.filteredPostsPage.popularTitle : ""} @@ -196,14 +207,14 @@ export default async function FilteredPosts(props: FilteredPostsPagepropsType) {

  • )) ) : ( - + )}
    {FilteredPostsData.data.length > 0 && FilteredPostsData.meta.last_page > 1 && ( )} diff --git a/src/app/lib/functions/client-utils.ts b/src/app/lib/functions/client-utils.ts index 834d775..8544ebc 100644 --- a/src/app/lib/functions/client-utils.ts +++ b/src/app/lib/functions/client-utils.ts @@ -1,3 +1,11 @@ +import { getCookie } from "cookies-next"; + +export type Locale = "fa" | "en"; + +const SUPPORTED_LOCALES: readonly Locale[] = ["fa", "en"]; + +export const DEFAULT_LOCALE: Locale = "en"; + export const toPersianDigits = (str: string | number): string => String(str).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[parseInt(d)]); @@ -10,3 +18,42 @@ export const getCleanImgSrc = (src: string): string => { if (src.startsWith('/')) return src; return `/images/projects/${src}`; }; + +/** + * Resolves the active locale from the browser cookies. + * + * `selectedLocale` is the explicit user override, `defaultLocale` is written by + * the proxy on the first request. Either cookie can be missing (or hold a value + * the backend does not know about) before the first navigation completes, so the + * result is always narrowed to a supported locale instead of leaking `undefined` + * into API paths such as `/api/website/services/{locale}`. + */ +export const resolveLocale = (): Locale => { + const candidate = + getCookie("selectedLocale") || getCookie("defaultLocale") || DEFAULT_LOCALE; + + return SUPPORTED_LOCALES.includes(candidate as Locale) + ? (candidate as Locale) + : DEFAULT_LOCALE; +}; + +/** + * Deterministically maps a seed to one of `total` slots. + * + * Illustration pickers used `Math.random()` during render, which is impure: two + * renders of the same URL can return different images, the result cannot be + * cached, and the value cannot be reasoned about. Hashing a stable seed (a route + * param, a category slug) keeps the choice varied while guaranteeing the same + * input always yields the same illustration. + */ +export const pickStableIndex = (seed: string, total: number): number => { + if (total <= 1) return 0; + + let hash = 0; + + for (let index = 0; index < seed.length; index += 1) { + hash = (Math.imul(31, hash) + seed.charCodeAt(index)) | 0; + } + + return Math.abs(hash) % total; +}; diff --git a/src/app/lib/hooks/use-selected-locale.ts b/src/app/lib/hooks/use-selected-locale.ts new file mode 100644 index 0000000..7fb1125 --- /dev/null +++ b/src/app/lib/hooks/use-selected-locale.ts @@ -0,0 +1,46 @@ +"use client"; + +import { setCookie } from "cookies-next"; +import { useSyncExternalStore } from "react"; + +import { resolveLocale, type Locale } from "@/app/lib/functions/client-utils"; + +/** + * `document.cookie` is an external, mutable store: it changes outside of React + * (the proxy writes `defaultLocale`, the language pickers write `selectedLocale`) + * and it is not available while rendering on the server. Reading it during render + * plus syncing it with an effect produced both a cascading render and an SSR + * mismatch, so it is consumed as a store instead. + */ +const LOCALE_CHANGE_EVENT = "parsaaghayi:locale-change"; + +const subscribeToLocale = (onStoreChange: () => void) => { + window.addEventListener(LOCALE_CHANGE_EVENT, onStoreChange); + return () => window.removeEventListener(LOCALE_CHANGE_EVENT, onStoreChange); +}; + +const getLocaleSnapshot = (): Locale | null => + typeof document === "undefined" ? null : resolveLocale(); + +const getServerLocaleSnapshot = (): Locale | null => null; + +/** + * Returns the active locale on the client, or `null` while rendering on the + * server. `resolveLocale` returns a narrowed primitive, so the snapshot is + * referentially stable between calls. + */ +export const useSelectedLocale = (): Locale | null => + useSyncExternalStore( + subscribeToLocale, + getLocaleSnapshot, + getServerLocaleSnapshot, + ); + +/** + * Persists the explicit locale override and notifies `useSelectedLocale` + * subscribers, so every consumer re-reads the cookie without a full reload. + */ +export const setSelectedLocale = (locale: Locale) => { + setCookie("selectedLocale", locale); + window.dispatchEvent(new Event(LOCALE_CHANGE_EVENT)); +}; \ No newline at end of file