%PDF- %PDF-
| Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/hooks/ |
| Current File : //home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/hooks/useSEO.ts |
import { useEffect } from "react";
const SITE_NAME = "KURNIADEV AI";
const BASE_URL = "https://rezakurnia.com";
interface SEOOptions {
title?: string;
description?: string;
/** Path canonical relatif, mis. "/", "/login". */
canonicalPath?: string;
ogType?: string;
image?: string;
/** Objek Schema.org (JSON-LD) — null/undefined untuk hapus. */
jsonLd?: object | null;
}
function ensureMeta(attr: "name" | "property", key: string, content: string) {
let el = document.head.querySelector<HTMLMetaElement>(`meta[${attr}="${key}"]`);
if (!el) {
el = document.createElement("meta");
el.setAttribute(attr, key);
document.head.appendChild(el);
}
el.setAttribute("content", content);
}
/**
* Kelola tag SEO per halaman (SPA): title, description, Open Graph,
* Twitter card, canonical, dan JSON-LD — tanpa dependency tambahan.
*/
export function useSEO({
title,
description = "",
canonicalPath = "/",
ogType = "website",
image = `${BASE_URL}/logo-kd.png`,
jsonLd = null,
}: SEOOptions = {}) {
useEffect(() => {
const prevTitle = document.title;
const fullTitle = title ? `${title} — ${SITE_NAME}` : SITE_NAME;
document.title = fullTitle;
ensureMeta("name", "description", description);
ensureMeta("property", "og:title", fullTitle);
ensureMeta("property", "og:description", description);
ensureMeta("property", "og:type", ogType);
ensureMeta("property", "og:url", `${BASE_URL}${canonicalPath}`);
ensureMeta("property", "og:image", image);
ensureMeta("property", "og:site_name", SITE_NAME);
ensureMeta("name", "twitter:card", "summary_large_image");
ensureMeta("name", "twitter:title", fullTitle);
ensureMeta("name", "twitter:description", description);
let canonical = document.head.querySelector<HTMLLinkElement>(
'link[rel="canonical"]',
);
if (!canonical) {
canonical = document.createElement("link");
canonical.rel = "canonical";
document.head.appendChild(canonical);
}
canonical.href = `${BASE_URL}${canonicalPath}`;
const ldId = "jsonld-page";
let ld = document.getElementById(ldId) as HTMLScriptElement | null;
if (jsonLd) {
if (!ld) {
ld = document.createElement("script");
ld.type = "application/ld+json";
ld.id = ldId;
document.head.appendChild(ld);
}
ld.textContent = JSON.stringify(jsonLd);
} else if (ld) {
ld.remove();
}
return () => {
document.title = prevTitle;
};
}, [title, description, canonicalPath, ogType, image, jsonLd]);
}