Skip to content
This repository has been archived by the owner on Oct 27, 2021. It is now read-only.

Initial working version with MDX remote #9

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"semi": false
}
8 changes: 4 additions & 4 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
// [[wiki-links]], backlinking etc
"kortina.vscode-markdown-notes",

// Adds `show graph` command that displays graph of linked notes
"tchayen.markdown-links",
// Image-pasting for markdown
"mushan.vscode-paste-image",

// Understated grayscale theme (light and dark variants)
"philipbe.theme-gray-matter"
// Spell checking for text, markdown and latex
"ban.spellright",
]
}
20 changes: 15 additions & 5 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,29 @@
"editor.minimap.enabled": false,
"editor.wrappingIndent": "indent",
"editor.overviewRulerBorder": false,
"editor.lineHeight": 24,
"workbench.colorTheme": "Gray Matter Light",
"[markdown]": {
"editor.lineHeight": 24,
"editor.quickSuggestions": true
},
"git.enableSmartCommit": true,
"git.postCommitCommand": "sync",
"files.defaultLanguage": "markdown",
"files.exclude": {
"**/node_modules": true
},
"files.watcherExclude": {
"**/node_modules": true
},
"foam.edit.linkReferenceDefinitions": "withExtensions",
"foam.openDailyNote.directory": "_posts",
"foam.openDailyNote.fileExtension": "mdx",
"foam.openDailyNote.titleFormat": "fullDate",
"git.enableSmartCommit": true,
"git.postCommitCommand": "sync",
"markdown.preview.breaks": true,
"pasteImage.path": "${projectRoot}/public/images",
"pasteImage.showFilePathConfirmInputBox": true,
"spellright.notificationClass": "warning",
"vscodeMarkdownNotes.defaultFileExtension": "mdx",
"vscodeMarkdownNotes.noteCompletionConvention": "noExtension",
"vscodeMarkdownNotes.slugifyMethod": "github-slugger"
"vscodeMarkdownNotes.slugifyMethod": "github-slugger",
"window.autoDetectColorScheme": true
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import Button from '../components/button.js'

# JSX Component in Mdx Example

Look, a button! 👇

<Button>👋 Hello</Button>


File renamed without changes.
8 changes: 0 additions & 8 deletions pages/readme.md → _posts/readme.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,3 @@ We've created a few Bubbles (markdown documents) to get you started.
They should work as expected in VS Code, and in rendered GitHub Pages.

If GitHub preview (or general 100% support with all Markdown tools) is a requirement, for the time being you can use the standard `[description](page.md)` syntax.



[//begin]: # "Autogenerated link references for markdown compatibility"
[inbox]: inbox "Inbox"
[foam-tips]: foam-tips "Foam tips"
[todo]: todo "Todo"
[//end]: # "Autogenerated link references"
File renamed without changes.
15 changes: 15 additions & 0 deletions components/MDXComponents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import dynamic from 'next/dynamic'
import AnchorTag from '../components/AnchorTag'
import CodeBlock from '../components/CodeBlock'
import Image from '../components/Image'

// prettier-ignore
const MDXComponents = {
a: props => <AnchorTag {...props} />,
code: CodeBlock,
img: (props) => <div className="nextImageWrapper"><Image {...props} /></div>,
Image: (props) => <div className="nextImageWrapper"><Image {...props} /></div>,
Button: dynamic(() => import('../components/button')),
}

export default MDXComponents
92 changes: 92 additions & 0 deletions lib/mdx.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import fs from 'fs'
import matter from 'gray-matter'
import renderToString from 'next-mdx-remote/render-to-string'
import path from 'path'
import remarkExternalLinks from 'remark-external-links'
import remarkImages from 'remark-images'
import remarkInlineLinks from 'remark-inline-links'
import remarkFootnote from 'remark-numbered-footnote-labels'
import remarkUnwrapImages from 'remark-unwrap-images'
import remarkWikiLink from 'remark-wiki-link'
import MDXComponents from '../components/MDXComponents'

const root = process.cwd()
const POSTS_DIR = '_posts'

// POSTS_PATH is useful when you want to get the path to a specific file
export const POSTS_PATH = path.join(root, POSTS_DIR)

export const getAllFiles = function (dirPath, arrayOfFiles) {
let files = fs.readdirSync(dirPath)

arrayOfFiles = arrayOfFiles || []

files.forEach(function (file) {
if (fs.statSync(`${dirPath}/${file}`).isDirectory()) {
arrayOfFiles = getAllFiles(`${dirPath}/${file}`, arrayOfFiles)
} else {
arrayOfFiles.push(
path.join(dirPath, '/', file).replace(`${POSTS_PATH}/`, '')
)
}
})

return arrayOfFiles
}

// postFilePaths is the list of all mdx files inside the POSTS_PATH directory
export const postFilePaths = getAllFiles(POSTS_PATH)
// Only include md(x) files
.filter((path) => /\.mdx?$/.test(path))

export async function getFileBySlug(slug) {
const postFilePath = path.join(root, POSTS_DIR, `${slug}.mdx`)
const source = fs.readFileSync(postFilePath, 'utf8')

const { data, content } = matter(source)
const mdxSource = await renderToString(content, {
components: MDXComponents,
mdxOptions: {
remarkPlugins: [
remarkImages,
remarkExternalLinks,
remarkFootnote,
remarkInlineLinks,
remarkUnwrapImages,
[
remarkWikiLink,
{
hrefTemplate: (permalink) => `${permalink}`,
pageResolver: (name) => [name.replace(/ /g, '-').toLowerCase()],
},
],
],
},
scope: data,
})

return {
mdxSource,
frontMatter: {
slug: slug || null,
...data,
},
}
}

export async function getAllFilesFrontMatter() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this imported?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nowhere yet... I've kept it in case of wanting a blog listing somewhere

const files = fs.readdirSync(path.join(root, POSTS_DIR))

return files.reduce((allPosts, postSlug) => {
const source = fs.readFileSync(path.join(root, POSTS_DIR, postSlug), 'utf8')
const { data } = matter(source)

return [
{
...data,
slug: postSlug.replace('.mdx', ''),
},
...allPosts,
]
}, [])
}
19 changes: 0 additions & 19 deletions next.config.js

This file was deleted.

101 changes: 0 additions & 101 deletions package-lock.json

This file was deleted.

8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@
"start": "next start"
},
"dependencies": {
"@mdx-js/loader": "^1.6.21",
"@next/mdx": "^10.0.1",
"gray-matter": "4.0.2",
"next": "^10.0.1",
"next-mdx-remote": "2.1.3",
"prism-react-renderer": "^1.1.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"remark-external-links": "^7.0.0",
"remark-images": "^2.0.0",
"remark-inline-links": "5.0.0",
"remark-numbered-footnote-labels": "^1.1.0",
"remark-unwrap-images": "^2.0.0"
"remark-unwrap-images": "^2.0.0",
"remark-wiki-link": "0.0.4"
},
"devDependencies": {},
"license": "ISC"
Expand Down
34 changes: 34 additions & 0 deletions pages/[...slug].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import hydrate from 'next-mdx-remote/hydrate'
import MDXComponents from '../components/MDXComponents'
import { getAllFiles, getFileBySlug, POSTS_PATH } from '../lib/mdx'

export default function PostPage({ mdxSource, frontMatter }) {
const content = hydrate(mdxSource, { components: MDXComponents })
return content
}

export const getStaticProps = async ({ params }) => {
let slug = 'index'

if (params && params.slug) {
slug = Array.isArray(params.slug) ? params.slug.join('/') : params.slug
}

const post = await getFileBySlug(slug)

return { props: post }
}

export const getStaticPaths = async () => {
const posts = await getAllFiles(POSTS_PATH)
const paths = posts
// Remove file extensions for page paths
.map((path) => path.replace(/\.mdx?$/, ''))
// Map the path into the static paths object required by Next.js
.map((slug) => ({ params: { slug: slug.split('/') } }))

return {
paths,
fallback: false,
}
}
16 changes: 3 additions & 13 deletions pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,14 @@ import '../styles/global.css'
import '../styles/prism-theme-night-owl.css'
import Layout from '../components/Layout'
import siteData from '../siteconfig'
import { MDXProvider } from '@mdx-js/react'
import CodeBlock from '../components/CodeBlock'
import AnchorTag from '../components/AnchorTag'
import Image from '../components/Image'

const mdComponents = {
a: props => <AnchorTag {...props} />,
code: CodeBlock,
img: (props) => <div className="nextImageWrapper"><Image {...props} /></div>,
Image: (props) => <div className="nextImageWrapper"><Image {...props} /></div>
}

export default function App({ Component, pageProps }) {
return (
<MDXProvider components={mdComponents}>
<Layout siteData={siteData}>
<Component {...pageProps} />
</Layout>
</MDXProvider>
<Layout siteData={siteData}>
<Component {...pageProps} />
</Layout>
)
}
1 change: 1 addition & 0 deletions pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default, getStaticProps } from './[...slug]'
Loading