Enable loading stork script from StorkClient

This commit is contained in:
Sam Carlton 2022-05-10 16:20:22 -05:00
parent 83f0f6abf4
commit 2966b9bf2d

View file

@ -1,16 +1,20 @@
import {
storkIndexRelativeURL,
storkScriptURL
} from '~/helpers/stork/config.js'
export class StorkClient {
constructor ( options = {} ) {
this.name = options.name
this.url = options.url
this.name = options.name || 'index'
this.url = options.url || storkIndexRelativeURL
// Configuration - https://github.com/jameslittle230/stork/blob/ff49f163db06734e18ab690c188b45a3c68442ae/js/config.ts#L4
this.config = options.config || {}
// Stork instance
this.stork = options.stork
this.stork = options.stork || null
}
setupState = 'not-setup'
@ -48,6 +52,42 @@ export class StorkClient {
})
}
loadStorkScript () {
return new Promise((resolve, reject) => {
if ( !!this.stork ) resolve()
if ( !!window.stork ) {
this.stork = window.stork
resolve()
}
const s = document.createElement('script')
let r = false
s.type = 'text/javascript'
s.src = storkScriptURL
s.async = true
s.onerror = function(err) {
reject(err, s)
}
s.onload = s.onreadystatechange = () => {
// console.log(this.readyState); // uncomment this line to see which ready states are called.
if (!r && (!this.readyState || this.readyState == 'complete')) {
r = true
this.stork = window.stork
// console.log('window.stork', typeof window.stork)
resolve()
}
}
const t = document.getElementsByTagName('script')[0]
t.parentElement.insertBefore(s, t)
})
}
// https://github.com/jameslittle230/stork/blob/ff49f163db06734e18ab690c188b45a3c68442ae/js/main.ts#L40
async setup () {
// Prevent multiple setups
@ -56,6 +96,16 @@ export class StorkClient {
return
}
// We're the first to setup
// so let's set the state to prevent duplicates
this.setupState = 'pending'
// Load Stork Script
if ( !this.stork ) {
// console.log('Loading stork script...')
await this.loadStorkScript()
}
const {
initialize,
downloadIndex,
@ -70,7 +120,7 @@ export class StorkClient {
// This silly `then` call turns a [(void), (void)] into a (void), which is
// only necessary to make Typescript happy.
// You begin to wonder if you write Typescript code, or if Typescript code writes you.
await Promise.all([initPromise, downloadPromise])
await Promise.all([ initPromise, downloadPromise ])
// Mark setup as complete
this.setupState = 'complete'