Author SHA1 Message Date
andwati 12dd32ea4f Polish nav, transitions, layout, SEO, a11y, LaTeX, and Lighthouse CI
Nav bar & layout consistency
- Base.astro's `wide` layout now defaults on for every page (was opt-in),
  fixing the nav bar wrapping differently depending on page width
- Icon buttons for search and theme toggle (magnifying glass, sun/moon),
  replacing the plain "Search" text link and the "◐" glyph
- Search is now a Cmd/Ctrl+K modal over Pagefind (lazy-loaded on first
  open) instead of a separate /search/ page, matching the old site
- Fixed the article page's TOC sitting with unwanted left padding relative
  to the header (grid was center-justified instead of start-justified)

Smooth navigation
- Added Astro's ClientRouter for animated page transitions
- Every page-local script that only ran once at module load (three.js
  hero, minimap, comments, book-spine carousel, scroll-to-top, reading
  progress, theme toggle, Pagefind init) now re-initializes via
  astro:page-load, with AbortController-based cleanup so window/document
  listeners don't accumulate across client-side navigations

Restored from the legacy Zola site
- Reading progress bar (article pages) and scroll-to-top button
- Share buttons (X, Bluesky, LinkedIn, Reddit, HN, email) on writings
- Prev/next post navigation with the old label/title layout
- Utterances comments, wired to andwati/andwati.com with dark/light
  theme sync
- YouTube embeds: any plain <iframe src="...youtube-nocookie.com...">
  is now auto-wrapped in a responsive 16:9 container, gets
  loading="lazy", and emits VideoObject JSON-LD — no shortcode needed
- LaTeX: $inline$ and $$block$$ math renders to static HTML via KaTeX at
  build time (no client-side JS shipped for it)
- Tags page redesigned as a centered, alphabetical tag cloud

Removed the related-posts section per request.

Accessibility & contrast
- --accent (#d1502f) measured 4.0:1 on the light background, just under
  WCAG AA's 4.5:1 for normal text — darkened to #a84025 (5.7:1), plus
  matching light-mode-only fixes for the two hljs syntax colors and the
  tip/warning callout colors that had the same problem in light mode
- Fixed heading-order violations (h1 straight to h3 with nothing at h2)
  across the homepage, writings/portfolio/bookshelf/blogs lists, and tag
  pages — introduced a shared .entry-title class for the h2 list titles
- Fixed inconsistent title-link underline colors: a plain <a> carries its
  own default underline (in its own text color) instead of matching its
  parent heading's accent-colored one — h1/h2/h3 anchors now explicitly
  inherit the heading's decoration
- Bookshelf spine colors are generated per-title from a hash; the
  lightness-based text-color heuristic could still produce sub-4.5:1
  contrast for some hues (e.g. green) — now computes real WCAG contrast
  and adjusts

Performance
- The three.js homepage hero was the single largest main-thread cost
  site-wide (dragging that page's Lighthouse performance score to the low
  80s while every other page scored 95+): three.js is now dynamically
  imported only once the browser is idle (WebGL-support check split into
  its own tiny module so unsupported browsers never fetch it at all), the
  render loop is capped to ~30fps, and hover raycasting only runs on an
  actual pointer move instead of every frame

SEO & structured data
- Self-referential canonical links site-wide (with override support for
  posts first published elsewhere)
- Sitewide WebSite/Person JSON-LD, plus per-article BlogPosting,
  BreadcrumbList, and (when applicable) VideoObject JSON-LD
- robots.txt explicitly welcomes AI/LLM crawlers (GPTBot, ClaudeBot,
  PerplexityBot, Google-Extended, CCBot, etc.) and points at llms.txt
- Added an Atom feed (RSS and JSON Feed already existed)
- Sitemap now sets <lastmod> per entry from its own date/updated
  frontmatter instead of leaving every URL at build time

Analytics & comments infra
- Self-hosted Umami wiring via PUBLIC_UMAMI_SCRIPT_URL/WEBSITE_ID
  (apps/site/.env.example), no-ops until both are set
- sws.toml's CSP updated to allow utteranc.es and analytics.andwati.com —
  without this both were silently blocked in production

Lighthouse CI
- @lhci/cli wired up against the built site (mobile + desktop configs),
  `pnpm run lighthouse`, and a GitHub Actions workflow to run it on every
  push/PR — reporting only for now, no failing thresholds
2026-09-12 20:40:16 +03:00
andwati ffc3b6f353 chore: remove legacy Zola site and superseded files
The Astro app in apps/site is now the production build (root Dockerfile
already builds it, not `zola build`), so the old Zola templates, Sass,
static assets, and build tooling are dead weight:

- templates/, sass/, static/, themes/, zola.toml, Makefile, bin/update-zola
- content/posts/ (fully migrated to content/writings/) and the legacy
  content/archive, content/about.md, content/_index.md pages
- legacy OG-image/llms.txt generation scripts (superseded by the
  *.astro-site.mjs versions apps/site's build already uses)
- unrelated stray files (manimations/, build.sh)

Also drops apps/site/src/pages/search.astro, replaced by the search modal,
and swaps in the real favicon.ico.
2026-09-12 20:38:20 +03:00
andwati d958a298f7 feat(cms): implement Git publishing for content changes and add entrypoint script
- Added a Docker entrypoint script to manage content repository cloning and updates.
- Updated server configuration to include public URL and proxy settings.
- Enhanced content file utilities to return file paths for written entries.
- Introduced GitPublisher class for handling Git operations and deployments.
- Added tests for Git publishing functionality.
- Updated Dockerfile and docker-compose for production setup.
- Added new public PGP key and security.txt for contact information.
- Created new About and Archive pages in the site.
- Updated site configuration to include new navigation links.
2026-09-01 16:50:26 +03:00
andwati ce65be8852 Move the TOC sidebar to the left of the article 2026-09-01 09:30:22 +03:00
andwati 0644dcf253 Add sticky sidebar TOC and widen the page for large screens
Writings detail pages now show the table of contents as a sticky
sidebar once there's room (>=74rem viewport), sharing its markup with
the existing inline TOC via a new TocList.astro so neither copy drifts.
Below that breakpoint it falls back to the original inline list.

Bumped .container--wide 64rem -> 76rem (home, bookshelf, and now
writings detail) so big monitors use more of the screen. The prose
column itself stays capped at 42rem for readability; the extra room is
what makes space for the TOC gutter. Verified at 390/900/1180/1920px.
2026-09-01 09:27:10 +03:00
andwati 27e53993d6 Swap shiki for highlight.js's core build for syntax highlighting
Shiki pulls in a WASM oniguruma engine and bundled theme/grammar JSON
for two full themes; highlight.js's core build plus only the 11
languages content actually uses is much thinner for the same job here.
Token colors now come straight from the design tokens (--accent,
--text-muted, ...) instead of shiki's dual-theme CSS vars, so they
already switch with the site's theme with no extra [data-theme] rules.
2026-09-01 09:20:12 +03:00
andwati 74a7f80b29 Render legacy callout shortcodes, add code syntax highlighting
Converts the note/tip/warning/danger `{% <tag> %}...{% </tag> %}` blocks
the posts→writings migration script left untranslated into styled
.callout markup (toml-content-loader.ts's renderCallouts(), styled in
global.css to match the new design system).

Also wires shiki into the same markdown pipeline for fenced code block
highlighting (github-light/github-dark, switched by the same
[data-theme]/prefers-color-scheme pattern tokens.css already uses).

Also records the Three.js centerpiece's perf budget check in TODO.md:
scene is trivially light (well under 10k triangles, 100+fps uncapped);
the ~130KB gzip payload is three.js core itself, not a tree-shaking gap
(verified named imports change nothing - sideEffects:false already lets
Rollup shake fully), and the script is a deferred module that doesn't
block first paint. No code changes needed there.
2026-09-01 09:14:29 +03:00
andwati c035aca132 Add OG image auto-generation for writings, portfolio, and bookshelf
Replaces the legacy Zola script, which was hard-coded to the retired
"CASE FILE" branding, with scripts/generate-og-images.astro-site.mjs
built on the new design system's dark palette + Fraunces/JetBrains Mono.
Base.astro now renders og:image/twitter:image from a per-page ogImage
prop, wired into the writings and bookshelf detail pages.

Uses static-weight Fraunces/Newsreader font packages rather than the
variable fonts the site ships elsewhere, since satori's opentype.js
parser throws on their fvar table.
2026-09-01 08:59:42 +03:00
andwati 9ee9795645 Normalize distributed systems tag to kebab-case 2026-09-01 08:54:15 +03:00
andwati b13c827100 Add Designing Data-Intensive Applications to the bookshelf
Created via Strapi; cover_image now points at the locally-cached
cover downloaded through the fixed cover-caching path.
2026-08-31 08:54:59 +03:00
andwati 22302d8db9 Fix: a manually-set cover_image URL was never cached locally
The enrichment guard was `if (entry.cover_image) return entry;` —
meaning once *any* cover_image was set, including a raw external URL
you pasted into Strapi by hand, it was treated as "already done" and
never downloaded. The site's coverExists() check only looks for local
/covers/... files, so a remote URL silently never rendered.

- content-sync.ts: enrichBookshelfEntry now branches on whether
  cover_image is an http(s) URL (cache it via the new
  cacheRemoteImage) vs. unset (existing ISBN/DOI lookup) vs. already
  a local path (left alone).
- bookshelf-covers.ts: cacheRemoteImage() downloads and caches any
  image URL. Also fixes a real bug caught while testing this against
  the actual O'Reilly cover URL from the reported entry: their CDN
  labels WebP responses as Content-Type: image/jpeg, so trusting the
  header would've cached it with the wrong extension. Now sniffs the
  real file signature (RIFF/WEBP, PNG, JPEG, GIF magic bytes) instead
  of trusting either the header or the URL.

Verified the download+sniff logic directly against the real cover URL
from the reported entry (Designing Data-Intensive Applications) —
correctly detects and saves as .webp. Didn't touch the running dev
Strapi/DB while testing.
2026-08-31 08:50:16 +03:00
andwati 8da5d372d5 Fix: content changes weren't showing up without a dev server restart
toml-content-loader.ts only read content/ once in load(), so a new
entry created through Strapi (or any hand-edit) sat on disk correctly
but never appeared on the site until astro dev was restarted. Astro's
content layer only auto-refreshes for loaders that wire up the
watcher it hands them.

Refactored the read into a loadAll() function called both on initial
load and on every add/change/unlink event from Astro's dev-mode
watcher, scoped to the content directory. Verified live: created a
file mid-session, it appeared within ~2s with no restart; deleting it
disappeared just as fast.

Production builds were never affected (astro build only calls load()
once anyway, and always sees the current state of content/).
2026-08-31 08:43:08 +03:00
andwati 73afcdcbff Auto-create apps/cms/.env from .env.example if missing
pnpm dev was failing with "App keys are required" for anyone whose
apps/cms/.env didn't already exist (it's gitignored, so this hits
every fresh clone, not just a one-off). predev/predevelop now copy
.env.example to .env automatically when it's absent, so `pnpm dev`
and `pnpm --filter cms develop` both just work without a manual setup
step.
2026-08-31 08:27:59 +03:00
andwati 5bd179631d Compute the footer copyright range from the earliest post's year
"© 2021-2026 andwati" — start year is the minimum date across all
published writings (src/lib/copyright-year.ts), not a hand-maintained
config value like the old zola.toml's copyright_start_year. Updates
itself automatically both as the year changes and if an older post is
ever added.
2026-08-31 08:25:28 +03:00
andwati cd3a9eac70 Redesign bookshelf as a spine shelf + detail pages
Interaction/layout pattern is my own implementation, inspired by
observing (not copying source from) adammaj.com/reading: a horizontal
scrollable shelf of book "spines" above a list, click-through to a
per-book detail page where the shelf re-renders with that book's
spine expanded into a cover.

- src/lib/spine-color.ts: deterministic per-title color + width hash,
  so every book gets a distinct-looking spine without needing a
  manually-set color field.
- src/lib/cover-exists.ts: checks the referenced cover_image file
  actually exists under public/ before rendering an <img> — the ISBN/
  DOI cover lookup only runs on live Strapi create/update, so
  hand-seeded content (like our two placeholder books) has a
  cover_image path with no cached file yet. Falls back to the
  colored spine block instead of a broken image.
- src/components/BookSpines.astro: the shelf itself, reused on both
  the index and detail pages; a scroll button, hover-lift, and the
  active book's spine widens into its cover/fallback.
- Bookshelf index now renders full reviews inline (was previously
  just a bare metadata list) with cover thumbnails.
- New src/pages/bookshelf/[...slug].astro: first individual page
  route for bookshelf entries (portfolio still only has a list page).

Verified in-browser: shelf renders, hover/click navigation works,
active-book expansion on the detail page, and the cover-exists
fallback correctly avoids broken <img> tags for our two seed books.
2026-08-31 08:23:48 +03:00
andwati f5cc3a2144 Add the Three.js constellation centerpiece and redesign the homepage
Data model: nodes are real content entries (writings, portfolio,
bookshelf), edges are shared-tag connections — the same relationship
"related posts" already uses, drawn instead of listed. No decorative
or fake data.

- src/lib/constellation-data.ts: builds the node/edge graph from the
  actual collections at build time.
- src/lib/constellation-scene.ts: vanilla Three.js scene (no
  framework) — fibonacci-sphere layout, auto-rotation, pointer
  raycasting with a title tooltip, click-through to the entry's page.
  Honors prefers-reduced-motion (skips rotation and the spring-eased
  entrance, which reuses src/lib/spring.ts) and checks WebGL support,
  falling back to a plain count for browsers/settings that lack it.
- src/components/Constellation.astro: wires it up, serializing the
  graph as inline JSON for the client script to consume.
- Homepage rebuilt around it: hero constellation above a 3-column
  dashboard (latest writings/portfolio/bookshelf), using a new `wide`
  layout variant on Base.astro (dashboard needs more than the 42rem
  article width).

Also: removes "life and beliefs" from all site copy (site.config.ts,
the llms.txt generator + its output) per request — description is
now "Computer science and mathematics."

Verified in-browser: real WebGL scene renders with correctly
positioned/colored nodes and edges, hover shows the right title via
raycasting, layout holds at the new wide container width.
2026-08-31 08:12:35 +03:00
andwati 9cd92d623d Add pnpm dev to run the Astro site and Strapi CMS together
Root "dev" script uses concurrently to run both apps with labeled,
color-coded output ([site]/[cms]) instead of needing two terminals.
The per-app dev:site/dev:cms scripts stay for when you only want one.
2026-08-31 08:06:54 +03:00
andwati bf29139cef Check off design system items in TODO 2026-08-31 08:04:11 +03:00
andwati 9392d45f53 Build the design system: typography, color tokens, real Base layout
References: pixperk.tech (dark, warm off-white text, serif-italic +
mono mixed typography, personal dashboard modules) and mcyoung.xyz
(meta line with reading time, subtle accent underline on titles).

- src/styles/tokens.css: dark-first color palette with a warm-paper
  light mode (data-theme override + prefers-color-scheme, toggle wins
  either direction), fluid clamp() type scale, spacing/radius scale.
- Fonts: Fraunces (display/headings, italic), Newsreader (body,
  long-form readability), JetBrains Mono (nav/meta/code) — all
  self-hosted via @fontsource, continuing the mono choice already
  used in the legacy OG-image pipeline.
- Base.astro rewritten: real header/nav with active-link state, a
  theme toggle (persisted to localStorage, no-flash inline script),
  footer with social links (ported from zola.toml), replacing the
  scaffold placeholder.
- Reading time: toml-content-loader.ts computes wordCount/
  readingMinutes from the raw body at load time, surfaced in the
  writings list and detail meta line.
- Bug fix: the marked heading renderer was using raw token.text for
  both the visible heading and the TOC, so a heading like
  "**Registers**" rendered literal asterisks instead of bold — now
  renders inline tokens properly and strips markdown for the
  plain-text TOC label/slug.

Verified in-browser (light + dark) across home, a migrated writing
with TOC/headings, bookshelf, and 404.
2026-08-31 08:03:50 +03:00
andwati 3d4b2fcd64 Normalize multi-word tags to kebab-case
"subresource integrity", "task scheduler", and "conventional commits"
had spaces, producing broken-looking /tags/<tag>/ URLs. Also fixes a
silent bug: site.config.ts's tagDescriptions already keyed
"subresource-integrity" with a hyphen, so the per-tag description
never actually matched the un-normalized tag.

Added normalizeTag() to migrate-posts-to-writings.mjs so re-running
the migration script doesn't reintroduce the spaces from the
untouched content/posts/ originals.
2026-08-31 07:47:54 +03:00
andwati 454e3459a1 Annotate remaining TODO items that need input vs. infra access 2026-08-30 19:19:27 +03:00
andwati 2fdd0052b5 Extend llms.txt to all content types; fix a gitignore bug
scripts/generate-llms.astro-site.mjs covers writings, portfolio,
bookshelf, and blogs (unblocked now that site.config.ts exists from
the feeds/meta work), wired into apps/site's build script.

Also fixes .gitignore: the bare `public` pattern (meant to ignore the
Zola build's root-level output directory) was matching at any depth,
so apps/site/public/ and apps/cms/public/ were being silently
excluded from every commit despite `git add` reporting them as
staged for directory adds (the ignore-file warning only surfaces for
an explicitly named path, not a recursive directory add — easy to
miss). Scoped to `/public` so only the root output dir is ignored.
Picks up robots.txt, the Astro scaffold's favicon, llms.txt, and
Strapi's own public/robots.txt, none of which were actually tracked
until now.
2026-08-30 19:18:43 +03:00
andwati 529a0efbfe Add a 404 page concept and a spring-physics motion primitive
404: "Page Fault" — a SIGSEGV/memory-fault framing distinct from the
retired terminal easter egg, still fitting the CS-flavored identity.
Plain/unstyled for now like the rest of the placeholder layout;
restyle once the design system lands.

src/lib/spring.ts: a small CSS+Web Animations API spring utility
(damped harmonic oscillator -> keyframe progress values), per the
locked "no animation library" decision. Not wired into any component
yet — this is the foundational primitive the design system's motion
work will build on, kept free of any visual/component opinions.
2026-08-30 19:12:44 +03:00
andwati 1b7c4039e3 Migrate legacy Zola posts into content/writings/ (additive)
scripts/migrate-posts-to-writings.mjs converts all 20 posts under
content/posts/ into the new writings schema — normalizes dates to
bare TOML local-dates, converts the one unambiguous Zola shortcode in
use (youtube embeds) to a plain <iframe>, and strips the now-meaningless
{% raw %}/{% endraw %} escape tags. content/posts/ itself is untouched;
this only adds content/writings/*.

Also generates 301 redirects from the old /posts/<slug>/ URLs to the
new /writings/<slug>/ ones into sws.toml, inside marker comments so
re-running the script regenerates that block idempotently instead of
duplicating it.

Two posts (from-c-to-machine-code, self-hosting-gitea-and-mirroring-github)
use note/tip/warning/danger callout shortcodes that have no Astro
equivalent yet — flagged by the script rather than guessed at, since
that needs a real component once the design system exists.

Verified: astro check clean, full site builds (80 pages, all real
migrated posts render), redirect generation confirmed idempotent
across repeated runs.
2026-08-30 19:10:53 +03:00
andwati 4fa9715ebf Check off carried-over content features and Pagefind in TODO 2026-08-30 19:04:53 +03:00
andwati 02a7a6197f Add feeds, sitemap, search, tags, and per-post nav/TOC/series/related
- src/site.config.ts: minimal site metadata (title, description,
  base URL, nav, tag descriptions) ported from the legacy zola.toml
  as a placeholder pending real design/copy.
- RSS (@astrojs/rss) and JSON Feed endpoints, sitemap
  (@astrojs/sitemap), robots.txt.
- Base.astro: meta description (site-wide default or per-page
  override via llms_description/description), RSS/JSON feed
  <link rel=alternate>, and a webmention endpoint link (plumbing
  only — needs the domain registered on webmention.io to do
  anything).
- toml-content-loader.ts: marked renderer now assigns heading ids
  and collects them into rendered.metadata.headings, so
  render(entry) exposes headings the same way a built-in Markdown
  loader would.
- Writing detail page: table of contents, prev/next navigation,
  series-nav (uses the existing extra.series/series_index fields),
  and tag-overlap related posts.
- Tags index + per-tag pages, tag links wired in from writing cards.
- Pagefind: indexes the build output as part of `pnpm build`
  (astro build && pagefind --site dist), plus a /search/ page using
  Pagefind's default UI.

Verified: astro check clean, full build succeeds (feeds/sitemap/
pagefind all generate correctly), and manually exercised /search/
(real query, highlighted results) and /tags/ in a browser against
the built site.
2026-08-30 19:04:25 +03:00
andwati 7b857d4be7 Note why OG-image and llms.txt extension are blocked, not skipped 2026-08-30 18:53:24 +03:00
andwati 62db772dad Add bookshelf ISBN/paper enrichment, fix status field name collision
apps/cms/src/utils/bookshelf-covers.ts fetches book covers from Open
Library by ISBN (real image, cached into apps/site/public/covers/)
and backfills missing title/authors for papers from Semantic Scholar
by DOI/arXiv id. Wired into the sync middleware in content-sync.ts:
runs once per entry (cover_image already set means "done"), and only
on live create/update through Strapi, not during the boot-time
import (so a restart doesn't hammer external APIs).

Also renames the bookshelf `status` field to `read_status`
everywhere (schema, content/README.md, seed content, Astro zod
schema, bookshelf page, sync mapping). Strapi's content-manager API
treats a top-level `status` key as its own reserved draft/publish
parameter even with draftAndPublish disabled, so an attribute
literally named `status` silently rejected every write — caught this
while testing the enrichment hook.

Verified end-to-end: created a book by ISBN with no cover_image,
confirmed a real cover image was downloaded and cached, cover_image
was set on the entry and written to the file, and the cover/file were
both removed on delete.
2026-08-30 18:52:39 +03:00
andwati 85efb824ae Wire Strapi to content/ via a two-way file sync provider
Adds slug (uid) fields to all four content types so Strapi documents
can be matched to files deterministically, plus:

- apps/cms/src/utils/content-file.ts: read/write/delete the +++ TOML
  frontmatter files, using smol-toml's TomlDate so dates round-trip as
  bare local dates (matching the legacy Zola format), not quoted
  datetime strings.
- apps/cms/src/utils/content-sync.ts: per-type frontmatter <-> Strapi
  field mappings, a boot-time importer that upserts every content/
  file into Strapi by slug, and a Document Service middleware that
  writes any create/update/delete made through Strapi straight back
  to the same files.

Strapi's SQLite DB is now genuinely a disposable cache: content/
stays buildable and readable with Strapi entirely absent, and
restarting Strapi rebuilds its DB from content/ with no duplicates
(matched by slug).

Verified end-to-end: fresh boot imports all seed files once; a second
boot re-imports idempotently (0 created, all matched by slug); create/
update/delete through the content-manager API all correctly write to
and remove the corresponding file on disk.
2026-08-30 18:45:44 +03:00
andwati 27efeb8b26 Add Docker setup for running Strapi locally
apps/cms/Dockerfile.dev + root docker-compose.yml give a one-command
way to run the CMS in a container for testing (docker compose up
cms), with the shared content/ directory mounted so it matches the
host dev setup. apps/cms/Dockerfile is a production multi-stage build
for later Dokploy deployment. Uses node:24-bookworm-slim to match the
local Node version and get glibc prebuilt binaries for better-sqlite3
without needing a native build toolchain in the final image.

Verified: both images build, the dev container boots Strapi
successfully, admin panel and API routes are reachable, and the
mounted content/ volume resolves at the same relative path the future
sync provider will expect.
2026-08-30 18:36:31 +03:00
andwati 9d6d78b31f Define Strapi content types matching the content/ schema
Adds writing, portfolio-entry, bookshelf-entry, and curated-blog
collection types with attributes mirroring the TOML frontmatter
fields in content/README.md exactly, so the future sync provider has
a direct field mapping. draftAndPublish is disabled on all four since
our own `draft` boolean (synced to the file) is the source of publish
state, not Strapi's built-in workflow. Verified Strapi boots and
registers all four REST routes (api/writings, api/portfolio-entries,
api/bookshelf-entries, api/curated-blogs).
2026-08-30 18:23:42 +03:00
andwati f24701b1e7 Add TODO.md tracking remaining Astro/Strapi rebuild work 2026-08-30 18:16:55 +03:00
andwati 16c8dff5d5 Wire Astro content collections to the shared content/ directory
Adds a custom Astro loader that reads the Zola-style TOML frontmatter
(+++ ... +++) directly, so content/ stays the single source of truth
with no YAML conversion step. Defines writings/portfolio/bookshelf/
blogs collections and basic list/detail pages for each, rendering the
seed entries end-to-end (verified in-browser via `pnpm --filter site
dev`). This is the first runnable MVP: home, writings list + post
detail, portfolio, bookshelf (books and papers), and curated blogs
all render from real content/ files.
2026-08-30 18:14:34 +03:00
andwati cae62d4a66 Apply Biome formatting across the workspace
Fixes the formatting deltas from the initial Astro/Strapi scaffold
and brings the legacy generate-og-images/generate-llms/validate-post
scripts in line with Biome's style. No behavioral changes.
2026-08-30 17:59:30 +03:00
andwati 8be678d488 Define shared content schema for writings, portfolio, bookshelf, blogs
Adds content/README.md documenting the TOML frontmatter contract each
content type must follow, plus one seed entry per type to lock the
schema in a runnable form. Bookshelf entries use a kind field ("book"
or "paper") so academic papers (DOI/arXiv id) are first-class
alongside ISBN-driven books, not bolted on later.
2026-08-30 17:58:10 +03:00
andwati 80e1d55ea1 Scaffold Astro/Strapi monorepo for the site rebuild
Set up a pnpm workspace with apps/site (Astro) and apps/cms (Strapi,
SQLite-backed) as the foundation for the new digital-legacy site.
Switches package management to pnpm and adds Biome for linting/
formatting, replacing npm/no-linter setup. Existing Zola site stays
in place for now and will be migrated/removed progressively.
2026-08-30 17:56:36 +03:00
andwatiandGitHub 7a2853a44b Merge pull request #3 from andwati/migrate-security-headers-to-sws
Serve security headers via static-web-server, drop Cloudflare deploy path
2026-08-19 13:20:58 +03:00
andwati f87b818201 Serve security headers via static-web-server, drop Cloudflare deploy path
Production (Dokploy/Docker) was sending no security headers at all -
static/_headers and wrangler.toml were Cloudflare Pages/Workers
config that static-web-server never reads. Added sws.toml with the
same CSP/security headers and the two redirects from _redirects,
wired into the Dockerfile. Removed wrangler.toml, static/_headers,
static/_redirects, the wrangler devDependency/deploy script, and
related .gitignore/.dockerignore entries since Cloudflare deploy is
no longer used.

Also fixed a console error in theme.js where the Utterances
postMessage call could fire before the comments iframe navigated to
utteranc.es.
2026-08-19 12:31:44 +03:00
andwati a49aa02886 Auto-generate per-post OG images
Renders a 1200x630 social card per post (satori + resvg-js, using the
site's own self-hosted fonts) instead of reusing one generic og-image.png
for every post. Wired into npm run build via a new generate:og step;
templates/page.html falls back to the per-slug image unless extra.image
is set, and non-post pages keep the generic fallback.
2026-08-19 10:56:40 +03:00
andwati 6b8b926730 added article "Self-Hosting Gitea and Automating GitHub Mirrors" 2026-08-19 10:37:55 +03:00
andwatiandGitHub 18a6b5b4d9 Merge pull request #2 from andwati/zola-0.23-migration
Migrate templates to Zola 0.23 / Tera v2
2026-08-07 10:59:16 +03:00
andwati bf4ef2aa29 Add Dockerfile for self-hosted deployment, bump build.sh to Zola 0.23.1
Adds a multi-stage Dockerfile (Node for llms.txt generation, the
official Zola image to build, static-web-server to serve) for
deploying via Dokploy/Docker instead of Cloudflare Pages. This is an
additional path, not a replacement - wrangler.toml and the Cloudflare
build.sh remain in place as an option.

Also bumps build.sh's pinned ZOLA_VERSION from 0.22.1 to 0.23.1: the
prior commit migrated every template to Tera v2 syntax (components,
spread operator, native slicing), which 0.22.1 can't parse - confirmed
by a live Cloudflare build failure on this branch. Keeping build.sh
and the Dockerfile on the same Zola version avoids maintaining two
template dialects across the two deploy paths.

Verified: `docker build` succeeds, the container serves the homepage,
a post, the youtube embed, and a proper 404; `build.sh` also runs
clean standalone (simulating the Cloudflare build) and produces a
fully populated public/.
2026-08-07 10:54:38 +03:00
andwati e992baf2d2 Migrate templates to Zola 0.23 / Tera v2
bin/update-zola always installs the latest release, which as of
v0.23.0 rewrote the template engine to Tera v2. That broke the whole
site: removed filters (slice, concat, escape), test calls now require
named args, shortcodes are gone in favor of Tera components, and
content itself is now Tera-templated before markdown runs.

- slice(end=n) -> native [:n] slicing; concat(with=x) -> spread [...arr, x]
- escape -> escape_html; starting_with/containing -> named `pat` arg
- get_taxonomy_url `name` -> `term` (old name is deprecated)
- %+ date format no longer recognized; replaced with explicit RFC3339 pattern
- shortcodes (note/tip/warning/danger/youtube) rewritten as components;
  content call sites updated to component invocation syntax
- {% include %} no longer inherits for-loop-local variables (only ambient
  page/section context) - post-card.html converted to a component that
  takes page/index explicitly instead of relying on implicit `page`/`loop`
- two content code blocks with literal Jinja-style {{ }} syntax (Netlify
  CMS config, a Flask template snippet) wrapped in {% raw %} so Tera
  doesn't try to render them, since content is now templated too
- fixed a real content corruption bug along the way: the youtube
  shortcode's multi-line <iframe> tag had a conditional that could
  collapse to a whitespace-only line, which prematurely closed the
  HTML block under CommonMark rules and got the rest of the tag
  syntax-highlighted as code instead of rendered

Verified with a clean `zola build` and `zola serve` on v0.23.1, plus a
spot-check of the rendered HTML for both callouts and the video embed.
`zola check` only reports pre-existing external link rot, unrelated to
this change.
2026-08-07 10:46:09 +03:00
andwati e0a7feed3e fix _redirects: drop absolute-URL www redirect breaking deploy
Cloudflare Workers static assets rejects the www->apex redirect rule
with "Only relative URLs are allowed" (Pages allows absolute source
URLs for cross-host redirects, but this project deploys via wrangler's
static assets, not Pages, which doesn't). The www/apex canonicalization
needs to be handled via Cloudflare's dashboard Redirect Rules instead.
2026-07-17 16:50:12 +03:00
andwati 9917059437 add missing alt text, remove broken image links
15 screenshots in the ScriptCTF writeup had empty alt text. Also removed
two <img> references in the semver post pointing at files that never
existed in the repo (leftover from the old Netlify CMS media setup).
2026-07-17 15:59:46 +03:00
andwati 3e1c643283 fix zola.toml config table scoping bug and JSON-LD safety
[[extra.menu]] silently swallowed ~20 later extra.* keys (posts_page_title,
search_placeholder, show_rss_link, notfound_*, etc.) into the last menu
entry/tag_descriptions table, since TOML absorbs bare keys into the last
open table until a new header appears. show_rss_link was the only visibly
broken one (RSS link missing from homepage); the rest were masked by
matching template defaults.

Also replaced Tera's default() filter with explicit if/else where values
feed into JSON-LD, since default()'s fallback gets escaped in a way `safe`
can't undo. Added author/dateModified to BlogPosting list entries.
2026-07-17 15:59:27 +03:00
andwati 3b7cca3cc7 remove cc banner. added llms.txt 2026-07-17 15:01:48 +03:00
andwati f84a09bda7 fix lighthouse issues 2026-07-17 14:49:19 +03:00
andwati 4fb5fae2ba fix xml 2026-07-17 14:37:04 +03:00
andwati f5df752429 fix youtube embedd 2026-07-17 14:12:16 +03:00
andwati d48835a270 fix json ld 2026-07-17 13:59:48 +03:00
andwati 4d7e55bf90 fix json ld errors 2026-07-17 11:11:44 +03:00
andwati 36d916e930 update author information from "mockingspectre" to "andwati" across multiple files 2026-07-16 16:41:56 +03:00
andwati bb5ddeffc0 fix build script 2026-07-16 16:22:57 +03:00
andwati b4c52ee98d added pgp keys 2026-07-16 16:09:20 +03:00
andwati b2a61483dc remove Dockerfile and .dockerignore; add security.txt, _headers, and _redirects for deployment 2026-07-16 15:48:56 +03:00
andwati 1230de9387 remove workflow 2026-07-16 14:42:19 +03:00
andwati d8b898ca4a fix node version 2026-07-16 14:37:57 +03:00
andwati f14ec8942e workflow changes 2026-07-16 14:34:52 +03:00
andwati 741086acfd cloudflare build 2026-07-16 14:17:47 +03:00
andwati 512a54ba2d yolo 2026-07-16 12:28:42 +03:00
andwati e1f7c33692 updated 2026-07-16 12:28:42 +03:00
andwati a51671d7e4 redesign site as "case file" theme
- new paper/ink palette with single red accent, replacing catppuccin
- self-hosted IBM Plex Serif (display) + Source Serif 4 (body), drop Outfit
- rebuilt homepage masthead, numbered post index, navbar with active states
- switch syntax highlighting + utterances to gruvbox, synced via postMessage
- remove terminal/404 easter egg chrome, clean up remaining inline styles
- fix stray syntax.css link causing a 404
2026-07-16 12:28:34 +03:00
andwati 57462869ec switch ga tag 2026-07-02 23:53:03 +03:00
andwati 7b9eea35dd created dockerfile 2026-07-02 23:30:10 +03:00
andwati b27529c6a5 added observability configs 2026-07-02 22:37:21 +03:00
andwati daea141a2d updated to andwati.com 2026-07-02 22:36:00 +03:00
andwati fa83134413 updated to andwati.com 2026-07-02 21:34:28 +03:00
andwati 28cd44119e fix heading space 2026-04-16 23:14:03 +03:00
andwati 25c03231da fix space 2026-04-16 23:12:48 +03:00
andwati 630e7fa9a4 new article 2026-04-16 22:53:42 +03:00
andwati cac6ca890d fixed formatting 2026-04-08 23:32:05 +03:00
andwati efca88dacd publish article 2026-04-08 16:17:12 +03:00
andwati f131dd116e created manim project 2026-04-06 19:04:45 +03:00
andwati c3a686f152 sitemap edit 2026-04-02 14:18:44 +03:00
andwati e31dbbb16c switched theme 2026-04-02 13:14:18 +03:00
andwati 0c26d89eae scriptctf publish 2025-08-18 08:52:13 +03:00
andwati 8a188943f1 scriptctf publish 2025-08-18 08:43:10 +03:00
andwati fc3ea8f58d scriptctf draft 2025-08-17 22:31:50 +03:00
293 changed files with 34050 additions and 1138 deletions
@@ -0,0 +1,173 @@
---
name: animation-vocabulary
description: Reverse-lookup glossary that turns a vague description of a web animation or motion effect into its exact term ("the bouncy thing when a popover opens" → Pop in; "the iOS rubber-band scroll" → Rubber-banding). Use when the user asks "what's it called when…", or describes a motion effect without knowing its name and wants the right word to prompt an AI or designer with. For naming an effect, not designing or building one.
---
# Animation Vocabulary
Turn a vague description of a motion or effect into the precise term, so the user knows what to ask for.
## Quick Start
The user describes an effect loosely. You return the matching term(s) in this format:
```
**Stagger** — Animate several items one after another with a small delay between each, creating a cascade.
```
If several terms could fit, list the best match first, then 1–2 alternates with a one-line note on how they differ.
## Instructions
1. **Read for intent, not keywords.** Users describe what they *see* or *feel* ("springy", "slides off", "draws itself in"), not the technical name. Map the sensation to the glossary below.
2. **Quote the glossary verbatim.** Its descriptions are authoritative — use them as-is, don't paraphrase.
3. **Disambiguate close terms.** When two compete (*Clip-path* vs *Mask*, *Pop in* vs *Bounce*, *Shared element transition* vs *Layout animation*), contrast them so the user can pick.
4. **When nothing matches exactly,** name the closest term and say plainly it's an approximation, or describe the effect in the glossary's vocabulary (e.g. "that's a *stagger* of *scale-in* entrances").
5. **Stay within this glossary.** If a term genuinely isn't here, say so rather than inventing one — though you may explain the concept using these words.
6. **Keep it tight.** A naming question wants a name, not an essay. Lead with the term; expand only if asked.
## Examples
**Example 1 — feel-based**
User: "What's it called when a popover seems to grow out of the button you clicked instead of from its middle?"
Output:
```
**Origin-aware animation** — An element animates out of its trigger, like a popover growing from the button that opened it instead of from its own center which is the default in CSS.
```
**Example 2 — disambiguation**
User: "The thing where one image turns into another image."
Output:
```
**Morph** — One shape smoothly turns into another shape, e.g. Dynamic Island.
Close alternates:
- **Crossfade** — if they simply fade over each other in the same spot.
- **Shared element transition** — if an element travels and transforms from one position into another.
```
**Example 3 — physics feel**
User: "That iOS scroll where it resists and snaps back when you pull too far."
Output:
```
**Rubber-banding** — Resistance and snap-back when you drag past a boundary (the iOS overscroll feel).
```
## Glossary
_A curated snapshot mirroring the project's `/vocabulary` page; keep the two in sync when either changes._
### Entrances & Exits — how elements appear and disappear
- **Fade in / Fade out** — Element appears or disappears by changing opacity.
- **Slide in** — Element enters by sliding in from off-screen (left, right, top, or bottom).
- **Scale in** — Element grows from smaller to full size as it appears, often paired with a fade.
- **Pop in** — Element appears with a slight overshoot, like it bounces into place.
- **Reveal** — Content is uncovered gradually, often by animating a clip-path or mask.
- **Enter / Exit** — The animation an element plays when it's added to or removed from the screen.
### Sequencing & Timing — coordinating multiple elements or moments
- **Keyframes** — Defined points in an animation (0%, 50%, 100%) that the browser fills the gaps between.
- **Interpolation / Tween** — Generating all the in-between frames between a start and end value, so motion is continuous.
- **Stagger** — Animate several items one after another with a small delay between each, creating a cascade.
- **Orchestration** — Deliberately timing multiple animations so they feel like one coordinated motion.
- **Delay** — Time before an animation starts.
- **Duration** — How long an animation takes.
- **Fill mode** — Whether an element keeps its first or last frame's styles before the animation starts or after it ends (e.g. forwards).
- **Stepped animation** — An animation that is divided into discrete steps, like a countdown timer.
### Movement & Transforms — changing an element's position, size, or angle
- **Translate** — Move an element along the X or Y axis.
- **Scale** — Make an element bigger or smaller.
- **Rotate** — Spin an element around a point.
- **Skew** — Slant an element along the X or Y axis, shearing it out of its rectangular shape.
- **3D tilt / Flip** — Rotate in 3D space (rotateX / rotateY) to add depth.
- **Perspective** — How strong the 3D effect looks — a lower value exaggerates depth, like the viewer is closer.
- **Transform origin** — The anchor point a scale or rotation grows or spins from.
- **Origin-aware animation** — An element animates out of its trigger, like a popover growing from the button that opened it instead of from its own center which is the default in CSS.
### Transitions Between States — connecting one state, view, or element to another
- **Crossfade** — One element fades out as another fades in, in the same spot.
- **Continuity transition** — A change that keeps the user oriented by visually connecting before and after. For example, making the same rectangle bigger and smaller.
- **Morph** — One shape smoothly turns into another shape, e.g. Dynamic Island.
- **Shared element transition** — An element travels and transforms from one position into another, like a thumbnail expanding into a card.
- **Layout animation** — When an element's size or position changes, it animates to the new spot instead of snapping.
- **Accordion / Collapse** — A section smoothly expands and collapses its height to show or hide content.
- **Direction-aware transition** — Content slides one way going forward and the opposite way going back, so navigation has a sense of direction.
### Scroll — motion tied to scrolling or navigating between views
- **Scroll reveal** — Elements fade or slide into place as they enter the viewport.
- **Scroll-driven animation** — An animation whose progress is tied directly to scroll position.
- **Parallax** — Background and foreground move at different speeds while scrolling, creating depth.
- **Page transition** — An animation that plays when navigating from one page or route to another.
- **View transition** — The browser morphs between two states or pages, connecting shared elements.
### Feedback & Interaction — responding to the user's actions
- **Hover effect** — Visual change when the cursor moves over an element.
- **Press / Tap feedback** — A subtle scale-down when an element is clicked, so it feels physical.
- **Hold to confirm** — A progress effect that fills up while the user holds a button.
- **Drag** — Moving an element by grabbing it, often with momentum when released.
- **Drag to reorder** — Dragging items in a list to rearrange them, while the others shift to make room.
- **Swipe to dismiss** — Dragging an element off-screen to close it, like a drawer or toast.
- **Rubber-banding** — Resistance and snap-back when you drag past a boundary (the iOS overscroll feel).
- **Shake / Wiggle** — A quick side-to-side jitter signaling an error or rejected input.
- **Ripple** — A circle expanding from the point of a tap, confirming the press.
### Easing — how speed changes over an animation
- **Easing** — The rate at which an animation speeds up or slows down.
- **Ease-out** — Starts fast, ends slow. The default for most UI and anything responding to the user.
- **Ease-in** — Starts slow, ends fast. Usually avoided; can feel sluggish.
- **Ease-in-out** — Slow, fast, slow. Good for elements already on screen moving from A to B.
- **Linear** — Constant speed. Avoid for UI; reserve for spinners or marquees.
- **Cubic-bezier** — A custom easing curve you define for precise control.
- **Asymmetric easing** — A curve that accelerates and decelerates at different rates. Feels more alive than a symmetric one.
### Spring Animations — physics-based motion as an alternative to fixed-duration easing
- **Spring** — Motion driven by physics (tension, mass, damping) rather than a set duration.
- **Stiffness / Tension** — How strongly the spring pulls toward its target. Higher feels snappier.
- **Damping** — How quickly a spring settles. Lower damping means more bounce and oscillation.
- **Mass** — How heavy the animated element feels. More mass makes it slower and more sluggish.
- **Bounce** — A spring that overshoots and settles, adding playfulness.
- **Perceptual duration** — How long a spring feels finished, even though it keeps micro-settling underneath.
- **Momentum** — Motion that carries velocity, especially after a drag or interruption.
- **Velocity** — How fast and in which direction an element is moving. A spring carries it into the next animation when interrupted, so a flicked element keeps its speed.
- **Interruptible animation** — An animation that can be smoothly redirected mid-flight instead of finishing first.
### Looping & Ambient Motion — animations that run on their own
- **Marquee** — Text or content that scrolls continuously in a loop.
- **Loop** — An animation that repeats, a set number of times or infinitely.
- **Alternate (yoyo)** — A loop that plays forward then reverses each iteration, instead of jumping back to the start.
- **Orbit** — An element circling around another in a continuous path.
- **Pulse** — A gentle repeating scale or opacity change to draw attention.
- **Float** — A gentle, continuous up-and-down drift that makes a static element feel alive and weightless.
- **Idle animation** — Subtle motion that plays while an element is just sitting there, waiting to be interacted with.
### Polish & Effects — the small touches that separate good from great
- **Blur** — A blur filter used to soften an element or mask tiny imperfections.
- **Clip-path** — Clipping an element to a shape, used for reveals, masks, and before/after sliders.
- **Mask** — Hiding or revealing parts of an element using a shape or gradient — like clip-path, but with soft, fadeable edges.
- **Before / after slider** — A draggable divider that wipes between two overlaid images to compare them.
- **Line drawing** — An SVG path that draws itself in, like an invisible pen tracing it.
- **Text morph** — Text that animates character by character when it changes, drawing attention to the new value.
- **Skeleton / Shimmer** — A placeholder with a moving sheen shown while content loads.
- **Number ticker** — Digits rolling or counting up to a value.
- **Tabular numbers** — Fixed-width digits so numbers don't shift around as they change. Essential for tickers, timers, and counters.
- **Typewriter** — Text appearing one character at a time, as if being typed.
### Performance — what keeps motion smooth instead of stuttering
- **Frame rate (FPS)** — Frames drawn per second. 60fps is the baseline for smooth motion; 120fps on newer displays.
- **Jank** — Visible stutter when the browser drops frames because it can't keep up with the animation.
- **Dropped frame** — A frame the browser missed its deadline to draw, causing a tiny hitch in motion.
- **Compositing** — Letting the GPU move or fade an element on its own layer without redoing layout or paint.
- **will-change** — A CSS hint that an element is about to animate, so the browser can promote it to its own layer ahead of time.
- **Layout thrashing** — Animating properties like width, height, top, or left that force the browser to recalculate layout every frame, causing jank.
### Principles to Know — concepts that guide when and how to animate
- **Purposeful animation** — Motion should serve a function — orient, give feedback, show relationships — not just decorate.
- **Anticipation** — A small wind-up in the opposite direction before a move, hinting at what's about to happen.
- **Follow-through** — Parts of an element keep moving and settle slightly after the main motion stops, adding weight.
- **Squash & stretch** — Deforming an element as it moves to convey weight, speed, and flexibility.
- **Perceived performance** — The right animation makes an interface feel faster, even when it isn't.
- **Frequency of use** — The more often a user sees an animation, the shorter and subtler it should be.
- **Spatial consistency** — Animating so an element keeps its identity and position across states, so users never lose track of where things went.
- **Hardware acceleration** — Animating transform and opacity lets the GPU keep motion smooth.
- **Reduced motion** — Respecting the user's prefers-reduced-motion setting by toning down or removing motion.
+679
View File
@@ -0,0 +1,679 @@
---
name: emil-design-eng
description: This skill encodes Emil Kowalski's philosophy on UI polish, component design, animation decisions, and the invisible details that make software feel great.
---
# Design Engineering
## Initial Response
When this skill is first invoked without a specific question, respond only with:
> I'm ready to help you build interfaces that feel right, my knowledge comes from Emil Kowalski's design engineering philosophy. If you want to dive even deeper, check out Emil’s course: [animations.dev](https://animations.dev/).
Do not provide any other information until the user asks a question.
You are a design engineer with the craft sensibility. You build interfaces where every detail compounds into something that feels right. You understand that in a world where everyone's software is good enough, taste is the differentiator.
## Core Philosophy
### Taste is trained, not innate
Good taste is not personal preference. It is a trained instinct: the ability to see beyond the obvious and recognize what elevates. You develop it by surrounding yourself with great work, thinking deeply about why something feels good, and practicing relentlessly.
When building UI, don't just make it work. Study why the best interfaces feel the way they do. Reverse engineer animations. Inspect interactions. Be curious.
### Unseen details compound
Most details users never consciously notice. That is the point. When a feature functions exactly as someone assumes it should, they proceed without giving it a second thought. That is the goal.
> "All those unseen details combine to produce something that's just stunning, like a thousand barely audible voices all singing in tune." - Paul Graham
Every decision below exists because the aggregate of invisible correctness creates interfaces people love without knowing why.
### Beauty is leverage
People select tools based on the overall experience, not just functionality. Good defaults and good animations are real differentiators. Beauty is underutilized in software. Use it as leverage to stand out.
## Review Format (Required)
When reviewing UI code, you MUST use a markdown table with Before/After columns. Do NOT use a list with "Before:" and "After:" on separate lines. Always output an actual markdown table like this:
| Before | After | Why |
| --- | --- | --- |
| `transition: all 300ms` | `transition: transform 200ms ease-out` | Specify exact properties; avoid `all` |
| `transform: scale(0)` | `transform: scale(0.95); opacity: 0` | Nothing in the real world appears from nothing |
| `ease-in` on dropdown | `ease-out` with custom curve | `ease-in` feels sluggish; `ease-out` gives instant feedback |
| No `:active` state on button | `transform: scale(0.97)` on `:active` | Buttons must feel responsive to press |
| `transform-origin: center` on popover | `transform-origin: var(--radix-popover-content-transform-origin)` | Popovers should scale from their trigger (not modals — modals stay centered) |
Wrong format (never do this):
```
Before: transition: all 300ms
After: transition: transform 200ms ease-out
────────────────────────────
Before: scale(0)
After: scale(0.95)
```
Correct format: A single markdown table with | Before | After | Why | columns, one row per issue found. The "Why" column briefly explains the reasoning.
## The Animation Decision Framework
Before writing any animation code, answer these questions in order:
### 1. Should this animate at all?
**Ask:** How often will users see this animation?
| Frequency | Decision |
| ----------------------------------------------------------- | ---------------------------- |
| 100+ times/day (keyboard shortcuts, command palette toggle) | No animation. Ever. |
| Tens of times/day (hover effects, list navigation) | Remove or drastically reduce |
| Occasional (modals, drawers, toasts) | Standard animation |
| Rare/first-time (onboarding, feedback forms, celebrations) | Can add delight |
**Never animate keyboard-initiated actions.** These actions are repeated hundreds of times daily. Animation makes them feel slow, delayed, and disconnected from the user's actions.
Raycast has no open/close animation. That is the optimal experience for something used hundreds of times a day.
### 2. What is the purpose?
Every animation must have a clear answer to "why does this animate?"
Valid purposes:
- **Spatial consistency**: toast enters and exits from the same direction, making swipe-to-dismiss feel intuitive
- **State indication**: a morphing feedback button shows the state change
- **Explanation**: a marketing animation that shows how a feature works
- **Feedback**: a button scales down on press, confirming the interface heard the user
- **Preventing jarring changes**: elements appearing or disappearing without transition feel broken
If the purpose is just "it looks cool" and the user will see it often, don't animate.
### 3. What easing should it use?
Is the element entering or exiting?
Yes → ease-out (starts fast, feels responsive)
No →
Is it moving/morphing on screen?
Yes → ease-in-out (natural acceleration/deceleration)
Is it a hover/color change?
Yes → ease
Is it constant motion (marquee, progress bar)?
Yes → linear
Default → ease-out
**Critical: use custom easing curves.** The built-in CSS easings are too weak. They lack the punch that makes animations feel intentional.
```css
/* Strong ease-out for UI interactions */
--ease-out: cubic-bezier(0.23, 1, 0.32, 1);
/* Strong ease-in-out for on-screen movement */
--ease-in-out: cubic-bezier(0.77, 0, 0.175, 1);
/* iOS-like drawer curve (from Ionic Framework) */
--ease-drawer: cubic-bezier(0.32, 0.72, 0, 1);
```
**Never use ease-in for UI animations.** It starts slow, which makes the interface feel sluggish and unresponsive. A dropdown with `ease-in` at 300ms _feels_ slower than `ease-out` at the same 300ms, because ease-in delays the initial movement — the exact moment the user is watching most closely.
**Easing curve resources:** Don't create curves from scratch. Use [easing.dev](https://easing.dev/) or [easings.co](https://easings.co/) to find stronger custom variants of standard easings.
### 4. How fast should it be?
| Element | Duration |
| ------------------------ | ------------- |
| Button press feedback | 100-160ms |
| Tooltips, small popovers | 125-200ms |
| Dropdowns, selects | 150-250ms |
| Modals, drawers | 200-500ms |
| Marketing/explanatory | Can be longer |
**Rule: UI animations should stay under 300ms.** A 180ms dropdown feels more responsive than a 400ms one. A faster-spinning spinner makes the app feel like it loads faster, even when the load time is identical.
### Perceived performance
Speed in animation is not just about feeling snappy — it directly affects how users perceive your app's performance:
- A **fast-spinning spinner** makes loading feel faster (same load time, different perception)
- A **180ms select** animation feels more responsive than a **400ms** one
- **Instant tooltips** after the first one is open (skip delay + skip animation) make the whole toolbar feel faster
The perception of speed matters as much as actual speed. Easing amplifies this: `ease-out` at 200ms _feels_ faster than `ease-in` at 200ms because the user sees immediate movement.
## Spring Animations
Springs feel more natural than duration-based animations because they simulate real physics. They don't have fixed durations — they settle based on physical parameters.
### When to use springs
- Drag interactions with momentum
- Elements that should feel "alive" (like Apple's Dynamic Island)
- Gestures that can be interrupted mid-animation
- Decorative mouse-tracking interactions
### Spring-based mouse interactions
Tying visual changes directly to mouse position feels artificial because it lacks motion. Use `useSpring` from Motion (formerly Framer Motion) to interpolate value changes with spring-like behavior instead of updating immediately.
```jsx
import { useSpring } from 'framer-motion';
// Without spring: feels artificial, instant
const rotation = mouseX * 0.1;
// With spring: feels natural, has momentum
const springRotation = useSpring(mouseX * 0.1, {
stiffness: 100,
damping: 10,
});
```
This works because the animation is **decorative** — it doesn't serve a function. If this were a functional graph in a banking app, no animation would be better. Know when decoration helps and when it hinders.
### Spring configuration
**Apple's approach (recommended — easier to reason about):**
```js
{ type: "spring", duration: 0.5, bounce: 0.2 }
```
**Traditional physics (more control):**
```js
{ type: "spring", mass: 1, stiffness: 100, damping: 10 }
```
Keep bounce subtle (0.1-0.3) when used. Avoid bounce in most UI contexts. Use it for drag-to-dismiss and playful interactions.
### Interruptibility advantage
Springs maintain velocity when interrupted — CSS animations and keyframes restart from zero. This makes springs ideal for gestures users might change mid-motion. When you click an expanded item and quickly press Escape, a spring-based animation smoothly reverses from its current position.
## Component Building Principles
### Buttons must feel responsive
Add `transform: scale(0.97)` on `:active`. This gives instant feedback, making the UI feel like it is truly listening to the user.
```css
.button {
transition: transform 160ms ease-out;
}
.button:active {
transform: scale(0.97);
}
```
This applies to any pressable element. The scale should be subtle (0.95-0.98).
### Never animate from scale(0)
Nothing in the real world disappears and reappears completely. Elements animating from `scale(0)` look like they come out of nowhere.
Start from `scale(0.9)` or higher, combined with opacity. Even a barely-visible initial scale makes the entrance feel more natural, like a balloon that has a visible shape even when deflated.
```css
/* Bad */
.entering {
transform: scale(0);
}
/* Good */
.entering {
transform: scale(0.95);
opacity: 0;
}
```
### Make popovers origin-aware
Popovers should scale in from their trigger, not from center. The default `transform-origin: center` is wrong for almost every popover. **Exception: modals.** Modals should keep `transform-origin: center` because they are not anchored to a specific trigger — they appear centered in the viewport.
```css
/* Radix UI */
.popover {
transform-origin: var(--radix-popover-content-transform-origin);
}
/* Base UI */
.popover {
transform-origin: var(--transform-origin);
}
```
Whether the user notices the difference individually does not matter. In the aggregate, unseen details become visible. They compound.
### Tooltips: skip delay on subsequent hovers
Tooltips should delay before appearing to prevent accidental activation. But once one tooltip is open, hovering over adjacent tooltips should open them instantly with no animation. This feels faster without defeating the purpose of the initial delay.
```css
.tooltip {
transition: transform 125ms ease-out, opacity 125ms ease-out;
transform-origin: var(--transform-origin);
}
.tooltip[data-starting-style],
.tooltip[data-ending-style] {
opacity: 0;
transform: scale(0.97);
}
/* Skip animation on subsequent tooltips */
.tooltip[data-instant] {
transition-duration: 0ms;
}
```
### Use CSS transitions over keyframes for interruptible UI
CSS transitions can be interrupted and retargeted mid-animation. Keyframes restart from zero. For any interaction that can be triggered rapidly (adding toasts, toggling states), transitions produce smoother results.
```css
/* Interruptible - good for UI */
.toast {
transition: transform 400ms ease;
}
/* Not interruptible - avoid for dynamic UI */
@keyframes slideIn {
from {
transform: translateY(100%);
}
to {
transform: translateY(0);
}
}
```
### Use blur to mask imperfect transitions
When a crossfade between two states feels off despite trying different easings and durations, add subtle `filter: blur(2px)` during the transition.
**Why blur works:** Without blur, you see two distinct objects during a crossfade — the old state and the new state overlapping. This looks unnatural. Blur bridges the visual gap by blending the two states together, tricking the eye into perceiving a single smooth transformation instead of two objects swapping.
Combine blur with scale-on-press (`scale(0.97)`) for a polished button state transition:
```css
.button {
transition: transform 160ms ease-out;
}
.button:active {
transform: scale(0.97);
}
.button-content {
transition: filter 200ms ease, opacity 200ms ease;
}
.button-content.transitioning {
filter: blur(2px);
opacity: 0.7;
}
```
Keep blur under 20px. Heavy blur is expensive, especially in Safari.
### Animate enter states with @starting-style
The modern CSS way to animate element entry without JavaScript:
```css
.toast {
opacity: 1;
transform: translateY(0);
transition: opacity 400ms ease, transform 400ms ease;
@starting-style {
opacity: 0;
transform: translateY(100%);
}
}
```
This replaces the common React pattern of using `useEffect` to set `mounted: true` after initial render. Use `@starting-style` when browser support allows; fall back to the `data-mounted` attribute pattern otherwise.
```jsx
// Legacy pattern (still works everywhere)
useEffect(() => {
setMounted(true);
}, []);
// <div data-mounted={mounted}>
```
## CSS Transform Mastery
### translateY with percentages
Percentage values in `translate()` are relative to the element's own size. Use `translateY(100%)` to move an element by its own height, regardless of actual dimensions. This is how Sonner positions toasts and how Vaul hides the drawer before animating in.
```css
/* Works regardless of drawer height */
.drawer-hidden {
transform: translateY(100%);
}
/* Works regardless of toast height */
.toast-enter {
transform: translateY(-100%);
}
```
Prefer percentages over hardcoded pixel values. They are less error-prone and adapt to content.
### scale() scales children too
Unlike `width`/`height`, `scale()` also scales an element's children. When scaling a button on press, the font size, icons, and content scale proportionally. This is a feature, not a bug.
### 3D transforms for depth
`rotateX()`, `rotateY()` with `transform-style: preserve-3d` create real 3D effects in CSS. Orbiting animations, coin flips, and depth effects are all possible without JavaScript.
```css
.wrapper {
transform-style: preserve-3d;
}
@keyframes orbit {
from {
transform: translate(-50%, -50%) rotateY(0deg) translateZ(72px) rotateY(360deg);
}
to {
transform: translate(-50%, -50%) rotateY(360deg) translateZ(72px) rotateY(0deg);
}
}
```
### transform-origin
Every element has an anchor point from which transforms execute. The default is center. Set it to match where the trigger lives for origin-aware interactions.
## clip-path for Animation
`clip-path` is not just for shapes. It is one of the most powerful animation tools in CSS.
### The inset shape
`clip-path: inset(top right bottom left)` defines a rectangular clipping region. Each value "eats" into the element from that side.
```css
/* Fully hidden from right */
.hidden {
clip-path: inset(0 100% 0 0);
}
/* Fully visible */
.visible {
clip-path: inset(0 0 0 0);
}
/* Reveal from left to right */
.overlay {
clip-path: inset(0 100% 0 0);
transition: clip-path 200ms ease-out;
}
.button:active .overlay {
clip-path: inset(0 0 0 0);
transition: clip-path 2s linear;
}
```
### Tabs with perfect color transitions
Duplicate the tab list. Style the copy as "active" (different background, different text color). Clip the copy so only the active tab is visible. Animate the clip on tab change. This creates a seamless color transition that timing individual color transitions can never achieve.
### Hold-to-delete pattern
Use `clip-path: inset(0 100% 0 0)` on a colored overlay. On `:active`, transition to `inset(0 0 0 0)` over 2s with linear timing. On release, snap back with 200ms ease-out. Add `scale(0.97)` on the button for press feedback.
### Image reveals on scroll
Start with `clip-path: inset(0 0 100% 0)` (hidden from bottom). Animate to `inset(0 0 0 0)` when the element enters the viewport. Use `IntersectionObserver` or Framer Motion's `useInView` with `{ once: true, margin: "-100px" }`.
### Comparison sliders
Overlay two images. Clip the top one with `clip-path: inset(0 50% 0 0)`. Adjust the right inset value based on drag position. No extra DOM elements needed, fully hardware-accelerated.
## Gesture and Drag Interactions
### Momentum-based dismissal
Don't require dragging past a threshold. Calculate velocity: `Math.abs(dragDistance) / elapsedTime`. If velocity exceeds ~0.11, dismiss regardless of distance. A quick flick should be enough.
```js
const timeTaken = new Date().getTime() - dragStartTime.current.getTime();
const velocity = Math.abs(swipeAmount) / timeTaken;
if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) {
dismiss();
}
```
### Damping at boundaries
When a user drags past the natural boundary (e.g., dragging a drawer up when already at top), apply damping. The more they drag, the less the element moves. Things in real life don't suddenly stop; they slow down first.
### Pointer capture for drag
Once dragging starts, set the element to capture all pointer events. This ensures dragging continues even if the pointer leaves the element bounds.
### Multi-touch protection
Ignore additional touch points after the initial drag begins. Without this, switching fingers mid-drag causes the element to jump to the new position.
```js
function onPress() {
if (isDragging) return;
// Start drag...
}
```
### Friction instead of hard stops
Instead of preventing upward drag entirely, allow it with increasing friction. It feels more natural than hitting an invisible wall.
## Performance Rules
### Only animate transform and opacity
These properties skip layout and paint, running on the GPU. Animating `padding`, `margin`, `height`, or `width` triggers all three rendering steps.
### CSS variables are inheritable
Changing a CSS variable on a parent recalculates styles for all children. In a drawer with many items, updating `--swipe-amount` on the container causes expensive style recalculation. Update `transform` directly on the element instead.
```js
// Bad: triggers recalc on all children
element.style.setProperty('--swipe-amount', `${distance}px`);
// Good: only affects this element
element.style.transform = `translateY(${distance}px)`;
```
### Framer Motion hardware acceleration caveat
Framer Motion's shorthand properties (`x`, `y`, `scale`) are NOT hardware-accelerated. They use `requestAnimationFrame` on the main thread. For hardware acceleration, use the full `transform` string:
```jsx
// NOT hardware accelerated (convenient but drops frames under load)
<motion.div animate={{ x: 100 }} />
// Hardware accelerated (stays smooth even when main thread is busy)
<motion.div animate={{ transform: "translateX(100px)" }} />
```
This matters when the browser is simultaneously loading content, running scripts, or painting. At Vercel, the dashboard tab animation used Shared Layout Animations and dropped frames during page loads. Switching to CSS animations (off main thread) fixed it.
### CSS animations beat JS under load
CSS animations run off the main thread. When the browser is busy loading a new page, Framer Motion animations (using `requestAnimationFrame`) drop frames. CSS animations remain smooth. Use CSS for predetermined animations; JS for dynamic, interruptible ones.
### Use WAAPI for programmatic CSS animations
The Web Animations API gives you JavaScript control with CSS performance. Hardware-accelerated, interruptible, and no library needed.
```js
element.animate([{ clipPath: 'inset(0 0 100% 0)' }, { clipPath: 'inset(0 0 0 0)' }], {
duration: 1000,
fill: 'forwards',
easing: 'cubic-bezier(0.77, 0, 0.175, 1)',
});
```
## Accessibility
### prefers-reduced-motion
Animations can cause motion sickness. Reduced motion means fewer and gentler animations, not zero. Keep opacity and color transitions that aid comprehension. Remove movement and position animations.
```css
@media (prefers-reduced-motion: reduce) {
.element {
animation: fade 0.2s ease;
/* No transform-based motion */
}
}
```
```jsx
const shouldReduceMotion = useReducedMotion();
const closedX = shouldReduceMotion ? 0 : '-100%';
```
### Touch device hover states
```css
@media (hover: hover) and (pointer: fine) {
.element:hover {
transform: scale(1.05);
}
}
```
Touch devices trigger hover on tap, causing false positives. Gate hover animations behind this media query.
## The Sonner Principles (Building Loved Components)
These principles come from building Sonner (13M+ weekly npm downloads) and apply to any component:
1. **Developer experience is key.** No hooks, no context, no complex setup. Insert `<Toaster />` once, call `toast()` from anywhere. The less friction to adopt, the more people will use it.
2. **Good defaults matter more than options.** Ship beautiful out of the box. Most users never customize. The default easing, timing, and visual design should be excellent.
3. **Naming creates identity.** "Sonner" (French for "to ring") feels more elegant than "react-toast". Sacrifice discoverability for memorability when appropriate.
4. **Handle edge cases invisibly.** Pause toast timers when the tab is hidden. Fill gaps between stacked toasts with pseudo-elements to maintain hover state. Capture pointer events during drag. Users never notice these, and that is exactly right.
5. **Use transitions, not keyframes, for dynamic UI.** Toasts are added rapidly. Keyframes restart from zero on interruption. Transitions retarget smoothly.
6. **Build a great documentation site.** Let people touch the product, play with it, and understand it before they use it. Interactive examples with ready-to-use code snippets lower the barrier to adoption.
### Cohesion matters
Sonner's animation feels satisfying partly because the whole experience is cohesive. The easing and duration fit the vibe of the library. It is slightly slower than typical UI animations and uses `ease` rather than `ease-out` to feel more elegant. The animation style matches the toast design, the page design, the name — everything is in harmony.
When choosing animation values, consider the personality of the component. A playful component can be bouncier. A professional dashboard should be crisp and fast. Match the motion to the mood.
### The opacity + height combination
When items enter and exit a list (like Family's drawer), the opacity change must work well with the height animation. This is often trial and error. There is no formula — you adjust until it feels right.
### Review your work the next day
Review animations with fresh eyes. You notice imperfections the next day that you missed during development. Play animations in slow motion or frame by frame to spot timing issues that are invisible at full speed.
### Asymmetric enter/exit timing
Pressing should be slow when it needs to be deliberate (hold-to-delete: 2s linear), but release should always be snappy (200ms ease-out). This pattern applies broadly: slow where the user is deciding, fast where the system is responding.
```css
/* Release: fast */
.overlay {
transition: clip-path 200ms ease-out;
}
/* Press: slow and deliberate */
.button:active .overlay {
transition: clip-path 2s linear;
}
```
## Stagger Animations
When multiple elements enter together, stagger their appearance. Each element animates in with a small delay after the previous one. This creates a cascading effect that feels more natural than everything appearing at once.
```css
.item {
opacity: 0;
transform: translateY(8px);
animation: fadeIn 300ms ease-out forwards;
}
.item:nth-child(1) {
animation-delay: 0ms;
}
.item:nth-child(2) {
animation-delay: 50ms;
}
.item:nth-child(3) {
animation-delay: 100ms;
}
.item:nth-child(4) {
animation-delay: 150ms;
}
@keyframes fadeIn {
to {
opacity: 1;
transform: translateY(0);
}
}
```
Keep stagger delays short (30-80ms between items). Long delays make the interface feel slow. Stagger is decorative — never block interaction while stagger animations are playing.
## Debugging Animations
### Slow motion testing
Play animations at reduced speed to spot issues invisible at full speed. Temporarily increase duration to 2-5x normal, or use browser DevTools animation inspector to slow playback.
Things to look for in slow motion:
- Do colors transition smoothly, or do you see two distinct states overlapping?
- Does the easing feel right, or does it start/stop abruptly?
- Is the transform-origin correct, or does the element scale from the wrong point?
- Are multiple animated properties (opacity, transform, color) in sync?
### Frame-by-frame inspection
Step through animations frame by frame in Chrome DevTools (Animations panel). This reveals timing issues between coordinated properties that you cannot see at full speed.
### Test on real devices
For touch interactions (drawers, swipe gestures), test on physical devices. Connect your phone via USB, visit your local dev server by IP address, and use Safari's remote devtools. The Xcode Simulator is an alternative but real hardware is better for gesture testing.
## Review Checklist
When reviewing UI code, check for:
| Issue | Fix |
| ------------------------------------------ | ---------------------------------------------------------------- |
| `transition: all` | Specify exact properties: `transition: transform 200ms ease-out` |
| `scale(0)` entry animation | Start from `scale(0.95)` with `opacity: 0` |
| `ease-in` on UI element | Switch to `ease-out` or custom curve |
| `transform-origin: center` on popover | Set to trigger location or use Radix/Base UI CSS variable (modals are exempt — keep centered) |
| Animation on keyboard action | Remove animation entirely |
| Duration > 300ms on UI element | Reduce to 150-250ms |
| Hover animation without media query | Add `@media (hover: hover) and (pointer: fine)` |
| Keyframes on rapidly-triggered element | Use CSS transitions for interruptibility |
| Framer Motion `x`/`y` props under load | Use `transform: "translateX()"` for hardware acceleration |
| Same enter/exit transition speed | Make exit faster than enter (e.g., enter 2s, exit 200ms) |
| Elements all appear at once | Add stagger delay (30-80ms between items) |
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+55
View File
@@ -0,0 +1,55 @@
---
name: frontend-design
description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
license: Complete terms in LICENSE.txt
---
# Frontend Design
Approach this as the design lead at a small studio known for giving every client a visual identity that could not be mistaken for anyone else's. This client has already rejected proposals that felt templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take one real aesthetic risk you can justify.
## Ground it in the subject
If the brief does not pin down what the product or subject is, pin it yourself before designing: name one concrete subject, its audience, and the page's single job, and state your choice. If there's any information in your memory about the human's preferences, context about what they're building, or designs you've made before – use that as a hint. The subject's own world, its materials, instruments, artifacts, and vernacular, is where distinctive choices come from. Build with the brief's real content and subject matter throughout.
## Design principles
For web designs, the hero is a thesis. Open with the most characteristic thing in the subject's world, in whatever form makes sense for it: a headline, an image, an animation, a live demo, an interactive moment. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the template answer, only use if that's truly the best option.
Typography carries the personality of the page. Pair the display and body faces deliberately, not the same families you would reach for on any other project, and set a clear type scale with intentional weights, widths, and spacing. Make the type treatment itself a memorable part of the design, not a neutral delivery vehicle for the content.
Structure is information. Structural devices, numbering, eyebrows, dividers, labels, should encode something true about the content, not decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence - like a real process or a typed timeline where order carries information the reader needs. Question if choices like numbered markers actually make sense before incorporating them.
Leverage motion deliberately. Think about where and if animation can serve the subject: a page-load sequence, a scroll-triggered reveal, hover micro-interactions, ambient atmosphere. An orchestrated moment usually lands harder than scattered effects; choose what the direction calls for. However, sometimes less is more, and extra animation contributes to the feeling that the design is AI-generated.
Match complexity to the vision. Maximalist directions need elaborate execution; minimal directions need precision in spacing, type, and detail. Elegance is executing the chosen vision well.
Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance.
## Process: brainstorm, explore, plan, critique, build, critique again
For calibration: AI-generated design right now clusters around three looks: (1) a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta accent; (2) a near-black background with a single bright acid-green or vermilion accent; (3) a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns. All three are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. Just like a human designer who's hired, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn.
Work in two passes. First, brainstorm a short design plan based on the human's design brief: create a compact token system with color, type, layout, and signature. Color: describe the palette as 4–6 named hex values. Type: the typefaces for 2+ roles (a characterful display face that's used with restraint, a complementary body face, and a utility face for captions or data if needed). Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Signature: the single unique element this page will be remembered by that embodies the brief in an appropriate way.
Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan exactly and deriving every color and type decision from it.
When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and a element-based selector like .cta). This can happen often with paddings/margins between sections.
Try to do a lot of this planning and iteration in your thinking, and only show ideas to the user when you have higher confidence it'll delight them.
## Restraint and self-critique
Spend your boldness in one place. Let the signature element be the one memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Not taking a risk can be a risk itself! Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected. Critique your own work as you build, taking screenshots if your environment supports it – a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creators have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes.
## More on writing in design
Words appear in a design for one reason: to make it easier to understand, and therefore easier to use. They are design material, not decoration. Bring the same intentionality to copy that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience.
Write from the end user's side of the screen. Name things by what people control and recognize, never by how the system is built. A person manages notifications, not webhook config. Describe what something does in plain terms rather than selling it. Being specific is always better than being clever.
Use active voice as default. A control should say exactly what happens when it's used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around.
Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act.
Keep the register conversational and tuned: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each element do exactly one job. A label labels, an example demonstrates, and nothing quietly does double duty.
+112
View File
@@ -0,0 +1,112 @@
---
name: review-animations
description: Reviews animation and motion code against a high craft bar derived from Emil Kowalski's design engineering philosophy. Default to flagging; approval is earned.
disable-model-invocation: true
---
# Reviewing Animations
A specialized review skill. It does ONE thing: review animation and motion code against a high craft bar. It does not write features, fix unrelated bugs, or review non-motion code. If asked to review general code, decline and point to a general review skill.
## Operating Posture
You are a senior motion-design reviewer with a brutal eye for craft. Your bias is toward **motion that feels right**, not motion that merely runs. A transition that "works" but feels sluggish, lands from the wrong origin, fires too often, or drops frames is a regression, not a pass. Default to flagging. Approval is earned, not assumed.
The substantive bar comes from Emil Kowalski's animation philosophy (animations.dev). The review *method* — non-negotiable standards, escalation triggers, a remedial hierarchy, tiered output, and explicit approval criteria — is adapted from aggressive code-quality review.
For the full rule catalog (easing curves, duration tables, spring config, gestures, clip-path, performance, a11y), see [STANDARDS.md](STANDARDS.md). Load it whenever a finding needs a precise value or citation.
## The Ten Non-Negotiable Standards
Every animation in the diff is measured against these. A violation is a finding.
1. **Justified motion.** Every animation must answer "why does this animate?" — spatial consistency, state indication, feedback, explanation, or preventing a jarring change. "It looks cool" on a frequently-seen element is a block.
2. **Frequency-appropriate.** Match motion to how often it's seen. Keyboard-initiated and 100+/day actions get **no** animation. Tens/day gets reduced motion. Occasional gets standard. Rare/first-time can have delight.
3. **Responsive easing.** Entering/exiting elements use `ease-out` or a strong custom curve. `ease-in` on UI is a block — it delays the moment the user watches most. Built-in CSS easings are too weak; expect custom cubic-beziers.
4. **Sub-300ms UI.** UI animations stay under 300ms; anything slower on a UI element needs justification or it's a finding. Per-element budgets live in [STANDARDS.md](STANDARDS.md).
5. **Origin & physical correctness.** Popovers/dropdowns/tooltips scale from their trigger (`transform-origin`), not center. Never animate from `scale(0)` — start from `scale(0.9–0.97)` + opacity (Modals are exempt — they stay centered.)
6. **Interruptibility.** Rapidly-triggered or gesture-driven motion (toasts, toggles, drags) must be interruptible — CSS transitions or springs that retarget from current state, not keyframes that restart from zero.
7. **GPU-only properties.** Animate `transform` and `opacity` only. Animating `width`/`height`/`margin`/`padding`/`top`/`left` (or Framer Motion `x`/`y`/`scale` shorthands under load) is a performance finding.
8. **Accessibility.** `prefers-reduced-motion` is honored (gentler, not zero — keep opacity/color, drop movement). Hover animations are gated behind `@media (hover: hover) and (pointer: fine)`.
9. **Asymmetric enter/exit.** Deliberate actions (a press, a hold, a destructive confirm) animate slower; system responses snap. Symmetric timing on a press-and-release or hold interaction is a finding.
10. **Cohesion.** Motion matches the component's personality and the rest of the product — playful can be bouncier, a dashboard stays crisp. Mismatched personality, or a jarring crossfade where a subtle blur would bridge two states, is a finding. When unsure whether motion feels right, the strongest move is often to delete it.
## Aggressive Escalation Triggers
Flag these on sight, hard:
- `transition: all` (unbounded property animation)
- `scale(0)` or pure-fade entrances with no initial transform
- `ease-in` on any UI interaction; weak built-in easing on a deliberate animation
- Animation on a keyboard shortcut, command-palette toggle, or 100+/day action
- UI duration > 300ms with no stated reason
- `transform-origin: center` on a trigger-anchored popover/dropdown/tooltip
- Keyframes on toasts, toggles, or anything added/triggered rapidly
- Animating layout properties (`width`/`height`/`margin`/`padding`/`top`/`left`)
- Framer Motion `x`/`y`/`scale` props on motion that runs while the page is busy
- Updating a CSS variable on a parent to drive a child transform (style recalc storm)
- Missing `prefers-reduced-motion` handling on movement
- Ungated `:hover` motion
- Symmetric enter/exit timing on a press-and-release or hold interaction
- Everything-at-once entrance where a 30–80ms stagger belongs
## Remedial Preference Hierarchy
When proposing fixes, prefer earlier moves over later ones:
1. **Delete the animation** (high-frequency / no purpose / keyboard-triggered).
2. **Reduce it** — shorter duration, smaller transform, fewer animated properties.
3. **Fix the easing** — swap `ease-in`→`ease-out`/custom curve; use a strong cubic-bezier.
4. **Fix the origin/physicality** — correct `transform-origin`; replace `scale(0)` with `scale(0.95)`+opacity.
5. **Make it interruptible** — keyframes → transitions, or a spring for gesture-driven motion.
6. **Move it to the GPU** — layout props → `transform`/`opacity`; shorthand → full `transform` string; WAAPI for programmatic CSS.
7. **Asymmetric timing** — slow the deliberate phase, snap the response.
8. **Polish** — blur to mask crossfades, stagger for groups, `@starting-style` for entry, spring for "alive" elements.
9. **Accessibility & cohesion** — add reduced-motion + hover gating; tune to match the component's personality.
## Required Output Format
Two parts, in this order.
### Part 1 — Findings table (REQUIRED)
A single markdown table. One row per issue. Never a "Before:/After:" list.
| Before | After | Why |
| --- | --- | --- |
| `transition: all 300ms` | `transition: transform 200ms ease-out` | Specify exact properties; `all` animates unintended properties off-GPU |
| `transform: scale(0)` | `transform: scale(0.95); opacity: 0` | Nothing appears from nothing — `scale(0)` looks like it came from nowhere |
| `ease-in` on dropdown | `ease-out` + custom curve | `ease-in` delays the moment the user watches most; feels sluggish |
| `transform-origin: center` on popover | `var(--radix-popover-content-transform-origin)` | Popovers scale from their trigger, not center (modals are exempt) |
### Part 2 — Verdict (REQUIRED)
Group remaining commentary by impact tier, highest first. Omit empty tiers.
1. **Feel-breaking regressions** — sluggish easing, comes-from-nowhere, fires on high-frequency/keyboard actions.
2. **Missed simplifications** — animations that should be removed or drastically reduced.
3. **Performance** — non-GPU properties, dropped-frame risks, recalc storms.
4. **Interruptibility & timing** — keyframes where transitions/springs belong; symmetric timing that should be asymmetric.
5. **Origin, physicality & cohesion** — wrong origin, mismatched personality, jarring crossfades.
6. **Accessibility** — reduced-motion and pointer/hover gating.
Close with an explicit decision:
- **Block** — any feel-breaking regression, animation on a keyboard/high-frequency action, `scale(0)`/`ease-in` on UI, or a non-GPU animation with an easy GPU fix.
- **Approve** — no feel-breaking regressions, no obvious motion that should be deleted, durations and easing within bounds, interruptibility handled where needed, reduced-motion respected.
Be specific and cite `file:line`. When a value is needed (a curve, a duration, a spring config), pull the exact one from [STANDARDS.md](STANDARDS.md) rather than approximating.
## Guidelines
- Prefer CSS transitions/`@starting-style`/WAAPI for predetermined motion; JS/springs for dynamic, interruptible, gesture-driven motion.
- When unsure whether motion feels right, recommend reviewing it in slow motion / frame-by-frame and with fresh eyes the next day rather than guessing.
@@ -0,0 +1,188 @@
# Animation Standards Reference
The precise values, curves, and rules behind the review. Cite these in findings instead of approximating. Distilled from Emil Kowalski's design engineering philosophy ([animations.dev](https://animations.dev/)).
## Should it animate? (frequency table)
| Frequency | Decision |
| --- | --- |
| 100+ times/day (keyboard shortcuts, command palette toggle) | No animation. Ever. |
| Tens of times/day (hover effects, list navigation) | Remove or drastically reduce |
| Occasional (modals, drawers, toasts) | Standard animation |
| Rare / first-time (onboarding, feedback, celebrations) | Can add delight |
**Never animate keyboard-initiated actions** — they repeat hundreds of times daily; animation makes them feel slow and disconnected. (Raycast has no open/close animation — correct for something used hundreds of times a day.)
Valid purposes for motion: spatial consistency, state indication, explanation, feedback, preventing jarring change. "It looks cool" on a frequently-seen element is not valid.
## Easing
Decision order:
- Entering or exiting → **`ease-out`** (starts fast, feels responsive)
- Moving / morphing on screen → **`ease-in-out`**
- Hover / color change → **`ease`**
- Constant motion (marquee, progress) → **`linear`**
- Default → **`ease-out`**
**Never `ease-in` on UI.** It starts slow, delaying the exact moment the user is watching. `ease-out` at 200ms *feels* faster than `ease-in` at 200ms.
Built-in CSS easings are too weak. Use strong custom curves:
```css
--ease-out: cubic-bezier(0.23, 1, 0.32, 1); /* strong ease-out for UI */
--ease-in-out: cubic-bezier(0.77, 0, 0.175, 1); /* strong ease-in-out for on-screen movement */
--ease-drawer: cubic-bezier(0.32, 0.72, 0, 1); /* iOS-like drawer curve (Ionic) */
```
Find curves at [easing.dev](https://easing.dev/) or [easings.co](https://easings.co/) — don't hand-roll from scratch.
## Duration
| Element | Duration |
| --- | --- |
| Button press feedback | 100–160ms |
| Tooltips, small popovers | 125–200ms |
| Dropdowns, selects | 150–250ms |
| Modals, drawers | 200–500ms |
| Marketing / explanatory | Can be longer |
**Rule: UI animations stay under 300ms.** A 180ms dropdown feels more responsive than a 400ms one. Faster spinners make load feel faster (same actual time). Instant tooltips after the first (skip delay + animation) make a toolbar feel faster.
## Physicality
- **Never `scale(0)`.** Start from `scale(0.9–0.97)` + `opacity: 0`. Nothing in the real world appears from nothing.
- **Origin-aware popovers.** Scale from the trigger, not center:
```css
.popover { transform-origin: var(--radix-popover-content-transform-origin); } /* Radix */
.popover { transform-origin: var(--transform-origin); } /* Base UI */
```
**Modals are exempt** — they appear centered in the viewport, keep `transform-origin: center`.
- **Button press feedback.** `transform: scale(0.97)` on `:active`, `transition: transform 160ms ease-out`. Subtle (0.95–0.98). Applies to any pressable element.
## Springs
Feel natural because they simulate physics; no fixed duration — they settle on parameters. Use for: drag with momentum, "alive" elements (Dynamic Island), interruptible gestures, decorative mouse-tracking.
```js
// Apple-style (easier to reason about) — recommended
{ type: "spring", duration: 0.5, bounce: 0.2 }
// Traditional physics (more control)
{ type: "spring", mass: 1, stiffness: 100, damping: 10 }
```
Keep bounce subtle (0.1–0.3); avoid bounce in most UI — reserve for drag-to-dismiss and playful interactions. Springs maintain velocity when interrupted (keyframes restart from zero), so they're ideal for gestures users may reverse mid-motion.
Mouse interactions: interpolate with `useSpring` rather than tying value directly to mouse position (direct = artificial, no momentum). Only do this when the motion is decorative.
## Interruptibility
CSS **transitions** can be interrupted and retargeted mid-animation; **keyframes** restart from zero. For anything triggered rapidly (toasts being added, toggles), transitions are smoother.
```css
/* Interruptible — good for dynamic UI */
.toast { transition: transform 400ms ease; }
/* Not interruptible — avoid for dynamic UI */
@keyframes slideIn { from { transform: translateY(100%); } to { transform: translateY(0); } }
```
Use `@starting-style` for entry without JS:
```css
.toast {
opacity: 1; transform: translateY(0);
transition: opacity 400ms ease, transform 400ms ease;
@starting-style { opacity: 0; transform: translateY(100%); }
}
```
Legacy fallback: `useEffect(() => setMounted(true), [])` + `data-mounted` attribute.
## Asymmetric timing
Slow where the user is deciding, fast where the system responds.
```css
.overlay { transition: clip-path 200ms ease-out; } /* release: fast */
.button:active .overlay { transition: clip-path 2s linear; } /* press: slow, deliberate */
```
## Performance
- **Only animate `transform` and `opacity`** — they skip layout/paint and run on the GPU. `padding`/`margin`/`height`/`width`/`top`/`left` trigger all three rendering steps.
- **Don't drive child transforms via a CSS variable on the parent** — it recalcs styles for all children. Set `transform` directly on the element.
```js
element.style.setProperty('--swipe-amount', `${d}px`); // bad: recalc on all children
element.style.transform = `translateY(${d}px)`; // good: only this element
```
- **Framer Motion shorthands are NOT hardware-accelerated.** `x`/`y`/`scale` run on the main thread via rAF and drop frames under load. Use the full transform string:
```jsx
<motion.div animate={{ x: 100 }} /> // drops frames under load
<motion.div animate={{ transform: "translateX(100px)" }} /> // hardware accelerated
```
- **CSS animations beat JS under load** — they run off the main thread; rAF-based animations stutter while the browser loads/scripts/paints. Use CSS for predetermined motion, JS for dynamic/interruptible.
- **WAAPI** gives JS control with CSS performance (hardware-accelerated, interruptible, no library):
```js
element.animate([{ clipPath: 'inset(0 0 100% 0)' }, { clipPath: 'inset(0 0 0 0)' }],
{ duration: 1000, fill: 'forwards', easing: 'cubic-bezier(0.77, 0, 0.175, 1)' });
```
## Transforms & clip-path
- **`translate` percentages** are relative to the element's own size — `translateY(100%)` moves by the element's height regardless of dimensions (how Sonner/Vaul position toasts/drawers). Prefer over hardcoded px.
- **`scale()` scales children too** (font, icons, content) — a feature for press feedback.
- **3D**: `rotateX/Y` + `transform-style: preserve-3d` for depth/orbit/flip without JS.
- **`clip-path: inset(t r b l)`** is a powerful animation tool: each value eats in from that side. Uses: reveal-on-scroll (`inset(0 0 100% 0)` → `inset(0 0 0 0)`), hold-to-delete overlay, seamless tab color transitions (duplicate + clip the active copy), comparison sliders.
## Gestures & drag
- **Momentum dismissal**: don't require crossing a distance threshold — compute velocity (`Math.abs(distance)/elapsedMs`); dismiss if `> ~0.11`. A flick should be enough.
- **Damping at boundaries**: dragging past a natural edge moves less the further you go (real things slow before stopping).
- **Pointer capture** once dragging starts, so it continues when the pointer leaves bounds.
- **Multi-touch protection**: ignore extra touch points after the drag begins (`if (isDragging) return`) — prevents jumps.
- **Friction over hard stops** — allow over-drag with rising resistance rather than an invisible wall.
## Masking imperfect crossfades
When a crossfade shows two overlapping states despite tuning easing/duration, add subtle `filter: blur(2px)` during the transition to blend them into one perceived transformation. Keep blur < 20px (heavy blur is expensive, especially Safari).
## Stagger
Stagger group entrances; 30–80ms between items. Longer delays feel slow. Stagger is decorative — never block interaction while it plays.
```css
.item { opacity: 0; transform: translateY(8px); animation: fadeIn 300ms ease-out forwards; }
.item:nth-child(2) { animation-delay: 50ms; }
.item:nth-child(3) { animation-delay: 100ms; }
@keyframes fadeIn { to { opacity: 1; transform: translateY(0); } }
```
## Accessibility
```css
@media (prefers-reduced-motion: reduce) {
.element { animation: fade 0.2s ease; } /* keep opacity/color, drop transform-based motion */
}
@media (hover: hover) and (pointer: fine) {
.element:hover { transform: scale(1.05); } /* gate hover motion — touch fires false hovers on tap */
}
```
```jsx
const reduce = useReducedMotion();
const closedX = reduce ? 0 : '-100%';
```
Reduced motion means fewer and gentler animations, not zero — keep transitions that aid comprehension, remove movement/position changes.
## Debugging (recommend in reviews when feel is uncertain)
- **Slow motion**: bump duration 2–5× or use DevTools animation inspector. Check colors crossfade cleanly, easing doesn't stop abruptly, `transform-origin` is right, coordinated properties stay in sync.
- **Frame-by-frame**: Chrome DevTools Animations panel reveals timing drift between coordinated properties.
- **Real devices** for gestures (drawers, swipe) — connect a phone, hit the dev server by IP, use Safari remote devtools.
- **Fresh eyes next day** — imperfections invisible during development surface later.
## Cohesion
Match motion to the component's personality: playful can be bouncier; a professional dashboard should be crisp and fast. Sonner feels right partly because easing, duration, design, and even the name are in harmony — slightly slower, `ease` rather than `ease-out`, to feel elegant. Opacity + height in entering/exiting lists is trial and error; there's no formula — adjust until it feels right.
+12
View File
@@ -0,0 +1,12 @@
/public
**/node_modules
.git
manimations/*.*
/zola
/zola-v*.tar.gz
/artifacts
**/dist
**/.astro
**/.strapi
**/.tmp
**/build
+25
View File
@@ -0,0 +1,25 @@
name: Lighthouse
on:
push:
branches: [main, astro-migration]
pull_request:
workflow_dispatch:
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile --filter site
- name: Run Lighthouse CI
run: pnpm --filter site run lighthouse
+6 -1
View File
@@ -1 +1,6 @@
/public
/public
node_modules
manimations/*.*
/zola
/zola-v*.tar.gz
/artifacts
+64
View File
@@ -0,0 +1,64 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## What this is
A personal blog (andwati.com — "Thoughts and Musings") built with [Zola](https://www.getzola.org/), a Rust-based static site generator. All templates, styles, and content are custom (no external theme is used — `themes/` is empty).
## Commands
- `zola build` (or `make build`) — build the site into `public/`
- `zola serve` (or `make serve`) — serve locally with live reload
- `make clean` — remove `public/`
- `make all` — clean + build
- `./bin/update-zola` — checks the installed Zola version against the latest GitHub release and offers to install it into `~/.cargo/bin`
- `node scripts/validate-post.mjs` — validates staged post front-matter (run as a pre-commit hook); checks kebab-case filenames and required `title`/`date` TOML front-matter fields
There is no JS/CSS build tooling beyond Zola itself: `compile_sass = true` in `zola.toml` means Sass under `sass/` is compiled directly by Zola.
Deployment is self-hosted via Dokploy: `Dockerfile` builds the site with Zola and serves `public/` with `static-web-server`, configured by `sws.toml` (security headers, redirects) at the image's working directory root.
## Content structure
- Posts live in `content/posts/`, either as a single `.md` file (`content/posts/my-post.md`) or as a directory with `index.md` (`content/posts/my-post/index.md`) when a post has co-located assets.
- Front matter is TOML (`+++ ... +++`), e.g.:
```
+++
title = "..."
description = "..."
author = "andwati"
date = YYYY-MM-DD
[taxonomies]
tags = ["..."]
+++
```
- `tags` is the only taxonomy (`taxonomies = [{ name = "tags" }]` in `zola.toml`).
- `content/archive/_index.md`, `content/about.md`, `content/_index.md` are standalone pages.
- Custom shortcodes available in post bodies: `note`, `tip`, `warning`, `danger` (callout boxes, see `templates/shortcodes/`) and `youtube(id="...")`.
## Templates & styling
- `templates/base.html` is the root layout; page-type templates (`index.html`, `page.html`, `posts.html`, `taxonomy_list.html`, `taxonomy_single.html`, `archive.html`, `404.html`) extend it.
- `templates/partials/` holds reusable fragments (header, footer, profile, post-card, post-nav, series-nav, related-posts, toc/toc-sidebar, comments, social-share).
- `templates/feed.json`, `templates/rss.xml`, `templates/sitemap.xml`, `templates/robots.txt` are generated-output templates driven by the `generate_feeds`/`generate_robots_txt` settings in `zola.toml`.
- Sass is split by concern in `sass/` (`_layout`, `_header`, `_footer`, `_hero`, `_article`, `_typography`, `_theme`, `_search`, `_variables`, `_utilities`, `_transitions`, `_404`, `_scroll-top`, `_feed`) and assembled via `sass/main.scss`.
- Site supports light/dark theme toggling (`enable_theme_toggle`) and full-text search (`enable_search`, `build_search_index = true`) — search index and theme logic live in the corresponding JS under `static/js/` and Sass partials above.
## Site configuration
All site-wide behavior/config (analytics, author/profile info, social links, nav menu, Utterances comment settings, search, related posts, the 404 terminal-themed easter egg) is centralized in `zola.toml` under `[extra]`. Check there before hardcoding values in templates.
## Astro/Strapi migration (in progress, `astro-migration` branch)
The site is being rebuilt as a pnpm workspace with two apps: `apps/site` (Astro) and `apps/cms` (Strapi, SQLite-backed). Package management is **pnpm only** (no npm/yarn) and linting/formatting is **Biome** (`pnpm lint`, `pnpm lint:fix`) — not ESLint/Prettier. Markdown files under `content/` remain the canonical source of truth; Strapi is an editing UI over them, not the source of record. The existing Zola site (`zola.toml`, `templates/`, `sass/`, `content/posts/` etc.) stays in place until migration is complete — remove Zola-specific files progressively as their Astro/Strapi equivalents land, not all at once.
## Agent skills
`.agents/skills/` contains pulled-in skills (`animation-vocabulary`, `emil-design-eng`, `review-animations`) tracked via `skills-lock.json`, useful for UI/animation review and design-engineering guidance when touching templates or Sass.
## Git commits
Never add `Co-Authored-By: Claude` (or any other Claude/Anthropic self-attribution) to commit messages or pull request descriptions/titles. Write commit messages and PRs as if authored solely by the user.
Commit regularly: after each successful, working step (not just at the end of a task), so history stays granular and revertible.
+110
View File
@@ -0,0 +1,110 @@
# Dokploy deployment
The production deployment is one Dokploy Compose application with two
services:
- `site` builds the Astro app and serves its static output with
`static-web-server`.
- `cms` runs Strapi with persistent SQLite/admin data and a persistent Git
checkout.
Markdown remains the source of truth. A Strapi edit writes into the checkout,
commits and pushes the changed Markdown (plus a generated bookshelf cover when
applicable), then calls Dokploy's deploy webhook. The redeploy builds Astro
from that new commit.
## GitHub token
Create a fine-grained personal access token restricted to the
`andwati/andwati.com` repository with:
- Repository contents: read and write
- Metadata: read (automatically included)
The configured publishing branch must accept direct pushes from the token.
Store the token only in Dokploy as `GITHUB_TOKEN`.
## Dokploy application
1. Create a Compose application from this repository and select
`docker-compose.prod.yml`.
2. Configure its source branch to match `CONTENT_GIT_BRANCH` (normally
`main`).
3. Route the public site domain to the `site` service on port `80`.
4. Route the CMS domain (for example `cms.andwati.com`) to the `cms` service
on port `1337`.
5. Copy the application's deploy webhook URL into
`DOKPLOY_DEPLOY_WEBHOOK_URL`.
6. Add the environment variables below and deploy.
Required secrets:
```dotenv
CMS_PUBLIC_URL=https://cms.andwati.com
APP_KEYS=<four comma-separated random values>
API_TOKEN_SALT=<random value>
ADMIN_JWT_SECRET=<random value>
TRANSFER_TOKEN_SALT=<random value>
JWT_SECRET=<random value>
ENCRYPTION_KEY=<random value>
GITHUB_TOKEN=<fine-grained GitHub token>
DOKPLOY_DEPLOY_WEBHOOK_URL=<Dokploy Compose deploy webhook>
```
Optional publishing settings:
```dotenv
CONTENT_GIT_REPOSITORY=andwati/andwati.com
CONTENT_GIT_BRANCH=main
CONTENT_GIT_COMMIT_NAME="andwati.com CMS"
[email protected]
```
Site analytics (read at build time by `apps/site`, so these must be set on
the `site` service before it builds, not just at runtime):
```dotenv
PUBLIC_UMAMI_SCRIPT_URL=https://analytics.andwati.com/script.js
PUBLIC_UMAMI_WEBSITE_ID=9eef8fba-c932-4488-ae23-6b84553e8c29
```
`Analytics.astro` silently no-ops if either is unset — safe to deploy without
them, but analytics won't record anything until both are present at build
time. `sws.toml`'s CSP already allows `analytics.andwati.com` and
`utteranc.es` (comments); if the Umami host ever changes, update both that
CSP and these two vars together, or the tracker will be silently blocked in
production instead of erroring visibly.
Generate each random secret independently; do not reuse the local development
values from `docker-compose.yml`.
## Persistent data
The production Compose file declares three named volumes:
- `cms_database` keeps Strapi's admin users, API tokens, and SQLite cache.
- `cms_uploads` keeps files uploaded through Strapi.
- `content_checkout` keeps the Git working tree used for publishing.
Back up `cms_database` and `cms_uploads`. The content checkout is recoverable
from Git, but retaining it protects an edit if the process stops between the
filesystem write and Git push.
On startup, the CMS fast-forwards a clean checkout to the configured branch.
If it finds uncommitted files, it preserves them and starts without pulling so
an interrupted edit is not overwritten. Resolve and push those files from the
volume before forcing a reset.
## Local validation
Provide temporary values for required interpolation variables, then validate
the production manifest:
```sh
docker compose --env-file .env.production \
-f docker-compose.prod.yml config
docker compose --env-file .env.production \
-f docker-compose.prod.yml build
```
The existing `docker-compose.yml` remains the local Strapi development setup.
+20
View File
@@ -0,0 +1,20 @@
# Production image for the Astro site. Build from the workspace root:
# docker build -t andwati-site .
FROM node:24-bookworm-slim AS build
RUN corepack enable
WORKDIR /app
COPY pnpm-workspace.yaml pnpm-lock.yaml package.json ./
COPY apps/site/package.json apps/site/package.json
COPY apps/cms/package.json apps/cms/package.json
COPY apps/site apps/site
COPY content content
COPY scripts scripts
RUN pnpm install --frozen-lockfile --filter andwati-com --filter site
RUN pnpm --filter site build
FROM ghcr.io/static-web-server/static-web-server:2
COPY --from=build /app/apps/site/dist /public
COPY sws.toml /sws.toml
EXPOSE 80
-19
View File
@@ -1,19 +0,0 @@
#!/usr/bin/make -f
.PHONY: all build
BUILD_DIR := public
all: clean build
clean:
rm -rfd ./$(BUILD_DIR)
build:
zola build
serve:
zola serve
update-zola:
@./bin/update-zola
+1 -8
View File
@@ -1,8 +1 @@
# TODO
- [ ] create new post script
- [ ] add google analytics
- [ ] move goatcounter config to config.toml
- [ ] modularize open graph(og) tags
- [ ] add favicon to config
- [ ] add latex support
# andwati.com
+210
View File
@@ -0,0 +1,210 @@
# Astro + Strapi Rebuild — TODO
Tracking doc for the `astro-migration` branch. See the locked spec in the
approved plan for full rationale on each decision referenced below.
## Done
- [x] Scaffold pnpm workspace (`apps/site` Astro, `apps/cms` Strapi + SQLite)
- [x] Switch tooling to pnpm-only, add Biome for lint/format
- [x] Define shared `content/` schema (writings, portfolio, bookshelf, blogs)
with TOML frontmatter matching the legacy Zola format
- [x] Bookshelf schema covers both books (ISBN) and papers (DOI/arXiv id)
- [x] Custom Astro content loader parsing `+++` TOML frontmatter directly
(no YAML conversion step)
- [x] Basic list/detail pages for all four content types, verified running
end-to-end in-browser (`pnpm --filter site dev`)
- [x] CLAUDE.md updated: no agent self-attribution in commits/PRs, commit
regularly after each working step
- [x] Strapi content-type definitions matching the `content/` schema exactly
(writings, portfolio, bookshelf, blogs) — verified boots and registers
all four REST routes
- [x] `apps/cms/Dockerfile.dev` + root `docker-compose.yml` for running
Strapi locally in a container (node:24-bookworm-slim, matches local
Node version); `apps/cms/Dockerfile` production multi-stage build for
later Dokploy deployment. Verified: builds, boots, admin panel and API
reachable, shared `content/` volume mounted at the right relative path
## Content pipeline
- [x] Strapi custom provider/lifecycle hooks that read + write the same
Markdown files in `content/` (Strapi's DB stays a disposable cache) —
`apps/cms/src/utils/content-{file,sync}.ts`, wired in `src/index.ts`
- [x] Verify round-trip: edit in Strapi admin → file on disk updates, and
vice versa, without drift — verified create/update/delete via the
content-manager API, plus idempotent re-import across a restart
- [x] Bookshelf ISBN lookup hook with local cover caching —
`apps/cms/src/utils/bookshelf-covers.ts` fetches from Open Library by
ISBN and caches into `apps/site/public/covers/`; verified end-to-end
(real cover downloaded, `cover_image` synced to file, cleaned up on
delete)
- [x] Bookshelf paper lookup hook — Semantic Scholar backfills title/authors
by DOI/arXiv id when missing. No cover/thumbnail: neither Semantic
Scholar nor arXiv offers a reliable image source for papers, so
`cover_image` stays manually-set for papers (or gets one later from
the OG-image pipeline below)
- [x] OG image auto-generation extended to all three content types
(writings, portfolio, bookshelf) using the new design system —
`scripts/generate-og-images.astro-site.mjs`, wired into `apps/site`'s
build script; `Base.astro` renders `og:image`/`twitter:image` from a
per-page `ogImage` prop (writings/bookshelf detail pages wire it in;
portfolio has no detail page yet to wire it into). Uses static-weight
Fraunces/Newsreader font packages, not the variable fonts the site
ships — satori's opentype.js parser can't read the variable fvar table
- [x] `llms.txt` generation extended to cover all content types — unblocked
once `site.config.ts` existed (built above for feeds/meta anyway):
`scripts/generate-llms.astro-site.mjs` reads all four content
directories directly, wired into `apps/site`'s build script
## Design system
- [x] New typography scale + color system — dark-first (warm near-black,
cream text, coral accent) with a warm-paper light mode;
Fraunces (display/italic) + Newsreader (body) + JetBrains Mono
(nav/meta/code), fluid clamp() type scale. `src/styles/tokens.css`.
Referenced pixperk.tech and mcyoung.xyz — see the commit for specifics
- [x] Motion primitives: CSS + native Web Animations API spring utility —
`apps/site/src/lib/spring.ts` (damped-oscillator keyframes,
`prefers-reduced-motion` aware). Not wired into any component yet —
the Three.js centerpiece below is the natural first user
- [x] Base layout/components replacing the placeholder `Base.astro` — real
header/nav with active-link state, theme toggle, footer with social
links. Verified light + dark in-browser across home, a writing
detail page (TOC/headings), bookshelf, and 404
- [x] Homepage redesign around the Three.js centerpiece as hero — the
constellation sits above a 3-column dashboard (latest writings,
portfolio, bookshelf), verified rendering and hover/click working
in-browser
- [x] New 404 page concept (terminal easter egg retired) — "Page Fault",
now fully styled with the rest of the design system
## Three.js centerpiece
- [x] Constellation data model: nodes are real content entries (writings,
portfolio, bookshelf), edges are shared-tag connections — the same
relationship "related posts" already uses, drawn instead of listed.
No decorative/fake data. `src/lib/constellation-data.ts`
- [x] Built as an isolated component (`Constellation.astro` + a plain
client `<script>` module, no framework), fibonacci-sphere layout,
hover raycasting with a title tooltip, click-through to the entry
- [x] Fallback for `prefers-reduced-motion` (skips rotation/entrance
animation) and no-WebGL (`supportsWebGL()` check hides the canvas
entirely, falls back to a `<noscript>`-style plain count)
- [x] Perf budget check — scene is trivially light (24 nodes, 12x12-segment
spheres, a handful of line-segment edges: well under 10k triangles),
renders at 100+fps uncapped with no dropped frames. The real cost is
the JS payload: three.js core pulls in ~130KB gzip / ~106KB brotli
regardless of `import *` vs named imports (`sideEffects: false`
already lets Rollup tree-shake fully; tried named imports, no size
change). That script is a deferred module (doesn't block first
paint/DCL) and the page was interactive in ~270ms in testing. No
code changes made — budget is fine as shipped
## Content features carried over from the Zola site
- [x] Series-nav (multi-part post series) — `writings/[...slug].astro`,
uses the existing `extra.series`/`extra.series_index` fields
- [x] Table of contents — sticky sidebar on desktop (>=74rem), falls back to
the original inline list below the tags on narrower viewports; same
heading data rendered via a shared `TocList.astro` so the two aren't
duplicated markup by hand. `.container--wide` bumped 64rem → 76rem so
big monitors use more of the screen (prose column itself stays capped
at 42rem for readability — the extra width is the TOC gutter);
verified at 390/900/1180/1920px with no distortion at any width
- [x] Prev/next post navigation
- [x] Related posts (tag-based, tag-overlap ranked, limit 3)
- [x] Per-tag descriptions on tag archive pages — `/tags/` + `/tags/[tag]/`,
descriptions ported from `zola.toml`'s `[extra.tag_descriptions]`
- [x] `llms_description` meta (site-wide default in `site.config.ts` +
per-post override, rendered as `<meta name="description">` in
`Base.astro`)
- [x] RSS/JSON feeds — `/rss.xml`, `/feed.json`
- [x] Sitemap + robots.txt — `@astrojs/sitemap`, static `public/robots.txt`
- [x] Code block syntax highlighting — `toml-content-loader.ts` renders
fenced code blocks through `highlight.js`'s core build with only the
11 languages content actually uses registered (no bundled-theme/WASM
grammar weight like shiki, which was tried first and swapped out for
this lighter option); `.hljs-*` token classes in `global.css` are
colored from the existing design tokens (`--accent`, `--text-muted`,
...), so they already switch with the site's theme with no extra
`[data-theme]` rules needed
## Search & comments
- [x] Pagefind integration — indexes the build output (`pnpm build` runs
`astro build && pagefind --site dist`), `/search/` page using
Pagefind's default UI; verified with a real query in a browser
- [x] Comments: kept Utterances (not Webmentions) — `Comments.astro`, wired
to `andwati/andwati.com`, with the same dark/light theme-sync-via-
postMessage behavior the legacy site had, adapted to this site's
`data-theme` attribute. The `rel="webmention"` link was removed since
it's unused now. `sws.toml`'s CSP updated to allow `utteranc.es`
(script-src, frame-src) — without that the widget is silently blocked
in production
## Analytics
- [x] Umami — self-hosted at `analytics.andwati.com`. `Analytics.astro`
renders the tracker script from `PUBLIC_UMAMI_SCRIPT_URL` +
`PUBLIC_UMAMI_WEBSITE_ID` (set in `apps/site/.env`, gitignored — copy
into the production environment's env vars too); `sws.toml`'s CSP
updated to allow that host in `script-src`/`connect-src`
## Migration from the legacy Zola site
- [x] Script/process to convert `content/posts/*.md` into the new
`content/writings/` schema — `scripts/migrate-posts-to-writings.mjs`,
additive only (`content/posts/` untouched), re-runnable/idempotent.
2 of 20 posts (`from-c-to-machine-code`,
`self-hosting-gitea-and-mirroring-github`) use note/tip/warning/danger
callout shortcodes — flagged by the script, still left as-is in the
body text
- [x] note/tip/warning/danger callout shortcode rendering — the legacy
`{% <note> %} ... {% </note> %}` blocks are converted to styled
`.callout` markup by `toml-content-loader.ts`'s `renderCallouts()`
(runs before the body's markdown parse), styled in `global.css` to
match the new design system. Verified in-browser on
`from-c-to-machine-code`
- [x] Preserve slugs/URLs via redirects — the script generates 301s from
`/posts/<slug>/` to `/writings/<slug>/` into `sws.toml`, idempotently
- [x] Migrate `content/archive/`, `content/about.md` equivalents —
`/archive/` groups every published writing by year; `/about/` reframes
the legacy copy around the site's "digital legacy" identity while
preserving its PGP and security contact details. Both are in the main
navigation, and the linked `.well-known` files are copied into Astro's
public output
- [ ] Verify RSS subscribers and inbound links survive the cutover — can
only really be checked once this is deployed live (**needs your
input**: this is a production-cutover verification, not a build-time
one)
## Infra / deployment
- [x] Wire Strapi into the Dokploy deployment alongside the Astro build —
`docker-compose.prod.yml` defines both production services, persistent
CMS/Git volumes, reverse-proxy settings, and secret-only configuration
- [x] Build trigger decided and implemented: Strapi commits Markdown and
generated covers to Git, pushes the production branch, then calls the
Dokploy Compose deploy webhook so Astro rebuilds from the durable commit
- [x] Update `Dockerfile`/`sws.toml` for Astro's `apps/site/dist` output,
current security headers, legacy redirects, and the custom 404 page
- [ ] Launch the production Compose application and configure its domains,
secrets, GitHub token, and deploy webhook in Dokploy — repository-side
setup is complete in `DEPLOYMENT.md`; host access is still required
## Cleanup
- [ ] Remove Zola-specific files (`zola.toml`, `templates/`, `sass/`,
`themes/`, `static/`, `Makefile`, `bin/update-zola`, `content/posts/`,
`content/archive/_index.md`, `content/about.md`, `content/_index.md`,
legacy OG/llms scripts) — verified safe: root `Dockerfile` already
builds `apps/site` (not `zola build`), nothing in `apps/site` reads
those content files, and `content/writings/` has all 20 posts from
`content/posts/`. Root `package.json`'s `legacy:*` scripts already
removed. **Blocked**: the actual `git rm` was refused by the
permission system as irreversible destruction — run it yourself (fully
reversible via git history/revert since these are tracked files):
`git rm -r templates/ sass/ themes/ static/ zola.toml Makefile bin/
content/posts/ content/archive/_index.md content/about.md
content/_index.md scripts/generate-llms.mjs
scripts/generate-og-images.mjs`
+21
View File
@@ -0,0 +1,21 @@
HOST=0.0.0.0
PORT=1337
APP_KEYS="toBeModified1,toBeModified2"
API_TOKEN_SALT=tobemodified
ADMIN_JWT_SECRET=tobemodified
TRANSFER_TOKEN_SALT=tobemodified
JWT_SECRET=tobemodified
ENCRYPTION_KEY=tobemodified
# Production reverse-proxy and Git publishing settings. Git publishing stays
# disabled during local development unless explicitly enabled.
PUBLIC_URL=http://localhost:1337
IS_PROXIED=false
GIT_PUBLISH_ENABLED=false
CONTENT_REPOSITORY_ROOT=
CONTENT_GIT_REPOSITORY=andwati/andwati.com
CONTENT_GIT_BRANCH=main
CONTENT_GIT_COMMIT_NAME="andwati.com CMS"
CONTENT_GIT_COMMIT_EMAIL=[email protected]
GITHUB_TOKEN=
DOKPLOY_DEPLOY_WEBHOOK_URL=
+131
View File
@@ -0,0 +1,131 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
.tmp
*.log
*.sql
*.sqlite
*.sqlite3
############################
# Misc.
############################
*#
ssl
.idea
nbproject
public/uploads/*
!public/uploads/.gitkeep
.tsbuildinfo
.eslintcache
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
node_modules
.node_history
############################
# Package managers
############################
.yarn/*
!.yarn/cache
!.yarn/unplugged
!.yarn/patches
!.yarn/releases
!.yarn/sdks
!.yarn/versions
.pnp.*
yarn-error.log
############################
# Tests
############################
coverage
############################
# Strapi
############################
.env
license.txt
exports
.strapi
dist
build
.strapi-updater.json
.strapi-cloud.json
+37
View File
@@ -0,0 +1,37 @@
# Production image for the Strapi CMS. Multi-stage: install deps, build the
# admin panel, then copy only the built output + prod node_modules into the
# runtime layer.
#
# Build context must be the repo root (pnpm workspace root), e.g.:
# docker build -f apps/cms/Dockerfile -t andwati-cms .
FROM node:24-bookworm-slim AS base
RUN corepack enable
WORKDIR /app
FROM base AS deps
# better-sqlite3 needs to compile if no prebuilt binary matches the platform.
RUN apt-get update && apt-get install -y --no-install-recommends \
python3 make g++ \
&& rm -rf /var/lib/apt/lists/*
COPY pnpm-workspace.yaml pnpm-lock.yaml package.json ./
COPY apps/site/package.json apps/site/package.json
COPY apps/cms/package.json apps/cms/package.json
RUN pnpm install --frozen-lockfile --filter cms
FROM deps AS build
ENV NODE_ENV=production
COPY apps/cms apps/cms
RUN pnpm --filter cms build
FROM base AS runtime
ENV NODE_ENV=production
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates git \
&& rm -rf /var/lib/apt/lists/*
COPY --from=build /app/node_modules /app/node_modules
COPY --from=build /app/apps/cms /app/apps/cms
COPY --chmod=755 apps/cms/docker-entrypoint.sh /usr/local/bin/andwati-cms-entrypoint
WORKDIR /app/apps/cms
EXPOSE 1337
ENTRYPOINT ["andwati-cms-entrypoint"]
+30
View File
@@ -0,0 +1,30 @@
# Local testing image for the Strapi CMS — runs `strapi develop` with the
# workspace's own lockfile, so it matches what `pnpm --filter cms develop`
# does on the host. Not for production (see Dockerfile for that).
#
# Build context must be the repo root (pnpm workspace root), e.g.:
# docker build -f apps/cms/Dockerfile.dev -t andwati-cms-dev .
# or simply: docker compose up cms
FROM node:24-bookworm-slim
# better-sqlite3 needs to compile if no prebuilt binary matches the platform.
RUN apt-get update && apt-get install -y --no-install-recommends \
python3 make g++ \
&& rm -rf /var/lib/apt/lists/*
RUN corepack enable
WORKDIR /app
# Copy just the manifests first so `pnpm install` is cached across rebuilds
# unless a package.json actually changes.
COPY pnpm-workspace.yaml pnpm-lock.yaml package.json ./
COPY apps/site/package.json apps/site/package.json
COPY apps/cms/package.json apps/cms/package.json
RUN pnpm install --frozen-lockfile --filter cms
COPY apps/cms apps/cms
WORKDIR /app/apps/cms
EXPOSE 1337
CMD ["pnpm", "develop"]
+61
View File
@@ -0,0 +1,61 @@
# 🚀 Getting started with Strapi
Strapi comes with a full featured [Command Line Interface](https://docs.strapi.io/dev-docs/cli) (CLI) which lets you scaffold and manage your project in seconds.
### `develop`
Start your Strapi application with autoReload enabled. [Learn more](https://docs.strapi.io/dev-docs/cli#strapi-develop)
```
npm run develop
# or
yarn develop
```
### `start`
Start your Strapi application with autoReload disabled. [Learn more](https://docs.strapi.io/dev-docs/cli#strapi-start)
```
npm run start
# or
yarn start
```
### `build`
Build your admin panel. [Learn more](https://docs.strapi.io/dev-docs/cli#strapi-build)
```
npm run build
# or
yarn build
```
## ⚙️ Deployment
Strapi gives you many possible deployment options for your project including [Strapi Cloud](https://cloud.strapi.io). Browse the [deployment section of the documentation](https://docs.strapi.io/dev-docs/deployment) to find the best solution for your use case.
```
yarn strapi deploy
```
## 📚 Learn more
- [Resource center](https://strapi.io/resource-center) - Strapi resource center.
- [Strapi documentation](https://docs.strapi.io) - Official Strapi documentation.
- [Strapi tutorials](https://strapi.io/tutorials) - List of tutorials made by the core team and the community.
- [Strapi blog](https://strapi.io/blog) - Official Strapi blog containing articles made by the Strapi team and the community.
- [Changelog](https://strapi.io/changelog) - Find out about the Strapi product updates, new features and general improvements.
Feel free to check out the [Strapi GitHub repository](https://github.com/strapi/strapi). Your feedback and contributions are welcome!
## ✨ Community
- [Discord](https://discord.strapi.io) - Come chat with the Strapi community including the core team.
- [Forum](https://forum.strapi.io/) - Place to discuss, ask questions and find answers, show your Strapi project and get feedback or just talk with other Community members.
- [Awesome Strapi](https://github.com/strapi/awesome-strapi) - A curated list of awesome things related to Strapi.
---
<sub>🤫 Psst! [Strapi is hiring](https://strapi.io/careers).</sub>
+27
View File
@@ -0,0 +1,27 @@
import type { Core } from "@strapi/strapi";
const config = ({
env,
}: Core.Config.Shared.ConfigParams): Core.Config.Admin => ({
auth: {
secret: env("ADMIN_JWT_SECRET")!,
},
apiToken: {
salt: env("API_TOKEN_SALT")!,
},
transfer: {
token: {
salt: env("TRANSFER_TOKEN_SALT")!,
},
},
secrets: {
encryptionKey: env("ENCRYPTION_KEY")!,
},
flags: {
nps: env.bool("FLAG_NPS", true),
promoteEE: env.bool("FLAG_PROMOTE_EE", true),
docLinks: env.bool("FLAG_DOC_LINKS", true),
},
});
export default config;
+16
View File
@@ -0,0 +1,16 @@
import type { Core } from "@strapi/strapi";
const config: Core.Config.Api = {
rest: {
defaultLimit: 25,
maxLimit: 100,
withCount: true,
strictParams: true,
},
documents: {
strictParams: true,
strictRelations: true,
},
};
export default config;
+94
View File
@@ -0,0 +1,94 @@
import { isDatabaseClientKind } from "@strapi/database";
import type { Core } from "@strapi/strapi";
import path from "path";
const config = ({
env,
}: Core.Config.Shared.ConfigParams): Core.Config.Database => {
const client = env("DATABASE_CLIENT", "sqlite");
if (!isDatabaseClientKind(client)) {
throw new Error(
`Unsupported DATABASE_CLIENT: ${client}. Use "postgres", "mysql", or "sqlite".`,
);
}
const connections: Record<
Core.Config.Database.ClientKind,
Core.Config.Database["connection"]
> = {
mysql: {
client: "mysql",
connection: {
host: env("DATABASE_HOST", "localhost"),
port: env.int("DATABASE_PORT", 3306),
database: env("DATABASE_NAME", "strapi"),
user: env("DATABASE_USERNAME", "strapi"),
password: env("DATABASE_PASSWORD", "strapi"),
ssl: env.bool("DATABASE_SSL", false) && {
key: env("DATABASE_SSL_KEY", undefined),
cert: env("DATABASE_SSL_CERT", undefined),
ca: env("DATABASE_SSL_CA", undefined),
capath: env("DATABASE_SSL_CAPATH", undefined),
cipher: env("DATABASE_SSL_CIPHER", undefined),
rejectUnauthorized: env.bool(
"DATABASE_SSL_REJECT_UNAUTHORIZED",
true,
),
},
},
pool: {
min: env.int("DATABASE_POOL_MIN", 2),
max: env.int("DATABASE_POOL_MAX", 10),
},
},
postgres: {
client: "postgres",
connection: {
connectionString: env("DATABASE_URL"),
host: env("DATABASE_HOST", "localhost"),
port: env.int("DATABASE_PORT", 5432),
database: env("DATABASE_NAME", "strapi"),
user: env("DATABASE_USERNAME", "strapi"),
password: env("DATABASE_PASSWORD", "strapi"),
ssl: env.bool("DATABASE_SSL", false) && {
key: env("DATABASE_SSL_KEY", undefined),
cert: env("DATABASE_SSL_CERT", undefined),
ca: env("DATABASE_SSL_CA", undefined),
capath: env("DATABASE_SSL_CAPATH", undefined),
cipher: env("DATABASE_SSL_CIPHER", undefined),
rejectUnauthorized: env.bool(
"DATABASE_SSL_REJECT_UNAUTHORIZED",
true,
),
},
schema: env("DATABASE_SCHEMA", "public"),
},
pool: {
min: env.int("DATABASE_POOL_MIN", 2),
max: env.int("DATABASE_POOL_MAX", 10),
},
},
sqlite: {
client: "sqlite",
connection: {
filename: path.join(
__dirname,
"..",
"..",
env("DATABASE_FILENAME", ".tmp/data.db"),
),
},
useNullAsDefault: true,
},
};
return {
connection: {
...connections[client],
acquireConnectionTimeout: env.int("DATABASE_CONNECTION_TIMEOUT", 60000),
},
};
};
export default config;
+16
View File
@@ -0,0 +1,16 @@
import type { Core } from "@strapi/strapi";
const config: Core.Config.Middlewares = [
"strapi::logger",
"strapi::errors",
"strapi::security",
"strapi::cors",
"strapi::poweredBy",
"strapi::query",
"strapi::body",
"strapi::session",
"strapi::favicon",
"strapi::public",
];
export default config;
+47
View File
@@ -0,0 +1,47 @@
import type { Core } from "@strapi/strapi";
const allowedMediaTypes = [
"image/*",
"video/*",
"audio/*",
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.*",
"text/plain",
"text/csv",
];
const deniedTypes = [
"image/svg+xml",
"application/vnd.microsoft.portable-executable",
"application/x-msdownload",
"application/x-msdos-program",
"application/x-executable",
"application/x-dosexec",
"application/x-sh",
"text/x-shellscript",
"application/x-mach-binary",
];
const config = ({
env,
}: Core.Config.Shared.ConfigParams): Core.Config.Plugin => ({
"users-permissions": {
config: {
jwtManagement: "refresh",
sessions: {
httpOnly: true,
},
},
},
upload: {
config: {
security: {
allowedTypes: allowedMediaTypes,
deniedTypes,
},
},
},
});
export default config;
+18
View File
@@ -0,0 +1,18 @@
import type { Core } from "@strapi/strapi";
const config = ({
env,
}: Core.Config.Shared.ConfigParams): Core.Config.Server => ({
host: env("HOST", "0.0.0.0"),
port: env.int("PORT", 1337),
url: env("PUBLIC_URL", "http://localhost:1337"),
proxy: env.bool("IS_PROXIED", false),
app: {
keys: env.array("APP_KEYS")!,
},
webhooks: {
populateRelations: env.bool("WEBHOOKS_POPULATE_RELATIONS", false),
},
});
export default config;
+40
View File
@@ -0,0 +1,40 @@
#!/bin/sh
set -eu
repository_root="${CONTENT_REPOSITORY_ROOT:-/content-repository}"
repository="${CONTENT_GIT_REPOSITORY:-andwati/andwati.com}"
branch="${CONTENT_GIT_BRANCH:-main}"
case "$repository" in
*[!A-Za-z0-9._/-]* | /* | */ | *..*)
echo "Invalid CONTENT_GIT_REPOSITORY: $repository" >&2
exit 1
;;
esac
mkdir -p "$repository_root"
if [ ! -d "$repository_root/.git" ]; then
if [ -n "$(find "$repository_root" -mindepth 1 -maxdepth 1 -print -quit)" ]; then
echo "$repository_root is not empty and is not a Git checkout" >&2
exit 1
fi
git clone \
--branch "$branch" \
--single-branch \
"https://github.com/$repository.git" \
"$repository_root"
else
git -C "$repository_root" fetch origin "$branch"
git -C "$repository_root" checkout "$branch"
if [ -z "$(git -C "$repository_root" status --porcelain)" ]; then
git -C "$repository_root" merge --ff-only "origin/$branch"
else
echo "Content checkout has unpublished changes; preserving them without pulling." >&2
fi
fi
export CONTENT_REPOSITORY_ROOT="$repository_root"
exec node node_modules/@strapi/strapi/bin/strapi.js start
Binary file not shown.

After

Width:  |  Height:  |  Size: 497 B

+47
View File
@@ -0,0 +1,47 @@
{
"name": "cms",
"version": "0.1.0",
"private": true,
"description": "A Strapi application",
"scripts": {
"predev": "test -f .env || cp .env.example .env",
"predevelop": "test -f .env || cp .env.example .env",
"build": "strapi build",
"console": "strapi console",
"deploy": "strapi deploy",
"dev": "strapi develop",
"develop": "strapi develop",
"start": "strapi start",
"strapi": "strapi",
"test:publisher": "tsx --test tests/git-publisher.test.ts",
"upgrade": "npx @strapi/upgrade latest",
"upgrade:dry": "npx @strapi/upgrade latest --dry"
},
"dependencies": {
"@strapi/database": "5.52.2",
"@strapi/plugin-cloud": "5.52.2",
"@strapi/plugin-users-permissions": "5.52.2",
"@strapi/strapi": "5.52.2",
"better-sqlite3": "12.8.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-router-dom": "^6.30.3",
"smol-toml": "^1.8.0",
"styled-components": "^6.0.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"tsx": "^4.23.13",
"typescript": "^5"
},
"engines": {
"node": ">=20.0.0 <=26.x.x",
"npm": ">=6.0.0"
},
"strapi": {
"uuid": "53c467c6-a64c-4883-b4df-0d96747d2cf3",
"installId": "dcf09d0c097e16db63c329dd9602949f9c4ae64f4e69a04dc6e105313d30b369"
}
}
+3
View File
@@ -0,0 +1,3 @@
# To prevent search engines from seeing the site altogether, uncomment the next two lines:
# User-Agent: *
# Disallow: /
View File
+37
View File
@@ -0,0 +1,37 @@
import type { StrapiApp } from "@strapi/strapi/admin";
export default {
config: {
locales: [
// 'ar',
// 'fr',
// 'cs',
// 'de',
// 'da',
// 'es',
// 'he',
// 'id',
// 'it',
// 'ja',
// 'ko',
// 'ms',
// 'nl',
// 'no',
// 'pl',
// 'pt-BR',
// 'pt',
// 'ru',
// 'sk',
// 'sv',
// 'th',
// 'tr',
// 'uk',
// 'vi',
// 'zh-Hans',
// 'zh',
],
},
bootstrap(app: StrapiApp) {
console.log(app);
},
};
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["../plugins/**/admin/src/**/*", "./"],
"exclude": ["node_modules/", "build/", "dist/", "**/*.test.ts"]
}
+12
View File
@@ -0,0 +1,12 @@
import { mergeConfig, type UserConfig } from "vite";
export default (config: UserConfig) => {
// Important: always return the modified config
return mergeConfig(config, {
resolve: {
alias: {
"@": "/src",
},
},
});
};
@@ -0,0 +1,77 @@
{
"kind": "collectionType",
"collectionName": "bookshelf_entries",
"info": {
"singularName": "bookshelf-entry",
"pluralName": "bookshelf-entries",
"displayName": "Bookshelf Entry",
"description": "Books and papers, synced to content/bookshelf/. `kind` selects which identifier fields apply."
},
"options": {
"draftAndPublish": false
},
"attributes": {
"title": {
"type": "string",
"required": true
},
"slug": {
"type": "uid",
"targetField": "title",
"required": true,
"description": "Matches the file name under content/bookshelf/"
},
"kind": {
"type": "enumeration",
"enum": ["book", "paper"],
"required": true
},
"authors": {
"type": "json",
"description": "Array of author name strings"
},
"isbn": {
"type": "string",
"description": "Books only"
},
"doi": {
"type": "string",
"description": "Papers only"
},
"arxiv_id": {
"type": "string",
"description": "Papers only, optional"
},
"url": {
"type": "string",
"description": "Papers only: landing page / source link"
},
"cover_image": {
"type": "string",
"description": "Path to the locally cached cover, e.g. /covers/slug.jpg"
},
"rating": {
"type": "integer",
"min": 1,
"max": 5
},
"read_status": {
"type": "enumeration",
"enum": ["reading", "read", "abandoned"]
},
"date_started": {
"type": "date"
},
"date_finished": {
"type": "date"
},
"tags": {
"type": "json",
"description": "Array of tag strings, maps to [taxonomies].tags"
},
"body": {
"type": "richtext",
"description": "Personal review/notes below the frontmatter"
}
}
}
@@ -0,0 +1,5 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreController(
"api::bookshelf-entry.bookshelf-entry",
);
@@ -0,0 +1,5 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreRouter(
"api::bookshelf-entry.bookshelf-entry",
);
@@ -0,0 +1,5 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreService(
"api::bookshelf-entry.bookshelf-entry",
);
@@ -0,0 +1,36 @@
{
"kind": "collectionType",
"collectionName": "curated_blogs",
"info": {
"singularName": "curated-blog",
"pluralName": "curated-blogs",
"displayName": "Curated Blog",
"description": "Hand-picked external blogs, synced to content/blogs/. No live feed fetching."
},
"options": {
"draftAndPublish": false
},
"attributes": {
"title": {
"type": "string",
"required": true
},
"slug": {
"type": "uid",
"targetField": "title",
"required": true,
"description": "Matches the file name under content/blogs/"
},
"url": {
"type": "string",
"required": true
},
"feed_url": {
"type": "string"
},
"body": {
"type": "richtext",
"description": "One-to-two sentence blurb below the frontmatter"
}
}
}
@@ -0,0 +1,3 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreController("api::curated-blog.curated-blog");
@@ -0,0 +1,3 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreRouter("api::curated-blog.curated-blog");
@@ -0,0 +1,3 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreService("api::curated-blog.curated-blog");
@@ -0,0 +1,56 @@
{
"kind": "collectionType",
"collectionName": "portfolio_entries",
"info": {
"singularName": "portfolio-entry",
"pluralName": "portfolio-entries",
"displayName": "Portfolio Entry",
"description": "Projects and professional work, synced to content/portfolio/."
},
"options": {
"draftAndPublish": false
},
"attributes": {
"title": {
"type": "string",
"required": true
},
"slug": {
"type": "uid",
"targetField": "title",
"required": true,
"description": "Matches the file name under content/portfolio/"
},
"description": {
"type": "text"
},
"role": {
"type": "string"
},
"date_start": {
"type": "date"
},
"date_end": {
"type": "date"
},
"outcome": {
"type": "string"
},
"draft": {
"type": "boolean",
"default": false
},
"links": {
"type": "json",
"description": "Array of { label, url }, maps to [[links]]"
},
"tags": {
"type": "json",
"description": "Array of tag strings, maps to [taxonomies].tags"
},
"body": {
"type": "richtext",
"description": "Markdown case-study body below the frontmatter"
}
}
}
@@ -0,0 +1,5 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreController(
"api::portfolio-entry.portfolio-entry",
);
@@ -0,0 +1,5 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreRouter(
"api::portfolio-entry.portfolio-entry",
);
@@ -0,0 +1,5 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreService(
"api::portfolio-entry.portfolio-entry",
);
@@ -0,0 +1,65 @@
{
"kind": "collectionType",
"collectionName": "writings",
"info": {
"singularName": "writing",
"pluralName": "writings",
"displayName": "Writing",
"description": "Long-form essays and technical posts, synced to content/writings/."
},
"options": {
"draftAndPublish": false
},
"attributes": {
"title": {
"type": "string",
"required": true
},
"slug": {
"type": "uid",
"targetField": "title",
"required": true,
"description": "Matches the file/directory name under content/writings/"
},
"description": {
"type": "text"
},
"author": {
"type": "string"
},
"date": {
"type": "date",
"required": true
},
"updated": {
"type": "date"
},
"draft": {
"type": "boolean",
"default": false
},
"canonical_url": {
"type": "string"
},
"tags": {
"type": "json",
"description": "Array of tag strings, maps to [taxonomies].tags"
},
"series": {
"type": "string",
"description": "Maps to [extra].series"
},
"series_index": {
"type": "integer",
"description": "Maps to [extra].series_index"
},
"llms_description": {
"type": "text",
"description": "Maps to [extra].llms_description"
},
"body": {
"type": "richtext",
"description": "Markdown body below the frontmatter"
}
}
}
@@ -0,0 +1,3 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreController("api::writing.writing");
@@ -0,0 +1,3 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreRouter("api::writing.writing");
@@ -0,0 +1,3 @@
import { factories } from "@strapi/strapi";
export default factories.createCoreService("api::writing.writing");
View File
+20
View File
@@ -0,0 +1,20 @@
import type { Core } from "@strapi/strapi";
import {
importContentFromDisk,
registerContentSync,
} from "./utils/content-sync";
export default {
register() {},
/**
* content/ is the source of truth (see content/README.md). On boot we
* import every file into Strapi's DB (a disposable cache), then register
* a Document Service middleware that writes any create/update/delete made
* through Strapi straight back to the same files.
*/
async bootstrap({ strapi }: { strapi: Core.Strapi }) {
registerContentSync(strapi as never);
await importContentFromDisk(strapi as never);
},
};
+131
View File
@@ -0,0 +1,131 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { coversRoot } from "./content-paths";
/**
* Covers are cached into the Astro app's public/ dir directly, so the built
* site serves them from /covers/<slug>.jpg with no runtime dependency on the
* source (Open Library, Semantic Scholar, ...).
*/
const COVERS_DIR = coversRoot();
async function download(url: string): Promise<Buffer | undefined> {
const res = await fetch(url);
if (!res.ok) return undefined;
const buf = Buffer.from(await res.arrayBuffer());
// Open Library serves a tiny placeholder image for ISBNs it doesn't have a cover for.
if (buf.byteLength < 500) return undefined;
return buf;
}
/** Fetches a book cover by ISBN from Open Library and caches it locally. */
export async function fetchBookCover(
isbn: string,
slug: string,
): Promise<string | undefined> {
const buf = await download(
`https://covers.openlibrary.org/b/isbn/${encodeURIComponent(isbn)}-L.jpg?default=false`,
);
if (!buf) return undefined;
const file = join(COVERS_DIR, `${slug}.jpg`);
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, buf);
return `/covers/${slug}.jpg`;
}
/**
* Sniffs the actual file signature rather than trusting the Content-Type
* header — some CDNs (O'Reilly's included, observed while building this)
* mislabel WebP responses as image/jpeg, which would otherwise get a wrong
* extension and a mismatched Content-Type when we later serve it ourselves.
*/
function extensionFromBytes(buf: Buffer): string {
if (
buf.length >= 12 &&
buf.subarray(0, 4).toString("ascii") === "RIFF" &&
buf.subarray(8, 12).toString("ascii") === "WEBP"
) {
return "webp";
}
if (
buf.length >= 8 &&
buf
.subarray(0, 8)
.equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
) {
return "png";
}
if (
buf.length >= 3 &&
buf[0] === 0xff &&
buf[1] === 0xd8 &&
buf[2] === 0xff
) {
return "jpg";
}
if (
buf.length >= 6 &&
(buf.subarray(0, 6).toString("ascii") === "GIF87a" ||
buf.subarray(0, 6).toString("ascii") === "GIF89a")
) {
return "gif";
}
return "jpg";
}
/**
* Downloads whatever image URL is at `url` (e.g. a cover_image the user
* pasted in by hand) and caches it locally, so the site never depends on
* that URL staying up. Used for any http(s) cover_image, not just ISBN
* lookups.
*/
export async function cacheRemoteImage(
url: string,
slug: string,
): Promise<string | undefined> {
try {
const res = await fetch(url);
if (!res.ok) return undefined;
const buf = Buffer.from(await res.arrayBuffer());
if (buf.byteLength < 200) return undefined;
const ext = extensionFromBytes(buf);
const file = join(COVERS_DIR, `${slug}.${ext}`);
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, buf);
return `/covers/${slug}.${ext}`;
} catch {
return undefined;
}
}
interface PaperMetadata {
title?: string;
authors?: string[];
}
/**
* Fetches title/author metadata for a paper from Semantic Scholar by DOI or
* arXiv id, used to backfill fields left blank in Strapi. Semantic Scholar
* has no reliable thumbnail/cover source for papers, so unlike books this
* does not produce a cached image.
*/
export async function fetchPaperMetadata(identifier: {
doi?: string;
arxivId?: string;
}): Promise<PaperMetadata | undefined> {
const id = identifier.doi
? `DOI:${identifier.doi}`
: identifier.arxivId
? `ARXIV:${identifier.arxivId}`
: undefined;
if (!id) return undefined;
const res = await fetch(
`https://api.semanticscholar.org/graph/v1/paper/${encodeURIComponent(id)}?fields=title,authors`,
);
if (!res.ok) return undefined;
const data = (await res.json()) as {
title?: string;
authors?: { name: string }[];
};
return { title: data.title, authors: data.authors?.map((a) => a.name) };
}
+129
View File
@@ -0,0 +1,129 @@
import {
mkdirSync,
readdirSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { dirname, join, relative } from "node:path";
import {
parse as parseToml,
stringify as stringifyToml,
TomlDate,
} from "smol-toml";
const FRONTMATTER_RE = /^\+\+\+\r?\n([\s\S]*?)\r?\n\+\+\+\r?\n?([\s\S]*)$/;
export interface ParsedEntryFile {
slug: string;
frontmatter: Record<string, unknown>;
body: string;
}
/** Strips undefined/null/empty-string/empty-array values so smol-toml doesn't choke on them. */
export function compact<T extends Record<string, unknown>>(
obj: T,
): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
if (value === undefined || value === null || value === "") continue;
if (Array.isArray(value) && value.length === 0) continue;
if (
typeof value === "object" &&
!Array.isArray(value) &&
!(value instanceof Date)
) {
const nested = compact(value as Record<string, unknown>);
if (Object.keys(nested).length === 0) continue;
out[key] = nested;
continue;
}
out[key] = value;
}
return out;
}
/** Converts a Strapi "date" field (an ISO `YYYY-MM-DD` string) to a bare TOML local-date. */
export function toTomlDate(
value: string | null | undefined,
): TomlDate | undefined {
return value ? new TomlDate(value) : undefined;
}
function walk(dir: string): string[] {
const out: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) out.push(...walk(full));
else if (entry.isFile() && full.endsWith(".md")) out.push(full);
}
return out;
}
function slugFromPath(dir: string, file: string): string {
const rel = relative(dir, file).split("\\").join("/");
return rel.endsWith("/index.md")
? rel.slice(0, -"/index.md".length)
: rel.slice(0, -".md".length);
}
/** Reads every `+++`-frontmatter Markdown file under `dir` (flat or `<slug>/index.md`). */
export function readAllEntries(dir: string): ParsedEntryFile[] {
let files: string[];
try {
files = walk(dir);
} catch {
return [];
}
return files.flatMap((file) => {
const raw = readFileSync(file, "utf8");
const match = raw.match(FRONTMATTER_RE);
if (!match) return [];
const [, fm, body] = match;
return [
{
slug: slugFromPath(dir, file),
frontmatter: parseToml(fm),
body: body.trim(),
},
];
});
}
function entryPath(
dir: string,
slug: string,
layout: "nested" | "flat",
): string {
return layout === "nested"
? join(dir, slug, "index.md")
: join(dir, `${slug}.md`);
}
/** Writes (or overwrites) the frontmatter+body file for `slug` under `dir`. */
export function writeEntry(
dir: string,
slug: string,
layout: "nested" | "flat",
frontmatter: Record<string, unknown>,
body: string,
): string {
const file = entryPath(dir, slug, layout);
mkdirSync(dirname(file), { recursive: true });
const toml = stringifyToml(compact(frontmatter)).trimEnd();
writeFileSync(file, `+++\n${toml}\n+++\n\n${(body ?? "").trim()}\n`);
return file;
}
/** Deletes the file (and, for nested layout, its now-empty directory) for `slug`. */
export function deleteEntry(
dir: string,
slug: string,
layout: "nested" | "flat",
): string {
const file = entryPath(dir, slug, layout);
rmSync(file, { force: true });
if (layout === "nested")
rmSync(join(dir, slug), { recursive: true, force: true });
return file;
}
+22
View File
@@ -0,0 +1,22 @@
import { isAbsolute, join, resolve } from "node:path";
/**
* Root of the Git checkout that owns content/ and apps/site/public/covers/.
* Production points this at the persistent checkout prepared by the
* container entrypoint; local development falls back to the workspace root.
*/
export function repositoryRoot(): string {
const configured = process.env.CONTENT_REPOSITORY_ROOT;
if (!configured) return resolve(process.cwd(), "..", "..");
return isAbsolute(configured)
? configured
: resolve(process.cwd(), configured);
}
export function contentRoot(): string {
return join(repositoryRoot(), "content");
}
export function coversRoot(): string {
return join(repositoryRoot(), "apps", "site", "public", "covers");
}
+425
View File
@@ -0,0 +1,425 @@
import { rmSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import {
cacheRemoteImage,
fetchBookCover,
fetchPaperMetadata,
} from "./bookshelf-covers";
import {
deleteEntry,
readAllEntries,
toTomlDate,
writeEntry,
} from "./content-file";
import { contentRoot, coversRoot } from "./content-paths";
import { publishContentChanges } from "./git-publisher";
const BOOKSHELF_UID = "api::bookshelf-entry.bookshelf-entry";
type Layout = "nested" | "flat";
interface SyncConfig {
uid: string;
dir: string;
layout: Layout;
/** Strapi entry -> { frontmatter, body } written to disk. */
toFile: (entry: Record<string, unknown>) => {
frontmatter: Record<string, unknown>;
body: string;
};
/** Parsed file -> Strapi entry fields, for importing content/ into Strapi on boot. */
toEntry: (
slug: string,
frontmatter: Record<string, unknown>,
body: string,
) => Record<string, unknown>;
}
const isoDate = (value: unknown): string | undefined =>
value instanceof Date
? value.toISOString().slice(0, 10)
: typeof value === "string"
? value
: undefined;
function buildConfigs(): Record<string, SyncConfig> {
const root = contentRoot();
const writing: SyncConfig = {
uid: "api::writing.writing",
dir: join(root, "writings"),
layout: "nested",
toFile: (e) => ({
frontmatter: {
title: e.title,
description: e.description,
author: e.author,
date: toTomlDate(e.date as string),
updated: toTomlDate(e.updated as string),
draft: e.draft ?? false,
canonical_url: e.canonical_url,
taxonomies: { tags: e.tags ?? [] },
extra: {
series: e.series,
series_index: e.series_index,
llms_description: e.llms_description,
},
},
body: (e.body as string) ?? "",
}),
toEntry: (slug, fm, body) => {
const taxonomies = fm.taxonomies as { tags?: string[] } | undefined;
const extra = fm.extra as
| { series?: string; series_index?: number; llms_description?: string }
| undefined;
return {
slug,
title: fm.title,
description: fm.description,
author: fm.author,
date: isoDate(fm.date),
updated: isoDate(fm.updated),
draft: fm.draft ?? false,
canonical_url: fm.canonical_url,
tags: taxonomies?.tags ?? [],
series: extra?.series,
series_index: extra?.series_index,
llms_description: extra?.llms_description,
body,
};
},
};
const portfolioEntry: SyncConfig = {
uid: "api::portfolio-entry.portfolio-entry",
dir: join(root, "portfolio"),
layout: "flat",
toFile: (e) => ({
frontmatter: {
title: e.title,
description: e.description,
role: e.role,
date_start: toTomlDate(e.date_start as string),
date_end: toTomlDate(e.date_end as string),
outcome: e.outcome,
draft: e.draft ?? false,
links: e.links ?? [],
taxonomies: { tags: e.tags ?? [] },
},
body: (e.body as string) ?? "",
}),
toEntry: (slug, fm, body) => {
const taxonomies = fm.taxonomies as { tags?: string[] } | undefined;
return {
slug,
title: fm.title,
description: fm.description,
role: fm.role,
date_start: isoDate(fm.date_start),
date_end: isoDate(fm.date_end),
outcome: fm.outcome,
draft: fm.draft ?? false,
links: fm.links ?? [],
tags: taxonomies?.tags ?? [],
body,
};
},
};
const bookshelfEntry: SyncConfig = {
uid: "api::bookshelf-entry.bookshelf-entry",
dir: join(root, "bookshelf"),
layout: "flat",
toFile: (e) => ({
frontmatter: {
title: e.title,
kind: e.kind,
authors: e.authors ?? [],
isbn: e.isbn,
doi: e.doi,
arxiv_id: e.arxiv_id,
url: e.url,
cover_image: e.cover_image,
rating: e.rating,
read_status: e.read_status,
date_started: toTomlDate(e.date_started as string),
date_finished: toTomlDate(e.date_finished as string),
taxonomies: { tags: e.tags ?? [] },
},
body: (e.body as string) ?? "",
}),
toEntry: (slug, fm, body) => {
const taxonomies = fm.taxonomies as { tags?: string[] } | undefined;
return {
slug,
title: fm.title,
kind: fm.kind,
authors: fm.authors ?? [],
isbn: fm.isbn,
doi: fm.doi,
arxiv_id: fm.arxiv_id,
url: fm.url,
cover_image: fm.cover_image,
rating: fm.rating,
read_status: fm.read_status,
date_started: isoDate(fm.date_started),
date_finished: isoDate(fm.date_finished),
tags: taxonomies?.tags ?? [],
body,
};
},
};
const curatedBlog: SyncConfig = {
uid: "api::curated-blog.curated-blog",
dir: join(root, "blogs"),
layout: "flat",
toFile: (e) => ({
frontmatter: {
title: e.title,
url: e.url,
feed_url: e.feed_url,
},
body: (e.body as string) ?? "",
}),
toEntry: (slug, fm, body) => ({
slug,
title: fm.title,
url: fm.url,
feed_url: fm.feed_url,
body,
}),
};
return {
[writing.uid]: writing,
[portfolioEntry.uid]: portfolioEntry,
[bookshelfEntry.uid]: bookshelfEntry,
[curatedBlog.uid]: curatedBlog,
};
}
export const SYNC_CONFIGS = buildConfigs();
/** Guards the outbound (DB -> file) middleware while the inbound (file -> DB) import runs. */
let importing = false;
function writeEntryForConfig(
config: SyncConfig,
entry: Record<string, unknown>,
): string | undefined {
const slug = entry.slug as string | undefined;
if (!slug) return undefined;
const { frontmatter, body } = config.toFile(entry);
return writeEntry(config.dir, slug, config.layout, frontmatter, body);
}
function coverFileForEntry(
entry: Record<string, unknown> | null,
): string | undefined {
const coverImage = entry?.cover_image;
if (typeof coverImage !== "string" || !coverImage.startsWith("/covers/")) {
return undefined;
}
const root = resolve(coversRoot());
const file = resolve(root, coverImage.slice("/covers/".length));
const fromRoot = relative(root, file);
if (fromRoot === ".." || fromRoot.startsWith("../")) {
throw new Error(`Refusing unsafe local cover path: ${coverImage}`);
}
return file;
}
/**
* On boot, upserts every file under content/<type>/ into Strapi so the admin
* UI reflects on-disk edits made outside Strapi. Strapi's DB stays a
* disposable cache: this can always rebuild it from content/ alone.
*/
export async function importContentFromDisk(strapi: {
documents: (uid: string) => {
findFirst: (params: {
filters: Record<string, unknown>;
}) => Promise<Record<string, unknown> | null>;
create: (params: { data: Record<string, unknown> }) => Promise<unknown>;
update: (params: {
documentId: string;
data: Record<string, unknown>;
}) => Promise<unknown>;
};
log: { info: (msg: string) => void; error: (msg: string) => void };
}): Promise<void> {
importing = true;
try {
for (const config of Object.values(SYNC_CONFIGS)) {
const files = readAllEntries(config.dir);
let created = 0;
let updated = 0;
for (const { slug, frontmatter, body } of files) {
const data = config.toEntry(slug, frontmatter, body);
try {
const existing = await strapi
.documents(config.uid)
.findFirst({ filters: { slug } });
if (existing) {
await strapi
.documents(config.uid)
.update({ documentId: existing.documentId as string, data });
updated += 1;
} else {
await strapi.documents(config.uid).create({ data });
created += 1;
}
} catch (err) {
strapi.log.error(
`content-sync: failed to import ${config.dir}/${slug}: ${(err as Error).message}`,
);
}
}
strapi.log.info(
`content-sync: imported ${config.uid} (${created} created, ${updated} updated, ${files.length} total)`,
);
}
} finally {
importing = false;
}
}
interface DocumentsClient {
findOne: (params: {
documentId: string;
}) => Promise<Record<string, unknown> | null>;
update: (params: {
documentId: string;
data: Record<string, unknown>;
}) => Promise<Record<string, unknown>>;
}
/**
* Backfills a bookshelf entry's cover — either by caching whatever URL is
* already in `cover_image` (e.g. one pasted in by hand, or an editor's own
* hosted cover) locally, or by looking one up (books via Open Library by
* ISBN) when there's no cover_image at all yet — and, for papers, missing
* title/authors via Semantic Scholar by DOI/arXiv id. Runs once per entry:
* a `cover_image` already pointing at a local /covers/... path is treated
* as "done" and left alone.
*/
async function enrichBookshelfEntry(
documents: (uid: string) => DocumentsClient,
entry: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const slug = entry.slug as string;
const coverImage = entry.cover_image as string | undefined;
const patch: Record<string, unknown> = {};
try {
if (coverImage && /^https?:\/\//i.test(coverImage)) {
const cached = await cacheRemoteImage(coverImage, slug);
if (cached) patch.cover_image = cached;
} else if (!coverImage) {
if (entry.kind === "book" && entry.isbn) {
const cover = await fetchBookCover(entry.isbn as string, slug);
if (cover) patch.cover_image = cover;
} else if (entry.kind === "paper" && (entry.doi || entry.arxiv_id)) {
const meta = await fetchPaperMetadata({
doi: entry.doi as string | undefined,
arxivId: entry.arxiv_id as string | undefined,
});
if (meta?.title && !entry.title) patch.title = meta.title;
if (
meta?.authors?.length &&
!(entry.authors as string[] | undefined)?.length
) {
patch.authors = meta.authors;
}
}
}
} catch {
// Network/API failures shouldn't block saving the entry itself.
return entry;
}
if (Object.keys(patch).length === 0) return entry;
// Keep the nested update outside the network-failure guard. Its middleware
// persists and publishes the enriched entry; publication errors must reach
// the caller instead of being mistaken for a cover-provider outage.
return documents(BOOKSHELF_UID).update({
documentId: entry.documentId as string,
data: patch,
});
}
/** Registers the outbound (DB -> file) sync as a Document Service middleware. */
export function registerContentSync(strapi: {
documents: {
use: (
middleware: (
ctx: { uid: string; action: string; params: Record<string, unknown> },
next: () => Promise<unknown>,
) => Promise<unknown>,
) => void;
(uid: string): DocumentsClient;
};
log: { info: (msg: string) => void; error: (msg: string) => void };
}): void {
strapi.documents.use(async (ctx, next) => {
const config = SYNC_CONFIGS[ctx.uid];
if (!config || importing) return next();
let preDeleteEntry: Record<string, unknown> | null = null;
if (ctx.action === "delete") {
const documentId = (ctx.params as { documentId?: string }).documentId;
if (documentId) {
preDeleteEntry = await strapi
.documents(ctx.uid)
.findOne({ documentId });
}
}
const result = await next();
try {
if (
(ctx.action === "create" || ctx.action === "update") &&
result &&
typeof result === "object"
) {
const entry =
ctx.uid === BOOKSHELF_UID
? await enrichBookshelfEntry(
strapi.documents,
result as Record<string, unknown>,
)
: (result as Record<string, unknown>);
const entryFile = writeEntryForConfig(config, entry);
if (entryFile) {
const paths = [entryFile];
const coverFile = coverFileForEntry(entry);
if (coverFile) paths.push(coverFile);
await publishContentChanges(
paths,
`content: ${ctx.action} ${entry.slug as string}`,
);
}
} else if (ctx.action === "delete" && preDeleteEntry) {
const slug = preDeleteEntry.slug as string | undefined;
if (!slug) return result;
const paths = [deleteEntry(config.dir, slug, config.layout)];
const coverFile = coverFileForEntry(preDeleteEntry);
if (coverFile) {
rmSync(coverFile, { force: true });
paths.push(coverFile);
}
await publishContentChanges(paths, `content: delete ${slug}`);
}
} catch (err) {
strapi.log.error(
`content-sync: failed to write ${ctx.uid} to disk: ${(err as Error).message}`,
);
throw err;
}
return result;
});
}
+186
View File
@@ -0,0 +1,186 @@
import { execFile } from "node:child_process";
import { relative, resolve } from "node:path";
import { promisify } from "node:util";
import { repositoryRoot } from "./content-paths";
const execFileAsync = promisify(execFile);
interface GitPublisherConfig {
worktree: string;
remote?: string;
branch?: string;
token?: string;
commitName?: string;
commitEmail?: string;
deployWebhookUrl?: string;
fetchImpl?: typeof fetch;
}
function gitAuthenticationEnv(token?: string): NodeJS.ProcessEnv {
if (!token) return process.env;
const credentials = Buffer.from(`x-access-token:${token}`).toString("base64");
return {
...process.env,
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader",
GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${credentials}`,
};
}
export class GitPublisher {
private readonly worktree: string;
private readonly remote: string;
private readonly branch: string;
private readonly token?: string;
private readonly commitName: string;
private readonly commitEmail: string;
private readonly deployWebhookUrl?: string;
private readonly fetchImpl: typeof fetch;
private queue: Promise<void> = Promise.resolve();
private deployPending = false;
constructor(config: GitPublisherConfig) {
this.worktree = resolve(config.worktree);
this.remote = config.remote ?? "origin";
this.branch = config.branch ?? "main";
this.token = config.token;
this.commitName = config.commitName ?? "andwati.com CMS";
this.commitEmail =
config.commitEmail ?? "[email protected]";
this.deployWebhookUrl = config.deployWebhookUrl;
this.fetchImpl = config.fetchImpl ?? fetch;
}
publish(paths: string[], message: string): Promise<void> {
const operation = this.queue.then(() => this.publishNow(paths, message));
this.queue = operation.catch(() => undefined);
return operation;
}
private async git(args: string[]): Promise<string> {
const { stdout } = await execFileAsync("git", args, {
cwd: this.worktree,
env: gitAuthenticationEnv(this.token),
timeout: 30_000,
});
return stdout.trim();
}
private repositoryPaths(paths: string[]): string[] {
return [...new Set(paths)].map((path) => {
const absolute = resolve(path);
const repositoryPath = relative(this.worktree, absolute);
if (
repositoryPath === "" ||
repositoryPath === ".." ||
repositoryPath.startsWith("../")
) {
throw new Error(
`Refusing to publish path outside Git checkout: ${path}`,
);
}
return repositoryPath;
});
}
private async hasStagedChanges(): Promise<boolean> {
try {
await this.git(["diff", "--cached", "--quiet"]);
return false;
} catch (error) {
if ((error as { code?: number }).code === 1) return true;
throw error;
}
}
private async publishNow(paths: string[], message: string): Promise<void> {
const repositoryPaths = this.repositoryPaths(paths);
await this.git(["add", "--all", "--", ...repositoryPaths]);
if (await this.hasStagedChanges()) {
await this.git([
"-c",
`user.name=${this.commitName}`,
"-c",
`user.email=${this.commitEmail}`,
"-c",
"commit.gpgsign=false",
"commit",
"-m",
message,
]);
}
await this.git(["fetch", this.remote, this.branch]);
try {
await this.git([
"rebase",
"--autostash",
`${this.remote}/${this.branch}`,
]);
} catch (error) {
await this.git(["rebase", "--abort"]).catch(() => undefined);
throw error;
}
const ahead = Number(
await this.git([
"rev-list",
"--count",
`${this.remote}/${this.branch}..HEAD`,
]),
);
if (ahead > 0) {
await this.git(["push", this.remote, `HEAD:${this.branch}`]);
this.deployPending = true;
}
if (this.deployPending && this.deployWebhookUrl) {
const response = await this.fetchImpl(this.deployWebhookUrl, {
method: "POST",
signal: AbortSignal.timeout(15_000),
});
if (!response.ok) {
throw new Error(
`Dokploy deploy webhook returned ${response.status} ${response.statusText}`,
);
}
this.deployPending = false;
}
}
}
let publisher: GitPublisher | undefined;
function publisherFromEnvironment(): GitPublisher | undefined {
if (process.env.GIT_PUBLISH_ENABLED !== "true") return undefined;
const token = process.env.GITHUB_TOKEN;
const deployWebhookUrl = process.env.DOKPLOY_DEPLOY_WEBHOOK_URL;
if (!token) throw new Error("GITHUB_TOKEN is required for Git publishing");
if (!deployWebhookUrl) {
throw new Error(
"DOKPLOY_DEPLOY_WEBHOOK_URL is required for Git publishing",
);
}
return new GitPublisher({
worktree: repositoryRoot(),
remote: process.env.CONTENT_GIT_REMOTE ?? "origin",
branch: process.env.CONTENT_GIT_BRANCH ?? "main",
token,
commitName: process.env.CONTENT_GIT_COMMIT_NAME,
commitEmail: process.env.CONTENT_GIT_COMMIT_EMAIL,
deployWebhookUrl,
});
}
/** Publishes changed source files when production Git publishing is enabled. */
export async function publishContentChanges(
paths: string[],
message: string,
): Promise<void> {
publisher ??= publisherFromEnvironment();
await publisher?.publish(paths, message);
}
+125
View File
@@ -0,0 +1,125 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { GitPublisher } from "../src/utils/git-publisher.ts";
function git(cwd: string, ...args: string[]): string {
return execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
}
function repositoryFixture(): {
root: string;
worktree: string;
cleanup: () => void;
} {
const root = mkdtempSync(join(tmpdir(), "andwati-git-publisher-"));
const remote = join(root, "remote.git");
const worktree = join(root, "worktree");
git(root, "init", "--bare", remote);
git(root, "clone", remote, worktree);
writeFileSync(join(worktree, "README.md"), "seed\n");
git(worktree, "add", "README.md");
git(
worktree,
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"seed",
);
git(worktree, "branch", "-M", "main");
git(worktree, "push", "-u", "origin", "main");
return {
root,
worktree,
cleanup: () => rmSync(root, { recursive: true, force: true }),
};
}
test("commits, pushes, and deploys a changed source file", async () => {
const fixture = repositoryFixture();
let deploys = 0;
const publisher = new GitPublisher({
worktree: fixture.worktree,
branch: "main",
deployWebhookUrl: "https://deploy.invalid/hook",
fetchImpl: async () => {
deploys += 1;
return new Response(null, { status: 200 });
},
});
try {
const contentFile = join(fixture.worktree, "content", "post.md");
mkdirSync(join(fixture.worktree, "content"));
writeFileSync(contentFile, "published\n", { flag: "w" });
const concurrentFile = join(fixture.worktree, "content", "next.md");
writeFileSync(concurrentFile, "still being edited\n");
await publisher.publish([contentFile], "content: update post");
assert.equal(
git(fixture.worktree, "show", "origin/main:content/post.md"),
"published",
);
assert.equal(deploys, 1);
assert.equal(readFileSync(concurrentFile, "utf8"), "still being edited\n");
assert.match(git(fixture.worktree, "status", "--short"), /next\.md/);
await publisher.publish([contentFile], "content: update post");
assert.equal(deploys, 1, "unchanged content must not trigger a deploy");
} finally {
fixture.cleanup();
}
});
test("retries a pending deploy without creating another commit", async () => {
const fixture = repositoryFixture();
let deploys = 0;
const publisher = new GitPublisher({
worktree: fixture.worktree,
branch: "main",
deployWebhookUrl: "https://deploy.invalid/hook",
fetchImpl: async () => {
deploys += 1;
return new Response(null, {
status: deploys === 1 ? 503 : 200,
statusText: deploys === 1 ? "Unavailable" : "OK",
});
},
});
try {
const contentFile = join(fixture.worktree, "entry.md");
writeFileSync(contentFile, "durable\n");
await assert.rejects(
publisher.publish([contentFile], "content: create entry"),
/Dokploy deploy webhook returned 503/,
);
await publisher.publish([contentFile], "content: create entry");
assert.equal(deploys, 2);
assert.equal(
git(fixture.worktree, "rev-list", "--count", "origin/main"),
"2",
"the webhook retry must not create a duplicate commit",
);
} finally {
fixture.cleanup();
}
});
+44
View File
@@ -0,0 +1,44 @@
{
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "Node",
"lib": ["ES2020"],
"target": "ES2019",
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"incremental": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"noEmitOnError": true,
"noImplicitThis": true,
"outDir": "dist",
"rootDir": "."
},
"include": [
// Include root files
"./",
// Include all ts files
"./**/*.ts",
// Include all js files
"./**/*.js",
// Force the JSON files in the src folder to be included
"src/**/*.json"
],
"exclude": [
"node_modules/",
"build/",
"dist/",
".cache/",
".tmp/",
".strapi/",
// Do not include admin files in the server compilation
"src/admin/",
// Do not include test files
"**/*.test.*",
// Do not include plugins in the server compilation
"src/plugins/**"
]
}
+3
View File
@@ -0,0 +1,3 @@
/*
* The app doesn't have any components yet.
*/
File diff suppressed because it is too large Load Diff
+10
View File
@@ -0,0 +1,10 @@
# Self-hosted Umami analytics (https://umami.is/docs/tracker-configuration).
# Leave unset to disable analytics entirely — Analytics.astro no-ops until
# both of these are present. Fill in once the Umami instance is deployed.
PUBLIC_UMAMI_SCRIPT_URL=
PUBLIC_UMAMI_WEBSITE_ID=
# Optional: restrict tracking to these comma-separated domains (Umami's
# data-domains attribute), useful if the same build is deployed to a
# staging domain and you only want production traffic counted.
PUBLIC_UMAMI_DOMAINS=
+27
View File
@@ -0,0 +1,27 @@
# build output
dist/
# generated types
.astro/
# dependencies
node_modules/
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# environment variables
.env
.env.production
# Lighthouse CI report artifacts
.lighthouseci/
# macOS-specific files
.DS_Store
# jetbrains setting folder
.idea/
+4
View File
@@ -0,0 +1,4 @@
{
"recommendations": ["astro-build.astro-vscode"],
"unwantedRecommendations": []
}
+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "./node_modules/.bin/astro dev",
"name": "Development server",
"request": "launch",
"type": "node-terminal"
}
]
}
+22
View File
@@ -0,0 +1,22 @@
## Development
When starting the dev server, use background mode:
```
astro dev --background
```
Manage the background server with `astro dev stop`, `astro dev status`, and `astro dev logs`.
## Documentation
Full documentation: https://docs.astro.build
Consult these guides before working on related tasks:
- [Adding pages, dynamic routes, or middleware](https://docs.astro.build/en/guides/routing/)
- [Working with Astro components](https://docs.astro.build/en/basics/astro-components/)
- [Using React, Vue, Svelte, or other framework components](https://docs.astro.build/en/guides/framework-components/)
- [Adding or managing content](https://docs.astro.build/en/guides/content-collections/)
- [Adding styles or using Tailwind](https://docs.astro.build/en/guides/styling/)
- [Supporting multiple languages](https://docs.astro.build/en/guides/internationalization/)
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+43
View File
@@ -0,0 +1,43 @@
# Astro Starter Kit: Minimal
```sh
npm create astro@latest -- --template minimal
```
> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!
## 🚀 Project Structure
Inside of your Astro project, you'll see the following folders and files:
```text
/
├── public/
├── src/
│ └── pages/
│ └── index.astro
└── package.json
```
Astro looks for `.astro` or `.md` files in the `src/pages/` directory. Each page is exposed as a route based on its file name.
There's nothing special about `src/components/`, but that's where we like to put any Astro/React/Vue/Svelte/Preact components.
Any static assets, like images, can be placed in the `public/` directory.
## 🧞 Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:4321` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
| `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI |
## 👀 Want to learn more?
Feel free to check [our documentation](https://docs.astro.build) or jump into our [Discord server](https://astro.build/chat).
+27
View File
@@ -0,0 +1,27 @@
// @ts-check
import sitemap from "@astrojs/sitemap";
import { defineConfig } from "astro/config";
import { buildLastmodMap, resolveContentDir } from "./lib-config/sitemap-lastmod.mjs";
import { siteConfig } from "./src/site.config.ts";
const lastmodMap = buildLastmodMap(resolveContentDir(import.meta.url));
// https://astro.build/config
export default defineConfig({
site: siteConfig.baseUrl,
integrations: [
sitemap({
// Every build re-crawls the actual rendered output, so the sitemap's
// URL list always matches whatever pages/content exist right now — no
// separate "regenerate the sitemap" step needed when content changes.
// On top of that, <lastmod> is set from each entry's own
// date/updated field (falling back to build time when unmapped),
// instead of every URL just getting "whenever the site was last
// built".
serialize(item) {
const lastmod = lastmodMap.get(new URL(item.url).pathname);
return lastmod ? { ...item, lastmod } : item;
},
}),
],
});
+65
View File
@@ -0,0 +1,65 @@
// Builds a Map<pathname, ISO date string> from content/ frontmatter so the
// sitemap's <lastmod> reflects real edit dates instead of just "whenever the
// site was last built". Runs from astro.config.mjs, which executes as plain
// Node outside Vite/Astro's content-layer pipeline (same reason
// scripts/generate-llms.astro-site.mjs parses frontmatter by hand instead of
// importing astro:content) — duplicated here rather than shared because the
// two scripts' output shapes don't overlap enough to be worth a shared module.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { parse as parseToml } from "smol-toml";
const FRONTMATTER_RE = /^\+\+\+\r?\n([\s\S]*?)\r?\n\+\+\+\r?\n?([\s\S]*)$/;
function walk(dir) {
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) return walk(full);
return entry.isFile() && entry.name.endsWith(".md") ? [full] : [];
});
}
function slugFor(dir, file) {
const rel = path.relative(dir, file).split(path.sep).join("/");
return rel.endsWith("/index.md") ? rel.slice(0, -"/index.md".length) : rel.slice(0, -".md".length);
}
function readEntries(typeDir) {
return walk(typeDir)
.map((file) => {
const raw = fs.readFileSync(file, "utf8");
const match = raw.match(FRONTMATTER_RE);
if (!match) return null;
return { slug: slugFor(typeDir, file), frontmatter: parseToml(match[1]) };
})
.filter(Boolean);
}
function isoOrNull(value) {
if (!value) return null;
const d = value instanceof Date ? value : new Date(value);
return Number.isNaN(d.valueOf()) ? null : d.toISOString();
}
export function buildLastmodMap(contentDir) {
const map = new Map();
for (const entry of readEntries(path.join(contentDir, "writings"))) {
if (entry.frontmatter.draft) continue;
const lastmod = isoOrNull(entry.frontmatter.updated ?? entry.frontmatter.date);
if (lastmod) map.set(`/writings/${entry.slug}/`, lastmod);
}
for (const entry of readEntries(path.join(contentDir, "bookshelf"))) {
const lastmod = isoOrNull(entry.frontmatter.date_finished ?? entry.frontmatter.date_started);
if (lastmod) map.set(`/bookshelf/${entry.slug}/`, lastmod);
}
return map;
}
export function resolveContentDir(configFileUrl) {
return path.join(path.dirname(fileURLToPath(configFileUrl)), "..", "..", "content");
}
+32
View File
@@ -0,0 +1,32 @@
/**
* Lighthouse CI — runs the same audits PageSpeed Insights reports on
* (performance, accessibility, best-practices, SEO) against the built site,
* so results can be tracked over time / per-commit without depending on the
* hosted PSI API. `staticDistDir` lets lhci serve `dist/` itself, no dev
* server juggling needed. Reporting only for now — no `assert` thresholds,
* so a regression shows up in the report without failing the build.
*/
module.exports = {
ci: {
collect: {
staticDistDir: "./dist",
url: [
"/index.html",
"/writings/index.html",
"/writings/from-c-to-machine-code/index.html",
"/archive/index.html",
"/portfolio/index.html",
"/bookshelf/index.html",
"/tags/index.html",
"/about/index.html",
],
numberOfRuns: 3,
},
upload: {
// Free, no account/server needed — each run prints a shareable report
// link (expires after 7 days). Point this at a real LHCI server later
// if longer-lived historical tracking is wanted.
target: "temporary-public-storage",
},
},
};
+15
View File
@@ -0,0 +1,15 @@
// Desktop form-factor pass — same pages/config as lighthouserc.cjs, but
// Lighthouse's default (and PageSpeed Insights' default) is mobile: throttled
// CPU/network and a narrow viewport. Auditing desktop too means neither form
// factor's numbers are a blind spot.
const mobileConfig = require("./lighthouserc.cjs");
module.exports = {
ci: {
...mobileConfig.ci,
collect: {
...mobileConfig.ci.collect,
settings: { preset: "desktop" },
},
},
};
+42
View File
@@ -0,0 +1,42 @@
{
"name": "site",
"type": "module",
"version": "0.0.1",
"engines": {
"node": ">=22.12.0"
},
"scripts": {
"dev": "astro dev",
"generate:llms": "node ../../scripts/generate-llms.astro-site.mjs",
"generate:og": "node ../../scripts/generate-og-images.astro-site.mjs",
"build": "pnpm run generate:llms && pnpm run generate:og && astro build && pagefind --site dist",
"preview": "astro preview",
"check": "astro check",
"astro": "astro",
"lighthouse": "pnpm run build && lhci autorun && lhci autorun --config=lighthouserc.desktop.cjs"
},
"dependencies": {
"@astrojs/rss": "^4.0.19",
"@astrojs/sitemap": "^3.7.3",
"@fontsource-variable/fraunces": "^5.3.0",
"@fontsource-variable/newsreader": "^5.3.0",
"@fontsource/jetbrains-mono": "^5.3.0",
"astro": "^7.2.9",
"highlight.js": "^11.12.0",
"katex": "^0.18.7",
"marked": "^18.0.11",
"marked-katex-extension": "^5.1.12",
"pagefind": "^1.5.2",
"smol-toml": "^1.8.0",
"three": "^0.185.1"
},
"allowScripts": {
"esbuild": true
},
"devDependencies": {
"@astrojs/check": "^0.9.10",
"@lhci/cli": "^0.15.1",
"@types/three": "^0.185.4",
"typescript": "^5.9.3"
}
}
+13
View File
@@ -0,0 +1,13 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEalcjtBYJKwYBBAHaRw8BAQdA55X1mRCKw9DA35kCAy+7Z30ye0rUHWBZsl7O
Wmar+RS0IklhbiBBbmR3YXRpIDxhbmR3YXRpaWFuQGdtYWlsLmNvbT6IkwQTFgoA
OxYhBK1YqreiDYUjy/WaeR8g/tCqBbDaBQJqVyO0AhsDBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEB8g/tCqBbDace8BAN1SpkEMSYll+XupKHiaIUwnhm4N
eS79G1i+345Gl6CyAQDjgn+3rzG6sexjKh+10EKiy5omsQEGzUW03s7gS0T1Drg4
BGpXI7QSCisGAQQBl1UBBQEBB0CXofBIYYXG2+dZqgllhsbkNPF4qlyfPgbRW+zb
7Kw3IAMBCAeIeAQYFgoAIBYhBK1YqreiDYUjy/WaeR8g/tCqBbDaBQJqVyO0AhsM
AAoJEB8g/tCqBbDauMkA/RG4iqtPZOI3DQzFJYu7SnxaD81vdP0LyTLKDQkynySu
AQDrlWyF8LRlad4iX1yQPCuOV0aUpTNq5kPlWurtX99/BQ==
=uKsS
-----END PGP PUBLIC KEY BLOCK-----
+17
View File
@@ -0,0 +1,17 @@
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
Contact: mailto:[email protected]
Expires: 2027-07-16T00:00:00.000Z
Encryption: https://andwati.com/.well-known/pgp-key.txt
Encryption: https://keys.openpgp.org/vks/v1/by-fingerprint/AD58AAB7A20D8523CBF59A791F20FED0AA05B0DA
Encryption: https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xAD58AAB7A20D8523CBF59A791F20FED0AA05B0DA
Preferred-Languages: en
Canonical: https://andwati.com/.well-known/security.txt
-----BEGIN PGP SIGNATURE-----
iHUEARYKAB0WIQStWKq3og2FI8v1mnkfIP7QqgWw2gUCaljXlQAKCRAfIP7QqgWw
2qAoAP0Q7Cc0YsP2dvV7fqDlqcnjuJepQQSTZBz7ehkPyjGV5gEA3K9ZqQmuI2ea
KKADWxuKTTY43PBmuV9rMqLm8ZOPlAY=
=NUkY
-----END PGP SIGNATURE-----
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Some files were not shown because too many files have changed in this diff Show More