manage markdowns by path

This commit is contained in:
h z
2024-12-05 18:28:15 +00:00
parent 788fd2f37a
commit da1860a269
12 changed files with 441 additions and 198 deletions

View File

@@ -1,86 +1,46 @@
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { fetchWithCache } from "../../utils/fetchWithCache";
import PermissionGuard from "../PermissionGuard";
import PathNode from "./PathNode";
import config from "../../config";
import "./SideNavigation.css";
import {fetch_} from "../../utils/requestUtils";
const SideNavigation = () => {
const [markdowns, setMarkdowns] = useState([]);
const [tree, setTree] = useState(null);
const [paths, setPaths] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
fetchWithCache(`${config.BACKEND_HOST}/api/markdown/`)
setLoading(true);
fetch_(`${config.BACKEND_HOST}/api/path/`, {},{ use_cache: true, use_token:false })
.then((data) => {
setMarkdowns(data);
setTree(buildTree(data));
setPaths(data);
})
.catch((error) => console.log(error));
.catch((error) => console.log(error))
.finally(() => setLoading(false));
}, []);
function buildTree(markdowns) {
const root = {};
markdowns.forEach((markdown) => {
const segments = markdown.path.split("/").filter(Boolean);
let current = root;
segments.forEach((segment, index) => {
if (!current[segment]) {
current[segment] =
index === segments.length - 1 ? { markdown } : {};
}
current = current[segment];
});
});
return root;
}
function renderTree(node, basePath = "") {
return (
<ul>
<PermissionGuard rolesRequired={["admin", "creator"]}>
<li>
<Link
to="/markdown/create"
className="button is-primary is-small"
>
Create New Markdown
</Link>
</li>
</PermissionGuard>
{Object.entries(node).map(([key, value]) => {
if (value.markdown) {
return (
<li key={value.markdown.id} className="menu-list-item">
<Link
to={`${config.BACKEND_HOST}/markdown/${value.markdown.id}`}
className="is-link"
>
{value.markdown.title}
</Link>
</li>
);
}
return (
<li key={key}>
<span className="has-text-weight-bold">{key}</span>
{renderTree(value, `${basePath}/${key}`)}
</li>
);
})}
</ul>
);
}
return (
<aside className="menu">
<p className="menu-label">Markdown Directory</p>
<PermissionGuard rolesRequired={["admin", "creator"]}>
<a
href="/markdown/create"
className="button is-primary is-small"
>
Create New Markdown
</a>
</PermissionGuard>
<ul className="menu-list">
{tree ? renderTree(tree) : <p>Loading...</p>}
{loading && <p>Loading...</p>}
{paths.map((path) => (
<PathNode
key={path.id}
path={path}
isRoot={true}
/>
))}
</ul>
</aside>
);
};
export default SideNavigation;
export default SideNavigation;