This commit is contained in:
maropboia 2024-05-03 11:38:47 +06:00
parent 99766f9439
commit 228d89ca23

View file

@ -1,12 +1,19 @@
import type { HeadConfig, TransformContext } from 'vitepress'
/**
* Generates meta tags for a given page based on the page's frontmatter and file path.
* @param context - The transform context containing information about the current page.
* @param hostname - The hostname to use for generating URLs.
* @returns An array of HeadConfig objects representing the generated meta tags.
*/
export function generateMeta(context: TransformContext, hostname: string) {
const head: HeadConfig[] = []
const { pageData } = context
const head: HeadConfig[] = [] // Initialize an array to store the generated meta tags
const { pageData } = context // Get the page data from the transform context
// Generate the canonical URL for the page
const url = `${hostname}/${pageData.relativePath.replace(/((^|\/)index)?\.md$/, '$2')}`
head.push(
head.push( // Add meta tags to the head array
['link', { rel: 'canonical', href: url }],
['meta', { property: 'og:url', content: url }],
['meta', { name: 'twitter:url', content: url }],
@ -14,6 +21,8 @@ export function generateMeta(context: TransformContext, hostname: string) {
['meta', { property: 'og:title', content: pageData.frontmatter.title }],
['meta', { name: 'twitter:title', content: pageData.frontmatter.title }]
)
// If the page has a description in its frontmatter, add it to the meta tags
if (pageData.frontmatter.description) {
head.push(
[
@ -32,6 +41,8 @@ export function generateMeta(context: TransformContext, hostname: string) {
]
)
}
// If the page has an image in its frontmatter, add it to the meta tags
if (pageData.frontmatter.image) {
head.push([
'meta',
@ -48,6 +59,7 @@ export function generateMeta(context: TransformContext, hostname: string) {
}
])
} else {
// If no image is provided, generate a default image based on the page's URL
const url = pageData.filePath.replace('index.md', '').replace('.md', '')
const imageUrl = `${url}/__og_image__/og.png`
.replaceAll('//', '/')
@ -71,12 +83,16 @@ export function generateMeta(context: TransformContext, hostname: string) {
]
)
}
// If the page has a tag in its frontmatter, add it to the meta tags
if (pageData.frontmatter.tag) {
head.push([
'meta',
{ property: 'article:tag', content: pageData.frontmatter.tag }
])
}
// If the page has a date in its frontmatter, add it to the meta tags
if (pageData.frontmatter.date) {
head.push([
'meta',
@ -86,15 +102,5 @@ export function generateMeta(context: TransformContext, hostname: string) {
}
])
}
if (pageData.lastUpdated && pageData.frontmatter.lastUpdated !== false) {
head.push([
'meta',
{
property: 'article:modified_time',
content: new Date(pageData.lastUpdated).toISOString()
}
])
}
return head
}
// If the page has a lastUpdated field and it's not explicitly set to false, add the