Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
424a7ac1ed | ||
|
|
d236eb3dc4 | ||
|
|
e7cd4c2231 | ||
|
|
80577d6404 | ||
|
|
2b775cbf99 | ||
|
|
d7b8a351c1 | ||
|
|
fb8e42f632 |
No files matched your search
@@ -0,0 +1,23 @@
|
|||||||
|
# Copy to .env (gitignored; dotenv-cli loads it for dev/start/build).
|
||||||
|
#
|
||||||
|
# Content reads are PUBLIC — every Appwrite table grants read("any") — so the
|
||||||
|
# site works with none of these set. Defaults point at the homelab instance.
|
||||||
|
|
||||||
|
# Appwrite TablesDB content backend (src/lib/appwrite.ts)
|
||||||
|
# APPWRITE_ENDPOINT=https://appwrite.spaghet.io/v1
|
||||||
|
# APPWRITE_PROJECT_ID=homelab
|
||||||
|
# APPWRITE_DATABASE_ID=spaghet-home
|
||||||
|
|
||||||
|
# Optional: a server key sent with every read (bypasses the guest rate
|
||||||
|
# limiter). Needs only databases.read/collections.read/documents.read-style
|
||||||
|
# read scopes — see the spaghet-home-content key. Never exposed to the browser.
|
||||||
|
# APPWRITE_API_KEY=
|
||||||
|
|
||||||
|
*** In-process cache lifetime for content reads, seconds. On a failed refresh
|
||||||
|
# the stale value is served; a cold-cache failure falls back to the bundled
|
||||||
|
# .md copies under src/content.
|
||||||
|
# APPWRITE_CONTENT_TTL_SECONDS=60
|
||||||
|
|
||||||
|
# Uptime Kuma status page (src/lib/status.ts)
|
||||||
|
# STATUS_PAGE_URL=https://uptime.spaghet.io
|
||||||
|
# STATUS_PAGE_SLUG=public
|
||||||
@@ -1,17 +1,66 @@
|
|||||||
# Spaghet.io
|
# Spaghet.io
|
||||||
|
|
||||||
Welcome to my personal website! This site showcases my projects, blog posts, and professional experience. It's built with Astro and hosted using a modern deployment pipeline.
|
Welcome to my personal website! This site showcases my projects, blog posts, and
|
||||||
|
professional experience. It's built with Astro in SSR mode and runs entirely on
|
||||||
|
self-hosted infrastructure: the site itself is an [Appwrite](https://appwrite.io)
|
||||||
|
Site, its content lives in Appwrite TablesDB, and its images come from Appwrite
|
||||||
|
Storage — all on my own server.
|
||||||
|
|
||||||
|
Live at [spaghet.io](https://spaghet.io) (served from the Appwrite site at
|
||||||
|
[home.spaghet.io](https://home.spaghet.io)).
|
||||||
|
|
||||||
## Deployment Pipeline
|
## Deployment Pipeline
|
||||||
|
|
||||||
My website follows a robust deployment workflow:
|
My website follows a push-to-deploy workflow:
|
||||||
|
|
||||||
1. **Development**: I develop content and code locally using Gitea as my Git hosting solution
|
1. **Development**: I develop content and code locally and push to
|
||||||
2. **Auto-push**: Changes are automatically pushed from Gitea to GitHub via configured webhooks
|
[Gitea](https://gitea.spaghet.io/spaghet/Spaghet.io), my canonical Git host.
|
||||||
3. **Hosting**: The site is hosted on self-hosted infrastructure, which provides a scalable and secure hosting environment
|
2. **Auto-deploy**: a Gitea webhook notifies Appwrite Sites. A push to `main`
|
||||||
4. **Delivery**: NGINX reverse proxy handles routing and serves content with optimal performance
|
builds a new deployment and becomes the live one; pushes to other branches
|
||||||
|
build ephemeral preview deployments at `branch-<name>-<hash>.spaghet.io`
|
||||||
|
(console sign-in required to view).
|
||||||
|
3. **Runtime**: Appwrite's compute (Open Runtimes, Node 22) runs the Astro SSR
|
||||||
|
server (`@astrojs/node`). Pages fetch their content per request, so editing
|
||||||
|
a blog post in the Appwrite console goes live without a rebuild.
|
||||||
|
4. **Edge**: NGINX Proxy Manager terminates TLS (Let's Encrypt wildcard cert
|
||||||
|
for `*.spaghet.io`) and routes to Appwrite's Traefik router, which matches
|
||||||
|
the site's proxy rule.
|
||||||
|
|
||||||
This pipeline ensures that my website is always up-to-date with the latest changes while leveraging modern hosting technologies.
|
## Content: Appwrite TablesDB
|
||||||
|
|
||||||
|
The markdown under `src/content/` is the source of truth and backup, but pages
|
||||||
|
read from Appwrite at request time:
|
||||||
|
|
||||||
|
- Database `spaghet-home` (project `homelab` on `appwrite.spaghet.io`), one
|
||||||
|
table per collection: `blog`, `projects`, `work`, `legal`. Frontmatter
|
||||||
|
fields are columns, the markdown body is the `content` column, and the
|
||||||
|
filename is the row id and slug.
|
||||||
|
- `src/lib/appwrite.ts` is the service layer: SDK reads, markdown rendered at
|
||||||
|
request time with Astro's own Shiki pipeline (dual themes, same config as
|
||||||
|
`astro.config.mjs`), 60-second in-process cache with stale-serving.
|
||||||
|
- `src/lib/content-source.ts` is the facade every page imports: Appwrite first,
|
||||||
|
bundled `.md` copies as fallback when Appwrite is cold-unreachable. The site
|
||||||
|
never 500s on a backend outage.
|
||||||
|
- Reads are public: each table grants `read("any")`, so the server needs no API
|
||||||
|
key for normal traffic. `scripts/appwrite-migrate.mjs` (re-)imports all
|
||||||
|
content rows and both images; it is idempotent.
|
||||||
|
- Images (`logo.png`, `profile.jpg`) live in the Storage bucket `site-media`
|
||||||
|
under stable file ids; `src/lib/media.ts` builds the browser URLs (including
|
||||||
|
the on-the-fly resized profile preview), and each `<img>` falls back to the
|
||||||
|
`public/images/` copy via `onerror` if storage is ever down.
|
||||||
|
|
||||||
|
Optional environment variables (all have working defaults, see `.env.example`):
|
||||||
|
|
||||||
|
| Variable | Default | Purpose |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `APPWRITE_ENDPOINT` | `https://appwrite.spaghet.io/v1` | Content/media backend origin |
|
||||||
|
| `APPWRITE_PROJECT_ID` | `homelab` | Appwrite project |
|
||||||
|
| `APPWRITE_DATABASE_ID` | `spaghet-home` | TablesDB database |
|
||||||
|
| `APPWRITE_API_KEY` | *(unset)* | Optional server key for reads (bypasses guest rate limits) |
|
||||||
|
| `APPWRITE_CONTENT_TTL_SECONDS` | `60` | In-process content cache lifetime |
|
||||||
|
|
||||||
|
Search (`/search`) runs client-side with fuse.js over a slim index of blog and
|
||||||
|
project titles, summaries and tags — bodies are never shipped to the browser.
|
||||||
|
|
||||||
## Site Components
|
## Site Components
|
||||||
|
|
||||||
@@ -85,14 +134,19 @@ has something warm to sit on.
|
|||||||
|
|
||||||
Code blocks use dual Shiki themes (`light-plus` / `everforest-dark`, chosen by measuring
|
Code blocks use dual Shiki themes (`light-plus` / `everforest-dark`, chosen by measuring
|
||||||
every bundled theme's tokens against the site's own code backgrounds) with the
|
every bundled theme's tokens against the site's own code backgrounds) with the
|
||||||
`--shiki-light` / `--shiki-dark` swap in `global.css`.
|
`--shiki-light` / `--shiki-dark` swap in `global.css`. The same config is mirrored in
|
||||||
|
`src/lib/appwrite.ts`, which renders stored markdown at request time, so code blocks
|
||||||
|
look identical whether content came from Appwrite or the bundled `.md` fallback.
|
||||||
|
|
||||||
## Technologies Used
|
## Technologies Used
|
||||||
|
|
||||||
- **Framework**: Astro (Static site generation)
|
- **Framework**: Astro 7 (server-side rendering via `@astrojs/node`)
|
||||||
- **Styling**: Tailwind CSS
|
- **Interactivity**: SolidJS islands (filterable listings, search)
|
||||||
|
- **Styling**: Tailwind CSS 4 with custom semantic tokens
|
||||||
- **TypeScript**: Type-safe development
|
- **TypeScript**: Type-safe development
|
||||||
- **Deployment**: Gitea → GitHub → Self-hosted infrastructure → NGINX reverse proxy
|
- **Backend**: Appwrite 2.7 — Sites (compute), TablesDB (content), Storage (media)
|
||||||
|
- **Deployment**: Gitea → webhook → Appwrite Sites build → SSR runtime, behind
|
||||||
|
NGINX Proxy Manager (TLS) and Appwrite's Traefik router
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
@@ -102,8 +156,11 @@ To run this site locally:
|
|||||||
# Install dependencies
|
# Install dependencies
|
||||||
npm install
|
npm install
|
||||||
|
|
||||||
# Start development server
|
# Start development server (content reads hit Appwrite; the .md fallback works offline)
|
||||||
npm run dev
|
npm run dev
|
||||||
|
|
||||||
|
# Re-import content and images into Appwrite after editing .md files
|
||||||
|
APPWRITE_API_KEY=*** node scripts/appwrite-migrate.mjs
|
||||||
```
|
```
|
||||||
|
|
||||||
For more information about the Astro framework and its features, please refer to the [Astro documentation](https://docs.astro.build/).
|
For more information about the Astro framework and its features, please refer to the [Astro documentation](https://docs.astro.build/).
|
||||||
|
|||||||
+21
-1
@@ -4,11 +4,31 @@ import sitemap from "@astrojs/sitemap"
|
|||||||
import solidJs from "@astrojs/solid-js"
|
import solidJs from "@astrojs/solid-js"
|
||||||
import node from "@astrojs/node"
|
import node from "@astrojs/node"
|
||||||
import tailwindcss from "@tailwindcss/vite"
|
import tailwindcss from "@tailwindcss/vite"
|
||||||
|
import { readdirSync } from "node:fs"
|
||||||
|
|
||||||
|
// The blog/projects/legal detail pages are served from Appwrite at request
|
||||||
|
// time (prerender = false), so they no longer appear in the build-time route
|
||||||
|
// list the sitemap integration collects. Compute their URLs from the bundled
|
||||||
|
// markdown copies — the same files scripts/appwrite-migrate.mjs imports, and
|
||||||
|
// the fallback source — so the sitemap stays complete without a build-time
|
||||||
|
// network call.
|
||||||
|
function contentPages() {
|
||||||
|
const site = "https://spaghet.io"
|
||||||
|
const slugs = (dir) =>
|
||||||
|
readdirSync(new URL(`./src/content/${dir}/`, import.meta.url))
|
||||||
|
.filter((f) => f.endsWith(".md"))
|
||||||
|
.map((f) => f.replace(/\.md$/, ""))
|
||||||
|
return [
|
||||||
|
...slugs("blog").map((s) => `${site}/blog/${s}/`),
|
||||||
|
...slugs("projects").map((s) => `${site}/projects/${s}/`),
|
||||||
|
...slugs("legal").map((s) => `${site}/legal/${s}/`),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
// https://astro.build/config
|
// https://astro.build/config
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
site: "https://spaghet.io",
|
site: "https://spaghet.io",
|
||||||
integrations: [mdx(), sitemap(), solidJs()],
|
integrations: [mdx(), sitemap({ customPages: contentPages() }), solidJs()],
|
||||||
output: "server",
|
output: "server",
|
||||||
adapter: node({ mode: "ssr" }),
|
adapter: node({ mode: "ssr" }),
|
||||||
markdown: {
|
markdown: {
|
||||||
|
|||||||
Generated
+42
@@ -9,6 +9,7 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/check": "^0.9.10",
|
"@astrojs/check": "^0.9.10",
|
||||||
|
"@astrojs/markdown-satteri": "^0.4.3",
|
||||||
"@astrojs/mdx": "^8.0.3",
|
"@astrojs/mdx": "^8.0.3",
|
||||||
"@astrojs/node": "^11.1.7",
|
"@astrojs/node": "^11.1.7",
|
||||||
"@astrojs/rss": "^4.0.19",
|
"@astrojs/rss": "^4.0.19",
|
||||||
@@ -20,6 +21,7 @@
|
|||||||
"astro": "^7.3.8",
|
"astro": "^7.3.8",
|
||||||
"clsx": "^2.1.0",
|
"clsx": "^2.1.0",
|
||||||
"fuse.js": "^7.0.0",
|
"fuse.js": "^7.0.0",
|
||||||
|
"node-appwrite": "^32.4.0",
|
||||||
"notenv": "^2.0.3",
|
"notenv": "^2.0.3",
|
||||||
"rehype-stringify": "^10.0.1",
|
"rehype-stringify": "^10.0.1",
|
||||||
"remark": "^15.0.1",
|
"remark": "^15.0.1",
|
||||||
@@ -3246,6 +3248,15 @@
|
|||||||
"url": "https://github.com/sponsors/wooorm"
|
"url": "https://github.com/sponsors/wooorm"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/bignumber.js": {
|
||||||
|
"version": "9.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
|
||||||
|
"integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/boolbase": {
|
"node_modules/boolbase": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
|
||||||
@@ -4324,6 +4335,15 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/json-bigint": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"bignumber.js": "^9.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/json-schema-traverse": {
|
"node_modules/json-schema-traverse": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
||||||
@@ -5284,6 +5304,28 @@
|
|||||||
"url": "https://opencollective.com/unified"
|
"url": "https://opencollective.com/unified"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/node-appwrite": {
|
||||||
|
"version": "32.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/node-appwrite/-/node-appwrite-32.4.0.tgz",
|
||||||
|
"integrity": "sha512-m+NeMSCpqE8Vfe6rBQvOnzL+X7aEahizG60I2TdKQK7jHzVIKnlhgOfSAW8z87/fi5qp/bks5GHC8kdpehsMjQ==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"json-bigint": "1.0.0",
|
||||||
|
"undici": "^6.27.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/node-appwrite/node_modules/undici": {
|
||||||
|
"version": "6.29.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz",
|
||||||
|
"integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.17"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/node-fetch-native": {
|
"node_modules/node-fetch-native": {
|
||||||
"version": "1.6.7",
|
"version": "1.6.7",
|
||||||
"resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz",
|
"resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz",
|
||||||
|
|||||||
+5
-3
@@ -6,17 +6,18 @@
|
|||||||
"dev": "dotenv -e .env -- astro dev",
|
"dev": "dotenv -e .env -- astro dev",
|
||||||
"dev:network": "dotenv -e .env -- astro dev --host",
|
"dev:network": "dotenv -e .env -- astro dev --host",
|
||||||
"start": "dotenv -e .env -- astro dev",
|
"start": "dotenv -e .env -- astro dev",
|
||||||
"build": "astro check && astro build",
|
"build": "export RAYON_NUM_THREADS=1 TOKIO_WORKER_THREADS=1; astro check && astro build",
|
||||||
"preview": "dotenv -e .env -- astro preview",
|
"preview": "dotenv -e .env -- astro preview",
|
||||||
"preview:network": "dotenv -e .env -- astro dev --host",
|
"preview:network": "dotenv -e .env -- astro dev --host",
|
||||||
"astro": "astro",
|
"astro": "astro",
|
||||||
"test": "vitest run",
|
"test": "export RAYON_NUM_THREADS=1 TOKIO_WORKER_THREADS=1; vitest run",
|
||||||
"test:watch": "vitest",
|
"test:watch": "export RAYON_NUM_THREADS=1 TOKIO_WORKER_THREADS=1; vitest",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"lint:fix": "eslint . --fix"
|
"lint:fix": "eslint . --fix"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/check": "^0.9.10",
|
"@astrojs/check": "^0.9.10",
|
||||||
|
"@astrojs/markdown-satteri": "^0.4.3",
|
||||||
"@astrojs/mdx": "^8.0.3",
|
"@astrojs/mdx": "^8.0.3",
|
||||||
"@astrojs/node": "^11.1.7",
|
"@astrojs/node": "^11.1.7",
|
||||||
"@astrojs/rss": "^4.0.19",
|
"@astrojs/rss": "^4.0.19",
|
||||||
@@ -28,6 +29,7 @@
|
|||||||
"astro": "^7.3.8",
|
"astro": "^7.3.8",
|
||||||
"clsx": "^2.1.0",
|
"clsx": "^2.1.0",
|
||||||
"fuse.js": "^7.0.0",
|
"fuse.js": "^7.0.0",
|
||||||
|
"node-appwrite": "^32.4.0",
|
||||||
"notenv": "^2.0.3",
|
"notenv": "^2.0.3",
|
||||||
"rehype-stringify": "^10.0.1",
|
"rehype-stringify": "^10.0.1",
|
||||||
"remark": "^15.0.1",
|
"remark": "^15.0.1",
|
||||||
|
|||||||
@@ -24,5 +24,10 @@
|
|||||||
<path fill="#6366f1" d="M23.5 6.5C17.5 6.5 13.75 9.5 12.25 15.5C14.5 12.5 17.125 11.375 20.125 12.125C21.8367 12.5529 23.0601 13.7947 24.4142 15.1692C26.6202 17.4084 29.1734 20 34.75 20C40.75 20 44.5 17 46 11C43.75 14 41.125 15.125 38.125 14.375C36.4133 13.9471 35.1899 12.7053 33.8357 11.3308C31.6297 9.09158 29.0766 6.5 23.5 6.5ZM12.25 20C6.25 20 2.5 23 1 29C3.25 26 5.875 24.875 8.875 25.625C10.5867 26.0529 11.8101 27.2947 13.1642 28.6693C15.3702 30.9084 17.9234 33.5 23.5 33.5C29.5 33.5 33.25 30.5 34.75 24.5C32.5 27.5 29.875 28.625 26.875 27.875C25.1633 27.4471 23.9399 26.2053 22.5858 24.8307C20.3798 22.5916 17.8266 20 12.25 20Z"/>
|
<path fill="#6366f1" d="M23.5 6.5C17.5 6.5 13.75 9.5 12.25 15.5C14.5 12.5 17.125 11.375 20.125 12.125C21.8367 12.5529 23.0601 13.7947 24.4142 15.1692C26.6202 17.4084 29.1734 20 34.75 20C40.75 20 44.5 17 46 11C43.75 14 41.125 15.125 38.125 14.375C36.4133 13.9471 35.1899 12.7053 33.8357 11.3308C31.6297 9.09158 29.0766 6.5 23.5 6.5ZM12.25 20C6.25 20 2.5 23 1 29C3.25 26 5.875 24.875 8.875 25.625C10.5867 26.0529 11.8101 27.2947 13.1642 28.6693C15.3702 30.9084 17.9234 33.5 23.5 33.5C29.5 33.5 33.25 30.5 34.75 24.5C32.5 27.5 29.875 28.625 26.875 27.875C25.1633 27.4471 23.9399 26.2053 22.5858 24.8307C20.3798 22.5916 17.8266 20 12.25 20Z"/>
|
||||||
</symbol>
|
</symbol>
|
||||||
|
|
||||||
|
<!-- appwrite icon (brand pink, simple-icons shape) -->
|
||||||
|
<symbol id="appwrite" viewBox="0 0 24 24">
|
||||||
|
<path fill="#FD366E" d="M24 17.291v5.29H10.557A10.58 10.58 0 0 1 0 12.715v-1.43c.048-.735.174-1.463.374-2.171C1.63 4.673 5.713 1.419 10.557 1.419c4.844 0 8.927 3.254 10.183 7.695h-5.749a5.283 5.283 0 0 0-4.434-2.404 5.282 5.282 0 0 0-4.434 2.404A5.23 5.23 0 0 0 5.267 12a5.27 5.27 0 0 0 1.66 3.848 5.27 5.27 0 0 0 3.63 1.443H24Zm0-6.734v5.291h-9.813A5.276 5.276 0 0 0 15.848 12c0-.5-.07-.984-.199-1.443H24Z"/>
|
||||||
|
</symbol>
|
||||||
|
|
||||||
</defs>
|
</defs>
|
||||||
</svg>
|
</svg>
|
||||||
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 5.0 KiB |
@@ -0,0 +1,155 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Import (and re-sync) the markdown content in src/content/* into the
|
||||||
|
* `spaghet-home` TablesDB database on appwrite.spaghet.io.
|
||||||
|
*
|
||||||
|
* Tables (schema, created once via API/console): blog, projects, work, legal.
|
||||||
|
* The frontmatter fields become row columns, the markdown body becomes the
|
||||||
|
* `content` column (mediumtext), and the filename (minus .md) is both the
|
||||||
|
* row $id and the `slug` column. Dates are sent as ISO 8601 UTC.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* APPWRITE_API_KEY=*** node scripts/appwrite-migrate.mjs [--collection blog]
|
||||||
|
*
|
||||||
|
* The key needs scopes: databases.read/write, tables.read/write,
|
||||||
|
* rows.read/write. It is sent as the x-appwrite-key header (server SDK
|
||||||
|
* auth; Bearer works for reads but this instance rejects it for writes).
|
||||||
|
*
|
||||||
|
* Idempotent: each file is upserted (create, fall back to update on 409).
|
||||||
|
* Run it again after editing any .md to push changes to Appwrite.
|
||||||
|
*
|
||||||
|
* NOTE: this script is the migration/backup path. Once src/lib/appwrite.ts
|
||||||
|
* serves reads, Appwrite is the source of truth for published content and
|
||||||
|
* this script only needs to run when you deliberately re-import.
|
||||||
|
*/
|
||||||
|
import { readdir, readFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
const ENDPOINT = process.env.APPWRITE_ENDPOINT ?? "https://appwrite.spaghet.io/v1";
|
||||||
|
const PROJECT = process.env.APPWRITE_PROJECT_ID ?? "homelab";
|
||||||
|
const DATABASE = process.env.APPWRITE_DATABASE_ID ?? "spaghet-home";
|
||||||
|
const KEY = process.env.APPWRITE_API_KEY;
|
||||||
|
if (!KEY) throw new Error("APPWRITE_API_KEY is required (tablesdb-scoped key)");
|
||||||
|
|
||||||
|
const COLLECTIONS = ["blog", "projects", "work", "legal"];
|
||||||
|
|
||||||
|
// --- frontmatter -------------------------------------------------------
|
||||||
|
function parseFrontmatter(raw) {
|
||||||
|
const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
|
||||||
|
if (!m) return { data: {}, body: raw };
|
||||||
|
const data = {};
|
||||||
|
for (const line of m[1].split(/\r?\n/)) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
const idx = line.indexOf(":");
|
||||||
|
if (idx === -1) continue;
|
||||||
|
const key = line.slice(0, idx).trim();
|
||||||
|
let value = line.slice(idx + 1).trim();
|
||||||
|
if (value.startsWith("[") && value.endsWith("]")) {
|
||||||
|
data[key] = value
|
||||||
|
.slice(1, -1)
|
||||||
|
.split(",")
|
||||||
|
.map((s) => s.trim().replace(/^["']|["']$/g, ""))
|
||||||
|
.filter(Boolean);
|
||||||
|
} else if (value === "true" || value === "false") {
|
||||||
|
data[key] = value === "true";
|
||||||
|
} else if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||||
|
data[key] = `${value}T00:00:00.000Z`; // Appwrite datetime
|
||||||
|
} else {
|
||||||
|
data[key] = value.replace(/^["']|["']$/g, "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { data, body: m[2] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Appwrite REST -----------------------------------------------------
|
||||||
|
async function api(method, url, body) {
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
"x-appwrite-key": KEY,
|
||||||
|
"x-appwrite-project": PROJECT,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
let json;
|
||||||
|
try {
|
||||||
|
json = JSON.parse(text);
|
||||||
|
} catch {
|
||||||
|
json = { message: text };
|
||||||
|
}
|
||||||
|
return { status: res.status, json };
|
||||||
|
}
|
||||||
|
|
||||||
|
const base = path.resolve(import.meta.dirname, "..", "src", "content");
|
||||||
|
const only = (() => {
|
||||||
|
const i = process.argv.indexOf("--collection");
|
||||||
|
return i !== -1 ? process.argv[i + 1] : null;
|
||||||
|
})();
|
||||||
|
|
||||||
|
let created = 0, updated = 0, failed = 0;
|
||||||
|
for (const coll of COLLECTIONS) {
|
||||||
|
if (only && only !== coll) continue;
|
||||||
|
const files = (await readdir(path.join(base, coll))).filter((f) => f.endsWith(".md")).sort();
|
||||||
|
for (const file of files) {
|
||||||
|
const slug = file.replace(/\.md$/, "");
|
||||||
|
const raw = await readFile(path.join(base, coll, file), "utf8");
|
||||||
|
const { data, body } = parseFrontmatter(raw);
|
||||||
|
const row = { slug, content: body.trim() + "\n", ...data };
|
||||||
|
const url = `${ENDPOINT}/tablesdb/${DATABASE}/tables/${coll}/rows`;
|
||||||
|
let res = await api("POST", url, { rowId: slug, data: row });
|
||||||
|
if (res.status === 201) {
|
||||||
|
created++;
|
||||||
|
} else if (res.status === 409) {
|
||||||
|
res = await api("PUT", `${url}/${encodeURIComponent(slug)}`, { data: row });
|
||||||
|
if (res.status === 200) updated++;
|
||||||
|
}
|
||||||
|
if (res.status >= 400) {
|
||||||
|
failed++;
|
||||||
|
console.error(`${coll}/${slug}: ${res.status} ${res.json.message ?? ""}`);
|
||||||
|
} else {
|
||||||
|
console.log(`${coll}/${slug}: ok`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- media (public/images/*.{png,jpg,jpeg,webp}) --------------------------
|
||||||
|
// Files are upserted under stable IDs equal to the filename, so a re-import
|
||||||
|
// replaces bytes rather than piling up versions. The bucket (`site-media`)
|
||||||
|
// must exist with read("any") and a non-zero maximumFileSize; create it once
|
||||||
|
// from the console or the API.
|
||||||
|
if (!only) {
|
||||||
|
const BUCKET = process.env.APPWRITE_BUCKET_ID ?? "site-media";
|
||||||
|
const imgDir = path.resolve(import.meta.dirname, "..", "public", "images");
|
||||||
|
const images = (await readdir(imgDir)).filter((f) => /\.(png|jpe?g|webp)$/i.test(f)).sort();
|
||||||
|
for (const file of images) {
|
||||||
|
const buf = await readFile(path.join(imgDir, file));
|
||||||
|
const existing = await api("GET", `${ENDPOINT}/storage/buckets/${BUCKET}/files/${encodeURIComponent(file)}`);
|
||||||
|
if (existing.status === 200 && existing.json.sizeOriginal === buf.length) {
|
||||||
|
console.log(`media/${file}: unchanged`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (existing.status === 200) {
|
||||||
|
// No content-replace endpoint: delete, then re-create with the same id.
|
||||||
|
await api("DELETE", `${ENDPOINT}/storage/buckets/${BUCKET}/files/${encodeURIComponent(file)}`);
|
||||||
|
}
|
||||||
|
const form = new FormData();
|
||||||
|
form.append("fileId", file);
|
||||||
|
form.append("fileUpload", new Blob([buf]), file);
|
||||||
|
const res = await fetch(`${ENDPOINT}/storage/buckets/${BUCKET}/files`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "x-appwrite-key": KEY, "x-appwrite-project": PROJECT },
|
||||||
|
body: form,
|
||||||
|
});
|
||||||
|
if (res.status === 201) {
|
||||||
|
console.log(`media/${file}: uploaded (${buf.length} bytes)`);
|
||||||
|
} else {
|
||||||
|
failed++;
|
||||||
|
console.error(`media/${file}: ${res.status} ${(await res.text()).slice(0, 120)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`\ncreated=${created} updated=${updated} failed=${failed}`);
|
||||||
|
process.exit(failed ? 1 : 0);
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
import type { BlogPost } from "@lib/types"
|
|
||||||
import { createMemo, createSignal, For } from "solid-js"
|
|
||||||
import ArrowCard from "@components/ArrowCard"
|
|
||||||
import { cn } from "@lib/utils"
|
|
||||||
import { filterByTags } from "@lib/content"
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
tags: string[]
|
|
||||||
data: BlogPost[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Blog({ data, tags }: Props) {
|
|
||||||
const [filter, setFilter] = createSignal(new Set<string>())
|
|
||||||
|
|
||||||
// `createMemo`, not `createEffect` + a signal: effects never run during SSR, so the
|
|
||||||
// signal stayed at its initial `[]` and the server emitted "SHOWING 0 OF 3" with an
|
|
||||||
// empty <ul>. The list was only ever filled by client hydration, which meant any
|
|
||||||
// island load failure hid every post.
|
|
||||||
const posts = createMemo<BlogPost[]>(() => filterByTags(data, filter()))
|
|
||||||
|
|
||||||
function toggleTag(tag: string) {
|
|
||||||
setFilter((prev) =>
|
|
||||||
new Set(prev.has(tag)
|
|
||||||
? [...prev].filter((t) => t !== tag)
|
|
||||||
: [...prev, tag]
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
|
|
||||||
<div class="col-span-3 sm:col-span-1">
|
|
||||||
<div class="sticky top-24">
|
|
||||||
<div class="text-sm font-semibold uppercase mb-2 text-ink">Filter</div>
|
|
||||||
{/* Tag Filter */}
|
|
||||||
<div class="mb-2">
|
|
||||||
<div class="text-xs uppercase mb-1 text-ink-muted">Tags</div>
|
|
||||||
<ul class="flex flex-wrap sm:flex-col gap-1.5">
|
|
||||||
<For each={tags}>
|
|
||||||
{(tag) => (
|
|
||||||
<li>
|
|
||||||
<button onClick={() => toggleTag(tag)} class={cn("w-full px-2 py-1 rounded text-ink", "whitespace-nowrap overflow-hidden overflow-ellipsis", "flex gap-2 items-center", "border border-transparent hover:border-edge hover:bg-wash", "transition-colors duration-300 ease-in-out", filter().has(tag) && "bg-chip text-chip-ink border-chip")}>
|
|
||||||
<svg class={cn("size-5 fill-current opacity-60", "transition-colors duration-300 ease-in-out", filter().has(tag) && "opacity-100")}>
|
|
||||||
<use href={`/ui.svg#square`} class={cn(!filter().has(tag) ? "block" : "hidden")} />
|
|
||||||
<use href={`/ui.svg#square-check`} class={cn(filter().has(tag) ? "block" : "hidden")} />
|
|
||||||
</svg>
|
|
||||||
{tag}
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
)}
|
|
||||||
</For>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-span-3 sm:col-span-2">
|
|
||||||
<div class="flex flex-col">
|
|
||||||
<div class="text-sm uppercase mb-2">
|
|
||||||
SHOWING {posts().length} OF {data.length} POSTS
|
|
||||||
</div>
|
|
||||||
<ul class="flex flex-col gap-3">
|
|
||||||
<For each={posts()}>
|
|
||||||
{(post) => (
|
|
||||||
<li>
|
|
||||||
<ArrowCard entry={post} collection={'blog'} />
|
|
||||||
</li>
|
|
||||||
)}
|
|
||||||
</For>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
import { createEffect, createMemo, createSignal, onCleanup, onMount, For } from "solid-js"
|
||||||
|
import ArrowCard from "@components/ArrowCard"
|
||||||
|
import { cn } from "@lib/utils"
|
||||||
|
import {
|
||||||
|
collectTags,
|
||||||
|
filterEntries,
|
||||||
|
hasActiveFilters,
|
||||||
|
parseFilterParams,
|
||||||
|
tagCounts,
|
||||||
|
writeFilterParams,
|
||||||
|
DEFAULT_SORT,
|
||||||
|
SORT_KEYS,
|
||||||
|
SORT_LABELS,
|
||||||
|
type FilterState,
|
||||||
|
type ListEntry,
|
||||||
|
type SortKey,
|
||||||
|
} from "@lib/filters"
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
entries: ListEntry[]
|
||||||
|
collection: "blog" | "projects"
|
||||||
|
/**
|
||||||
|
* Filter state read from the incoming request URL. The island is SSR'd, so
|
||||||
|
* seeding from `window.location` would render one list on the server and a
|
||||||
|
* different one on hydration; the page passes the parsed request URL instead.
|
||||||
|
*/
|
||||||
|
initial?: FilterState
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared tag + keyword + sort filter for the /blog and /projects listings.
|
||||||
|
*
|
||||||
|
* Both islands used to be byte-identical copies of each other, which is how
|
||||||
|
* the AND-vs-OR semantics, the duplicate-case tags and the missing empty state
|
||||||
|
* ended up duplicated too. One component, one place to fix.
|
||||||
|
*/
|
||||||
|
export default function FilteredList({ entries, collection, initial }: Props) {
|
||||||
|
const [filter, setFilter] = createSignal<FilterState>(
|
||||||
|
initial ?? { tags: [], query: "", sort: DEFAULT_SORT }
|
||||||
|
)
|
||||||
|
|
||||||
|
const tags = createMemo(() => collectTags(entries))
|
||||||
|
const counts = createMemo(() => tagCounts(entries, filter()))
|
||||||
|
const visible = createMemo(() => filterEntries(entries, filter()))
|
||||||
|
const filtered = createMemo(() => hasActiveFilters(filter()))
|
||||||
|
|
||||||
|
function toggleTag(key: string) {
|
||||||
|
setFilter((prev) => ({
|
||||||
|
...prev,
|
||||||
|
tags: prev.tags.includes(key)
|
||||||
|
? prev.tags.filter((tag) => tag !== key)
|
||||||
|
: [...prev.tags, key],
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
setFilter({ tags: [], query: "", sort: DEFAULT_SORT })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mirror state into the address bar so a filtered view survives a refresh and
|
||||||
|
// can be shared, matching what the search island already does.
|
||||||
|
const syncUrl = () => {
|
||||||
|
if (typeof window === "undefined") return
|
||||||
|
const url = new URL(window.location.href)
|
||||||
|
writeFilterParams(url.searchParams, filter())
|
||||||
|
window.history.replaceState({}, "", url.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
createEffect(syncUrl)
|
||||||
|
|
||||||
|
// Restore filters when the user navigates with browser back/forward. Bound
|
||||||
|
// only in onMount: this component is SSR'd, and `window` does not exist there.
|
||||||
|
const onPopState = () =>
|
||||||
|
setFilter(parseFilterParams(new URL(window.location.href).searchParams))
|
||||||
|
|
||||||
|
let popStateBound = false
|
||||||
|
onMount(() => {
|
||||||
|
window.addEventListener("popstate", onPopState)
|
||||||
|
popStateBound = true
|
||||||
|
})
|
||||||
|
|
||||||
|
onCleanup(() => {
|
||||||
|
if (popStateBound) window.removeEventListener("popstate", onPopState)
|
||||||
|
})
|
||||||
|
|
||||||
|
const noun = collection === "blog" ? "post" : "project"
|
||||||
|
const plural = `${noun}s`
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
|
||||||
|
<div class="col-span-3 sm:col-span-1">
|
||||||
|
<div class="sticky top-24">
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<div class="text-sm font-semibold uppercase mb-2 text-ink">Filter</div>
|
||||||
|
{filtered() && (
|
||||||
|
<button
|
||||||
|
onClick={reset}
|
||||||
|
class="text-xs uppercase text-link hover:text-link-hover underline underline-offset-2 mb-2 transition-colors duration-300 ease-in-out"
|
||||||
|
>
|
||||||
|
Clear all
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label class="block text-xs uppercase mb-1 text-ink-muted" for="filter-q">
|
||||||
|
Keyword
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="filter-q"
|
||||||
|
type="search"
|
||||||
|
value={filter().query}
|
||||||
|
onInput={(e) => setFilter((prev) => ({ ...prev, query: e.currentTarget.value }))}
|
||||||
|
placeholder={`Search ${plural}…`}
|
||||||
|
autocomplete="off"
|
||||||
|
spellcheck={false}
|
||||||
|
class="w-full px-2.5 py-1.5 rounded outline-none text-ink bg-chip border border-edge focus:border-edge transition-colors duration-300 ease-in-out"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<label class="block text-xs uppercase mt-3 mb-1 text-ink-muted" for="filter-sort">
|
||||||
|
Sort
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="filter-sort"
|
||||||
|
value={filter().sort}
|
||||||
|
onChange={(e) => setFilter((prev) => ({ ...prev, sort: e.currentTarget.value as SortKey }))}
|
||||||
|
class="w-full px-2 py-1.5 rounded text-ink bg-chip border border-edge outline-none transition-colors duration-300 ease-in-out"
|
||||||
|
>
|
||||||
|
<For each={SORT_KEYS}>
|
||||||
|
{/* `selected` is set explicitly because `<select value>` has no
|
||||||
|
content attribute: SSR writes it as one, which browsers ignore,
|
||||||
|
so a deep link like ?sort=az would render the wrong option
|
||||||
|
selected until hydration. */}
|
||||||
|
{(key) => <option value={key} selected={filter().sort === key}>{SORT_LABELS[key]}</option>}
|
||||||
|
</For>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<div class="mt-3">
|
||||||
|
<div class="text-xs uppercase mb-1 text-ink-muted">Tags</div>
|
||||||
|
<ul role="group" aria-label="Filter by tag" class="flex flex-wrap sm:flex-col gap-1.5">
|
||||||
|
<For each={tags()}>
|
||||||
|
{(tag) => {
|
||||||
|
const selected = () => filter().tags.includes(tag.key)
|
||||||
|
const count = () => counts().get(tag.key) ?? 0
|
||||||
|
return (
|
||||||
|
<li>
|
||||||
|
<button
|
||||||
|
onClick={() => toggleTag(tag.key)}
|
||||||
|
aria-pressed={selected()}
|
||||||
|
class={cn(
|
||||||
|
"w-full px-2 py-1 rounded text-ink",
|
||||||
|
"whitespace-nowrap overflow-hidden overflow-ellipsis",
|
||||||
|
"flex gap-2 items-center",
|
||||||
|
"border border-transparent hover:border-edge hover:bg-wash",
|
||||||
|
"transition-colors duration-300 ease-in-out",
|
||||||
|
selected() && "bg-chip text-chip-ink border-chip",
|
||||||
|
count() === 0 && !selected() && "opacity-50"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<svg class={cn("size-5 shrink-0 fill-current opacity-60", "transition-colors duration-300 ease-in-out", selected() && "opacity-100")}>
|
||||||
|
<use href={`/ui.svg#square`} class={cn(selected() ? "hidden" : "block")} />
|
||||||
|
<use href={`/ui.svg#square-check`} class={cn(selected() ? "block" : "hidden")} />
|
||||||
|
</svg>
|
||||||
|
<span class="flex-1 text-left truncate">{tag.label}</span>
|
||||||
|
<span class="text-xs tabular-nums opacity-70">{count()}</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
</For>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="col-span-3 sm:col-span-2">
|
||||||
|
<div class="flex flex-col">
|
||||||
|
<div class="text-sm uppercase mb-2" aria-live="polite">
|
||||||
|
SHOWING {visible().length} OF {entries.length} {plural.toUpperCase()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{visible().length === 0 ? (
|
||||||
|
<div class="p-4 border border-edge rounded-lg bg-surface">
|
||||||
|
<div class="font-semibold text-ink">No {plural} match these filters.</div>
|
||||||
|
<div class="text-sm text-ink-muted mt-1">
|
||||||
|
Tags are combined with OR, so a keyword that excludes everything is the usual
|
||||||
|
culprit. Try shortening the keyword or clearing the filters.
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={reset}
|
||||||
|
class="mt-3 px-2 py-1 rounded text-ink border border-edge hover:bg-wash transition-colors duration-300 ease-in-out"
|
||||||
|
>
|
||||||
|
Clear filters
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul class="flex flex-col gap-3">
|
||||||
|
<For each={visible()}>
|
||||||
|
{(entry) => (
|
||||||
|
<li>
|
||||||
|
<ArrowCard entry={entry} collection={collection} />
|
||||||
|
</li>
|
||||||
|
)}
|
||||||
|
</For>
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
import { SITE, SOCIALS } from "@consts"
|
import { SITE, SOCIALS } from "@consts"
|
||||||
import Container from "@components/Container.astro"
|
import Container from "@components/Container.astro"
|
||||||
import SystemStatus from "@components/SystemStatus.astro"
|
import SystemStatus from "@components/SystemStatus.astro"
|
||||||
|
import { mediaUrl, mediaFallback } from "@lib/media"
|
||||||
import { getSystemStatus } from "@lib/status"
|
import { getSystemStatus } from "@lib/status"
|
||||||
|
|
||||||
// Rendered server-side so the light is correct in the first paint (and with JS
|
// Rendered server-side so the light is correct in the first paint (and with JS
|
||||||
@@ -32,7 +33,7 @@ const statusSnapshot = await getSystemStatus()
|
|||||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||||
<div class="flex flex-col items-center sm:items-start">
|
<div class="flex flex-col items-center sm:items-start">
|
||||||
<a href="/" class="flex gap-1 w-fit font-semibold text-ink transition-colors duration-300 ease-in-out hover:text-link">
|
<a href="/" class="flex gap-1 w-fit font-semibold text-ink transition-colors duration-300 ease-in-out hover:text-link">
|
||||||
<img src="/images/logo.png" alt="Logo" class="size-6" />
|
<img src={mediaUrl("logo.png")} alt="Logo" class="size-6" onerror={mediaFallback("/images/logo.png")} />
|
||||||
{SITE.TITLE}
|
{SITE.TITLE}
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
---
|
---
|
||||||
import { SITE, LINKS, RESUME } from "@consts"
|
import { SITE, LINKS, RESUME } from "@consts"
|
||||||
import { cn, ACTIVE_NAV_COLORS, isNavActive } from "@lib/utils"
|
import { cn, ACTIVE_NAV_COLORS, isNavActive } from "@lib/utils"
|
||||||
|
import { mediaUrl, mediaFallback } from "@lib/media"
|
||||||
import Container from "@components/Container.astro"
|
import Container from "@components/Container.astro"
|
||||||
const { pathname } = Astro.url
|
const { pathname } = Astro.url
|
||||||
---
|
---
|
||||||
@@ -14,7 +15,7 @@ const { pathname } = Astro.url
|
|||||||
<div class="relative h-full w-full">
|
<div class="relative h-full w-full">
|
||||||
<div class="absolute left-0 top-1/2 -translate-y-1/2 flex gap-1 font-semibold">
|
<div class="absolute left-0 top-1/2 -translate-y-1/2 flex gap-1 font-semibold">
|
||||||
<a href="/" class="flex gap-1 text-ink transition-colors duration-300 ease-in-out hover:text-link">
|
<a href="/" class="flex gap-1 text-ink transition-colors duration-300 ease-in-out hover:text-link">
|
||||||
<img src='/images/logo.png' alt="Logo" class="size-6" />
|
<img src={mediaUrl("logo.png")} alt="Logo" class="size-6" onerror={mediaFallback("/images/logo.png")} />
|
||||||
<div>
|
<div>
|
||||||
{SITE.TITLE}
|
{SITE.TITLE}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
import type { Project } from "@lib/types"
|
|
||||||
import { createMemo, createSignal, For } from "solid-js"
|
|
||||||
import ArrowCard from "@components/ArrowCard"
|
|
||||||
import { cn } from "@lib/utils"
|
|
||||||
import { filterByTags } from "@lib/content"
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
tags: string[]
|
|
||||||
data: Project[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Projects({ data, tags }: Props) {
|
|
||||||
const [filter, setFilter] = createSignal(new Set<string>())
|
|
||||||
|
|
||||||
// See Blog.tsx: a memo (not an effect writing a signal) so the list is populated
|
|
||||||
// in the server-rendered HTML and survives a failed hydration.
|
|
||||||
const projects = createMemo<Project[]>(() => filterByTags(data, filter()))
|
|
||||||
|
|
||||||
function toggleTag(tag: string) {
|
|
||||||
setFilter((prev) =>
|
|
||||||
new Set(prev.has(tag)
|
|
||||||
? [...prev].filter((t) => t !== tag)
|
|
||||||
: [...prev, tag]
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
|
|
||||||
<div class="col-span-3 sm:col-span-1">
|
|
||||||
<div class="sticky top-24">
|
|
||||||
<div class="text-sm font-semibold uppercase mb-2 text-ink">Filter</div>
|
|
||||||
<ul class="flex flex-wrap sm:flex-col gap-1.5">
|
|
||||||
<For each={tags}>
|
|
||||||
{(tag) => (
|
|
||||||
<li>
|
|
||||||
<button onClick={() => toggleTag(tag)} class={cn("w-full px-2 py-1 rounded text-ink", "whitespace-nowrap overflow-hidden overflow-ellipsis", "flex gap-2 items-center", "border border-transparent hover:border-edge hover:bg-wash", "transition-colors duration-300 ease-in-out", filter().has(tag) && "bg-chip text-chip-ink border-chip")}>
|
|
||||||
<svg class={cn("size-5 fill-current opacity-60", "transition-colors duration-300 ease-in-out", filter().has(tag) && "opacity-100")}>
|
|
||||||
<use href={`/ui.svg#square`} class={cn(!filter().has(tag) ? "block" : "hidden")} />
|
|
||||||
<use href={`/ui.svg#square-check`} class={cn(filter().has(tag) ? "block" : "hidden")} />
|
|
||||||
</svg>
|
|
||||||
{tag}
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
)}
|
|
||||||
</For>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-span-3 sm:col-span-2">
|
|
||||||
<div class="flex flex-col">
|
|
||||||
<div class="text-sm uppercase mb-2">
|
|
||||||
SHOWING {projects().length} OF {data.length} PROJECTS
|
|
||||||
</div>
|
|
||||||
<ul class="flex flex-col gap-3">
|
|
||||||
<For each={projects()}>
|
|
||||||
{(project) => (
|
|
||||||
<li>
|
|
||||||
<ArrowCard entry={project} collection={'projects'} />
|
|
||||||
</li>
|
|
||||||
)}
|
|
||||||
</For>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,83 +1,153 @@
|
|||||||
// src/components/__tests__/list-islands.test.ts
|
// src/components/__tests__/list-islands.test.ts
|
||||||
import { describe, it, expect } from "vitest"
|
import { describe, it, expect } from "vitest"
|
||||||
import { renderToString } from "solid-js/web"
|
import { renderToString } from "solid-js/web"
|
||||||
import Blog from "@components/Blog"
|
import FilteredList from "@components/FilteredList"
|
||||||
import Projects from "@components/Projects"
|
import type { FilterState, ListEntry } from "@lib/filters"
|
||||||
import type { BlogPost, Project } from "@lib/types"
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* These render the islands through solid-js/web's server renderer, which is
|
* Renders the shared listing island through solid-js/web's server renderer,
|
||||||
* the same path Astro takes for `output: "server"` + `client:load`. That is
|
* which is the same path Astro takes for `output: "server"` + `client:load`.
|
||||||
* the point: the regression being locked in here is that the filtered list
|
*
|
||||||
* must exist in the SERVER HTML. The old `createEffect` + signal version
|
* The regression locked in here is that the list must exist in the SERVER HTML:
|
||||||
* rendered "SHOWING 0 OF 3" with an empty <ul> because effects never run
|
* the original `createEffect` + signal version rendered "SHOWING 0 OF 3" with an
|
||||||
* during SSR, so any island/hydration failure hid every post.
|
* empty <ul>, so any hydration failure hid every entry. The second regression is
|
||||||
|
* the case-duplicated tag list, which made /blog and /projects render two
|
||||||
|
* checkboxes that did exactly the same thing.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function post(id: string, tags: string[]): BlogPost {
|
function entry(id: string, tags: string[], overrides: Partial<ListEntry> = {}): ListEntry {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
title: `Post ${id}`,
|
title: `Entry ${id}`,
|
||||||
summary: `Summary ${id}`,
|
summary: `Summary ${id}`,
|
||||||
date: "2026-01-01T00:00:00.000Z",
|
date: "2026-01-01T00:00:00.000Z",
|
||||||
tags,
|
tags,
|
||||||
draft: false,
|
...overrides,
|
||||||
content: "",
|
|
||||||
template: "default",
|
|
||||||
featured: false,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function project(id: string, tags: string[]): Project {
|
const posts: ListEntry[] = [
|
||||||
return {
|
entry("a", ["CSS", "Html"], { title: "Alpha", date: "2025-01-01T00:00:00.000Z" }),
|
||||||
id,
|
entry("b", ["CSS", "css"], { title: "Bravo", date: "2026-01-01T00:00:00.000Z" }),
|
||||||
title: `Project ${id}`,
|
entry("c", ["html"], { title: "Charlie", date: "2025-06-01T00:00:00.000Z" }),
|
||||||
summary: `Summary ${id}`,
|
]
|
||||||
date: "2026-01-01T00:00:00.000Z",
|
|
||||||
tags,
|
/**
|
||||||
draft: false,
|
* Solid's SSR output interleaves hydration markers around every dynamic value
|
||||||
content: "",
|
* (`SHOWING <!--$-->3<!--/--> OF …`). Stripping comments keeps the assertions
|
||||||
}
|
* about real content instead of about marker placement.
|
||||||
|
*/
|
||||||
|
function render(props: {
|
||||||
|
entries?: ListEntry[]
|
||||||
|
collection?: "blog" | "projects"
|
||||||
|
initial?: FilterState
|
||||||
|
}): string {
|
||||||
|
const html = renderToString(() =>
|
||||||
|
FilteredList({
|
||||||
|
entries: props.entries ?? posts,
|
||||||
|
collection: props.collection ?? "blog",
|
||||||
|
initial: props.initial,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
return html.replace(/<!--.*?-->/g, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("Blog island (SSR render)", () => {
|
describe("FilteredList island (SSR render)", () => {
|
||||||
const data = [post("a", ["css", "html"]), post("b", ["css"]), post("c", ["html"])]
|
it("should render every entry in the server HTML with no filter applied", () => {
|
||||||
|
const html = render({})
|
||||||
|
|
||||||
it("should render every post in the server HTML with no filter applied", () => {
|
expect(html).toContain("SHOWING 3 OF 3 POSTS")
|
||||||
const html = renderToString(() => Blog({ data, tags: ["css", "html"] }))
|
for (const item of posts) {
|
||||||
|
expect(html).toContain(`href="/blog/${item.id}"`)
|
||||||
expect(html).toContain("SHOWING <!--$-->3<!--/--> OF <!--$-->3<!--/--> POSTS")
|
|
||||||
for (const entry of data) {
|
|
||||||
expect(html).toContain(`href="/blog/${entry.id}"`)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
it("should not regress to an empty list when the filter signal is untouched", () => {
|
it("should not regress to an empty list when no initial state is passed", () => {
|
||||||
// Guards the createEffect bug specifically: an empty filter must still show all.
|
// Guards the createEffect bug specifically: an untouched filter must show all.
|
||||||
const html = renderToString(() => Blog({ data, tags: [] }))
|
expect(render({})).not.toContain("SHOWING 0")
|
||||||
expect(html).not.toContain("SHOWING <!--$-->0")
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it("should render the tag filter buttons server-side", () => {
|
it("should apply initial state server-side so a filtered deep link renders filtered", () => {
|
||||||
const html = renderToString(() => Blog({ data, tags: ["css", "html"] }))
|
const html = render({ initial: { tags: ["css"], query: "", sort: "newest" } })
|
||||||
expect(html).toContain(">css<!--/--></button>")
|
|
||||||
expect(html).toContain(">html<!--/--></button>")
|
expect(html).toContain("SHOWING 2 OF 3 POSTS")
|
||||||
|
expect(html).toContain('href="/blog/a"')
|
||||||
|
expect(html).toContain('href="/blog/b"')
|
||||||
|
expect(html).not.toContain('href="/blog/c"')
|
||||||
})
|
})
|
||||||
})
|
|
||||||
|
|
||||||
describe("Projects island (SSR render)", () => {
|
it("should render one checkbox per tag, deduped across spellings", () => {
|
||||||
const data = [project("x", ["react"]), project("y", ["react", "rust"])]
|
// `CSS`/`css` and `html`/`Html` collapse to two options, not four.
|
||||||
|
const html = render({})
|
||||||
|
|
||||||
it("should render every project in the server HTML", () => {
|
expect(html).toContain(">CSS</span>")
|
||||||
const html = renderToString(() => Projects({ data, tags: ["react", "rust"] }))
|
expect(html).toContain(">Html</span>")
|
||||||
|
expect(html.match(/aria-pressed/g)).toHaveLength(2)
|
||||||
|
})
|
||||||
|
|
||||||
expect(html).toContain("SHOWING <!--$-->2<!--/--> OF <!--$-->2<!--/--> PROJECTS")
|
it("should show a per-tag count next to each option", () => {
|
||||||
|
// css -> a, b; html -> a, c. Assert on the rendered counts rather than on
|
||||||
|
// the exact class string so the test survives a restyle.
|
||||||
|
const html = render({})
|
||||||
|
const counts = [...html.matchAll(/<\/span><span[^>]*>(\d+)<\/span>/g)].map((m) => m[1])
|
||||||
|
|
||||||
|
expect(counts).toHaveLength(2)
|
||||||
|
expect(counts.every((count) => count === "2")).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should render the keyword input, sort select and live count region", () => {
|
||||||
|
const html = render({})
|
||||||
|
|
||||||
|
expect(html).toContain('id="filter-q"')
|
||||||
|
expect(html).toContain('id="filter-sort"')
|
||||||
|
expect(html).toContain('aria-live="polite"')
|
||||||
|
expect(html).toContain('role="group"')
|
||||||
|
expect(html).toContain("Newest first")
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should sort by the requested key in the server HTML", () => {
|
||||||
|
const html = render({ initial: { tags: [], query: "", sort: "az" } })
|
||||||
|
expect(html.indexOf('href="/blog/a"')).toBeLessThan(html.indexOf('href="/blog/b"'))
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should render an empty state instead of a blank list when nothing matches", () => {
|
||||||
|
const html = render({ initial: { tags: [], query: "zzzz", sort: "newest" } })
|
||||||
|
|
||||||
|
expect(html).toContain("SHOWING 0 OF 3 POSTS")
|
||||||
|
expect(html).toContain("No posts match these filters.")
|
||||||
|
expect(html).toContain("Clear filters")
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should offer Clear all only once a filter is active", () => {
|
||||||
|
expect(render({})).not.toContain("Clear all")
|
||||||
|
expect(render({ initial: { tags: ["css"], query: "", sort: "newest" } })).toContain("Clear all")
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should label the count PROJECTS for the projects collection", () => {
|
||||||
|
const html = render({
|
||||||
|
entries: [entry("x", ["react"]), entry("y", ["react", "rust"])],
|
||||||
|
collection: "projects",
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(html).toContain("SHOWING 2 OF 2 PROJECTS")
|
||||||
expect(html).toContain('href="/projects/x"')
|
expect(html).toContain('href="/projects/x"')
|
||||||
expect(html).toContain('href="/projects/y"')
|
expect(html).toContain('href="/projects/y"')
|
||||||
})
|
})
|
||||||
|
|
||||||
it("should tolerate entries without optional demoUrl/repoUrl", () => {
|
it("should render an empty collection without throwing", () => {
|
||||||
// The content schema marks both optional; the memo must not throw on SSR.
|
// A collection where every entry is still a draft: no tags to list, nothing
|
||||||
expect(() => renderToString(() => Projects({ data, tags: [] }))).not.toThrow()
|
// to show, and the empty state must carry the panel.
|
||||||
|
const html = render({ entries: [] })
|
||||||
|
|
||||||
|
expect(html).toContain("SHOWING 0 OF 0 POSTS")
|
||||||
|
expect(html).toContain("No posts match these filters.")
|
||||||
|
expect(html.match(/aria-pressed/g)).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should render entries that carry no tags at all", () => {
|
||||||
|
const html = render({ entries: [entry("solo", [])] })
|
||||||
|
|
||||||
|
expect(html).toContain("SHOWING 1 OF 1 POSTS")
|
||||||
|
expect(html).toContain('href="/blog/solo"')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
// src/lib/__tests__/appwrite.test.ts
|
||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* node-appwrite's Client captures its own fetch binding, so stubbing
|
||||||
|
* globalThis.fetch does not intercept it (a previous version of this file
|
||||||
|
* silently hit the live Appwrite). Instead the SDK is mocked at the module
|
||||||
|
* boundary: listRows/getRow become vi.fn()s returning the exact JSON shapes
|
||||||
|
* the tablesdb endpoints return (verified against the live instance), and the
|
||||||
|
* mapping, rendering, caching and fallback behavior under test is all ours.
|
||||||
|
* The wire contract itself is covered by scripts/appwrite-migrate.mjs and the
|
||||||
|
* live probes documented in the migration thread.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const listRows = vi.fn()
|
||||||
|
const getRow = vi.fn()
|
||||||
|
|
||||||
|
vi.mock("node-appwrite", () => {
|
||||||
|
class AppwriteException extends Error {
|
||||||
|
code: number
|
||||||
|
type: string
|
||||||
|
constructor(message: string, code = 0, type = "") {
|
||||||
|
super(message)
|
||||||
|
this.code = code
|
||||||
|
this.type = type
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
AppwriteException,
|
||||||
|
Client: class {
|
||||||
|
setEndpoint() { return this }
|
||||||
|
setProject() { return this }
|
||||||
|
setKey() { return this }
|
||||||
|
},
|
||||||
|
TablesDB: class {
|
||||||
|
listRows = listRows
|
||||||
|
getRow = getRow
|
||||||
|
},
|
||||||
|
Query: {
|
||||||
|
// Record the (attribute, op) pairs so tests can assert the queries we
|
||||||
|
// compose without coupling to the SDK's JSON encoding.
|
||||||
|
equal: (attribute: string, values: unknown) => ({ op: "equal", attribute, values }),
|
||||||
|
orderDesc: (attribute: string) => ({ op: "orderDesc", attribute }),
|
||||||
|
limit: (values: unknown) => ({ op: "limit", values }),
|
||||||
|
select: (values: unknown) => ({ op: "select", values }),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const {
|
||||||
|
listContent,
|
||||||
|
listSlim,
|
||||||
|
getContent,
|
||||||
|
listSearchEntries,
|
||||||
|
__resetCache,
|
||||||
|
} = await import("@lib/appwrite")
|
||||||
|
|
||||||
|
type FakeRow = Record<string, unknown> & { $id: string }
|
||||||
|
|
||||||
|
const BLOG_ROW: FakeRow = {
|
||||||
|
$id: "01-building-my-personal-website",
|
||||||
|
$sequence: "1",
|
||||||
|
$tableId: "blog",
|
||||||
|
$databaseId: "spaghet-home",
|
||||||
|
slug: "01-building-my-personal-website",
|
||||||
|
title: "Building My Personal Website",
|
||||||
|
summary: "A journey through creating my portfolio.",
|
||||||
|
// Exactly what a datetime column returns over the wire.
|
||||||
|
date: "2025-08-12T00:00:00.000+00:00",
|
||||||
|
tags: ["Astro", "Docker"],
|
||||||
|
draft: false,
|
||||||
|
template: "default",
|
||||||
|
featured: false,
|
||||||
|
content: "## The Concept\n\nSome **markdown** body.",
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
__resetCache()
|
||||||
|
listRows.mockReset()
|
||||||
|
getRow.mockReset()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("listContent", () => {
|
||||||
|
it("maps rows into the astro:content entry shape with rendered HTML", async () => {
|
||||||
|
listRows.mockResolvedValue({ total: 1, rows: [BLOG_ROW] })
|
||||||
|
const entries = await listContent("blog")
|
||||||
|
expect(entries).toHaveLength(1)
|
||||||
|
const entry = entries[0]
|
||||||
|
// Flat fields (what the article layouts read) plus `data` (PageLayout).
|
||||||
|
expect(entry.id).toBe("01-building-my-personal-website")
|
||||||
|
expect(entry.title).toBe("Building My Personal Website")
|
||||||
|
expect(entry.date).toBeInstanceOf(Date)
|
||||||
|
expect(entry.date.toISOString()).toBe("2025-08-12T00:00:00.000Z")
|
||||||
|
expect(entry.tags).toEqual(["Astro", "Docker"])
|
||||||
|
expect(entry.draft).toBe(false)
|
||||||
|
expect(entry.data.title).toBe("Building My Personal Website")
|
||||||
|
// content is rendered HTML, not raw markdown.
|
||||||
|
expect(entry.content).toContain("<h2")
|
||||||
|
expect(entry.content).toContain("<strong>markdown</strong>")
|
||||||
|
expect(entry.data.content).toBe(entry.content)
|
||||||
|
// The list query excludes drafts and orders newest-first on the date column.
|
||||||
|
const queries = listRows.mock.calls[0][0].queries as { op: string; attribute?: string }[]
|
||||||
|
expect(queries.some((q) => q.op === "equal" && q.attribute === "draft")).toBe(true)
|
||||||
|
expect(queries.some((q) => q.op === "orderDesc" && q.attribute === "date")).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("work rows map company/role/dateStart/dateEnd", async () => {
|
||||||
|
listRows.mockResolvedValue({
|
||||||
|
total: 1,
|
||||||
|
rows: [{
|
||||||
|
$id: "09-chaplain-assistant",
|
||||||
|
slug: "09-chaplain-assistant",
|
||||||
|
company: "National Guard Bureau",
|
||||||
|
role: "Chaplain Assistant",
|
||||||
|
dateStart: "2007-12-01T00:00:00.000+00:00",
|
||||||
|
dateEnd: "2012-12-01T00:00:00.000+00:00",
|
||||||
|
content: "Body",
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
const [entry] = await listContent("work")
|
||||||
|
expect(entry.company).toBe("National Guard Bureau")
|
||||||
|
expect(entry.dateStart).toBeInstanceOf(Date)
|
||||||
|
// work has no draft column; querying one would error.
|
||||||
|
const queries = listRows.mock.calls[0][0].queries as { op: string; attribute?: string }[]
|
||||||
|
expect(queries.some((q) => q.attribute === "draft")).toBe(false)
|
||||||
|
expect(queries.some((q) => q.op === "orderDesc" && q.attribute === "dateStart")).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("caches within the TTL: a second call makes no request", async () => {
|
||||||
|
listRows.mockResolvedValue({ total: 1, rows: [BLOG_ROW] })
|
||||||
|
const first = await listContent("blog")
|
||||||
|
await listContent("blog")
|
||||||
|
expect(listRows).toHaveBeenCalledTimes(1)
|
||||||
|
expect(first).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("serves the stale cache when a refresh fails", async () => {
|
||||||
|
listRows.mockResolvedValue({ total: 1, rows: [BLOG_ROW] })
|
||||||
|
const first = await listContent("blog")
|
||||||
|
// Expire the entry by moving the clock past the default 60s TTL, then fail
|
||||||
|
// the refresh.
|
||||||
|
vi.useFakeTimers()
|
||||||
|
vi.setSystemTime(Date.now() + 61_000)
|
||||||
|
listRows.mockRejectedValue(new TypeError("fetch failed"))
|
||||||
|
const second = await listContent("blog")
|
||||||
|
vi.useRealTimers()
|
||||||
|
expect(second).toHaveLength(1)
|
||||||
|
expect(second[0].id).toBe(first[0].id)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("throws when the cache is cold and Appwrite is down (caller falls back)", async () => {
|
||||||
|
listRows.mockRejectedValue(new TypeError("fetch failed"))
|
||||||
|
await expect(listContent("blog")).rejects.toThrow("fetch failed")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("getContent", () => {
|
||||||
|
it("returns the entry for a published slug", async () => {
|
||||||
|
getRow.mockResolvedValue(BLOG_ROW)
|
||||||
|
const entry = await getContent("blog", "01-building-my-personal-website")
|
||||||
|
expect(entry?.title).toBe("Building My Personal Website")
|
||||||
|
expect(entry?.content).toContain("<h2")
|
||||||
|
expect(getRow.mock.calls[0][0]).toMatchObject({
|
||||||
|
databaseId: "spaghet-home",
|
||||||
|
tableId: "blog",
|
||||||
|
rowId: "01-building-my-personal-website",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it("returns null on 404", async () => {
|
||||||
|
const { AppwriteException } = await import("node-appwrite")
|
||||||
|
getRow.mockRejectedValue(new AppwriteException("not found", 404, "row_not_found"))
|
||||||
|
expect(await getContent("blog", "nope")).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it("rethrows non-404 failures so the caller can fall back", async () => {
|
||||||
|
const { AppwriteException } = await import("node-appwrite")
|
||||||
|
getRow.mockRejectedValue(new AppwriteException("server error", 500))
|
||||||
|
await expect(getContent("blog", "x")).rejects.toThrow("server error")
|
||||||
|
})
|
||||||
|
|
||||||
|
it("returns null for a draft even when the row exists", async () => {
|
||||||
|
getRow.mockResolvedValue({ ...BLOG_ROW, draft: true })
|
||||||
|
expect(await getContent("blog", "01-building-my-personal-website")).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("listSlim", () => {
|
||||||
|
it("selects only the listing columns and keeps Date objects", async () => {
|
||||||
|
listRows.mockResolvedValue({ total: 1, rows: [{ ...BLOG_ROW, content: undefined }] })
|
||||||
|
const slim = await listSlim("blog")
|
||||||
|
const queries = listRows.mock.calls[0][0].queries as { op: string; values?: string[] }[]
|
||||||
|
const select = queries.find((q) => q.op === "select")
|
||||||
|
expect(select?.values).toContain("title")
|
||||||
|
expect(select?.values).not.toContain("content")
|
||||||
|
expect(slim[0].data.date).toBeInstanceOf(Date)
|
||||||
|
expect(slim[0].data.tags).toEqual(["Astro", "Docker"])
|
||||||
|
expect(slim[0].id).toBe(BLOG_ROW.$id)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("listSearchEntries", () => {
|
||||||
|
it("merges blog and projects with ISO dates and collection tags", async () => {
|
||||||
|
listRows.mockImplementation(({ tableId }: { tableId: string }) =>
|
||||||
|
Promise.resolve({
|
||||||
|
total: 1,
|
||||||
|
rows: [tableId === "blog"
|
||||||
|
? BLOG_ROW
|
||||||
|
: { ...BLOG_ROW, $id: "gitea", slug: "gitea", title: "Gitea" }],
|
||||||
|
})
|
||||||
|
)
|
||||||
|
const entries = await listSearchEntries()
|
||||||
|
expect(entries.map((e) => e.collection)).toEqual(["blog", "projects"])
|
||||||
|
expect(entries[0].date).toBe("2025-08-12T00:00:00.000Z")
|
||||||
|
expect(entries[1].slug).toBe("gitea")
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// src/lib/__tests__/content.test.ts
|
// src/lib/__tests__/content.test.ts
|
||||||
import { describe, it, expect } from "vitest"
|
import { describe, it, expect } from "vitest"
|
||||||
import { byDateDesc, filterByTags } from "../content"
|
import { byDateDesc } from "../content"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fixture factory rather than inline literals in every test: mirrors the shape
|
* Fixture factory rather than inline literals in every test: mirrors the shape
|
||||||
@@ -65,35 +65,3 @@ describe("byDateDesc", () => {
|
|||||||
expect(([] as ReturnType<typeof dated>[]).sort(byDateDesc)).toEqual([])
|
expect(([] as ReturnType<typeof dated>[]).sort(byDateDesc)).toEqual([])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("filterByTags", () => {
|
|
||||||
const tagged = (id: string, tags: string[]) => ({ id, tags })
|
|
||||||
const entries = [
|
|
||||||
tagged("css-html", ["CSS", "html"]),
|
|
||||||
tagged("css-only", ["css"]),
|
|
||||||
tagged("html-only", ["Html"]),
|
|
||||||
]
|
|
||||||
|
|
||||||
it("should return everything when no tags are selected", () => {
|
|
||||||
expect(filterByTags(entries, []).map((e) => e.id)).toEqual([
|
|
||||||
"css-html",
|
|
||||||
"css-only",
|
|
||||||
"html-only",
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
it("should match tags case-insensitively on both sides", () => {
|
|
||||||
expect(filterByTags(entries, ["CSS"]).map((e) => e.id)).toEqual(["css-html", "css-only"])
|
|
||||||
expect(filterByTags(entries, ["hTmL"]).map((e) => e.id)).toEqual(["css-html", "html-only"])
|
|
||||||
})
|
|
||||||
|
|
||||||
it("should AND selected tags, narrowing rather than unioning", () => {
|
|
||||||
// Deliberate behavior, not an accident: selecting two tags keeps only entries
|
|
||||||
// carrying both, which is why most multi-tag selections return few results.
|
|
||||||
expect(filterByTags(entries, ["css", "html"]).map((e) => e.id)).toEqual(["css-html"])
|
|
||||||
})
|
|
||||||
|
|
||||||
it("should return nothing for an unselected tag", () => {
|
|
||||||
expect(filterByTags(entries, ["rust"])).toEqual([])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
// src/lib/__tests__/filters.test.ts
|
||||||
|
import { describe, it, expect } from "vitest"
|
||||||
|
import {
|
||||||
|
collectTags,
|
||||||
|
filterEntries,
|
||||||
|
hasActiveFilters,
|
||||||
|
matchesQuery,
|
||||||
|
normalizeTag,
|
||||||
|
parseFilterParams,
|
||||||
|
sortEntries,
|
||||||
|
tagCounts,
|
||||||
|
writeFilterParams,
|
||||||
|
DEFAULT_SORT,
|
||||||
|
type FilterState,
|
||||||
|
type ListEntry,
|
||||||
|
} from "../filters"
|
||||||
|
|
||||||
|
/** Mirrors the fields the listing island receives, without Astro's virtual module. */
|
||||||
|
function entry(
|
||||||
|
id: string,
|
||||||
|
tags: string[],
|
||||||
|
overrides: Partial<ListEntry> = {}
|
||||||
|
): ListEntry {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
title: `Entry ${id}`,
|
||||||
|
summary: `Summary ${id}`,
|
||||||
|
date: "2026-01-01T00:00:00.000Z",
|
||||||
|
tags,
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function state(overrides: Partial<FilterState> = {}): FilterState {
|
||||||
|
return { tags: [], query: "", sort: DEFAULT_SORT, ...overrides }
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("normalizeTag", () => {
|
||||||
|
it("should case-fold and trim", () => {
|
||||||
|
expect(normalizeTag(" Tailwind CSS ")).toBe("tailwind css")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("collectTags", () => {
|
||||||
|
it("should collapse tags that differ only by case into one option", () => {
|
||||||
|
// The real bug: /projects carries both `Astro` and `astro` in frontmatter,
|
||||||
|
// so the sidebar rendered two checkboxes that did the same thing.
|
||||||
|
const tags = collectTags([
|
||||||
|
entry("a", ["Astro", "React"]),
|
||||||
|
entry("b", ["astro", "Tailwind CSS"]),
|
||||||
|
])
|
||||||
|
|
||||||
|
expect(tags.map((tag) => tag.key)).toEqual(["astro", "react", "tailwind css"])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should pick the most frequent spelling as the label", () => {
|
||||||
|
const tags = collectTags([
|
||||||
|
entry("a", ["astro"]),
|
||||||
|
entry("b", ["Astro"]),
|
||||||
|
entry("c", ["Astro"]),
|
||||||
|
])
|
||||||
|
|
||||||
|
expect(tags).toEqual([{ key: "astro", label: "Astro" }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should keep the first-seen spelling when the counts tie", () => {
|
||||||
|
const first = collectTags([entry("a", ["Docker"]), entry("b", ["docker"])])
|
||||||
|
const second = collectTags([entry("a", ["docker"]), entry("b", ["Docker"])])
|
||||||
|
|
||||||
|
expect(first).toEqual([{ key: "docker", label: "Docker" }])
|
||||||
|
expect(second).toEqual([{ key: "docker", label: "docker" }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should sort options alphabetically and drop blanks", () => {
|
||||||
|
const tags = collectTags([entry("a", ["zeta", "", " ", "alpha"])])
|
||||||
|
expect(tags.map((tag) => tag.label)).toEqual(["alpha", "zeta"])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should return nothing for an empty collection", () => {
|
||||||
|
expect(collectTags([])).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("matchesQuery", () => {
|
||||||
|
const post = entry("k", ["Docker"], {
|
||||||
|
title: "Home Server",
|
||||||
|
summary: "Unraid and backups",
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should match everything on an empty or whitespace query", () => {
|
||||||
|
expect(matchesQuery(post, "")).toBe(true)
|
||||||
|
expect(matchesQuery(post, " ")).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should match title, summary and tags case-insensitively", () => {
|
||||||
|
expect(matchesQuery(post, "SERVER")).toBe(true)
|
||||||
|
expect(matchesQuery(post, "backups")).toBe(true)
|
||||||
|
expect(matchesQuery(post, "docKer")).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should not match the body, which is not part of the shape", () => {
|
||||||
|
expect(matchesQuery(post, "nope")).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("filterEntries", () => {
|
||||||
|
const entries = [
|
||||||
|
entry("css-html", ["CSS", "html"]),
|
||||||
|
entry("css-only", ["css"]),
|
||||||
|
entry("html-only", ["Html"]),
|
||||||
|
entry("rust-only", ["rust"]),
|
||||||
|
]
|
||||||
|
|
||||||
|
it("should return everything when nothing is selected", () => {
|
||||||
|
expect(filterEntries(entries, state()).map((e) => e.id)).toEqual([
|
||||||
|
"css-html",
|
||||||
|
"css-only",
|
||||||
|
"html-only",
|
||||||
|
"rust-only",
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should OR selected tags, broadening rather than narrowing", () => {
|
||||||
|
// Deliberate change from the old AND behavior: clicking a second tag adds
|
||||||
|
// results, which is what a checkbox list looks like it does.
|
||||||
|
expect(filterEntries(entries, state({ tags: ["css", "html"] })).map((e) => e.id)).toEqual([
|
||||||
|
"css-html",
|
||||||
|
"css-only",
|
||||||
|
"html-only",
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should match selected tags case-insensitively on both sides", () => {
|
||||||
|
expect(filterEntries(entries, state({ tags: ["CsS"] })).map((e) => e.id)).toEqual([
|
||||||
|
"css-html",
|
||||||
|
"css-only",
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should intersect the keyword filter with the tag filter", () => {
|
||||||
|
const result = filterEntries(entries, state({ tags: ["css", "rust"], query: "html" }))
|
||||||
|
expect(result.map((e) => e.id)).toEqual(["css-html"])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should return nothing for a tag nobody carries", () => {
|
||||||
|
expect(filterEntries(entries, state({ tags: ["go"] }))).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should not throw when an entry is missing tags", () => {
|
||||||
|
const loose = [{ ...entry("a", []), tags: undefined }] as unknown as ListEntry[]
|
||||||
|
expect(() => filterEntries(loose, state({ tags: ["css"] }))).not.toThrow()
|
||||||
|
expect(collectTags(loose)).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("sortEntries", () => {
|
||||||
|
const entries = [
|
||||||
|
entry("old", [], { date: "2025-01-01T00:00:00.000Z", title: "Bravo" }),
|
||||||
|
entry("new", [], { date: "2026-01-01T00:00:00.000Z", title: "alpha" }),
|
||||||
|
entry("mid", [], { date: "2025-06-01T00:00:00.000Z", title: "Charlie" }),
|
||||||
|
]
|
||||||
|
|
||||||
|
it("should sort newest first by default", () => {
|
||||||
|
expect(sortEntries(entries, "newest").map((e) => e.id)).toEqual(["new", "mid", "old"])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should sort oldest first", () => {
|
||||||
|
expect(sortEntries(entries, "oldest").map((e) => e.id)).toEqual(["old", "mid", "new"])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should sort by title case-insensitively", () => {
|
||||||
|
expect(sortEntries(entries, "az").map((e) => e.title)).toEqual(["alpha", "Bravo", "Charlie"])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should not mutate the caller's array", () => {
|
||||||
|
const original = entries.map((e) => e.id)
|
||||||
|
sortEntries(entries, "oldest")
|
||||||
|
expect(entries.map((e) => e.id)).toEqual(original)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should tolerate an unparseable date without throwing", () => {
|
||||||
|
const broken = [entry("a", [], { date: "not-a-date" }), entry("b", [], { date: "2026-01-01T00:00:00.000Z" })]
|
||||||
|
expect(() => sortEntries(broken, "newest")).not.toThrow()
|
||||||
|
expect(sortEntries(broken, "newest").map((e) => e.id)).toEqual(["b", "a"])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("tagCounts", () => {
|
||||||
|
const entries = [
|
||||||
|
entry("a", ["Docker", "Astro"]),
|
||||||
|
entry("b", ["docker"]),
|
||||||
|
entry("c", ["Rust"]),
|
||||||
|
]
|
||||||
|
|
||||||
|
it("should count each tag once per entry", () => {
|
||||||
|
expect(tagCounts(entries, state()).get("docker")).toBe(2)
|
||||||
|
expect(tagCounts(entries, state()).get("astro")).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should count within the keyword filter", () => {
|
||||||
|
const counts = tagCounts(entries, state({ query: "Entry c" }))
|
||||||
|
expect(counts.get("rust")).toBe(1)
|
||||||
|
expect(counts.get("docker")).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should not count a tag twice when an entry spells it two ways", () => {
|
||||||
|
const counts = tagCounts([entry("a", ["Astro", "astro"])], state())
|
||||||
|
expect(counts.get("astro")).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("hasActiveFilters", () => {
|
||||||
|
it("should be false for the default state", () => {
|
||||||
|
expect(hasActiveFilters(state())).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should be true for tags, a keyword, or a non-default sort", () => {
|
||||||
|
expect(hasActiveFilters(state({ tags: ["css"] }))).toBe(true)
|
||||||
|
expect(hasActiveFilters(state({ query: " hi " }))).toBe(true)
|
||||||
|
expect(hasActiveFilters(state({ sort: "az" }))).toBe(true)
|
||||||
|
expect(hasActiveFilters(state({ query: " " }))).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("URL params", () => {
|
||||||
|
it("should round-trip tags, keyword and sort", () => {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
writeFilterParams(params, state({ tags: ["docker", "astro"], query: "home lab", sort: "oldest" }))
|
||||||
|
|
||||||
|
expect(parseFilterParams(params)).toEqual({
|
||||||
|
tags: ["docker", "astro"],
|
||||||
|
query: "home lab",
|
||||||
|
sort: "oldest",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should omit defaults so /blog stays clean", () => {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
writeFilterParams(params, state())
|
||||||
|
expect(params.toString()).toBe("")
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should case-fold and dedupe tags when parsing", () => {
|
||||||
|
const parsed = parseFilterParams(new URLSearchParams("tags=Docker,docker,,astro"))
|
||||||
|
expect(parsed.tags).toEqual(["docker", "astro"])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should fall back to defaults for junk values", () => {
|
||||||
|
const parsed = parseFilterParams(new URLSearchParams("sort=random&tags=%20%20"))
|
||||||
|
expect(parsed.sort).toBe(DEFAULT_SORT)
|
||||||
|
expect(parsed.tags).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should ignore a missing sort entirely", () => {
|
||||||
|
expect(parseFilterParams(new URLSearchParams("q=x")).query).toBe("x")
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,338 @@
|
|||||||
|
/**
|
||||||
|
* Appwrite TablesDB content service.
|
||||||
|
*
|
||||||
|
* The site's content (blog posts, projects, work history, legal docs) lives in
|
||||||
|
* the `spaghet-home` database on appwrite.spaghet.io (project `homelab`), one
|
||||||
|
* table per collection, with the markdown body in the `content` column. This
|
||||||
|
* module fetches rows with the node-appwrite SDK, renders the markdown to HTML
|
||||||
|
* with Astro's own Sätteri pipeline (same Shiki dual-theme config as
|
||||||
|
* astro.config.mjs, so code blocks look identical to the old astro:content
|
||||||
|
* output), and maps rows into entry shapes that match what astro:content's
|
||||||
|
* glob loader used to hand the pages: `data` carries the typed frontmatter
|
||||||
|
* with dates as Date objects, and the same fields are spread flat on the entry
|
||||||
|
* for the article layouts (the old pages spread `...entry.data` themselves).
|
||||||
|
*
|
||||||
|
* Auth: reads are public — every table grants `read("any")`, so the server
|
||||||
|
* talks to Appwrite with only the project header and no secret. Set
|
||||||
|
* APPWRITE_API_KEY to send one anyway (bypasses the guest rate limiter on a
|
||||||
|
* busy deployment); it is never required and never reaches the browser.
|
||||||
|
*
|
||||||
|
* Resilience: every list/get is cached in-process for APPWRITE_CONTENT_TTL_SECONDS
|
||||||
|
* (default 60). On a failed refresh the stale value is served; if there is no
|
||||||
|
* cached value at all the error propagates and the caller (content-source.ts)
|
||||||
|
* falls back to the local .md copies via astro:content.
|
||||||
|
*/
|
||||||
|
import { AppwriteException, Client, Query, TablesDB } from "node-appwrite"
|
||||||
|
import { createSatteriMarkdownProcessor } from "@astrojs/markdown-satteri"
|
||||||
|
import type { MarkdownRenderer } from "@astrojs/internal-helpers/markdown"
|
||||||
|
import type { BlogPost, LegalDocument, Project, SearchEntry, WorkExperience } from "./types"
|
||||||
|
|
||||||
|
export const APPWRITE_ENDPOINT = process.env.APPWRITE_ENDPOINT ?? "https://appwrite.spaghet.io/v1"
|
||||||
|
export const APPWRITE_PROJECT_ID = process.env.APPWRITE_PROJECT_ID ?? "homelab"
|
||||||
|
export const APPWRITE_DATABASE_ID = process.env.APPWRITE_DATABASE_ID ?? "spaghet-home"
|
||||||
|
|
||||||
|
const TTL_MS = Number(process.env.APPWRITE_CONTENT_TTL_SECONDS ?? 60) * 1000
|
||||||
|
|
||||||
|
export type ContentTable = "blog" | "projects" | "work" | "legal"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Frontmatter with dates as Date, matching what the astro:content glob loader
|
||||||
|
* produced (its schema used z.date()). The types.ts shapes keep ISO strings
|
||||||
|
* because they mirror the raw frontmatter; the pages that call
|
||||||
|
* `.toISOString()` (search index, cards) rely on the Date form.
|
||||||
|
*/
|
||||||
|
export type BlogPostData = Omit<BlogPost, "date"> & { date: Date }
|
||||||
|
export type ProjectData = Omit<Project, "date"> & { date: Date }
|
||||||
|
export type WorkData = Omit<WorkExperience, "dateStart" | "dateEnd"> & { dateStart: Date; dateEnd: Date }
|
||||||
|
export type LegalData = Omit<LegalDocument, "date"> & { date: Date }
|
||||||
|
|
||||||
|
export interface TableDataMap {
|
||||||
|
blog: BlogPostData
|
||||||
|
projects: ProjectData
|
||||||
|
work: WorkData
|
||||||
|
legal: LegalData
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An Appwrite row as it arrives over the wire (column bag plus $-metadata). */
|
||||||
|
type Row = Record<string, unknown> & { $id: string }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The entry shape the pages render: the typed fields spread flat (title,
|
||||||
|
* summary, date at the top level, as the article layouts expect from the old
|
||||||
|
* `...entry.data` spread), plus `data` for PageLayout props, and `content` as
|
||||||
|
* rendered HTML (what the old code took from entry.rendered.html).
|
||||||
|
*/
|
||||||
|
export type ContentEntry<K extends ContentTable = ContentTable> = {
|
||||||
|
id: string
|
||||||
|
collection: K
|
||||||
|
data: TableDataMap[K]
|
||||||
|
content: string
|
||||||
|
} & TableDataMap[K]
|
||||||
|
|
||||||
|
/** The slim listing shape (no body): cards, filters, search index, RSS. */
|
||||||
|
export interface SlimEntry {
|
||||||
|
id: string
|
||||||
|
collection: ContentTable
|
||||||
|
data: { title: string; summary: string; date: Date; tags: string[] }
|
||||||
|
}
|
||||||
|
|
||||||
|
let client: Client | undefined
|
||||||
|
function tables(): TablesDB {
|
||||||
|
if (!client) {
|
||||||
|
client = new Client().setEndpoint(APPWRITE_ENDPOINT).setProject(APPWRITE_PROJECT_ID)
|
||||||
|
const key = process.env.APPWRITE_API_KEY
|
||||||
|
if (key) client.setKey(key)
|
||||||
|
}
|
||||||
|
return new TablesDB(client)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- markdown rendering -------------------------------------------------
|
||||||
|
|
||||||
|
let renderer: Promise<MarkdownRenderer> | undefined
|
||||||
|
function getRenderer(): Promise<MarkdownRenderer> {
|
||||||
|
if (!renderer) {
|
||||||
|
// Mirrors astro.config.mjs `markdown.shikiConfig`: every token ships as a
|
||||||
|
// --shiki-light/--shiki-dark pair and global.css flips per mode.
|
||||||
|
renderer = createSatteriMarkdownProcessor({
|
||||||
|
syntaxHighlight: "shiki",
|
||||||
|
shikiConfig: {
|
||||||
|
themes: { light: "light-plus", dark: "everforest-dark" },
|
||||||
|
defaultColor: false,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return renderer
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renderMarkdown(markdown: string): Promise<string> {
|
||||||
|
const result = await (await getRenderer()).render(markdown, { frontmatter: {} })
|
||||||
|
return result.code
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- caching --------------------------------------------------------------
|
||||||
|
|
||||||
|
type CacheEntry = { at: number; value: unknown }
|
||||||
|
const cache = new Map<string, CacheEntry>()
|
||||||
|
const inflight = new Map<string, Promise<unknown>>()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serve `load()` fresh (TTL_MS), dedupe concurrent calls onto one promise, and
|
||||||
|
* fall back to the last good value — however old — when the load fails. Only
|
||||||
|
* throws when there is nothing cached at all, i.e. a cold cache with Appwrite
|
||||||
|
* unreachable; content-source.ts turns that into the .md fallback.
|
||||||
|
*/
|
||||||
|
async function cached<T>(key: string, load: () => Promise<T>): Promise<T> {
|
||||||
|
const hit = cache.get(key)
|
||||||
|
if (hit && Date.now() - hit.at < TTL_MS) return hit.value as T
|
||||||
|
const running = inflight.get(key)
|
||||||
|
if (running) return running as Promise<T>
|
||||||
|
const promise = load()
|
||||||
|
.then((value) => {
|
||||||
|
cache.set(key, { at: Date.now(), value })
|
||||||
|
return value
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
if (hit) {
|
||||||
|
console.warn(`[appwrite] refresh failed for ${key}; serving stale (${(err as Error).message})`)
|
||||||
|
return hit.value as T
|
||||||
|
}
|
||||||
|
throw err
|
||||||
|
})
|
||||||
|
.finally(() => inflight.delete(key))
|
||||||
|
inflight.set(key, promise)
|
||||||
|
return promise
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- row -> entry mappers ---------------------------------------------------
|
||||||
|
|
||||||
|
function str(row: Row, key: string): string {
|
||||||
|
return String(row[key] ?? "")
|
||||||
|
}
|
||||||
|
function optStr(row: Row, key: string): string | undefined {
|
||||||
|
const v = row[key]
|
||||||
|
return typeof v === "string" && v !== "" ? v : undefined
|
||||||
|
}
|
||||||
|
function bool(row: Row, key: string): boolean {
|
||||||
|
return row[key] === true
|
||||||
|
}
|
||||||
|
function date(row: Row, key: string): Date {
|
||||||
|
// Appwrite datetime columns come back as e.g. "2025-08-12T00:00:00.000+00:00".
|
||||||
|
return new Date(str(row, key))
|
||||||
|
}
|
||||||
|
function tags(row: Row): string[] {
|
||||||
|
return Array.isArray(row.tags) ? (row.tags as string[]) : []
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBlogPostData(row: Row): BlogPostData {
|
||||||
|
return {
|
||||||
|
id: row.$id,
|
||||||
|
title: str(row, "title"),
|
||||||
|
summary: str(row, "summary"),
|
||||||
|
date: date(row, "date"),
|
||||||
|
tags: tags(row),
|
||||||
|
draft: bool(row, "draft"),
|
||||||
|
content: "", // filled with rendered HTML below
|
||||||
|
template: str(row, "template") || "default",
|
||||||
|
featured: bool(row, "featured"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toProjectData(row: Row): ProjectData {
|
||||||
|
return {
|
||||||
|
id: row.$id,
|
||||||
|
title: str(row, "title"),
|
||||||
|
summary: str(row, "summary"),
|
||||||
|
date: date(row, "date"),
|
||||||
|
tags: tags(row),
|
||||||
|
draft: bool(row, "draft"),
|
||||||
|
content: "",
|
||||||
|
demoUrl: optStr(row, "demoUrl"),
|
||||||
|
repoUrl: optStr(row, "repoUrl"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toWorkData(row: Row): WorkData {
|
||||||
|
return {
|
||||||
|
id: row.$id,
|
||||||
|
company: str(row, "company"),
|
||||||
|
role: str(row, "role"),
|
||||||
|
dateStart: date(row, "dateStart"),
|
||||||
|
dateEnd: date(row, "dateEnd"),
|
||||||
|
content: "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toLegalData(row: Row): LegalData {
|
||||||
|
return {
|
||||||
|
id: row.$id,
|
||||||
|
title: str(row, "title"),
|
||||||
|
date: date(row, "date"),
|
||||||
|
content: "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the flat page entry from a row. `content` starts as the RAW markdown;
|
||||||
|
* loadEntries renders it in place and returns the HTML.
|
||||||
|
*/
|
||||||
|
function rowToEntry<K extends ContentTable>(table: K, row: Row): ContentEntry<K> {
|
||||||
|
const data: TableDataMap[K] =
|
||||||
|
table === "blog" ? (toBlogPostData(row) as TableDataMap[K])
|
||||||
|
: table === "projects" ? (toProjectData(row) as TableDataMap[K])
|
||||||
|
: table === "work" ? (toWorkData(row) as TableDataMap[K])
|
||||||
|
: (toLegalData(row) as TableDataMap[K])
|
||||||
|
data.content = str(row, "content")
|
||||||
|
// `...data` first: its id/content are the same values restated below, and
|
||||||
|
// TS flags a literal key that a later spread would overwrite (ts 2783).
|
||||||
|
return { ...data, id: row.$id, collection: table, data, content: data.content } as ContentEntry<K>
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadEntries<K extends ContentTable>(table: K, rows: Row[]): Promise<ContentEntry<K>[]> {
|
||||||
|
const entries = rows.map((row) => rowToEntry(table, row))
|
||||||
|
// Render sequentially: the satteri/shiki pipeline initialises once and the
|
||||||
|
// payloads are small; 18 docs never justified a pool.
|
||||||
|
for (const entry of entries) {
|
||||||
|
entry.content = await renderMarkdown(entry.content)
|
||||||
|
entry.data.content = entry.content
|
||||||
|
}
|
||||||
|
return entries
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- public API -------------------------------------------------------------
|
||||||
|
|
||||||
|
const LIST_ORDER: Record<ContentTable, string> = {
|
||||||
|
blog: "date",
|
||||||
|
projects: "date",
|
||||||
|
work: "dateStart",
|
||||||
|
legal: "date",
|
||||||
|
}
|
||||||
|
|
||||||
|
function listQueries(table: ContentTable, publishedOnly: boolean): ReturnType<typeof Query.orderDesc>[] {
|
||||||
|
const queries = [Query.orderDesc(LIST_ORDER[table]), Query.limit(100)]
|
||||||
|
// work/legal tables have no draft column; filtering on it would error.
|
||||||
|
if (publishedOnly && (table === "blog" || table === "projects")) {
|
||||||
|
queries.unshift(Query.equal("draft", false))
|
||||||
|
}
|
||||||
|
return queries as ReturnType<typeof Query.orderDesc>[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Full entries (rendered HTML bodies), newest first. */
|
||||||
|
export function listContent<K extends ContentTable>(table: K, publishedOnly = true): Promise<ContentEntry<K>[]> {
|
||||||
|
return cached(`list:${table}:${publishedOnly}`, async () => {
|
||||||
|
const res = await tables().listRows({
|
||||||
|
databaseId: APPWRITE_DATABASE_ID,
|
||||||
|
tableId: table,
|
||||||
|
queries: listQueries(table, publishedOnly),
|
||||||
|
})
|
||||||
|
return loadEntries(table, res.rows as unknown as Row[])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Slim entries for listing cards, filters, the search index and RSS (no body). */
|
||||||
|
export function listSlim<K extends ContentTable>(table: K): Promise<(Omit<SlimEntry, "collection"> & { collection: K })[]> {
|
||||||
|
return cached(`slim:${table}`, async () => {
|
||||||
|
const res = await tables().listRows({
|
||||||
|
databaseId: APPWRITE_DATABASE_ID,
|
||||||
|
tableId: table,
|
||||||
|
queries: [
|
||||||
|
...listQueries(table, true),
|
||||||
|
Query.select(["slug", "title", "summary", "date", "tags"]),
|
||||||
|
],
|
||||||
|
})
|
||||||
|
return (res.rows as unknown as Row[]).map((row) => ({
|
||||||
|
id: row.$id,
|
||||||
|
collection: table as K,
|
||||||
|
data: {
|
||||||
|
title: str(row, "title"),
|
||||||
|
summary: str(row, "summary"),
|
||||||
|
date: date(row, "date"),
|
||||||
|
tags: tags(row),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One published entry by slug, or null when missing/draft. */
|
||||||
|
export function getContent<K extends ContentTable>(table: K, slug: string): Promise<ContentEntry<K> | null> {
|
||||||
|
return cached(`get:${table}:${slug}`, async () => {
|
||||||
|
let row: Row
|
||||||
|
try {
|
||||||
|
row = (await tables().getRow({
|
||||||
|
databaseId: APPWRITE_DATABASE_ID,
|
||||||
|
tableId: table,
|
||||||
|
rowId: slug,
|
||||||
|
})) as unknown as Row
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof AppwriteException && err.code === 404) return null
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
if (table === "blog" || table === "projects") {
|
||||||
|
if (bool(row, "draft")) return null
|
||||||
|
}
|
||||||
|
const [entry] = await loadEntries(table, [row])
|
||||||
|
return entry ?? null
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The client-side fuse.js payload: blog + projects, slim, newest first. */
|
||||||
|
export async function listSearchEntries(): Promise<SearchEntry[]> {
|
||||||
|
const [blog, projects] = await Promise.all([listSlim("blog"), listSlim("projects")])
|
||||||
|
const toEntry = (e: SlimEntry): SearchEntry => ({
|
||||||
|
id: e.id,
|
||||||
|
slug: e.id,
|
||||||
|
collection: e.collection as "blog" | "projects",
|
||||||
|
title: e.data.title,
|
||||||
|
summary: e.data.summary,
|
||||||
|
tags: e.data.tags,
|
||||||
|
date: e.data.date.toISOString(),
|
||||||
|
})
|
||||||
|
return [...blog.map(toEntry), ...projects.map(toEntry)]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Test helper: drop every cached value (and the client/renderer singletons). */
|
||||||
|
export function __resetCache(): void {
|
||||||
|
cache.clear()
|
||||||
|
inflight.clear()
|
||||||
|
client = undefined
|
||||||
|
renderer = undefined
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
/**
|
||||||
|
* Content source facade: Appwrite TablesDB first, bundled .md fallback.
|
||||||
|
*
|
||||||
|
* Every page imports getCollectionContent/getCollectionEntry/listSlimContent
|
||||||
|
* from here instead of touching astro:content or the Appwrite SDK directly.
|
||||||
|
*
|
||||||
|
* Why a fallback at all: the markdown files under src/content stay in the repo
|
||||||
|
* as the backup copy (scripts/appwrite-migrate.mjs re-imports from them), and
|
||||||
|
* the astro:content glob loader reads them at build time for free. If Appwrite
|
||||||
|
* is unreachable when a page is requested and this process has never cached a
|
||||||
|
* successful read, we serve from the bundled copies so the site never 500s on
|
||||||
|
* a backend outage. Stale beats dead.
|
||||||
|
*
|
||||||
|
* Entries from both sources share one shape (see appwrite.ts ContentEntry):
|
||||||
|
* the typed frontmatter spread flat for the article layouts, `data` for page
|
||||||
|
* props, and `content` as rendered HTML.
|
||||||
|
*/
|
||||||
|
import { getCollection as getAstroCollection } from "astro:content"
|
||||||
|
import {
|
||||||
|
getContent as appwriteGetContent,
|
||||||
|
listContent as appwriteListContent,
|
||||||
|
listSlim as appwriteListSlim,
|
||||||
|
type ContentEntry,
|
||||||
|
type ContentTable,
|
||||||
|
} from "./appwrite"
|
||||||
|
import type { SearchEntry } from "./types"
|
||||||
|
|
||||||
|
export type { ContentEntry, ContentTable }
|
||||||
|
|
||||||
|
/** True after the most recent content read succeeded against Appwrite. */
|
||||||
|
let appwriteHealthy = false
|
||||||
|
export function isAppwriteHealthy(): boolean {
|
||||||
|
return appwriteHealthy
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap an astro:content entry in the shared shape. The glob loader already
|
||||||
|
* gives `data` with Date objects (z.date() schema); the old pages spread
|
||||||
|
* `...entry.data` at the call site, so we do it here instead.
|
||||||
|
*/
|
||||||
|
async function toFallbackEntry(table: ContentTable, entry: Awaited<ReturnType<typeof getAstroCollection>>[number]): Promise<ContentEntry> {
|
||||||
|
// The glob loader pre-renders markdown at build time; the old pages read the
|
||||||
|
// same `entry.rendered?.html`.
|
||||||
|
const html = entry.rendered?.html ?? ""
|
||||||
|
const data = { ...(entry.data as object), id: entry.id } as ContentEntry["data"]
|
||||||
|
data.content = html
|
||||||
|
// `...data` first: its id/content are restated below, and TS flags a literal
|
||||||
|
// key that a later spread would overwrite (ts 2783).
|
||||||
|
return { ...data, id: entry.id, collection: table, data, content: html } as ContentEntry
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortEntries(entries: ContentEntry[], table: ContentTable): ContentEntry[] {
|
||||||
|
const key = table === "work" ? "dateStart" : "date"
|
||||||
|
return entries.sort((a, b) => {
|
||||||
|
const da = (a.data as unknown as Record<string, Date>)[key]?.getTime() ?? 0
|
||||||
|
const db = (b.data as unknown as Record<string, Date>)[key]?.getTime() ?? 0
|
||||||
|
// Equal dates fall back to id, matching byDateDesc in lib/content.ts.
|
||||||
|
return db - da || a.id.localeCompare(b.id)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fallbackList(table: ContentTable): Promise<ContentEntry[]> {
|
||||||
|
const entries = await getAstroCollection(table as "blog")
|
||||||
|
const out: ContentEntry[] = []
|
||||||
|
for (const entry of entries) {
|
||||||
|
if ((entry.data as { draft?: boolean }).draft) continue
|
||||||
|
out.push(await toFallbackEntry(table, entry))
|
||||||
|
}
|
||||||
|
return sortEntries(out, table)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fallbackGet(table: ContentTable, slug: string): Promise<ContentEntry | null> {
|
||||||
|
const entries = await getAstroCollection(table as "blog")
|
||||||
|
const entry = entries.find((e) => e.id === slug)
|
||||||
|
if (!entry) return null
|
||||||
|
if ((entry.data as { draft?: boolean }).draft) return null
|
||||||
|
return toFallbackEntry(table, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Full entries (rendered HTML bodies), newest first, drafts excluded.
|
||||||
|
*
|
||||||
|
* Appwrite throws only on a cold-cache outage (appwrite.ts serves stale
|
||||||
|
* otherwise), which is exactly when we switch to the bundled .md copies.
|
||||||
|
*/
|
||||||
|
export async function getCollectionContent<K extends ContentTable>(table: K): Promise<ContentEntry<K>[]> {
|
||||||
|
try {
|
||||||
|
const entries = await appwriteListContent(table)
|
||||||
|
appwriteHealthy = true
|
||||||
|
return entries
|
||||||
|
} catch (err) {
|
||||||
|
appwriteHealthy = false
|
||||||
|
console.error(`[content] Appwrite unreachable for ${table}; falling back to bundled .md (${(err as Error).message})`)
|
||||||
|
return (await fallbackList(table)) as unknown as ContentEntry<K>[]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One published entry by slug, or null. */
|
||||||
|
export async function getCollectionEntry<K extends ContentTable>(table: K, slug: string): Promise<ContentEntry<K> | null> {
|
||||||
|
try {
|
||||||
|
const entry = await appwriteGetContent(table, slug)
|
||||||
|
appwriteHealthy = true
|
||||||
|
return entry
|
||||||
|
} catch (err) {
|
||||||
|
appwriteHealthy = false
|
||||||
|
console.error(`[content] Appwrite unreachable for ${table}/${slug}; falling back to bundled .md (${(err as Error).message})`)
|
||||||
|
return (await fallbackGet(table, slug)) as unknown as ContentEntry<K> | null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Slim listing entries (no body) for cards, filters and RSS. */
|
||||||
|
export async function listSlimContent<K extends ContentTable>(table: K): Promise<SlimSource<K>[]> {
|
||||||
|
try {
|
||||||
|
const rows = await appwriteListSlim(table)
|
||||||
|
appwriteHealthy = true
|
||||||
|
return rows
|
||||||
|
} catch (err) {
|
||||||
|
appwriteHealthy = false
|
||||||
|
console.error(`[content] Appwrite unreachable for ${table} listing; falling back to bundled .md (${(err as Error).message})`)
|
||||||
|
const entries = await fallbackList(table)
|
||||||
|
return entries.map((e) => ({
|
||||||
|
id: e.id,
|
||||||
|
collection: table,
|
||||||
|
data: {
|
||||||
|
title: (e.data as { title?: string }).title ?? "",
|
||||||
|
summary: (e.data as { summary?: string }).summary ?? "",
|
||||||
|
date: (e.data as { date?: Date }).date ?? new Date(0),
|
||||||
|
tags: (e.data as { tags?: string[] }).tags ?? [],
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type SlimSource<K extends ContentTable = ContentTable> = Awaited<ReturnType<typeof appwriteListSlim<K>>>[number]
|
||||||
|
|
||||||
|
/** The client-side fuse.js payload (blog + projects, slim). */
|
||||||
|
export async function getSearchEntries(): Promise<SearchEntry[]> {
|
||||||
|
const [posts, projects] = await Promise.all([listSlimContent("blog"), listSlimContent("projects")])
|
||||||
|
const toEntry = (e: SlimSource): SearchEntry => ({
|
||||||
|
id: e.id,
|
||||||
|
slug: e.id,
|
||||||
|
collection: e.collection as "blog" | "projects",
|
||||||
|
title: e.data.title,
|
||||||
|
summary: e.data.summary,
|
||||||
|
tags: e.data.tags,
|
||||||
|
date: e.data.date.toISOString(),
|
||||||
|
})
|
||||||
|
return [...posts.map(toEntry), ...projects.map(toEntry)]
|
||||||
|
}
|
||||||
+4
-21
@@ -23,33 +23,16 @@ export function byDateDesc(a: DatedEntry, b: DatedEntry): number {
|
|||||||
return diff !== 0 ? diff : a.id.localeCompare(b.id)
|
return diff !== 0 ? diff : a.id.localeCompare(b.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Tag filter shared by the Blog and Projects islands (their logic was
|
|
||||||
* byte-identical duplicates of each other).
|
|
||||||
*
|
|
||||||
* AND semantics: an entry must carry *every* selected tag, so adding a second
|
|
||||||
* tag narrows the result set rather than unioning it. Case-insensitive on both
|
|
||||||
* sides. Lives here (not in the islands) because the memo now runs during SSR,
|
|
||||||
* so a throw on a malformed entry would be a 500 rather than an empty list —
|
|
||||||
* and because this is the behavior worth asserting directly.
|
|
||||||
*/
|
|
||||||
export function filterByTags<T extends { tags: string[] }>(
|
|
||||||
entries: T[],
|
|
||||||
selected: Iterable<string>
|
|
||||||
): T[] {
|
|
||||||
const wanted = Array.from(selected, (value) => String(value).toLowerCase())
|
|
||||||
return entries.filter((entry) =>
|
|
||||||
wanted.every((tag) => entry.tags.some((entryTag) => entryTag.toLowerCase() === tag))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Map a blog or project content entry down to the slim, serializable shape
|
* Map a blog or project content entry down to the slim, serializable shape
|
||||||
* used by ArrowCard and the search index. Centralising this keeps every page
|
* used by ArrowCard and the search index. Centralising this keeps every page
|
||||||
* (home, blog, projects, search) emitting identical card props.
|
* (home, blog, projects, search) emitting identical card props.
|
||||||
*/
|
*/
|
||||||
export function toSearchEntry(
|
export function toSearchEntry(
|
||||||
entry: CollectionEntry<"blog"> | CollectionEntry<"projects">
|
entry:
|
||||||
|
| CollectionEntry<"blog">
|
||||||
|
| CollectionEntry<"projects">
|
||||||
|
| { id: string; collection: "blog" | "projects"; data: { title: string; summary: string; date: Date; tags: string[] } }
|
||||||
): SearchEntry {
|
): SearchEntry {
|
||||||
return {
|
return {
|
||||||
id: entry.id,
|
id: entry.id,
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
// src/lib/filters.ts
|
||||||
|
import type { ListEntry } from "@lib/types"
|
||||||
|
|
||||||
|
export type { ListEntry }
|
||||||
|
|
||||||
|
export type SortKey = "newest" | "oldest" | "az"
|
||||||
|
|
||||||
|
export const DEFAULT_SORT: SortKey = "newest"
|
||||||
|
export const SORT_KEYS: SortKey[] = ["newest", "oldest", "az"]
|
||||||
|
export const SORT_LABELS: Record<SortKey, string> = {
|
||||||
|
newest: "Newest first",
|
||||||
|
oldest: "Oldest first",
|
||||||
|
az: "Title A–Z",
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TagOption {
|
||||||
|
/** Case-folded identity, what gets stored in state and in the URL. */
|
||||||
|
key: string
|
||||||
|
/** The spelling shown to humans. */
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FilterState {
|
||||||
|
tags: string[]
|
||||||
|
query: string
|
||||||
|
sort: SortKey
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TAGS_PARAM = "tags"
|
||||||
|
export const QUERY_PARAM = "q"
|
||||||
|
export const SORT_PARAM = "sort"
|
||||||
|
|
||||||
|
export function normalizeTag(tag: string): string {
|
||||||
|
return tag.trim().toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dedupe tags case-insensitively and pick one canonical spelling per tag.
|
||||||
|
*
|
||||||
|
* Frontmatter is hand-written, so the same tag appears as both `Astro` and
|
||||||
|
* `astro` across the projects collection. Matching has always been
|
||||||
|
* case-insensitive, which meant the filter sidebar rendered two visually
|
||||||
|
* different checkboxes that did exactly the same thing. The label with the
|
||||||
|
* most occurrences wins; ties fall back to first-seen order, so the result is
|
||||||
|
* stable across builds.
|
||||||
|
*/
|
||||||
|
export function collectTags(entries: ListEntry[]): TagOption[] {
|
||||||
|
const spellings = new Map<string, Map<string, number>>()
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
for (const raw of entry.tags ?? []) {
|
||||||
|
const label = raw.trim()
|
||||||
|
if (!label) continue
|
||||||
|
const key = normalizeTag(label)
|
||||||
|
const counts = spellings.get(key) ?? new Map<string, number>()
|
||||||
|
counts.set(label, (counts.get(label) ?? 0) + 1)
|
||||||
|
spellings.set(key, counts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Array.from(spellings, ([key, counts]) => ({
|
||||||
|
key,
|
||||||
|
label: mostFrequent(counts),
|
||||||
|
})).sort((a, b) => a.label.localeCompare(b.label))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Highest count wins; `Map` iteration order breaks ties by first insertion. */
|
||||||
|
function mostFrequent(counts: Map<string, number>): string {
|
||||||
|
let best = ""
|
||||||
|
let bestCount = -1
|
||||||
|
for (const [label, count] of counts) {
|
||||||
|
if (count > bestCount) {
|
||||||
|
best = label
|
||||||
|
bestCount = count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keyword match over the fields the card shows: title, summary and tags. Body
|
||||||
|
* text is intentionally out of scope — full-text search lives on /search.
|
||||||
|
*/
|
||||||
|
export function matchesQuery(entry: ListEntry, query: string): boolean {
|
||||||
|
const needle = query.trim().toLowerCase()
|
||||||
|
if (!needle) return true
|
||||||
|
return (
|
||||||
|
entry.title.toLowerCase().includes(needle) ||
|
||||||
|
entry.summary.toLowerCase().includes(needle) ||
|
||||||
|
(entry.tags ?? []).some((tag) => tag.toLowerCase().includes(needle))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OR semantics: an entry is kept when it carries *any* selected tag.
|
||||||
|
*
|
||||||
|
* The old filter AND-ed the selection, so picking a second tag almost always
|
||||||
|
* emptied the list with no explanation. Broadening on click is what the
|
||||||
|
* checkboxes look like they do.
|
||||||
|
*/
|
||||||
|
export function filterEntries<T extends ListEntry>(
|
||||||
|
entries: T[],
|
||||||
|
state: FilterState
|
||||||
|
): T[] {
|
||||||
|
const selected = state.tags.map(normalizeTag).filter(Boolean)
|
||||||
|
const matched = entries.filter(
|
||||||
|
(entry) =>
|
||||||
|
matchesQuery(entry, state.query) &&
|
||||||
|
(selected.length === 0 ||
|
||||||
|
(entry.tags ?? []).some((tag) => selected.includes(normalizeTag(tag))))
|
||||||
|
)
|
||||||
|
return sortEntries(matched, state.sort)
|
||||||
|
}
|
||||||
|
|
||||||
|
function timestamp(entry: ListEntry): number {
|
||||||
|
const ms = new Date(entry.date).getTime()
|
||||||
|
// A malformed frontmatter date must not sort the whole list to NaN.
|
||||||
|
return Number.isFinite(ms) ? ms : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortEntries<T extends ListEntry>(entries: T[], sort: SortKey): T[] {
|
||||||
|
const copy = [...entries]
|
||||||
|
if (sort === "az") return copy.sort((a, b) => a.title.localeCompare(b.title))
|
||||||
|
if (sort === "oldest") return copy.sort((a, b) => timestamp(a) - timestamp(b))
|
||||||
|
return copy.sort((a, b) => timestamp(b) - timestamp(a))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How many entries each tag would contribute *within the current keyword
|
||||||
|
* filter*, keyed by tag. Tags are not counted against each other: under OR
|
||||||
|
* semantics every selected tag is contributing, and a count that collapsed as
|
||||||
|
* soon as you clicked something would read like the filter was broken.
|
||||||
|
*/
|
||||||
|
export function tagCounts(entries: ListEntry[], state: FilterState): Map<string, number> {
|
||||||
|
const counts = new Map<string, number>()
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!matchesQuery(entry, state.query)) continue
|
||||||
|
for (const key of new Set((entry.tags ?? []).map(normalizeTag))) {
|
||||||
|
if (!key) continue
|
||||||
|
counts.set(key, (counts.get(key) ?? 0) + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return counts
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasActiveFilters(state: FilterState): boolean {
|
||||||
|
return state.tags.length > 0 || state.query.trim().length > 0 || state.sort !== DEFAULT_SORT
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read filter state out of a URL query string. Anything unparseable falls back
|
||||||
|
* to the default rather than throwing: these values come from a hand-edited
|
||||||
|
* address bar and have no contract to honour.
|
||||||
|
*/
|
||||||
|
export function parseFilterParams(params: URLSearchParams): FilterState {
|
||||||
|
const rawSort = params.get(SORT_PARAM)
|
||||||
|
return {
|
||||||
|
tags: Array.from(
|
||||||
|
new Set(
|
||||||
|
(params.get(TAGS_PARAM) ?? "")
|
||||||
|
.split(",")
|
||||||
|
.map(normalizeTag)
|
||||||
|
.filter(Boolean)
|
||||||
|
)
|
||||||
|
),
|
||||||
|
query: params.get(QUERY_PARAM) ?? "",
|
||||||
|
sort: SORT_KEYS.includes(rawSort as SortKey) ? (rawSort as SortKey) : DEFAULT_SORT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write filter state back into a URLSearchParams, omitting defaults so a plain
|
||||||
|
* /blog stays a clean, shareable /blog.
|
||||||
|
*/
|
||||||
|
export function writeFilterParams(params: URLSearchParams, state: FilterState): void {
|
||||||
|
if (state.tags.length > 0) params.set(TAGS_PARAM, state.tags.join(","))
|
||||||
|
else params.delete(TAGS_PARAM)
|
||||||
|
|
||||||
|
if (state.query.trim().length > 0) params.set(QUERY_PARAM, state.query.trim())
|
||||||
|
else params.delete(QUERY_PARAM)
|
||||||
|
|
||||||
|
if (state.sort !== DEFAULT_SORT) params.set(SORT_PARAM, state.sort)
|
||||||
|
else params.delete(SORT_PARAM)
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
/**
|
||||||
|
* Browser-facing URLs for images stored in Appwrite Storage
|
||||||
|
* (bucket `site-media`, project `homelab`, files with stable IDs).
|
||||||
|
*
|
||||||
|
* The files themselves are uploaded by scripts/appwrite-migrate.mjs and are
|
||||||
|
* readable by anyone (bucket grants read("any")), so the only thing a page
|
||||||
|
* needs is the URL. Because the URLs are absolute and public, they must point
|
||||||
|
* at the hostnames a *browser* can reach — not at the internal endpoint the
|
||||||
|
* server SDK uses (inside Appwrite Sites that is http://appwrite). Override
|
||||||
|
* with APPWRITE_MEDIA_URL if the instance is ever renamed.
|
||||||
|
*
|
||||||
|
* /view serves the original bytes (Appwrite re-encodes png to webp for free);
|
||||||
|
* /preview resizes/re-encodes on demand and caches the result on disk — used
|
||||||
|
* for the profile circle, which renders at 128 CSS px (256 for retina) and
|
||||||
|
* would otherwise ship a 44 KB original for a 10 KB job.
|
||||||
|
*
|
||||||
|
* Server-rendered .astro components only: reads process.env, so importing
|
||||||
|
* this from a client island would bake in nothing.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const MEDIA_BASE =
|
||||||
|
process.env.APPWRITE_MEDIA_URL ?? "https://appwrite.spaghet.io/v1/storage/buckets/site-media/files"
|
||||||
|
const PROJECT = process.env.APPWRITE_PROJECT_ID ?? "homelab"
|
||||||
|
|
||||||
|
export type MediaOptions = {
|
||||||
|
/** Target width in CSS px; doubles for retina use, e.g. 256 for a 128px circle. */
|
||||||
|
width?: number
|
||||||
|
/** Preview quality 0-100 (default 80). Ignored without width. */
|
||||||
|
quality?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mediaUrl(file: string, opts: MediaOptions = {}): string {
|
||||||
|
const params = new URLSearchParams({ project: PROJECT })
|
||||||
|
if (opts.width) {
|
||||||
|
params.set("width", String(opts.width))
|
||||||
|
params.set("quality", String(opts.quality ?? 80))
|
||||||
|
return `${MEDIA_BASE}/${encodeURIComponent(file)}/preview?${params}`
|
||||||
|
}
|
||||||
|
return `${MEDIA_BASE}/${encodeURIComponent(file)}/view?${params}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inline onerror handler that swaps to the repo copy under public/images/ if
|
||||||
|
* Appwrite storage is ever unreachable. The local files stay in git as the
|
||||||
|
* backup and the upload source; this keeps them as the visible fallback too.
|
||||||
|
*/
|
||||||
|
export function mediaFallback(localPath: string): string {
|
||||||
|
return `this.onerror=null;this.src='${localPath}'`
|
||||||
|
}
|
||||||
+20
-4
@@ -41,11 +41,27 @@ export interface SearchEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shape accepted by ArrowCard. A union so the cards on the blog/projects
|
* The fields a listing card and its filters actually read.
|
||||||
* listing pages (flat BlogPost/Project) and search results (SearchEntry,
|
*
|
||||||
* which carries `collection` + `slug`) both type-check.
|
* Deliberately excludes the markdown `content`: the /blog and /projects islands
|
||||||
|
* serialized every entry's full body into the island's props on each request and
|
||||||
|
* never matched against it. `BlogPost`, `Project` and `SearchEntry` all satisfy
|
||||||
|
* this shape structurally, so cards and filters accept any of them.
|
||||||
*/
|
*/
|
||||||
export type CardEntry = BlogPost | Project | SearchEntry
|
export interface ListEntry {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
summary: string;
|
||||||
|
date: string;
|
||||||
|
tags: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shape accepted by ArrowCard. A union so the cards on the blog/projects
|
||||||
|
* listing pages (flat ListEntry) and search results (SearchEntry, which
|
||||||
|
* carries `collection` + `slug`) both type-check.
|
||||||
|
*/
|
||||||
|
export type CardEntry = ListEntry | SearchEntry
|
||||||
|
|
||||||
export interface WorkExperience {
|
export interface WorkExperience {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
@@ -1,31 +1,26 @@
|
|||||||
---
|
---
|
||||||
import { getCollection } from "astro:content"
|
|
||||||
import PageLayout from "@layouts/PageLayout.astro"
|
import PageLayout from "@layouts/PageLayout.astro"
|
||||||
import TopLayout from "@layouts/TopLayout.astro"
|
import TopLayout from "@layouts/TopLayout.astro"
|
||||||
import BottomLayout from "@layouts/BottomLayout.astro"
|
import BottomLayout from "@layouts/BottomLayout.astro"
|
||||||
import ArticleTopLayout from "@layouts/ArticleTopLayout.astro"
|
import ArticleTopLayout from "@layouts/ArticleTopLayout.astro"
|
||||||
import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro"
|
import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro"
|
||||||
|
import { getCollectionContent, getCollectionEntry } from "@lib/content-source"
|
||||||
|
|
||||||
export const prerender = true
|
// Content comes from Appwrite at request time, so these pages can no longer be
|
||||||
|
// prerendered at build time; the node adapter serves them (output: "server" is
|
||||||
|
// already the default). A cold Appwrite falls back to the bundled .md copies
|
||||||
|
// (src/lib/content-source.ts), not to a 500.
|
||||||
|
export const prerender = false
|
||||||
|
|
||||||
export async function getStaticPaths() {
|
const { slug } = Astro.params
|
||||||
const entries = await getCollection("blog", ({ data }) => !data.draft)
|
const entry = slug ? await getCollectionEntry("blog", slug) : null
|
||||||
// The article layouts expect the flat BlogPost shape (title/summary/date at the
|
if (!entry) return Astro.redirect("/blog")
|
||||||
// top level). Astro's collection entries nest frontmatter under `data`, so
|
// The article layouts expect the flat BlogPost shape (title/summary/date at the
|
||||||
// spreading the entry alone left every article heading blank and made
|
// top level); getCollectionEntry already spreads `data` onto the entry.
|
||||||
// formatDate(undefined) fall back to today's date.
|
// ArticleBottomLayout derives prev/next from array position (index-1 = Prev),
|
||||||
const flat = entries.map((entry) => ({
|
// so it needs oldest-first — the reverse of the listContent default, and the
|
||||||
...entry,
|
// same order the old filename-sorted getStaticPaths produced.
|
||||||
...entry.data,
|
const allEntries = (await getCollectionContent("blog")).reverse()
|
||||||
content: entry.rendered?.html ?? "",
|
|
||||||
}))
|
|
||||||
return entries.map((entry, i) => ({
|
|
||||||
params: { slug: entry.id },
|
|
||||||
props: { entry: flat[i], allEntries: flat },
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
const { entry, allEntries } = Astro.props
|
|
||||||
const { title, summary } = entry.data
|
const { title, summary } = entry.data
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+21
-20
@@ -1,28 +1,29 @@
|
|||||||
---
|
---
|
||||||
import { getCollection } from "astro:content"
|
|
||||||
import PageLayout from "@layouts/PageLayout.astro"
|
import PageLayout from "@layouts/PageLayout.astro"
|
||||||
import TopLayout from "@layouts/TopLayout.astro"
|
import TopLayout from "@layouts/TopLayout.astro"
|
||||||
import BottomLayout from "@layouts/BottomLayout.astro"
|
import BottomLayout from "@layouts/BottomLayout.astro"
|
||||||
import Blog from "@components/Blog"
|
import FilteredList from "@components/FilteredList"
|
||||||
import { BLOG } from "@consts"
|
import { BLOG } from "@consts"
|
||||||
import { byDateDesc } from "@lib/content"
|
import { parseFilterParams } from "@lib/filters"
|
||||||
|
import { listSlimContent } from "@lib/content-source"
|
||||||
|
|
||||||
const entries = await getCollection("blog", ({ data }) => !data.draft)
|
// Only the fields the cards and the filters read. `content` was serialized into
|
||||||
const posts = entries
|
// the island's props on every request and never matched against — the markdown
|
||||||
.sort(byDateDesc)
|
// body is the single largest thing on this page. Appwrite TablesDB first,
|
||||||
.map((entry) => ({
|
// bundled .md fallback (src/lib/content-source.ts); ordering is already
|
||||||
id: entry.id,
|
// newest-first with the byDateDesc tie-break.
|
||||||
slug: entry.id,
|
const slim = await listSlimContent("blog")
|
||||||
title: entry.data.title,
|
const posts = slim.map((entry) => ({
|
||||||
summary: entry.data.summary,
|
id: entry.id,
|
||||||
date: entry.data.date.toISOString(),
|
title: entry.data.title,
|
||||||
tags: entry.data.tags,
|
summary: entry.data.summary,
|
||||||
draft: entry.data.draft,
|
date: entry.data.date.toISOString(),
|
||||||
content: entry.body ?? "",
|
tags: entry.data.tags,
|
||||||
template: entry.data.template,
|
}))
|
||||||
featured: entry.data.featured,
|
|
||||||
}))
|
// Frontmatter runs on the server, so the initial filter state has to come from
|
||||||
const tags = Array.from(new Set(posts.flatMap((p) => p.tags)))
|
// the request URL rather than `window.location` (see src/pages/search/index.astro).
|
||||||
|
const initial = parseFilterParams(Astro.url.searchParams)
|
||||||
---
|
---
|
||||||
|
|
||||||
<PageLayout title={BLOG.TITLE} description={BLOG.DESCRIPTION}>
|
<PageLayout title={BLOG.TITLE} description={BLOG.DESCRIPTION}>
|
||||||
@@ -33,7 +34,7 @@ const tags = Array.from(new Set(posts.flatMap((p) => p.tags)))
|
|||||||
</TopLayout>
|
</TopLayout>
|
||||||
<BottomLayout>
|
<BottomLayout>
|
||||||
<div class="animate">
|
<div class="animate">
|
||||||
<Blog client:load tags={tags} data={posts} />
|
<FilteredList client:load collection="blog" entries={posts} initial={initial} />
|
||||||
</div>
|
</div>
|
||||||
</BottomLayout>
|
</BottomLayout>
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
+16
-13
@@ -1,24 +1,22 @@
|
|||||||
---
|
---
|
||||||
import { getCollection } from "astro:content"
|
|
||||||
import PageLayout from "@layouts/PageLayout.astro"
|
import PageLayout from "@layouts/PageLayout.astro"
|
||||||
import ArrowCard from "@components/ArrowCard"
|
import ArrowCard from "@components/ArrowCard"
|
||||||
import StackCard from "@components/StackCard.astro"
|
import StackCard from "@components/StackCard.astro"
|
||||||
import { SITE, SOCIALS } from "@consts"
|
import { SITE, SOCIALS } from "@consts"
|
||||||
import { byDateDesc, toSearchEntry } from "@lib/content"
|
import { toSearchEntry } from "@lib/content"
|
||||||
|
import { listSlimContent } from "@lib/content-source"
|
||||||
|
import { mediaUrl, mediaFallback } from "@lib/media"
|
||||||
import ParmesanFlecks from "@components/ParmesanFlecks.astro"
|
import ParmesanFlecks from "@components/ParmesanFlecks.astro"
|
||||||
import MeatballShower from "@components/MeatballShower.astro"
|
import MeatballShower from "@components/MeatballShower.astro"
|
||||||
|
|
||||||
const allBlogEntries = await getCollection("blog", ({ data }) => !data.draft)
|
// Appwrite TablesDB first, bundled .md fallback (src/lib/content-source.ts).
|
||||||
const posts = allBlogEntries
|
// listSlimContent already returns published entries newest-first with the
|
||||||
.sort(byDateDesc)
|
// byDateDesc tie-break, so no local sort is needed here.
|
||||||
.slice(0, 3)
|
const blogSlim = await listSlimContent("blog")
|
||||||
.map(toSearchEntry)
|
const posts = blogSlim.slice(0, 3).map(toSearchEntry)
|
||||||
|
|
||||||
const allProjectEntries = await getCollection("projects", ({ data }) => !data.draft)
|
const projectSlim = await listSlimContent("projects")
|
||||||
const projects = allProjectEntries
|
const projects = projectSlim.slice(0, 3).map(toSearchEntry)
|
||||||
.sort(byDateDesc)
|
|
||||||
.slice(0, 3)
|
|
||||||
.map(toSearchEntry)
|
|
||||||
|
|
||||||
const stack = [
|
const stack = [
|
||||||
{
|
{
|
||||||
@@ -40,6 +38,11 @@ const stack = [
|
|||||||
text: "Tailwind",
|
text: "Tailwind",
|
||||||
icon: "tailwind",
|
icon: "tailwind",
|
||||||
href: "https://tailwindcss.com"
|
href: "https://tailwindcss.com"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: "Appwrite",
|
||||||
|
icon: "appwrite",
|
||||||
|
href: "https://appwrite.io"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
---
|
---
|
||||||
@@ -88,7 +91,7 @@ const stack = [
|
|||||||
<div class="animate absolute h-full w-full flex items-center justify-center">
|
<div class="animate absolute h-full w-full flex items-center justify-center">
|
||||||
<div class='relative w-full h-full flex items-center justify-center text-ink'>
|
<div class='relative w-full h-full flex items-center justify-center text-ink'>
|
||||||
<div class='p-5 text-center'>
|
<div class='p-5 text-center'>
|
||||||
<img src='/images/profile.jpg' alt="Quinn Marvin" class="rounded-full w-32 h-32 mx-auto mb-4 border-4 border-edge" />
|
<img src={mediaUrl("profile.jpg", { width: 256 })} alt="Quinn Marvin" class="rounded-full w-32 h-32 mx-auto mb-4 border-4 border-edge" loading="lazy" width="128" height="128" onerror={mediaFallback("/images/profile.jpg")} />
|
||||||
<p class='animated text-lg md:text-xl lg:text-2xl font-semibold opacity-75'>
|
<p class='animated text-lg md:text-xl lg:text-2xl font-semibold opacity-75'>
|
||||||
Hello, I am Quinn Marvin
|
Hello, I am Quinn Marvin
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -1,22 +1,15 @@
|
|||||||
---
|
---
|
||||||
export const prerender = true;
|
export const prerender = false;
|
||||||
import { getCollection } from "astro:content"
|
|
||||||
import PageLayout from "@layouts/PageLayout.astro"
|
import PageLayout from "@layouts/PageLayout.astro"
|
||||||
import TopLayout from "@layouts/TopLayout.astro"
|
import TopLayout from "@layouts/TopLayout.astro"
|
||||||
import BottomLayout from "@layouts/BottomLayout.astro"
|
import BottomLayout from "@layouts/BottomLayout.astro"
|
||||||
import { formatDate } from "@lib/utils"
|
import { formatDate } from "@lib/utils"
|
||||||
import { SITE } from "@consts"
|
import { SITE } from "@consts"
|
||||||
|
import { getCollectionEntry } from "@lib/content-source"
|
||||||
|
|
||||||
export async function getStaticPaths() {
|
const { slug } = Astro.params
|
||||||
const entries = await getCollection("legal")
|
const doc = slug ? await getCollectionEntry("legal", slug) : null
|
||||||
return entries.map((entry) => ({
|
if (!doc) return Astro.redirect("/")
|
||||||
params: { slug: entry.id },
|
|
||||||
props: { entry },
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
const { entry } = Astro.props
|
|
||||||
const doc = entry
|
|
||||||
---
|
---
|
||||||
|
|
||||||
<PageLayout title={doc.data.title} description={`${doc.data.title} for ${SITE.TITLE}`}>
|
<PageLayout title={doc.data.title} description={`${doc.data.title} for ${SITE.TITLE}`}>
|
||||||
@@ -31,6 +24,6 @@ const doc = entry
|
|||||||
</div>
|
</div>
|
||||||
</TopLayout>
|
</TopLayout>
|
||||||
<BottomLayout>
|
<BottomLayout>
|
||||||
<article class="animate prose dark:prose-invert text-ink" set:html={doc.rendered?.html}></article>
|
<article class="animate prose dark:prose-invert text-ink" set:html={doc.content}></article>
|
||||||
</BottomLayout>
|
</BottomLayout>
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
@@ -1,29 +1,19 @@
|
|||||||
---
|
---
|
||||||
import { getCollection } from "astro:content"
|
|
||||||
import PageLayout from "@layouts/PageLayout.astro"
|
import PageLayout from "@layouts/PageLayout.astro"
|
||||||
import TopLayout from "@layouts/TopLayout.astro"
|
import TopLayout from "@layouts/TopLayout.astro"
|
||||||
import BottomLayout from "@layouts/BottomLayout.astro"
|
import BottomLayout from "@layouts/BottomLayout.astro"
|
||||||
import ArticleTopLayout from "@layouts/ArticleTopLayout.astro"
|
import ArticleTopLayout from "@layouts/ArticleTopLayout.astro"
|
||||||
import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro"
|
import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro"
|
||||||
|
import { getCollectionContent, getCollectionEntry } from "@lib/content-source"
|
||||||
|
|
||||||
export const prerender = true
|
// Content comes from Appwrite at request time; see the note in
|
||||||
|
// src/pages/blog/[...slug].astro.
|
||||||
|
export const prerender = false
|
||||||
|
|
||||||
export async function getStaticPaths() {
|
const { slug } = Astro.params
|
||||||
const entries = await getCollection("projects", ({ data }) => !data.draft)
|
const entry = slug ? await getCollectionEntry("projects", slug) : null
|
||||||
// Flatten frontmatter to the shape ArticleTopLayout/ArticleBottomLayout expect;
|
if (!entry) return Astro.redirect("/projects")
|
||||||
// see the note in src/pages/blog/[...slug].astro.
|
const allEntries = (await getCollectionContent("projects")).reverse()
|
||||||
const flat = entries.map((entry) => ({
|
|
||||||
...entry,
|
|
||||||
...entry.data,
|
|
||||||
content: entry.rendered?.html ?? "",
|
|
||||||
}))
|
|
||||||
return entries.map((entry, i) => ({
|
|
||||||
params: { slug: entry.id },
|
|
||||||
props: { entry: flat[i], allEntries: flat },
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
const { entry, allEntries } = Astro.props
|
|
||||||
const { title, summary } = entry.data
|
const { title, summary } = entry.data
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +1,25 @@
|
|||||||
---
|
---
|
||||||
import { getCollection } from "astro:content"
|
|
||||||
import PageLayout from "@layouts/PageLayout.astro"
|
import PageLayout from "@layouts/PageLayout.astro"
|
||||||
import TopLayout from "@layouts/TopLayout.astro"
|
import TopLayout from "@layouts/TopLayout.astro"
|
||||||
import BottomLayout from "@layouts/BottomLayout.astro"
|
import BottomLayout from "@layouts/BottomLayout.astro"
|
||||||
import Projects from "@components/Projects"
|
import FilteredList from "@components/FilteredList"
|
||||||
import { PROJECTS } from "@consts"
|
import { PROJECTS } from "@consts"
|
||||||
import { byDateDesc } from "@lib/content"
|
import { parseFilterParams } from "@lib/filters"
|
||||||
|
import { listSlimContent } from "@lib/content-source"
|
||||||
|
|
||||||
const entries = await getCollection("projects", ({ data }) => !data.draft)
|
// Only the fields the cards and the filters read; see src/pages/blog/index.astro.
|
||||||
const posts = entries
|
const slim = await listSlimContent("projects")
|
||||||
.sort(byDateDesc)
|
const projects = slim.map((entry) => ({
|
||||||
.map((entry) => ({
|
id: entry.id,
|
||||||
id: entry.id,
|
title: entry.data.title,
|
||||||
slug: entry.id,
|
summary: entry.data.summary,
|
||||||
title: entry.data.title,
|
date: entry.data.date.toISOString(),
|
||||||
summary: entry.data.summary,
|
tags: entry.data.tags,
|
||||||
date: entry.data.date.toISOString(),
|
}))
|
||||||
tags: entry.data.tags,
|
|
||||||
draft: entry.data.draft,
|
// Frontmatter runs on the server, so the initial filter state has to come from
|
||||||
content: entry.body ?? "",
|
// the request URL rather than `window.location` (see src/pages/search/index.astro).
|
||||||
demoUrl: entry.data.demoUrl,
|
const initial = parseFilterParams(Astro.url.searchParams)
|
||||||
repoUrl: entry.data.repoUrl,
|
|
||||||
}))
|
|
||||||
const tags = Array.from(new Set(posts.flatMap((p) => p.tags)))
|
|
||||||
---
|
---
|
||||||
|
|
||||||
<PageLayout title={PROJECTS.TITLE} description={PROJECTS.DESCRIPTION}>
|
<PageLayout title={PROJECTS.TITLE} description={PROJECTS.DESCRIPTION}>
|
||||||
@@ -33,7 +30,7 @@ const tags = Array.from(new Set(posts.flatMap((p) => p.tags)))
|
|||||||
</TopLayout>
|
</TopLayout>
|
||||||
<BottomLayout>
|
<BottomLayout>
|
||||||
<div class="animate">
|
<div class="animate">
|
||||||
<Projects client:load tags={tags} data={posts} />
|
<FilteredList client:load collection="projects" entries={projects} initial={initial} />
|
||||||
</div>
|
</div>
|
||||||
</BottomLayout>
|
</BottomLayout>
|
||||||
</PageLayout>
|
</PageLayout>
|
||||||
+9
-10
@@ -1,22 +1,21 @@
|
|||||||
import rss from "@astrojs/rss"
|
import rss from "@astrojs/rss"
|
||||||
import { getCollection } from "astro:content"
|
|
||||||
import { SITE } from "@consts"
|
import { SITE } from "@consts"
|
||||||
|
import { listSlimContent } from "@lib/content-source"
|
||||||
|
|
||||||
type Context = {
|
type Context = {
|
||||||
site: string
|
site: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET(context: Context) {
|
export async function GET(context: Context) {
|
||||||
const entries = await getCollection("blog", ({ data }) => !data.draft)
|
// Published posts, newest first (listSlimContent ordering).
|
||||||
|
const entries = await listSlimContent("blog")
|
||||||
|
|
||||||
const items = entries
|
const items = entries.map((entry) => ({
|
||||||
.sort((a, b) => b.data.date.getTime() - a.data.date.getTime())
|
title: entry.data.title,
|
||||||
.map((entry) => ({
|
description: entry.data.summary,
|
||||||
title: entry.data.title,
|
pubDate: entry.data.date,
|
||||||
description: entry.data.summary,
|
link: `/blog/${entry.id}/`,
|
||||||
pubDate: entry.data.date,
|
}))
|
||||||
link: `/blog/${entry.id}/`,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return rss({
|
return rss({
|
||||||
title: SITE.TITLE,
|
title: SITE.TITLE,
|
||||||
|
|||||||
@@ -1,38 +1,15 @@
|
|||||||
---
|
---
|
||||||
import { getCollection } from "astro:content"
|
|
||||||
import PageLayout from "@layouts/PageLayout.astro"
|
import PageLayout from "@layouts/PageLayout.astro"
|
||||||
import TopLayout from "@layouts/TopLayout.astro"
|
import TopLayout from "@layouts/TopLayout.astro"
|
||||||
import BottomLayout from "@layouts/BottomLayout.astro"
|
import BottomLayout from "@layouts/BottomLayout.astro"
|
||||||
import Search from "@components/Search"
|
import Search from "@components/Search"
|
||||||
import { SEARCH } from "@consts"
|
import { SEARCH } from "@consts"
|
||||||
import type { SearchEntry } from "@lib/search"
|
import type { SearchEntry } from "@lib/search"
|
||||||
|
import { getSearchEntries } from "@lib/content-source"
|
||||||
|
|
||||||
// Blog posts -> slim searchable entries.
|
// Blog + projects -> slim searchable entries (fuse.js runs in the browser;
|
||||||
// `body` is intentionally NOT serialized to the client; see src/lib/search.ts.
|
// `body` is intentionally NOT serialized to the client, see src/lib/search.ts).
|
||||||
const blogEntries = await getCollection("blog", ({ data }) => !data.draft)
|
const entries: SearchEntry[] = await getSearchEntries()
|
||||||
const posts: SearchEntry[] = blogEntries.map((entry) => ({
|
|
||||||
id: entry.id,
|
|
||||||
slug: entry.id,
|
|
||||||
collection: "blog",
|
|
||||||
title: entry.data.title,
|
|
||||||
summary: entry.data.summary,
|
|
||||||
date: entry.data.date.toISOString(),
|
|
||||||
tags: entry.data.tags,
|
|
||||||
}))
|
|
||||||
|
|
||||||
// Projects -> slim searchable entries.
|
|
||||||
const projectEntries = await getCollection("projects", ({ data }) => !data.draft)
|
|
||||||
const projects: SearchEntry[] = projectEntries.map((entry) => ({
|
|
||||||
id: entry.id,
|
|
||||||
slug: entry.id,
|
|
||||||
collection: "projects",
|
|
||||||
title: entry.data.title,
|
|
||||||
summary: entry.data.summary,
|
|
||||||
date: entry.data.date.toISOString(),
|
|
||||||
tags: entry.data.tags,
|
|
||||||
}))
|
|
||||||
|
|
||||||
const entries: SearchEntry[] = [...posts, ...projects]
|
|
||||||
|
|
||||||
// Read the `?search=` param from the incoming SSR request.
|
// Read the `?search=` param from the incoming SSR request.
|
||||||
// NOTE: this frontmatter runs on the server, so `window` is never available
|
// NOTE: this frontmatter runs on the server, so `window` is never available
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
---
|
---
|
||||||
import { getCollection } from "astro:content"
|
|
||||||
import PageLayout from "@layouts/PageLayout.astro"
|
import PageLayout from "@layouts/PageLayout.astro"
|
||||||
import TopLayout from "@layouts/TopLayout.astro"
|
import TopLayout from "@layouts/TopLayout.astro"
|
||||||
import BottomLayout from "@layouts/BottomLayout.astro"
|
import BottomLayout from "@layouts/BottomLayout.astro"
|
||||||
import { WORK } from "@consts"
|
import { WORK } from "@consts"
|
||||||
|
import { getCollectionContent } from "@lib/content-source"
|
||||||
|
|
||||||
const work = await getCollection("work")
|
const work = await getCollectionContent("work")
|
||||||
|
|
||||||
function formatWorkDate(input: Date | string) {
|
function formatWorkDate(input: Date | string) {
|
||||||
if (typeof input === "string") input = new Date(input)
|
if (typeof input === "string") input = new Date(input)
|
||||||
@@ -39,7 +39,7 @@ function formatWorkDate(input: Date | string) {
|
|||||||
<div class="text-sm font-semibold text-accent">
|
<div class="text-sm font-semibold text-accent">
|
||||||
{entry.data.role}
|
{entry.data.role}
|
||||||
</div>
|
</div>
|
||||||
<article class="prose dark:prose-invert text-ink" set:html={entry.rendered?.html}></article>
|
<article class="prose dark:prose-invert text-ink" set:html={entry.content}></article>
|
||||||
</li>
|
</li>
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,5 +23,14 @@ export default defineConfig({
|
|||||||
test: {
|
test: {
|
||||||
environment: "node",
|
environment: "node",
|
||||||
include: ["src/**/__tests__/**/*.test.ts", "src/**/*.test.ts"],
|
include: ["src/**/__tests__/**/*.test.ts", "src/**/*.test.ts"],
|
||||||
|
// Rolldown (Vite 8's bundler, loaded when Vitest reads this config) sizes
|
||||||
|
// its native thread pool to `nproc`. On hosts that report many CPUs but
|
||||||
|
// cannot actually spawn that many threads, the default `forks` pool aborts
|
||||||
|
// with "spawn node EAGAIN". The `threads` pool with a single worker avoids
|
||||||
|
// forking one child process per file; the matching RAYON/TOKIO caps live in
|
||||||
|
// the package.json scripts.
|
||||||
|
pool: "threads",
|
||||||
|
maxWorkers: 1,
|
||||||
|
fileParallelism: false,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
Reference in new issue
Block a user