Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add help article page and table of contents
Marc Seitz1ebeebd9ed64
diff --git a/app/(static)/help/[slug]/page.tsx b/app/(static)/help/article/[slug]/page.tsxsimilarity index 51%rename from app/(static)/help/[slug]/page.tsxrename to app/(static)/help/article/[slug]/page.tsxindex 5b79efbb..8d3829d8 100644--- a/app/(static)/help/[slug]/page.tsx+++ b/app/(static)/help/article/[slug]/page.tsx@@ -1,14 +1,23 @@-import { getHelpPosts, getHelpPost } from "@/lib/content/help";+import { getHelpArticles, getHelpArticle } from "@/lib/content/help";import { ContentBody } from "@/components/mdx/post-body";import { notFound } from "next/navigation";import Link from "next/link";import BlurImage from "@/components/blur-image";import { constructMetadata, formatDate } from "@/lib/utils";import { Metadata } from "next";+import {+ Breadcrumb,+ BreadcrumbItem,+ BreadcrumbLink,+ BreadcrumbList,+ BreadcrumbPage,+ BreadcrumbSeparator,+} from "@/components/ui/breadcrumb";+import TableOfContents from "@/components/mdx/table-of-contents";export async function generateStaticParams() {- const posts = await getHelpPosts();- return posts.map((post) => ({ slug: post?.data.slug }));+ const articles = await getHelpArticles();+ return articles.map((article) => ({ slug: article?.data.slug }));}export const generateMetadata = async ({@@ -18,10 +27,10 @@ export const generateMetadata = async ({slug: string;};}): Promise<Metadata> => {- const post = (await getHelpPosts()).find(- (post) => post?.data.slug === params.slug,+ const article = (await getHelpArticles()).find(+ (article) => article?.data.slug === params.slug,);- const { title, summary: description, image } = post?.data || {};+ const { title, summary: description, image } = article?.data || {};return constructMetadata({title: `${title} - Papermark`,@@ -35,24 +44,40 @@ export default async function BlogPage({}: {params: { slug: string };}) {- const post = await getHelpPost(params.slug);- if (!post) return notFound();+ const article = await getHelpArticle(params.slug);+ if (!article) return notFound();++ // const category = article.data.categories ? article.data.categories[0] : "";return (<><div className="max-w-7xl w-full mx-auto px-4 md:px-8 mb-10"><div className="flex max-w-screen-sm flex-col space-y-4 pt-16"><div className="flex items-center space-x-4">- <time dateTime={post.data.publishedAt} className="text-sm">- {formatDate(post.data.publishedAt)}- </time>+ <Breadcrumb>+ <BreadcrumbList>+ <BreadcrumbItem>+ <BreadcrumbPage>Help Center</BreadcrumbPage>+ </BreadcrumbItem>+ {/* <BreadcrumbSeparator />+ <BreadcrumbItem>+ <BreadcrumbLink asChild>+ <Link href={`/help/category/${category}`}>{category}</Link>+ </BreadcrumbLink>+ </BreadcrumbItem> */}+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ <BreadcrumbPage>{article.data.title}</BreadcrumbPage>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb></div>- <h1 className="text-4xl md:text-6xl text-balance">- {post.data.title}+ <h1 className="text-4xl md:text-5xl text-balance">+ {article.data.title}</h1>- <p className="text-xl text-gray-600">{post.data.summary}</p>+ <p className="text-lg text-gray-600">{article.data.summary}</p>- <div className="items-center space-x-4 flex flex-col self-start sm:hidden">+ <div className="items-center space-x-4 flex flex-col self-start"><Linkhref={`https://twitter.com/mfts0`}className="group flex items-center space-x-3"@@ -72,39 +97,28 @@ export default async function BlogPage({</div></Link></div>+ <div className="flex items-center space-x-4 text-gray-700">+ <time dateTime={article.data.publishedAt} className="text-sm">+ Last updated {formatDate(article.data.publishedAt, true)}+ </time>+ </div></div></div><div className="relative"><div className="grid grid-cols-4 gap-10 py-10 max-w-7xl w-full mx-auto px-4 md:px-8">- <div className="relative col-span-4 mb-10 flex flex-col space-y-8 bg-white md:col-span-3 sm:border-r sm:border-orange-500/50">- <div className="prose prose-h2:mb-2 first:prose-h2:mt-0 prose-h2:mt-10 prose-headings:font-medium sm:max-w-screen-md sm:pr-2 md:pr-0">- <ContentBody>{post.body}</ContentBody>+ <div className="relative col-span-4 mb-10 flex flex-col space-y-8 bg-white md:col-span-3 sm:border-r sm:border-orange-500">+ <div+ data-mdx-container+ className="prose prose-h2:mb-2 first:prose-h2:mt-0 prose-h2:mt-10 prose-headings:font-medium sm:max-w-screen-md sm:pr-2 md:pr-0"+ >+ <ContentBody>{article.body}</ContentBody></div></div><div className="sticky top-14 col-span-1 hidden flex-col divide-y divide-gray-200 self-start sm:flex"><div className="flex flex-col space-y-4">- <p className="text-sm text-gray-500">Written by</p>- {/* <Author username={data.author} /> */}- <Link- href={`https://twitter.com/mfts0`}- className="group flex items-center space-x-3"- target="_blank"- rel="noopener noreferrer"- >- <BlurImage- src={`https://pbs.twimg.com/profile_images/1176854646343852032/iYnUXJ-m_400x400.jpg`}- alt={`Marc Seitz`}- width={40}- height={40}- className="rounded-full transition-all group-hover:brightness-90"- />- <div className="flex flex-col">- <p className="font-semibold text-gray-700">Marc Seitz</p>- <p className="text-sm text-gray-500">@mfts0</p>- </div>- </Link>+ <TableOfContents items={article.toc} /></div></div></div>diff --git a/components/mdx/components/index.tsx b/components/mdx/components/index.tsxindex ff08aac6..fa3e8b5a 100644--- a/components/mdx/components/index.tsx+++ b/components/mdx/components/index.tsx@@ -63,5 +63,23 @@ export const mdxComponents: MDXComponents = {</Link>);},+ h2: ({ children, ...props }) => (+ <h2+ data-mdx-heading+ className="text-2xl font-semibold text-black"+ id={props.id}+ >+ {children}+ </h2>+ ),+ h3: ({ children, ...props }) => (+ <h3+ data-mdx-heading+ className="text-xl font-semibold text-black"+ id={props.id}+ >+ {children}+ </h3>+ ),// any other components you want to use in your markdown};diff --git a/components/mdx/table-of-contents.tsx b/components/mdx/table-of-contents.tsxnew file mode 100644index 00000000..68a61743--- /dev/null+++ b/components/mdx/table-of-contents.tsx@@ -0,0 +1,105 @@+"use client";++// import useCurrentAnchor from "#/lib/hooks/use-current-anchor";+import { cn } from "@/lib/utils";+import slugify from "@sindresorhus/slugify";+import Link from "next/link";++export default function TableOfContents({+ items,+}: {+ items: {+ text: string;+ level: number;+ }[];+}) {+ const currentAnchor = useCurrentAnchor();++ return (+ <div className="grid gap-4 -ml-[2.55rem] pl-10 border-l border-orange-500">+ {items &&+ items.map((item, idx) => {+ const itemId = slugify(item.text);+ return (+ <Link+ key={itemId}+ href={`#${itemId}`}+ className={cn("text-sm text-gray-500 ", {+ "border-l-2 border-black -ml-[2.6rem] pl-10 text-black":+ currentAnchor ? currentAnchor === itemId : idx === 0,+ })}+ >+ {item.text}+ </Link>+ );+ })}+ </div>+ );+}++import { useEffect, useState } from "react";++function useCurrentAnchor() {+ const [currentAnchor, setCurrentAnchor] = useState<string | null>(null);++ useEffect(() => {+ const mdxContainer: HTMLElement | null = document.querySelector(+ "[data-mdx-container]",+ );++ if (!mdxContainer) return;++ const offsetTop = 200;++ const observer = new IntersectionObserver(+ (entries) => {+ let currentEntry = entries[0];+ if (!currentEntry) return;++ const offsetBottom =+ (currentEntry.rootBounds?.height || 0) * 0.3 + offsetTop;++ for (let i = 1; i < entries.length; i++) {+ const entry = entries[i];+ if (!entry) break;++ if (+ entry.boundingClientRect.top <+ currentEntry.boundingClientRect.top ||+ currentEntry.boundingClientRect.bottom < offsetTop+ ) {+ currentEntry = entry;+ }+ }++ let target: Element | undefined = currentEntry.target;++ // if the target is too high up, we need to find the next sibling+ while (target && target.getBoundingClientRect().bottom < offsetTop) {+ target = siblings.get(target)?.next;+ }++ // if the target is too low, we need to find the previous sibling+ while (target && target.getBoundingClientRect().top > offsetBottom) {+ target = siblings.get(target)?.prev;+ }+ if (target) setCurrentAnchor(target.id);+ },+ {+ threshold: 1,+ rootMargin: `-${offsetTop}px 0px 0px 0px`,+ },+ );++ const siblings = new Map();++ const anchors = mdxContainer?.querySelectorAll("[data-mdx-heading]");+ anchors.forEach((anchor) => observer.observe(anchor));++ return () => {+ observer.disconnect();+ };+ }, []);++ return currentAnchor?.replace("#", "");+}diff --git a/lib/content/help.ts b/lib/content/help.tsindex 664e9538..b5d5424d 100644--- a/lib/content/help.ts+++ b/lib/content/help.ts@@ -1,7 +1,7 @@import matter from "gray-matter";import { cache } from "react";-type Post = {+type Article = {data: {title: string;summary: string;@@ -10,14 +10,16 @@ type Post = {image: string;slug: string;published: boolean;+ categories?: string[];};body: string;+ toc: { text: string; level: number }[];};const GITHUB_CONTENT_TOKEN = process.env.GITHUB_CONTENT_TOKEN;const GITHUB_CONTENT_REPO = process.env.GITHUB_CONTENT_REPO;-export const getHelpPosts = cache(async () => {+export const getHelpArticles = cache(async () => {const apiUrl = `https://api.github.com/repos/${GITHUB_CONTENT_REPO}/contents/content/help`;const headers = {Authorization: `Bearer ${GITHUB_CONTENT_TOKEN}`,@@ -28,7 +30,7 @@ export const getHelpPosts = cache(async () => {const response = await fetch(apiUrl, { headers });const data = await response.json();- const posts = await Promise.all(+ const articles = await Promise.all(data.filter((file: any) => file.name.endsWith(".mdx")).map(async (file: any) => {@@ -42,15 +44,40 @@ export const getHelpPosts = cache(async () => {return null;}- return { data, body: fileContent } as Post;+ const headingItems = await getHeadings(fileContent);++ return { data, body: fileContent, toc: headingItems } as Article;}),);- const filteredPosts = posts.filter((post: Post) => post !== null) as Post[];- return filteredPosts;+ const filteredArticles = articles.filter(+ (article: Article) => article !== null,+ ) as Article[];+ return filteredArticles;});-export async function getHelpPost(slug: string) {- const posts = await getHelpPosts();- return posts.find((post) => post?.data.slug === slug);+export async function getHelpArticle(slug: string) {+ const articles = await getHelpArticles();+ return articles.find((article) => article?.data.slug === slug);+}++async function getHeadings(source: string) {+ // Get each line individually, and filter out anything that+ // isn't a heading.+ const headingLines = source.split("\n").filter((line) => {+ return line.match(/^###*\s/);+ });++ // Transform the string '## Some text' into an object+ // with the shape '{ text: 'Some text', level: 2 }'+ return headingLines.map((raw) => {+ const text = raw.replace(/^###*\s/, "");+ // I only care about h2.+ // If I wanted more levels, I'd need to count the+ // number of #s.+ // match only h2+ const level = raw.slice(0, 3) === "###" ? 3 : 2;++ return { text, level };+ });}diff --git a/lib/utils.ts b/lib/utils.tsindex e954cc51..c7c8ed74 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -53,7 +53,10 @@ export const log = async ({mention?: boolean;}) => {/* If in development or env variable not set, log to the console */- if (process.env.NODE_ENV === "development" || !process.env.PPMK_SLACK_WEBHOOK_URL) {+ if (+ process.env.NODE_ENV === "development" ||+ !process.env.PPMK_SLACK_WEBHOOK_URL+ ) {console.log(message);return;}@@ -232,11 +235,15 @@ export const getFirstAndLastDay = (day: number) => {}};-export const formatDate = (dateString: string) => {+export const formatDate = (dateString: string, updateDate?: boolean) => {return new Date(dateString).toLocaleDateString("en-US", {day: "numeric",month: "long",- year: "numeric",+ year:+ updateDate &&+ new Date(dateString).getFullYear() === new Date().getFullYear()+ ? undefined+ : "numeric",timeZone: "UTC",});};@@ -419,12 +426,12 @@ export const generateGravatarHash = (email: string | null): string => {};export const sanitizeAllowDenyList = (list: string): string[] => {- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;- const domainRegex = /^@[^\s@]+\.[^\s@]+$/;-- return list- .split("\n")- .map(item => item.trim().replace(/,$/, '')) // Trim whitespace and remove trailing commas- .filter(item => item !== "") // Remove empty items- .filter(item => emailRegex.test(item) || domainRegex.test(item)); // Remove items that don't match email or domain regex- };\ No newline at end of file+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;+ const domainRegex = /^@[^\s@]+\.[^\s@]+$/;++ return list+ .split("\n")+ .map((item) => item.trim().replace(/,$/, "")) // Trim whitespace and remove trailing commas+ .filter((item) => item !== "") // Remove empty items+ .filter((item) => emailRegex.test(item) || domainRegex.test(item)); // Remove items that don't match email or domain regex+};