]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/root-helpers/utils.ts
Merge remote-tracking branch 'weblate/develop' into develop
[github/Chocobozzz/PeerTube.git] / client / src / root-helpers / utils.ts
1 import { environment } from '../environments/environment'
2
3 function objectToUrlEncoded (obj: any) {
4 const str: string[] = []
5 for (const key of Object.keys(obj)) {
6 str.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
7 }
8
9 return str.join('&')
10 }
11
12 // Thanks: https://github.com/uupaa/dynamic-import-polyfill
13 function importModule (path: string) {
14 return new Promise((resolve, reject) => {
15 const vector = '$importModule$' + Math.random().toString(32).slice(2)
16 const script = document.createElement('script')
17
18 const destructor = () => {
19 delete window[ vector ]
20 script.onerror = null
21 script.onload = null
22 script.remove()
23 URL.revokeObjectURL(script.src)
24 script.src = ''
25 }
26
27 script.defer = true
28 script.type = 'module'
29
30 script.onerror = () => {
31 reject(new Error(`Failed to import: ${path}`))
32 destructor()
33 }
34 script.onload = () => {
35 resolve(window[ vector ])
36 destructor()
37 }
38 const absURL = (environment.apiUrl || window.location.origin) + path
39 const loader = `import * as m from "${absURL}"; window.${vector} = m;` // export Module
40 const blob = new Blob([ loader ], { type: 'text/javascript' })
41 script.src = URL.createObjectURL(blob)
42
43 document.head.appendChild(script)
44 })
45 }
46
47 export {
48 importModule,
49 objectToUrlEncoded
50 }