Skip to content

Commit

Permalink
Merge pull request #89 from lumirlumir/feat-category
Browse files Browse the repository at this point in the history
feat: category
  • Loading branch information
lumirlumir authored Oct 7, 2024
2 parents 619dba3 + 29ad4be commit 455c67b
Show file tree
Hide file tree
Showing 42 changed files with 263 additions and 86 deletions.
41 changes: 41 additions & 0 deletions archives/Categories.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { join } from 'path';

import Link from 'next/link';

import { DOCS, EXTENSION } from '@/constants/path';
import { readDirTree } from '@/utils/fs/dirTree';

/* Custom Declaration */
const { md, mdRegExp } = EXTENSION;

function renderDirTree(dirTree, basePath = '') {
return (
<ul>
{dirTree.map(dirTreeNode => {
const currPath = join(basePath, dirTreeNode.name);

return (
<li key={currPath}>
{dirTreeNode.name.endsWith(md) ? (
<Link href={`/posts/${currPath.replace(mdRegExp, '')}`}>
{dirTreeNode.name.replace(mdRegExp, '')}
</Link>
) : (
<>
<span>{dirTreeNode.name}</span>
{renderDirTree(dirTreeNode.children, currPath)}
</>
)}
</li>
);
})}
</ul>
);
}

/* React Declaration */
export default async function Categories() {
const dirTree = await readDirTree(DOCS);

return <>{renderDirTree(dirTree)}</>;
}
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
},
"dependencies": {
"@giscus/react": "^3.0.0",
"@types/node": "^22.7.4",
"@vercel/analytics": "^1.3.1",
"@vercel/speed-insights": "^1.0.12",
"github-markdown-css": "^5.7.0",
Expand Down
24 changes: 24 additions & 0 deletions src/app/categories/[tag]/page.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Link from 'next/link';

import { DOCS, EXTENSION } from '@/constants/path';
import { readTagTree } from '@/utils/fs/tagTree';
import markdownToText from '@/utils/markdownToText';

const { mdRegExp } = EXTENSION;

export default async function Page({ params }) {
const tagTree = await readTagTree(DOCS);

return tagTree[params.tag].map(({ basename, data: { title, description, tags } }) => (
<div key={basename}>
<h2>
<Link href={`/posts/${basename.replace(mdRegExp, '')}`}>
{markdownToText(title)}
</Link>
</h2>
<p>{markdownToText(description)}</p>
<p>{tags.join(', ')}</p>
<hr />
</div>
));
}
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,35 +1,31 @@
import { promises as fs } from 'fs';
import { join, sep } from 'path';
import { join } from 'path';

import { DOCS } from '@/constants/path';
import markdownToJsx, { readMarkdownWithFrontMatter } from '@/utils/markdownToJsx';
import { DOCS, EXTENSION } from '@/constants/path';
import { readFileForMarkdown, readDirByExtension } from '@/utils/fs';
import markdownToJsx from '@/utils/markdownToJsx';
import markdownToText from '@/utils/markdownToText';

/* Custom Declaration */
const { md, mdRegExp } = EXTENSION;

function getFilePath(params) {
return join(DOCS, `${params.categories.join(sep)}.md`);
return join(DOCS, `${params.markdown}${md}`);
}

/* Next.js Declaration */
// Control what happens when a dynamic segment is visited that was not generated with `generateStaticParams`.
export const dynamicParams = false;

export async function generateStaticParams() {
const paths = await fs.readdir(DOCS, {
recursive: true,
});

return paths
.filter(path => path.endsWith('.md'))
.map(path => ({
categories: path.replace(/\.md$/, '').split(sep),
}));
const paths = await readDirByExtension(DOCS, md);

return paths.map(path => ({
markdown: path.replace(mdRegExp, ''),
}));
}

export async function generateMetadata({ params }) {
const {
data: { title, description },
} = await readMarkdownWithFrontMatter(getFilePath(params));
const { title, description } = await readFileForMarkdown(getFilePath(params), 'data');

return {
title: markdownToText(title),
Expand Down
35 changes: 9 additions & 26 deletions src/components/aside/Categories/Categories.jsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,20 @@
import { join } from 'path';

import Link from 'next/link';

import { DOCS } from '@/constants/path';
import { getDirTree } from '@/utils/dirTree';
import { readTagTree } from '@/utils/fs/tagTree';

/* React Declaration */
export default async function Categories() {
const dirTree = await getDirTree(DOCS);

return <>{renderDirTree(dirTree)}</>;
}
const tagTree = await readTagTree(DOCS);

function renderDirTree(dirTree, basePath = '') {
return (
<ul>
{dirTree.map(dirTreeNode => {
const currPath = join(basePath, dirTreeNode.name);

return (
<li key={currPath}>
{dirTreeNode.name.endsWith('.md') ? (
<Link href={`/docs/${currPath.replace('.md', '')}`}>
{dirTreeNode.name.replace('.md', '')}
</Link>
) : (
<>
<span>{dirTreeNode.name}</span>
{renderDirTree(dirTreeNode.children, currPath)}
</>
)}
</li>
);
})}
{Object.keys(tagTree).map(key => (
<li key={key}>
<Link href={`/categories/${key}`}>{key}</Link>
<span>&nbsp;({tagTree[key].length})</span>
</li>
))}
</ul>
);
}
2 changes: 1 addition & 1 deletion src/components/layouts/Aside/Aside.module.scss
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
.aside {
position: sticky;
top: 0;
width: 300px;
width: 250px;
height: 100vh;
overflow-y: scroll;
background-color: inherit;
Expand Down
2 changes: 1 addition & 1 deletion src/constants/github.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
export const USER = Object.freeze({
login: 'lumirlumir',
name: '루밀LuMir',
bio: 'ᗩᖇTIᔕT🎨『PLAY KEYBOARD, STRIKE A CODE',
bio: 'PLAY KEYBOARD, STRIKE A CODE🎨',
get htmlUrl() {
return `https://github.com/${this.login}`;
},
Expand Down
7 changes: 7 additions & 0 deletions src/constants/path.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import { join } from 'path';

export const DOCS = join(process.cwd(), 'src', 'posts', 'docs');

export const EXTENSION = Object.freeze({
md: '.md',
get mdRegExp() {
return new RegExp(`${this.md}$`, 'i');
},
});
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
26 changes: 26 additions & 0 deletions src/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Represents a Markdown file structure with its content and data(front matter).
*/
export type Markdown = {
content: string;
data: {
[key: string]: any;
};
};

/**
* Represents a node in a directory tree.
*/
export type DirTreeNode = {
name: string; // The name of the node.
children?: DirTreeNode[]; // The array of child nodes if the node is a directory. This is a recursive structure.
};

/**
* Represents a node in a tag tree.
*/
export type TagTreeNode = {
[key: string]: {
basename: string;
} & Markdown;
};
22 changes: 9 additions & 13 deletions src/utils/dirTree.js → src/utils/fs/dirTree.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,31 @@
// @ts-check
import { promises as fs } from 'fs';
import { join } from 'path';

/**
* @typedef {object} DirTreeNode
*
* @property {string} name The name of the node.
* @property {Array<DirTreeNode>} [children] The array of child nodes if the node is a directory. This is a recursive structure.
* @typedef {import('@/types').DirTreeNode} DirTreeNode
*/

/**
* Asynchronously retrieves the directory tree structure.
*
* @async
* @param {string} dirPath The path of the directory.
* @returns {Promise<Array<DirTreeNode>>} A promise that resolves to an array of `DirTreeNode`.
*
* @returns {Promise<DirTreeNode[]>} A promise that resolves to an array of `DirTreeNode`.
* @example
* // Get the directory tree structure
* const dirTree = await getDirTree('/path/to/dir');
* // Read the directory tree structure
* const dirTree = await readDirTree('/path/to/dir');
* console.log(dirTree);
*/
export async function getDirTree(dirPath) {
export async function readDirTree(dirPath) {
// `readdir` automatically throws an error when `dirPath` is not a directory.
const dirents = await fs.readdir(dirPath, { withFileTypes: true });

return await Promise.all(
dirents.map(async dirent => ({
name: dirent.name,
...(dirent.isDirectory()
? { children: await getDirTree(join(dirPath, dirent.name)) }
? { children: await readDirTree(join(dirPath, dirent.name)) }
: {}),
})),
);
Expand All @@ -39,12 +36,11 @@ export async function getDirTree(dirPath) {
*
* @param {DirTreeNode} dirTreeNode The `DirTreeNode` object.
* @returns {boolean} `true` if the node is a directory. otherwise, `false`.
*
* @example
* // Check if a node is a directory
* const isDir = isDirectory({ name: 'folder', children: [...] });
* const isDir = isDir({ name: 'folder', children: [...] });
* console.log(isDir); // true
*/
export function isDirectory(dirTreeNode) {
export function isDir(dirTreeNode) {
return Boolean(dirTreeNode.children);
}
65 changes: 65 additions & 0 deletions src/utils/fs/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// @ts-check
import { promises as fs } from 'fs';

import matter from 'gray-matter';

/**
* @typedef {import('fs').ObjectEncodingOptions} ObjectEncodingOptions
*/

/**
* Asynchronously reads the contents of a file.
*
* @async
* @param {string} filePath The path to the file.
* @returns {Promise<string>} The content of the file.
*/
export async function readFile(filePath) {
return fs.readFile(filePath, 'utf-8');
}

/**
* Asynchronously reads a Markdown file and returns either the content or data(front matter).
*
* @async
* @param {string} filePath The path to the Markdown file.
* @param {'content' | 'data' | 'all'} [option='all'] The type of data to return.
* @returns {Promise<string | {[key: string]: any} | {content: string, data: {[key: string]: any}}>} The content or data(front matter) of the file.
* @throws {TypeError} If the option is invalid.
*/
export async function readFileForMarkdown(filePath, option = 'all') {
const { content, data } = matter(await readFile(filePath));

switch (option) {
case 'content':
return content;
case 'data':
return data;
case 'all':
return {
content,
data,
};
default:
throw TypeError();
}
}

/**
* Asynchronously reads a directory and returns a list of file paths with the specified extension.
*
* @async
* @param {string} dirPath The path to the directory.
* @param {string} extension The file extension to filter by. `extension` cannot be a RegExp. It must be a string.
* @param {ObjectEncodingOptions & {withFileTypes?: false | undefined; recursive?: boolean | undefined;}} [options = { recursive: true }] Optional `readdir` options.
* @returns {Promise<string[]>} An array of file paths.
*/
export async function readDirByExtension(
dirPath,
extension,
options = { recursive: true },
) {
const filePaths = await fs.readdir(dirPath, options);

return filePaths.filter(filePath => filePath.endsWith(extension));
}
Loading

0 comments on commit 455c67b

Please sign in to comment.