From b7f0198c17f2fc1f459864630cb48e50dc4943f3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 1 May 2026 16:32:50 +0100 Subject: [PATCH] Add image-forward social card generation --- quartz/components/Head.tsx | 9 +- quartz/plugins/emitters/ogImage.tsx | 89 ++++-- quartz/plugins/transformers/frontmatter.ts | 2 + quartz/util/og.tsx | 349 ++++++++++++--------- quartz/util/siteOg.ts | 28 ++ quartz/util/social.ts | 226 ++++++++++++- 6 files changed, 534 insertions(+), 169 deletions(-) create mode 100644 quartz/util/siteOg.ts diff --git a/quartz/components/Head.tsx b/quartz/components/Head.tsx index 63d537e..18445d9 100644 --- a/quartz/components/Head.tsx +++ b/quartz/components/Head.tsx @@ -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 diff --git a/quartz/plugins/emitters/ogImage.tsx b/quartz/plugins/emitters/ogImage.tsx index ab2206b..dae44b9 100644 --- a/quartz/plugins/emitters/ogImage.tsx +++ b/quartz/plugins/emitters/ogImage.tsx @@ -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 { 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> = 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> = // 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> = 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 && ( <> diff --git a/quartz/plugins/transformers/frontmatter.ts b/quartz/plugins/transformers/frontmatter.ts index e4537f2..9691410 100644 --- a/quartz/plugins/transformers/frontmatter.ts +++ b/quartz/plugins/transformers/frontmatter.ts @@ -177,6 +177,8 @@ declare module "vfile" { enableToc: string cssclasses: string[] socialImage: string + socialDeck: string + socialSection: string comments: boolean | string }> } diff --git a/quartz/util/og.tsx b/quartz/util/og.tsx index 2afd606..b64ce7c 100644 --- a/quartz/util/og.tsx +++ b/quartz/util/og.tsx @@ -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 (
- {/* Header Section */}
+ {showImage && ( + + )} + {showImage && ( +
+ )} +
+
- {iconBase64 && ( - +
- )} -
- {cfg.baseUrl} + > + {iconBase64 && ( + + )} +
+ {cfg.pageTitle} +
+
+ {section && ( +
+ {section} +
+ )}
-
- - {/* Title Section */} -
-

- {title} -

-
- - {/* Description Section */} -
-

- {description} -

-
- - {/* Footer with Metadata */} -
- {/* Left side - Date and Reading Time */}
- {date && ( +
+

+ {title} +

+
+
+

+ {displayDeck} +

+
+
+ {date && ( +
+ + + + + + + {date} +
+ )}
- - - - + + - {date} + {readingTimeText}
- )} -
- - - - - {readingTimeText}
- - {/* Right side - Tags */} -
- {tags.slice(0, 3).map((tag: string) => ( -
- #{tag} -
- ))} -
) diff --git a/quartz/util/siteOg.ts b/quartz/util/siteOg.ts new file mode 100644 index 0000000..d920eb6 --- /dev/null +++ b/quartz/util/siteOg.ts @@ -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 {} +} diff --git a/quartz/util/social.ts b/quartz/util/social.ts index 2618807..97b10f7 100644 --- a/quartz/util/social.ts +++ b/quartz/util/social.ts @@ -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 + } +}