refactor: extract find node

This commit is contained in:
EnixCoda 2019-02-21 18:13:43 +08:00
parent 589bc25939
commit 1043c0dfd4
No known key found for this signature in database
GPG key ID: 6825847C88AA329A
3 changed files with 26 additions and 20 deletions

View file

@ -3,7 +3,8 @@ import DOMHelper from 'utils/DOMHelper'
import treeParser from 'utils/treeParser'
import URLHelper from 'utils/URLHelper'
import VisibleNodesGenerator, { TreeNode, VisibleNodes } from 'utils/VisibleNodesGenerator'
import GitHubHelper, { BlobData, TreeData, MetaData } from 'utils/GitHubHelper'
import GitHubHelper, { BlobData, TreeData } from 'utils/GitHubHelper'
import { findNode } from 'utils/general'
import { MethodCreator } from 'driver/connect'
import { Props } from 'components/FileExplorer'
import Node from 'components/Node'
@ -56,8 +57,7 @@ function resolveGitModules(root: TreeNode, blobData: BlobData) {
const parsed = ini.parse(content)
Object.values(parsed).map((value: { url: string; path: string }) => {
const { url, path } = value
// for now, handle modules at root only
const node = Array.isArray(root.contents) && root.contents.find(node => node.path === path)
const node = findNode(root, path.split('/'))
if (node) {
node.url = url
}

View file

@ -1,3 +1,5 @@
import { TreeNode } from './VisibleNodesGenerator'
export function pick<T>(source: T, keys: string[]): Partial<T> {
if (keys && typeof keys === 'object') {
return (Array.isArray(keys) ? keys : Object.keys(keys)).reduce(
@ -44,3 +46,19 @@ export function friendlyFormatShortcut(shortcut?: string) {
return shortcut
}
}
export function findNode(
root: TreeNode,
path: string[],
callback?: (node: TreeNode) => void,
): TreeNode | undefined {
if (Array.isArray(root.contents)) {
for (const content of root.contents) {
if (content.name === path[0]) {
if (callback) callback(content)
if (path.length === 1) return content
return findNode(content, path.slice(1), callback)
}
}
}
}

View file

@ -1,3 +1,5 @@
import { findNode } from './general'
/**
* This is the stack for generating an array of nodes for rendering
*
@ -170,23 +172,9 @@ class L3 {
}
expandTo = (path: string) => {
let root = this.l2.getRoot()
const findNode: (root: TreeNode) => TreeNode | undefined = root => {
if (path.indexOf(root.path) === 0) {
if (root.path === path) return root
this.setExpand(root, true)
if (root.contents) {
for (const content of root.contents) {
const node = findNode(content)
if (node) return node
}
}
}
}
const node = findNode(root)
if (node) {
this.setExpand(node, true)
}
const root = this.l2.getRoot()
const node = findNode(root, path.split('/'), node => this.setExpand(node, true))
if (node) this.setExpand(node, true)
return node
}