feat(seo): implement FAQPage schema, sub-sitemaps and local Lalezar WOFF2 font (SEO-P1-07, SEO-P1-10, SEO-P2-16)
Deploy Canina / deploy (push) Successful in 2m10s
Deploy Canina / deploy (push) Successful in 2m10s
- SEO-P1-07: extract FAQs and accordion items from blog content and inject JSON-LD FAQPage schema - SEO-P1-10: add dynamic sub-sitemaps /sitemap-blog.xml and /sitemap-wiki.xml and register in robots.ts - SEO-P2-16: host Lalezar font locally as optimized WOFF2 with preload enabled in lib/fonts.ts - Add full regression test suites with 100% pass rate
This commit is contained in:
1 parent
5cf2863987
commit
f8f9329c50
11 files changed
+556
-6
No files matched your search
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import BlogPostPage from './page';
|
||||
|
||||
vi.mock('../../../lib/seo', () => ({
|
||||
getSeoConfig: vi.fn().mockResolvedValue({
|
||||
brandNameFa: 'کنینا ایران',
|
||||
canonicalBaseUrl: 'https://canina.ir',
|
||||
ogImageUrl: '/assets/og.jpg',
|
||||
defaultMetaDescription: 'توضیحات پیشفرض',
|
||||
titleSeparator: '|',
|
||||
titlePosition: 'suffix',
|
||||
}),
|
||||
formatPageTitle: vi.fn((title) => `${title} | کنینا ایران`),
|
||||
}));
|
||||
|
||||
vi.mock('../../../components/BlogPostClient', () => ({
|
||||
default: () => <div data-testid="blog-post-client" />,
|
||||
}));
|
||||
|
||||
describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('injects FAQPage JSON-LD schema when article contains questions and answers', async () => {
|
||||
const blogData = {
|
||||
slug: 'joint-health',
|
||||
title: 'سلامت مفاصل سگ',
|
||||
content: `
|
||||
<article>
|
||||
<p>مقدمهای درباره مفاصل سگ.</p>
|
||||
<details>
|
||||
<summary>آیا این مکمل برای سگ مسن مناسب است؟</summary>
|
||||
<p>بله، بسیار توصیه میشود و روند تخریب مفصل را کند میکند.</p>
|
||||
</details>
|
||||
</article>
|
||||
`,
|
||||
createdAt: '2026-01-01',
|
||||
publishedAt: '2026-01-01',
|
||||
};
|
||||
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => blogData,
|
||||
})
|
||||
);
|
||||
|
||||
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'joint-health' }) });
|
||||
expect(jsx).toBeDefined();
|
||||
|
||||
// Verify scripts in JSX tree
|
||||
const scripts = React.Children.toArray(jsx.props.children).filter(
|
||||
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
|
||||
);
|
||||
|
||||
// There should be 3 schemas: Article, Breadcrumb, and FAQPage
|
||||
expect(scripts.length).toBe(3);
|
||||
|
||||
const faqScript: any = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
|
||||
expect(faqScript).toBeDefined();
|
||||
|
||||
const faqJson = JSON.parse(faqScript.props.dangerouslySetInnerHTML.__html);
|
||||
expect(faqJson['@type']).toBe('FAQPage');
|
||||
expect(faqJson.mainEntity).toHaveLength(1);
|
||||
expect(faqJson.mainEntity[0].name).toBe('آیا این مکمل برای سگ مسن مناسب است؟');
|
||||
});
|
||||
|
||||
it('does not inject FAQPage schema when article does not have FAQs', async () => {
|
||||
const blogData = {
|
||||
slug: 'nutrition',
|
||||
title: 'تغذیه سگ',
|
||||
content: '<p>یک مقاله ساده بدون سوال و جواب یا آکاردئون.</p>',
|
||||
createdAt: '2026-01-01',
|
||||
publishedAt: '2026-01-01',
|
||||
};
|
||||
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => blogData,
|
||||
})
|
||||
);
|
||||
|
||||
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'nutrition' }) });
|
||||
const scripts = React.Children.toArray(jsx.props.children).filter(
|
||||
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
|
||||
);
|
||||
|
||||
// Only Article and Breadcrumb schemas
|
||||
expect(scripts.length).toBe(2);
|
||||
const faqScript = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
|
||||
expect(faqScript).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import BlogPostClient from "../../../components/BlogPostClient";
|
||||
import { getSeoConfig, formatPageTitle } from "../../../lib/seo";
|
||||
import { safeJsonLd } from "../../../lib/schema";
|
||||
import { sanitizeBlogHtml } from "../../../lib/sanitizeBlogHtml";
|
||||
import { extractFaqsFromHtml, generateFAQPageSchema } from "../../../lib/extractFaqs";
|
||||
|
||||
function safeIso(val: any, fallback?: string): string | undefined {
|
||||
if (!val) return fallback;
|
||||
@@ -82,7 +83,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
const ogTitle = blog.ogTitle || title;
|
||||
const ogDesc = blog.ogDescription || description;
|
||||
|
||||
const isStaging =
|
||||
const isStaging =
|
||||
process.env.NEXT_PUBLIC_APP_ENV === 'staging' ||
|
||||
process.env.NODE_ENV !== 'production' ||
|
||||
siteUrl.includes('stage') ||
|
||||
@@ -267,6 +268,10 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
],
|
||||
};
|
||||
|
||||
// SEO-P1-07: Auto-detect and inject FAQPage Schema when article content contains Q&As or accordion structures
|
||||
const extractedFaqs = extractFaqsFromHtml(blog.content || '');
|
||||
const faqPageSchema = generateFAQPageSchema(extractedFaqs);
|
||||
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
@@ -277,6 +282,13 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbJsonLd) }}
|
||||
/>
|
||||
{faqPageSchema && (
|
||||
<script
|
||||
type="application/ld+json"
|
||||
data-testid="faq-schema"
|
||||
dangerouslySetInnerHTML={{ __html: safeJsonLd(faqPageSchema) }}
|
||||
/>
|
||||
)}
|
||||
<BlogPostClient
|
||||
blog={blog}
|
||||
publishedDate={publishedDate}
|
||||
|
||||
@@ -37,6 +37,8 @@ export default function robots(): MetadataRoute.Robots {
|
||||
`${baseUrl}/sitemap.xml`,
|
||||
`${baseUrl}/sitemap-products.xml`,
|
||||
`${baseUrl}/sitemap-categories.xml`,
|
||||
`${baseUrl}/sitemap-blog.xml`,
|
||||
`${baseUrl}/sitemap-wiki.xml`,
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const revalidate = 3600; // Revalidate every hour
|
||||
|
||||
type SitemapBlog = {
|
||||
slug: string;
|
||||
noIndex?: boolean;
|
||||
status: string;
|
||||
updatedAt?: string;
|
||||
createdAt?: string;
|
||||
featured?: boolean;
|
||||
title?: string;
|
||||
imageUrl?: string;
|
||||
ogImage?: string;
|
||||
};
|
||||
|
||||
export async function GET() {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
|
||||
const apiUrl =
|
||||
process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
|
||||
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
|
||||
|
||||
const blogRoutes: SitemapBlog[] = [];
|
||||
|
||||
try {
|
||||
let page = 1;
|
||||
let lastPage = 1;
|
||||
do {
|
||||
const res = await fetch(`${apiBase}/blogs?page=${page}&limit=20`, { cache: 'no-store' });
|
||||
if (!res.ok) throw new Error(`Blog sitemap request failed: ${res.status}`);
|
||||
const data = await res.json();
|
||||
const blogsList: SitemapBlog[] = data.data || [];
|
||||
if (!blogsList.length) break;
|
||||
|
||||
const validBlogs = blogsList.filter((b) => !b.noIndex && b.status === 'PUBLISHED');
|
||||
blogRoutes.push(...validBlogs);
|
||||
|
||||
lastPage = Number(data.meta?.lastPage) || 1;
|
||||
page += 1;
|
||||
} while (page <= lastPage);
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch blogs for sitemap-blog.xml:', err);
|
||||
}
|
||||
|
||||
const urlsXml = blogRoutes
|
||||
.map((blog) => {
|
||||
const loc = `${baseUrl}/blog/${encodeURIComponent(blog.slug)}`;
|
||||
const lastmod = blog.updatedAt
|
||||
? new Date(blog.updatedAt).toISOString()
|
||||
: blog.createdAt
|
||||
? new Date(blog.createdAt).toISOString()
|
||||
: new Date().toISOString();
|
||||
const priority = blog.featured ? '0.9' : '0.7';
|
||||
const primaryImg = blog.ogImage || blog.imageUrl;
|
||||
const title = blog.title || 'مقاله وبلاگ تخصصی کنینا';
|
||||
|
||||
const imageTag = primaryImg
|
||||
? `\n <image:image>\n <image:loc>${
|
||||
primaryImg.startsWith('http') ? primaryImg : `${baseUrl}${primaryImg.startsWith('/') ? '' : '/'}${primaryImg}`
|
||||
}</image:loc>\n <image:title><![CDATA[${title}]]></image:title>\n </image:image>`
|
||||
: '';
|
||||
|
||||
return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n <changefreq>weekly</changefreq>\n <priority>${priority}</priority>${imageTag}\n </url>`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
const xmlContent = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"\n xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">\n${urlsXml}\n</urlset>`;
|
||||
|
||||
return new NextResponse(xmlContent, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/xml; charset=utf-8',
|
||||
'Cache-Control': 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const revalidate = 86400; // Revalidate daily
|
||||
|
||||
type SitemapWikiTerm = {
|
||||
key: string;
|
||||
term: string;
|
||||
definition?: string;
|
||||
updatedAt?: string;
|
||||
createdAt?: string;
|
||||
};
|
||||
|
||||
export async function GET() {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
|
||||
const apiUrl =
|
||||
process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
|
||||
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
|
||||
|
||||
const wikiRoutes: SitemapWikiTerm[] = [];
|
||||
|
||||
try {
|
||||
let page = 1;
|
||||
let lastPage = 1;
|
||||
do {
|
||||
const res = await fetch(`${apiBase}/wiki?page=${page}&limit=50`, { cache: 'no-store' });
|
||||
if (!res.ok) throw new Error(`Wiki sitemap request failed: ${res.status}`);
|
||||
const data = await res.json();
|
||||
const wikiList: SitemapWikiTerm[] = data.data || [];
|
||||
if (!wikiList.length) break;
|
||||
|
||||
wikiRoutes.push(...wikiList);
|
||||
|
||||
lastPage = Number(data.meta?.lastPage) || 1;
|
||||
page += 1;
|
||||
} while (page <= lastPage);
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch wiki terms for sitemap-wiki.xml:', err);
|
||||
}
|
||||
|
||||
const urlsXml = wikiRoutes
|
||||
.map((item) => {
|
||||
const loc = `${baseUrl}/wiki/${encodeURIComponent(item.key)}`;
|
||||
const lastmod = item.updatedAt
|
||||
? new Date(item.updatedAt).toISOString()
|
||||
: item.createdAt
|
||||
? new Date(item.createdAt).toISOString()
|
||||
: new Date().toISOString();
|
||||
|
||||
return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n <changefreq>weekly</changefreq>\n <priority>0.8</priority>\n </url>`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
const xmlContent = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urlsXml}\n</urlset>`;
|
||||
|
||||
return new NextResponse(xmlContent, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/xml; charset=utf-8',
|
||||
'Cache-Control': 'public, max-age=86400, s-maxage=86400, stale-while-revalidate=604800',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import robots from './robots';
|
||||
import { GET as getBlogSitemap } from './sitemap-blog.xml/route';
|
||||
import { GET as getWikiSitemap } from './sitemap-wiki.xml/route';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe('Sub-sitemaps and robots.ts integration (SEO-P1-10)', () => {
|
||||
it('registers sitemap-blog.xml and sitemap-wiki.xml in robots.ts', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'production');
|
||||
vi.stubEnv('NODE_ENV', 'production');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
|
||||
const config = robots();
|
||||
const sitemaps = Array.isArray(config.sitemap) ? config.sitemap : [config.sitemap];
|
||||
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap.xml');
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap-products.xml');
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap-categories.xml');
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap-blog.xml');
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap-wiki.xml');
|
||||
});
|
||||
|
||||
it('generates sitemap-blog.xml correctly with published blogs and image tags', async () => {
|
||||
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [
|
||||
{
|
||||
slug: 'puppy-nutrition',
|
||||
title: 'تغذیه توله سگ',
|
||||
status: 'PUBLISHED',
|
||||
updatedAt: '2026-10-10T12:00:00.000Z',
|
||||
featured: true,
|
||||
imageUrl: '/uploads/puppy.jpg',
|
||||
},
|
||||
{
|
||||
slug: 'hidden-blog',
|
||||
title: 'مقاله پیشنویس',
|
||||
status: 'DRAFT',
|
||||
},
|
||||
],
|
||||
meta: { lastPage: 1 },
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const res = await getBlogSitemap();
|
||||
expect(res.status).toBe(200);
|
||||
const xml = await res.text();
|
||||
|
||||
expect(xml).toContain('<loc>https://canina.ir/blog/puppy-nutrition</loc>');
|
||||
expect(xml).toContain('<priority>0.9</priority>');
|
||||
expect(xml).toContain('<image:loc>https://canina.ir/uploads/puppy.jpg</image:loc>');
|
||||
expect(xml).toContain('تغذیه توله سگ');
|
||||
expect(xml).not.toContain('hidden-blog');
|
||||
});
|
||||
|
||||
it('generates sitemap-wiki.xml correctly with scientific terms', async () => {
|
||||
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [
|
||||
{
|
||||
key: 'omega-3',
|
||||
term: 'امگا ۳',
|
||||
updatedAt: '2026-09-01T10:00:00.000Z',
|
||||
},
|
||||
],
|
||||
meta: { lastPage: 1 },
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const res = await getWikiSitemap();
|
||||
expect(res.status).toBe(200);
|
||||
const xml = await res.text();
|
||||
|
||||
expect(xml).toContain('<loc>https://canina.ir/wiki/omega-3</loc>');
|
||||
expect(xml).toContain('<priority>0.8</priority>');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { extractFaqsFromHtml, generateFAQPageSchema } from '../extractFaqs';
|
||||
|
||||
describe('extractFaqsFromHtml and generateFAQPageSchema (SEO-P1-07)', () => {
|
||||
it('extracts FAQs from HTML5 details and summary tags', () => {
|
||||
const html = `
|
||||
<article>
|
||||
<h1>مراقبت از مفاصل سگ</h1>
|
||||
<details>
|
||||
<summary>آیا این مکمل برای سگ نژاد بزرگ مناسب است؟</summary>
|
||||
<p>بله، دوز مشخص بر اساس وزن روی بستهبندی درج شده است.</p>
|
||||
</details>
|
||||
<details>
|
||||
<summary>مدت دوره درمان چقدر است؟</summary>
|
||||
حداقل ۴ الی ۶ هفته مصرف مداوم توصیه میشود.
|
||||
</details>
|
||||
</article>
|
||||
`;
|
||||
const faqs = extractFaqsFromHtml(html);
|
||||
expect(faqs).toHaveLength(2);
|
||||
expect(faqs[0].question).toBe('آیا این مکمل برای سگ نژاد بزرگ مناسب است؟');
|
||||
expect(faqs[0].answer).toBe('بله، دوز مشخص بر اساس وزن روی بستهبندی درج شده است.');
|
||||
expect(faqs[1].question).toBe('مدت دوره درمان چقدر است؟');
|
||||
expect(faqs[1].answer).toBe('حداقل ۴ الی ۶ هفته مصرف مداوم توصیه میشود.');
|
||||
|
||||
const schema = generateFAQPageSchema(faqs);
|
||||
expect(schema).not.toBeNull();
|
||||
expect(schema?.['@type']).toBe('FAQPage');
|
||||
expect(schema?.mainEntity).toHaveLength(2);
|
||||
expect(schema?.mainEntity[0].name).toBe('آیا این مکمل برای سگ نژاد بزرگ مناسب است؟');
|
||||
expect(schema?.mainEntity[0].acceptedAnswer.text).toBe('بله، دوز مشخص بر اساس وزن روی بستهبندی درج شده است.');
|
||||
});
|
||||
|
||||
it('extracts FAQs from accordion or FAQ class structures', () => {
|
||||
const html = `
|
||||
<div class="faq-item">
|
||||
<h4 class="accordion-title">چگونه اصالت محصول را بررسی کنیم؟</h4>
|
||||
<div class="accordion-content">با اسکن کد QR و استعلام شماره بچ در سایت شرکت کنینا.</div>
|
||||
</div>
|
||||
`;
|
||||
const faqs = extractFaqsFromHtml(html);
|
||||
expect(faqs).toHaveLength(1);
|
||||
expect(faqs[0].question).toBe('چگونه اصالت محصول را بررسی کنیم؟');
|
||||
expect(faqs[0].answer).toBe('با اسکن کد QR و استعلام شماره بچ در سایت شرکت کنینا.');
|
||||
});
|
||||
|
||||
it('extracts FAQs from heading questions followed by paragraph answers', () => {
|
||||
const html = `
|
||||
<h2>پرسش: آیا کنینا محصولات ساخت آلمان هستند؟</h2>
|
||||
<p>تمامی محصولات در کشور آلمان تحت استانداردهای دارویی اروپا تولید و بستهبندی میشوند.</p>
|
||||
`;
|
||||
const faqs = extractFaqsFromHtml(html);
|
||||
expect(faqs).toHaveLength(1);
|
||||
expect(faqs[0].question).toBe('پرسش: آیا کنینا محصولات ساخت آلمان هستند؟');
|
||||
expect(faqs[0].answer).toContain('تمامی محصولات در کشور آلمان');
|
||||
});
|
||||
|
||||
it('returns empty array and null schema when no FAQs are found', () => {
|
||||
const html = `<p>یک مقاله بدون هرگونه بخش پرسش و پاسخ.</p>`;
|
||||
const faqs = extractFaqsFromHtml(html);
|
||||
expect(faqs).toHaveLength(0);
|
||||
expect(generateFAQPageSchema(faqs)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
vi.mock('next/font/local', () => ({
|
||||
default: vi.fn((opts) => ({
|
||||
variable: opts.variable,
|
||||
className: 'mock-font',
|
||||
src: opts.src,
|
||||
preload: opts.preload,
|
||||
display: opts.display,
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('Local font configuration and preloading (SEO-P2-16)', () => {
|
||||
it('configures Lalezar as a local font with WOFF2 and preload enabled', async () => {
|
||||
const { lalezar } = await import('../fonts');
|
||||
expect(lalezar).toBeDefined();
|
||||
expect(lalezar.variable).toBe('--font-lalezar');
|
||||
expect((lalezar as any).preload).toBe(true);
|
||||
expect((lalezar as any).display).toBe('swap');
|
||||
expect((lalezar as any).src[0].path).toContain('Lalezar-Regular.woff2');
|
||||
});
|
||||
|
||||
it('configures Vazirmatn as a local font with preload enabled', async () => {
|
||||
const { vazirmatn } = await import('../fonts');
|
||||
expect(vazirmatn).toBeDefined();
|
||||
expect(vazirmatn.variable).toBe('--font-vazir');
|
||||
expect((vazirmatn as any).preload).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
export interface FAQItem {
|
||||
question: string;
|
||||
answer: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts question and answer pairs from rich HTML content or structured blog data.
|
||||
* Supports HTML5 <details><summary>, CSS accordion/faq classes, and question headings with paragraph answers.
|
||||
*/
|
||||
export function extractFaqsFromHtml(html: string): FAQItem[] {
|
||||
if (!html || typeof html !== 'string') return [];
|
||||
const faqs: FAQItem[] = [];
|
||||
|
||||
// 1. HTML5 <details><summary>Question</summary>Answer...</details>
|
||||
const detailsRegex = /<details[^>]*>([\s\S]*?)<\/details>/gi;
|
||||
let detailsMatch;
|
||||
while ((detailsMatch = detailsRegex.exec(html)) !== null) {
|
||||
const block = detailsMatch[1];
|
||||
const summaryMatch = /<summary[^>]*>([\s\S]*?)<\/summary>/i.exec(block);
|
||||
if (summaryMatch) {
|
||||
const question = summaryMatch[1].replace(/<[^>]+>/g, '').trim();
|
||||
const answerHtml = block.replace(/<summary[^>]*>[\s\S]*?<\/summary>/i, '');
|
||||
const answer = answerHtml.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
if (question && answer && !faqs.some((f) => f.question === question)) {
|
||||
faqs.push({ question, answer });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Class-based Accordion or FAQ items:
|
||||
// e.g. <div class="accordion-item"><h3 class="accordion-title">Q</h3><div class="accordion-content">A</div></div>
|
||||
// Use regex looking forward to next item or end of string
|
||||
const itemSplitRegex = /<(?:div|article|section|li)[^>]*class=["'][^"']*(?:faq-item|accordion-item|faq-box|qa-item)[^"']*["'][^>]*>/gi;
|
||||
const itemIndices: number[] = [];
|
||||
let itemMatch;
|
||||
while ((itemMatch = itemSplitRegex.exec(html)) !== null) {
|
||||
itemIndices.push(itemMatch.index);
|
||||
}
|
||||
|
||||
for (let i = 0; i < itemIndices.length; i++) {
|
||||
const start = itemIndices[i];
|
||||
const end = i + 1 < itemIndices.length ? itemIndices[i + 1] : html.length;
|
||||
const block = html.substring(start, end);
|
||||
|
||||
const qMatch =
|
||||
/<[^>]*class=["'][^"']*(?:question|faq-q|accordion-title|accordion-header|faq-header)[^"']*["'][^>]*>([\s\S]*?)<\/[^>]+>/i.exec(
|
||||
block
|
||||
);
|
||||
const aMatch =
|
||||
/<[^>]*class=["'][^"']*(?:answer|faq-a|accordion-content|accordion-body|faq-body)[^"']*["'][^>]*>([\s\S]*?)<\/[^>]+>/i.exec(
|
||||
block
|
||||
);
|
||||
if (qMatch && aMatch) {
|
||||
const question = qMatch[1].replace(/<[^>]+>/g, '').trim();
|
||||
const answer = aMatch[1].replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
if (question && answer && !faqs.some((f) => f.question === question)) {
|
||||
faqs.push({ question, answer });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Headings with questions followed immediately by paragraph answers:
|
||||
// e.g. <h2>پرسش: آیا این مکمل برای سگ مفید است؟</h2> <p>بله، کاملاً مفید است.</p>
|
||||
const headingRegex = /<h[2-4][^>]*>([\s\S]*?)<\/h[2-4]>\s*<p[^>]*>([\s\S]*?)<\/p>/gi;
|
||||
let headingMatch;
|
||||
while ((headingMatch = headingRegex.exec(html)) !== null) {
|
||||
const rawHeading = headingMatch[1].replace(/<[^>]+>/g, '').trim();
|
||||
const rawParagraph = headingMatch[2].replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
if (
|
||||
(rawHeading.endsWith('?') ||
|
||||
rawHeading.endsWith('؟') ||
|
||||
/^(?:پرسش|سوال|سؤال|آیا|چگونه|چرا|چه|کدام)\s*[:؛-]?/i.test(rawHeading)) &&
|
||||
rawParagraph.length > 5
|
||||
) {
|
||||
if (!faqs.some((f) => f.question === rawHeading)) {
|
||||
faqs.push({ question: rawHeading, answer: rawParagraph });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return faqs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a Schema.org FAQPage structured data entity if valid FAQs exist.
|
||||
*/
|
||||
export function generateFAQPageSchema(faqs: FAQItem[]) {
|
||||
if (!faqs || faqs.length === 0) return null;
|
||||
return {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'FAQPage',
|
||||
mainEntity: faqs.map((faq) => ({
|
||||
'@type': 'Question',
|
||||
name: faq.question,
|
||||
acceptedAnswer: {
|
||||
'@type': 'Answer',
|
||||
text: faq.answer,
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Lalezar } from 'next/font/google';
|
||||
import localFont from 'next/font/local';
|
||||
|
||||
export const vazirmatn = localFont({
|
||||
@@ -14,10 +13,16 @@ export const vazirmatn = localFont({
|
||||
preload: true,
|
||||
});
|
||||
|
||||
export const lalezar = Lalezar({
|
||||
weight: '400',
|
||||
subsets: ['arabic'],
|
||||
export const lalezar = localFont({
|
||||
src: [
|
||||
{
|
||||
path: '../public/fonts/Lalezar-Regular.woff2',
|
||||
weight: '400',
|
||||
style: 'normal',
|
||||
},
|
||||
],
|
||||
variable: '--font-lalezar',
|
||||
display: 'swap',
|
||||
preload: false,
|
||||
fallback: ['cursive', 'system-ui', 'sans-serif'],
|
||||
preload: true,
|
||||
});
|
||||
Binary file not shown.
Reference in new issue
Block a user