diff --git a/docs/README.md b/docs/README.md index 9c83027..d8d3965 100644 --- a/docs/README.md +++ b/docs/README.md @@ -30,6 +30,16 @@ pnpm start Development and production builds copy `../schema/preset.schema.json` into the public site, so the CLI and website share one schema source. +## Social previews + +Every canonical page gets Open Graph and X Card metadata from its existing +frontmatter title and description. The build generates a matching 1200 × 630 +PNG under `/og/` using a shared text layout and the bundled Noto Sans SC font. +English and Chinese pages have separate previews; `/en/` aliases share the +canonical English preview. No per-page image configuration or image server is +required. Run `pnpm dev` to preview images locally, or inspect the PNG files in +`.next-static/og/` after `pnpm build`. + ## Deployment The [Pages workflow](../.github/workflows/website.yml) validates pull requests and diff --git a/docs/assets/fonts/NotoSansSC-Regular.woff b/docs/assets/fonts/NotoSansSC-Regular.woff new file mode 100644 index 0000000..4dde89e Binary files /dev/null and b/docs/assets/fonts/NotoSansSC-Regular.woff differ diff --git a/docs/assets/fonts/OFL.txt b/docs/assets/fonts/OFL.txt new file mode 100644 index 0000000..d952d62 --- /dev/null +++ b/docs/assets/fonts/OFL.txt @@ -0,0 +1,92 @@ +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/docs/assets/fonts/README.md b/docs/assets/fonts/README.md new file mode 100644 index 0000000..9a30ae5 --- /dev/null +++ b/docs/assets/fonts/README.md @@ -0,0 +1,10 @@ +# Social preview font + +`NotoSansSC-Regular.woff` is the complete Noto Sans SC Regular font, converted +from OpenType to WOFF without removing glyphs. It supports English and Chinese +social previews without requests to a remote font service during builds. + +Source: [Noto CJK](https://github.com/notofonts/noto-cjk/blob/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/SubsetOTF/SC/NotoSansSC-Regular.otf). +Licensed under the SIL Open Font License 1.1; see `OFL.txt`. + +Copyright © 2014–2021 Adobe (http://www.adobe.com/). diff --git a/docs/src/app/[[...slug]]/page.tsx b/docs/src/app/[[...slug]]/page.tsx index 825d79b..9373a1d 100644 --- a/docs/src/app/[[...slug]]/page.tsx +++ b/docs/src/app/[[...slug]]/page.tsx @@ -2,13 +2,13 @@ import { DocsPage, createDocsSource, resolveDocsRoute, - generateMetadata as generateDocsMetadata, generateStaticParams as generateDocsStaticParams, } from '@blackwork/docs' import { notFound, redirect } from 'next/navigation' import { docsConfig } from '../../../docs.config' import { LegacyRedirectPage } from './redirects/legacy-redirect-page' import { PresetHome } from '@/home/preset-home' +import { createSocialMetadata } from '@/site/social-metadata' export const dynamicParams = false @@ -31,10 +31,17 @@ export async function generateMetadata({ }: { params: Promise<{ slug?: string[] }> }): Promise { - return generateDocsMetadata({ + const source = createDocsSource({ config: docsConfig, rootDir }) + const routeParams = await params + const resolution = resolveDocsRoute({ source, params: routeParams }) + + if (resolution.kind === 'notFound') return {} + + return createSocialMetadata({ config: docsConfig, - params, - rootDir, + entry: resolution.entry, + pathname: `/${(routeParams.slug ?? []).join('/')}`, + source, }) } diff --git a/docs/src/app/og/[...slug]/route.ts b/docs/src/app/og/[...slug]/route.ts new file mode 100644 index 0000000..84ba2ba --- /dev/null +++ b/docs/src/app/og/[...slug]/route.ts @@ -0,0 +1,37 @@ +import { createDocsSource } from '@blackwork/docs' +import { docsConfig } from '../../../../docs.config' +import { createSocialImage } from '@/site/social-image' +import { getSocialImagePath } from '@/site/social-metadata' + +export const dynamic = 'force-static' +export const dynamicParams = false + +function getEntries() { + const source = createDocsSource({ config: docsConfig, rootDir: '.' }) + return source.getLocaleCodes().flatMap((locale) => source.getEntries(locale)) +} + +export function generateStaticParams() { + return getEntries().map((entry) => ({ + slug: getSocialImagePath(entry) + .slice('/og/'.length) + .split('/') + .map(decodeURIComponent), + })) +} + +export async function GET( + _request: Request, + { params }: { params: Promise<{ slug: string[] }> }, +) { + const { slug } = await params + const path = `/og/${slug.map(encodeURIComponent).join('/')}` + const entry = getEntries().find((entry) => getSocialImagePath(entry) === path) + + if (!entry) return new Response('Not found', { status: 404 }) + + return createSocialImage( + entry, + entry.description || docsConfig.site?.description || '', + ) +} diff --git a/docs/src/site/social-image.tsx b/docs/src/site/social-image.tsx new file mode 100644 index 0000000..00a26bb --- /dev/null +++ b/docs/src/site/social-image.tsx @@ -0,0 +1,100 @@ +import type { DocEntry } from '@blackwork/docs' +import { ImageResponse } from 'next/og' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { socialImageSize } from './social-metadata' + +// Bundle the full SC font so new Chinese pages render without font-service requests. +const font = readFile(join(process.cwd(), 'assets/fonts/NotoSansSC-Regular.woff')) + +export async function createSocialImage(entry: DocEntry, description: string) { + const fontData = await font + + return new ImageResponse( + ( +
+
+
+ {'>_'} +
+
Create Preset
+
+
+
+ {entry.title} +
+
+ {description} +
+
+
+
preset.js.org
+
{entry.href}
+
+
+ ), + { + ...socialImageSize, + fonts: [ + { name: 'Noto Sans SC', data: fontData, weight: 400, style: 'normal' }, + ], + }, + ) +} diff --git a/docs/src/site/social-metadata.test.ts b/docs/src/site/social-metadata.test.ts new file mode 100644 index 0000000..4dafc34 --- /dev/null +++ b/docs/src/site/social-metadata.test.ts @@ -0,0 +1,74 @@ +import { createDocsSource, type DocEntry } from '@blackwork/docs' +import { describe, expect, test } from 'vitest' +import { docsConfig } from '../../docs.config' +import { createSocialMetadata, getSocialImagePath } from './social-metadata' + +const source = createDocsSource({ config: docsConfig, rootDir: '.' }) + +function getEntry(locale: string, slugSegments: string[] = []) { + const entry = source.getEntry(locale, slugSegments) + expect(entry).not.toBeNull() + return entry as DocEntry +} + +describe('social previews', () => { + test.each([ + ['en', 'en_US', 'Preset Configs', '/og/en/guide/preset-configs.png'], + ['zh', 'zh_CN', 'Preset 配置', '/og/zh/guide/preset-configs.png'], + ])('uses %s page content and canonical URLs', (locale, ogLocale, title, imagePath) => { + const entry = getEntry(locale, ['guide', 'preset-configs']) + const metadata = createSocialMetadata({ config: docsConfig, entry, source }) + + expect(metadata.title).toBe(`${title} | Create Preset`) + expect(metadata.description).toBe(entry.description) + expect(metadata.openGraph).toMatchObject({ + title: metadata.title, + description: entry.description, + locale: ogLocale, + url: metadata.alternates?.canonical, + images: [{ + url: `https://preset.js.org${imagePath}`, + width: 1200, + height: 630, + alt: metadata.title, + }], + }) + expect(metadata.twitter).toMatchObject({ + card: 'summary_large_image', + title: metadata.title, + description: entry.description, + images: metadata.openGraph?.images, + }) + expect(metadata.alternates?.languages).toHaveProperty('en-US') + expect(metadata.alternates?.languages).toHaveProperty('zh-CN') + }) + + test('keeps English aliases noindex and shares the canonical preview', () => { + const entry = getEntry('en', ['guide', 'preset-configs']) + const metadata = createSocialMetadata({ + config: docsConfig, + entry, + source, + pathname: '/en/guide/preset-configs', + }) + + expect(metadata.robots).toEqual({ index: false, follow: true }) + expect(metadata.openGraph?.url).toBe(`https://preset.js.org${entry.href}`) + expect(metadata.openGraph?.images).toMatchObject([ + { url: 'https://preset.js.org/og/en/guide/preset-configs.png' }, + ]) + }) + + test('gives both homepages their own image and uses the site description as fallback', () => { + expect(getSocialImagePath(getEntry('en'))).toBe('/og/en/index.png') + expect(getSocialImagePath(getEntry('zh'))).toBe('/og/zh/index.png') + + const metadata = createSocialMetadata({ + config: docsConfig, + entry: { ...getEntry('en'), description: '' }, + source, + }) + expect(metadata.openGraph?.description).toBe(docsConfig.site?.description) + expect(metadata.twitter?.description).toBe(docsConfig.site?.description) + }) +}) diff --git a/docs/src/site/social-metadata.ts b/docs/src/site/social-metadata.ts new file mode 100644 index 0000000..1689580 --- /dev/null +++ b/docs/src/site/social-metadata.ts @@ -0,0 +1,42 @@ +import { + createDocMetadata, + type CreateDocMetadataOptions, + type DocEntry, +} from '@blackwork/docs' +import type { Metadata } from 'next' + +export const socialImageSize = { width: 1200, height: 630 } + +export function getSocialImagePath(entry: DocEntry) { + const path = entry.slugSegments.length ? entry.slugSegments : ['index'] + return `/og/${[entry.locale, ...path].map(encodeURIComponent).join('/')}.png` +} + +export function createSocialMetadata(options: CreateDocMetadataOptions): Metadata { + const metadata = createDocMetadata(options) + const { entry, config } = options + const image = { + url: new URL(getSocialImagePath(entry), metadata.alternates.canonical).href, + ...socialImageSize, + alt: metadata.title, + } + + return { + ...metadata, + openGraph: { + type: 'website', + siteName: config?.site?.title, + title: metadata.title, + description: metadata.description, + url: metadata.alternates.canonical, + locale: config?.content?.locales?.[entry.locale]?.lang?.replace('-', '_'), + images: [image], + }, + twitter: { + card: 'summary_large_image', + title: metadata.title, + description: metadata.description, + images: [image], + }, + } +}