1 "use client"
2
3 import React, { useEffect, useState } from "react"
4 import type { TechArticle } from "schema-dts"
5 import { getJsonLd } from "../../utils"
6 import { usePathname } from "next/navigation"
7 import { useSiteConfig } from "../../providers/SiteConfig"
8 import { useIsBrowser } from "../../providers/BrowserProvider"
9
10 export const TechArticleJsonLd = () => {
11 const {
12 config: { baseUrl, basePath, description: configDescription, titleSuffix },
13 frontmatter,
14 } = useSiteConfig()
15 const pathname = usePathname()
16 const { isBrowser } = useIsBrowser()
17 const [jsonLdData, setJsonLdData] = useState("{}")
18
19 useEffect(() => {
20 if (!isBrowser) {
21 return
22 }
23
24 const updateJsonLd = () => {
25 const baseLink = `${baseUrl}${basePath}`.replace(/\/+$/, "")
26 const title = document.title.replace(` - ${titleSuffix}`, "")
27 const description =
28 document.querySelector("#main p")?.textContent ||
29 configDescription ||
30 ""
31
32 const data = getJsonLd<TechArticle>({
33 "@context": "https://schema.org",
34 "@type": "TechArticle",
35 headline: title,
36 description,
37 proficiencyLevel: "Expert",
38 author: "Medusa",
39 genre: "Documentation",
40 keywords:
41 frontmatter.keywords?.join(", ") || "medusa, ecommerce, open-source",
42 url: `${baseLink}${pathname}`,
43 })
44
45 setJsonLdData(data)
46 }
47
48 // Update immediately
49 updateJsonLd()
50
51 // Also set up a MutationObserver to watch for title changes
52 const titleObserver = new MutationObserver(() => {
53 updateJsonLd()
54 })
55
56 const titleElement = document.querySelector("title")
57 if (titleElement) {
58 titleObserver.observe(titleElement, {
59 childList: true,
60 characterData: true,
61 subtree: true,
62 })
63 }
64
65 return () => {
66 titleObserver.disconnect()
67 }
68 }, [isBrowser, pathname, baseUrl, basePath, configDescription, titleSuffix])
69
70 return (
71 <script
72 type="application/ld+json"
73 dangerouslySetInnerHTML={{ __html: jsonLdData }}
74 />
75 )
76 }