@docuify/engine
Version:
A flexible, pluggable engine for building and transforming documentation content from source files.
87 lines (86 loc) • 2.34 kB
JavaScript
// lib/utils/build_tree.ts
var idCounter = 0;
function generateId() {
return `node-${idCounter++}`;
}
function createFolderNode(name, fullPath, parentId) {
return {
id: generateId(),
name,
fullPath,
type: "folder",
parentId,
children: []
};
}
function createFileNode(file, name, fullPath, parentId) {
const nodeId = generateId();
const transformQueue = [];
const getRawContent = file.loadContent;
async function transformContent(rawContent) {
let result = rawContent;
for (const transformFunction of transformQueue) {
result = await transformFunction(result);
}
return result;
}
async function loadContent() {
if (!getRawContent) {
throw new Error(`No content getter for ${file.path}`);
}
const raw = await getRawContent();
return transformContent(raw);
}
return {
id: nodeId,
name,
fullPath,
type: "file",
parentId,
extension: file.extension,
metadata: file.metadata ? { ...file.metadata } : void 0,
// For inspection or debugging purposes — it's like peeking under the hood.
_contentTransformQueue: transformQueue,
// All the file's special powers are grouped here. Transform, load, mutate!
actions: {
useTransform: (fn) => {
transformQueue.push(fn);
},
transformContent,
loadContent
}
};
}
function buildTree(sourceFiles) {
const root = {
id: generateId(),
name: "root",
// Root node — the top of the tree. No parents. Just responsibilities.
fullPath: ".",
type: "folder",
children: []
};
for (const file of sourceFiles) {
const parts = file.path.split("/");
let current = root;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const isLast = i === parts.length - 1;
if (!current.children) {
current.children = [];
}
let found = current.children.find((child) => child.name === part);
if (!found) {
const fullPath = parts.slice(0, i + 1).join("/");
const newNode = isLast && file.type === "file" ? createFileNode(file, part, fullPath, current.id) : createFolderNode(part, fullPath, current.id);
current.children.push(newNode);
found = newNode;
}
current = found;
}
}
return root;
}
export {
buildTree
};