Skip to content

Commit

Permalink
chore(refactor): create system to handle markdowns
Browse files Browse the repository at this point in the history
Co-authored-by: Gabriel Hijazi <[email protected]>
  • Loading branch information
pablo1v and Gabriel Hijazi committed Feb 17, 2021
1 parent fefa984 commit 40d6112
Show file tree
Hide file tree
Showing 14 changed files with 325 additions and 209 deletions.
6 changes: 6 additions & 0 deletions docs/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@ const sourceMaps = require('@zeit/next-source-maps');
const composePlugins = require('next-compose-plugins');
const optimizedImages = require('next-optimized-images');

const { REHYPE_PLUGINS, REMARK_PLUGINS } = require('./shared/plugins');

module.exports = composePlugins(
[
[sourceMaps],
[optimizedImages],
[
mdx({
extension: /\.mdx?$/,
options: {
rehypePlugins: REHYPE_PLUGINS,
remarkPlugins: REMARK_PLUGINS,
},
}),
],
[
Expand Down
6 changes: 4 additions & 2 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,22 @@
},
"dependencies": {
"@hitechline/react": "^1.0.7",
"@mapbox/rehype-prism": "^0.5.0",
"@mdx-js/loader": "^1.6.22",
"@mdx-js/mdx": "^1.6.22",
"@mdx-js/react": "^1.6.22",
"@mdx-js/runtime": "^1.6.22",
"@next/mdx": "^10.0.7",
"@tailwindcss/ui": "0.7.2",
"axios": "0.21.1",
"gray-matter": "^4.0.2",
"next": "10.0.3",
"postcss-nesting": "7.0.1",
"postcss-preset-env": "^6.7.0",
"prism-react-renderer": "^1.1.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-icons": "^4.1.0",
"remark": "^13.0.0",
"remark-html": "^13.0.1",
"remark-prism": "^1.3.4",
"tailwindcss": "1.9.6",
"url-join": "4.0.1"
Expand Down
3 changes: 3 additions & 0 deletions docs/shared/plugins.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export declare const REMARK_PLUGINS: any[];

export declare const REHYPE_PLUGINS: any[];
10 changes: 10 additions & 0 deletions docs/shared/plugins.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const REMARK_PLUGINS = [require('remark-prism')];

const REHYPE_PLUGINS = [require('@mapbox/rehype-prism')];

module.exports = {
REMARK_PLUGINS,
REHYPE_PLUGINS,
};

/* eslint import-helpers/order-imports: 0 */
54 changes: 24 additions & 30 deletions docs/src/pages/[...slug].tsx
Original file line number Diff line number Diff line change
@@ -1,46 +1,40 @@
import { promises } from 'fs';
import matter from 'gray-matter';
// import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
import { join } from 'path';
import { GetStaticProps, GetStaticPaths, GetStaticPathsResult } from 'next';
import React from 'react';
import remark from 'remark';
import html from 'remark-html';
import prism from 'remark-prism';

const Document = ({ content }) => {
return <div>{content}</div>;
};

export async function getStaticProps({ params }) {
const baseUrl = join(process.cwd(), 'src', 'markdown');
const documentPath = [].concat(params.slug).join('/');
import { getAllDocumentFiles } from '@utils/mdx/getAllDocumentFiles';
import { getDocument } from '@utils/mdx/getDocument';
import type { Document as DocumentType } from '@utils/mdx/types';

const documentFullPath = join(baseUrl, `${documentPath}.mdx`);
const fileContent = await promises.readFile(documentFullPath, 'utf8');
const Document = ({ content }) => (
<div>
<div dangerouslySetInnerHTML={{ __html: content }} />
</div>
);

const { data, content: markdown } = matter(fileContent);
const content = await remark().use(html).use(prism).process(markdown);
export const getStaticProps: GetStaticProps<
DocumentType,
{
slug: string[];
}
> = async ({ params }) => {
const document = await getDocument(params.slug);

return {
props: {
data,
content: content.toString(),
},
props: document,
};
}

export async function getStaticPaths() {
const baseUrl = join(process.cwd(), 'src', 'markdown');
};

const files = await promises.readdir(baseUrl);
type Paths = GetStaticPathsResult['paths'];

const paths = files.map(path => ({
export const getStaticPaths: GetStaticPaths = async () => {
const documents = await getAllDocumentFiles();
const paths: Paths = documents.map<Paths[number]>(({ slug }) => ({
params: {
slug: [path.replace(/\.mdx/, '')],
slug,
},
}));

return { paths, fallback: false };
}
};

export default Document;
7 changes: 7 additions & 0 deletions docs/src/utils/mdx/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { join } from 'path';

export const EXTENSION_MD = 'md';

export const EXTENSION_MDX = 'mdx';

export const BASE_PATH = join(process.cwd(), 'src', 'markdown');
11 changes: 11 additions & 0 deletions docs/src/utils/mdx/getAllDocumentFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { promises } from 'fs';

import { BASE_PATH } from './constants';
import { getFileInfo } from './getFileInfo';
import type { DocumentFile } from './types';

export async function getAllDocumentFiles(): Promise<DocumentFile[]> {
const files = await promises.readdir(BASE_PATH);

return files.map(path => getFileInfo(path));
}
24 changes: 24 additions & 0 deletions docs/src/utils/mdx/getDocument.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { promises } from 'fs';
import matter from 'gray-matter';
import ReactDOMServer from 'react-dom/server';

import { getFileInfo } from './getFileInfo';
import { makeMDX } from './makeMDX';
import { resolveFileBySlug } from './resolveFileBySlug';
import type { Document, DocumentData } from './types';

export async function getDocument(slug: string[]): Promise<Document> {
const filePath = await resolveFileBySlug(slug);
const info = getFileInfo(filePath);

const fileContent = await promises.readFile(info.fullPath, 'utf8');
const { data, content: markdown } = matter(fileContent);

const element = ReactDOMServer.renderToString(makeMDX(markdown)());

return {
info,
content: element,
data: data as DocumentData,
};
}
17 changes: 17 additions & 0 deletions docs/src/utils/mdx/getFileInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { join } from 'path';

import { BASE_PATH } from './constants';
import type { DocumentFile } from './types';

export function getFileInfo(filePath: string): DocumentFile {
const pathCleaned = filePath.replace(/\.mdx?/, '');
const pathSplited = pathCleaned.split(/\//g);

return {
path: filePath,
slug: pathSplited,
fullName: pathCleaned,
name: pathSplited.slice(-1)[0],
fullPath: join(BASE_PATH, filePath),
};
}
13 changes: 13 additions & 0 deletions docs/src/utils/mdx/makeMDX.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import MDX from '@mdx-js/runtime';
import { REMARK_PLUGINS, REHYPE_PLUGINS } from '@shared/plugins';
import React from 'react';

export function makeMDX(content: any): () => JSX.Element {
return () => (
<MDX remarkPlugins={REMARK_PLUGINS} rehypePlugins={REHYPE_PLUGINS}>
{content}
</MDX>
);
}

/* eslint react/display-name:0 */
35 changes: 35 additions & 0 deletions docs/src/utils/mdx/resolveFileBySlug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { promises } from 'fs';
import { join } from 'path';

import { BASE_PATH, EXTENSION_MD, EXTENSION_MDX } from './constants';

export async function resolveFileBySlug(slug: string[]): Promise<string> {
const array: string[] = [];
const slugParsed = array.concat(slug).join('/');
const slugFullPath = join(BASE_PATH, slugParsed);

const hasFileWithExtension_MD = await exists(
`${slugFullPath}.${EXTENSION_MD}`,
);

if (hasFileWithExtension_MD) {
return `${slugParsed}.${EXTENSION_MD}`;
}

const hasFileWithExtension_MDX = await exists(
`${slugFullPath}.${EXTENSION_MDX}`,
);

if (hasFileWithExtension_MDX) {
return `${slugParsed}.${EXTENSION_MDX}`;
}

throw new Error('File not existis.');
}

async function exists(path: string): Promise<boolean> {
return promises
.access(path)
.then(() => true)
.catch(() => false);
}
17 changes: 17 additions & 0 deletions docs/src/utils/mdx/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export interface DocumentFile {
path: string;
name: string;
fullName: string;
fullPath: string;
slug: string[];
}

export interface DocumentData {
title: string;
}

export interface Document {
content: string;
info: DocumentFile;
data: DocumentData;
}
51 changes: 13 additions & 38 deletions docs/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
{
"exclude": [
"node_modules"
],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"compilerOptions": {
"rootDir": ".",
"baseUrl": "src",
"baseUrl": ".",
"jsx": "preserve",
"module": "ESNext",
"target": "ESNext",
Expand All @@ -22,36 +16,17 @@
"esModuleInterop": true,
"resolveJsonModule": true,
"forceConsistentCasingInFileNames": true,
"lib": [
"DOM",
"ESNext",
"DOM.Iterable"
],
"lib": ["DOM", "ESNext", "DOM.Iterable"],
"paths": {
"@/*": [
"*"
],
"@utils/*": [
"utils/*"
],
"@styles/*": [
"styles/*"
],
"@services/*": [
"services/*"
],
"@fixtures/*": [
"fixtures/*"
],
"@sections/*": [
"sections/*"
],
"@layout": [
"components/Layout"
],
"@components/*": [
"components/*"
]
"@/*": ["src/*"],
"@shared/*": ["shared/*"],
"@utils/*": ["src/utils/*"],
"@styles/*": ["src/styles/*"],
"@services/*": ["services/*"],
"@fixtures/*": ["src/fixtures/*"],
"@sections/*": ["src/sections/*"],
"@layout": ["src/components/Layout"],
"@components/*": ["src/components/*"]
}
}
}
Loading

0 comments on commit 40d6112

Please sign in to comment.