Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/util/getOgImageUrl.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, it, vi } from 'vitest';
import { getOgImageUrl } from './getOgImageUrl';

// `getOgImageUrl` looks a derived filename up in the set of images
// astro-og-canvas actually generated, which comes from the content collection
// and so needs the Astro build pipeline. Stub that set and test the derivation
// — the half where the homepage bug was.
vi.mock('../pages/open-graph/[...path]', () => ({
getStaticPaths: async () => [
{ params: { path: 'index.png' } },
{ params: { path: 'merge-queue.png' } },
],
}));

describe('getOgImageUrl', () => {
it('resolves the homepage to the index image', () => {
// Regression: stripping the slashes off `/` left an empty slug, so the
// homepage was the one page that shipped an empty `og:image`.
expect(getOgImageUrl('/')).toBe('/open-graph/index.png');
});

it('resolves a normal page, with or without a trailing slash', () => {
expect(getOgImageUrl('/merge-queue')).toBe('/open-graph/merge-queue.png');
expect(getOgImageUrl('/merge-queue/')).toBe('/open-graph/merge-queue.png');
});

it('returns undefined when no image was generated', () => {
expect(getOgImageUrl('/not-a-page')).toBeUndefined();
});
});
6 changes: 5 additions & 1 deletion src/util/getOgImageUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ const paths = new Set(routes.map(({ params }) => params.path));
* @returns Path to the OpenGraph image if found. Otherwise, `undefined`.
*/
export function getOgImageUrl(path: string): string | undefined {
const imagePath = path.replace(/^\//, '').replace(/\/$/, '') + '.png';
// The homepage's collection id is `index`, so stripping its slashes leaves an
// empty string and the lookup misses — which is why the homepage shipped with
// an empty `og:image` while every other page had one.
const slug = path.replace(/^\//, '').replace(/\/$/, '') || 'index';
const imagePath = slug + '.png';
if (paths.has(imagePath)) return '/open-graph/' + imagePath;
Comment thread
jd marked this conversation as resolved.
}