Skip to content
This repository has been archived by the owner on Sep 8, 2024. It is now read-only.

Commit

Permalink
add toc
Browse files Browse the repository at this point in the history
  • Loading branch information
noxify committed Jan 3, 2024
1 parent 1c78414 commit a39ad0a
Show file tree
Hide file tree
Showing 6 changed files with 182 additions and 19 deletions.
144 changes: 144 additions & 0 deletions apps/content/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,147 @@ code content
{% /tab %}

{% /tabs %}


## Spes terra illis cum silvas gaudere videtque

Lorem markdownum tu peto? Fessa peteretur tyranni nota aquaticus iussere, io
vivere, conditur meum ut lassaque. Adsiduo perveni Atrides postquam alte illa et
spernenda, late ferarum, modo. Reticere munus sui vertit est nescius adhuc
insuperabile nidos! Tumidam _hospes_ ferrum a pulsat inferius: aut es marmoris!

> Pectore ursaeque, fuit prolisque erit amnesque: nam datis viro caecaque
> resupino notavi. Quoque dolentius multi, has quicquam magni, ruunt omnia
> imagine? Delphice quae illo est cruor adhuc telisque et manu, amor,
> _causamque_ te vestes; rerum.
## Carituraque debet penetrabile alta imagine

Egerat solent, Iuppiter non rictus, Parnasosque illa; talia. Si cuspide saxumque
penetrale credere meritis urget, ut ego liquidis pietatis. Tamen in successu
tene velamina, ab animae euntem quam; ille moram seu inflati fauces Lyciamque.
Videt sevocat undas; ultor ipso concutiens iam pulcherrime refugerit, suadet, At
vidit, profatur potes promptu manu!

Cadit **tangit quo** sine valuere nulla, Philemon quoque luctantiaque. [Ante
exsecrantia](http://orant.com/sed.php) alis iam! Fluctusque utinam pennis deum
pocula cum. Tetigit avis aequoreis posses alto Tyriis, voce reor habet solet
postquam _adsuetaque_ regnat medium locis.

## Tanto ortas harenis collaque dant

Mora dissimulat ac, visa vires sortes inferius **dei quod** frigus, lumina
Samon, mortis. **Parte fluctus** tum, in invitam satis, _nominat retentis
videre_ finis tu et mendacia nomen. Huic illic abdita Terram.

Est verso praedam repetitaque mons esse, mora petenti haec scopulus ille
medioque, ne verumque, ales. Sideraque invidit. Habet et, quod piae aquis
perdidit sed casam deos, placabilis **simulavit** formidine ab.

Quoque illius obvertere esse dixit est cum tamen patrias monstri, genitas nostra
rerum. Mihi movit Rhodopen dolores refers summo, commonuit vera clamat versa et
uvis **monte summoque rarior**, Venus, Imbreus. Lacer tamen cupit, trans sacras
territaque, custodemque saltem Procne punior. Sparsos debita spes arma asperitas
turis ostendens dixerat!

## Tabs

### use first

{% tabs %}

{% tab label="Preview" %}
preview content
{% /tab %}

{% tab label="Code" %}
code content
{% /tab %}

{% /tabs %}

### custom default

{% tabs %}

{% tab label="Preview" %}
preview content
{% /tab %}

{% tab label="Code" default=true %}
code content
{% /tab %}

{% /tabs %}


## Spes terra illis cum silvas gaudere videtque

Lorem markdownum tu peto? Fessa peteretur tyranni nota aquaticus iussere, io
vivere, conditur meum ut lassaque. Adsiduo perveni Atrides postquam alte illa et
spernenda, late ferarum, modo. Reticere munus sui vertit est nescius adhuc
insuperabile nidos! Tumidam _hospes_ ferrum a pulsat inferius: aut es marmoris!

> Pectore ursaeque, fuit prolisque erit amnesque: nam datis viro caecaque
> resupino notavi. Quoque dolentius multi, has quicquam magni, ruunt omnia
> imagine? Delphice quae illo est cruor adhuc telisque et manu, amor,
> _causamque_ te vestes; rerum.
## Carituraque debet penetrabile alta imagine

Egerat solent, Iuppiter non rictus, Parnasosque illa; talia. Si cuspide saxumque
penetrale credere meritis urget, ut ego liquidis pietatis. Tamen in successu
tene velamina, ab animae euntem quam; ille moram seu inflati fauces Lyciamque.
Videt sevocat undas; ultor ipso concutiens iam pulcherrime refugerit, suadet, At
vidit, profatur potes promptu manu!

Cadit **tangit quo** sine valuere nulla, Philemon quoque luctantiaque. [Ante
exsecrantia](http://orant.com/sed.php) alis iam! Fluctusque utinam pennis deum
pocula cum. Tetigit avis aequoreis posses alto Tyriis, voce reor habet solet
postquam _adsuetaque_ regnat medium locis.

## Tanto ortas harenis collaque dant

Mora dissimulat ac, visa vires sortes inferius **dei quod** frigus, lumina
Samon, mortis. **Parte fluctus** tum, in invitam satis, _nominat retentis
videre_ finis tu et mendacia nomen. Huic illic abdita Terram.

Est verso praedam repetitaque mons esse, mora petenti haec scopulus ille
medioque, ne verumque, ales. Sideraque invidit. Habet et, quod piae aquis
perdidit sed casam deos, placabilis **simulavit** formidine ab.

Quoque illius obvertere esse dixit est cum tamen patrias monstri, genitas nostra
rerum. Mihi movit Rhodopen dolores refers summo, commonuit vera clamat versa et
uvis **monte summoque rarior**, Venus, Imbreus. Lacer tamen cupit, trans sacras
territaque, custodemque saltem Procne punior. Sparsos debita spes arma asperitas
turis ostendens dixerat!

## Tabs

### use first

{% tabs %}

{% tab label="Preview" %}
preview content
{% /tab %}

{% tab label="Code" %}
code content
{% /tab %}

{% /tabs %}

### custom default

{% tabs %}

{% tab label="Preview" %}
preview content
{% /tab %}

{% tab label="Code" default=true %}
code content
{% /tab %}

{% /tabs %}
37 changes: 26 additions & 11 deletions apps/docs/src/app/[...slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import path from "path"
import type { Metadata, ResolvingMetadata } from "next"
import React from "react"
import { Metadata, ResolvingMetadata } from "next"
import { notFound } from "next/navigation"

import {
components,
generateTableOfContents,
getAllDocuments,
getDocument,
Markdoc,
parseContent,
TableOfContents,
} from "@acme/markdoc-base"
import { SidebarNavigation } from "@acme/ui/components"

Expand All @@ -25,6 +27,14 @@ function getContentPath() {
return path.join(projectDirectory, "apps/content")
}

async function getContent({ params }: DocPageProps) {
const contentPath = getContentPath()

const parsedParams = `/${params.slug.join("/")}`

return await getDocument(contentPath, parsedParams)
}

export async function generateStaticParams(): Promise<
DocPageProps["params"][]
> {
Expand All @@ -38,27 +48,19 @@ export async function generateMetadata(
{ params }: DocPageProps,
parent: ResolvingMetadata,
): Promise<Metadata> {
const contentPath = getContentPath()
const parsedParams = `/${params.slug.join("/")}`

const document = await getDocument(contentPath, parsedParams)
const document = await getContent({ params })

const parentMeta = await parent

console.log({ parentMeta })

return {
applicationName: parentMeta.applicationName,
title: document?.frontmatter.title ?? parentMeta.title,
description: document?.frontmatter.description ?? parentMeta.description,
}
}
export default async function DocsPage({ params }: DocPageProps) {
const contentPath = getContentPath()

const parsedParams = `/${params.slug.join("/")}`
const document = await getContent({ params })

const document = await getDocument(contentPath, parsedParams)
if (!document) notFound()

const pageContent = await parseContent(document.docPath)
Expand All @@ -79,6 +81,19 @@ export default async function DocsPage({ params }: DocPageProps) {
components,
})}
</main>
<div className="hidden xl:sticky xl:top-[1.5rem] xl:-mr-6 xl:block xl:h-[calc(100vh-4.5rem)] xl:flex-none xl:overflow-y-auto xl:py-16 xl:pr-6">
<nav aria-labelledby="on-this-page-title" className="w-56">
<h2
id="on-this-page-title"
className="font-display text-sm font-medium text-foreground"
>
On this page
</h2>
<TableOfContents
toc={generateTableOfContents(pageContent.headings)}
/>
</nav>
</div>
</div>
</div>
</div>
Expand Down
1 change: 1 addition & 0 deletions packages/markdoc-base/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export { Markdoc, config, components }
export * from "./src/helpers"
export * from "./src/frontmatter"
export * from "./src/documents"
export * from "./src/components/table-of-contents"
8 changes: 4 additions & 4 deletions packages/markdoc-base/src/components/table-of-contents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import { useEffect, useMemo, useState } from "react"

import { cn } from "@acme/helpers"

import type { TableOfContents } from "../helpers"
import type { TableOfContentsProps } from "../helpers"

interface TocProps {
toc: TableOfContents[]
toc: TableOfContentsProps[]
}

interface TreeProps {
tree: TableOfContents[]
tree: TableOfContentsProps[]
level?: number
activeItem?: string
}
Expand Down Expand Up @@ -84,7 +84,7 @@ function Tree({ tree, level = 1, activeItem }: TreeProps) {
className={cn(
"inline-block no-underline transition-colors hover:text-foreground",
`#${item.id}` === `#${activeItem}`
? "font-medium text-foreground"
? "text-foreground"
: "text-muted-foreground",
)}
>
Expand Down
6 changes: 3 additions & 3 deletions packages/markdoc-base/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import type { HeadingNode } from "@acme/markdoc-typography/components"
import { config } from "./config"
import { getFrontmatter } from "./frontmatter"

export interface TableOfContents {
export interface TableOfContentsProps {
id: string
title: string
level: number
children?: TableOfContents[]
children?: TableOfContentsProps[]
}

export async function getFileContent(filePath: PathLike | fs.FileHandle) {
Expand Down Expand Up @@ -50,7 +50,7 @@ export async function parseContent(filePath: PathLike | fs.FileHandle) {
}

export function generateTableOfContents(headings: Tag[]) {
const sections: TableOfContents[] = []
const sections: TableOfContentsProps[] = []

for (const heading of headings) {
const attributes = (heading as unknown as HeadingNode).attributes
Expand Down
5 changes: 4 additions & 1 deletion packages/markdoc-typography/src/components/Heading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ export function Heading({ children, level, id }: HeadingProps) {
className={cn("group my-4 scroll-m-20 tracking-tight", headingClass)}
>
{children}
<a href={`#${id}`} className="ml-2 hidden group-hover:inline">
<a
href={`#${id}`}
className="ml-2 hidden text-muted-foreground hover:text-foreground group-hover:inline"
>
#
</a>
</HeadingTag>
Expand Down

0 comments on commit a39ad0a

Please sign in to comment.