Fix the locale bug and the shared-metadata race behind the lint errors
services.tsx fetched /api/website/services/undefined, because the locale
cookie was read with a check that is false for the empty string and then fell
through unguarded. The endpoint is /api/website/services/{locale}. It also
ignored response.ok and assumed a payload shape, so a failing API threw. All
three are covered by a new regression test; the suite was 2 failures before
and passes 10/10 now.
The filtered-posts page rewrote fields of an exported module-level `metadata`
object during render. That object is a singleton shared by every request in the
process, so concurrent visits to different filters could serve each other's
title, description and OG image, and Next reads the export at build time so the
runtime writes were largely discarded anyway. Values now live in an immutable
record and generateMetadata returns a fresh object per request.
Also replaces set-state-in-effect locale reads with a useSyncExternalStore hook
over the cookie store, derives the active project category instead of storing
it in state (so it self-heals when the data or locale changes), makes the
"random" not-found picks stable per path instead of Math.random() during
render, and tightens a few `any` types.
eslint goes from 36 errors to 0, tsc stays clean.
This commit is contained in:
1 parent
80b3be48ea
commit
68b0bf4b91
21 files changed
+615
-270
No files matched your search
@@ -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<unknown>) => {
|
||||
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(<Services dict={dict} />);
|
||||
|
||||
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(<Services dict={dict} />);
|
||||
|
||||
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(<Services dict={dict} />);
|
||||
|
||||
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(<Services dict={dict} />);
|
||||
|
||||
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(<Services dict={dict} />);
|
||||
|
||||
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(<Services dict={dict} />);
|
||||
|
||||
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(<Services dict={dict} />);
|
||||
|
||||
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(<Services dict={dict} />);
|
||||
|
||||
expect(await screen.findByText("Next.js")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -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<number>;
|
||||
|
||||
private readonly callback: IntersectionObserverCallback;
|
||||
private readonly targets = new Set<Element>();
|
||||
|
||||
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;
|
||||
@@ -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 (
|
||||
<div className="mt-[80px] flex flex-col items-center justify-center gap-3">
|
||||
@@ -18,7 +23,7 @@ export default async function NotFound(props: PropsType) {
|
||||
<p className="select-none font-[600]">
|
||||
Could not find{" "}
|
||||
<span className="cursor-pointer font-[800] text-[#fd6f00] underline">
|
||||
/blog/{params.notFound.join("/")}
|
||||
/blog/{requestedPath}
|
||||
</span>{" "}
|
||||
!
|
||||
</p>
|
||||
|
||||
@@ -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<any>(null);
|
||||
const [dict, setDict] = useState<Dictionary | null>(null);
|
||||
const [scrolled, setScrolled] = useState(false);
|
||||
|
||||
const selectedLocale = getCookie("selectedLocale") || getCookie("defaultLocale") || "en";
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<React.SetStateAction<boolean>>;
|
||||
@@ -12,24 +15,33 @@ type propsType = {
|
||||
|
||||
export default function MobileMenu({ clicked, setClicked, dict }: propsType) {
|
||||
const router = useRouter();
|
||||
const [selectedLocale, setSelectedLocale] = useState<string | null>("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 (
|
||||
<div className="flex">
|
||||
<div
|
||||
className={`${clicked ? "fixed end-0" : "end-[-1000px] hidden"} top-0 z-30 flex h-full w-full bg-slate-950 opacity-20 lg:hidden`}
|
||||
onClick={() => setClicked(false)}
|
||||
onClick={closeMenu}
|
||||
></div>
|
||||
<div
|
||||
className={`fixed start-0 top-0 z-40 flex h-full w-[250px] select-none flex-col items-start bg-[#fd6f00] ${clicked ? "start-0" : "start-[-260px]"} mobile-menu lg:start-[-260px]`}
|
||||
@@ -43,90 +55,35 @@ export default function MobileMenu({ clicked, setClicked, dict }: propsType) {
|
||||
</p>
|
||||
</div>
|
||||
<nav className="mt-5 flex w-full flex-col">
|
||||
<a
|
||||
href="/#home"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"
|
||||
onClick={() => setClicked(false)}
|
||||
>
|
||||
{dict.website.homePage.nav.home}
|
||||
</a>
|
||||
<a
|
||||
href="/#about-me"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"
|
||||
onClick={() => {
|
||||
setClicked(false);
|
||||
}}
|
||||
>
|
||||
{dict.website.homePage.nav.aboutMe}
|
||||
</a>
|
||||
<a
|
||||
href="/#services"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"
|
||||
onClick={() => {
|
||||
setClicked(false);
|
||||
}}
|
||||
>
|
||||
{dict.website.homePage.nav.services}
|
||||
</a>
|
||||
<a
|
||||
href="/#projects"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"
|
||||
onClick={() => {
|
||||
setClicked(false);
|
||||
}}
|
||||
>
|
||||
{dict.website.homePage.nav.projects}
|
||||
</a>
|
||||
<a
|
||||
href="/#testimonials"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"
|
||||
onClick={() => {
|
||||
setClicked(false);
|
||||
}}
|
||||
>
|
||||
{dict.website.homePage.nav.testimonials}
|
||||
</a>
|
||||
<a
|
||||
href="/#contact"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"
|
||||
onClick={() => {
|
||||
setClicked(false);
|
||||
}}
|
||||
>
|
||||
{dict.website.homePage.nav.contact}
|
||||
</a>
|
||||
{navLinks.map(({ href, label }) => (
|
||||
<Link
|
||||
key={href}
|
||||
href={href}
|
||||
className={navClassName}
|
||||
onClick={closeMenu}
|
||||
>
|
||||
{label}
|
||||
</Link>
|
||||
))}
|
||||
<Link
|
||||
href="/blog"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"
|
||||
onClick={() => setClicked(false)}
|
||||
className={navClassName}
|
||||
onClick={closeMenu}
|
||||
>
|
||||
{dict.website.homePage.nav.blog}
|
||||
</Link>
|
||||
</nav>
|
||||
{selectedLocale === "fa" ? (
|
||||
<Link
|
||||
href="#"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleLocaleChange("en");
|
||||
}}
|
||||
>
|
||||
English
|
||||
</Link>
|
||||
) : (
|
||||
<Link
|
||||
href="#"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] hover:cursor-pointer hover:bg-slate-100"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleLocaleChange("fa");
|
||||
}}
|
||||
>
|
||||
فارسی
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
href="#"
|
||||
className={navClassName}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleLocaleChange(selectedLocale === "fa" ? "en" : "fa");
|
||||
}}
|
||||
>
|
||||
{selectedLocale === "fa" ? "English" : "فارسی"}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<ProjectCategory[]>([]);
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [selectedCategory, setSelectedCategory] = useState<string>("");
|
||||
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [selectedProject, setSelectedProject] = useState<Project | null>(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<Record<string, Project[]>>((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"
|
||||
}`}
|
||||
|
||||
@@ -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 (
|
||||
<div className="relative flex min-w-[100px] justify-center">
|
||||
@@ -30,22 +37,20 @@ export default function SelectLanguage() {
|
||||
>
|
||||
<Link
|
||||
href=""
|
||||
className="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] font-[var(--font-mikhak)]"
|
||||
className={`${optionClassName} font-[var(--font-mikhak)]`}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setCookie("selectedLocale", "fa"), router.refresh();
|
||||
setisOpen(false);
|
||||
changeLocale("fa");
|
||||
}}
|
||||
>
|
||||
فارسی
|
||||
</Link>
|
||||
<Link
|
||||
href=""
|
||||
className="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] font-sans"
|
||||
className={`${optionClassName} font-sans`}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setCookie("selectedLocale", "en"), router.refresh();
|
||||
setisOpen(false);
|
||||
changeLocale("en");
|
||||
}}
|
||||
>
|
||||
English
|
||||
@@ -53,4 +58,4 @@ export default function SelectLanguage() {
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<Service[]>([]);
|
||||
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) => (
|
||||
<motion.div
|
||||
key={service?.id || index}
|
||||
key={service?.id ?? index}
|
||||
initial={{ opacity: 0, y: 30 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.5, delay: (index || 0) * 0.1 }}
|
||||
transition={{ duration: 0.5, delay: index * 0.1 }}
|
||||
viewport={{ once: true }}
|
||||
whileHover={{ y: -10 }}
|
||||
className="group flex h-full w-full flex-col items-start rounded-3xl glass-panel p-8 transition-all duration-300 hover:border-primary/50"
|
||||
>
|
||||
<div className="mb-6 relative overflow-hidden rounded-2xl w-20 h-20 bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
|
||||
{loading ? (
|
||||
{loading || !service ? (
|
||||
<Skeleton containerClassName="w-12 h-12" />
|
||||
) : (
|
||||
<img
|
||||
src={service!.imageSrc}
|
||||
alt={service!.altText}
|
||||
className="w-12 h-12 object-contain transition-transform duration-300 group-hover:scale-110 dark:brightness-0 dark:invert dark-invert-target"
|
||||
<img
|
||||
src={service.imageSrc}
|
||||
alt={service.altText}
|
||||
className="w-12 h-12 object-contain transition-transform duration-300 group-hover:scale-110 dark:brightness-0 dark:invert dark-invert-target"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<h3 className="mb-4 text-2xl font-bold text-foreground group-hover:text-primary transition-colors">
|
||||
{loading ? (
|
||||
{loading || !service ? (
|
||||
<Skeleton containerClassName="w-full" height={32} />
|
||||
) : (
|
||||
service!.title
|
||||
service.title
|
||||
)}
|
||||
</h3>
|
||||
<p className="text-muted-foreground leading-relaxed text-sm md:text-base">
|
||||
{loading ? (
|
||||
{loading || !service ? (
|
||||
<Skeleton containerClassName="w-full" height={60} />
|
||||
) : (
|
||||
service!.description
|
||||
service.description
|
||||
)}
|
||||
</p>
|
||||
</motion.div>
|
||||
);
|
||||
|
||||
const isEmpty = !loading && services.length === 0;
|
||||
|
||||
return (
|
||||
<section
|
||||
className="relative flex w-full max-w-[1200px] flex-col items-center py-20"
|
||||
id="services"
|
||||
>
|
||||
<div className="text-center mb-16 space-y-4">
|
||||
<motion.h2
|
||||
<motion.h2
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.6 }}
|
||||
@@ -92,7 +119,7 @@ export default function Services({ dict }: ServicesProps) {
|
||||
>
|
||||
{dict.website.homePage.services.title}
|
||||
</motion.h2>
|
||||
<motion.p
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.6, delay: 0.2 }}
|
||||
@@ -106,10 +133,40 @@ export default function Services({ dict }: ServicesProps) {
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 max-w-5xl mx-auto w-full">
|
||||
{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))}
|
||||
</div>
|
||||
|
||||
{isEmpty && (
|
||||
<div className="col-span-full flex flex-col items-center justify-center py-20 text-center">
|
||||
<div className="w-20 h-20 rounded-full bg-muted flex items-center justify-center mb-6">
|
||||
<svg
|
||||
className="w-10 h-10 text-muted-foreground"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.5}
|
||||
d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-xl font-bold text-foreground mb-2">
|
||||
{locale === "fa" ? "خدمتی یافت نشد" : "No services found"}
|
||||
</h3>
|
||||
<p className="text-muted-foreground max-w-md">
|
||||
{locale === "fa"
|
||||
? "در حال حاضر خدمتی برای نمایش وجود ندارد. لطفاً بعداً دوباره تلاش کنید."
|
||||
: "No services to show right now. Please try again later."}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<HTMLDivElement>(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) {
|
||||
|
||||
<div className="flex-grow pt-2">
|
||||
<p className="w-full min-w-0 normal-case whitespace-normal break-words tracking-normal block mb-6 italic text-sm md:text-base text-start px-6 md:px-10 leading-relaxed">
|
||||
"{testimonial.quote}"
|
||||
“{testimonial.quote}”
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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 <div className="w-10 h-10" />;
|
||||
|
||||
@@ -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({
|
||||
<NextTopLoader color="rgb(253 111 0)" showAtBottom={false} />
|
||||
<div className="main flex w-full justify-center">{children}</div>
|
||||
|
||||
<a
|
||||
<Link
|
||||
href="/#here-is-top"
|
||||
className="fixed bottom-8 end-8 z-40 flex h-12 w-12 items-center justify-center rounded-full bg-primary text-white shadow-lg shadow-primary/30 transition-all duration-300 hover:scale-110 hover:shadow-xl hover:shadow-primary/40 active:scale-95"
|
||||
id="back-to-top"
|
||||
@@ -167,7 +168,7 @@ export default function RootLayout({
|
||||
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M5 15l7-7 7 7" />
|
||||
</svg>
|
||||
</a>
|
||||
</Link>
|
||||
|
||||
<Footer />
|
||||
</>
|
||||
|
||||
@@ -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 (
|
||||
<div className="mb-10 flex flex-col items-center justify-center gap-3 sm:mb-0">
|
||||
@@ -24,7 +29,7 @@ export default async function NotFound(props: PropsType) {
|
||||
<p className="select-none font-[600]">
|
||||
Could not find{" "}
|
||||
<span className="cursor-pointer font-[800] text-blog-text-quote underline">
|
||||
/blog/{params.notFound.join("/")}
|
||||
/blog/{requestedPath}
|
||||
</span>{" "}
|
||||
!
|
||||
</p>
|
||||
|
||||
@@ -146,7 +146,7 @@ export default async function SingleCategory(props: categorySlugPropsType) {
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<NoDataFounded />
|
||||
<NoDataFounded seed={params.categorySlug} />
|
||||
)}
|
||||
</div>
|
||||
{categoryData.posts.length > 0 && categoryData.meta.last_page > 1 && (
|
||||
|
||||
@@ -98,7 +98,7 @@ export default async function Categories(props: categoryPropsType) {
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<NoDataFounded />
|
||||
<NoDataFounded seed="all-categories" />
|
||||
)}
|
||||
</div>
|
||||
{CategoriesData.data.length > 0 &&
|
||||
|
||||
@@ -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<string | null>("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
|
||||
</Link>
|
||||
</nav>
|
||||
{selectedLocale === "fa" ? (
|
||||
<Link
|
||||
href="#"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] text-white hover:cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleLocaleChange("en");
|
||||
}}
|
||||
>
|
||||
English
|
||||
</Link>
|
||||
) : (
|
||||
<Link
|
||||
href="#"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] text-white hover:cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleLocaleChange("fa");
|
||||
}}
|
||||
>
|
||||
فارسی
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
href="#"
|
||||
className="block w-full whitespace-nowrap px-[14px] py-[10px] text-[21px] font-[400] text-white hover:cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleLocaleChange(selectedLocale === "fa" ? "en" : "fa");
|
||||
}}
|
||||
>
|
||||
{selectedLocale === "fa" ? "English" : "فارسی"}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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 (
|
||||
<div className="mb-10 flex flex-col items-center justify-center gap-3 sm:mb-0">
|
||||
@@ -15,4 +27,4 @@ export default function NoDataFounded() {
|
||||
<h2 className="text-[30px] font-[800]">No Data founded!</h2>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 (
|
||||
<div className={`relative flex min-w-[100px] justify-center ${className}`}>
|
||||
{selectedLocale ? (
|
||||
@@ -42,19 +49,13 @@ export default function SelectLanguage({
|
||||
>
|
||||
<li
|
||||
className="w-[70%] border-b-2 border-[rgba(0,0,0,0)] pb-1 text-center hover:cursor-pointer hover:border-blog-red"
|
||||
onClick={() => {
|
||||
setCookie("selectedLocale", "fa"), router.refresh();
|
||||
setisOpen(false);
|
||||
}}
|
||||
onClick={() => changeLocale("fa")}
|
||||
>
|
||||
فارسی
|
||||
</li>
|
||||
<li
|
||||
className="w-[70%] border-b-2 border-[rgba(0,0,0,0)] pb-1 text-center hover:cursor-pointer hover:border-blog-red"
|
||||
onClick={() => {
|
||||
setCookie("selectedLocale", "en"), router.refresh();
|
||||
setisOpen(false);
|
||||
}}
|
||||
onClick={() => changeLocale("en")}
|
||||
>
|
||||
English
|
||||
</li>
|
||||
|
||||
@@ -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<FilterKey, FilterConfig> = {
|
||||
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<Metadata> {
|
||||
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) {
|
||||
<div className="my-10 flex w-full max-w-[1280px] flex-wrap justify-center">
|
||||
<div className="flex w-full max-w-[90%] flex-col gap-5">
|
||||
<h1 className="text-[36px] font-[700] capitalize text-blog-text-default">
|
||||
{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
|
||||
: ""}
|
||||
</h1>
|
||||
<p className="text-[18px] font-[600] text-blog-text-default">
|
||||
{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
|
||||
: ""}
|
||||
</p>
|
||||
@@ -131,10 +143,9 @@ export default async function FilteredPosts(props: FilteredPostsPagepropsType) {
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<p className="relative text-[12px] font-[600] capitalize text-blog-text-default">
|
||||
{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) {
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<NoDataFounded />
|
||||
<NoDataFounded seed={normalizeFilter(params.filter)} />
|
||||
)}
|
||||
</div>
|
||||
{FilteredPostsData.data.length > 0 &&
|
||||
FilteredPostsData.meta.last_page > 1 && (
|
||||
<Pagination
|
||||
meta={FilteredPostsData.meta}
|
||||
baseUrl={`/blog/filtered-posts/${params.filter.replaceAll(/%20|-|_/g, " ").toLowerCase()}`}
|
||||
baseUrl={`/blog/filtered-posts/${normalizeFilter(params.filter)}`}
|
||||
dict={dict}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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));
|
||||
};
|
||||
Reference in new issue
Block a user