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!

Autogenerated table of contents

Blue Mouse48db3e40e4e7
diff --git a/web/app/pages/Blog/Post.tsx b/web/app/pages/Blog/Post.tsx
index dc85b8a2a..cea921200 100644
--- a/web/app/pages/Blog/Post.tsx
+++ b/web/app/pages/Blog/Post.tsx
@@ -4,6 +4,7 @@ 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
@@ -14,6 +15,8 @@ interface Post {
date?: string
author?: string
twitter_handle?: string
+ toc: TocItem[]
+ tocEmbedded: boolean
}
export default function PostSlug() {
@@ -21,6 +24,8 @@ export default function PostSlug() {
const post = useLoaderData() as Post
const { t } = useTranslation('common')
+ console.log('post:', post)
+
useEffect(() => {
const meta = post?.author
? {
diff --git a/web/app/utils/getPosts.ts b/web/app/utils/getPosts.ts
index c844c0c9b..735968a19 100644
--- a/web/app/utils/getPosts.ts
+++ b/web/app/utils/getPosts.ts
@@ -3,6 +3,8 @@ import { marked, type Tokens } from 'marked'
import { getBlogPost, getBlogPostWithCategory } from '~/api'
+import { extractTableOfContents, ensureHeaderIds, generateSlug, renderTocAsHtml, type TocItem } from './toc'
+
const renderer = new marked.Renderer()
renderer.link = ({ href, text }: Tokens.Link) => {
@@ -15,6 +17,12 @@ renderer.link = ({ href, text }: Tokens.Link) => {
return `<a href="${url.toString()}" referrerpolicy="strict-origin-when-cross-origin" target="_blank" rel="noopener noreferrer">${text}</a>`
}
+// Add automatic ID generation to headers
+renderer.heading = ({ text, depth }: Tokens.Heading) => {
+ const id = generateSlug(text)
+ return `<h${depth} id="${id}">${text}</h${depth}>`
+}
+
// Removes first 10 characters from the string (i.e. 2023-10-07-)
export const getSlugFromFilename = (filename: string) => filename.substring(11)
export const getDateFromFilename = (filename: string) => filename.substring(0, 10)
@@ -28,6 +36,8 @@ interface GetPost {
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> {
@@ -47,14 +57,35 @@ export async function getPost(slug: string, category?: string): Promise<GetPost
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)
+ }
+
return {
slug,
title: post.attributes?.title,
- html: marked(post.body, { renderer }) as string,
+ html,
hidden: post.attributes?.hidden,
intro: post.attributes?.intro,
date: post.attributes?.date,
author: post.attributes?.author,
twitter_handle: post.attributes?.twitter_handle,
+ toc,
+ tocEmbedded: hasTocPlaceholder && toc.length > 0,
}
}
diff --git a/web/app/utils/toc.ts b/web/app/utils/toc.ts
new file mode 100644
index 000000000..7c0012d1e
--- /dev/null
+++ b/web/app/utils/toc.ts
@@ -0,0 +1,102 @@
+export interface TocItem {
+ id: string
+ text: string
+ level: number
+ children: TocItem[]
+}
+
+export function generateSlug(text: string): string {
+ return text
+ .toLowerCase()
+ .replace(/[^\w\s-]/g, '') // Remove special characters except spaces and hyphens
+ .replace(/\s+/g, '-') // Replace spaces with hyphens
+ .replace(/-+/g, '-') // Replace multiple hyphens with single hyphen
+ .trim()
+}
+
+export function renderTocAsHtml(items: TocItem[]): string {
+ if (items.length === 0) return ''
+
+ const renderTocList = (tocItems: TocItem[], level = 0, parentNum = ''): string => {
+ if (tocItems.length === 0) return ''
+
+ let html = `<ol class="${level > 0 ? '!my-0' : ''}">`
+
+ tocItems.forEach((item, index) => {
+ const currentNumber = parentNum ? `${parentNum}.${index + 1}` : `${index + 1}`
+
+ html += `<li class="flex flex-col">`
+ html += `<div class="flex items-start gap-0.5">`
+ html += `<span class="text-gray-600 dark:text-gray-400 font-medium mr-[1ch]">${currentNumber}.</span>`
+ html += `<a href="#${item.id}">${item.text}</a>`
+ html += `</div>`
+
+ if (item.children.length > 0) {
+ html += renderTocList(item.children, level + 1, currentNumber)
+ }
+
+ html += `</li>`
+ })
+
+ html += `</ol>`
+ return html
+ }
+
+ const tocHtml = renderTocList(items)
+
+ return tocHtml
+}
+
+export function extractTableOfContents(html: string): TocItem[] {
+ const headerRegex = /<h([1-6])(?:\s+id="([^"]*)")?[^>]*>(.*?)<\/h[1-6]>/gi
+ const tocItems: TocItem[] = []
+ const stack: TocItem[] = []
+ let match
+
+ while ((match = headerRegex.exec(html)) !== null) {
+ const level = parseInt(match[1])
+ const existingId = match[2]
+ const text = match[3].replace(/<[^>]*>/g, '').trim() // Remove HTML tags
+ const id = existingId || generateSlug(text)
+
+ const tocItem: TocItem = {
+ id,
+ text,
+ level,
+ children: [],
+ }
+
+ // Pop stack until we find a parent with lower level
+ while (stack.length > 0 && stack[stack.length - 1].level >= level) {
+ stack.pop()
+ }
+
+ if (stack.length === 0) {
+ // Top level item
+ tocItems.push(tocItem)
+ } else {
+ // Child item
+ stack[stack.length - 1].children.push(tocItem)
+ }
+
+ stack.push(tocItem)
+ }
+
+ return tocItems
+}
+
+export function ensureHeaderIds(html: string): string {
+ return html.replace(
+ /<h([1-6])(?:\s+id="([^"]*)")?([^>]*)>(.*?)<\/h[1-6]>/gi,
+ (match, level, existingId, attrs, content) => {
+ if (existingId) {
+ return match // Already has an ID
+ }
+
+ const text = content.replace(/<[^>]*>/g, '').trim()
+ const id = generateSlug(text)
+
+ return `<h${level} id="${id}"${attrs}>${content}</h${level}>`
+ },
+ )
+}