Skip to content

Commit

Permalink
Add dynamic og:image generation.
Browse files Browse the repository at this point in the history
  • Loading branch information
MrAlex94 committed Oct 31, 2023
1 parent c07721d commit 5167b2f
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 1 deletion.
3 changes: 2 additions & 1 deletion astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import starlight from '@astrojs/starlight'
import { defineConfig } from 'astro/config'
import blog from 'starlight-blog'
import svelte from '@astrojs/svelte'

import tailwind from '@astrojs/tailwind'

// https://astro.build/config
export default defineConfig({
site: 'https://www.waterfox.net',
integrations: [
blog({
authors: {
Expand All @@ -20,6 +20,7 @@ export default defineConfig({
}),
starlight({
components: {
Head: '~/components/Head.astro',
Header: '~/components/Header.astro',
MarkdownContent: 'starlight-blog/overrides/MarkdownContent.astro',
PageFrame: '~/components/CustomPageFrame.astro',
Expand Down
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@astrojs/tailwind": "^5.0.2",
"@tailwindcss/typography": "^0.5.10",
"astro": "^3.4.0",
"astro-og-canvas": "^0.2.1",
"clipboard": "^2.0.11",
"sass": "^1.69.5",
"sharp": "^0.32.6",
Expand Down
Binary file added public/default-og-image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/assets/waterfox-logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 13 additions & 0 deletions src/components/Head.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
import Default from '@astrojs/starlight/components/Head.astro'
import type { Props } from '@astrojs/starlight/props'
import { getOgImageUrl } from '~/utils/getOgImageUrl'
const { entry } = Astro.props
const ogImageUrl = getOgImageUrl(entry.slug, !!Astro.params.fallback)
const imageSrc = ogImageUrl ?? '/default-og-image.png?v=1'
const canonicalImageSrc = new URL(imageSrc, Astro.site)
---

<Default {...Astro.props}><slot /></Default>
<meta property="og:image" content={canonicalImageSrc} />
<meta name="twitter:image" content={canonicalImageSrc} />
56 changes: 56 additions & 0 deletions src/pages/open-graph/[...path].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { OGImageRoute } from 'astro-og-canvas'
import { getCollection } from 'astro:content'
import { join, resolve } from 'node:path'
import { writeFile } from 'node:fs'

const allPages = await getCollection('docs', (entry) => {
return true
})

// fs.writeFileSync('log.json', JSON.stringify(allPages))

/** Paths for all of our Markdown content we want to generate OG images for. */
const paths = process.env.SKIP_OG ? [] : allPages

/** An object mapping file paths to file metadata. */
const pages = Object.fromEntries(paths.map(({ id, slug, data }) => [id, { data, slug }]))

export const { getStaticPaths, GET } = OGImageRoute({
param: 'path',

pages,

getImageOptions: async (_, { data, slug }: (typeof pages)[string]) => {
return {
title: data.title,
description: data.description,
dir: slug,
logo: {
path: './src/assets/waterfox-logo.png',
size: [400]
},
border: { color: [5, 51, 97], width: 20, side: 'inline-start' },
bgGradient: [
[182, 156, 254],
[123, 165, 255]
],
font: {
title: {
size: 80,
families: ['Montserrat'],
weight: 'Bold'
},
description: {
size: 40,
lineHeight: 1.25,
families: ['Montserrat Thin'],
weight: 'Light'
}
},
fonts: [
'https://github.com/JulietaUla/Montserrat/raw/master/fonts/webfonts/Montserrat-Light.woff2',
'https://github.com/JulietaUla/Montserrat/raw/master/fonts/webfonts/Montserrat-Bold.woff2'
]
}
}
})
21 changes: 21 additions & 0 deletions src/utils/getOgImageUrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { GetStaticPathsOptions, GetStaticPathsResult } from 'astro'
import { getStaticPaths } from './src/pages/open-graph/[...path].ts'

const routes = (await getStaticPaths({} as GetStaticPathsOptions)) as GetStaticPathsResult

/** All the OpenGraph image paths as generated by our `getStaticPaths`. */
const paths = new Set(routes.map(({ params }) => params.path))

/**
* Get the path to the OpenGraph image for a page
* @param path Pathname of the page URL.
* @param isFallback Whether or not this page is displaying fallback content.
* @returns Path to the OpenGraph image if found. Otherwise, `undefined`.
*/
export function getOgImageUrl(path: string, isFallback: boolean): string | undefined {
let imagePath = path.replace(/^\//, '').replace(/\/$/, '') + '.png'
if (isFallback) {
imagePath = imagePath.slice(imagePath.indexOf('/'))
}
if (paths.has(imagePath)) return '/open-graph/' + imagePath
}

0 comments on commit 5167b2f

Please sign in to comment.