first project version mrDecor
This commit is contained in:
@@ -0,0 +1,336 @@
|
||||
/**
|
||||
* زیرساخت کشف بلاکهای محتوای بلاگ و تبدیل به JSON.
|
||||
* مرحله ۱: کشف بلاکهای شناختهشده در HTML (collapse, و بعداً blockquote, code, ...)
|
||||
* مرحله ۲: استخراج payload به صورت JSON برای هر بلاک
|
||||
* مرحله ۳: لایه بیرونی بر اساس blockType و payload کامپوننت مناسب را رندر میکند.
|
||||
*
|
||||
* برای افزودن بلاک جدید: یک تعریف در BLOCK_DEFINITIONS اضافه کنید و در رندر blockType را هندل کنید.
|
||||
*/
|
||||
import * as cheerio from "cheerio";
|
||||
import type { Element } from "domhandler";
|
||||
|
||||
// ─── انواع بلاک (برای گسترش بعدی) ───────────────────────────────────────────
|
||||
|
||||
/** نام نوع بلاک؛ با افزودن بلاک جدید این یونیون را گسترش دهید. */
|
||||
export type BlockType = "collapse" | "blockquote" | "pullquote" | "tip" | "code";
|
||||
|
||||
/** Payload بلاک collapse (سوالات متداول / accordion). */
|
||||
export interface CollapseBlockPayload {
|
||||
title: string;
|
||||
items: { question: string; answer: string }[];
|
||||
}
|
||||
|
||||
/** Payload بلاک blockquote (نقلقول و منبع). content به صورت HTML است و باید با dangerouslySetInnerHTML رندر شود. */
|
||||
export interface BlockquoteBlockPayload {
|
||||
/** HTML محتوای نقلقول (بدون تگ cite). */
|
||||
content: string;
|
||||
citation?: string;
|
||||
}
|
||||
|
||||
/** Payload بلاک tip (نکته / اینفو با variant: info, warn, danger). */
|
||||
export interface TipBlockPayload {
|
||||
variant: "info" | "warn" | "danger";
|
||||
/** HTML محتوای داخل بلاک (عنوان + متن). */
|
||||
content: string;
|
||||
}
|
||||
|
||||
/** Payload بلاک code — بعداً پیادهسازی میشود. */
|
||||
// export interface CodeBlockPayload { ... }
|
||||
|
||||
/** یونیون همهٔ payloadها برای تایپامن رندر. */
|
||||
export type BlockPayload =
|
||||
| CollapseBlockPayload
|
||||
| BlockquoteBlockPayload
|
||||
| TipBlockPayload;
|
||||
// | CodeBlockPayload
|
||||
|
||||
// ─── سگمنت خروجی برای لایه رندر ─────────────────────────────────────────────
|
||||
|
||||
/** یک سگمنت HTML خام. */
|
||||
export interface HtmlSegment {
|
||||
type: "html";
|
||||
content: string;
|
||||
}
|
||||
|
||||
/** یک بلاک با نوع و payload (JSON) برای رندر با کامپوننت مناسب. */
|
||||
export interface BlockSegment {
|
||||
type: "block";
|
||||
blockType: BlockType;
|
||||
payload: BlockPayload;
|
||||
}
|
||||
|
||||
/** هر سگمنت محتوا: یا HTML یا یک بلاک با JSON. */
|
||||
export type ContentSegment = HtmlSegment | BlockSegment;
|
||||
|
||||
/** خروجی کشف بلاک: HTML با placeholderها و آرایهٔ سگمنتها (با payload توکار). */
|
||||
export interface DiscoveredContent {
|
||||
/** HTML بعد از جایگزینی بلاکها با placeholder (برای ادامهٔ پردازش مثلاً تزریق id سرنویس). */
|
||||
htmlWithPlaceholders: string;
|
||||
/** سگمنتها به ترتیب برای رندر؛ هر بلاک شامل blockType و payload است. */
|
||||
segments: ContentSegment[];
|
||||
}
|
||||
|
||||
// ─── تعریف بلاکها (ثبت برای کشف و استخراج) ────────────────────────────────
|
||||
|
||||
export interface BlockDefinition<T extends BlockPayload = BlockPayload> {
|
||||
blockType: BlockType;
|
||||
/** سلکتور Cheerio برای پیدا کردن المنت ریشهٔ بلاک. */
|
||||
selector: string;
|
||||
/** استخراج payload (JSON) از المنت. */
|
||||
extract: ($: cheerio.CheerioAPI, el: Element) => T;
|
||||
}
|
||||
|
||||
function extractCollapsePayload(
|
||||
$: cheerio.CheerioAPI,
|
||||
el: Element
|
||||
): CollapseBlockPayload {
|
||||
const $el = $(el);
|
||||
const innerHtml = $el.html() ?? "";
|
||||
const $inner = cheerio.load(innerHtml, null, false);
|
||||
|
||||
const title = $inner("h2").first().text().trim();
|
||||
const items: { question: string; answer: string }[] = [];
|
||||
$inner("ul").each((_: number, ul: Element) => {
|
||||
const question = $inner(ul).find("li strong").first().text().trim();
|
||||
const answer = $inner(ul).nextAll("p").first().text().trim();
|
||||
if (question || answer) items.push({ question, answer });
|
||||
});
|
||||
|
||||
return { title, items };
|
||||
}
|
||||
|
||||
/**
|
||||
* استخراج از بلاک آکاردئون وردپرس (core/accordion):
|
||||
* div.wp-block-accordion > div.wp-block-accordion-item با
|
||||
* .wp-block-accordion-heading__toggle-title (سؤال) و .wp-block-accordion-panel (جواب به صورت HTML).
|
||||
*/
|
||||
function extractAccordionPayload(
|
||||
$: cheerio.CheerioAPI,
|
||||
el: Element
|
||||
): CollapseBlockPayload {
|
||||
const $el = $(el);
|
||||
const items: { question: string; answer: string }[] = [];
|
||||
|
||||
$el.find(".wp-block-accordion-item").each((_: number, itemEl: Element) => {
|
||||
const $item = $(itemEl);
|
||||
const question = $item.find(".wp-block-accordion-heading__toggle-title").first().text().trim();
|
||||
const $panel = $item.find(".wp-block-accordion-panel").first();
|
||||
const answer = ($panel.html() ?? $panel.text() ?? "").trim();
|
||||
if (question || answer) items.push({ question, answer });
|
||||
});
|
||||
|
||||
return { title: "", items };
|
||||
}
|
||||
|
||||
function extractBlockquotePayload(
|
||||
$: cheerio.CheerioAPI,
|
||||
el: Element
|
||||
): BlockquoteBlockPayload {
|
||||
const $el = $(el);
|
||||
const citation = $el.find("cite").first().text().trim() || undefined;
|
||||
const $body = $el.clone();
|
||||
$body.find("cite").remove();
|
||||
const content = ($body.html() ?? "").trim();
|
||||
return { content, citation };
|
||||
}
|
||||
|
||||
/**
|
||||
* استخراج از بلاک pullquote وردپرس: figure.wp-block-pullquote > blockquote > p + cite.
|
||||
* همان شکل blockquote (content HTML + citation).
|
||||
*/
|
||||
function extractPullquotePayload(
|
||||
$: cheerio.CheerioAPI,
|
||||
el: Element
|
||||
): BlockquoteBlockPayload {
|
||||
const $el = $(el);
|
||||
const $blockquote = $el.find("blockquote").first();
|
||||
const citation = $blockquote.find("cite").first().text().trim() || undefined;
|
||||
const $body = $blockquote.clone();
|
||||
$body.find("cite").remove();
|
||||
const content = ($body.html() ?? "").trim();
|
||||
return { content, citation };
|
||||
}
|
||||
|
||||
/**
|
||||
* استخراج از بلاک tip وردپرس: div.wp-block-group.tip با کلاس tip-info | tip-warn | tip-danger.
|
||||
*/
|
||||
function extractTipPayload($: cheerio.CheerioAPI, el: Element): TipBlockPayload {
|
||||
const $el = $(el);
|
||||
const classList = ($el.attr("class") ?? "").split(/\s+/);
|
||||
let variant: "info" | "warn" | "danger" = "info";
|
||||
if (classList.includes("tip-danger")) variant = "danger";
|
||||
else if (classList.includes("tip-warn")) variant = "warn";
|
||||
else if (classList.includes("tip-info")) variant = "info";
|
||||
const content = ($el.html() ?? "").trim();
|
||||
return { variant, content };
|
||||
}
|
||||
|
||||
/**
|
||||
* ثبت همهٔ بلاکهای شناختهشده.
|
||||
* برای بلاکهای جدید (مثلاً blockquote, code) فقط یک مورد جدید به این آرایه اضافه کنید.
|
||||
*/
|
||||
export const BLOCK_DEFINITIONS: BlockDefinition[] = [
|
||||
{
|
||||
blockType: "collapse",
|
||||
selector: "div.wp-block-group.collapse-section",
|
||||
extract: extractCollapsePayload as BlockDefinition["extract"],
|
||||
},
|
||||
{
|
||||
blockType: "collapse",
|
||||
selector: "div.wp-block-accordion",
|
||||
extract: extractAccordionPayload as BlockDefinition["extract"],
|
||||
},
|
||||
{
|
||||
blockType: "blockquote",
|
||||
selector: "blockquote.wp-block-quote",
|
||||
extract: extractBlockquotePayload as BlockDefinition["extract"],
|
||||
},
|
||||
{
|
||||
blockType: "pullquote",
|
||||
selector: "figure.wp-block-pullquote",
|
||||
extract: extractPullquotePayload as BlockDefinition["extract"],
|
||||
},
|
||||
{
|
||||
blockType: "tip",
|
||||
selector: "div.wp-block-group.tip",
|
||||
extract: extractTipPayload as BlockDefinition["extract"],
|
||||
},
|
||||
// { blockType: "code", selector: "pre.wp-block-code", extract: extractCodePayload },
|
||||
];
|
||||
|
||||
// ─── کشف بلاک و ساخت سگمنتها ─────────────────────────────────────────────
|
||||
|
||||
const PLACEHOLDER_REGEX =
|
||||
/<div data-blog-block-type="([^"]+)" data-blog-block-id="(\d+)"[^>]*><\/div>/g;
|
||||
|
||||
function isElement(node: unknown): node is Element {
|
||||
return typeof node === "object" && node !== null && (node as Element).type === "tag";
|
||||
}
|
||||
|
||||
/**
|
||||
* ترتیب قرارگیری المنت در سند را با یک مپ نگه میدارد.
|
||||
*/
|
||||
function buildDocumentOrderMap($: cheerio.CheerioAPI): Map<Element, number> {
|
||||
const map = new Map<Element, number>();
|
||||
let index = 0;
|
||||
$("*")
|
||||
.toArray()
|
||||
.filter(isElement)
|
||||
.forEach((el) => {
|
||||
map.set(el, index++);
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* مرحله ۱ و ۲: از روی HTML محتوا بلاکهای شناختهشده را کشف میکند،
|
||||
* به JSON (payload) تبدیل میکند، و خروجی را به صورت HTML با placeholder و
|
||||
* آرایهٔ segments (با payload توکار) به لایه بیرونی میدهد.
|
||||
*/
|
||||
export function discoverBlocks(html: string): DiscoveredContent {
|
||||
const $ = cheerio.load(html, null, false);
|
||||
const orderMap = buildDocumentOrderMap($);
|
||||
|
||||
type BlockEntry = {
|
||||
el: Element;
|
||||
blockType: BlockType;
|
||||
blockId: number;
|
||||
payload: BlockPayload;
|
||||
};
|
||||
const entries: BlockEntry[] = [];
|
||||
const blocksByType: Record<string, BlockPayload[]> = {
|
||||
collapse: [],
|
||||
blockquote: [],
|
||||
pullquote: [],
|
||||
tip: [],
|
||||
code: [],
|
||||
};
|
||||
|
||||
for (const def of BLOCK_DEFINITIONS) {
|
||||
const elements = $(def.selector).toArray().filter(isElement);
|
||||
for (const el of elements) {
|
||||
const payload = def.extract($, el) as BlockPayload;
|
||||
const blockId = blocksByType[def.blockType].length;
|
||||
blocksByType[def.blockType].push(payload);
|
||||
entries.push({
|
||||
el,
|
||||
blockType: def.blockType,
|
||||
blockId,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// مرتبسازی بر اساس ترتیب در سند (از آخر به اول جایگزین میکنیم تا ایندکسها جابجا نشوند)
|
||||
entries.sort((a, b) => orderMap.get(a.el)! - orderMap.get(b.el)!);
|
||||
|
||||
// جایگزینی با placeholder از آخر به اول
|
||||
for (let i = entries.length - 1; i >= 0; i--) {
|
||||
const { el, blockType, blockId } = entries[i];
|
||||
$(el).replaceWith(
|
||||
`<div data-blog-block-type="${blockType}" data-blog-block-id="${blockId}"></div>`
|
||||
);
|
||||
}
|
||||
|
||||
const htmlWithPlaceholders = $.html() ?? html;
|
||||
|
||||
// ساخت segments: تقسیم با placeholder و قرار دادن payload در هر بلاک
|
||||
const segments: ContentSegment[] = [];
|
||||
let lastEnd = 0;
|
||||
const regex = new RegExp(PLACEHOLDER_REGEX.source, "g");
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = regex.exec(htmlWithPlaceholders)) !== null) {
|
||||
if (m.index > lastEnd) {
|
||||
segments.push({
|
||||
type: "html",
|
||||
content: htmlWithPlaceholders.slice(lastEnd, m.index),
|
||||
});
|
||||
}
|
||||
const blockType = m[1] as BlockType;
|
||||
const blockId = parseInt(m[2], 10);
|
||||
const list = blocksByType[blockType];
|
||||
if (list && blockId >= 0 && blockId < list.length) {
|
||||
segments.push({
|
||||
type: "block",
|
||||
blockType,
|
||||
payload: list[blockId],
|
||||
});
|
||||
}
|
||||
lastEnd = regex.lastIndex;
|
||||
}
|
||||
if (lastEnd < htmlWithPlaceholders.length) {
|
||||
segments.push({
|
||||
type: "html",
|
||||
content: htmlWithPlaceholders.slice(lastEnd),
|
||||
});
|
||||
}
|
||||
|
||||
return { htmlWithPlaceholders, segments };
|
||||
}
|
||||
|
||||
/**
|
||||
* بعد از تزریق id سرنویسها در HTML، محتوای هر سگمنت html را با نسخهٔ بهروز (شامل idها) جایگزین میکند.
|
||||
* لایهٔ blog-utils بعد از inject کردن idها این تابع را صدا میزند.
|
||||
*/
|
||||
export function mergeHeadingIdsIntoContentSegments(
|
||||
contentWithIds: string,
|
||||
segments: ContentSegment[]
|
||||
): ContentSegment[] {
|
||||
const parts: string[] = [];
|
||||
let last = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
const regex = new RegExp(PLACEHOLDER_REGEX.source, "g");
|
||||
while ((m = regex.exec(contentWithIds)) !== null) {
|
||||
parts.push(contentWithIds.slice(last, m.index));
|
||||
last = regex.lastIndex;
|
||||
}
|
||||
parts.push(contentWithIds.slice(last));
|
||||
|
||||
let j = 0;
|
||||
return segments.map((seg) => {
|
||||
if (seg.type === "html") {
|
||||
return { ...seg, content: parts[j++] ?? seg.content };
|
||||
}
|
||||
return seg;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import {
|
||||
discoverBlocks,
|
||||
mergeHeadingIdsIntoContentSegments,
|
||||
type ContentSegment,
|
||||
} from "@/lib/blog-blocks";
|
||||
|
||||
export type { ContentSegment } from "@/lib/blog-blocks";
|
||||
|
||||
/**
|
||||
* Creates a URL-safe slug from heading text (strip HTML, normalize, Persian-friendly).
|
||||
*/
|
||||
function slugify(text: string): string {
|
||||
const stripped = text.replace(/<[^>]*>/g, "").trim();
|
||||
return stripped
|
||||
.replace(/\s+/g, "-")
|
||||
.replace(/[^\p{L}\p{N}-]/gu, "")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.toLowerCase() || "section";
|
||||
}
|
||||
|
||||
export interface TocItem {
|
||||
id: string;
|
||||
text: string;
|
||||
level: number; // 2 = h2, 3 = h3, 4 = h4
|
||||
}
|
||||
|
||||
const HEADING_REGEX = /<(h[234])[^>]*>([\s\S]*?)<\/\1>/gi;
|
||||
const usedIds = new Map<string, number>();
|
||||
|
||||
function ensureUniqueId(baseId: string): string {
|
||||
const count = usedIds.get(baseId) ?? 0;
|
||||
usedIds.set(baseId, count + 1);
|
||||
return count === 0 ? baseId : `${baseId}-${count}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* پارس محتوا: ابتدا بلاکها کشف و به JSON تبدیل میشوند (blog-blocks)،
|
||||
* سپس id سرنویسها تزریق میشود و سگمنتهای نهایی برای رندر برمیگردند.
|
||||
*/
|
||||
export function parseContentHeadings(html: string): {
|
||||
contentWithIds: string;
|
||||
toc: TocItem[];
|
||||
segments: ContentSegment[];
|
||||
} {
|
||||
const { htmlWithPlaceholders, segments: rawSegments } = discoverBlocks(html);
|
||||
|
||||
usedIds.clear();
|
||||
const toc: TocItem[] = [];
|
||||
let lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
const parts: string[] = [];
|
||||
const regex = new RegExp(HEADING_REGEX.source, "gi");
|
||||
|
||||
while ((match = regex.exec(htmlWithPlaceholders)) !== null) {
|
||||
const [fullMatch, tag, inner] = match;
|
||||
const level = parseInt(tag.charAt(1), 10) as 2 | 3 | 4;
|
||||
const text = inner.replace(/<[^>]*>/g, "").trim();
|
||||
const baseId = slugify(text);
|
||||
const id = ensureUniqueId(baseId);
|
||||
|
||||
toc.push({ id, text, level });
|
||||
|
||||
const openTag = fullMatch.slice(0, fullMatch.indexOf(">") + 1);
|
||||
const hasId = /^\s*<h[234][^>]*\bid\s*=/i.test(openTag);
|
||||
const newOpenTag = hasId
|
||||
? openTag
|
||||
: openTag.replace(/^(<\s*h[234])(\s|>)/i, `$1 id="${id}"$2`);
|
||||
|
||||
parts.push(htmlWithPlaceholders.slice(lastIndex, match.index));
|
||||
parts.push(newOpenTag + inner + `</${tag}>`);
|
||||
lastIndex = regex.lastIndex;
|
||||
}
|
||||
|
||||
parts.push(htmlWithPlaceholders.slice(lastIndex));
|
||||
const contentWithIds = parts.join("");
|
||||
const segments = mergeHeadingIdsIntoContentSegments(
|
||||
contentWithIds,
|
||||
rawSegments
|
||||
);
|
||||
|
||||
return { contentWithIds, toc, segments };
|
||||
}
|
||||
|
||||
/** Average reading speed in words per minute (Persian/English mix). */
|
||||
const WPM = 200;
|
||||
|
||||
/**
|
||||
* Estimates reading time in minutes from HTML content.
|
||||
*/
|
||||
export function getReadingTimeMinutes(html: string): number {
|
||||
const text = html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
|
||||
const wordCount = text.split(/\s+/).filter(Boolean).length;
|
||||
return Math.max(1, Math.ceil(wordCount / WPM));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
export type ProductCategory =
|
||||
| "vitrin-tala"
|
||||
| "vitrin-khorde-sal"
|
||||
| "vitrin-javaher"
|
||||
| "mankan-service"
|
||||
| "mankan-ring"
|
||||
| "mankan-earring";
|
||||
|
||||
export interface ProductItem {
|
||||
id: string;
|
||||
name: string;
|
||||
category: ProductCategory;
|
||||
categoryLabel: string;
|
||||
image: string;
|
||||
}
|
||||
|
||||
export interface ProductDetailFeature {
|
||||
title: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface ProductDetail extends ProductItem {
|
||||
gallery: { src: string; alt: string }[];
|
||||
color: string;
|
||||
material: string;
|
||||
description: string;
|
||||
features: ProductDetailFeature[];
|
||||
}
|
||||
|
||||
const PRODUCT_IMAGE_POOL = [
|
||||
"/assets/main-pic/product/sampleghaleb.png",
|
||||
"/assets/main-pic/product/محصول 2.jpg",
|
||||
"/assets/main-pic/product/محصول 4.jpg",
|
||||
"/assets/main-pic/product/محصول 3.jpg",
|
||||
"/assets/main-pic/product/محصول 1.jpg",
|
||||
] as const;
|
||||
|
||||
const MODEL_SUFFIXES = [
|
||||
"پرستیژ",
|
||||
"کلاسیک لوکس",
|
||||
"باروک",
|
||||
"مینیمال",
|
||||
"نئوکلاسیک",
|
||||
"رویال",
|
||||
"الماس",
|
||||
"پلاتینیوم",
|
||||
"نگین",
|
||||
"آریا",
|
||||
"سافایر",
|
||||
"کهکشانی",
|
||||
] as const;
|
||||
|
||||
const COLOR_OPTIONS = [
|
||||
"طلایی براق",
|
||||
"طلایی مات",
|
||||
"رزگلد",
|
||||
"نقرهای",
|
||||
"مشکی مات",
|
||||
"کروم",
|
||||
] as const;
|
||||
|
||||
const MATERIAL_VITRIN = "MDF روکشدار، یراق آلات فلزی و شیشه امنیت بالا";
|
||||
const MATERIAL_MANKAN = "پایه فلزی، بدنه ترکیبی و روکش مقاوم در برابر سایش";
|
||||
|
||||
function categoryMaterial(category: ProductCategory): string {
|
||||
return category.startsWith("mankan") ? MATERIAL_MANKAN : MATERIAL_VITRIN;
|
||||
}
|
||||
|
||||
function hashId(id: string): number {
|
||||
return id.split("").reduce((acc, ch) => acc + ch.charCodeAt(0), 0);
|
||||
}
|
||||
|
||||
function buildGallery(primary: string, id: string): { src: string; alt: string }[] {
|
||||
const pool = [...PRODUCT_IMAGE_POOL];
|
||||
const h = hashId(id);
|
||||
const ordered: string[] = [primary];
|
||||
while (ordered.length < 4) {
|
||||
ordered.push(pool[(h + ordered.length) % pool.length]!);
|
||||
}
|
||||
const name = getProductById(id)?.name ?? "محصول";
|
||||
return ordered.map((src) => ({ src, alt: name }));
|
||||
}
|
||||
|
||||
function buildDescription(product: ProductItem): string {
|
||||
return `${product.name} از خط ${product.categoryLabel} مستر دکور است؛ برای فضای فروش طلا و جواهر با تمرکز بر نمایش منظم، امنیت ویترین و هماهنگی بصری با دکور مجموعه شما طراحی شده است. جزئیات اجرایی و ابعاد نهایی پس از هماهنگی پروژه در اختیار شما قرار میگیرد.`;
|
||||
}
|
||||
|
||||
function buildFeatures(product: ProductItem): ProductDetailFeature[] {
|
||||
return [
|
||||
{
|
||||
title: "کاربرد و جایگاه",
|
||||
content: `${product.name} برای چیدمان حرفهای در ویترین و فضای فروش مناسب است و با سایر اقلام ${product.categoryLabel} قابل ترکیب است.`,
|
||||
},
|
||||
{
|
||||
title: "کیفیت ساخت",
|
||||
content:
|
||||
"کنترل کیفیت در مراحل ساخت و مونتاژ انجام میشود؛ متریال اعلامشده در همین صفحه مبنای اجرای استاندارد محصول است.",
|
||||
},
|
||||
{
|
||||
title: "هماهنگی با پروژه",
|
||||
content:
|
||||
"در صورت نیاز به ابعاد، رنگ یا جزئیات اختصاصی، پس از ثبت درخواست مشاوره، تیم فنی مسیر سفارشیسازی را با شما هماهنگ میکند.",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function makeCategoryProducts(
|
||||
category: ProductCategory,
|
||||
categoryLabel: string,
|
||||
namePrefix: string,
|
||||
): ProductItem[] {
|
||||
return MODEL_SUFFIXES.map((suffix, index) => ({
|
||||
id: `${category}-${String(index + 1).padStart(2, "0")}`,
|
||||
name: `${namePrefix} مدل ${suffix}`,
|
||||
category,
|
||||
categoryLabel,
|
||||
image: PRODUCT_IMAGE_POOL[index % PRODUCT_IMAGE_POOL.length]!,
|
||||
}));
|
||||
}
|
||||
|
||||
export const CATALOG_PRODUCTS: ProductItem[] = [
|
||||
...makeCategoryProducts("vitrin-tala", "ویترین طلا", "ویترین طلا"),
|
||||
...makeCategoryProducts("vitrin-khorde-sal", "ویترین خردسال", "ویترین خردسال"),
|
||||
...makeCategoryProducts("vitrin-javaher", "ویترین جواهر", "ویترین جواهر"),
|
||||
...makeCategoryProducts("mankan-service", "مانکن سرویس", "مانکن سرویس"),
|
||||
...makeCategoryProducts("mankan-ring", "مانکن انگشتر", "مانکن انگشتر"),
|
||||
...makeCategoryProducts("mankan-earring", "مانکن گوشواره", "مانکن گوشواره"),
|
||||
];
|
||||
|
||||
export function getProductById(id: string): ProductItem | undefined {
|
||||
return CATALOG_PRODUCTS.find((p) => p.id === id);
|
||||
}
|
||||
|
||||
export function getProductDetail(id: string): ProductDetail | null {
|
||||
const product = getProductById(id);
|
||||
if (!product) return null;
|
||||
const color = COLOR_OPTIONS[hashId(product.id) % COLOR_OPTIONS.length]!;
|
||||
return {
|
||||
...product,
|
||||
gallery: buildGallery(product.image, product.id),
|
||||
color,
|
||||
material: categoryMaterial(product.category),
|
||||
description: buildDescription(product),
|
||||
features: buildFeatures(product),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAllProductIds(): string[] {
|
||||
return CATALOG_PRODUCTS.map((p) => p.id);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import path from 'node:path'
|
||||
import fs from 'node:fs'
|
||||
|
||||
import staticContent from '@/content/site-content.json'
|
||||
|
||||
/**
|
||||
* نوع کلی محتوای سایت.
|
||||
* با تغییر فایل content/site-content.json یا public/content.json
|
||||
* میتوان بدون بیلد مجدد متنها و تصاویر را عوض کرد.
|
||||
*/
|
||||
export type SiteContent = typeof staticContent
|
||||
|
||||
/**
|
||||
* محتوای پیشفرض (از content/site-content.json در بیلد).
|
||||
*/
|
||||
export const defaultContent: SiteContent = staticContent as SiteContent
|
||||
|
||||
/**
|
||||
* خواندن محتوای سایت.
|
||||
* در سرور ابتدا public/content.json را امتحان میکند (برای تغییر بدون بیلد)،
|
||||
* در صورت نبود یا خطا از محتوای پیشفرض استفاده میکند.
|
||||
*/
|
||||
export async function getContent(): Promise<SiteContent> {
|
||||
if (typeof window !== 'undefined') {
|
||||
return defaultContent
|
||||
}
|
||||
try {
|
||||
const publicPath = path.join(process.cwd(), 'public', 'content.json')
|
||||
const raw = fs.readFileSync(publicPath, 'utf-8')
|
||||
const parsed = JSON.parse(raw) as SiteContent
|
||||
return parsed
|
||||
} catch {
|
||||
return defaultContent
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* نسخهٔ همگام برای استفاده در Server Components که await پشتیبانی نمیکنند.
|
||||
*/
|
||||
export function getContentSync(): SiteContent {
|
||||
if (typeof window !== 'undefined') {
|
||||
return defaultContent
|
||||
}
|
||||
try {
|
||||
const publicPath = path.join(process.cwd(), 'public', 'content.json')
|
||||
const raw = fs.readFileSync(publicPath, 'utf-8')
|
||||
return JSON.parse(raw) as SiteContent
|
||||
} catch {
|
||||
return defaultContent
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { format, newDate } from "date-fns-jalali";
|
||||
import { faIR } from "date-fns-jalali/locale";
|
||||
|
||||
/**
|
||||
* Format a Gregorian date (Date or ISO string) to Shamsi (Jalali) Persian string.
|
||||
* Example: "۱۴ بهمن ۱۴۰۴"
|
||||
*/
|
||||
export function formatDateShamsi(
|
||||
date: Date | string,
|
||||
formatStr: string = "d MMMM yyyy"
|
||||
): string {
|
||||
const d = typeof date === "string" ? new Date(date) : date;
|
||||
if (Number.isNaN(d.getTime())) return "";
|
||||
return format(d, formatStr, { locale: faIR });
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
const WP_API_BASE = "";
|
||||
const FETCH_TIMEOUT_MS = 15_000;
|
||||
|
||||
export interface WpMediaSize {
|
||||
source_url: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
export interface WpFeaturedMedia {
|
||||
source_url: string;
|
||||
alt_text?: string;
|
||||
media_details?: {
|
||||
width?: number;
|
||||
height?: number;
|
||||
sizes?: Record<string, WpMediaSize>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface WpAuthor {
|
||||
id: number;
|
||||
name: string;
|
||||
slug?: string;
|
||||
}
|
||||
|
||||
export interface WpPost {
|
||||
id: number;
|
||||
date: string;
|
||||
modified?: string;
|
||||
slug: string;
|
||||
title: { rendered: string };
|
||||
content: { rendered: string };
|
||||
excerpt: { rendered: string };
|
||||
featured_media: number;
|
||||
categories: number[];
|
||||
author?: number;
|
||||
_embedded?: {
|
||||
"wp:featuredmedia"?: WpFeaturedMedia[];
|
||||
author?: WpAuthor[];
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns thumbnail URL for list/card (medium) or full for single post. */
|
||||
export function getFeaturedImageUrl(
|
||||
post: WpPost,
|
||||
size: "medium" | "medium_large" | "full" = "medium"
|
||||
): string | null {
|
||||
const media = post._embedded?.["wp:featuredmedia"]?.[0];
|
||||
if (!media?.source_url) return null;
|
||||
const sizes = media.media_details?.sizes;
|
||||
if (sizes?.[size]?.source_url) return sizes[size].source_url;
|
||||
if (size !== "full" && sizes?.medium?.source_url) return sizes.medium.source_url;
|
||||
return media.source_url;
|
||||
}
|
||||
|
||||
export interface WpCategory {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface GetPostsResult {
|
||||
posts: WpPost[];
|
||||
total: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export interface GetPostsOptions {
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
search?: string;
|
||||
categoryId?: number;
|
||||
/** ترتیب بر اساس: date, modified, title, ... در وردپرس. برای اولویت دستی (menu_order) پلاگین/فیلتر در وردپرس لازم است. */
|
||||
orderby?: string;
|
||||
order?: "asc" | "desc";
|
||||
}
|
||||
|
||||
async function fetchWithTimeout(
|
||||
url: string,
|
||||
options?: RequestInit
|
||||
): Promise<Response> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
next: { revalidate: 0 },
|
||||
});
|
||||
clearTimeout(timeout);
|
||||
return res;
|
||||
} catch (e) {
|
||||
clearTimeout(timeout);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPosts(
|
||||
options: GetPostsOptions = {}
|
||||
): Promise<GetPostsResult> {
|
||||
const { page = 1, perPage = 9, search, categoryId, orderby, order } = options;
|
||||
const params = new URLSearchParams();
|
||||
params.set("page", String(page));
|
||||
params.set("per_page", String(perPage));
|
||||
if (search?.trim()) params.set("search", search.trim());
|
||||
if (categoryId) params.set("categories", String(categoryId));
|
||||
if (orderby) params.set("orderby", orderby);
|
||||
if (order) params.set("order", order);
|
||||
params.set("_embed", "1");
|
||||
|
||||
const url = `${WP_API_BASE}/posts?${params.toString()}`;
|
||||
const res = await fetchWithTimeout(url);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`WP API error: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const total = parseInt(res.headers.get("x-wp-total") ?? "0", 10);
|
||||
const totalPages = parseInt(res.headers.get("x-wp-totalpages") ?? "1", 10);
|
||||
const posts: WpPost[] = await res.json();
|
||||
|
||||
return { posts, total, totalPages };
|
||||
}
|
||||
|
||||
export async function getPostBySlug(slug: string): Promise<WpPost | null> {
|
||||
const decodedSlug = decodeURIComponent(slug);
|
||||
const params = new URLSearchParams({ slug: decodedSlug, _embed: "1" });
|
||||
const url = `${WP_API_BASE}/posts?${params.toString()}`;
|
||||
const res = await fetchWithTimeout(url);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`WP API error: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const posts: WpPost[] = await res.json();
|
||||
return posts.length > 0 ? posts[0] : null;
|
||||
}
|
||||
|
||||
export async function getRelatedPosts(
|
||||
postId: number,
|
||||
categoryIds: number[],
|
||||
limit = 3
|
||||
): Promise<WpPost[]> {
|
||||
const params = new URLSearchParams();
|
||||
params.set("exclude", String(postId));
|
||||
params.set("per_page", String(limit));
|
||||
params.set("_embed", "1");
|
||||
if (categoryIds.length > 0) {
|
||||
params.set("categories", String(categoryIds[0]));
|
||||
}
|
||||
|
||||
const url = `${WP_API_BASE}/posts?${params.toString()}`;
|
||||
const res = await fetchWithTimeout(url);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`WP API error: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const posts: WpPost[] = await res.json();
|
||||
return posts;
|
||||
}
|
||||
|
||||
export async function getCategories(): Promise<WpCategory[]> {
|
||||
const url = `${WP_API_BASE}/categories?per_page=100`;
|
||||
const res = await fetchWithTimeout(url);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`WP API error: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const data: WpCategory[] = await res.json();
|
||||
return data.filter((c) => c.count > 0);
|
||||
}
|
||||
Reference in New Issue
Block a user