Skip to content

Commit

Permalink
add automatically generate OG images (#204)
Browse files Browse the repository at this point in the history
  • Loading branch information
Arhell authored Dec 17, 2024
1 parent f6f2eb8 commit 9b86778
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@octokit/core": "^5.1.0",
"@pagefind/default-ui": "^1.2.0",
"astro": "^4.16.17",
"astro-og-canvas": "^0.5.5",
"astro-rehype-relative-markdown-links": "^0.17.0",
"astro-vtbot": "^1.10.7",
"bunosh": "^0.1.5",
Expand Down
18 changes: 18 additions & 0 deletions src/components/Head.astro
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,30 @@ const article: WithContext<Article> = {
inLanguage: Astro.props.lang,
}
const ogImageUrl = new URL(
`/og/${Astro.props.id.replace(/\.\w+$/, '.png')}`,
Astro.site,
)
const pageAlreadyHasOgImage = Astro.props.entry.data.head.some(
(meta) => meta.tag === 'meta' && meta.attrs['name'] === 'og:image',
)
---

<VtbotStarlight {...Astro.props}>
<StarlightHead {...Astro.props}><slot /></StarlightHead>
</VtbotStarlight>

{!pageAlreadyHasOgImage && (
<>
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image" content={ogImageUrl} />
<meta name="twitter:image" content={ogImageUrl} />
</>
)}

<script>
document.addEventListener("astro:before-swap", (e) => {
document
Expand Down
42 changes: 42 additions & 0 deletions src/pages/og/[...slug].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { getCollection } from 'astro:content'
import { OGImageRoute } from 'astro-og-canvas'

const logoPath = './src/pages/og/logo.png';

const entries = await getCollection('docs')

const pages = Object.fromEntries(entries.map(({ data, id }) => [id, { data }]))

export const { getStaticPaths, GET } = OGImageRoute({
pages,
param: 'slug',
getImageOptions: (_path, page: (typeof pages)[number]) => {
return {
title: page.data.title,
description: page.data.description,
logo: {
path: logoPath,
size: [ 340 ]
},
bgGradient: [
[35, 38, 47],
[40, 43, 51],
],
border: { color: [92, 137, 252], width: 30 },
padding: 40,
font: {
title: {
color: [78, 138, 244],
size: 64,
weight: 'Bold',
},
description: {
color: [255, 255, 255],
size: 38,
lineHeight: 1.25,
weight: 'Normal',
},
},
}
},
})
Binary file added src/pages/og/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 9b86778

Please sign in to comment.