Compare commits

..

2 commits

15 changed files with 152 additions and 54 deletions

View file

@ -39,7 +39,11 @@ const DRAFT_PATHS = readPostFiles()
export default defineConfig({
site: 'https://gabeefran.co',
redirects: Object.fromEntries(LEGACY_EN_PATHS.map((path) => [path, path === '/' ? '/en' : `/en${path}`])),
redirects: {
...Object.fromEntries(LEGACY_EN_PATHS.map((path) => [path, path === '/' ? '/en' : `/en${path}`])),
// The Portuguese about page used to share the English slug.
'/pt/about': '/pt/sobre',
},
integrations: [react(), mdx(), sitemap({ filter: (page) => !DRAFT_PATHS.some((path) => page.endsWith(path)) })],

View file

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 46 KiB

View file

@ -10,15 +10,16 @@
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { LANGS, pageMeta, tagPageMeta, type Lang, type PageKey } from '../src/lib/i18n.ts';
import { readPostFiles, type PostFile } from '../src/lib/post-files.ts';
import { pageCardPath, postCardPath, tagCardPath } from '../src/lib/social-cards.ts';
import { readAboutFiles, readPostFiles, type PostFile } from '../src/lib/post-files.ts';
import { aboutCardPath, pageCardPath, postCardPath, tagCardPath } from '../src/lib/social-cards.ts';
const BASE_URL = process.env.SOCIAL_CARD_BASE_URL ?? 'https://gabeefran.co';
const CF_API = 'https://api.cloudflare.com/client/v4/accounts';
// 404.html is prerendered once, in English (see src/pages/404.astro).
// The about page is missing here: it comes from src/content/about/<lang>.mdx.
const LANG_PAGES: Record<Lang, PageKey[]> = {
en: ['home', 'posts', 'about', '404'],
pt: ['home', 'posts', 'about'],
en: ['home', 'posts', '404'],
pt: ['home', 'posts'],
};
interface Card {
@ -38,9 +39,12 @@ function listCards(posts: PostFile[]): Card[] {
const pageCards: Card[] = LANGS.flatMap((lang) => {
const pages = LANG_PAGES[lang].map((key) => ({ path: pageCardPath(lang, key), meta: pageMeta(lang, key) }));
const aboutPages = readAboutFiles()
.filter((about) => about.lang === lang)
.map(({ slug, title, description }) => ({ path: aboutCardPath(lang, slug), meta: { title, description } }));
const tags = [...new Set(posts.filter((p) => p.lang === lang).flatMap((p) => p.tags))].sort();
const tagPages = tags.map((tag) => ({ path: tagCardPath(lang, tag), meta: tagPageMeta(lang, tag) }));
return [...pages, ...tagPages].map(({ path, meta }) => ({
return [...pages, ...aboutPages, ...tagPages].map(({ path, meta }) => ({
path,
route: '/page-card' as const,
params: { title: meta.title, description: meta.description },

View file

@ -1,5 +1,6 @@
---
import ThemeToggle from './ThemeToggle.astro';
import { aboutPath } from '../lib/about';
import { getLocalizedPath, LANG_LABELS, useTranslations, type Lang } from '../lib/i18n';
interface Props {
@ -15,7 +16,7 @@ const otherLang: Lang = lang === 'en' ? 'pt' : 'en';
const pathname = Astro.url.pathname;
const homeHref = getLocalizedPath('/', lang);
const postsHref = getLocalizedPath('/posts', lang);
const aboutHref = getLocalizedPath('/about', lang);
const aboutHref = await aboutPath(lang);
// Not everything is translated: fall back to the other language's home page.
const langSwitchHref = alternates[otherLang] ?? getLocalizedPath('/', otherLang);

View file

@ -1,6 +1,7 @@
---
import PostCard from './PostCard.astro';
import { getPostsByLang } from '../lib/posts';
import { aboutPath } from '../lib/about';
import { getLocalizedPath, useTranslations, type Lang } from '../lib/i18n';
interface Props {
@ -12,7 +13,7 @@ const t = useTranslations(lang);
const posts = await getPostsByLang(lang);
const recentPosts = posts.slice(0, 3);
const postsHref = getLocalizedPath('/posts', lang);
const aboutHref = getLocalizedPath('/about', lang);
const aboutHref = await aboutPath(lang);
---
<section class="mx-10 my-10 flex flex-col gap-5 font-mono">

View file

@ -23,4 +23,19 @@ const posts = defineCollection({
}),
});
export const collections = { posts };
// The about page, one file per language: src/content/about/<lang>.mdx. The
// entry id is the language; the URL is /<lang>/<slug>.
const about = defineCollection({
loader: glob({
pattern: '*.mdx',
base: './src/content/about',
generateId: ({ entry }) => entry.replace(/\.mdx$/, ''),
}),
schema: z.object({
title: z.string(),
description: z.string(),
slug: z.string(),
}),
});
export const collections = { posts, about };

13
src/content/about/en.mdx Normal file
View file

@ -0,0 +1,13 @@
---
title: "About"
slug: "about"
description: "Gabriel Franco: computer science student at PUCRS, interested in how software actually works and in the history of open source."
---
Hi, I'm Gabe — Gabriel Franco. I'm a computer science student at PUCRS (Pontifícia Universidade Católica do Rio Grande do Sul), and this blog is where I write down the things I'm learning and thinking about along the way.
I care a lot about computer science as a field, not just as a set of tools to ship products with. I have a fairly specific way of doing things: I'd rather understand a system properly than memorize the steps to make it work, and I tend to slow down on purpose to figure out what's actually happening under the hood — in a compiler, an operating system, a language runtime, whatever it is. That habit shapes most of what ends up on this blog.
I'm also genuinely interested in the history of the open source movement: the people, the arguments, and the decisions that shaped the software we all rely on. Figures like Linus Torvalds and projects like GNU come up often in what I read and write about, not as trivia, but because understanding where a tool came from usually explains a lot about how and why it works the way it does today.
This site is bilingual, in English and in Portuguese, and every post exists in both languages. Thanks for stopping by.

13
src/content/about/pt.mdx Normal file
View file

@ -0,0 +1,13 @@
---
title: "Sobre"
slug: "sobre"
description: "Gabriel Franco: estudante de ciência da computação na PUCRS, interessado em como o software realmente funciona e na história do open source."
---
Olá, eu sou o Gabe — Gabriel Franco. Sou estudante de ciência da computação na PUCRS (Pontifícia Universidade Católica do Rio Grande do Sul), e este blog é onde registro as coisas que vou aprendendo e pensando pelo caminho.
Eu me importo bastante com ciência da computação como área, não só como um conjunto de ferramentas para lançar produtos. Tenho um jeito bem específico de fazer as coisas: prefiro entender um sistema de verdade a decorar os passos para fazê-lo funcionar, e costumo desacelerar de propósito para descobrir o que realmente está acontecendo por baixo dos panos — em um compilador, em um sistema operacional, no runtime de uma linguagem, seja lá o que for. Esse hábito molda a maior parte do que acaba virando post aqui.
Também tenho um interesse genuíno pela história do movimento open source: as pessoas, os debates e as decisões que moldaram o software do qual todos dependemos. Figuras como Linus Torvalds e projetos como o GNU aparecem com frequência no que leio e escrevo, não como curiosidade, mas porque entender de onde uma ferramenta veio costuma explicar bastante sobre como e por que ela funciona do jeito que funciona hoje.
Este site é bilíngue, em inglês e em português, e todo post existe nos dois idiomas. Obrigado pela visita.

21
src/lib/about.ts Normal file
View file

@ -0,0 +1,21 @@
import { getEntry, type CollectionEntry } from 'astro:content';
import { LANGS, type Lang } from './i18n';
export type AboutEntry = CollectionEntry<'about'>;
/** The id is the language (see src/content.config.ts). */
export async function getAbout(lang: Lang): Promise<AboutEntry> {
const entry = await getEntry('about', lang);
if (!entry) throw new Error(`Missing src/content/about/${lang}.mdx`);
return entry;
}
/** Every language has its own slug for the about page (/en/about, /pt/sobre). */
export async function aboutPath(lang: Lang): Promise<string> {
return `/${lang}/${(await getAbout(lang)).data.slug}`;
}
export async function getAboutAlternates(): Promise<Record<Lang, string>> {
const paths = await Promise.all(LANGS.map(async (lang) => [lang, await aboutPath(lang)] as const));
return Object.fromEntries(paths) as Record<Lang, string>;
}

View file

@ -51,16 +51,6 @@ export const ui = {
'post.updated': 'Updated',
'tag.label': 'Tag',
'tag.description': 'Everything I’ve written tagged #{tag}.',
'about.title': 'About',
'about.description':
'Gabriel Franco: computer science student at PUCRS, interested in how software actually works and in the history of open source.',
// Paragraphs are separated by a blank line.
'about.body': [
"Hi, I'm Gabe — Gabriel Franco. I'm a computer science student at PUCRS (Pontifícia Universidade Católica do Rio Grande do Sul), and this blog is where I write down the things I'm learning and thinking about along the way.",
"I care a lot about computer science as a field, not just as a set of tools to ship products with. I have a fairly specific way of doing things: I'd rather understand a system properly than memorize the steps to make it work, and I tend to slow down on purpose to figure out what's actually happening under the hood — in a compiler, an operating system, a language runtime, whatever it is. That habit shapes most of what ends up on this blog.",
"I'm also genuinely interested in the history of the open source movement: the people, the arguments, and the decisions that shaped the software we all rely on. Figures like Linus Torvalds and projects like GNU come up often in what I read and write about, not as trivia, but because understanding where a tool came from usually explains a lot about how and why it works the way it does today.",
'This site is bilingual, in English and in Portuguese, and every post exists in both languages. Thanks for stopping by.',
].join('\n\n'),
'footer.tagline': 'Written by hand in Porto Alegre.',
'footer.rights': 'All rights reserved.',
'footer.source': 'Source',
@ -102,15 +92,6 @@ export const ui = {
'post.updated': 'Atualizado em',
'tag.label': 'Tag',
'tag.description': 'Tudo que já escrevi com a tag #{tag}.',
'about.title': 'Sobre',
'about.description':
'Gabriel Franco: estudante de ciência da computação na PUCRS, interessado em como o software realmente funciona e na história do open source.',
'about.body': [
'Olá, eu sou o Gabe — Gabriel Franco. Sou estudante de ciência da computação na PUCRS (Pontifícia Universidade Católica do Rio Grande do Sul), e este blog é onde registro as coisas que vou aprendendo e pensando pelo caminho.',
'Eu me importo bastante com ciência da computação como área, não só como um conjunto de ferramentas para lançar produtos. Tenho um jeito bem específico de fazer as coisas: prefiro entender um sistema de verdade a decorar os passos para fazê-lo funcionar, e costumo desacelerar de propósito para descobrir o que realmente está acontecendo por baixo dos panos — em um compilador, em um sistema operacional, no runtime de uma linguagem, seja lá o que for. Esse hábito molda a maior parte do que acaba virando post aqui.',
'Também tenho um interesse genuíno pela história do movimento open source: as pessoas, os debates e as decisões que moldaram o software do qual todos dependemos. Figuras como Linus Torvalds e projetos como o GNU aparecem com frequência no que leio e escrevo, não como curiosidade, mas porque entender de onde uma ferramenta veio costuma explicar bastante sobre como e por que ela funciona do jeito que funciona hoje.',
'Este site é bilíngue, em inglês e em português, e todo post existe nos dois idiomas. Obrigado pela visita.',
].join('\n\n'),
'footer.tagline': 'Escrito à mão em Porto Alegre.',
'footer.rights': 'Todos os direitos reservados.',
'footer.source': 'Código-fonte',
@ -141,8 +122,11 @@ export function useTranslations(lang: Lang) {
};
}
/** Pages with their own title/description (tag pages use tagPageMeta). */
export type PageKey = 'home' | 'posts' | 'about' | '404';
/**
* Pages with their own title/description (tag pages use tagPageMeta). The about
* page's live in src/content/about/<lang>.mdx.
*/
export type PageKey = 'home' | 'posts' | '404';
export interface PageMeta {
title: string;
@ -152,7 +136,6 @@ export interface PageMeta {
const PAGE_META_KEYS: Record<PageKey, { title: UiKey; description: UiKey }> = {
home: { title: 'hero.title', description: 'home.description' },
posts: { title: 'posts.title', description: 'posts.description' },
about: { title: 'about.title', description: 'about.description' },
'404': { title: '404.title', description: '404.body' },
};

View file

@ -50,3 +50,22 @@ export function readPostFiles(): PostFile[] {
});
});
}
export interface AboutFile {
lang: Lang;
slug: string;
title: string;
description: string;
}
/** The about page lives at src/content/about/<lang>.mdx (see src/content.config.ts). */
export function readAboutFiles(): AboutFile[] {
return LANGS.flatMap((lang) => {
const file = join('src/content/about', `${lang}.mdx`);
if (!existsSync(file)) return [];
const raw = readFileSync(file, 'utf-8');
const slug = getFrontmatterField(raw, 'slug');
if (!slug) throw new Error(`${file} is missing a \`slug\` in its frontmatter`);
return [{ lang, slug, title: getFrontmatterField(raw, 'title') ?? slug, description: getFrontmatterField(raw, 'description') ?? '' }];
});
}

View file

@ -11,6 +11,11 @@ export function pageCardPath(lang: Lang, page: PageKey): string {
return `/social-cards/${lang}/pages/${page}.png`;
}
/** Named after the slug, like the page itself (/pt/sobre -> pt/pages/sobre.png). */
export function aboutCardPath(lang: Lang, slug: string): string {
return `/social-cards/${lang}/pages/${slug}.png`;
}
export function tagCardPath(lang: Lang, tag: string): string {
return `/social-cards/${lang}/tags/${tag}.png`;
}

View file

@ -0,0 +1,39 @@
---
import { render } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';
import { LANGS, useTranslations, type Lang } from '../../lib/i18n';
import { getAbout, getAboutAlternates } from '../../lib/about';
import { aboutCardPath } from '../../lib/social-cards';
// The slug comes from src/content/about/<lang>.mdx, so each language names its own route.
export async function getStaticPaths() {
return Promise.all(
LANGS.map(async (lang) => {
const page = await getAbout(lang);
return { params: { lang, about: page.data.slug }, props: { page } };
}),
);
}
const lang = Astro.params.lang as Lang;
const t = useTranslations(lang);
const { page } = Astro.props;
const { Content } = await render(page);
const alternates = await getAboutAlternates();
---
<BaseLayout
title={`${page.data.title} — ${t('site.name')}`}
description={page.data.description}
lang={lang}
image={aboutCardPath(lang, page.data.slug)}
alternates={alternates}
>
<section class="mx-10 mt-10 font-mono">
<h1 class="text-3xl font-bold tracking-tight text-text sm:text-4xl">{page.data.title}</h1>
<div class="prose prose-neutral mt-6 max-w-none prose-headings:font-semibold prose-a:text-primary prose-a:no-underline hover:prose-a:underline dark:prose-invert">
<Content />
</div>
</section>
</BaseLayout>

View file

@ -1,21 +0,0 @@
---
import BaseLayout from '../../layouts/BaseLayout.astro';
import { langPaths, pageMeta, useTranslations, type Lang } from '../../lib/i18n';
import { pageCardPath } from '../../lib/social-cards';
export const getStaticPaths = langPaths;
const lang = Astro.params.lang as Lang;
const t = useTranslations(lang);
const page = pageMeta(lang, 'about');
---
<BaseLayout title={`${page.title} — ${t('site.name')}`} description={page.description} lang={lang} image={pageCardPath(lang, 'about')}>
<section class="mx-10 mt-10 font-mono">
<h1 class="text-3xl font-bold tracking-tight text-text sm:text-4xl">{page.title}</h1>
<div class="prose prose-neutral mt-6 max-w-none prose-headings:font-semibold prose-a:text-primary prose-a:no-underline hover:prose-a:underline dark:prose-invert">
{t('about.body').split('\n\n').map((paragraph) => <p>{paragraph}</p>)}
</div>
</section>
</BaseLayout>

View file

@ -3,14 +3,15 @@ import { pickLocale, SUPPORTED } from "../lib/i18n";
export const prerender = false;
export const GET: APIRoute = ({ request, cookies, redirect }) => {
export const GET: APIRoute = ({ request, cookies, redirect, url }) => {
const saved = cookies.get("lang")?.value;
const lang =
saved && (SUPPORTED as readonly string[]).includes(saved)
? saved
: pickLocale(request.headers.get("accept-language"));
const res = redirect(`/${lang}/`, 302);
// Keep the query string (e.g. utm_* tags) through the redirect.
const res = redirect(`/${lang}/${url.search}`, 302);
res.headers.set("Vary", "Accept-Language, Cookie");
return res;
};