-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhot-reload.js
64 lines (50 loc) · 1.21 KB
/
hot-reload.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
// SETTINGS
const CHECK_INTERVAL = 500
const RELOAD_ACTIVE_TABS = true
function filesInDirectory(dir) {
return new Promise((resolve) =>
dir.createReader().readEntries((entries) =>
Promise.all(entries.filter(e => e.name[0] !== '.').map(e =>
e.isDirectory
? filesInDirectory(e)
: new Promise(resolve => e.file(resolve))
))
.then(files => [].concat(...files))
.then(resolve)
)
)
}
function timestampForFilesInDirectory(dir) {
return filesInDirectory(dir).then((files) => {
return files.map(f => f.name + f.lastModifiedDate).join()
})
}
function reload() {
if (!RELOAD_ACTIVE_TABS) {
chrome.runtime.reload()
return
}
chrome.tabs.query({active: true}, (tabs) => {
tabs.forEach((tab) => {
chrome.tabs.reload(tab.id)
})
chrome.runtime.reload()
})
}
function watchChanges(dir, lastTimestamp) {
timestampForFilesInDirectory(dir).then((timestamp) => {
if (!lastTimestamp || (lastTimestamp === timestamp)) {
setTimeout(() => {
watchChanges(dir, timestamp)
}, CHECK_INTERVAL)
} else {
reload()
}
})
}
// start
chrome.management.getSelf((self) => {
if (self.installType === 'development') {
chrome.runtime.getPackageDirectoryEntry(dir => watchChanges(dir))
}
})