-
Notifications
You must be signed in to change notification settings - Fork 0
/
kiwotigo.mjs
88 lines (78 loc) · 2.09 KB
/
kiwotigo.mjs
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
let worker
let lastBuild
let publishChannel
export const startBroadcasting = () => {
if (!publishChannel && typeof BroadcastChannel !== 'undefined') {
publishChannel = new BroadcastChannel('kiwotigo')
publishChannel.onmessage = ({ data }) => {
if (data) {
switch (data.type) {
case 'publishBuild':
if (lastBuild) {
publishChannel.postMessage(lastBuild)
}
break;
case 'ping':
publishChannel.postMessage({ type: 'pong' })
break;
}
}
}
if (lastBuild) {
publishChannel.postMessage(lastBuild)
}
}
}
const tmpResolvers = new Map() // temporary id -> resolve: Promise.resolve(), onProgressFn
const createMessageId = (() => {
let lastId = 0
return () => {
++lastId
return `kiwotigo-${lastId.toString(36)}`
}
})()
const initWorker = () => {
worker = new Worker('kiwotigo.worker.js')
worker.onmessage = ({data}) => {
const { id, type } = data
const resolve = tmpResolvers.get(id)
if (resolve) {
switch (type) {
case 'progress':
if (resolve.onProgressFn) {
resolve.onProgressFn(data.progress)
}
break
case 'result':
tmpResolvers.delete(id)
delete data.type
if (data.originData) {
localStorage.setItem('kiwotigoOriginData',
typeof data.originData === 'string'
? data.originData
: JSON.stringify(data.originData)
)
}
resolve.resolve(data)
if (publishChannel) {
lastBuild = { type: 'build', data }
publishChannel.postMessage(lastBuild)
}
break
default:
console.warn('unknown message type:', type, data)
}
}
}
}
const getWorker = () => {
if (!worker) {
initWorker()
}
return worker
}
export const build = (config, onProgressFn) => new Promise(resolve => {
const id = createMessageId()
tmpResolvers.set(id, { resolve, onProgressFn })
getWorker().postMessage({ ...config, id })
})