Skip to content

Commit 0e02c09

Browse files
committed
feat: export useContentHead for seo header
1 parent 99f25df commit 0e02c09

File tree

5 files changed

+126
-7
lines changed

5 files changed

+126
-7
lines changed

src/module.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ export default defineNuxtModule<ModuleOptions>({
115115
{ name: 'queryCollectionSearchSections', from: resolver.resolve('./runtime/app') },
116116
{ name: 'queryCollectionNavigation', from: resolver.resolve('./runtime/app') },
117117
{ name: 'queryCollectionItemSurroundings', from: resolver.resolve('./runtime/app') },
118+
{ name: 'useContentHead', from: resolver.resolve('./runtime/app') },
118119
])
119120
addServerImports([
120121
{ name: 'queryCollectionWithEvent', as: 'queryCollection', from: resolver.resolve('./runtime/nitro') },
@@ -145,7 +146,6 @@ export default defineNuxtModule<ModuleOptions>({
145146
config.handlers.push({
146147
route: '/api/content/:collection/query',
147148
handler: resolver.resolve('./runtime/api/query.post'),
148-
method: 'POST',
149149
})
150150
})
151151

src/runtime/app.ts

Lines changed: 111 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import type { Collections, PageCollections, CollectionQueryBuilder, SurroundOptions } from '@nuxt/content'
1+
import type { Collections, PageCollections, CollectionQueryBuilder, SurroundOptions, PageCollectionItemBase } from '@nuxt/content'
2+
import { hasProtocol, withTrailingSlash, withoutTrailingSlash, joinURL } from 'ufo'
23
import { collectionQureyBuilder } from './internal/query'
34
import { measurePerformance } from './internal/performance'
45
import { generateNavigationTree } from './internal/navigation'
56
import { generateItemSurround } from './internal/surround'
67
import { generateSearchSections } from './internal/search'
78
import { fetchQuery } from './internal/api'
8-
import { tryUseNuxtApp } from '#imports'
9+
import { tryUseNuxtApp, useRuntimeConfig, useRoute, useHead } from '#imports'
910

1011
export const queryCollection = <T extends keyof Collections>(collection: T): CollectionQueryBuilder<Collections[T]> => {
1112
return collectionQureyBuilder<T>(collection, (collection, sql) => executeContentQuery(collection, sql))
@@ -45,3 +46,111 @@ async function queryContentSqlClientWasm<T extends keyof Collections, Result = C
4546

4647
return rows as Result[]
4748
}
49+
50+
export const useContentHead = (content: PageCollectionItemBase | null, { host, trailingSlash }: { host?: string, trailingSlash?: boolean } = {}) => {
51+
if (!content) {
52+
return
53+
}
54+
55+
const config = useRuntimeConfig()
56+
const route = useRoute()
57+
// Default head to `data?.seo`
58+
const head = Object.assign({} as unknown as Exclude<PageCollectionItemBase['seo'], undefined>, content?.seo || {})
59+
60+
head.meta = [...(head.meta || [])]
61+
head.link = [...(head.link || [])]
62+
63+
// Great basic informations from the content
64+
const title = head.title || content?.title
65+
if (title) {
66+
head.title = title
67+
if (import.meta.server && !head.meta?.some(m => m.property === 'og:title')) {
68+
head.meta.push({
69+
property: 'og:title',
70+
content: title as string,
71+
})
72+
}
73+
}
74+
75+
if (import.meta.server && host) {
76+
const _url = joinURL(host ?? '/', config.app.baseURL, route.fullPath)
77+
const url = trailingSlash ? withTrailingSlash(_url) : withoutTrailingSlash(_url)
78+
if (!head.meta.some(m => m.property === 'og:url')) {
79+
head.meta.push({
80+
property: 'og:url',
81+
content: url,
82+
})
83+
}
84+
if (!head.link.some(m => m.rel === 'canonical')) {
85+
head.link.push({
86+
rel: 'canonical',
87+
href: url,
88+
})
89+
}
90+
}
91+
92+
// Grab description from `head.description` or fallback to `data.description`
93+
const description = head?.description || content?.description
94+
95+
// Shortcut for head.description
96+
if (description && head.meta.filter(m => m.name === 'description').length === 0) {
97+
head.meta.push({
98+
name: 'description',
99+
content: description,
100+
})
101+
}
102+
if (import.meta.server && description && !head.meta.some(m => m.property === 'og:description')) {
103+
head.meta.push({
104+
property: 'og:description',
105+
content: description,
106+
})
107+
}
108+
109+
// Grab description from `head` or fallback to `data.description`
110+
const image = head?.image || content?.image
111+
112+
// Shortcut for head.image to og:image in meta
113+
if (image && head.meta.filter(m => m.property === 'og:image').length === 0) {
114+
// Handles `image: '/image/src.jpg'`
115+
if (typeof image === 'string') {
116+
head.meta.push({
117+
property: 'og:image',
118+
content: host && !hasProtocol(image) ? new URL(joinURL(config.app.baseURL, image), host).href : image,
119+
})
120+
}
121+
122+
// Handles: `image.src: '/image/src.jpg'` & `image.alt: 200`...
123+
if (typeof image === 'object') {
124+
// https://ogp.me/#structured
125+
const imageKeys = [
126+
'src',
127+
'secure_url',
128+
'type',
129+
'width',
130+
'height',
131+
'alt',
132+
]
133+
134+
// Look on available keys
135+
for (const key of imageKeys) {
136+
// `src` is a shorthand for the URL.
137+
if (key === 'src' && image.src) {
138+
const isAbsoluteURL = hasProtocol(image.src)
139+
const imageURL = isAbsoluteURL ? image.src : joinURL(config.app.baseURL, image.src ?? '/')
140+
head.meta.push({
141+
property: 'og:image',
142+
content: host && !isAbsoluteURL ? new URL(imageURL, host).href : imageURL,
143+
})
144+
}
145+
else if (image[key]) {
146+
head.meta.push({
147+
property: `og:image:${key}`,
148+
content: image[key],
149+
})
150+
}
151+
}
152+
}
153+
}
154+
155+
useHead(head)
156+
}

src/types/collection.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,11 @@ export interface PageCollectionItemBase extends CollectionItemBase {
8080
path: string
8181
title: string
8282
description: string
83-
seo?: {
84-
title: string
85-
description: string
83+
seo: {
84+
title?: string
85+
description?: string
86+
meta?: Array<Partial<Record<'id' | 'name' | 'property' | 'content', string>>>
87+
link?: Array<Partial<Record<'color' | 'rel' | 'href' | 'hreflang' | 'imagesizes' | 'imagesrcset' | 'integrity' | 'media' | 'sizes' | 'id', string>>>
8688

8789
[key: string]: unknown
8890
}

src/utils/schema.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,11 @@ export const pageSchema = z.object({
1717
z.object({
1818
title: z.string().optional(),
1919
description: z.string().optional(),
20+
meta: z.array(z.record(z.string(), z.any())).optional(),
21+
link: z.array(z.record(z.string(), z.any())).optional(),
2022
}),
2123
z.record(z.string(), z.any()),
22-
).optional(),
24+
).optional().default({}),
2325
body: z.object({
2426
type: z.string(),
2527
children: z.any(),

src/utils/templates.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ export const fullDatabaseCompressedDumpTemplate = (manifest: Manifest) => ({
8484
filename: moduleTemplates.fullCompressedDump,
8585
getContents: ({ options }: { options: { manifest: Manifest } }) => {
8686
return Object.entries(options.manifest.dump).map(([key, value]) => {
87+
const collection = options.manifest.collections.find(c => c.name === key)
88+
// Ignore provate collections
89+
if (collection?.private) {
90+
return ''
91+
}
92+
8793
const str = Buffer.from(deflate(value.join('\n')).buffer).toString('base64')
8894
return `export const ${key} = "${str}"`
8995
}).join('\n')

0 commit comments

Comments
 (0)