Skip to content

Commit

Permalink
Generate OG images as WebP (#7940)
Browse files Browse the repository at this point in the history
  • Loading branch information
delucis committed May 6, 2024
1 parent 42acee5 commit 0620640
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 48 deletions.
4 changes: 2 additions & 2 deletions package.json
Expand Up @@ -41,9 +41,9 @@
"astro": "^4.6.3",
"astro-auto-import": "^0.4.2",
"astro-eslint-parser": "^0.16.0",
"astro-og-canvas": "^0.4.1",
"astro-og-canvas": "^0.5.0",
"bcp-47-normalize": "^2.1.0",
"canvaskit-wasm": "^0.37.0",
"canvaskit-wasm": "^0.39.1",
"dedent-js": "^1.0.1",
"domhandler": "^4.3.1",
"eslint": "^8.29.0",
Expand Down
96 changes: 51 additions & 45 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions src/pages/open-graph/[...path].ts
Expand Up @@ -19,9 +19,18 @@ export const { getStaticPaths, GET } = OGImageRoute({

pages,

getSlug(path) {
path = path.replace(/^\/src\/pages\//, '');
path = path.replace(/\.[^.]*$/, '') + '.webp';
path = path.replace(/\/index\.webp$/, '.webp');
return path;
},

getImageOptions: async (_, { data, slug }: (typeof pages)[string]): Promise<OGImageOptions> => {
const isRtl = rtlLanguages.has(getLangFromSlug(slug));
return {
format: 'WEBP',
quality: 90,
title: data.title,
description: data.description,
dir: isRtl ? 'rtl' : 'ltr',
Expand Down
2 changes: 1 addition & 1 deletion src/util/getOgImageUrl.ts
Expand Up @@ -13,7 +13,7 @@ const paths = new Set(routes.map(({ params }) => params.path));
* @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';
let imagePath = path.replace(/^\//, '').replace(/\/$/, '') + '.webp';
if (isFallback) {
// Replace the language segment with 'en' for fallback pages.
imagePath = 'en' + imagePath.slice(imagePath.indexOf('/'));
Expand Down

0 comments on commit 0620640

Please sign in to comment.