From cfb23347f804131cb12fb6f8649fec0d9f730a8a Mon Sep 17 00:00:00 2001 From: wancat Date: Tue, 29 Aug 2023 13:26:14 +0800 Subject: [PATCH] feat: add load nested fileNode --- packages/file-graph/fileNode.js | 16 +++++++++---- packages/file-graph/fileNode.test.js | 36 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/packages/file-graph/fileNode.js b/packages/file-graph/fileNode.js index 96fc60c..d7d4e01 100644 --- a/packages/file-graph/fileNode.js +++ b/packages/file-graph/fileNode.js @@ -9,7 +9,8 @@ import { basename, dirname } from './utils.js' export default class FileNode extends File { constructor(file) { super(file) - this.children = file.children || [] + this.children = [] + if (file.children) this.children = file.children.map((f) => new FileNode(f)) } addChild(fileInput, { makeParents } = {}) { @@ -76,6 +77,8 @@ export default class FileNode extends File { // Merge the children of the provided file node into this node // If a child already exists, merge the children of that child // If a child does not exist, add it to this node + + // If this is the same node, merge the children if (fileNode.path === this.path) { fileNode.children.forEach((child) => { const existingChild = this.children.find((c) => c.path === child.path) @@ -92,12 +95,17 @@ export default class FileNode extends File { fileNode.children.some((c) => c.path === child.path) ) } - } else if (this.contains(fileNode)) { + } + // If this contains the parent node + else if (this.contains(fileNode)) { const childNode = this.children.find((child) => child.contains(fileNode)) + // If a child node exists, merge the provided node into the child node if (childNode) { childNode.merge(fileNode) - } else { - this.addChild(fileNode) + } + // If a child node does not exist, add the provided node as a child + else { + this.addChild(fileNode, { makeParents: true }) } } else { throw new Error( diff --git a/packages/file-graph/fileNode.test.js b/packages/file-graph/fileNode.test.js index b58e38f..4621baf 100644 --- a/packages/file-graph/fileNode.test.js +++ b/packages/file-graph/fileNode.test.js @@ -219,3 +219,39 @@ describe('FileNode', () => { removeChildTest(files, fileToRemove, expected) }) }) + +test('load nested fileNode', () => { + const data = { + path: '/', + type: 'folder', + children: [ + { + path: '/a', + type: 'file', + }, + { + path: '/b', + type: 'folder', + children: [ + { + path: '/b/c', + type: 'folder', + children: [ + { + path: '/b/c/d', + type: 'file', + }, + ], + }, + ], + }, + ], + } + + const node = new FileNode(data) + + console.log(node.toString()) + expect(node.children.length).toBe(2) + expect(node.children[1].children.length).toBe(1) + expect(node.children[1].children[0].children.length).toBe(1) +})