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
145 changes: 145 additions & 0 deletions server/frontend/scripts/blog.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// The blog (content/blog), for scripts/prerender.mjs: content/blog/<slug>.md is the post at /blog/<slug>/, with its
// Markdown copy at /blog/<slug>.md, and the files in content/blog/<slug>/ (its images) served next to it. /blog/ lists
// the posts, newest first, and /blog/feed.xml is their Atom feed.
//
// Front matter: title, description, date (YYYY-MM-DD) and author, all required; `image`, a PNG or JPG in the post's
// folder for its link preview; `draft: true` keeps a post out of the build unless VISUALCI_BLOG_DRAFTS=1 (a dev server).
// A published post with a `[TODO` placeholder left in it fails the build.
// With no published posts there's no /blog/ at all, so the site never links an empty blog.
import { cp, readdir, readFile, stat } from 'node:fs/promises'
import { join } from 'node:path'
import { SITE, root } from './docs-source.mjs'

export const blogDir = join(root, 'content/blog')

const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
/** Paths under /blog/ that can't be posts. */
const RESERVED = new Set(['feed', 'index'])

async function exists(path) {
try {
await stat(path)
return true
} catch {
return false
}
}

function parsePost(slug, source) {
const file = `content/blog/${slug}.md`
const match = source.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/)
if (!match) throw new Error(`${file} has no front matter`)
const meta = {}
for (const line of match[1].split('\n')) {
const kv = line.match(/^(\w+):\s*(.*)$/)
if (kv) meta[kv[1]] = kv[2].replace(/^"(.*)"$/, '$1')
}
for (const key of ['title', 'description', 'date', 'author']) {
if (!meta[key]) throw new Error(`${file} has no ${key}`)
}
if (!/^\d{4}-\d{2}-\d{2}$/.test(meta.date) || Number.isNaN(Date.parse(`${meta.date}T00:00:00Z`))) {
throw new Error(`${file}: date must be YYYY-MM-DD, not ${meta.date}`)
}
if (meta.image && !/\.(png|jpe?g)$/i.test(meta.image)) throw new Error(`${file}: image must be a PNG or JPG`)
// A link or image by relative path (`chart.png`, `img/chart.png`) is a file in the post's folder.
const body = match[2].trim().replace(/\]\((?![a-z][a-z0-9+.-]*:|\/|#)([^)\s]+)/gi, `](/blog/${slug}/$1`)
return {
slug,
title: meta.title,
description: meta.description,
date: meta.date,
author: meta.author,
image: meta.image || null,
draft: meta.draft === 'true',
body,
}
}

/** The published posts, newest first (and drafts too when `drafts`). Fails on a broken post, so it never ships. */
export async function loadPosts({ drafts = false } = {}) {
if (!(await exists(blogDir))) return []
const posts = []
for (const entry of await readdir(blogDir, { withFileTypes: true })) {
if (!entry.isFile() || !entry.name.endsWith('.md')) continue
const slug = entry.name.slice(0, -'.md'.length)
if (!SLUG.test(slug)) throw new Error(`content/blog/${entry.name}: a post's file name is its URL, in lowercase words and hyphens`)
if (RESERVED.has(slug)) throw new Error(`content/blog/${entry.name}: /blog/${slug} is taken`)
const post = parsePost(slug, await readFile(join(blogDir, entry.name), 'utf8'))
if (post.image && !(await exists(join(blogDir, slug, post.image)))) {
throw new Error(`content/blog/${slug}.md: image ${post.image} isn't in content/blog/${slug}/`)
}
// A post waiting on a fact (`[TODO ...]`) stays a draft: it never reaches the site with the placeholder in it.
if (!post.draft && post.body.includes('[TODO')) throw new Error(`content/blog/${slug}.md still has a [TODO]: fill it in or keep the post a draft`)
if (!post.draft || drafts) posts.push(post)
}
return posts.sort((a, b) => b.date.localeCompare(a.date) || a.slug.localeCompare(b.slug))
}

/** Copy each post's folder (its images) to /blog/<slug>/, next to its page. */
export async function copyPostFiles(posts, dist) {
for (const post of posts) {
const dir = join(blogDir, post.slug)
if (await exists(dir)) await cp(dir, join(dist, 'blog', post.slug), { recursive: true })
}
}

export const postPath = (post) => `/blog/${post.slug}/`
export const postMarkdown = (post) => `/blog/${post.slug}.md`
export const postImage = (post) => (post.image ? `${SITE}/blog/${post.slug}/${post.image}` : null)

const escapeHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')

/** "3 December 2026", from YYYY-MM-DD. */
export function formatDate(date) {
return new Date(`${date}T00:00:00Z`).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' })
}

/** The line under a post's title: its date and author. */
export function postMetaHtml(post) {
return `<p class="blog-meta"><time datetime="${post.date}">${formatDate(post.date)}</time> · ${escapeHtml(post.author)}${post.draft ? ' · <strong>Draft</strong>' : ''}</p>\n`
}

/** /blog/: every post, newest first. */
export function indexHtml(posts) {
const items = posts.map(
(p) =>
`<li class="blog-item"><a class="blog-item-title" href="${postPath(p)}">${escapeHtml(p.title)}</a><p class="blog-meta"><time datetime="${p.date}">${formatDate(p.date)}</time> · ${escapeHtml(p.author)}</p><p class="blog-item-description">${escapeHtml(p.description)}</p></li>`,
)
return `<p>Notes from the people building VisualCI. Follow along with the <a href="/blog/feed.xml">Atom feed</a>.</p>\n<ul class="blog-list">${items.join('')}</ul>\n`
}

export function indexMarkdown(posts) {
return [
`Notes from the people building VisualCI. Atom feed: ${SITE}/blog/feed.xml`,
posts.map((p) => `- [${p.title}](${SITE}${postMarkdown(p)}) (${p.date}, ${p.author}): ${p.description}`).join('\n'),
].join('\n\n')
}

/** The Atom feed, with each post's full HTML and absolute URLs (feed readers resolve nothing). */
export function atomFeed(posts, htmlBySlug) {
const absolute = (html) => html.replace(/(href|src)="\/(?!\/)/g, `$1="${SITE}/`)
const updated = `${posts[0].date}T00:00:00Z`
const entries = posts.map(
(p) => ` <entry>
<title>${escapeHtml(p.title)}</title>
<link rel="alternate" type="text/html" href="${SITE}${postPath(p)}"/>
<id>${SITE}${postPath(p)}</id>
<published>${p.date}T00:00:00Z</published>
<updated>${p.date}T00:00:00Z</updated>
<author><name>${escapeHtml(p.author)}</name></author>
<summary>${escapeHtml(p.description)}</summary>
<content type="html">${escapeHtml(absolute(htmlBySlug.get(p.slug)))}</content>
</entry>`,
)
return `<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>VisualCI blog</title>
<subtitle>Notes from the people building VisualCI.</subtitle>
<link rel="self" type="application/atom+xml" href="${SITE}/blog/feed.xml"/>
<link rel="alternate" type="text/html" href="${SITE}/blog/"/>
<id>${SITE}/blog/</id>
<updated>${updated}</updated>
${entries.join('\n')}
</feed>
`
}
2 changes: 2 additions & 0 deletions server/frontend/scripts/has-blog.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/** Whether content/blog has a published post (or any post, with `drafts`). */
export function hasBlog(drafts: boolean): boolean
17 changes: 17 additions & 0 deletions server/frontend/scripts/has-blog.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Whether the blog (content/blog, scripts/blog.mjs) has a published post, for vite.config.ts: the footer links /blog/
// only when it exists. Drafts count when `drafts` is true (VISUALCI_BLOG_DRAFTS=1), as in the prerender.
import { readdirSync, readFileSync } from 'node:fs'

export function hasBlog(drafts) {
const dir = new URL('../content/blog/', import.meta.url)
let names
try {
names = readdirSync(dir).filter((n) => n.endsWith('.md'))
} catch {
return false
}
return names.some((n) => {
const frontMatter = readFileSync(new URL(n, dir), 'utf8').split('\n---', 1)[0]
return drafts || !/^draft:\s*true\s*$/m.test(frontMatter)
})
}
51 changes: 48 additions & 3 deletions server/frontend/scripts/prerender.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { dirname, join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { Marked } from 'marked'
import { SITE, absoluteLinks, pageSlugs, parsePage, readPage, root } from './docs-source.mjs'
import { atomFeed, copyPostFiles, indexHtml, indexMarkdown, loadPosts, postImage, postMarkdown, postMetaHtml, postPath } from './blog.mjs'

const dist = join(root, 'dist')

Expand Down Expand Up @@ -127,8 +128,9 @@ const standalone = []
for (const slug of await standaloneSlugs(join(root, 'content/pages'))) {
standalone.push(parsePage(slug, await readFile(join(root, 'content/pages', `${slug}.md`), 'utf8')))
}
/** Write a page outside the docs: /<path>/index.html in the docs' design, and its Markdown copy. */
async function writeStandalone({ slug, title, description, html: body, copy }) {
/** Write a page outside the docs: /<path>/index.html in the docs' design, and its Markdown copy. `ogImage` replaces
* the site's link-preview image, and `head` is added to the page's <head> (the blog's feed link). */
async function writeStandalone({ slug, title, description, html: body, copy, ogImage = null, head = '' }) {
const markdown = standaloneMarkdown(slug)
const path = standalonePath(slug)
const data = { slug, title, description, html: body, nav: [], markdown }
Expand All @@ -142,6 +144,8 @@ async function writeStandalone({ slug, title, description, html: body, copy }) {
html = fill(html, '<!--docs-og-description-->', escapeAttr(description), 'docs.html')
html = fill(html, '<!--docs-url-->', `${SITE}${path}`, 'docs.html')
html = fill(html, '<!--docs-data-->', `<script id="docs-data" type="application/json">${json}</script>`, 'docs.html')
if (ogImage) html = fill(html, 'https://visualci.com/og.png', escapeAttr(ogImage), 'docs.html')
if (head) html = fill(html, '</head>', `${head}\n </head>`, 'docs.html')
await mkdir(join(dist, path), { recursive: true })
await writeFile(join(dist, path, 'index.html'), html)
await mkdir(dirname(join(dist, markdown)), { recursive: true })
Expand Down Expand Up @@ -297,6 +301,37 @@ const comparisons = standalone
if (!comparisons.some((p) => p.slug === 'compare/index')) throw new Error('content/pages/compare/index.md is missing')
console.log(`prerendered ${standalone.length} pages outside the docs (${standalone.map((p) => standalonePath(p.slug)).join(', ')})`)

// ---- The blog (scripts/blog.mjs): /blog/, a page per post and /blog/feed.xml, only once there's a published post.
const posts = await loadPosts({ drafts: process.env.VISUALCI_BLOG_DRAFTS === '1' })
if (posts.length) {
const feedLink = '<link rel="alternate" type="application/atom+xml" title="VisualCI blog" href="/blog/feed.xml" />'
const postHtml = new Map()
for (const post of posts) {
const body = await marked.parse(post.body)
postHtml.set(post.slug, body)
await writeStandalone({
slug: `blog/${post.slug}`,
title: post.title,
description: post.description,
html: postMetaHtml(post) + body,
copy: `${post.date}, ${post.author}\n\n${absoluteLinks(post.body)}`,
ogImage: postImage(post),
head: feedLink,
})
}
await writeStandalone({
slug: 'blog/index',
title: 'Blog',
description: 'Notes from the people building VisualCI.',
html: indexHtml(posts),
copy: indexMarkdown(posts),
head: feedLink,
})
await copyPostFiles(posts, dist)
await writeFile(join(dist, 'blog/feed.xml'), atomFeed(posts, postHtml))
console.log(`prerendered the blog: ${posts.map(postPath).join(', ')}, /blog/ and /blog/feed.xml`)
}

await rm(join(dist, 'docs.html'))
console.log(`prerendered ${pages.length} docs pages, with Markdown copies`)

Expand Down Expand Up @@ -330,7 +365,17 @@ How VisualCI compares with other visual and snapshot testing tools, each with a

${comparisons.map((p) => `- [${p.title}](${SITE}${standaloneMarkdown(p.slug)}): ${p.description}`).join('\n')}

## Screenshots
${
posts.length
? `## Blog

Notes from the people building VisualCI, newest first. Markdown copies (all of them: ${SITE}/blog/index.md; Atom feed: ${SITE}/blog/feed.xml):

${posts.map((p) => `- [${p.title}](${SITE}${postMarkdown(p)}) (${p.date}): ${p.description}`).join('\n')}

`
: ''
}## Screenshots

VisualCI's web app and site, from its own public gallery: [${SITE}/screenshots.md](${SITE}/screenshots.md)

Expand Down
15 changes: 15 additions & 0 deletions server/frontend/scripts/site.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,21 @@ for (const page of comparePages) {
if (!files.has(`${slug}.md`)) problems.push(`${dir}/ has no ${slug}.md`)
if (!llms.includes(`https://visualci.com/${slug}.md`)) problems.push(`llms.txt doesn't link ${slug}.md`)
}
// The blog (scripts/blog.mjs), once it has a post: /blog/ and each post with their Markdown copies, each post in
// llms.txt and in the Atom feed.
const blogPosts = [...files].filter((f) => f.startsWith('blog/') && f.endsWith('/index.html') && f !== 'blog/index.html')
if (blogPosts.length) {
for (const required of ['blog/index.html', 'blog/index.md', 'blog/feed.xml']) {
if (!files.has(required)) problems.push(`${required} is missing`)
}
const feed = files.has('blog/feed.xml') ? await readFile(join(out, 'blog/feed.xml'), 'utf8') : ''
for (const page of blogPosts) {
const slug = page.slice(0, -'/index.html'.length)
if (!files.has(`${slug}.md`)) problems.push(`${slug}/ has no ${slug}.md`)
if (!llms.includes(`https://visualci.com/${slug}.md`)) problems.push(`llms.txt doesn't link ${slug}.md`)
if (!feed.includes(`<id>https://visualci.com/${slug}/</id>`)) problems.push(`blog/feed.xml has no entry for ${slug}/`)
}
} else if (files.has('blog/index.html')) problems.push('/blog/ is built, but there are no posts')
for (const f of [...files].filter((f) => f.endsWith('.html') && f !== '404.html')) {
if (!f.endsWith('index.html')) problems.push(`${f} isn't at a directory URL, so the sitemap can't list it`)
}
Expand Down
2 changes: 2 additions & 0 deletions server/frontend/src/components/SiteFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export function SiteFooter() {
{
title: 'Company',
links: [
// Only once the blog has a published post (vite.config.ts); undefined in tests.
...(typeof __VISUALCI_BLOG__ !== 'undefined' && __VISUALCI_BLOG__ ? [{ label: 'Blog', href: siteUrl('/blog/') }] : []),
{ label: 'GitHub', href: 'https://github.com/DocSpring/visualci' },
{ label: 'Support', href: 'mailto:support@visualci.com' },
{ label: 'Security', href: siteUrl('/security/') },
Expand Down
53 changes: 53 additions & 0 deletions server/frontend/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -5285,3 +5285,56 @@ html.vci-signed-in .site-auth-out {
grid-template-columns: minmax(0, 1fr);
}
}

/* The blog (scripts/blog.mjs): a post's date and author under its title, and the list at /blog/, in the docs' design. */
.docs-content .blog-meta {
margin: 0 0 var(--space-6);
font-size: var(--text-sm);
color: var(--color-muted);
}

.docs-content .blog-list {
margin: var(--space-6) 0 0;
padding: 0;
list-style: none;
}

.docs-content .blog-item {
margin: 0;
padding: var(--space-5) 0;
border-top: 1px solid var(--color-rule);
}

.docs-content .blog-item + .blog-item {
margin-top: 0;
}

.docs-content .blog-item-title {
font-size: var(--text-lg);
font-weight: 600;
letter-spacing: -0.01em;
color: var(--color-ink);
}

.docs-content .blog-item-title:hover {
color: var(--color-accent);
}

.docs-content .blog-item-title:focus-visible {
outline: 2px solid var(--color-focus);
outline-offset: 2px;
border-radius: var(--radius-sm);
}

.docs-content .blog-item .blog-meta {
margin: var(--space-1) 0 var(--space-2);
}

.docs-content .blog-item-description {
margin: 0;
}

.docs-content img {
max-width: 100%;
height: auto;
}
3 changes: 3 additions & 0 deletions server/frontend/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
/// <reference types="vite/client" />

/** Set by vite.config.ts: whether the blog has a published post, so the footer links /blog/ only then. */
declare const __VISUALCI_BLOG__: boolean
2 changes: 2 additions & 0 deletions server/frontend/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import { analytics } from './analytics'
import { hasBlog } from './scripts/has-blog.mjs'

// The backend reads its port from `PORT` (see `config/development.yaml`:
// `get_env(name="PORT", default="5250")`), so this proxy has to read the same
Expand All @@ -15,6 +16,7 @@ export default defineConfig(({ mode, isSsrBuild }) => {

return {
plugins: [react(), analytics(env.VISUALCI_ANALYTICS === '1')],
define: { __VISUALCI_BLOG__: JSON.stringify(hasBlog(env.VISUALCI_BLOG_DRAFTS === '1')) },
// Three pages: the app (index.html), the landing page (landing.html) and the docs template (docs.html), which
// scripts/prerender.mjs fills with server-rendered HTML. The SSR build (`vite build --ssr`) has one entry for each
// prerendered page.
Expand Down
Loading