This repository has been archived by the owner on Jun 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
index.js
128 lines (105 loc) · 2.14 KB
/
index.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/* global node */
'use strict';
const drop = require('component/drop-anywhere');
const each = node('each-async');
const fs = node('fs');
const imagemin = node('imagemin');
const path = node('path');
const Spinner = require('component/spinner');
const imageminGifsicle = node('imagemin-gifsicle');
const imageminJpegtran = node('imagemin-jpegtran');
const imageminOptipng = node('imagemin-optipng');
const imageminPngquant = node('imagemin-pngquant');
const imageminSvgo = node('imagemin-svgo');
/**
* Minify images
*
* @param {Object} file
* @param {Function} cb
* @api private
*/
function minify(file, cb) {
fs.readFile(file.path, (err, buf) => {
if (err) {
cb(err);
return;
}
imagemin([file.path], path.join(path.dirname(file.path), 'build'), {
plugins: [
imageminGifsicle(),
imageminJpegtran(),
imageminOptipng(),
imageminPngquant(),
imageminSvgo()
]
}).then(file => {
cb(null, Object.assign(file, {original: buf}));
}).catch(error => {
cb(error);
});
});
}
/**
* Create spinner
*
* @api private
*/
function spin() {
let w = document.body.offsetWidth;
let h = document.body.offsetHeight;
const s = new Spinner()
.size(w / 4)
.light();
s.el.style.position = 'absolute';
s.el.style.top = `${(h / 2) - ((w / 4) / 2)}px`;
s.el.style.left = `${(w / 2) - ((w / 4) / 2)}px`;
spin.remove = () => {
document.body.removeChild(s.el);
};
window.addEventListener('resize', () => {
w = document.body.offsetWidth;
h = document.body.offsetHeight;
});
document.body.appendChild(s.el);
return s;
}
/**
* Toggle display
*
* @param {Element} el
* @api private
*/
function toggle(el) {
el = document.querySelector(el);
if (el.style.display === 'none') {
el.style.display = 'block';
return;
}
el.style.display = 'none';
}
/**
* Run
*/
drop(e => {
let files = [];
toggle('#drop-anywhere');
spin();
each(e.items, (item, i, done) => {
minify(item, (err, file) => {
if (err) {
done(err);
return;
}
files.push(file);
done();
});
}, err => {
if (err) {
console.error(err);
return;
}
toggle('#drop-anywhere');
spin.remove();
files = [];
});
});