forked from ipfs/js-ipfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiletree.js
81 lines (62 loc) · 1.68 KB
/
filetree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'use strict'
const {
log,
createNode
} = require('./utils')
const FILE_TYPES = {
FILE: 0,
DIRECTORY: 1
}
let selected = {}
const getSelected = () => {
return Object.values(selected)
}
const loadFiles = async (ipfs, path) => {
const output = {}
path = path.replace(/\/\/+/g, '/')
const contents = await ipfs.files.ls(path, {
long: true
})
.catch(error => log(error))
for (let i = 0; i < contents.length; i++) {
let entry = contents[i]
output[entry.name] = entry
if (entry.type === FILE_TYPES.DIRECTORY) {
entry.contents = await loadFiles(ipfs, `${path}/${entry.name}`)
}
}
return output
}
const listFiles = (parent, files, prefix) => {
const fileNames = Object.keys(files)
fileNames.forEach((name, index) => {
const file = files[name]
const lastFile = index === fileNames.length - 1
const listIcon = lastFile ? '└── ' : '├── '
const listing = `${prefix}${listIcon}${name}`
if (file.type === FILE_TYPES.DIRECTORY) {
parent.appendChild(createNode('pre', `${listing}/`))
let descender = '|'
let directoryPrefix = `${prefix}${descender} `
if (lastFile) {
directoryPrefix = `${prefix} `
}
listFiles(parent, file.contents, directoryPrefix)
} else {
parent.appendChild(createNode('pre', listing))
}
})
}
const updateTree = async (ipfs) => {
const files = await loadFiles(ipfs, '/')
const container = document.querySelector('#files')
while (container.firstChild) {
container.removeChild(container.firstChild)
}
container.appendChild(createNode('pre', '/'))
listFiles(container, files, '')
}
module.exports = {
getSelected,
updateTree
}