Files
aramesh-backend/frontend/src/seo.ts
T

162 lines
7.5 KiB
TypeScript

// تگ‌های سئوی سمت مرورگر — عنوان، توضیح متا، OG، توییتر، canonical، hreflang و JSON-LD.
// محتوا از دیتابیس می‌آید؛ برای خزنده‌های بدون جاوااسکریپت، بک‌اند همان تگ‌ها را
// سمت سرور داخل index.html تزریق می‌کند (app/seo_pages.py) و JSON-LD صفحه داخل
// همون <script id="seo-jsonld"> بازنویسی می‌شود — نسخهٔ تکراری ساخته نمی‌شود.
import { localeHref, langFromPathname } from './i18n/lang'
import type { Lang } from './i18n/lang'
/** تصویر پیش‌فرض شبکه‌های اجتماعی — وقتی صفحه تصویر اختصاصی ندارد */
export const DEFAULT_OG_IMAGE = '/og-default.jpg'
export function setMetaDescription(content: string): void {
// بدون توضیح از دیتابیس، پیش‌فرض استاتیک index.html دست‌نخورده می‌ماند
if (!content.trim()) return
let el = document.querySelector<HTMLMetaElement>('meta[name="description"]')
if (!el) {
el = document.createElement('meta')
el.setAttribute('name', 'description')
document.head.appendChild(el)
}
el.setAttribute('content', content.trim())
}
/** کلید سئوی مسیر جاری — فقط صفحه‌های فهرست دقیق؛ صفحه‌های جزئیات خودشان عنوان می‌گذارند */
export function seoKeyForPath(pathname: string): string | null {
// زبان از پیشوند /en جدا می‌شود — کلیدهای سئو برای هر دو زبان یکی است
const clean = pathname === '/en' ? '/' : pathname.startsWith('/en/') ? pathname.slice(3) : pathname
if (clean === '/') return 'home'
const seg = clean.split('/')[1] ?? ''
const known = ['about', 'services', 'projects', 'investment', 'blog', 'faq', 'contact']
// مسیرهای جزئی مثل /blog/{slug} شامل نمی‌شوند تا اثر خود صفحه جزئیات برسانند
return known.includes(seg) && clean === `/${seg}` ? seg : null
}
function upsertMeta(attr: 'name' | 'property', key: string, content: string): void {
let el = document.querySelector<HTMLMetaElement>(`meta[${attr}="${key}"]`)
if (!el) {
el = document.createElement('meta')
el.setAttribute(attr, key)
document.head.appendChild(el)
}
el.setAttribute('content', content)
}
function removeMeta(attr: 'name' | 'property', key: string): void {
document.querySelector<HTMLMetaElement>(`meta[${attr}="${key}"]`)?.remove()
}
function upsertCanonical(path: string): void {
let el = document.querySelector<HTMLLinkElement>('link[rel="canonical"]')
if (!el) {
el = document.createElement('link')
el.setAttribute('rel', 'canonical')
document.head.appendChild(el)
}
el.setAttribute('href', new URL(path, window.location.origin).href)
}
/** لینک alternate با hreflang مشخص را حذف می‌کند — وقتی ترجمه‌ای وجود ندارد */
function removeAlternate(hreflang: string): void {
document.querySelector<HTMLLinkElement>(`link[data-hreflang="${hreflang}"]`)?.remove()
}
/** لینک‌های alternate دو زبانه — مسیر جاری و معادل آن در زبان دیگر.
* مجموعهٔ کامل (fa/en/x-default) فقط وقتی اعلام می‌شود که ترجمهٔ انگلیسی واقعاً
* وجود داشته باشد؛ مجموعهٔ ناسازگار کل hreflang را بی‌اعتبار می‌کند. */
function upsertAlternates(path: string, lang: Lang, hasEn: boolean): void {
// صفحهٔ انگلیسیِ ترجمه‌نشده هیچ ادعایی ندارد؛ صفحهٔ فارسی فقط خودش و x-default
const targets: [Lang, string][] = hasEn
? [['fa', 'fa'], ['en', 'en'], ['fa', 'x-default']]
: lang === 'fa'
? [['fa', 'fa'], ['fa', 'x-default']]
: []
if (!hasEn) removeAlternate('en')
for (const [targetLang, hreflang] of targets) {
// x-default همیشه نسخه فارسی است
const target = localeHref(path, targetLang)
const attr = `data-hreflang="${hreflang}"`
let el = document.querySelector<HTMLLinkElement>(`link[${attr}]`)
if (!el) {
el = document.createElement('link')
el.setAttribute('rel', 'alternate')
el.setAttribute('hreflang', hreflang)
el.setAttribute('data-hreflang', hreflang)
document.head.appendChild(el)
}
el.setAttribute('href', new URL(target, window.location.origin).href)
}
}
function setJsonLd(data: Record<string, unknown> | Record<string, unknown>[] | null): void {
const id = 'seo-jsonld'
let el = document.getElementById(id)
if (!data || (Array.isArray(data) && data.length === 0)) {
el?.remove()
return
}
if (!el) {
el = document.createElement('script')
el.setAttribute('type', 'application/ld+json')
el.id = id
document.head.appendChild(el)
}
el.textContent = JSON.stringify(data)
}
export type SeoInput = {
title: string
description?: string
/** مسیر canonical — پیش‌فرض مسیر جاری مرورگر */
path?: string
/** تصویر OG — مسیر نسبی مثل /media/... به آدرس مطلق تبدیل می‌شود؛ بدون آن تصویر پیش‌فرض برند */
image?: string
type?: 'website' | 'article'
/** زبان جاری — برای og:locale و لینک‌های hreflang */
lang?: Lang
/** آیا ترجمهٔ انگلیسی همین صفحه واقعاً وجود دارد؟ (پیش‌فرض: بله — مثل رفتار قبلی) */
hasEn?: boolean
/** اسکیمای JSON-LD — یک شیء یا آرایه‌ای از چند اسکیما (مثل Article + Breadcrumb + FAQPage) */
jsonLd?: Record<string, unknown> | Record<string, unknown>[] | null
}
/** تنظیم همه تگ‌های سئوی صفحه در یک فراخوانی */
export function applySeo(input: SeoInput): void {
const title = input.title.trim()
const description = (input.description ?? '').trim()
const path = input.path ?? window.location.pathname
const image = (input.image ?? '').trim()
const hasEn = input.hasEn ?? true
const lang: Lang = input.lang ?? langFromPathname(path)
document.title = title
setMetaDescription(description)
upsertCanonical(path)
upsertMeta('property', 'og:title', title)
upsertMeta('property', 'og:description', description)
upsertMeta('property', 'og:type', input.type ?? 'website')
upsertMeta('property', 'og:url', new URL(path, window.location.origin).href)
upsertMeta('property', 'og:locale', lang === 'en' ? 'en_US' : 'fa_IR')
upsertMeta('property', 'og:locale:alternate', lang === 'en' ? 'fa_IR' : 'en_US')
upsertMeta('name', 'twitter:card', 'summary_large_image')
upsertMeta('name', 'twitter:title', title)
upsertMeta('name', 'twitter:description', description)
// تصویر OG — تصویر اختصاصی صفحه یا تصویر پیش‌فرض برند
{
const ogImage = new URL(image || DEFAULT_OG_IMAGE, window.location.origin).href
upsertMeta('property', 'og:image', ogImage)
upsertMeta('name', 'twitter:image', ogImage)
upsertMeta('property', 'og:image:alt', title)
if (image) {
// ابعاد فقط برای تصویر پیش‌فرض قطعی است؛ تصویر اختصاصی ابعاد متغیر دارد
removeMeta('property', 'og:image:width')
removeMeta('property', 'og:image:height')
} else {
upsertMeta('property', 'og:image:width', '1200')
upsertMeta('property', 'og:image:height', '630')
}
}
upsertAlternates(path, lang, hasEn)
setJsonLd(input.jsonLd ?? null)
}