80 lines
2.2 KiB
JavaScript
80 lines
2.2 KiB
JavaScript
const collectFrontmatter = (raw) => {
|
|
const lines = raw.split(/\r?\n/);
|
|
const meta = {};
|
|
let cursor = 0;
|
|
|
|
if (lines[0]?.trim() === '---') {
|
|
cursor = 1;
|
|
for (; cursor < lines.length; cursor += 1) {
|
|
const line = lines[cursor].trim();
|
|
if (line === '---') {
|
|
cursor += 1;
|
|
break;
|
|
}
|
|
if (!line) continue;
|
|
const [key, ...rest] = line.split(':');
|
|
meta[key.trim()] = rest.join(':').trim();
|
|
}
|
|
}
|
|
|
|
const body = lines.slice(cursor).join('\n').trim();
|
|
return { meta, body };
|
|
};
|
|
|
|
const extractTitle = (body) => {
|
|
const titleLine = body.split(/\r?\n/).find((line) => line.startsWith('# '));
|
|
return titleLine ? titleLine.replace(/^#\s+/, '').trim() : '';
|
|
};
|
|
|
|
const extractExcerpt = (body) => {
|
|
const lines = body.split(/\r?\n/);
|
|
for (const line of lines) {
|
|
if (!line.trim()) continue;
|
|
if (line.startsWith('#')) continue;
|
|
return line.trim();
|
|
}
|
|
return '';
|
|
};
|
|
|
|
const normalizeTags = (value) => {
|
|
if (!value) return [];
|
|
return value
|
|
.split(',')
|
|
.map((tag) => tag.trim())
|
|
.filter(Boolean);
|
|
};
|
|
|
|
const normalizeTitle = (slug) =>
|
|
slug
|
|
.replace(/-/g, ' ')
|
|
.replace(/\b\w/g, (letter) => letter.toUpperCase());
|
|
|
|
export const getBlogPosts = () => {
|
|
const modules = import.meta.glob('/src/content/blog/*.md', {
|
|
as: 'raw',
|
|
eager: true,
|
|
});
|
|
|
|
const posts = Object.entries(modules).map(([path, raw]) => {
|
|
const slug = path.split('/').pop().replace(/\.md$/, '');
|
|
const { meta, body } = collectFrontmatter(raw);
|
|
const title = meta.title || extractTitle(body) || normalizeTitle(slug);
|
|
const excerpt = meta.excerpt || extractExcerpt(body);
|
|
const date = meta.date || '';
|
|
return {
|
|
slug,
|
|
title,
|
|
excerpt,
|
|
date,
|
|
tags: normalizeTags(meta.tags),
|
|
body,
|
|
};
|
|
});
|
|
|
|
return posts.sort((a, b) => {
|
|
const aDate = Date.parse(a.date || '') || 0;
|
|
const bDate = Date.parse(b.date || '') || 0;
|
|
return bDate - aDate;
|
|
});
|
|
};
|