1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-11-05 04:35:41 -05:00

just some refactoring

This commit is contained in:
2022-03-09 14:07:06 -05:00
parent f5c8a7a21a
commit 87848cc697
26 changed files with 533 additions and 558 deletions

72
lib/helpers/build-feed.ts Normal file
View File

@@ -0,0 +1,72 @@
import { Feed } from "feed";
import { getAllNotes } from "./parse-notes";
import * as config from "../config";
import type { GetServerSidePropsContext, PreviewData } from "next";
import type { ParsedUrlQuery } from "querystring";
// handles literally *everything* about building the server-side rss/atom feeds and writing the response.
// all the page needs to do is `return buildFeed(context, { format: "rss" })` from getServerSideProps.
export const buildFeed = (
context: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>,
options?: { type: "rss" | "atom" }
): { props: Record<string, unknown> } => {
const { res } = context;
// https://github.com/jpmonette/feed#example
const feed = new Feed({
id: `${config.baseUrl}/`,
link: `${config.baseUrl}/`,
title: config.siteName,
description: config.longDescription,
copyright: "https://creativecommons.org/licenses/by/4.0/",
updated: new Date(),
image: `${config.baseUrl}/static/images/me.jpg`,
feedLinks: {
rss: `${config.baseUrl}/feed.xml`,
atom: `${config.baseUrl}/feed.atom`,
},
author: {
name: config.authorName,
link: `${config.baseUrl}/`,
email: config.authorEmail,
},
});
// add notes separately using their frontmatter
const notes = getAllNotes();
notes.forEach((note) => {
feed.addItem({
guid: note.permalink,
link: note.permalink,
title: note.title,
description: note.description,
image: note.image ? `${config.baseUrl}${note.image}` : "",
author: [
{
name: config.authorName,
link: config.baseUrl,
},
],
date: new Date(note.date),
});
});
// cache on edge for one hour
res.setHeader("cache-control", "s-maxage=3600, stale-while-revalidate");
// generates RSS by default
if (options?.type === "atom") {
res.setHeader("content-type", "application/atom+xml; charset=utf-8");
res.write(feed.atom1());
} else {
res.setHeader("content-type", "application/rss+xml; charset=utf-8");
res.write(feed.rss2());
}
res.end();
return {
props: {},
};
};

View File

@@ -0,0 +1,24 @@
import dynamic from "next/dynamic";
// Bundle these components by default:
export { default as Image } from "../../components/Image/Image";
export { default as Figure } from "../../components/Figure/Figure";
// These (mostly very small) components are direct replacements for HTML tags generated by remark:
export { default as a } from "../../components/Link/Link";
export { default as code } from "../../components/CodeBlock/CodeBlock";
export { default as blockquote } from "../../components/Blockquote/Blockquote";
export { default as hr } from "../../components/HorizontalRule/HorizontalRule";
export { H1 as h1, H2 as h2, H3 as h3, H4 as h4, H5 as h5, H6 as h6 } from "../../components/Heading/Heading";
export { UnorderedList as ul, OrderedList as ol, ListItem as li } from "../../components/List/List";
// ...and these components are technically passed into all posts, but next/dynamic ensures they're loaded only
// when they're referenced in the individual mdx files.
export const IFrame = dynamic(() => import("../../components/IFrame/IFrame"));
export const Video = dynamic(() => import("../../components/Video/Video"));
export const YouTube = dynamic(() => import("../../components/YouTubeEmbed/YouTubeEmbed"));
export const Tweet = dynamic(() => import("../../components/TweetEmbed/TweetEmbed"));
export const Gist = dynamic(() => import("../../components/GistEmbed/GistEmbed"));
// One-offs for specific posts:
export const OctocatLink = dynamic(() => import("../../components/OctocatLink/OctocatLink"));

107
lib/helpers/parse-notes.ts Normal file
View File

@@ -0,0 +1,107 @@
import fs from "fs";
import path from "path";
import { renderToStaticMarkup } from "react-dom/server";
import matter from "gray-matter";
import { serialize } from "next-mdx-remote/serialize";
import { minify } from "terser";
import { compiler } from "markdown-to-jsx";
import removeMarkdown from "remove-markdown";
import sanitizeHtml from "sanitize-html";
import readingTime from "reading-time";
import { baseUrl } from "../config";
import { NOTES_DIR } from "../config/constants";
// remark/rehype markdown plugins
import remarkGfm from "remark-gfm";
import rehypeSlug from "rehype-slug";
import rehypePrism from "rehype-prism-plus";
import type { MinifyOptions } from "terser";
import type { NoteType } from "../../types";
// returns all .mdx files in NOTES_DIR (without .mdx extension)
export const getNoteSlugs = () =>
fs
.readdirSync(path.join(process.cwd(), NOTES_DIR))
.filter((file) => /\.mdx$/.test(file))
.map((noteFile) => noteFile.replace(/\.mdx$/, ""));
// returns front matter and/or *raw* markdown contents of a given slug
export const getNoteData = (slug: string): Omit<NoteType, "source"> & { content: string } => {
const fullPath = path.join(process.cwd(), NOTES_DIR, `${slug}.mdx`);
const rawContent = fs.readFileSync(fullPath, "utf8");
const { data, content } = matter(rawContent);
// carefully allow VERY limited markdown in post titles...
const htmlTitle = sanitizeHtml(
renderToStaticMarkup(
compiler(data.title, {
forceInline: true,
disableParsingRawHTML: true,
})
),
{
allowedTags: ["code", "pre", "em", "strong", "del"],
}
);
// return both the parsed YAML front matter (with a few amendments) and the raw, unparsed markdown content
return {
frontMatter: {
...(data as Omit<NoteType["frontMatter"], "slug" | "title" | "htmlTitle" | "permalink" | "date" | "readingMins">),
// zero markdown title:
title: removeMarkdown(data.title),
// parsed markdown title:
htmlTitle,
slug,
permalink: `${baseUrl}/notes/${slug}/`,
date: new Date(data.date).toISOString(), // validate/normalize the date string provided from front matter
readingMins: Math.ceil(readingTime(content).minutes),
},
content,
};
};
// fully parses MDX into JS and returns *everything* about a note
export const getNote = async (slug: string): Promise<NoteType> => {
const { frontMatter, content } = getNoteData(slug);
const source = await serialize(content, {
parseFrontmatter: false,
mdxOptions: {
remarkPlugins: [[remarkGfm, { singleTilde: false }]],
rehypePlugins: [[rehypeSlug], [rehypePrism, { ignoreMissing: true }]],
},
});
// HACK: next-mdx-remote v4 doesn't (yet?) minify compiled JSX output, see:
// https://github.com/hashicorp/next-mdx-remote/pull/211#issuecomment-1013658514
// ...so for now, let's do it manually (and conservatively) with terser when building for production.
const terserOptions: MinifyOptions = {
ecma: 2018,
module: true,
parse: {
bare_returns: true,
},
compress: {
defaults: true,
},
sourceMap: false,
};
const compiledSource =
process.env.NEXT_PUBLIC_VERCEL_ENV === "production"
? (await minify(source.compiledSource, terserOptions)).code
: source.compiledSource;
return {
frontMatter,
source: {
compiledSource,
},
};
};
// returns the front matter of ALL notes, sorted reverse chronologically
export const getAllNotes = () =>
getNoteSlugs()
.map((slug) => getNoteData(slug).frontMatter)
.sort((note1: NoteType["frontMatter"], note2: NoteType["frontMatter"]) => (note1.date > note2.date ? -1 : 1));