-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
re.places.js
64 lines (54 loc) · 1.48 KB
/
re.places.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
// #TODO
// - implement non-CDN option, e.g. by specifying a local path
const fileURL = () => {
const [href] = new Error().stack.match(/http.*?\.js(?:\?.*?)?(?=(?::\d+){1,})/) || '';
const url = new URL(href || self.location.href);
return url;
};
const workerUrl = 'https://cdn.jsdelivr.net/npm/[email protected]/src/re.places.dw.js';
let placesWorker;
let activePost;
const initPlacesWorker = () => {
return fetch(workerUrl)
.then(e => e.text())
.then((txt) => {
const workerBlob = new Blob([txt], {type: 'application/javascript'})
placesWorker = new Worker(URL.createObjectURL(workerBlob));
placesWorker.onmessage = ({ data }) => {
if (data.id === activePost.data.id) {
activePost.resolve(data.search || null);
}
}
});
}
const postMessage = async (msg={}) => {
activePost = {
data: {
...msg,
id: performance.now(),
},
};
if (!placesWorker) {
await initPlacesWorker();
}
placesWorker.postMessage(activePost.data);
}
export const init = (params) => {
postMessage({ init: params, baseUrl });
}
export const search = async (params) => {
if (activePost) {
activePost.resolve();
}
return new Promise((resolve) => {
postMessage({ search: params });
activePost.resolve = resolve;
});
}
try {
if (fileURL().searchParams.has('global')) {
const globalKey = fileURL().searchParams.get('global') || 'replaces';
self[globalKey] = { init, search }
}
} catch (e) {/**/}
export default { init, search };