]> 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 function copyToClipboard (text: string) {
13 const el = document.createElement('textarea')
14 el.value = text
15 el.setAttribute('readonly', '')
16 el.style.position = 'absolute'
17 el.style.left = '-9999px'
18 document.body.appendChild(el)
19 el.select()
20 document.execCommand('copy')
21 document.body.removeChild(el)
22 }
23
24 // Thanks: https://github.com/uupaa/dynamic-import-polyfill
25 function importModule (path: string) {
26 return new Promise((resolve, reject) => {
27 const vector = '$importModule$' + Math.random().toString(32).slice(2)
28 const script = document.createElement('script')
29
30 const destructor = () => {
31 delete window[ vector ]
32 script.onerror = null
33 script.onload = null
34 script.remove()
35 URL.revokeObjectURL(script.src)
36 script.src = ''
37 }
38
39 script.defer = true
40 script.type = 'module'
41
42 script.onerror = () => {
43 reject(new Error(`Failed to import: ${path}`))
44 destructor()
45 }
46 script.onload = () => {
47 resolve(window[ vector ])
48 destructor()
49 }
50 const absURL = (environment.apiUrl || window.location.origin) + path
51 const loader = `import * as m from "${absURL}"; window.${vector} = m;` // export Module
52 const blob = new Blob([ loader ], { type: 'text/javascript' })
53 script.src = URL.createObjectURL(blob)
54
55 document.head.appendChild(script)
56 })
57 }
58
59 function wait (ms: number) {
60 return new Promise<void>(res => {
61 setTimeout(() => res(), ms)
62 })
63 }
64
65 export {
66 copyToClipboard,
67 importModule,
68 objectToUrlEncoded,
69 wait
70 }