-
Notifications
You must be signed in to change notification settings - Fork 0
Feat/blog #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
niclimcy
wants to merge
8
commits into
main
Choose a base branch
from
feat/blog
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feat/blog #9
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
3e1179c
feat: Blog posts
niclimcy d8427dd
card: Make cards glassy
niclimcy 16ab1ab
feat(mdx): Refactor out getPostSlugs
niclimcy bc62453
feat(blog): Add hero image support
niclimcy 2e987de
feat(blog): Add synopsis
niclimcy c9f1963
fix(home): Pre-render home
niclimcy 22ba2f3
feat(blog): Implement tag support
niclimcy 547beeb
fix(blog): Clean up
niclimcy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,3 @@ | ||
| { | ||
| "recommendations": ["oxc.oxc-vscode"] | ||
| "recommendations": ["oxc.oxc-vscode", "unifiedjs.vscode-mdx"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| { | ||
| "[markdown][yaml][json][typescript][javascript][typescriptreact][javascriptreact][css]": { | ||
| "[markdown][yaml][json][typescript][javascript][typescriptreact][javascriptreact][css][mdx]": { | ||
| "editor.defaultFormatter": "oxc.oxc-vscode" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| const formatDate = new Intl.DateTimeFormat("en-GB", { | ||
| year: "numeric", | ||
| month: "short", | ||
| day: "numeric", | ||
| weekday: "long", | ||
| }); | ||
|
|
||
| export default formatDate; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import fs from "fs"; | ||
| import { bundleMDX } from "mdx-bundler"; | ||
| import path from "path"; | ||
| import rehypePrettyCode from "rehype-pretty-code"; | ||
| import remarkFrontmatter from "remark-frontmatter"; | ||
| import remarkMdxFrontmatter from "remark-mdx-frontmatter"; | ||
| import * as z from "zod"; | ||
|
|
||
|
niclimcy marked this conversation as resolved.
|
||
| const frontMatterSchema = z.object({ | ||
| title: z.string(), | ||
| description: z.string(), | ||
| published: z.coerce.date(), | ||
| author: z.string(), | ||
| heroImage: z.string().optional(), | ||
| heroImageAlt: z.string().optional(), | ||
| tags: z.array(z.string()).default([]), | ||
| }); | ||
|
|
||
| export type FrontMatter = z.infer<typeof frontMatterSchema>; | ||
|
|
||
| function getComponentFiles(): Record<string, string> { | ||
| const componentsPath = path.join(process.cwd(), "app/components"); | ||
|
|
||
| function readFilesRecursively(dir: string): Record<string, string> { | ||
| const entries = fs.readdirSync(dir, { withFileTypes: true }); | ||
| return entries.reduce<Record<string, string>>((acc, entry) => { | ||
| const fullPath = path.join(dir, entry.name); | ||
| if (entry.isDirectory()) { | ||
| Object.assign(acc, readFilesRecursively(fullPath)); | ||
| } else if (entry.isFile()) { | ||
| const relativePath = path.relative(componentsPath, fullPath); | ||
| const normalizedPath = relativePath.replaceAll("\\", "/"); | ||
| const content = fs.readFileSync(fullPath, "utf8"); | ||
| acc["../app/components/" + normalizedPath] = content; | ||
| } | ||
|
niclimcy marked this conversation as resolved.
|
||
| return acc; | ||
| }, {}); | ||
| } | ||
|
niclimcy marked this conversation as resolved.
|
||
|
|
||
| try { | ||
| return readFilesRecursively(componentsPath); | ||
| } catch (e) { | ||
| console.warn("Components directory not found, continuing without components", e); | ||
| } | ||
| return {}; | ||
| } | ||
|
|
||
| // Run once and cache | ||
| const componentFiles = getComponentFiles(); | ||
|
|
||
| function resolvePostsPath(slug: string): string { | ||
| const postPath = path.join(process.cwd(), "posts", `${slug}.mdx`); | ||
| if (fs.existsSync(postPath)) return postPath; | ||
| throw new Error(`Post not found for slug: ${slug}`); | ||
| } | ||
|
|
||
| function extractSynopsis(source: string, maxLength = 500): string { | ||
| const cleaned = source | ||
| // Remove frontmatter block | ||
| .replace(/^---[\s\S]*?---/, "") | ||
| // Remove fenced code blocks (must come before inline code) | ||
| .replace(/```[\s\S]*?```/g, "") | ||
| // Remove import/export statements | ||
| .replace(/^(import|export).*$/gm, "") | ||
| // Remove JSX expressions | ||
| .replace(/\{[^}]*\}/g, "") | ||
| // Remove JSX tags | ||
| .replace(/<[^>]+>/g, "") | ||
| // Remove markdown headings, bold, italic, links, inline code | ||
| .replace(/#{1,6}\s+/g, "") | ||
| .replace(/(\*\*|__)(.*?)\1/g, "$2") | ||
| .replace(/(\*|_)(.*?)\1/g, "$2") | ||
| .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1") | ||
| .replace(/`[^`]*`/g, "") | ||
| // Collapse whitespace | ||
| .replace(/\s+/g, " ") | ||
| .trim(); | ||
|
|
||
| if (cleaned.length <= maxLength) return cleaned; | ||
|
|
||
| // Slice and avoid cutting mid-word | ||
| return cleaned.slice(0, maxLength).replace(/\s+\S*$/, ""); | ||
| } | ||
|
|
||
| export async function getPostBySlug(slug: string) { | ||
| try { | ||
| const postPath = resolvePostsPath(slug); | ||
| const source = fs.readFileSync(postPath, "utf8"); | ||
| const synopsis = extractSynopsis(source); | ||
| const { code, frontmatter } = await bundleMDX({ | ||
| source, | ||
| files: componentFiles, | ||
| mdxOptions(options) { | ||
| options.remarkPlugins = [remarkFrontmatter, remarkMdxFrontmatter]; | ||
| options.rehypePlugins = [rehypePrettyCode]; | ||
| return options; | ||
| }, | ||
| }); | ||
| const parsed = frontMatterSchema.safeParse(frontmatter); | ||
|
|
||
| if (!parsed.success) { | ||
| console.error(`Invalid frontmatter in "${slug}":`, parsed.error.message); | ||
| return null; | ||
| } | ||
| return { code, frontmatter: parsed.data, synopsis }; | ||
| } catch (err) { | ||
| console.error("Error processing MDX:", err); | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| export function getPostSlugs(): string[] { | ||
| const postsDir = path.join(process.cwd(), "posts"); | ||
| try { | ||
| const files = fs.readdirSync(postsDir); | ||
| return files.filter((file) => file.endsWith(".mdx")).map((file) => file.replace(/\.mdx$/, "")); | ||
| } catch (err) { | ||
| console.error("Error reading posts directory:", err); | ||
| return []; | ||
| } | ||
| } | ||
|
|
||
| export async function getPosts(): Promise< | ||
| { slug: string; frontmatter: FrontMatter; synopsis: string }[] | ||
| > { | ||
| const slugs = getPostSlugs(); | ||
| const posts = await Promise.all( | ||
| slugs.map(async (slug) => { | ||
| const post = await getPostBySlug(slug); | ||
| return post ? [{ slug, frontmatter: post.frontmatter, synopsis: post.synopsis }] : []; | ||
| }), | ||
| ); | ||
| return posts | ||
| .flat() | ||
| .sort((a, b) => b.frontmatter.published.getTime() - a.frontmatter.published.getTime()); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,8 @@ | ||
| import { type RouteConfig, index, route } from "@react-router/dev/routes"; | ||
| import { type RouteConfig, index, route, prefix } from "@react-router/dev/routes"; | ||
|
|
||
| export default [ | ||
| index("routes/home.tsx"), | ||
| route("/docs", "routes/docs.tsx"), | ||
| route("/dashboard", "routes/dashboard.tsx"), | ||
| ...prefix("blog", [index("routes/blog/home.tsx"), route(":slug", "routes/blog/$slug.tsx")]), | ||
| ] satisfies RouteConfig; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import { MDXProvider } from "@mdx-js/react"; | ||
| import { Calendar, UserPen } from "lucide-react"; | ||
| import { getMDXComponent } from "mdx-bundler/client"; | ||
| import { useMemo } from "react"; | ||
| import { useLoaderData } from "react-router"; | ||
| import { Badge } from "~/components/ui/badge"; | ||
| import { Separator } from "~/components/ui/separator"; | ||
| import formatDate from "~/lib/format-date"; | ||
| import { getPostBySlug } from "~/lib/mdx"; | ||
|
|
||
| import type { Route } from "./+types/$slug"; | ||
|
|
||
| export async function loader({ params }: { params: { slug: string } }) { | ||
| const post = await getPostBySlug(params.slug); | ||
| if (!post) { | ||
| throw new Response("Post not found", { status: 404 }); | ||
| } | ||
| if (!post.code) { | ||
| throw new Response("Post content is missing", { status: 500 }); | ||
| } | ||
|
|
||
| return { | ||
| code: post.code, | ||
| frontmatter: post.frontmatter, | ||
| }; | ||
| } | ||
|
|
||
| export function meta({ loaderData }: Route.MetaArgs) { | ||
| return [ | ||
| { title: `${loaderData.frontmatter.title} - wpbs` }, | ||
| { name: "description", content: loaderData.frontmatter.description }, | ||
| { property: "og:title", content: `${loaderData.frontmatter.title} - wpbs` }, | ||
| { property: "og:description", content: loaderData.frontmatter.description }, | ||
| { property: "og:type", content: "article" }, | ||
| ...(loaderData.frontmatter.heroImage | ||
| ? [{ property: "og:image", content: loaderData.frontmatter.heroImage }] | ||
| : []), | ||
| ]; | ||
| } | ||
|
|
||
| export default function Post() { | ||
| const { code, frontmatter } = useLoaderData<typeof loader>(); | ||
| const Component = useMemo(() => getMDXComponent(code), [code]); | ||
|
|
||
| return ( | ||
| <MDXProvider> | ||
| <main className="py-8"> | ||
| <div className="container mx-auto w-full"> | ||
| <article className="prose max-w-none px-6 dark:prose-invert"> | ||
| <h1 className="mb-0">{frontmatter.title}</h1> | ||
| <div className="my-2 flex flex-wrap items-center gap-2 text-sm"> | ||
| <div className="flex items-center gap-1"> | ||
| <Calendar className="size-4" /> | ||
| <time>{formatDate.format(frontmatter.published)}</time> | ||
| </div> | ||
| <div className="flex items-center gap-1"> | ||
| <UserPen className="size-4" /> | ||
| <span>{frontmatter.author}</span> | ||
| </div> | ||
| </div> | ||
| {frontmatter.tags.length > 0 && ( | ||
| <div className="mb-2 flex flex-wrap gap-1"> | ||
| {frontmatter.tags.map((tag) => ( | ||
| <Badge key={tag} variant="outline"> | ||
| {tag} | ||
| </Badge> | ||
| ))} | ||
| </div> | ||
| )} | ||
| <Separator /> | ||
| {frontmatter.heroImage && ( | ||
| <figure> | ||
| <img | ||
| src={frontmatter.heroImage} | ||
| alt={frontmatter.heroImageAlt ?? frontmatter.title} | ||
| className="max-h-100" | ||
|
niclimcy marked this conversation as resolved.
|
||
| /> | ||
| {frontmatter.heroImageAlt && ( | ||
| <figcaption className="mt-2">{frontmatter.heroImageAlt}</figcaption> | ||
| )} | ||
| </figure> | ||
| )} | ||
| <Component /> | ||
| </article> | ||
| </div> | ||
| </main> | ||
| </MDXProvider> | ||
| ); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.