fix(blog): represent absent article imagery honestly
Deploy Canina / deploy (push) Successful in 3m12s

This commit is contained in:
Canina Automation committed 2026-10-29 08:10:03 +00:00
1 parent 5642c1609c
commit 18094f91a6
17 files changed
+208 -24

No files matched your search

@@ -32,6 +32,37 @@ describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
vi.unstubAllEnvs();
});
it.each([null, undefined, ' '])('omits absent article imagery (%s) and overrides inherited social images', async (image) => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
slug: 'no-image', title: 'No image', content: '<p>x</p>', imageUrl: image, ogImage: image,
}) }));
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'no-image' }) });
expect((metadata.openGraph as any).images).toEqual([]);
expect(metadata.twitter).toMatchObject({ card: 'summary', images: [] });
expect(metadata.robots).toMatchObject({ index: false });
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'no-image' }) });
const script: any = React.Children.toArray(jsx.props.children)[0];
expect(JSON.parse(script.props.dangerouslySetInnerHTML.__html)).not.toHaveProperty('image');
});
it.each([
['/uploads/article.webp', null, '/uploads/article.webp'],
['/uploads/article.webp', '/uploads/social.webp', '/uploads/social.webp'],
[null, '/uploads/social.webp', '/uploads/social.webp'],
])('retains only authored image/social precedence (%s, %s)', async (imageUrl, ogImage, social) => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
slug: 'image', title: 'Image', imageAlt: 'Authored alt', content: '<p>x</p>', imageUrl, ogImage,
}) }));
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'image' }) });
expect((metadata.openGraph as any).images).toEqual([{ url: social, alt: 'Authored alt' }]);
expect(metadata.twitter).toMatchObject({ card: 'summary_large_image', images: [social] });
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'image' }) });
const script: any = React.Children.toArray(jsx.props.children)[0];
const article = JSON.parse(script.props.dangerouslySetInnerHTML.__html);
if (imageUrl) expect(article.image).toEqual([`https://canina.ir${imageUrl}`]);
else expect(article).not.toHaveProperty('image');
});
it('injects FAQPage JSON-LD schema when article contains questions and answers', async () => {
const blogData = {
slug: 'joint-health',
+6 -12
View File
@@ -81,7 +81,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
(typeof blog.content === 'string' ? blog.content.substring(0, 155).replace(/<[^>]+>/g, '') : '') ||
config.defaultMetaDescription;
const canonicalUrl = blog.canonicalUrl ? blog.canonicalUrl.replace(/\/+$/, '') : `${siteUrl}/blog/${slug}`;
const ogImageUrl = blog.ogImage || blog.imageUrl || config.ogImageUrl;
const ogImageUrl = blog.ogImage?.trim() || blog.imageUrl?.trim();
const ogTitle = blog.ogTitle || title;
const ogDesc = blog.ogDescription || description;
@@ -139,12 +139,8 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
openGraph: {
title: ogTitle,
description: ogDesc,
images: [
{
url: ogImageUrl,
alt: blog.imageAlt || blog.title || title,
},
],
// Explicit empty arrays prevent inheriting the unrelated root image.
images: ogImageUrl ? [{ url: ogImageUrl, alt: blog.imageAlt || blog.title || title }] : [],
url: canonicalUrl,
siteName: config.brandNameFa,
type: "article",
@@ -154,10 +150,10 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
tags: blog.tags?.map((t: any) => typeof t === 'string' ? t : t?.name).filter(Boolean) || [],
},
twitter: {
card: "summary_large_image",
card: ogImageUrl ? "summary_large_image" : "summary",
title: ogTitle,
description: ogDesc,
images: [ogImageUrl],
images: ogImageUrl ? [ogImageUrl] : [],
},
};
}
@@ -207,9 +203,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
},
headline: blog.title,
description: blog.excerpt || blog.metaDescription || blog.title,
image: blog.imageUrl
? [blog.imageUrl.startsWith('http') ? blog.imageUrl : `${siteUrl}${blog.imageUrl.startsWith('/') ? '' : '/'}${blog.imageUrl}`]
: [config.ogImageUrl.startsWith('http') ? config.ogImageUrl : `${siteUrl}${config.ogImageUrl.startsWith('/') ? '' : '/'}${config.ogImageUrl}`],
...(blog.imageUrl?.trim() ? { image: [new URL(blog.imageUrl.trim(), `${siteUrl}/`).href] } : {}),
datePublished: publishedIso,
...(modifiedIso ? { dateModified: modifiedIso } : {}),
author: authorSchema,
@@ -29,5 +29,6 @@ describe("blog page author identity", () => {
const props = blogPageSpy.mock.calls[0][0] as { blogs: Array<{ author: string }> };
expect(props.blogs[0].author).toBe("کنینا");
expect((props.blogs[0] as unknown as { image: string }).image).toBe('');
});
});
+1 -1
View File
@@ -64,7 +64,7 @@ async function getBlogs() {
? new Date(String(b.createdAt)).toLocaleDateString('fa-IR')
: '',
readingTime: b.readingTime || 3,
image: getMediaUrl(String(b.imageUrl || b.coverImage || '/assets/images/blog-placeholder.png')),
image: getMediaUrl(String(b.imageUrl || b.coverImage || '')),
imageAlt: b.imageAlt || b.title,
author: authorName,
content: String(b.content || ''),
@@ -0,0 +1,13 @@
"use client";
import React from "react";
import SafeImage from "./SafeImage";
type BlogImageProps = React.ComponentProps<typeof SafeImage>;
/** An empty blog image slot is not an article photograph or a pending upload. */
export default function BlogImage({ src, className, ...props }: BlogImageProps) {
if (!src?.trim()) {
return <div className={`flex items-center justify-center bg-medical-gray-100 text-medical-gray-500 text-xs ${className || ""}`}>بدون تصویر</div>;
}
return <SafeImage {...props} src={src} className={className} fallbackText="تصویر در دسترس نیست" fallbackAlt="" />;
}
+3 -3
View File
@@ -25,7 +25,7 @@ import { Product } from "../lib/data/products";
import { productService } from "../lib/services/productService";
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import SafeImage from './SafeImage';
import BlogImage from './BlogImage';
import { BLOG_TEAM_FALLBACK, publicationDate, validContentUpdatedAt, persianDate } from '../lib/blogDates';
export interface BlogCategory {
@@ -310,7 +310,7 @@ export default function BlogPage({
className="bg-white rounded-[3.5rem] overflow-hidden border border-medical-gray-200 shadow-2xl flex flex-col lg:flex-row cursor-pointer group hover:border-canina-blue/30 transition-all"
>
<div className="lg:w-1/2 aspect-video lg:aspect-auto relative overflow-hidden bg-medical-gray-100">
<SafeImage
<BlogImage
src={featuredPost.image}
alt={featuredPost.imageAlt || featuredPost.title}
priority
@@ -391,7 +391,7 @@ export default function BlogPage({
>
<div>
<div className="aspect-[16/10] overflow-hidden relative bg-medical-gray-100">
<SafeImage
<BlogImage
src={post.image}
alt={post.imageAlt || post.title}
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
@@ -3,7 +3,7 @@ import React, { useEffect, useState } from "react";
import Link from "next/link";
import { BookOpen, Calendar, Eye, MessageSquare, ArrowLeft } from "lucide-react";
import { motion } from "motion/react";
import SafeImage from "./SafeImage";
import BlogImage from "./BlogImage";
import { useSettingsStore } from "../lib/store/settingsStore";
import api, { BASE_DOMAIN } from "../lib/services/api";
import { toPersian } from "../lib/utils";
@@ -104,11 +104,12 @@ export default function BlogPreviewSection() {
) : (
<div className="flex md:grid md:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-8 overflow-x-auto md:overflow-visible pb-4 md:pb-0 micro-hscroll -mx-4 px-4 md:mx-0 md:px-0 select-none snap-x snap-mandatory md:snap-none overscroll-x-contain">
{blogs.map((blog, idx) => {
const image = blog.imageUrl?.startsWith("http")
? blog.imageUrl
: blog.imageUrl
? `${BASE_DOMAIN}${blog.imageUrl}`
: "/assets/images/blog-placeholder.png";
const imageUrl = blog.imageUrl?.trim();
const image = imageUrl?.startsWith("http")
? imageUrl
: imageUrl
? `${BASE_DOMAIN}${imageUrl}`
: "";
const authorName = resolveBlogAuthor(blog.author);
@@ -126,7 +127,7 @@ export default function BlogPreviewSection() {
className="bg-medical-gray-50/60 rounded-[1.5rem] sm:rounded-[2rem] border border-medical-gray-100 overflow-hidden hover:shadow-lg hover:-translate-y-1 transition-all flex flex-col group w-full"
>
<Link href={blogHref} className="block relative aspect-video w-full overflow-hidden bg-medical-gray-100">
<SafeImage
<BlogImage
src={image}
alt={blog.title}
sizes="(max-width: 768px) 70vw, (max-width: 1200px) 50vw, 33vw"
@@ -12,6 +12,7 @@ interface SafeImageProps extends Omit<React.ImgHTMLAttributes<HTMLImageElement>,
className?: string;
imgClassName?: string;
fallbackText?: string;
fallbackAlt?: string;
priority?: boolean;
sizes?: string;
quality?: number;
@@ -25,6 +26,7 @@ export default function SafeImage({
className,
imgClassName,
fallbackText = "در حال بروزرسانی تصویر...",
fallbackAlt,
priority = false,
sizes = "(max-width: 640px) 200px, (max-width: 1024px) 300px, 400px",
quality = 75,
@@ -64,7 +66,7 @@ export default function SafeImage({
{logoUrl ? (
<Image
src={logoUrl}
alt={alt || "Canina"}
alt={fallbackAlt ?? (alt || "Canina")}
width={80}
height={80}
className="w-12 h-12 object-contain opacity-70 mb-1"
@@ -0,0 +1,22 @@
import React from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import BlogImage from '../BlogImage';
vi.mock('next/image', () => ({ default: ({ priority, unoptimized, ...props }: any) => <img {...props} /> }));
vi.mock('../../lib/store/settingsStore', () => ({ useSettingsStore: (select: any) => select({ getText: () => '/logo.png' }) }));
afterEach(cleanup);
describe('BlogImage', () => {
it.each([undefined, '', ' '])('renders absent image (%s) as neutral text, never article photo', (src) => {
render(<BlogImage src={src} alt="Article title" />);
expect(screen.getByText('بدون تصویر')).toBeDefined();
expect(screen.queryByRole('img')).toBeNull();
});
it('preserves a real authored image and uses decorative logo on load failure, not title alt or updating claim', () => {
render(<BlogImage src="/image.jpg" alt="Authored image" />);
fireEvent.error(screen.getByRole('img', { name: 'Authored image' }));
expect(screen.getByText('تصویر در دسترس نیست')).toBeDefined();
expect(screen.queryByRole('img')).toBeNull();
expect(document.querySelector('img')?.getAttribute('alt')).toBe('');
expect(screen.queryByText(/در حال بروزرسانی/)).toBeNull();
});
});
@@ -20,6 +20,7 @@ const blogs=[{id:'1',slug:'joint',title:'Joint article',excerpt:'Mobility guide'
const categories=[{id:'joints',name:'Joints',slug:'joints'},{id:'skin',name:'Skin',slug:'skin'}];
beforeEach(()=>vi.clearAllMocks());
describe('BlogPage',()=>{
it('shows honest image absence on featured and regular cards without title-alt placeholders',()=>{render(<BlogPage blogs={blogs.map(b=>({...b,image:''}))}/>);expect(screen.getAllByText('بدون تصویر')).toHaveLength(2);expect(screen.queryByRole('img')).not.toBeInTheDocument();expect(screen.queryByText(/در حال بروزرسانی تصویر/)).not.toBeInTheDocument();});
it('renders featured and regular posts as semantic links',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');expect(screen.getByRole('link',{name:/Skin article/})).toHaveAttribute('href','/blog/skin');expect(screen.getByRole('link',{name:/Joint article/})).toHaveAttribute('href','/blog/joint');});
it('labels publication, including a same-day material update, author and stable team on featured and regular cards',()=>{const fresh=[{...blogs[0],publishedAt:'2026-01-01T08:00:00Z',contentUpdatedAt:'2026-01-02T08:00:00Z',authorTeam:'Clinical'}, {...blogs[1],publishedAt:'2026-01-02T08:00:00Z',contentUpdatedAt:'2026-01-02T12:00:00Z'}];render(<BlogPage blogs={fresh} categories={categories}/>);expect(screen.getAllByText(/تاریخ انتشار/)).toHaveLength(2);expect(screen.getAllByText(/آخرین به‌روزرسانی/)).toHaveLength(2);expect(screen.getAllByText(/نویسنده:/)).toHaveLength(2);expect(screen.getByText(/تیم: Clinical/)).toBeInTheDocument();expect(screen.getByText(/تیم: پژوهش و محتوای علمی کنینا/)).toBeInTheDocument();expect(document.querySelectorAll('time[datetime]').length).toBeGreaterThanOrEqual(4);});
it('stacks author and team on separate non-wrapping rows and keeps featured action on one line',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);const featuredMeta=screen.getByTestId('featured-attribution');expect(featuredMeta).toHaveClass('flex-col');expect(screen.getByTestId('featured-read-more')).toHaveClass('whitespace-nowrap');const regularMeta=screen.getByTestId('regular-attribution-1');expect(regularMeta).toHaveClass('flex-col');expect(regularMeta.children).toHaveLength(2);expect(regularMeta.children[0]).toHaveClass('whitespace-nowrap');expect(regularMeta.children[1]).toHaveClass('whitespace-nowrap');});
@@ -123,6 +123,24 @@ describe("BlogPreviewSection Component", () => {
expect(link2).toHaveAttribute("href", "/blog/cat-hair-loss-solutions");
});
it.each([null, undefined, "", " "])(
"renders neutral absence without an img for homepage imageUrl=%j",
async (imageUrl) => {
vi.mocked(api.get).mockResolvedValueOnce({
data: { blogs: [{
id: "no-image", slug: "no-image", title: "مقاله بدون عکس",
content: "", viewCount: 0, createdAt: "2026-01-01T00:00:00Z", imageUrl,
}] },
});
const { container } = render(<BlogPreviewSection />);
expect(await screen.findByText("مقاله بدون عکس")).toBeInTheDocument();
expect(screen.getByText("بدون تصویر")).toBeInTheDocument();
expect(container.querySelector("img")).toBeNull();
expect(api.get).toHaveBeenCalledWith("/blogs/homepage");
},
);
it("uses publication freshness and explicit byline labels on homepage cards", async () => {
vi.mocked(api.get).mockResolvedValueOnce({ data: { blogs: [{ id:"b",slug:"b",title:"B",content:"",viewCount:0,createdAt:"2026-01-01T00:00:00Z",publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-02T00:00:00Z",authorTeam:"Science" }] } });
render(<BlogPreviewSection />);