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
10 changes: 10 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Binary file added docs/assets/fonts/NotoSansSC-Regular.woff
Binary file not shown.
92 changes: 92 additions & 0 deletions docs/assets/fonts/OFL.txt
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 10 additions & 0 deletions docs/assets/fonts/README.md
Original file line number Diff line number Diff line change
@@ -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/).
15 changes: 11 additions & 4 deletions docs/src/app/[[...slug]]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -31,10 +31,17 @@ export async function generateMetadata({
}: {
params: Promise<{ slug?: string[] }>
}): Promise<import('next').Metadata> {
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,
})
}

Expand Down
37 changes: 37 additions & 0 deletions docs/src/app/og/[...slug]/route.ts
Original file line number Diff line number Diff line change
@@ -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 || '',
)
}
100 changes: 100 additions & 0 deletions docs/src/site/social-image.tsx
Original file line number Diff line number Diff line change
@@ -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(
(
<div
style={{
display: 'flex',
flexDirection: 'column',
width: '100%',
height: '100%',
padding: '64px 72px',
background: '#0b1110',
color: '#f1f5f3',
fontFamily: 'Noto Sans SC',
borderTop: '8px solid #10b981',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: 48,
height: 48,
borderRadius: 12,
background: '#10b981',
color: '#0b1110',
fontSize: 28,
}}
>
{'>_'}
</div>
<div style={{ display: 'flex', fontSize: 28 }}>Create Preset</div>
</div>
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
flex: 1,
gap: 24,
}}
>
<div
style={{
fontSize: 64,
lineHeight: 1.2,
lineClamp: 2,
textOverflow: 'ellipsis',
}}
>
{entry.title}
</div>
<div
style={{
fontSize: 30,
lineHeight: 1.5,
color: '#a8bdb4',
lineClamp: 3,
textOverflow: 'ellipsis',
}}
>
{description}
</div>
</div>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
paddingTop: 24,
borderTop: '1px solid #294038',
color: '#7dd3b0',
fontSize: 22,
}}
>
<div style={{ display: 'flex' }}>preset.js.org</div>
<div style={{ display: 'flex' }}>{entry.href}</div>
</div>
</div>
),
{
...socialImageSize,
fonts: [
{ name: 'Noto Sans SC', data: fontData, weight: 400, style: 'normal' },
],
},
)
}
74 changes: 74 additions & 0 deletions docs/src/site/social-metadata.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
Loading
Loading