1 import { DatePipe } from '@angular/common'
2 import { environment } from '../../environments/environment'
3 import { AuthService } from '../core/auth'
5 // Thanks: https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
6 function getParameterByName (name: string, url: string) {
7 if (!url) url = window.location.href
8 name = name.replace(/[\[\]]/g, '\\$&')
10 const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
11 const results = regex.exec(url)
13 if (!results) return null
14 if (!results[2]) return ''
16 return decodeURIComponent(results[2].replace(/\+/g, ' '))
19 function populateAsyncUserVideoChannels (authService: AuthService, channel: { id: number, label: string, support?: string }[]) {
20 return new Promise(res => {
21 authService.userInformationLoaded
24 const user = authService.getUser()
27 const videoChannels = user.videoChannels
28 if (Array.isArray(videoChannels) === false) return
30 videoChannels.forEach(c => channel.push({ id: c.id, label: c.displayName, support: c.support }))
38 function getAbsoluteAPIUrl () {
39 let absoluteAPIUrl = environment.hmr === true
40 ? 'http://localhost:9000'
43 if (!absoluteAPIUrl) {
44 // The API is on the same domain
45 absoluteAPIUrl = window.location.origin
51 function getAbsoluteEmbedUrl () {
52 let absoluteEmbedUrl = environment.embedUrl
53 if (!absoluteEmbedUrl) {
54 // The Embed is on the same domain
55 absoluteEmbedUrl = window.location.origin
58 return absoluteEmbedUrl
61 const datePipe = new DatePipe('en')
62 function dateToHuman (date: string) {
63 return datePipe.transform(date, 'medium')
66 function durationToString (duration: number) {
67 const hours = Math.floor(duration / 3600)
68 const minutes = Math.floor((duration % 3600) / 60)
69 const seconds = duration % 60
71 const minutesPadding = minutes >= 10 ? '' : '0'
72 const secondsPadding = seconds >= 10 ? '' : '0'
73 const displayedHours = hours > 0 ? hours.toString() + ':' : ''
76 displayedHours + minutesPadding + minutes.toString() + ':' + secondsPadding + seconds.toString()
80 function immutableAssign <A, B> (target: A, source: B) {
81 return Object.assign({}, target, source)
84 function objectToUrlEncoded (obj: any) {
85 const str: string[] = []
86 for (const key of Object.keys(obj)) {
87 str.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
93 // Thanks: https://gist.github.com/ghinda/8442a57f22099bdb2e34
94 function objectToFormData (obj: any, form?: FormData, namespace?: string) {
95 const fd = form || new FormData()
98 for (const key of Object.keys(obj)) {
99 if (namespace) formKey = `${namespace}[${key}]`
102 if (obj[key] === undefined) continue
104 if (Array.isArray(obj[key]) && obj[key].length === 0) {
109 if (obj[key] !== null && typeof obj[ key ] === 'object' && !(obj[ key ] instanceof File)) {
110 objectToFormData(obj[ key ], fd, formKey)
112 fd.append(formKey, obj[ key ])
119 function objectLineFeedToHtml (obj: any, keyToNormalize: string) {
120 return immutableAssign(obj, {
121 [keyToNormalize]: lineFeedToHtml(obj[keyToNormalize])
125 function lineFeedToHtml (text: string) {
126 if (!text) return text
128 return text.replace(/\r?\n|\r/g, '<br />')
131 function removeElementFromArray <T> (arr: T[], elem: T) {
132 const index = arr.indexOf(elem)
133 if (index !== -1) arr.splice(index, 1)
136 function sortBy (obj: any[], key1: string, key2?: string) {
137 return obj.sort((a, b) => {
138 const elem1 = key2 ? a[key1][key2] : a[key1]
139 const elem2 = key2 ? b[key1][key2] : b[key1]
141 if (elem1 < elem2) return -1
142 if (elem1 === elem2) return 0
147 function scrollToTop () {
151 // Thanks: https://github.com/uupaa/dynamic-import-polyfill
152 function importModule (path: string) {
153 return new Promise((resolve, reject) => {
154 const vector = '$importModule$' + Math.random().toString(32).slice(2)
155 const script = document.createElement('script')
157 const destructor = () => {
158 delete window[ vector ]
159 script.onerror = null
162 URL.revokeObjectURL(script.src)
167 script.type = 'module'
169 script.onerror = () => {
170 reject(new Error(`Failed to import: ${path}`))
173 script.onload = () => {
174 resolve(window[ vector ])
177 const absURL = (environment.apiUrl || window.location.origin) + path
178 const loader = `import * as m from "${absURL}"; window.${vector} = m;` // export Module
179 const blob = new Blob([ loader ], { type: 'text/javascript' })
180 script.src = URL.createObjectURL(blob)
182 document.head.appendChild(script)
186 function isInViewport (el: HTMLElement) {
187 const bounding = el.getBoundingClientRect()
190 bounding.left >= 0 &&
191 bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
192 bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
196 function isXPercentInViewport (el: HTMLElement, percentVisible: number) {
197 const rect = el.getBoundingClientRect()
198 const windowHeight = (window.innerHeight || document.documentElement.clientHeight)
201 Math.floor(100 - (((rect.top >= 0 ? 0 : rect.top) / +-(rect.height / 1)) * 100)) < percentVisible ||
202 Math.floor(100 - ((rect.bottom - windowHeight) / rect.height) * 100) < percentVisible
212 populateAsyncUserVideoChannels,
218 objectLineFeedToHtml,
219 removeElementFromArray,