Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Standalone posts support

Blue Mouse51ff1f17c7b3
diff --git a/backend/apps/cloud/src/blog/blog.service.ts b/backend/apps/cloud/src/blog/blog.service.ts
index 8a89e3e9d..f0fe94dea 100644
--- a/backend/apps/cloud/src/blog/blog.service.ts
+++ b/backend/apps/cloud/src/blog/blog.service.ts
@@ -195,14 +195,39 @@ export class BlogService {
category ? path.join(BLOG_POSTS_PATH, category) : BLOG_POSTS_PATH,
)) as string[]
const directories = _filter(allFiles, file => !_endsWith(file, '.md'))
-
- if (_isEmpty(directories)) {
- return allFiles
- }
-
- const files = _map(
- _filter(allFiles, file => _endsWith(file, '.md')),
- file => _replace(file, /\.md$/, ''),
+ const markdownFiles = _filter(allFiles, file => _endsWith(file, '.md'))
+
+ const processedFiles = await Promise.all(
+ _map(markdownFiles, async filename => {
+ const slug = _replace(filename, /\.md$/, '')
+
+ try {
+ const filePath = category
+ ? path.join(BLOG_POSTS_PATH, category, filename)
+ : path.join(BLOG_POSTS_PATH, filename)
+
+ const file = await fs.readFile(filePath)
+ const { attributes }: IParseFontMatter = parseFrontMatter(
+ file.toString(),
+ )
+
+ if (attributes.standalone === true) {
+ return slug
+ }
+
+ if (category) {
+ return ['blog', category, slug]
+ } else {
+ return ['blog', slug]
+ }
+ } catch {
+ if (category) {
+ return ['blog', category, slug]
+ } else {
+ return ['blog', slug]
+ }
+ }
+ }),
)
let filesInDirectories: any[] = []
@@ -210,19 +235,14 @@ export class BlogService {
for (let i = 0; i < _size(directories); ++i) {
const directory = directories[i]
- // set to true for infinite depth directory look-up
-
const _files = await this.getSitemapFileNames(
directory,
infiniteRecursive,
)
- filesInDirectories = [
- ...filesInDirectories,
- ..._map(_files, file => [directory, _replace(file, /\.md$/, '')]),
- ]
+ filesInDirectories = [...filesInDirectories, ..._files]
}
- const sitemap = [...files, ...filesInDirectories]
+ const sitemap = [...processedFiles, ...filesInDirectories]
await redis.set(
REDIS_SITEMAP_KEY,
diff --git a/backend/blog-posts b/backend/blog-posts
index 47305134f..21fe3d475 160000
--- a/backend/blog-posts
+++ b/backend/blog-posts
@@ -1 +1 @@
-Subproject commit 47305134f61d29701c3efdd587d9540b922b1c69
+Subproject commit 21fe3d4752d7528f51157df1aee39286e297d94c
diff --git a/web/app/pages/Blog/Post.tsx b/web/app/pages/Blog/Post.tsx
index cea921200..a66e02b5d 100644
--- a/web/app/pages/Blog/Post.tsx
+++ b/web/app/pages/Blog/Post.tsx
@@ -4,19 +4,17 @@ import { Link, useLoaderData, useLocation } from 'react-router'
import NotFound from '~/pages/NotFound'
import { trackPageview } from '~/utils/analytics'
-import { type TocItem } from '~/utils/toc'
interface Post {
slug: string
title?: string
html: string
hidden?: boolean
+ standalone?: boolean
intro?: string
date?: string
author?: string
twitter_handle?: string
- toc: TocItem[]
- tocEmbedded: boolean
}
export default function PostSlug() {
@@ -24,8 +22,6 @@ export default function PostSlug() {
const post = useLoaderData() as Post
const { t } = useTranslation('common')
- console.log('post:', post)
-
useEffect(() => {
const meta = post?.author
? {
@@ -52,25 +48,29 @@ export default function PostSlug() {
<div className='px-4 sm:px-6 md:px-8'>
<div className='mx-auto max-w-4xl pb-28'>
<main className='bg-gray-50 dark:bg-slate-900'>
- <Link
- to='/blog'
- className='group mt-10 mb-6 flex text-sm leading-6 font-semibold text-slate-700 uppercase hover:text-slate-900 dark:text-slate-200 dark:hover:text-white'
- >
- <svg
- viewBox='0 -9 3 24'
- className='mr-3 h-6 w-auto overflow-visible text-slate-400 group-hover:text-slate-600 dark:group-hover:text-slate-300'
+ {post.standalone ? (
+ <div className='mt-10 mb-6' />
+ ) : (
+ <Link
+ to='/blog'
+ className='group mt-10 mb-6 flex text-sm leading-6 font-semibold text-slate-700 uppercase hover:text-slate-900 dark:text-slate-200 dark:hover:text-white'
>
- <path
- d='M3 0L0 3L3 6'
- fill='none'
- stroke='currentColor'
- strokeWidth='2'
- strokeLinecap='round'
- strokeLinejoin='round'
- />
- </svg>
- {t('common.allPosts')}
- </Link>
+ <svg
+ viewBox='0 -9 3 24'
+ className='mr-3 h-6 w-auto overflow-visible text-slate-400 group-hover:text-slate-600 dark:group-hover:text-slate-300'
+ >
+ <path
+ d='M3 0L0 3L3 6'
+ fill='none'
+ stroke='currentColor'
+ strokeWidth='2'
+ strokeLinecap='round'
+ strokeLinejoin='round'
+ />
+ </svg>
+ {t('common.allPosts')}
+ </Link>
+ )}
<article className='relative'>
<div className='mb-2 font-mono text-sm leading-6 font-medium tracking-wide uppercase'>
<dl>
diff --git a/web/app/routes/$.tsx b/web/app/routes/$.tsx
index 63109672c..8799825cf 100644
--- a/web/app/routes/$.tsx
+++ b/web/app/routes/$.tsx
@@ -1,17 +1,53 @@
-import type { LoaderFunction } from 'react-router'
-import { data } from 'react-router'
+import type { LoaderFunction, MetaFunction } from 'react-router'
+import { data, useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { getOgImageUrl } from '~/lib/constants'
+import Post from '~/pages/Blog/Post'
import NotFound from '~/pages/NotFound'
+import { getPost } from '~/utils/getPosts'
+import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
+
+export const meta: MetaFunction = (loaderData: any) => {
+ if (!loaderData?.data) {
+ return [...getTitle('Page Not Found'), ...getDescription('The page you are looking for does not exist.')]
+ }
+
+ const ogImageUrl = getOgImageUrl(loaderData?.data?.title)
+
+ return [
+ ...getTitle(loaderData?.data?.title || 'Blog'),
+ ...getDescription(loaderData?.data?.intro || ''),
+ ...getPreviewImage(ogImageUrl),
+ ]
+}
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export const loader: LoaderFunction = () => {
+export const loader: LoaderFunction = async ({ params }) => {
+ const catchAllPath = params['*']
+
+ if (!catchAllPath) {
+ return data(null, { status: 404 })
+ }
+
+ const post = await getPost(catchAllPath, undefined, true)
+
+ if (post) {
+ return post
+ }
+
return data(null, { status: 404 })
}
-export default function Index() {
+export default function CatchAll() {
+ const post = useLoaderData()
+
+ if (post) {
+ return <Post />
+ }
+
return <NotFound />
}
diff --git a/web/app/routes/blog.$slug.tsx b/web/app/routes/blog.$slug.tsx
index ff5a5a7b7..cdc1c6d88 100644
--- a/web/app/routes/blog.$slug.tsx
+++ b/web/app/routes/blog.$slug.tsx
@@ -1,5 +1,4 @@
import _isString from 'lodash/isString'
-import _join from 'lodash/join'
import _last from 'lodash/last'
import _map from 'lodash/map'
import { redirect, data } from 'react-router'
@@ -37,16 +36,27 @@ export const sitemap: SitemapFunction = async () => {
let date: string
if (_isString(file)) {
+ // Standalone post - just the filename
handle = getSlugFromFilename(file)
date = getDateFromFilename(file)
} else {
+ // Array format: ["blog", ...] or ["blog", "category", ...]
const _file = _last(file) as string
- handle = _join([...file.slice(0, -1), getSlugFromFilename(_file)], '/')
+
+ if (file.length === 2) {
+ // ["blog", "filename"] - blog post in root
+ handle = `blog/${getSlugFromFilename(_file)}`
+ } else {
+ // ["blog", "category", "filename"] - blog post in subdirectory
+ const category = file[1]
+ handle = `blog/${category}/${getSlugFromFilename(_file)}`
+ }
+
date = getDateFromFilename(_file)
}
return {
- loc: `/blog/${handle}`,
+ loc: `/${handle}`,
lastmod: date,
changefreq: 'weekly',
}
diff --git a/web/app/utils/getPosts.ts b/web/app/utils/getPosts.ts
index 735968a19..71580e53c 100644
--- a/web/app/utils/getPosts.ts
+++ b/web/app/utils/getPosts.ts
@@ -3,12 +3,12 @@ import { marked, type Tokens } from 'marked'
import { getBlogPost, getBlogPostWithCategory } from '~/api'
-import { extractTableOfContents, ensureHeaderIds, generateSlug, renderTocAsHtml, type TocItem } from './toc'
+import { extractTableOfContents, ensureHeaderIds, generateSlug, renderTocAsHtml } from './toc'
const renderer = new marked.Renderer()
renderer.link = ({ href, text }: Tokens.Link) => {
- const url = new URL(href)
+ const url = new URL(href, 'https://swetrix.com')
if (url.hostname !== 'swetrix.com') {
url.searchParams.set('utm_source', 'swetrix.com')
@@ -32,15 +32,14 @@ interface GetPost {
title?: string
html: string
hidden?: boolean
+ standalone?: boolean
intro?: string
date?: string
author?: string
twitter_handle?: string
- toc: TocItem[]
- tocEmbedded: boolean // Flag to track if TOC was embedded in content
}
-export async function getPost(slug: string, category?: string): Promise<GetPost | null> {
+export async function getPost(slug: string, category?: string, tryStandalone?: boolean): Promise<GetPost | null> {
let post: any = null
try {
@@ -57,22 +56,21 @@ export async function getPost(slug: string, category?: string): Promise<GetPost
return null
}
+ if (!tryStandalone && post.attributes?.standalone) {
+ return null
+ }
+
const tocPlaceholder = '::TABLE_OF_CONTENTS::'
const hasTocPlaceholder = post.body.includes(tocPlaceholder)
- // Convert markdown to HTML
let html = marked(post.body, { renderer }) as string
- // Ensure all headers have IDs for linking
html = ensureHeaderIds(html)
- // Extract table of contents from the HTML
const toc = extractTableOfContents(html)
- // If TOC placeholder exists and we have TOC items, replace it with actual TOC HTML
if (hasTocPlaceholder && toc.length > 0) {
const tocHtml = renderTocAsHtml(toc)
- // Replace the placeholder with the actual TOC HTML
html = html.replace(new RegExp(tocPlaceholder, 'gi'), tocHtml)
}
@@ -85,7 +83,6 @@ export async function getPost(slug: string, category?: string): Promise<GetPost
date: post.attributes?.date,
author: post.attributes?.author,
twitter_handle: post.attributes?.twitter_handle,
- toc,
- tocEmbedded: hasTocPlaceholder && toc.length > 0,
+ standalone: post.attributes?.standalone,
}
}