forked from ipfs/js-ipfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
92 lines (71 loc) · 1.71 KB
/
utils.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
82
83
84
85
86
87
88
89
90
91
92
'use strict'
const createNode = (type, content, attrbutes) => {
attrbutes = attrbutes || {}
const node = document.createElement(type)
node.innerText = content
Object.keys(attrbutes).forEach(attrbute => {
if (attrbute === 'className') {
node.className = attrbutes[attrbute]
return
}
node.setAttribute(attrbute, attrbutes[attrbute])
})
return node
}
const log = (line) => {
const output = document.querySelector('#log')
let message
let className = ''
if (line instanceof Error) {
className = 'error'
message = `Error: ${line.message}`
} else if (typeof line === 'string') {
message = line
} else {
className = 'output'
message = JSON.stringify(line, null, 2)
}
if (!message) {
return
}
const node = createNode('p', message, {
className
})
output.appendChild(node)
output.scrollTop = output.offsetHeight
return node
}
const dragDrop = (onFiles) => {
const container = document.querySelector('#container')
container.ondragover = (event) => {
container.className = 'drag-over'
event.preventDefault()
}
container.ondragleave = () => {
container.className = ''
}
container.ondrop = (event) => {
container.className = ''
event.preventDefault()
const files = Array.from(event.dataTransfer.items)
.map(item => item.getAsFile())
.filter(item => Boolean(item))
if (files.length) {
onFiles(files)
}
}
}
const bufferToArrayBuffer = (buffer) => {
const ab = new ArrayBuffer(buffer.length)
const view = new Uint8Array(ab)
for (let i = 0; i < buffer.length; ++i) {
view[i] = buffer[i]
}
return ab
}
module.exports = {
log,
dragDrop,
createNode,
bufferToArrayBuffer
}