feat(site-builder): per-page SEO meta + favicon + design-token CSS-var wiring + published-output a11y/perf
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,13 +1,30 @@
|
||||
import { componentResolver } from '../components/resolver';
|
||||
import { cssPropsToString } from './style-helpers';
|
||||
import { escapeHtml, escapeAttr } from './escape';
|
||||
import { escapeHtml, escapeAttr, cssValue, safeImageUrl } from './escape';
|
||||
import { sanitizeContainerTag } from '../components/layout/Container';
|
||||
import { SiteDesign, DEFAULT_SITE_DESIGN } from '../state/SiteDesignContext';
|
||||
|
||||
export interface ExportOptions {
|
||||
title?: string;
|
||||
includeFonts?: boolean;
|
||||
minifyCss?: boolean;
|
||||
headCode?: string;
|
||||
/** PageSeo.metaDescription -- also feeds og:description when set. */
|
||||
description?: string;
|
||||
/** PageSeo.ogTitle -- falls back to `title` (which itself already folds in metaTitle) when empty. */
|
||||
ogTitle?: string;
|
||||
/** PageSeo.ogImage -- absolute or site-relative image URL. */
|
||||
ogImage?: string;
|
||||
/** PageSeo.twitterCard -- default 'summary_large_image' when ogImage set, else 'summary'. */
|
||||
twitterCard?: 'summary' | 'summary_large_image';
|
||||
/** PageSeo.noindex -- emits <meta name="robots" content="noindex, nofollow">. */
|
||||
noindex?: boolean;
|
||||
/** SiteDesign.favicon -- site-wide, one per site. */
|
||||
favicon?: string;
|
||||
/** Full site design tokens -- drives the :root{} CSS-variable block (contract §2).
|
||||
* Falls back to DEFAULT_SITE_DESIGN when omitted so every export (including legacy
|
||||
* callers that don't pass it) still emits the token/base/a11y CSS -- see §7. */
|
||||
design?: SiteDesign;
|
||||
}
|
||||
|
||||
interface ResolverMap {
|
||||
@@ -138,6 +155,149 @@ const GOOGLE_FONTS_LINK = `<link rel="preconnect" href="https://fonts.googleapis
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Roboto:wght@300;400;500;700&family=Open+Sans:wght@300;400;600;700&family=Poppins:wght@300;400;500;600;700&family=Montserrat:wght@300;400;500;600;700&family=Playfair+Display:wght@400;600;700&family=Merriweather:wght@300;400;700&family=Source+Code+Pro:wght@400;500;600&display=swap" rel="stylesheet">`;
|
||||
|
||||
// Google Fonts family= params for each of the 8 presets in constants/presets.ts
|
||||
// FONT_FAMILIES, keyed by the CSS font-family name (the part before the first
|
||||
// comma in e.g. 'Playfair Display, serif'). Used to build a best-effort
|
||||
// SUBSET fonts link (perf: §3) when every design font resolves to a known
|
||||
// preset; otherwise buildFontsLink() falls back to the full GOOGLE_FONTS_LINK
|
||||
// above (which already covers all 8 and already has &display=swap) so a
|
||||
// component using a preset outside the design's 3 font fields never loses
|
||||
// its font.
|
||||
const GOOGLE_FONT_PARAMS: Record<string, string> = {
|
||||
'Inter': 'family=Inter:wght@300;400;500;600;700',
|
||||
'Roboto': 'family=Roboto:wght@300;400;500;700',
|
||||
'Open Sans': 'family=Open+Sans:wght@300;400;600;700',
|
||||
'Poppins': 'family=Poppins:wght@300;400;500;600;700',
|
||||
'Montserrat': 'family=Montserrat:wght@300;400;500;600;700',
|
||||
'Playfair Display': 'family=Playfair+Display:wght@400;600;700',
|
||||
'Merriweather': 'family=Merriweather:wght@300;400;700',
|
||||
'Source Code Pro': 'family=Source+Code+Pro:wght@400;500;600',
|
||||
};
|
||||
|
||||
/** Extracts the CSS font-family name from a value like 'Inter, sans-serif' -> 'Inter'. */
|
||||
function extractFontName(value: string | undefined): string {
|
||||
return (value || '').split(',')[0].trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort Google Fonts link (contract §3): tries to build a SUBSET link
|
||||
* containing only the design's heading/body/button fonts (+ display=swap).
|
||||
* Falls back to the full multi-font GOOGLE_FONTS_LINK -- which still has
|
||||
* display=swap -- whenever any of those three fonts isn't one of the 8 known
|
||||
* presets, so a font a component actually uses is never silently dropped.
|
||||
*/
|
||||
export function buildFontsLink(design?: SiteDesign): string {
|
||||
if (!design) return GOOGLE_FONTS_LINK;
|
||||
const families = [design.headingFont, design.bodyFont, design.buttonFont]
|
||||
.map(extractFontName)
|
||||
.filter((f, i, arr) => f !== '' && arr.indexOf(f) === i);
|
||||
if (families.length === 0) return GOOGLE_FONTS_LINK;
|
||||
const params = families.map((f) => GOOGLE_FONT_PARAMS[f]).filter((p): p is string => !!p);
|
||||
if (params.length !== families.length) return GOOGLE_FONTS_LINK;
|
||||
return `<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?${params.join('&')}&display=swap" rel="stylesheet">`;
|
||||
}
|
||||
|
||||
// ---------- Design-token CSS-variable block (contract §2) ----------
|
||||
|
||||
// Ordered [cssVarName, SiteDesign key] pairs -- exact order/names from the
|
||||
// PKG-H shared contract §2. Both the frontend (here) and the backend
|
||||
// (site-builder.php) emit this same 16-line block for the same data so
|
||||
// editor Preview === published output.
|
||||
const TOKEN_VARS: Array<[string, keyof SiteDesign]> = [
|
||||
['--wsb-primary', 'primaryColor'],
|
||||
['--wsb-secondary', 'secondaryColor'],
|
||||
['--wsb-accent', 'accentColor'],
|
||||
['--wsb-link', 'linkColor'],
|
||||
['--wsb-success', 'successColor'],
|
||||
['--wsb-warning', 'warningColor'],
|
||||
['--wsb-error', 'errorColor'],
|
||||
['--wsb-bg', 'backgroundColor'],
|
||||
['--wsb-text', 'textColor'],
|
||||
['--wsb-muted', 'mutedTextColor'],
|
||||
['--wsb-border', 'borderColor'],
|
||||
['--wsb-radius', 'borderRadius'],
|
||||
['--wsb-heading-font', 'headingFont'],
|
||||
['--wsb-body-font', 'bodyFont'],
|
||||
['--wsb-button-font', 'buttonFont'],
|
||||
['--wsb-button-radius', 'buttonRadius'],
|
||||
];
|
||||
|
||||
// Fixed token-base CSS (contract §2) -- makes the tokens actually take effect
|
||||
// globally; component inline styles still override via specificity.
|
||||
const TOKEN_BASE_CSS = `body{font-family:var(--wsb-body-font);color:var(--wsb-text);background:var(--wsb-bg)}h1,h2,h3,h4,h5,h6{font-family:var(--wsb-heading-font)}a{color:var(--wsb-link)}`;
|
||||
|
||||
// Fixed a11y/perf CSS (contract §3), emitted for every published/preview page.
|
||||
const A11Y_PERF_CSS = `a:focus-visible,button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--wsb-accent);outline-offset:2px}@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important;scroll-behavior:auto!important}}`;
|
||||
|
||||
/**
|
||||
* Builds the `:root{...}` design-token block + the fixed token-base CSS +
|
||||
* the fixed a11y/perf CSS (contract §2/§3). Every token value is sanitized
|
||||
* through `cssValue()` before interpolation -- it sits raw inside a
|
||||
* `:root{ }` CSS-element context (not a string-quoted context), so a
|
||||
* malicious value could otherwise break out of the block / the `<style>`
|
||||
* element itself.
|
||||
*/
|
||||
export function buildTokenCss(design: SiteDesign): string {
|
||||
const vars = TOKEN_VARS.map(([varName, key]) => `${varName}:${cssValue(design[key] as string)}`).join(';');
|
||||
return `:root{${vars}}${TOKEN_BASE_CSS}${A11Y_PERF_CSS}`;
|
||||
}
|
||||
|
||||
// ---------- <head> SEO/meta block (contract §4) ----------
|
||||
|
||||
/**
|
||||
* Builds the ordered SEO/meta tag block from `<meta name="robots">` (only
|
||||
* when noindex) through the favicon `<link>` -- everything between `<title>`
|
||||
* and the Google Fonts link in the contract §4 order. `title` must already
|
||||
* be the FULLY RESOLVED title (i.e. `seo.metaTitle || page.name`) -- the
|
||||
* og:title fallback chain in the contract (`ogTitle || metaTitle || TITLE`)
|
||||
* collapses to `ogTitle || title` once `title` itself already folds in the
|
||||
* metaTitle fallback, so no separate metaTitle parameter is needed here.
|
||||
* Each optional tag is emitted ONLY when its source value is non-empty --
|
||||
* no empty `content=""` tags ever ship.
|
||||
*/
|
||||
export function buildSeoMeta(options: ExportOptions, title: string): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
if (options.noindex) {
|
||||
lines.push('<meta name="robots" content="noindex, nofollow">');
|
||||
}
|
||||
|
||||
lines.push(`<title>${escapeHtml(title)}</title>`);
|
||||
|
||||
const description = options.description || '';
|
||||
if (description) {
|
||||
lines.push(`<meta name="description" content="${escapeAttr(description)}">`);
|
||||
}
|
||||
|
||||
const ogTitle = options.ogTitle || title;
|
||||
lines.push(`<meta property="og:title" content="${escapeAttr(ogTitle)}">`);
|
||||
|
||||
if (description) {
|
||||
lines.push(`<meta property="og:description" content="${escapeAttr(description)}">`);
|
||||
}
|
||||
|
||||
const ogImage = options.ogImage ? safeImageUrl(options.ogImage) : '';
|
||||
if (ogImage) {
|
||||
lines.push(`<meta property="og:image" content="${escapeAttr(ogImage)}">`);
|
||||
}
|
||||
|
||||
lines.push('<meta property="og:type" content="website">');
|
||||
|
||||
if (ogImage || description) {
|
||||
const card = options.twitterCard || (ogImage ? 'summary_large_image' : 'summary');
|
||||
lines.push(`<meta name="twitter:card" content="${escapeAttr(card)}">`);
|
||||
}
|
||||
|
||||
const favicon = options.favicon ? safeImageUrl(options.favicon) : '';
|
||||
if (favicon) {
|
||||
lines.push(`<link rel="icon" href="${escapeAttr(favicon)}">`);
|
||||
}
|
||||
|
||||
return lines.join('\n ');
|
||||
}
|
||||
|
||||
const RESPONSIVE_CSS = `
|
||||
@media (max-width: 768px) {
|
||||
[style*="display: flex"][style*="flex-direction: row"],
|
||||
@@ -191,8 +351,15 @@ function wrapInDocument(bodyHtml: string, options: ExportOptions): string {
|
||||
const responsive = minify ? RESPONSIVE_CSS_MINIFIED : RESPONSIVE_CSS;
|
||||
const visibility = minify ? VISIBILITY_CSS_MINIFIED : VISIBILITY_CSS;
|
||||
const animation = minify ? ANIMATION_CSS_MINIFIED : ANIMATION_CSS;
|
||||
const fonts = options.includeFonts !== false ? `\n ${GOOGLE_FONTS_LINK}` : '';
|
||||
// §7 back-compat: even a caller that doesn't pass `design` (legacy call
|
||||
// sites, e.g. tests not yet updated) still gets the token/base/a11y CSS --
|
||||
// every project already has design defaults, so DEFAULT_SITE_DESIGN is the
|
||||
// correct stand-in rather than skipping the block entirely.
|
||||
const design = options.design || DEFAULT_SITE_DESIGN;
|
||||
const fonts = options.includeFonts !== false ? `\n ${buildFontsLink(design)}` : '';
|
||||
const headCode = options.headCode ? `\n ${options.headCode}` : '';
|
||||
const seoMeta = buildSeoMeta(options, title);
|
||||
const tokenCss = buildTokenCss(design);
|
||||
|
||||
// Only include animation CSS + script if body contains data-animation
|
||||
const hasAnimations = bodyHtml.includes('data-animation');
|
||||
@@ -204,8 +371,8 @@ function wrapInDocument(bodyHtml: string, options: ExportOptions): string {
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>${escapeHtml(title)}</title>${fonts}
|
||||
<style>${reset}${responsive}${visibility}${animationBlock}</style>${headCode}
|
||||
${seoMeta}${fonts}
|
||||
<style>${reset}${responsive}${visibility}${animationBlock}${tokenCss}</style>${headCode}
|
||||
</head>
|
||||
<body>
|
||||
${bodyHtml}${animationScript}
|
||||
|
||||
Reference in New Issue
Block a user