Files
2026-10-18 06:37:05 +00:00

121 lines
3.7 KiB
TypeScript

"use client";
import React, { useMemo } from "react";
import ArticleProductCard from "./ArticleProductCard";
interface ArticleContentRendererProps {
contentHtml: string;
relatedProducts?: any[];
}
export function parseContentWithProducts(
html: string,
relatedProducts: any[] = []
): Array<{ type: "html" | "product"; content?: string; product?: any }> {
if (!html) return [];
// Match tags like [product slug_or_id], [محصول slug_or_id]
// or HTML elements like <div data-product="slug_or_id"></div>
// or <span data-product="slug_or_id"></span>
const markerRegex = /(?:<p[^>]*>\s*)?(?:\[(?:product|محصول)\s+([a-zA-Z0-9_-]+)\]|<(?:div|span)[^>]*data-product=["']([a-zA-Z0-9_-]+)["'][^>]*>(?:<\/(?:div|span)>)?)(?:\s*<\/p>)?/gi;
const parts: Array<{ type: "html" | "product"; content?: string; product?: any }> = [];
let lastIndex = 0;
let match: RegExpExecArray | null;
// Build product lookup map (by slug, id)
const productMap = new Map<string, any>();
for (const prod of relatedProducts) {
if (prod.slug) productMap.set(String(prod.slug).toLowerCase(), prod);
if (prod.id) productMap.set(String(prod.id).toLowerCase(), prod);
}
while ((match = markerRegex.exec(html)) !== null) {
const matchedText = match[0];
const identifier = (match[1] || match[2] || "").trim();
const startIndex = match.index;
// Push preceding HTML
if (startIndex > lastIndex) {
const htmlSlice = html.slice(lastIndex, startIndex);
if (htmlSlice.trim()) {
parts.push({ type: "html", content: htmlSlice });
}
}
const matchedProduct = productMap.get(identifier.toLowerCase());
if (matchedProduct) {
parts.push({ type: "product", product: matchedProduct });
} else {
// If product not found in map, attempt fallback with slug info
parts.push({
type: "product",
product: {
id: identifier,
slug: identifier,
nameFa: `محصول ${identifier}`,
category: "مکمل دارویی کنینا",
},
});
}
lastIndex = startIndex + matchedText.length;
}
// Push remaining HTML
if (lastIndex < html.length) {
const trailingHtml = html.slice(lastIndex);
if (trailingHtml.trim()) {
parts.push({ type: "html", content: trailingHtml });
}
}
if (parts.length === 0 && html) {
parts.push({ type: "html", content: html });
}
return parts;
}
export default function ArticleContentRenderer({
contentHtml,
relatedProducts = [],
}: ArticleContentRendererProps) {
const sections = useMemo(
() => parseContentWithProducts(contentHtml, relatedProducts),
[contentHtml, relatedProducts]
);
// If there are no product cards inserted, preserve the exact original markup structure
const hasProducts = sections.some((s) => s.type === "product");
if (!hasProducts) {
return (
<div
className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5 article-html-content"
dangerouslySetInnerHTML={{ __html: contentHtml }}
/>
);
}
return (
<div className="article-html-content space-y-6">
{sections.map((section, idx) => {
if (section.type === "product" && section.product) {
return (
<ArticleProductCard
key={`article-prod-${section.product.id || idx}`}
product={section.product}
/>
);
}
return (
<div
key={`article-html-${idx}`}
className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5"
dangerouslySetInnerHTML={{ __html: section.content || "" }}
/>
);
})}
</div>
);
}