Skip to content

Commit

Permalink
refactor: detach Categories component from Aside component
Browse files Browse the repository at this point in the history
  • Loading branch information
lumirlumir committed Sep 16, 2024
1 parent 2b9f5a3 commit 7def555
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 54 deletions.
37 changes: 37 additions & 0 deletions src/components/aside/Categories/Categories.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { join } from 'path';

import Link from 'next/link';

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

export default async function Categories() {
const dirTree = await getDirTree(DOCS);

return <>{renderDirTree(dirTree)}</>;
}

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>
);
})}
</ul>
);
}
3 changes: 3 additions & 0 deletions src/components/aside/Categories/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import Categories from './Categories';

export default Categories;
56 changes: 2 additions & 54 deletions src/layouts/Aside/Aside.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { promises as fs } from 'fs';
import Link from 'next/link';

import { DOCS } from '@/constants/path';
import Categories from '@/components/aside/Categories';

import styles from './Aside.module.scss';

Expand All @@ -13,58 +12,7 @@ export default async function Aside() {
<Link href="/">Home</Link>
</li>
</ul>
{renderDirTree(buildDirTree(dirs))}
<Categories />
</aside>
);
}

const dirs = await fs.readdir(DOCS, {
encoding: 'utf-8',
recursive: true,
});

function buildDirTree(dirs) {
const tree = {};

dirs.forEach(dir => {
const parts = dir.split(/[/\\]/); // Use `/` or `\\` as a path seperator.

let current = tree;

parts.forEach((part, index) => {
if (!current[part]) {
current[part] = index === parts.length - 1 ? null : {};
}
current = current[part];
});
});

return tree;
}

function renderDirTree(tree, basePath = '') {
return (
<ul>
{Object.keys(tree).map(key => {
const path = `${basePath}/${key}`;

if (tree[key] === null) {
return (
<li key={path}>
<Link href={`/docs${path.replace('.md', '')}`}>
{key.replace('.md', '')}
</Link>
</li>
);
} else {
return (
<li key={path}>
<span>{key}</span>
{renderDirTree(tree[key], path)}
</li>
);
}
})}
</ul>
);
}

0 comments on commit 7def555

Please sign in to comment.