Skip to content
Merged
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
4 changes: 0 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,6 @@ yarn-error.log*
.env*.local
!.env.example

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
Expand All @@ -45,7 +42,6 @@ next-env.d.ts
# turbo cache
.turbo

.vercel

# cloudflare
.open-next
Expand Down
1 change: 0 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ node_modules
out
dist
.turbo
.vercel
.open-next
.wrangler
pnpm-lock.yaml
Expand Down
7 changes: 3 additions & 4 deletions apps/docs/app/[[...slug]]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { compileMdxFile, createPageMetadata, DocsPage, DocsPager, LandingLayout } from 'docora';
import { compileMdxFile, DocsPage, DocsPager, LandingLayout } from 'docora';
import { LandingPage } from '@/components/landing/landing-page';
import { DocsShell } from '@/components/layout/docs-shell';
import { mdxComponents } from '@/components/mdx/registry-components';
import docsConfig from '@/docs.config';
import { fetchStarCount } from '@/lib/github';
import {
docPageMetadata,
registryEntryForSlug,
registryJsonLd,
registryPageMetadata,
Expand Down Expand Up @@ -37,9 +38,7 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>
if (!page) return {};

const entry = registryEntryForSlug(slug);
return entry
? registryPageMetadata(entry, page)
: createPageMetadata({ config: docsConfig, page });
return entry ? registryPageMetadata(entry, page) : docPageMetadata(page);
}

const Page = async ({ params }: PageProps) => {
Expand Down
23 changes: 23 additions & 0 deletions apps/docs/app/og/[...slug]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { listOgImagePages } from '@/lib/og-image/og-image-pages';
import { ogImagePath } from '@/lib/og-image/og-image-params';
import { renderOgImage } from '@/lib/og-image/render-og-image';

type OgImageContext = Readonly<{
params: Promise<{ slug: string[] }>;
}>;

export const dynamic = 'force-static';
export const dynamicParams = false;

export async function generateStaticParams() {
const pages = await listOgImagePages();
return pages.map((page) => ({ slug: ogImagePath(page.path).split('/').slice(2) }));
}

export async function GET(_request: Request, { params }: OgImageContext) {
const imagePath = `/og/${(await params).slug.join('/')}`;
const pages = await listOgImagePages();
const page = pages.find((candidate) => ogImagePath(candidate.path) === imagePath);
if (!page) return new Response('Not found', { status: 404 });
return renderOgImage(page.params);
}
6 changes: 0 additions & 6 deletions apps/docs/app/og/route.tsx

This file was deleted.

2 changes: 1 addition & 1 deletion apps/docs/config/site.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export const siteConfig = {
name: 'Tween UI',
url: 'https://tween-ui.staticmania.com',
ogImage: 'https://tween-ui.staticmania.com/og',
ogImage: 'https://tween-ui.staticmania.com/og/index.png',
description: 'GSAP & CSS animated components for React. Copy the source, own the animation.',
links: {
github: 'https://github.com/StaticMania/tween-ui',
Expand Down
24 changes: 21 additions & 3 deletions apps/docs/lib/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createPageMetadata, createRootMetadata } from 'docora';
import { siteConfig } from '@/config/site';
import docsConfig from '@/docs.config';
import { buildOgImageUrl } from '@/lib/og-image/og-image-params';
import { OG_IMAGE_SIZE } from '@/lib/og-image/og-theme';
import { getEntry, hrefFor } from '@/registry/index';
import type { RegistryEntry } from '@/registry/schema';

Expand Down Expand Up @@ -68,8 +69,13 @@ export function registryKeywords(entry: RegistryEntry): string[] {

/** Site-wide defaults for the root layout: docora's base plus icons and crawl rules. */
export function rootMetadata(): Metadata {
const base = createRootMetadata(docsConfig);
const ogImage = buildOgImageUrl('/');

return {
...createRootMetadata(docsConfig),
...base,
openGraph: { ...base.openGraph, images: [{ url: ogImage, ...OG_IMAGE_SIZE }] },
twitter: { ...base.twitter, images: [ogImage] },
applicationName: siteConfig.name,
keywords: [...siteConfig.keywords],
authors: [{ name: siteConfig.name, url: siteConfig.links.github }],
Expand Down Expand Up @@ -114,7 +120,7 @@ export function registryPageMetadata(
const base = createPageMetadata({ config: docsConfig, page });
const description = clampDescription(entry.description);
const title = `${entry.title} — Animated React ${kindLabel(entry)}`;
const ogImage = buildOgImageUrl({ title: entry.title, description, kind: entry.type });
const ogImage = buildOgImageUrl(hrefFor(entry));

return {
...base,
Expand All @@ -127,7 +133,7 @@ export function registryPageMetadata(
title,
description,
url: absolute(hrefFor(entry)),
images: [{ url: ogImage, width: 1200, height: 630, alt: title }],
images: [{ url: ogImage, ...OG_IMAGE_SIZE, alt: title }],
},
twitter: {
...base.twitter,
Expand All @@ -138,6 +144,18 @@ export function registryPageMetadata(
};
}

/** Metadata for a plain docs page, pointing its share image at the prebuilt PNG. */
export function docPageMetadata(page: Parameters<typeof createPageMetadata>[0]['page']): Metadata {
const base = createPageMetadata({ config: docsConfig, page });
const ogImage = buildOgImageUrl(page?.path ?? '/');

return {
...base,
openGraph: { ...base.openGraph, images: [{ url: ogImage, ...OG_IMAGE_SIZE }] },
twitter: { ...base.twitter, images: [ogImage] },
};
}

/**
* The bare full-screen preview. It renders the same block as the doc page, so
* point search engines at the doc page and keep this one out of the index.
Expand Down
44 changes: 44 additions & 0 deletions apps/docs/lib/og-image/og-image-pages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import docsConfig from '@/docs.config';
import { clampDescription, registryEntryForSlug } from '@/lib/metadata';
import { toOgImageParams, type OgImageParams } from '@/lib/og-image/og-image-params';
import { source } from '@/lib/source';
import { hrefFor } from '@/registry/index';

export type OgImagePage = Readonly<{
path: string;
params: OgImageParams;
}>;

export async function listOgImagePages(): Promise<OgImagePage[]> {
const pages: OgImagePage[] = [{ path: '/', params: toOgImageParams({}) }];

for (const { slug } of await source.getStaticParams()) {
const entry = registryEntryForSlug(slug);
if (entry) {
pages.push({
path: hrefFor(entry),
params: toOgImageParams({
title: entry.title,
description: clampDescription(entry.description),
kind: entry.type,
}),
});
continue;
}

const page = await source.getPage(slug);
if (!page) continue;
pages.push({
path: page.path,
params: toOgImageParams({
title: page.title,
description:
page.frontmatter?.description ??
docsConfig.seo?.description ??
docsConfig.site.description,
}),
});
}

return pages;
}
34 changes: 20 additions & 14 deletions apps/docs/lib/og-image/og-image-params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,31 @@ export type OgImageParams = Readonly<{

const TITLE_LIMIT = 60;
const DESCRIPTION_LIMIT = 130;
const OG_IMAGE_PATH = '/og';

export function parseOgImageParams(searchParams: URLSearchParams): OgImageParams {
const kind = searchParams.get('kind');

const OG_IMAGE_DIR = '/og';

export function toOgImageParams({
title,
description,
kind,
}: {
title?: string;
description?: string;
kind?: string;
}): OgImageParams {
return {
title: clampText(searchParams.get('title') ?? siteConfig.name, TITLE_LIMIT),
description: clampText(
searchParams.get('description') ?? siteConfig.description,
DESCRIPTION_LIMIT
),
title: clampText(title ?? siteConfig.name, TITLE_LIMIT),
description: clampText(description ?? siteConfig.description, DESCRIPTION_LIMIT),
kind: kind === 'component' || kind === 'block' ? kind : undefined,
};
}

export function buildOgImageUrl({ title, description, kind }: OgImageParams): string {
const query = new URLSearchParams({ title, description });
if (kind) query.set('kind', kind);
return new URL(`${OG_IMAGE_PATH}?${query.toString()}`, siteConfig.url).toString();
export function ogImagePath(pagePath: string): string {
const slug = pagePath.replace(/^\/+|\/+$/g, '') || 'index';
return `${OG_IMAGE_DIR}/${slug}.png`;
}

export function buildOgImageUrl(pagePath: string): string {
return new URL(ogImagePath(pagePath), siteConfig.url).toString();
}

export function isSiteTitle(title: string): boolean {
Expand Down
13 changes: 11 additions & 2 deletions apps/docs/tests/metadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,11 @@ describe('registryPageMetadata', () => {
});
expect(metadata.twitter).toMatchObject({ card: 'summary_large_image' });
expect(JSON.stringify(metadata.openGraph?.images)).toContain(
'https://tween-ui.staticmania.com/og?title=Grid+Cascade'
'https://tween-ui.staticmania.com/og/block/grid-cascade.png'
);
expect(JSON.stringify(metadata.openGraph?.images)).toContain('kind=block');
expect(metadata.twitter).toMatchObject({
images: ['https://tween-ui.staticmania.com/og/block/grid-cascade.png'],
});
expect(metadata.alternates?.canonical).toBe(
'https://tween-ui.staticmania.com/block/grid-cascade'
);
Expand All @@ -97,6 +99,13 @@ describe('previewMetadata', () => {
});

describe('rootMetadata', () => {
it('points the share image at the prebuilt home PNG', () => {
const metadata = rootMetadata();
expect(JSON.stringify(metadata.openGraph?.images)).toContain(
'https://tween-ui.staticmania.com/og/index.png'
);
});

it('declares the icon set and manifest', () => {
const metadata = rootMetadata();
expect(metadata.manifest).toBe('/site.webmanifest');
Expand Down
36 changes: 17 additions & 19 deletions apps/docs/tests/og-image.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { describe, expect, it } from 'vitest';
import { siteConfig } from '@/config/site';
import { buildOgImageUrl, isSiteTitle, parseOgImageParams } from '@/lib/og-image/og-image-params';
import {
buildOgImageUrl,
isSiteTitle,
ogImagePath,
toOgImageParams,
} from '@/lib/og-image/og-image-params';

describe('parseOgImageParams', () => {
describe('toOgImageParams', () => {
it('falls back to the site name and description', () => {
const params = parseOgImageParams(new URLSearchParams());
const params = toOgImageParams({});
expect(params).toEqual({
title: siteConfig.name,
description: siteConfig.description,
Expand All @@ -14,32 +19,25 @@ describe('parseOgImageParams', () => {
});

it('accepts only known kinds', () => {
expect(parseOgImageParams(new URLSearchParams('kind=block')).kind).toBe('block');
expect(parseOgImageParams(new URLSearchParams('kind=component')).kind).toBe('component');
expect(parseOgImageParams(new URLSearchParams('kind=<script>')).kind).toBeUndefined();
expect(toOgImageParams({ kind: 'block' }).kind).toBe('block');
expect(toOgImageParams({ kind: 'component' }).kind).toBe('component');
expect(toOgImageParams({ kind: '<script>' }).kind).toBeUndefined();
});

it('clamps long text at a word boundary', () => {
const params = parseOgImageParams(
new URLSearchParams({ title: 'word '.repeat(40), description: 'word '.repeat(80) })
);
const params = toOgImageParams({ title: 'word '.repeat(40), description: 'word '.repeat(80) });
expect(params.title.length).toBeLessThanOrEqual(60);
expect(params.description.length).toBeLessThanOrEqual(130);
expect(params.description.endsWith('…')).toBe(true);
});
});

describe('buildOgImageUrl', () => {
it('round-trips through the parser on the site origin', () => {
const url = new URL(
buildOgImageUrl({ title: 'Grid Cascade', description: 'Cards fall in.', kind: 'block' })
it('maps a page path to its prebuilt PNG on the site origin', () => {
expect(buildOgImageUrl('/block/grid-cascade')).toBe(
new URL('/og/block/grid-cascade.png', siteConfig.url).toString()
);
expect(url.origin).toBe(new URL(siteConfig.url).origin);
expect(url.pathname).toBe('/og');
expect(parseOgImageParams(url.searchParams)).toEqual({
title: 'Grid Cascade',
description: 'Cards fall in.',
kind: 'block',
});
expect(ogImagePath('/')).toBe('/og/index.png');
expect(ogImagePath('/installation/setup-guide/')).toBe('/og/installation/setup-guide.png');
});
});
Loading