forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusePageMeta.ts
More file actions
71 lines (63 loc) · 2.28 KB
/
Copy pathusePageMeta.ts
File metadata and controls
71 lines (63 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { useEffect } from "react";
interface PageMetaOptions {
title: string;
description?: string;
ogImage?: string;
/** Canonical URL for the page. Defaults to the current location. */
url?: string;
/** Open Graph object type (e.g. "website", "article"). Defaults to "website". */
type?: string;
}
const SITE_NAME = "Prompt Hash Stellar";
const DEFAULT_DESCRIPTION =
"Buy and sell AI prompts securely on the Stellar blockchain. Wallet-verified access, on-chain ownership.";
const DEFAULT_OG_IMAGE = "/og-image.png";
function setMeta(nameOrProperty: string, content: string, isProperty = false) {
const attr = isProperty ? "property" : "name";
let el = document.querySelector<HTMLMetaElement>(`meta[${attr}="${nameOrProperty}"]`);
if (!el) {
el = document.createElement("meta");
el.setAttribute(attr, nameOrProperty);
document.head.appendChild(el);
}
el.setAttribute("content", content);
}
/** Resolves a relative path to an absolute URL so crawlers receive a usable link. */
function absoluteUrl(value: string): string {
if (/^https?:\/\//i.test(value)) return value;
if (typeof window !== "undefined") {
try {
return new URL(value, window.location.origin).toString();
} catch {
return value;
}
}
return value;
}
export function usePageMeta({ title, description, ogImage, url, type }: PageMetaOptions) {
useEffect(() => {
const fullTitle = `${title} | ${SITE_NAME}`;
const desc = description ?? DEFAULT_DESCRIPTION;
const image = absoluteUrl(ogImage ?? DEFAULT_OG_IMAGE);
const ogType = type ?? "website";
const canonical =
url ?? (typeof window !== "undefined" ? window.location.href : undefined);
document.title = fullTitle;
setMeta("description", desc);
setMeta("og:title", fullTitle, true);
setMeta("og:description", desc, true);
setMeta("og:image", image, true);
setMeta("og:type", ogType, true);
setMeta("og:site_name", SITE_NAME, true);
if (canonical) {
setMeta("og:url", canonical, true);
}
setMeta("twitter:card", "summary_large_image");
setMeta("twitter:title", fullTitle);
setMeta("twitter:description", desc);
setMeta("twitter:image", image);
return () => {
document.title = SITE_NAME;
};
}, [title, description, ogImage, url, type]);
}