PronounsPage/shared/blog/metadata.ts

64 lines
1.8 KiB
TypeScript

import type { Config } from '~~/locale/config.ts';
export interface PostMetadata {
title: string;
date: string;
authors: string[];
hero: { src: string; alt: string; class: string } | undefined;
}
export interface Post extends PostMetadata {
slug: string;
}
export interface PostWithContent extends Post {
content: string;
}
export const extractMetadata = (config: Config, content: string): PostMetadata | undefined => {
const lines = content.split('\n').filter((l) => !!l);
const title = lines[0]?.match(/^# (.*)$/)?.[1];
const secondLineMatch = lines[1]?.match(/^<small>(\d\d\d\d-\d\d-\d\d) \| ([^|]*).*<\/small>$/);
const date = secondLineMatch?.[1];
const authors = secondLineMatch?.[2].split(',').map((a) => {
a = a.trim();
const teamName = config.contact.team?.route;
if (teamName && a.startsWith(teamName)) {
return teamName;
}
const m = a.match(/^\[([^\]]+)]/);
if (m) {
return m[1];
}
return a;
}) ?? [];
let hero = undefined;
const classHeroImages = lines
.map((x) => x.match(/<img src="([^"]+)" class="hero([^"]*)" alt="([^"]*)"/))
.filter((x) => !!x);
if (classHeroImages.length) {
hero = {
src: classHeroImages[0][1],
alt: classHeroImages[0][3],
class: classHeroImages[0][2].replace('d-none', ''),
};
} else {
const images = lines.map((x) => x.match(/^!\[([^\]]*)]\(([^)]+)\)$/)).filter((x) => !!x);
if (images.length) {
hero = {
src: images[0][2],
alt: images[0][1],
class: '',
};
}
}
if (title === undefined || date === undefined) {
return undefined;
}
return { title, date, authors, hero };
};