commit 520c5f19e2666efa8b702bd10241bbe57897ddf5 Author: Kunthawat Greethong Date: Wed Apr 29 12:41:59 2026 +0700 Initial commit: EmDash blog template Fixed index.astro: escaped curly braces in code display block to prevent Astro parser misinterpreting them as expressions. Co-Authored-By: Claude Opus 4.6 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b3b1101 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules +dist +.astro +uploads +data.db diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..9524aad --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,38 @@ +This is an EmDash site -- a CMS built on Astro with a full admin UI. + +## Commands + +```bash +npx emdash dev # Start dev server (runs migrations, seeds, generates types) +npx emdash types # Regenerate TypeScript types from schema +npx emdash seed seed/seed.json --validate # Validate seed file +``` + +The admin UI is at `http://localhost:4321/_emdash/admin`. + +## Key Files + +| File | Purpose | +| ------------------------ | ---------------------------------------------------------------------------------- | +| `astro.config.mjs` | Astro config with `emdash()` integration, database, and storage | +| `src/live.config.ts` | EmDash loader registration (boilerplate -- don't modify) | +| `seed/seed.json` | Schema definition + demo content (collections, fields, taxonomies, menus, widgets) | +| `emdash-env.d.ts` | Generated types for collections (auto-regenerated on dev server start) | +| `src/layouts/Base.astro` | Base layout with EmDash wiring (menus, search, page contributions) | +| `src/pages/` | Astro pages -- all server-rendered | + +## Skills + +Agent skills are in `.agents/skills/`. Load them when working on specific tasks: + +- **building-emdash-site** -- Querying content, rendering Portable Text, schema design, seed files, site features (menus, widgets, search, SEO, comments, bylines). Start here. +- **creating-plugins** -- Building EmDash plugins with hooks, storage, admin UI, API routes, and Portable Text block types. +- **emdash-cli** -- CLI commands for content management, seeding, type generation, and visual editing flow. + +## Rules + +- All content pages must be server-rendered (`output: "server"`). No `getStaticPaths()` for CMS content. +- Image fields are objects (`{ src, alt }`), not strings. Use `` from `"emdash/ui"`. +- `entry.id` is the slug (for URLs). `entry.data.id` is the database ULID (for API calls like `getEntryTerms`). +- Always call `Astro.cache.set(cacheHint)` on pages that query content. +- Taxonomy names in queries must match the seed's `"name"` field exactly (e.g., `"category"` not `"categories"`). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..9524aad --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,38 @@ +This is an EmDash site -- a CMS built on Astro with a full admin UI. + +## Commands + +```bash +npx emdash dev # Start dev server (runs migrations, seeds, generates types) +npx emdash types # Regenerate TypeScript types from schema +npx emdash seed seed/seed.json --validate # Validate seed file +``` + +The admin UI is at `http://localhost:4321/_emdash/admin`. + +## Key Files + +| File | Purpose | +| ------------------------ | ---------------------------------------------------------------------------------- | +| `astro.config.mjs` | Astro config with `emdash()` integration, database, and storage | +| `src/live.config.ts` | EmDash loader registration (boilerplate -- don't modify) | +| `seed/seed.json` | Schema definition + demo content (collections, fields, taxonomies, menus, widgets) | +| `emdash-env.d.ts` | Generated types for collections (auto-regenerated on dev server start) | +| `src/layouts/Base.astro` | Base layout with EmDash wiring (menus, search, page contributions) | +| `src/pages/` | Astro pages -- all server-rendered | + +## Skills + +Agent skills are in `.agents/skills/`. Load them when working on specific tasks: + +- **building-emdash-site** -- Querying content, rendering Portable Text, schema design, seed files, site features (menus, widgets, search, SEO, comments, bylines). Start here. +- **creating-plugins** -- Building EmDash plugins with hooks, storage, admin UI, API routes, and Portable Text block types. +- **emdash-cli** -- CLI commands for content management, seeding, type generation, and visual editing flow. + +## Rules + +- All content pages must be server-rendered (`output: "server"`). No `getStaticPaths()` for CMS content. +- Image fields are objects (`{ src, alt }`), not strings. Use `` from `"emdash/ui"`. +- `entry.id` is the slug (for URLs). `entry.data.id` is the database ULID (for API calls like `getEntryTerms`). +- Always call `Astro.cache.set(cacheHint)` on pages that query content. +- Taxonomy names in queries must match the seed's `"name"` field exactly (e.g., `"category"` not `"categories"`). diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d0ae657 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,36 @@ +FROM node:20-alpine AS deps + +RUN apk add --no-cache python3 make g++ + +WORKDIR /app + +COPY package.json pnpm-lock.yaml* ./ +RUN corepack enable && corepack prepare pnpm@9.0.0 --activate +RUN pnpm install + +FROM deps AS builder + +WORKDIR /app + +COPY --from=deps /app/node_modules ./node_modules +COPY . . + +RUN pnpm build + +FROM deps AS runner + +WORKDIR /app + +ENV NODE_ENV=production + +RUN adduser --system --uid 1001 astro +USER astro + +COPY --from=builder /app/node_modules ./node_modules +COPY --from=builder /app/dist ./dist +COPY --from=builder /app/public ./public +COPY --from=builder /app/data.db ./data.db + +EXPOSE 4321 + +CMD ["node", "./dist/server/entry.mjs"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..5a25dcf --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# EmDash Blog Template + +A clean, minimal blog built with [EmDash](https://github.com/emdash-cms/emdash). Runs on any Node.js server with SQLite and local file storage. + +![Blog template homepage](https://raw.githubusercontent.com/emdash-cms/emdash/main/assets/templates/blog/latest/homepage-light-desktop.jpg) + +## What's Included + +- Featured post hero on the homepage +- Post archive with reading time estimates +- Category and tag archives +- Full-text search +- RSS feed +- SEO metadata and JSON-LD +- Dark/light mode +- Audit log plugin + +## Pages + +| Page | Route | +|---|---| +| Homepage | `/` | +| All posts | `/posts` | +| Single post | `/posts/:slug` | +| Category archive | `/category/:slug` | +| Tag archive | `/tag/:slug` | +| Search | `/search` | +| Static pages | `/pages/:slug` | +| 404 | fallback | + +## Screenshots + +| | Desktop | Mobile | +|---|---|---| +| Light | ![homepage light desktop](https://raw.githubusercontent.com/emdash-cms/emdash/main/assets/templates/blog/latest/homepage-light-desktop.jpg) | ![homepage light mobile](https://raw.githubusercontent.com/emdash-cms/emdash/main/assets/templates/blog/latest/homepage-light-mobile.jpg) | +| Dark | ![homepage dark desktop](https://raw.githubusercontent.com/emdash-cms/emdash/main/assets/templates/blog/latest/homepage-dark-desktop.jpg) | ![homepage dark mobile](https://raw.githubusercontent.com/emdash-cms/emdash/main/assets/templates/blog/latest/homepage-dark-mobile.jpg) | + +## Infrastructure + +- **Runtime:** Node.js +- **Database:** SQLite (local file) +- **Storage:** Local filesystem +- **Framework:** Astro with `@astrojs/node` + +## Getting Started + +```bash +pnpm install +pnpm bootstrap +pnpm dev +``` + +Open http://localhost:4321 for the site and http://localhost:4321/_emdash/admin for the CMS. + +## Want Cloudflare Instead? + +See the [Cloudflare variant](../blog-cloudflare) for a version that deploys to Cloudflare Workers with D1 and R2. + +[![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/emdash-cms/templates/tree/main/blog-cloudflare) + +## See Also + +- [All templates](../) +- [EmDash documentation](https://github.com/emdash-cms/emdash/tree/main/docs) diff --git a/astro.config.mjs b/astro.config.mjs new file mode 100644 index 0000000..6621681 --- /dev/null +++ b/astro.config.mjs @@ -0,0 +1,45 @@ +import node from "@astrojs/node"; +import react from "@astrojs/react"; +import { auditLogPlugin } from "@emdash-cms/plugin-audit-log"; +import { defineConfig, fontProviders } from "astro/config"; +import emdash, { local } from "emdash/astro"; +import { sqlite } from "emdash/db"; + +export default defineConfig({ + output: "server", + adapter: node({ + mode: "standalone", + }), + image: { + layout: "constrained", + responsiveStyles: true, + }, + integrations: [ + react(), + emdash({ + database: sqlite({ url: "file:./data.db" }), + storage: local({ + directory: "./uploads", + baseUrl: "/_emdash/api/media/file", + }), + plugins: [auditLogPlugin()], + }), + ], + fonts: [ + { + provider: fontProviders.google(), + name: "Inter", + cssVariable: "--font-sans", + weights: [400, 500, 600, 700], + fallbacks: ["sans-serif"], + }, + { + provider: fontProviders.google(), + name: "JetBrains Mono", + cssVariable: "--font-mono", + weights: [400, 500], + fallbacks: ["monospace"], + }, + ], + devToolbar: { enabled: false }, +}); diff --git a/emdash-env.d.ts b/emdash-env.d.ts new file mode 100644 index 0000000..abb2626 --- /dev/null +++ b/emdash-env.d.ts @@ -0,0 +1,39 @@ +// Generated by EmDash on dev server start +// Do not edit manually + +/// + +import type { ContentBylineCredit, PortableTextBlock } from "emdash"; + +export interface Page { + id: string; + slug: string | null; + status: string; + title: string; + content?: PortableTextBlock[]; + createdAt: Date; + updatedAt: Date; + publishedAt: Date | null; + bylines?: ContentBylineCredit[]; +} + +export interface Post { + id: string; + slug: string | null; + status: string; + title: string; + featured_image?: { id: string; src?: string; alt?: string; width?: number; height?: number }; + content?: PortableTextBlock[]; + excerpt?: string; + createdAt: Date; + updatedAt: Date; + publishedAt: Date | null; + bylines?: ContentBylineCredit[]; +} + +declare module "emdash" { + interface EmDashCollections { + pages: Page; + posts: Post; + } +} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..4c8ee00 --- /dev/null +++ b/package.json @@ -0,0 +1,37 @@ +{ + "name": "@emdash-cms/template-blog", + "version": "0.0.3", + "private": true, + "type": "module", + "emdash": { + "seed": "seed/seed.json" + }, + "scripts": { + "dev": "astro dev", + "build": "astro build", + "preview": "astro preview", + "start": "node ./dist/server/entry.mjs", + "bootstrap": "emdash init && emdash seed", + "seed": "emdash seed", + "typecheck": "astro check" + }, + "dependencies": { + "@astrojs/node": "^10.0.0", + "@astrojs/react": "^5.0.0", + "@emdash-cms/plugin-audit-log": "^0.1.1", + "astro": "^6.0.1", + "better-sqlite3": "^12.8.0", + "emdash": "^0.8.0", + "react": "19.2.4", + "react-dom": "19.2.4" + }, + "devDependencies": { + "@astrojs/check": "^0.9.7" + }, + "pnpm": { + "onlyBuiltDependencies": [ + "better-sqlite3", + "esbuild" + ] + } +} diff --git a/seed/seed.json b/seed/seed.json new file mode 100644 index 0000000..b6c7845 --- /dev/null +++ b/seed/seed.json @@ -0,0 +1,778 @@ +{ + "$schema": "https://emdashcms.com/seed.schema.json", + "version": "1", + "meta": { + "name": "Blog Starter", + "description": "A blog with posts and pages", + "author": "EmDash" + }, + + "settings": { + "title": "My Blog", + "tagline": "Thoughts on building for the web" + }, + + "collections": [ + { + "slug": "posts", + "label": "Posts", + "labelSingular": "Post", + "supports": ["drafts", "revisions", "search", "seo"], + "commentsEnabled": true, + "fields": [ + { + "slug": "title", + "label": "Title", + "type": "string", + "required": true, + "searchable": true + }, + { + "slug": "featured_image", + "label": "Featured Image", + "type": "image" + }, + { + "slug": "content", + "label": "Content", + "type": "portableText", + "searchable": true + }, + { + "slug": "excerpt", + "label": "Excerpt", + "type": "text" + } + ] + }, + { + "slug": "pages", + "label": "Pages", + "labelSingular": "Page", + "supports": ["drafts", "revisions", "search"], + "fields": [ + { + "slug": "title", + "label": "Title", + "type": "string", + "required": true, + "searchable": true + }, + { + "slug": "content", + "label": "Content", + "type": "portableText", + "searchable": true + } + ] + } + ], + + "taxonomies": [ + { + "name": "category", + "label": "Categories", + "labelSingular": "Category", + "hierarchical": true, + "collections": ["posts"], + "terms": [ + { "slug": "development", "label": "Development" }, + { "slug": "design", "label": "Design" }, + { "slug": "notes", "label": "Notes" } + ] + }, + { + "name": "tag", + "label": "Tags", + "labelSingular": "Tag", + "hierarchical": false, + "collections": ["posts"], + "terms": [ + { "slug": "webdev", "label": "Web Development" }, + { "slug": "opinion", "label": "Opinion" }, + { "slug": "tools", "label": "Tools" }, + { "slug": "creativity", "label": "Creativity" } + ] + } + ], + + "bylines": [ + { + "id": "byline-editorial", + "slug": "emdash-editorial", + "displayName": "EmDash Editorial" + }, + { + "id": "byline-guest", + "slug": "guest-contributor", + "displayName": "Guest Contributor", + "isGuest": true + } + ], + + "menus": [ + { + "name": "primary", + "label": "Primary Navigation", + "items": [ + { "type": "custom", "label": "Home", "url": "/" }, + { "type": "custom", "label": "About", "url": "/pages/about" }, + { "type": "custom", "label": "Posts", "url": "/posts" } + ] + } + ], + + "widgetAreas": [ + { + "name": "sidebar", + "label": "Sidebar", + "description": "Widget area displayed on single post pages", + "widgets": [ + { + "type": "component", + "componentId": "core:search", + "title": "Search" + }, + { + "type": "component", + "componentId": "core:categories", + "title": "Categories" + }, + { + "type": "component", + "componentId": "core:tags", + "title": "Tags" + }, + { + "type": "component", + "componentId": "core:recent-posts", + "title": "Recent Posts", + "settings": { + "count": 5, + "showDate": true + } + }, + { + "type": "component", + "componentId": "core:archives", + "title": "Archives", + "settings": { + "type": "monthly", + "limit": 6 + } + } + ] + }, + { + "name": "footer", + "label": "Footer", + "description": "Widget area displayed in the site footer", + "widgets": [ + { + "type": "content", + "title": "About", + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "A blog about software, design, and the occasional stray thought." + } + ] + } + ] + } + ] + } + ], + + "sections": [ + { + "slug": "newsletter-signup", + "title": "Newsletter Signup", + "description": "A call-to-action block for newsletter subscriptions", + "keywords": ["newsletter", "subscribe", "email", "cta"], + "source": "theme", + "content": [ + { + "_type": "block", + "style": "h3", + "children": [{ "_type": "span", "text": "Stay in the loop" }] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Get notified when new posts are published. No spam, unsubscribe anytime." + } + ] + } + ] + }, + { + "slug": "about-author", + "title": "About the Author", + "description": "Brief author bio for use in posts or pages", + "keywords": ["author", "bio", "about"], + "source": "theme", + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "A software developer who writes about building things on the web. Based somewhere with good coffee and reliable internet." + } + ] + } + ] + } + ], + + "content": { + "pages": [ + { + "id": "about", + "slug": "about", + "status": "published", + "data": { + "title": "About", + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "A place for writing about software, design, and the occasional stray thought. No posting schedule, no newsletter funnel. Just things I wanted to write down." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Built with Astro and EmDash. The source is open if you want to see how it works." + } + ] + } + ] + } + } + ], + "posts": [ + { + "id": "post-1", + "slug": "building-for-the-long-term", + "status": "published", + "data": { + "title": "Building for the Long Term", + "excerpt": "The frameworks will change. The databases will change. What survives is the clarity of your thinking.", + "featured_image": { + "$media": { + "url": "https://images.unsplash.com/photo-1461749280684-dccba630e2f6?w=1200&h=800&fit=crop", + "alt": "Code on a monitor in a dark room", + "filename": "building-long-term.jpg" + } + }, + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Every few years the industry collectively decides that everything we've been doing is wrong and there's a better way. New frameworks, new paradigms, new build tools. The churn is relentless, and if you're not careful, you spend more time migrating than building." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "I've been writing software long enough to have seen several of these cycles. jQuery to Backbone to Angular to React to whatever comes next. Each transition felt urgent at the time. Looking back, the things that actually mattered were rarely about the framework." + } + ] + }, + { + "_type": "block", + "style": "h2", + "children": [{ "_type": "span", "text": "What survives" }] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Clean data models survive. Clear boundaries between systems survive. Good naming survives. The decision to keep things simple when you could have made them clever - that definitely survives." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "What doesn't survive is code that was written to impress, abstractions built for problems that never materialized, and architectures designed around a framework's opinions rather than the domain's reality." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "The best code I've written is boring. It reads like prose, does one thing well, and doesn't require a PhD in category theory to understand. The worst code I've written was technically impressive at the time." + } + ] + } + ] + }, + "bylines": [ + { "byline": "byline-editorial" }, + { "byline": "byline-guest", "roleLabel": "Guest essay" } + ], + "taxonomies": { + "category": ["development"], + "tag": ["opinion"] + } + }, + { + "id": "post-2", + "slug": "the-case-for-static", + "status": "published", + "data": { + "title": "The Case for Static", + "excerpt": "Static sites aren't a step backwards. They're what you get when you take performance and simplicity seriously.", + "featured_image": { + "$media": { + "url": "https://images.unsplash.com/photo-1499750310107-5fef28a66643?w=1200&h=800&fit=crop", + "alt": "Laptop and coffee on a wooden table", + "filename": "case-for-static.jpg" + } + }, + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "There's a certain irony in the fact that the web started static, went dynamic, and is now swinging back toward static again. But the static sites of today aren't the hand-coded HTML pages of 1998. They're generated, optimized, and deployed to edge networks that serve them in milliseconds." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "The pitch for server-rendered everything was compelling: dynamic content, personalization, real-time data. But most sites don't need most of that most of the time. A blog post doesn't need to be rendered on every request. A product page doesn't change every second." + } + ] + }, + { + "_type": "block", + "style": "h2", + "children": [{ "_type": "span", "text": "The performance argument" }] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "A static file served from a CDN is as fast as the web gets. No cold starts, no database queries, no server-side rendering overhead. The Time to First Byte is essentially the network latency to your nearest edge node. You can't beat physics." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "And when you do need dynamic behavior, you can add it surgically. An island of interactivity in a sea of static HTML. The best of both worlds, without paying the cost of either at all times." + } + ] + } + ] + }, + "bylines": [{ "byline": "byline-editorial" }], + "taxonomies": { + "category": ["development"], + "tag": ["webdev", "opinion"] + } + }, + { + "id": "post-3", + "slug": "learning-in-public", + "status": "published", + "data": { + "title": "Learning in Public", + "excerpt": "Writing about what you're learning is the fastest way to find out what you don't actually understand.", + "featured_image": { + "$media": { + "url": "https://images.unsplash.com/photo-1432821596592-e2c18b78144f?w=1200&h=800&fit=crop", + "alt": "Notebook and pen on a desk", + "filename": "learning-in-public.jpg" + } + }, + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "I started writing about things I was learning not because I had anything original to say, but because I kept forgetting what I'd figured out. The blog posts were notes to my future self, published publicly more out of laziness than courage." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "What I didn't expect was how much the writing itself would accelerate the learning. There's a particular kind of clarity that comes from trying to explain something to someone else. The gaps in your understanding, which you can happily ignore when the knowledge lives only in your head, become painfully obvious when you try to put it into sentences." + } + ] + }, + { + "_type": "block", + "style": "h2", + "children": [{ "_type": "span", "text": "The fear of being wrong" }] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "The biggest barrier isn't time or writing skill. It's the fear of publishing something that turns out to be wrong. But here's the thing: being wrong publicly is one of the most efficient ways to learn. Someone will correct you, often kindly, and you'll remember that correction forever." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "The posts that helped me most weren't written by experts. They were written by people one step ahead of me on the same path, in language that hadn't yet been polished into abstraction. There's a place for that kind of writing, and it's more valuable than most people realize." + } + ] + } + ] + }, + "taxonomies": { + "category": ["notes"], + "tag": ["opinion"] + } + }, + { + "id": "post-4", + "slug": "small-tools-big-impact", + "status": "published", + "data": { + "title": "Small Tools, Big Impact", + "excerpt": "The best developer tools do one thing well and get out of your way. A love letter to focused software.", + "featured_image": { + "$media": { + "url": "https://images.unsplash.com/photo-1575026615908-666710ae5e47?w=1200&h=800&fit=crop", + "alt": "Wrenches and hand tools hanging on a workshop wall", + "filename": "small-tools.jpg" + } + }, + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "There's a class of software that doesn't get enough appreciation. Not the frameworks or the platforms or the IDEs, but the small, sharp tools that solve one problem so well you stop thinking about them. They become invisible, which is the highest compliment you can pay a tool." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "I'm talking about things like ripgrep, which searches code so fast it changed how I think about searching. Or jq, which makes JSON feel like a first-class data format in the terminal. Or curl, which has been quietly powering the internet's plumbing for decades." + } + ] + }, + { + "_type": "block", + "style": "h2", + "children": [{ "_type": "span", "text": "The Unix philosophy, revisited" }] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Do one thing well. The advice is old enough to be a cliche, but the best modern tools still follow it. They don't try to be platforms. They don't have plugin ecosystems or configuration languages or startup wizards. They do their job and they compose with other tools that do theirs." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "The temptation is always to add more. One more feature, one more option, one more integration. But every addition is a decision someone has to make, a path through the code that has to be maintained, a thing that can break. The best tools resist this. They stay small, and in staying small, they stay reliable." + } + ] + } + ] + }, + "taxonomies": { + "category": ["development"], + "tag": ["tools"] + } + }, + { + "id": "post-5", + "slug": "designing-with-constraints", + "status": "published", + "data": { + "title": "Designing with Constraints", + "excerpt": "Limitations aren't obstacles to creativity. They're the structure that makes creativity possible.", + "featured_image": { + "$media": { + "url": "https://images.unsplash.com/photo-1513542789411-b6a5d4f31634?w=1200&h=800&fit=crop", + "alt": "Pencils and design tools on a desk", + "filename": "designing-with-constraints.jpg" + } + }, + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Give a designer a blank canvas and unlimited time, and they'll often produce something mediocre. Give them a tight brief, a small screen, and a deadline, and they'll surprise you. This isn't a paradox - it's how creativity actually works." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Constraints force decisions. When you can't use more than two typefaces, you have to choose carefully. When the page has to load in under a second, every element earns its place. When the interface has to work on a 320px screen, you discover what's truly essential." + } + ] + }, + { + "_type": "block", + "style": "h2", + "children": [{ "_type": "span", "text": "Embracing the box" }] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "The web itself is a constraint. HTML flows in one direction. CSS has a box model. Browsers have viewport sizes and font rendering quirks. You can fight these constraints or you can work with them, and the results are dramatically different." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "The designs I admire most don't look like they were forced through a framework. They look like they grew naturally from the medium, respecting its grain rather than working against it. That only happens when you treat constraints as creative partners rather than enemies." + } + ] + } + ] + }, + "taxonomies": { + "category": ["design"], + "tag": ["creativity"] + } + }, + { + "id": "post-6", + "slug": "a-weekend-with-a-side-project", + "status": "published", + "data": { + "title": "A Weekend with a Side Project", + "excerpt": "No stakeholders, no deadlines, no Jira tickets. Just you and a dumb idea that might turn into something.", + "featured_image": { + "$media": { + "url": "https://images.unsplash.com/photo-1542831371-29b0f74f9713?w=1200&h=800&fit=crop", + "alt": "Code on a screen with a dark theme", + "filename": "weekend-side-project.jpg" + } + }, + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Saturday morning. Coffee's made, the house is quiet, and I've got an idea that's been nagging at me all week. Not a good idea, necessarily - just a persistent one. A small tool that does a thing I keep doing manually. How hard could it be?" + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "This is the best kind of programming. No requirements document, no sprint planning, no pull request reviews. Just a text editor and a problem. The freedom to make terrible architectural decisions, rewrite everything twice, and follow tangents that turn out to be dead ends." + } + ] + }, + { + "_type": "block", + "style": "h2", + "children": [{ "_type": "span", "text": "Why side projects matter" }] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Side projects are where you learn things your day job would never teach you. Not because the problems are harder, but because you're free to take risks. Try a language you've never used. Build something without a framework. Deploy to a platform you've only read about. The stakes are zero, which makes the learning maximum." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "By Sunday evening, the thing sort of works. It's rough, the error handling is nonexistent, and the README is a single sentence. But it solves the problem I set out to solve, and I learned three things I didn't know on Friday. Not a bad weekend." + } + ] + } + ] + }, + "taxonomies": { + "category": ["development"], + "tag": ["creativity"] + } + }, + { + "id": "post-7", + "slug": "notes-on-simplicity", + "status": "published", + "data": { + "title": "Notes on Simplicity", + "excerpt": "Simplicity isn't the absence of complexity. It's the result of understanding a problem well enough to solve it cleanly.", + "featured_image": { + "$media": { + "url": "https://images.unsplash.com/photo-1559051668-e1fa58f25786?w=1200&h=800&fit=crop", + "alt": "Geometric pattern carved into white paper", + "filename": "notes-on-simplicity.jpg" + } + }, + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Every piece of software starts simple. A few files, a clear purpose, a small surface area. Then features get added, edge cases get handled, and before long you're looking at something that requires a diagram to understand. This isn't inevitable, but it takes discipline to prevent." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "The hard part of simplicity isn't the initial design. It's the ongoing resistance to complication. Every feature request, every bug fix, every refactor is an opportunity to add complexity. Saying no is the most important design skill, and the least celebrated." + } + ] + }, + { + "_type": "block", + "style": "h2", + "children": [{ "_type": "span", "text": "Removing as a feature" }] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "The best version of a product often has fewer features than the previous one. Not because features were missing, but because someone had the courage to remove things that weren't earning their keep. Every feature has a cost - in maintenance, in cognitive load, in the weight of the interface." + } + ] + }, + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "Simplicity is a practice, not a destination. You never arrive at simple. You just keep asking: is this necessary? Could this be clearer? Is there a way to solve this problem by removing something instead of adding something? The answer is yes more often than you'd expect." + } + ] + } + ] + }, + "taxonomies": { + "category": ["notes"], + "tag": ["opinion"] + } + }, + { + "id": "post-draft", + "slug": "work-in-progress", + "status": "draft", + "data": { + "title": "Work in Progress", + "excerpt": "This post is still being written.", + "content": [ + { + "_type": "block", + "style": "normal", + "children": [ + { + "_type": "span", + "text": "This is a draft post that won't appear in the public listing." + } + ] + } + ] + } + } + ] + } +} diff --git a/src/components/PostCard.astro b/src/components/PostCard.astro new file mode 100644 index 0000000..500fbac --- /dev/null +++ b/src/components/PostCard.astro @@ -0,0 +1,279 @@ +--- +import type { MediaValue, ContentBylineCredit } from "emdash"; +import { Image } from "emdash/ui"; + +interface Props { + title: string; + excerpt?: string; + featuredImage?: MediaValue | string; + href: string; + date?: Date; + readingTime?: number; + tags?: Array<{ slug: string; label: string }>; + bylines?: ContentBylineCredit[]; +} + +const { + title, + excerpt, + featuredImage, + href, + date, + readingTime, + tags, + bylines, +} = Astro.props; + +const formattedDate = date + ? date.toLocaleDateString("en-US", { + year: "numeric", + month: "short", + day: "numeric", + }) + : null; +--- + +
+ + { + featuredImage ? ( +
+ +
+ ) : ( +
+ + diff --git a/src/components/TagList.astro b/src/components/TagList.astro new file mode 100644 index 0000000..d93122d --- /dev/null +++ b/src/components/TagList.astro @@ -0,0 +1,45 @@ +--- +interface Props { + tags: Array<{ slug: string; label: string }>; + class?: string; +} + +const { tags, class: className } = Astro.props; +--- + +{tags.length > 0 && ( + +)} + + diff --git a/src/layouts/Base.astro b/src/layouts/Base.astro new file mode 100644 index 0000000..b74aaa9 --- /dev/null +++ b/src/layouts/Base.astro @@ -0,0 +1,1011 @@ +--- +import { getMenu, getEmDashCollection, getSiteSettings } from "emdash"; +import { + WidgetArea, + EmDashHead, + EmDashBodyStart, + EmDashBodyEnd, +} from "emdash/ui"; +import { createPublicPageContext } from "emdash/page"; +import LiveSearch from "emdash/ui/search"; +import { Font } from "astro:assets"; +import { resolveBlogSiteIdentity } from "../utils/site-identity"; +import "../styles/theme.css"; + +interface Props { + title: string; + pageTitle?: string | null; + description?: string | null; + image?: string | null; + canonical?: string | null; + robots?: string | null; + type?: "website" | "article"; + publishedTime?: string | null; + modifiedTime?: string | null; + author?: string | null; + /** Pass content reference for plugin page contributions on content pages */ + content?: { collection: string; id: string; slug?: string | null }; +} + +const { + title, + pageTitle, + description, + image, + canonical, + robots, + type = "website", + publishedTime, + modifiedTime, + author, + content, +} = Astro.props; +const { siteTitle, siteTagline, siteLogo, siteFavicon } = resolveBlogSiteIdentity(await getSiteSettings()); +// If title already includes site title (from getSeoMeta), use as-is +const fullTitle = title.includes(siteTitle) ? title : `${title} — ${siteTitle}`; + +// Fetch primary menu defined in seed +const menu = await getMenu("primary"); + +// Fetch pages for footer +const { entries: pages } = await getEmDashCollection("pages"); + +// Build public page context for plugin contributions +// SEO data is passed here and rendered securely by EmDashHead +const pageCtx = createPublicPageContext({ + Astro, + kind: content ? "content" : "custom", + pageType: type, + title: fullTitle, + pageTitle: pageTitle ?? title, + description, + canonical, + image, + content, + seo: { ogImage: image, robots }, + articleMeta: { publishedTime, modifiedTime, author }, + siteName: siteTitle, +}); + +// Check if user is logged in (for showing admin link) +const isLoggedIn = !!Astro.locals.user; +--- + + + + + + + + + {fullTitle} + {siteFavicon && } + + + + + + + +
+ +
+ + + + + + + + + + + + + diff --git a/src/live.config.ts b/src/live.config.ts new file mode 100644 index 0000000..c8c819d --- /dev/null +++ b/src/live.config.ts @@ -0,0 +1,13 @@ +/** + * EmDash Live Content Collections + * + * Defines the _emdash collection that handles all content types from the database. + * Query specific types using getEmDashCollection() and getEmDashEntry(). + */ + +import { defineLiveCollection } from "astro:content"; +import { emdashLoader } from "emdash/runtime"; + +export const collections = { + _emdash: defineLiveCollection({ loader: emdashLoader() }), +}; diff --git a/src/pages/404.astro b/src/pages/404.astro new file mode 100644 index 0000000..0078a14 --- /dev/null +++ b/src/pages/404.astro @@ -0,0 +1,33 @@ +--- +import Base from "../layouts/Base.astro"; +--- + + +
+

404

+

The page you're looking for doesn't exist.

+ Go back home +
+ + + diff --git a/src/pages/category/[slug].astro b/src/pages/category/[slug].astro new file mode 100644 index 0000000..6920785 --- /dev/null +++ b/src/pages/category/[slug].astro @@ -0,0 +1,129 @@ +--- +import { + getTerm, + getEmDashCollection, + getTermsForEntries, + decodeSlug, +} from "emdash"; +import Base from "../../layouts/Base.astro"; +import PostCard from "../../components/PostCard.astro"; +import { getReadingTime } from "../../utils/reading-time"; + +const slug = decodeSlug(Astro.params.slug); +const term = slug ? await getTerm("category", slug) : null; + +if (!term) { + return Astro.redirect("/404"); +} + +const { entries: posts, cacheHint } = await getEmDashCollection("posts", { + where: { category: term.slug }, + orderBy: { published_at: "desc" }, +}); + +Astro.cache.set(cacheHint); + +// Single batched query for tags on every post in this category, rather +// than calling getEntryTerms() per post (which would be one round-trip +// per post). +const tagsByEntry = await getTermsForEntries( + "posts", + posts.map((p) => p.data.id), + "tag", +); +const filteredPosts = posts.map((post) => ({ + post, + tags: tagsByEntry.get(post.data.id) ?? [], +})); +--- + + +
+
+ Category +

{term.label}

+

+ {filteredPosts.length} + {filteredPosts.length === 1 ? "post" : "posts"} +

+
+ + { + filteredPosts.length === 0 ? ( +

No posts in this category yet.

+ ) : ( +
+ {filteredPosts.map(({ post, tags }) => ( + ({ slug: t.slug, label: t.label }))} + /> + ))} +
+ ) + } +
+ + + diff --git a/src/pages/index.astro b/src/pages/index.astro new file mode 100644 index 0000000..80cc658 --- /dev/null +++ b/src/pages/index.astro @@ -0,0 +1,544 @@ +--- +import { getSiteSettings } from "emdash"; +import Base from "../layouts/Base.astro"; + +const settings = await getSiteSettings(); +--- + +
+ +
+
+
Open Source • 10k+ Stars
+

+ The CMS that
+ runs on your server +

+

+ EmDash is a full-stack TypeScript CMS built on Astro. + No cloud account required, no external dependencies. + Just a complete admin panel and your content. +

+ +
+
+
+
+ + + + astro.config.mjs +
+
import emdash from "emdash/astro";
+import { betterSqlite } from "emdash/db";
+
+export default defineConfig({
+  integrations: [
+    emdash({
+      database: betterSqlite({
+        databasePath: "./data.db"
+      }),
+    }),
+  ],
+});
+
+
+
+ + +
+
+

Everything you need

+

A complete CMS without the vendor lock-in

+
+
+
+
+ + + + + +
+

Fully Self-Hosted

+

+ SQLite, D1, Turso, or PostgreSQL. Your data stays on your servers. + No cloud account required. +

+
+
+
+ + + + +
+

Admin Panel

+

+ Visual schema builder, media library, navigation menus. + Full admin at /_emdash/admin +

+
+
+
+ + + +
+

Passkey Auth

+

+ WebAuthn passkey-first authentication with OAuth and magic link fallbacks. + Role-based access control. +

+
+
+
+ + + + +
+

Built-in MCP

+

+ Model Context Protocol server for AI tools. + Claude and ChatGPT can interact with your site directly. +

+
+
+
+ + + + +
+

Plugin System

+

+ Sandboxed plugins on Cloudflare Workers. + Define capabilities, run safely in isolation. +

+
+
+
+ + + + + + +
+

WordPress Import

+

+ Import posts, pages, media, and taxonomies from WXR exports, + REST API, or WordPress.com. +

+
+
+
+ + +
+
+

EmDash vs Tina CMS

+

Both work with Astro, but differ in approach

+
+
+
+
Feature
+
EmDash
+
Tina CMS
+
+
+
Self-hosted
+
Fully local (SQLite)
+
Needs Tina Cloud
+
+
+
Admin URL
+
/_emdash/admin
+
/admin
+
+
+
Database
+
SQLite, D1, PostgreSQL
+
Git-based
+
+
+
Setup
+
Template-based
+
Manual config
+
+
+
Auth
+
Passkey + OAuth
+
Git-based
+
+
+
Price
+
Free (open source)
+
Free tier + paid plans
+
+
+
+ + +
+
+

Ready to get started?

+

+ Clone the template, run bootstrap, and you're ready to build. +

+ +
+
+
+ + + \ No newline at end of file diff --git a/src/pages/pages/[slug].astro b/src/pages/pages/[slug].astro new file mode 100644 index 0000000..2e81625 --- /dev/null +++ b/src/pages/pages/[slug].astro @@ -0,0 +1,108 @@ +--- +import { getEmDashEntry, decodeSlug } from "emdash"; +import { PortableText } from "emdash/ui"; +import Base from "../../layouts/Base.astro"; + +const slug = decodeSlug(Astro.params.slug); + +if (!slug) { + return Astro.redirect("/404"); +} + +const { entry: page, cacheHint } = await getEmDashEntry("pages", slug); + +if (!page) { + return Astro.redirect("/404"); +} + +Astro.cache.set(cacheHint); +--- + + +
+ + +
+ +
+
+ + + diff --git a/src/pages/posts/[slug].astro b/src/pages/posts/[slug].astro new file mode 100644 index 0000000..1549fd5 --- /dev/null +++ b/src/pages/posts/[slug].astro @@ -0,0 +1,970 @@ +--- +import { + getEmDashEntry, + getEmDashCollection, + getEntryTerms, + getTermsForEntries, + getSeoMeta, + decodeSlug, + getSiteSettings, +} from "emdash"; +import { + Image, + PortableText, + Comments, + CommentForm, + WidgetArea, +} from "emdash/ui"; +import Base from "../../layouts/Base.astro"; +import PostCard from "../../components/PostCard.astro"; +import { getReadingTime } from "../../utils/reading-time"; +import { resolveBlogSiteIdentity } from "../../utils/site-identity"; + +const slug = decodeSlug(Astro.params.slug); + +if (!slug) { + return Astro.redirect("/404"); +} + +const { entry: post, cacheHint } = await getEmDashEntry("posts", slug); + +if (!post) { + return Astro.redirect("/404"); +} + +Astro.cache.set(cacheHint); + +// Get featured image URL for OG fallback +// The image may have src (external) or meta.storageKey (local) +function getImageUrl(img: unknown): string | undefined { + if (!img || typeof img !== "object") return undefined; + const image = img as Record; + // Check for direct src + if (typeof image.src === "string" && image.src) { + return image.src.startsWith("http") + ? image.src + : `${Astro.url.origin}${image.src}`; + } + // Build from storageKey for local images + const meta = image.meta as Record | undefined; + const storageKey = + (typeof meta?.storageKey === "string" ? meta.storageKey : undefined) || + (typeof image.id === "string" ? image.id : undefined); + if (storageKey) { + return `${Astro.url.origin}/_emdash/api/media/file/${storageKey}`; + } + return undefined; +} +const featuredImageUrl = getImageUrl(post.data.featured_image); +const { siteTitle } = resolveBlogSiteIdentity(await getSiteSettings()); + +// Generate SEO meta from content +const seo = getSeoMeta(post, { + siteTitle, + siteUrl: Astro.url.origin, + path: `/posts/${slug}`, + defaultOgImage: featuredImageUrl, +}); + +// Bylines are already hydrated by getEmDashEntry +const bylines = post.data.bylines ?? []; + +// Get reading time +const readingTime = getReadingTime(post.data.content); + +// Fetch this post's tags and the related-posts list in parallel — they're +// independent queries, so running them concurrently halves the round-trip +// cost on remote databases. +// Note: post.id is the slug, post.data.id is the database ULID. +const [tags, { entries: recentPosts }] = await Promise.all([ + getEntryTerms("posts", post.data.id, "tag"), + // Fetch a few extra in case the current post is among them + getEmDashCollection("posts", { + orderBy: { published_at: "desc" }, + limit: 4, + }), +]); +const otherPosts = recentPosts.filter((p) => p.id !== post.id).slice(0, 3); + +// Single batched query for related-posts tags, rather than one +// getEntryTerms() call per related post. +const otherTagsByEntry = await getTermsForEntries( + "posts", + otherPosts.map((p) => p.data.id), + "tag", +); +const otherPostsWithTags = otherPosts.map((p) => ({ + post: p, + tags: otherTagsByEntry.get(p.data.id) ?? [], + bylines: p.data.bylines ?? [], +})); + +const publishDate = + post.data.publishedAt?.toLocaleDateString("en-US", { + year: "numeric", + month: "long", + day: "numeric", + }) ?? null; +--- + + +
+ {/* Hero: Full-width featured image */} + { + post.data.featured_image && ( +
+ +
+ ) + } + + {/* Three-column layout */} +
+ {/* Left gutter: Meta information */} + + + {/* Main content */} +
+
+ +

{post.data.title}

+ { + post.data.excerpt && ( +

{post.data.excerpt}

+ ) + } +
+ +
+ +
+ +
+ + +
+
+ + {/* Right gutter: TOC + Sidebar widgets */} + +
+
+ + { + otherPostsWithTags.length > 0 && ( + + ) + } + + + + + diff --git a/src/pages/posts/index.astro b/src/pages/posts/index.astro new file mode 100644 index 0000000..d58dce8 --- /dev/null +++ b/src/pages/posts/index.astro @@ -0,0 +1,272 @@ +--- +import { getEmDashCollection, getTermsForEntries } from "emdash"; +import Base from "../../layouts/Base.astro"; +import { getReadingTime } from "../../utils/reading-time"; + +// Sort in the database rather than in JS — lets the DB use its index on +// published_at and avoids a full-table scan on the client. +const { entries: posts, cacheHint } = await getEmDashCollection("posts", { + orderBy: { published_at: "desc" }, +}); + +Astro.cache.set(cacheHint); + +// Single batched query for tags across all posts, instead of one +// getEntryTerms() call per post (which would be N round-trips). +// Bylines are already hydrated on entry.data.bylines. +const tagsByEntry = await getTermsForEntries( + "posts", + posts.map((p) => p.data.id), + "tag", +); + +const postsWithTags = posts.map((post) => ({ + post, + tags: tagsByEntry.get(post.data.id) ?? [], + bylines: post.data.bylines ?? [], +})); + +const formatDate = (date: Date) => + date.toLocaleDateString("en-US", { + year: "numeric", + month: "long", + day: "numeric", + }); +--- + + + + + + diff --git a/src/pages/rss.xml.ts b/src/pages/rss.xml.ts new file mode 100644 index 0000000..2ea40db --- /dev/null +++ b/src/pages/rss.xml.ts @@ -0,0 +1,70 @@ +import type { APIRoute } from "astro"; +import { getEmDashCollection, getSiteSettings } from "emdash"; + +import { resolveBlogSiteIdentity } from "../utils/site-identity"; + +export const GET: APIRoute = async ({ site, url }) => { + const siteUrl = site?.toString() || url.origin; + const { siteTitle, siteTagline } = resolveBlogSiteIdentity(await getSiteSettings()); + + const { entries: posts } = await getEmDashCollection("posts", { + orderBy: { published_at: "desc" }, + limit: 20, + }); + + const items = posts + .map((post) => { + if (!post.data.publishedAt) return null; + const pubDate = post.data.publishedAt.toUTCString(); + + const postUrl = `${siteUrl}/posts/${post.id}`; + const title = escapeXml(post.data.title || "Untitled"); + const description = escapeXml(post.data.excerpt || ""); + + return ` + ${title} + ${postUrl} + ${postUrl} + ${pubDate} + ${description} + `; + }) + .filter(Boolean) + .join("\n"); + + const rss = ` + + + ${escapeXml(siteTitle)} + ${escapeXml(siteTagline)} + ${siteUrl} + + en-us + ${new Date().toUTCString()} +${items} + +`; + + return new Response(rss, { + headers: { + "Content-Type": "application/rss+xml; charset=utf-8", + "Cache-Control": "public, max-age=3600", + }, + }); +}; + +const XML_ESCAPE_PATTERNS = [ + [/&/g, "&"], + [//g, ">"], + [/"/g, """], + [/'/g, "'"], +] as const; + +function escapeXml(str: string): string { + let result = str; + for (const [pattern, replacement] of XML_ESCAPE_PATTERNS) { + result = result.replace(pattern, replacement); + } + return result; +} diff --git a/src/pages/search.astro b/src/pages/search.astro new file mode 100644 index 0000000..98e8a4e --- /dev/null +++ b/src/pages/search.astro @@ -0,0 +1,182 @@ +--- +export const prerender = false; + +import { search } from "emdash"; +import Base from "../layouts/Base.astro"; + +const query = Astro.url.searchParams.get("q")?.trim() || ""; + +// Use the FTS-backed search() API instead of loading every post and +// filtering in JS. FTS scales as the post count grows, returns ranked +// results, and handles tokenization/stemming. Templates that grep all +// post bodies in JS quickly become unusable past a few hundred posts. +const { items: results } = query + ? await search(query, { collections: ["posts"], limit: 30 }) + : { items: [] }; +--- + + +
+

Search

+ +
+ + +
+ + { + query && ( +

+ {results.length === 0 + ? `No results for "${query}"` + : `${results.length} result${results.length === 1 ? "" : "s"} for "${query}"`} +

+ ) + } + + { + results.length > 0 && ( +
    + {results.map((result) => ( +
  1. + +

    + {result.title ?? "Untitled"} +

    + {result.snippet && ( +

    + )} + +

  2. + ))} +
+ ) + } + + {!query &&

Enter a search term to find posts.

} +
+ + + diff --git a/src/pages/tag/[slug].astro b/src/pages/tag/[slug].astro new file mode 100644 index 0000000..262f238 --- /dev/null +++ b/src/pages/tag/[slug].astro @@ -0,0 +1,131 @@ +--- +import { + getTerm, + getEmDashCollection, + getTermsForEntries, + decodeSlug, +} from "emdash"; +import Base from "../../layouts/Base.astro"; +import PostCard from "../../components/PostCard.astro"; +import { getReadingTime } from "../../utils/reading-time"; + +const slug = decodeSlug(Astro.params.slug); +const term = slug ? await getTerm("tag", slug) : null; + +if (!term) { + return Astro.redirect("/404"); +} + +const { entries: posts, cacheHint } = await getEmDashCollection("posts", { + where: { tag: term.slug }, + orderBy: { published_at: "desc" }, +}); + +Astro.cache.set(cacheHint); + +// Single batched query for tags on every post tagged with this term, +// rather than calling getEntryTerms() per post. +const tagsByEntry = await getTermsForEntries( + "posts", + posts.map((p) => p.data.id), + "tag", +); +const filteredPosts = posts.map((post) => ({ + post, + tags: tagsByEntry.get(post.data.id) ?? [], +})); +--- + + +
+
+ Tag +

{term.label}

+

+ {filteredPosts.length} + {filteredPosts.length === 1 ? "post" : "posts"} +

+
+ + { + filteredPosts.length === 0 ? ( +

No posts with this tag yet.

+ ) : ( +
+ {filteredPosts.map(({ post, tags }) => ( + ({ slug: t.slug, label: t.label }))} + /> + ))} +
+ ) + } +
+ + + diff --git a/src/styles/theme.css b/src/styles/theme.css new file mode 100644 index 0000000..2f7249b --- /dev/null +++ b/src/styles/theme.css @@ -0,0 +1,108 @@ +/* + theme.css -- override any :root variable here to retheme the blog. + + This is the only file you need to edit to customize the site's visual + appearance. All defaults are listed below as comments. Uncomment and + change any value to override it. + + Base.astro puts its defaults inside @layer base, so declarations here + (which are unlayered) always take priority -- no specificity tricks needed. + + Note: this template defines explicit dark mode colors in Base.astro. + Overriding light-mode --color-* variables here won't affect dark mode. + To customize dark mode, also override --color-* variables inside a + @media (prefers-color-scheme: dark) block and/or in the :root.dark rule. +*/ + +:root { + /* --- Colors --- + --color-bg: #ffffff; + --color-bg-subtle: #fafafa; + --color-text: #1a1a1a; + --color-text-secondary: #525252; + --color-muted: #8b8b8b; + --color-border: #e5e5e5; + --color-border-subtle: #f0f0f0; + --color-surface: #f7f7f7; + --color-accent: #0066cc; + --color-accent-hover: #0052a3; + --color-on-accent: white; + --color-accent-ring: color-mix(in srgb, var(--color-accent) 25%, transparent); + */ + + /* --- Type scale --- + --font-size-xs: 0.8125rem; + --font-size-sm: 0.875rem; + --font-size-base: 1rem; + --font-size-lg: 1.125rem; + --font-size-xl: 1.25rem; + --font-size-2xl: 1.5rem; + --font-size-3xl: 2rem; + --font-size-4xl: 2.5rem; + --font-size-5xl: 3.5rem; + */ + + /* --- Line heights --- + --leading-tight: 1.15; + --leading-snug: 1.3; + --leading-normal: 1.5; + --leading-relaxed: 1.7; + */ + + /* --- Letter spacing --- + --tracking-tight: -0.03em; used on h1 and large titles + --tracking-snug: -0.02em; used on h2–h6, site/card titles + --tracking-wide: 0.06em; used on meta labels, TOC/widget titles + --tracking-wider: 0.08em; used on footer headings, section labels + */ + + /* --- Spacing --- + --spacing-1: 0.25rem; + --spacing-2: 0.5rem; + --spacing-3: 0.75rem; + --spacing-4: 1rem; + --spacing-5: 1.25rem; + --spacing-6: 1.5rem; + --spacing-8: 2rem; + --spacing-10: 2.5rem; + --spacing-12: 3rem; + --spacing-16: 4rem; + --spacing-20: 5rem; + --spacing-24: 6rem; + */ + + /* --- Layout --- + --content-width: 680px; article/page body column width + --wide-width: 1200px; max container width (home, archives) + --gutter-width: 200px; right sidebar column (TOC) on article pages + --meta-col-width: 180px; left meta column on article pages + --nav-height: 64px; sticky header height + --search-input-width: 180px; nav search box width + */ + + /* --- Borders & radius --- + --radius: 4px; + --radius-lg: 8px; + */ + + /* --- Transitions --- + --transition-fast: 120ms ease; + --transition-base: 180ms ease; + */ + + /* --- Avatars --- + --avatar-size-xs: 18px; card byline avatars + --avatar-size-sm: 20px; post list byline avatars + --avatar-size-md: 24px; featured post byline avatars + --avatar-size-lg: 32px; single post byline avatars + */ + + /* --- Shadows --- + --shadow-dropdown: 0 8px 30px rgba(0, 0, 0, 0.12); + --shadow-btn-active: 0 1px 2px rgba(0, 0, 0, 0.05); + */ + + /* --- Misc --- + --tag-padding-y: 2px; vertical padding on tag pills + */ +} diff --git a/src/utils/reading-time.ts b/src/utils/reading-time.ts new file mode 100644 index 0000000..c17794e --- /dev/null +++ b/src/utils/reading-time.ts @@ -0,0 +1,66 @@ +import type { PortableTextBlock } from "emdash"; + +const WORDS_PER_MINUTE = 200; +const CJK_CHARACTERS_PER_MINUTE = 500; +const WHITESPACE_REGEX = /\s+/; +const CJK_CHARACTER_REGEX = + /\p{Script=Han}|\p{Script=Hangul}|\p{Script=Hiragana}|\p{Script=Katakana}/gu; + +type PortableTextSpan = { + _type: string; + text?: string; +}; + +type PortableTextTextBlock = PortableTextBlock & { + _type: "block"; + children: PortableTextSpan[]; +}; + +function isTextBlock(block: PortableTextBlock): block is PortableTextTextBlock { + return block._type === "block" && Array.isArray(block.children); +} + +function countWords(text: string): number { + return text.split(WHITESPACE_REGEX).filter(Boolean).length; +} + +function countCjkCharacters(text: string): number { + return text.match(CJK_CHARACTER_REGEX)?.length ?? 0; +} + +/** + * Extract plain text from Portable Text blocks + */ +export function extractText(blocks: PortableTextBlock[] | undefined): string { + if (!blocks || !Array.isArray(blocks)) return ""; + + return blocks + .filter(isTextBlock) + .map((block) => + block.children + .filter((child) => child._type === "span" && typeof child.text === "string") + .map((span) => span.text) + .join(""), + ) + .join(" "); +} + +/** + * Calculate reading time in minutes from Portable Text content + */ +export function getReadingTime(content: PortableTextBlock[] | undefined): number { + const text = extractText(content); + const cjkCharacterCount = countCjkCharacters(text); + const wordCount = countWords(text.replace(CJK_CHARACTER_REGEX, " ")); + const minutes = Math.ceil( + wordCount / WORDS_PER_MINUTE + cjkCharacterCount / CJK_CHARACTERS_PER_MINUTE, + ); + return Math.max(1, minutes); +} + +/** + * Format reading time for display + */ +export function formatReadingTime(minutes: number): string { + return `${minutes} min read`; +} diff --git a/src/utils/site-identity.ts b/src/utils/site-identity.ts new file mode 100644 index 0000000..0dfa7a5 --- /dev/null +++ b/src/utils/site-identity.ts @@ -0,0 +1,25 @@ +/** Resolved media reference from getSiteSettings() */ +export interface MediaReference { + mediaId: string; + alt?: string; + url?: string; +} + +export interface BlogSiteIdentitySettings { + title?: string; + tagline?: string; + logo?: MediaReference; + favicon?: MediaReference; +} + +const DEFAULT_SITE_TITLE = "My Blog"; +const DEFAULT_SITE_TAGLINE = "Thoughts, stories, and ideas."; + +export function resolveBlogSiteIdentity(settings?: BlogSiteIdentitySettings) { + return { + siteTitle: settings?.title ?? DEFAULT_SITE_TITLE, + siteTagline: settings?.tagline ?? DEFAULT_SITE_TAGLINE, + siteLogo: settings?.logo?.url ? settings.logo : null, + siteFavicon: settings?.favicon?.url ?? null, + }; +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..0903753 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "astro/tsconfigs/base", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src", ".astro/types.d.ts", "emdash-env.d.ts"] +}