Add image-forward social card generation

This commit is contained in:
Meta Vens 2026-05-01 16:32:50 +01:00
commit b7f0198c17
6 changed files with 522 additions and 157 deletions

View file

@ -5,7 +5,7 @@ import { googleFontHref, googleFontSubsetHref } from "../util/theme"
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
import { unescapeHTML } from "../util/escape"
import { CustomOgImagesEmitterName } from "../plugins/emitters/ogImage"
import { canonicalSocialUrl, normalizeSocialDescription } from "../util/social"
import { canonicalSocialUrl, resolveSocialDescription } from "../util/social"
export default (() => {
const Head: QuartzComponent = ({
cfg,
@ -16,10 +16,9 @@ export default (() => {
const titleSuffix = cfg.pageTitleSuffix ?? ""
const title =
(fileData.frontmatter?.title ?? i18n(cfg.locale).propertyDefaults.title) + titleSuffix
const description = normalizeSocialDescription(
fileData.frontmatter?.socialDescription ??
fileData.frontmatter?.description ??
unescapeHTML(fileData.description?.trim() ?? i18n(cfg.locale).propertyDefaults.description),
const description = resolveSocialDescription(
fileData,
unescapeHTML(i18n(cfg.locale).propertyDefaults.description),
)
const { css, js, additionalHead } = externalResources

View file

@ -12,7 +12,15 @@ import { BuildCtx } from "../../util/ctx"
import { QuartzPluginData } from "../vfile"
import fs from "node:fs/promises"
import { styleText } from "util"
import { normalizeSocialDescription } from "../../util/social"
import {
resolveSocialDeck,
resolveSocialDescription,
resolveSocialImage,
resolveSocialMetadata,
resolveSocialSection,
socialImageLocalPath,
socialImageUrl,
} from "../../util/social"
const defaultOptions: SocialImageOptions = {
colorScheme: "lightMode",
@ -22,17 +30,34 @@ const defaultOptions: SocialImageOptions = {
excludeRoot: false,
}
function imageMimeType(filePath: string) {
const normalizedPath = isAbsoluteURL(filePath) ? new URL(filePath).pathname : filePath
const extension = getFileExtension(normalizedPath)?.replace(/^\./, "").toLowerCase()
switch (extension) {
case "jpg":
case "jpeg":
return "image/jpeg"
case "webp":
return "image/webp"
case "gif":
return "image/gif"
default:
return "image/png"
}
}
/**
* Generates social image (OG/twitter standard) and saves it as `.webp` inside the public folder
* @param opts options for generating image
*/
async function generateSocialImage(
{ cfg, description, fonts, title, fileData }: ImageOptions,
{ cfg, description, deck, section, fonts, title, fileData }: ImageOptions,
userOpts: SocialImageOptions,
): Promise<Readable> {
const { width, height } = userOpts
const iconPath = joinSegments(QUARTZ, "static", "icon.png")
let iconBase64: string | undefined = undefined
let imageBase64: string | undefined = undefined
try {
const iconData = await fs.readFile(iconPath)
iconBase64 = `data:image/png;base64,${iconData.toString("base64")}`
@ -40,14 +65,37 @@ async function generateSocialImage(
console.warn(styleText("yellow", `Warning: Could not find icon at ${iconPath}`))
}
const socialMetadata = resolveSocialMetadata(fileData)
const socialImage = resolveSocialImage(fileData, socialMetadata)
const localImagePath = socialImageLocalPath(fileData, socialImage)
if (localImagePath) {
try {
const imageData = await fs.readFile(localImagePath)
const normalizedImageData = await sharp(imageData)
.resize(width, height, {
fit: "cover",
position: "attention",
})
.png({ compressionLevel: 9 })
.toBuffer()
imageBase64 = `data:image/png;base64,${normalizedImageData.toString("base64")}`
} catch (err) {
console.warn(styleText("yellow", `Warning: Could not load social image at ${localImagePath}`))
}
}
const imageComponent = userOpts.imageStructure({
cfg,
userOpts,
title,
description,
deck,
section,
fonts,
fileData,
iconBase64,
imageBase64,
})
const svg = await satori(imageComponent, {
@ -77,16 +125,20 @@ async function processOgImage(
const titleSuffix = cfg.pageTitleSuffix ?? ""
const title =
(fileData.frontmatter?.title ?? i18n(cfg.locale).propertyDefaults.title) + titleSuffix
const description = normalizeSocialDescription(
fileData.frontmatter?.socialDescription ??
fileData.frontmatter?.description ??
unescapeHTML(fileData.description?.trim() ?? i18n(cfg.locale).propertyDefaults.description),
const description = resolveSocialDescription(
fileData,
unescapeHTML(i18n(cfg.locale).propertyDefaults.description),
)
const siteMetadata = resolveSocialMetadata(fileData)
const deck = resolveSocialDeck(fileData, description, siteMetadata)
const section = resolveSocialSection(fileData, siteMetadata)
const stream = await generateSocialImage(
{
title,
description,
deck,
section,
fonts,
cfg,
fileData,
@ -118,7 +170,7 @@ export const CustomOgImages: QuartzEmitterPlugin<Partial<SocialImageOptions>> =
const fonts = await getSatoriFonts(headerFont, bodyFont)
for (const [_tree, vfile] of content) {
if (vfile.data.frontmatter?.socialImage !== undefined) continue
if (fullOptions.excludeRoot && vfile.data.slug === "index") continue
yield processOgImage(ctx, vfile.data, fonts, fullOptions)
}
},
@ -131,7 +183,7 @@ export const CustomOgImages: QuartzEmitterPlugin<Partial<SocialImageOptions>> =
// find all slugs that changed or were added
for (const changeEvent of changeEvents) {
if (!changeEvent.file) continue
if (changeEvent.file.data.frontmatter?.socialImage !== undefined) continue
if (fullOptions.excludeRoot && changeEvent.file.data.slug === "index") continue
if (changeEvent.type === "add" || changeEvent.type === "change") {
yield processOgImage(ctx, changeEvent.file.data, fonts, fullOptions)
}
@ -147,23 +199,20 @@ export const CustomOgImages: QuartzEmitterPlugin<Partial<SocialImageOptions>> =
additionalHead: [
(pageData) => {
const isRealFile = pageData.filePath !== undefined
let userDefinedOgImagePath = pageData.frontmatter?.socialImage
if (userDefinedOgImagePath) {
userDefinedOgImagePath = isAbsoluteURL(userDefinedOgImagePath)
? userDefinedOgImagePath
: `https://${baseUrl}/static/${userDefinedOgImagePath}`
}
const generatedOgImagePath = isRealFile
const useGeneratedCard =
isRealFile && !(fullOptions.excludeRoot && pageData.slug === "index")
const generatedOgImagePath = useGeneratedCard
? `https://${baseUrl}/${pageData.slug!}-og-image.webp`
: undefined
const pageSiteMetadata = resolveSocialMetadata(pageData)
const pageSocialImage = resolveSocialImage(pageData, pageSiteMetadata)
const imageFromMetadata = socialImageUrl(baseUrl, pageData, pageSocialImage)
const defaultOgImagePath = `https://${baseUrl}/static/og-image.png`
const ogImagePath = userDefinedOgImagePath ?? generatedOgImagePath ?? defaultOgImagePath
const ogImageMimeType = `image/${getFileExtension(ogImagePath) ?? "png"}`
const ogImagePath = generatedOgImagePath ?? imageFromMetadata ?? defaultOgImagePath
const ogImageMimeType = imageMimeType(ogImagePath)
return (
<>
{!userDefinedOgImagePath && (
{generatedOgImagePath && (
<>
<meta property="og:image:width" content={fullOptions.width.toString()} />
<meta property="og:image:height" content={fullOptions.height.toString()} />

View file

@ -177,6 +177,8 @@ declare module "vfile" {
enableToc: string
cssclasses: string[]
socialImage: string
socialDeck: string
socialSection: string
comments: boolean | string
}>
}

View file

@ -141,6 +141,7 @@ export type SocialImageOptions = {
options: ImageOptions & {
userOpts: UserOpts
iconBase64?: string
imageBase64?: string
},
) => JSXInternal.Element
}
@ -156,6 +157,14 @@ export type ImageOptions = {
* what description to use as body in image
*/
description: string
/**
* short deck/tagline to use inside the image card
*/
deck: string
/**
* section label for the card
*/
section?: string
/**
* header + body font to be used when generating satori image (as promise to work around sync in component)
*/
@ -176,11 +185,14 @@ export const defaultImage: SocialImageOptions["imageStructure"] = ({
userOpts,
title,
description,
deck,
section,
fileData,
iconBase64,
imageBase64,
}) => {
const { colorScheme } = userOpts
const fontBreakPoint = 32
const fontBreakPoint = 30
const useSmallerFont = title.length > fontBreakPoint
// Format date if available
@ -193,10 +205,10 @@ export const defaultImage: SocialImageOptions["imageStructure"] = ({
minutes: Math.ceil(minutes),
})
// Get tags if available
const tags = fileData.frontmatter?.tags ?? []
const bodyFont = getFontSpecificationName(cfg.theme.typography.body)
const headerFont = getFontSpecificationName(cfg.theme.typography.header)
const displayDeck = deck || description
const showImage = Boolean(imageBase64)
return (
<div
@ -206,172 +218,223 @@ export const defaultImage: SocialImageOptions["imageStructure"] = ({
height: "100%",
width: "100%",
backgroundColor: cfg.theme.colors[colorScheme].light,
padding: "2.5rem",
position: "relative",
overflow: "hidden",
fontFamily: bodyFont,
}}
>
{/* Header Section */}
<div
style={{
display: "flex",
alignItems: "center",
gap: "1rem",
marginBottom: "0.5rem",
position: "absolute",
inset: 0,
background: `linear-gradient(135deg, ${cfg.theme.colors[colorScheme].highlight}, transparent 58%)`,
}}
/>
{showImage && (
<img
src={imageBase64}
width={1200}
height={630}
style={{
position: "absolute",
inset: 0,
width: "100%",
height: "100%",
objectFit: "cover",
objectPosition: "center",
}}
/>
)}
{showImage && (
<div
style={{
position: "absolute",
inset: 0,
background:
"linear-gradient(90deg, rgba(7,17,26,0.94) 0%, rgba(7,17,26,0.78) 28%, rgba(7,17,26,0.42) 52%, rgba(7,17,26,0.14) 72%, rgba(7,17,26,0.06) 100%)",
}}
/>
)}
<div
style={{
position: "absolute",
inset: 0,
background:
"linear-gradient(180deg, rgba(7,17,26,0.2) 0%, rgba(7,17,26,0.4) 60%, rgba(7,17,26,0.78) 100%)",
}}
/>
<div
style={{
display: "flex",
flexDirection: "column",
height: "100%",
width: "100%",
padding: "2.4rem",
position: "relative",
}}
>
{iconBase64 && (
<img
src={iconBase64}
width={56}
height={56}
<div
style={{
display: "flex",
alignItems: "flex-start",
justifyContent: "space-between",
gap: "1rem",
marginBottom: "2.2rem",
}}
>
<div
style={{
borderRadius: "50%",
display: "flex",
alignItems: "center",
gap: "1rem",
}}
/>
)}
<div
style={{
display: "flex",
fontSize: 32,
color: cfg.theme.colors[colorScheme].gray,
fontFamily: bodyFont,
}}
>
{cfg.baseUrl}
>
{iconBase64 && (
<img
src={iconBase64}
width={46}
height={46}
style={{
borderRadius: "50%",
}}
/>
)}
<div
style={{
display: "flex",
fontSize: 28,
color: cfg.theme.colors[colorScheme].darkgray,
fontFamily: bodyFont,
}}
>
{cfg.pageTitle}
</div>
</div>
{section && (
<div
style={{
display: "flex",
padding: "0.55rem 0.95rem",
borderRadius: "999px",
backgroundColor: "rgba(255, 138, 42, 0.16)",
border: `1px solid ${cfg.theme.colors[colorScheme].secondary}`,
color: cfg.theme.colors[colorScheme].secondary,
fontSize: 22,
fontFamily: bodyFont,
}}
>
{section}
</div>
)}
</div>
</div>
{/* Title Section */}
<div
style={{
display: "flex",
marginTop: "1rem",
marginBottom: "1.5rem",
}}
>
<h1
style={{
margin: 0,
fontSize: useSmallerFont ? 64 : 72,
fontFamily: headerFont,
fontWeight: 700,
color: cfg.theme.colors[colorScheme].dark,
lineHeight: 1.2,
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: 2,
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
{title}
</h1>
</div>
{/* Description Section */}
<div
style={{
display: "flex",
flex: 1,
fontSize: 36,
color: cfg.theme.colors[colorScheme].darkgray,
lineHeight: 1.4,
}}
>
<p
style={{
margin: 0,
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: 5,
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
{description}
</p>
</div>
{/* Footer with Metadata */}
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
marginTop: "2rem",
paddingTop: "2rem",
borderTop: `1px solid ${cfg.theme.colors[colorScheme].lightgray}`,
}}
>
{/* Left side - Date and Reading Time */}
<div
style={{
display: "flex",
alignItems: "center",
gap: "2rem",
color: cfg.theme.colors[colorScheme].gray,
fontSize: 28,
flexDirection: "column",
justifyContent: "flex-end",
flex: 1,
maxWidth: showImage ? "58%" : "100%",
padding: showImage ? "1.8rem 1.9rem 1.55rem" : 0,
borderRadius: showImage ? "28px" : 0,
backgroundColor: showImage ? "rgba(7,17,26,0.62)" : "transparent",
border: showImage ? "1px solid rgba(231,236,244,0.08)" : "none",
}}
>
{date && (
<div
style={{
display: "flex",
marginBottom: "1.2rem",
}}
>
<h1
style={{
margin: 0,
fontSize: useSmallerFont ? 66 : 78,
fontFamily: headerFont,
fontWeight: 300,
letterSpacing: "-0.04em",
color: cfg.theme.colors[colorScheme].dark,
lineHeight: 1.05,
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: 2,
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
{title}
</h1>
</div>
<div
style={{
display: "flex",
marginBottom: "2.4rem",
}}
>
<p
style={{
margin: 0,
fontSize: 31,
color: cfg.theme.colors[colorScheme].darkgray,
lineHeight: 1.25,
maxWidth: "100%",
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: 3,
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
{displayDeck}
</p>
</div>
<div
style={{
display: "flex",
alignItems: "center",
gap: "1.75rem",
marginTop: "auto",
paddingTop: "1.5rem",
borderTop: `1px solid ${cfg.theme.colors[colorScheme].lightgray}`,
color: cfg.theme.colors[colorScheme].gray,
fontSize: 24,
}}
>
{date && (
<div style={{ display: "flex", alignItems: "center" }}>
<svg
style={{ marginRight: "0.45rem" }}
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
>
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
<line x1="16" y1="2" x2="16" y2="6"></line>
<line x1="8" y1="2" x2="8" y2="6"></line>
<line x1="3" y1="10" x2="21" y2="10"></line>
</svg>
{date}
</div>
)}
<div style={{ display: "flex", alignItems: "center" }}>
<svg
style={{ marginRight: "0.5rem" }}
width="28"
height="28"
style={{ marginRight: "0.45rem" }}
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
>
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
<line x1="16" y1="2" x2="16" y2="6"></line>
<line x1="8" y1="2" x2="8" y2="6"></line>
<line x1="3" y1="10" x2="21" y2="10"></line>
<circle cx="12" cy="12" r="10"></circle>
<polyline points="12 6 12 12 16 14"></polyline>
</svg>
{date}
{readingTimeText}
</div>
)}
<div style={{ display: "flex", alignItems: "center" }}>
<svg
style={{ marginRight: "0.5rem" }}
width="28"
height="28"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
>
<circle cx="12" cy="12" r="10"></circle>
<polyline points="12 6 12 12 16 14"></polyline>
</svg>
{readingTimeText}
</div>
</div>
{/* Right side - Tags */}
<div
style={{
display: "flex",
gap: "0.5rem",
flexWrap: "wrap",
justifyContent: "flex-end",
maxWidth: "60%",
}}
>
{tags.slice(0, 3).map((tag: string) => (
<div
style={{
display: "flex",
padding: "0.5rem 1rem",
backgroundColor: cfg.theme.colors[colorScheme].highlight,
color: cfg.theme.colors[colorScheme].secondary,
borderRadius: "10px",
fontSize: 24,
}}
>
#{tag}
</div>
))}
</div>
</div>
</div>
)

28
quartz/util/siteOg.ts Normal file
View file

@ -0,0 +1,28 @@
import { QuartzPluginData } from "../plugins/vfile"
export type SocialImageRef =
| {
kind: "static"
path: string
alt?: string
}
| {
kind: "relative"
path: string
alt?: string
}
| {
kind: "absolute"
path: string
alt?: string
}
export type SiteSocialMetadata = {
section?: string
deck?: string
image?: SocialImageRef
}
export function resolveSiteSocialMetadata(_fileData: QuartzPluginData): SiteSocialMetadata {
return {}
}

View file

@ -1,4 +1,121 @@
import { FullSlug, joinSegments, simplifySlug } from "./path"
import path from "node:path"
import { Element, Root as HtmlRoot, RootContent } from "hast"
import { toString } from "hast-util-to-string"
import { QuartzPluginData } from "../plugins/vfile"
import { FullSlug, QUARTZ, joinSegments, simplifySlug } from "./path"
import { SiteSocialMetadata, SocialImageRef, resolveSiteSocialMetadata } from "./siteOg"
const taglinePattern = /^["'\u201C\u2018].+["'\u201D\u2019]$/u
function normalizeWhitespace(text: string): string {
return text.replace(/\s+/g, " ").trim()
}
function isElementNode(node: RootContent): node is Element {
return node.type === "element"
}
function isWhitespaceText(node: RootContent) {
return node.type === "text" && node.value.trim().length === 0
}
function stripSurroundingQuotes(value: string) {
return value
.replace(/^["'\u201C\u2018]+/u, "")
.replace(/["'\u201D\u2019]+$/u, "")
.trim()
}
function isStandaloneTagline(node: RootContent) {
if (!isElementNode(node) || node.tagName !== "p") {
return false
}
const meaningfulChildren = node.children.filter((child) => !isWhitespaceText(child))
if (meaningfulChildren.length !== 1) {
return false
}
const child = meaningfulChildren[0]
if (!isElementNode(child) || !["em", "strong"].includes(child.tagName)) {
return false
}
return taglinePattern.test(normalizeWhitespace(toString(child)))
}
function extractTopTagline(root?: HtmlRoot): string | undefined {
if (!root) {
return undefined
}
let titleSkipped = false
for (const node of root.children) {
if (!isElementNode(node)) {
continue
}
if (!titleSkipped && node.tagName === "h1") {
titleSkipped = true
continue
}
const text = normalizeWhitespace(toString(node))
if (text.length === 0) {
continue
}
if (isStandaloneTagline(node)) {
return stripSurroundingQuotes(text)
}
return undefined
}
return undefined
}
function extractFirstImage(root?: HtmlRoot): SocialImageRef | undefined {
if (!root) {
return undefined
}
const queue: RootContent[] = [...root.children]
while (queue.length > 0) {
const node = queue.shift()
if (!node || !isElementNode(node)) {
continue
}
if (node.tagName === "img" && typeof node.properties?.src === "string") {
const src = node.properties.src.trim()
const alt =
typeof node.properties.alt === "string" && node.properties.alt.trim().length > 0
? node.properties.alt.trim()
: undefined
if (/^https?:\/\//i.test(src)) {
return {
kind: "absolute",
path: src,
alt,
}
}
return {
kind: "relative",
path: src,
alt,
}
}
queue.unshift(...node.children)
}
return undefined
}
export function canonicalSocialUrl(baseUrl: string, slug?: FullSlug): string {
const rootUrl = `https://${baseUrl}`
@ -20,3 +137,110 @@ export function normalizeSocialDescription(description: string, maxLength = 220)
return truncated.replace(/[.,;:\s]+$/g, "") + "..."
}
export function resolveSocialDescription(fileData: QuartzPluginData, fallback: string): string {
return normalizeSocialDescription(
fileData.frontmatter?.socialDescription ??
fileData.frontmatter?.description ??
fileData.description?.trim() ??
fallback,
)
}
export function resolveSocialMetadata(fileData: QuartzPluginData): SiteSocialMetadata {
return resolveSiteSocialMetadata(fileData)
}
export function resolveSocialDeck(
fileData: QuartzPluginData,
description: string,
siteMetadata = resolveSiteSocialMetadata(fileData),
): string {
const explicitDeck = fileData.frontmatter?.socialDeck
if (typeof explicitDeck === "string" && explicitDeck.trim().length > 0) {
return explicitDeck.trim()
}
const tagline = extractTopTagline(fileData.htmlAst)
if (tagline) {
return tagline
}
if (siteMetadata.deck && siteMetadata.deck.trim().length > 0) {
return siteMetadata.deck.trim()
}
return description
}
export function resolveSocialSection(
fileData: QuartzPluginData,
siteMetadata = resolveSiteSocialMetadata(fileData),
): string {
if (
typeof fileData.frontmatter?.socialSection === "string" &&
fileData.frontmatter.socialSection
) {
return fileData.frontmatter.socialSection.trim()
}
if (siteMetadata.section && siteMetadata.section.trim().length > 0) {
return siteMetadata.section.trim()
}
return ""
}
export function resolveSocialImage(
fileData: QuartzPluginData,
siteMetadata = resolveSiteSocialMetadata(fileData),
): SocialImageRef | undefined {
const explicitImage = fileData.frontmatter?.socialImage
if (typeof explicitImage === "string" && explicitImage.trim().length > 0) {
const imagePath = explicitImage.trim()
return /^https?:\/\//i.test(imagePath)
? { kind: "absolute", path: imagePath }
: { kind: "static", path: imagePath }
}
return extractFirstImage(fileData.htmlAst) ?? siteMetadata.image
}
export function socialImageUrl(
baseUrl: string,
fileData: QuartzPluginData,
image?: SocialImageRef,
): string | undefined {
if (!image) {
return undefined
}
switch (image.kind) {
case "absolute":
return image.path
case "static":
return `https://${baseUrl}/static/${image.path.replace(/^\/+/, "")}`
case "relative":
return new URL(image.path, canonicalSocialUrl(baseUrl, fileData.slug)).toString()
}
}
export function socialImageLocalPath(
fileData: QuartzPluginData,
image?: SocialImageRef,
): string | undefined {
if (!image) {
return undefined
}
switch (image.kind) {
case "absolute":
return undefined
case "static":
return path.join(QUARTZ, "static", image.path.replace(/^[/\\]+/, ""))
case "relative":
return fileData.filePath
? path.resolve(path.dirname(fileData.filePath), image.path)
: undefined
}
}