-
Notifications
You must be signed in to change notification settings - Fork 0
/
a-load-screen.js
1414 lines (1315 loc) · 107 KB
/
a-load-screen.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global AFRAME, THREE, ldBar */
/*
todo:
// make text easier to read:
> It may increase readibility with the right colors and contrast, but here it doesn't work for me. Here are some really bad example for me https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow also some answers here https://ux.stackexchange.com/questions/72629/can-text-shadow-enhance-readability
// add scripts in dynamically
// estimated time to completion as optional stats we can render
// implement loading min time before showing load screen and min display time
// implement file retries
// debug('error',"non-fill-effect not yet implemented")
// add optional direct to VR/AR button, no 2d display
// this could of course be done manually with existing hooks
// what to do about timeout, if anything...?
// gradient background? animated background? how about for logo loader background?
// full screen logo background with glitch effect option
// hide logo until loaded?
// global stats: total loaded loading bar
// custom event hook that simplifies all data for them
to fix:
// placeholder for unloaded logo could be improved, though it's pretty good
// in some cases logo isn't horizontally centered, pretty sure just when image is smaller than stats below
// a-frame logo with glitch effect shows a weird doubling behind it that I don't like for some logos... haven't been able to fix
// how should we handle when all the data desired doesn't fit?
// should I also use findMaxFontSize function for file stat rows?
// for now, we fade the right side out
// a kind of overhaul on the filestats grid, so that it just always looks good
// https://stackoverflow.com/questions/45536537/centering-in-css-grid
// maybe arrays that specify what you want for each row, in what order?
// and their container will always just be centered or left justified?
// https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout
// statsRow1: ['DownloadSpeedVisual']
// statsRow2: [] // statsRow2: ['totals'] // statsRow2: ['downloadTotalsText','downloadSpeedText','timeElapsed']
*/
(function() {
// schema
let
anchor,
contrainedImageDimensions,
start = Date.now(),
assets,
maxWidth,
logo,
opts, // copy of options specified at init after combined with defaults
barCounter = 0,
firstByteTime,
globalLoadRegister = {
bytes: {
// dynamic
},
images: {
// dynamic, in theory; todo
}
}
;
function cssOverrides(styleString) {
// document.head.insertAdjacentHTML(`
// <style>
// /* custom CSS here */
// .ldBar.label-center > .ldBar-label {
// display: none;
// }
// </style>
// `)
const style = document.createElement('style');
style.innerHTML = styleString;
document.head.appendChild(style);
}
async function init(
options={}
) {
// defaults overridden on declaration
// when selecting the 'filenames' option, you can customize the SVG spcecs by modifying this object
// file name will be auto-injected during execution
options.filenamesPresetOptions = Object.assign({
"xmlns":"http://www.w3.org/2000/svg", "width":"350", "height":"20", "viewBox":"0 0 350 20", "x":"175", "y":"10", "text-anchor":"middle", "dominant-baseline":"central", "font-family":"arial"
}, options?.filenamesPresetOptions || {});
options.debug = options.debug === true ? ['log','warn','error'] : options.debug || ['error']; // can include 'log','warn','error', etc. | can also be "true" to just catch all
opts = Object.assign({
debug: ['error'],
delayStart: 300, // ms | not hooked up to anything yet | to prevent loading flash on page reloads, skips the load screen entirely if it can render before this time
delayEnd: 0, // ms | not hooked up to anything yet | if you never want the load screen to be skipped, set a minimum display time here
showLogo: true, // not hooked up to anything yet
useLogoFillEffect: true,
useLogoGlitchEffect: true,
logoURL: aframeLogoDataIMG, // "https://aframe.io/aframe-school/media/img/aframe-logo.png",
logoSize: [300,300],// width, height | always
font: "400 1.1rem/.1 Fira Sans,Helvetica,Arial,sans-serif",
showBarLoaders: true,
showTitle: true,
titleText: document.title || "",
showSubtitle: true,
subtitleOverride: "",
titleFontStyle: `text-align:center;font-weight:900;`, // don't specify font-size here, do that separate so that you can take advantage of max client-sizing
showTextSpeedometer: true,
useFilename: false, // by default we will use the ID, but you can also choose to use the filename
fadeLoaderRows: true,
autoReloadToHTTPS: true,
horizontalRulePercent: 60,
showGlobalStats: true, // not implemented
showFileStats: true, // not implemented
centeredLoadingBars: true,
titleFontSizeMax: 100, // titleFontSizeMax: see init for dynamic value setting;
showVisualSpeedometer: true,
showTimeElapsed:true,
smoothLogoLoadFactor: 10, // megabyte; make value as big or small as you like, bigger is less jitter, low is more responsive load values; only matters for first file load, real value is cached in localstorage on first load
// number exists as placeholder assumed size for files before we have received that info from server if it isn't supplied in html; higher the value, lower the chance and intensity of jitter--higher the value, the more artificially held back your image load is; used to prevent flickering of load logo in beginning as new objects start loading on first load when sice not manually specified in html directly
showFilenames: true,
showFileSizes: true,
showDownloadTotals: true,
barLoaderPreset: "rainbow", /// one of: "", null, line, rainbow, energy, stripe, text, filenames, | would require customization to work: fan, circle, bubble, | see https://loading.io/progress/ | also: https://github.com/loadingio/loading-bar/blob/af5271ef7c675783fe870b5a60d6057f32f73e47/src/presets.ls
customLogoLoaderAttributes: null, // see usage of this object in this script to get a clearer idea, along with docs @ https://loading.io/progress
customBarLoaderAttributes: null, // see usage of this object in this script to get a clearer idea, along with docs @ https://loading.io/progress
backgroundColor: "black",
backgroundImage: "",
containerCSS: "", // specify e.g. background image props
logoFillColor: "black",
backgroundOpacity: .9,
styleOverrides: `
/* this removes e.g. "100%" labels that by default get overlaid on top of loading elements by library */
.ldBar.label-center > .ldBar-label {
display: none;
}
.hide-loader {
opacity: 0 !important;
z-index: 0;
transition: all 1.5s;
}
.a-load-screen-content-container::-webkit-scrollbar {
display: none;
}
`,
onAframeRenderStart: function(evt) {
// https://aframe.io/docs/1.3.0/core/scene.html
// this fires last last
this.updateSubtitle("ready");
document.querySelector('.a-load-screen-main-container').classList.add('hide-loader'); // note: this is a 1.5s animation in CSS
setTimeout(() => this.hideLoader(),1500);
},
onAframeLoaded: function(evt) {
// oh, this will run also on every file load too
// this fires before renderstart
// need to see if this is tied to file loaded or to meshes loaded, but I think it's meshes
// document.querySelector('#a-loader-title').innerHTML = "rendering...";
// alert("loaded?")
this.updateSubtitle("rendering...");
},
onFilesLoaded: function(evt) {
// note: this isn't currently guaranteed to run, seems it's possible for a loading event
// to not fire because it has disk cached or downloaded too quickly?
// this usually fires before aframeloaded
// alert("file load complete")
// can have this here, but I want to change this to update the title to "rendering..."
// document.querySelector('.a-load-screen-main-container').classList.add('hide-loader');
// setTimeout(() => this.hideLoader(),1500);
// alt option to flash away:
// this.hideLoader()
this.updateSubtitle("file load complete");
},
skipLoadErrors: true, // if you have some error with some file, at least the show will _try_ to go on so you don't make users stuck at loading screen.
fileRetryOnError: 0, // this is not working yet, should leave on 0 until implemented. In the meantime, you can implement yourself with custom onFileLoadError
onFileLoadError: function(filename, url, evt) {
// you could:
// - warn users there was a problem and it will try to run without the file
// - implement manual reloading
// - track page reload attempts in local storage; e.g. if you tried twice and file still won't load, then let them just try anyways
// - could have different behavior based on how important the files are
// - force a page reload with location.reload()
// - silently report to server for stats collectiong
debug("error","error loading file:",filename,url,evt);
},
}, options || {});
const scene = document.querySelector('a-scene');
debug('log',scene, scene.renderStarted)
if (scene.renderStarted) {
debug('error','scene is already rendering, skipping load screen altogether');
debug('warn','will run all hooks sequentially right away!');
await opts.onFilesLoaded();
await opts.onAframeLoaded();
await opts.onAframeRenderStart();
debug('warn','completed loading hooks')
// note: they may be depending on the hooks running, we should probably default to executing those
return;
}
if (opts.onAframeLoaded) {
scene.addEventListener('loaded', evt => {
if (evt.target !== document.querySelector('a-scene')) return;
opts.onAframeLoaded(evt);
});
}
if (opts.onAframeRenderStart) {
scene.addEventListener('renderstart', (function onAframeRenderStart() {
let haveRun = false;
return () => {
if (haveRun) return;
haveRun = true;
opts.onAframeRenderStart.bind(opts)();
}
})());
}
if (!location.protocol.includes("https") && opts.autoReloadToHTTPS) location = location.href.replace('http','https');
if (opts.barLoaderPreset === "filenames") opts.showFilenames = false; // avoid likely accidental conflict to prevent duplicate filename display when using names as bars themselves
opts.smoothLogoLoadFactor *= (10**6); // cnovert mb input to the bytes form we use here;
// subtract 9 to leave space for image loader lib to add 9
contrainedImageDimensions = [
Math.min(window.screen.width - 9, opts.logoSize[0]),
Math.min(window.screen.width - 9, opts.logoSize[1]),
]; //opts.logoSize.split(",")[0] < window.screen.width ? opts.logoSize : `${window.screen.width-9},${window.screen.width-9}`;
maxWidth = contrainedImageDimensions[0] + 9; //Number(contrainedImageDimensions.split(',')[0]) - 9; // 9 is added for the fill outline of the logo
// todo:: need to handle when we don't use the logo
opts.hideLoader = hideLoader; // make function accessible to onFilesLoaded; todo: add fade default
opts.updateSubtitle = updateSubtitle;
// has to be included in scene html itself, won't be used in time
// setAttribute('a-scene','loading-screen',{enabled:false})
setupHTML();
cssOverrides(glitchEffectCSS(opts.titleText, opts.logoURL, contrainedImageDimensions[0], contrainedImageDimensions[1]));
cssOverrides(opts.styleOverrides);
anchor = document.querySelector('.a-load-screen-content-container');
debug('log',"anchor:",anchor)
if (opts.titleText) {
opts.titleFontSizeMax = Math.min(opts.titleFontSizeMax, findMaxFontSize(opts.titleText,anchor,anchor.offsetWidth,{style:opts.titleFontStyle})); // Math.floor(maxWidth/opts.titleText.length)
const margin = opts.titleFontSizeMax / 2;
opts.titleFontStyle = `margin-top:${margin}px;margin-bottom:${margin}px;font-size:${opts.titleFontSizeMax}px;` + opts.titleFontStyle;
}
addLogo();
assets = document.body.querySelector('a-assets').children;
debug('log',"assets found",assets);
addStats();
debug('log','opts',opts)
for (const child of assets) {
// debug('log',"asset",child);
addBar(child, opts.showBarLoaders);
// debug('log','loader?',child.fileLoader); // THREE fileLoader instance under the hood, though it isn't added at this point
}
// also see: THREE.cache
// Docs:
// https://aframe.io/docs/1.3.0/core/asset-management-system.html
// https://threejs.org/docs/#api/en/loaders/FileLoader
};
// currently unused; can try these later if desired to remove need to add dependencies manually?
function fetchStyle(url) {
// https://stackoverflow.com/a/40933978/4526479
return new Promise((resolve, reject) => {
let link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.onload = function() { resolve(); debug('log','style has loaded'); };
link.href = url;
let headScript = document.querySelector('script');
headScript.parentNode.insertBefore(link, headScript);
});
};
const loadScript = src =>
// https://stackoverflow.com/a/59612206/4526479
new Promise((resolve, reject) => {
if (document.querySelector(`head > script[src="${src}"]`) !== null) return resolve()
const script = document.createElement("script")
script.src = src
script.async = true
document.head.appendChild(script)
script.onload = resolve
script.onerror = reject
});
// end loadScript
function findMaxFontSize(string="a string", parent=document.body, maxWidth=parent.width, attributes = {id:'font-size-finder',class:'some-class-with-font'}) {
// by using parent, we can infer the same font inheritance;
// you can also manually specify fonts or relevant classes/id with attributes if preferred/needed
attributes.style = 'position:absolute; left:-10000; font-size:1px;' + (attributes.style || "");
let testFontEl = createEl('p', attributes, string);
parent.appendChild(testFontEl);
let currentWidth = testFontEl.offsetWidth;
let workingFontSize = 1;
let i = 0;
while (currentWidth < maxWidth && i < 1000) {
testFontEl.style.fontSize = Number(testFontEl.style.fontSize.split("px")[0]) + 1 + "px";
currentWidth = testFontEl.offsetWidth;
if (currentWidth < maxWidth) {
workingFontSize = testFontEl.style.fontSize;
}
i++; // safety to prevent infinite loops
}
debug('log',"determined maximum font size:",workingFontSize,'one larger would produce',currentWidth,'max width allowed is',maxWidth,'parent is',parent);
parent.removeChild(testFontEl);
return workingFontSize.split("px")[0];
}
function createEl(tag, attrs, children) {
let el = document.createElement(tag);
if (attrs) {
Object.keys(attrs).forEach(attr => {
el.setAttribute(attr, attrs[attr])
})
}
if (children) {
children = Array.isArray(children) ? children : [children];
for (let child of children) {
if (typeof child === "number") child = ""+child;
if (typeof child === "string") {
el.insertAdjacentText("afterbegin", child);
}
else {
try {
el.appendChild(child)
} catch (e) {
debugger
}
}
}
}
return el;
};
function setAttribute(selector,attr,value) {
document.querySelector(selector).setAttribute(attr,value);
}
function setCSS(selector, style) {
for (const property in style)
document.querySelector(selector).style[property] = style[property];
}
function hideLoader() {
setAttribute('.a-load-screen-main-container','style','display:none;')
}
function setupHTML() {
// note: these are required in the HTML itself, in the head (while this script should be added after the body)
// <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/loadingio/loading-bar@v0.1.0/dist/loading-bar.min.css"/>
// <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/loadingio/loading-bar@v0.1.0/dist/loading-bar.min.js"></script>
setAttribute('body','style',`overflow:hidden;color:white;background-color:${opts.backgroundColor};`);
document.body.prepend(
createEl('div', {class: 'a-load-screen-main-container', style: `
font:${opts.font};
font-size: 10pt;
text-shadow: 0 0 3px #fff;
z-index:1000;
height:100%;
position:relative;
overflow:hidden;
opacity:${opts.backgroundOpacity};
background-color:${opts.backgroundColor};
background-image:url(${opts.backgroundImage});
${opts.containerCSS || ""}
`}, // background image is experimental and untested
[
createEl('div', {/*class: 'center',*/ style: `
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
min-width:${contrainedImageDimensions[0]+9}px;
max-width:${contrainedImageDimensions[0]+9}px;
white-space:nowrap;
`},
[
createEl('div', {class: 'a-load-screen-content-container', style: `
position: relative;
height: unset;
display:grid;
overflow-y:scroll;
overflow-x:visible;
/* note that we have a class style that makes the scroll bars invisible here */
max-height:100vh;
`},
)
])
])
);
};
function cacheFileSize(el, size) {
debug('log',"WILL CACHE",el,size)
const url = el.getAttribute('src');
const cachedSizes = localStorage.cachedSizes ? JSON.parse(localStorage.cachedSizes) : {};
cachedSizes[url] = size;
localStorage.cachedSizes = JSON.stringify(cachedSizes);
}
function addEventListeners(el, bar, name) {
debug('log',el,bar,el.id, getFilename(el))
let firstByte = true;
let filename = getFilename(el);
el.addEventListener("error", evt => {
// note: this can be missed, sometimes the error happens before we've added the listeners it seems.
// Fetch error. Event detail contains xhr with XMLHttpRequest instance.
// used for a-asset-item, can be used for any file type
// also used for HTMLMediaElement (audio, video)
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
// this would normally cause a forever-hand, I think I want to patch that behavior though
debug('warn',"error loading file!", name, evt);
fileLoadError(name, evt, el);
// bar.set(n)
// bar.setAttribute('value',n)
// update to be red, different preset?
});
el.addEventListener("progress", evt => {
// used for a-asset-item, can be used for any file type
// also used for HTMLMediaElement (audio, video)
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
// debug('log',"progress", evt);
// xhr with XMLHttpRequest instance, loadedBytes, and totalBytes.
let loadedPercentage;
try {
loadedPercentage = (evt.detail.loadedBytes / evt.detail.totalBytes) * 100;
globalLoadRegister.bytes[filename][0] = evt.detail.loadedBytes;
globalLoadRegister.bytes[filename][1] = evt.detail.totalBytes;
updateBytes(name, bytesToMegabytes(evt.detail.loadedBytes, true), bytesToMegabytes(evt.detail.totalBytes, true));
updateGlobalLoader();
if (firstByte) {
firstByte = false;
cacheFileSize(el, globalLoadRegister.bytes[filename][1])
}
} catch (e) {
debug('warn','progress error, assuming this is a video and using experimental video load attempt',e)
if (el.buffered.length !== 0) {
debug("log","progress, likely video/audio?, buffered length is greater than 0", el.id, el)
try {
loadedPercentage = ((el.buffered.end(0)*100) / el.duration);
} catch (e) {
debug("error","problem using buffered.end(0)",e, el.buffered?.end)
debugger
}
debug('log', el.id, loadedPercentage);
} else {
debug("warn","progress, likely video (or audio?) but buffered length is 0", el.id, el)
}
}
if (loadedPercentage) bar.set(loadedPercentage, false);
});
el.addEventListener("loaded", evt => {
// emitted by a-asset-item
// however: this may be emitted when there is a timeout--makes sense with how aframe treats timeout...
// not sure, we should probably try to ignore that? todo...
bar.set(100,false);
globalLoadRegister.bytes[filename][0] = globalLoadRegister.bytes[filename][1];
updateBytes(name, Math.round(globalLoadRegister.bytes[filename][0] / 10000) / 100, Math.round(globalLoadRegister.bytes[filename][1] / 10000) / 100);
updateGlobalLoader();
// globalLoadRegister.bytes[name][1] = evt.detail.totalBytes;
if (firstByte) {
firstByte = false;
cacheFileSize(el, globalLoadRegister.bytes[filename][1])
}
});
el.addEventListener("timeout", evt => {
debug('warn',"timeout loading file?", evt);
// bar.set(n)
// bar.setAttribute('value',n)
// update to be red, different preset?
});
el.addEventListener("load", function(evt) {
// used for images
debug('log',"load event; IMG?", evt, this);
bar.set(100, false);
// bar.set(100, false) // maybe change color to green? do something else?
});
el.addEventListener("loadeddata", evt => {
// used for HTMLMediaElement (audio, video)
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
debug('log',"loadeddata; HTMLMediaElement (video/audio)?", evt);
bar.set(100, false);
// bar.set(n)
// bar.setAttribute('value',n)
});
};
function addLogo() {
if (opts.useLogoFillEffect && opts.useLogoGlitchEffect) {
let glitchAttributes = {
class:'glitch__item',
'style':`
min-width:${contrainedImageDimensions[0]}px; /* - 9 is because of the loading border*/
min-height:${contrainedImageDimensions[1]}px; /* this constains to a square when maxed out, not sure if this is the right compromise, but anyone is free to override this by passing in custom attributes instead! */
`
};
// let glitchLoaderAttributes =
// opts.customLogoLoaderAttributes ||
// {
// 'data-value':'0',
// 'data-fill-background':opts.logoFillColor,
// 'data-type':'fill',
// 'data-img':opts.logoURL,
// 'data-img-size': `${contrainedImageDimensions[0]},${contrainedImageDimensions[1]}`, //opts.logoSize,
// 'class': 'ldBar label-center auto a-loader-logo glitch__item',
// 'style':`
// min-width:${contrainedImageDimensions[0]}px; /* - 9 is because of the loading border*/
// min-height:${contrainedImageDimensions[1]}px; /* this constains to a square when maxed out, not sure if this is the right compromise, but anyone is free to override this by passing in custom attributes instead! */
// `
// // position:relative;
// };
let glitchLoaderAttributes =
Object.assign({
'data-value':'0',
'data-fill-background':opts.logoFillColor,
'data-type':'fill',
'data-img':opts.logoURL,
'data-img-size': `${contrainedImageDimensions[0]},${contrainedImageDimensions[1]}`, // contrainedImageDimensions, //opts.logoSize,
// 'class': 'ldBar label-center auto a-loader-logo',
'class': 'ldBar label-center auto a-loader-logo glitch__item',
'style':`
max-width:${contrainedImageDimensions[0] - 9}px; /* - 9 is because of the loading border*/
max-height:${contrainedImageDimensions[1] - 9}px; /* this constains to a square when maxed out, not sure if this is the right compromise, but anyone is free to override this by passing in custom attributes instead! */
position:relative;
`
}, opts.customLogoLoaderAttributes || {});
debug('log',"glitch loader attributes", glitchLoaderAttributes)
let glitchChildren = [0,1,2,3,4].map(n => {
let attrs = [0].includes(n) ? glitchLoaderAttributes : glitchAttributes;
return createEl('div', attrs);
});
if (opts.showTitle) {
glitchChildren = glitchChildren.concat([
createEl('p',{class:'glitch__title',style:`text-align:center;font-size:${opts.titleSize || '35px'};`})
])
}
anchor.appendChild(
createEl('div',{class:'glitch',
'style':`
max-width:${contrainedImageDimensions[0] + 9}px;
min-height:${contrainedImageDimensions[1] + 9}px;
`
}, glitchChildren)
)
logo = new ldBar('.a-loader-logo',{});
// see: https://codepen.io/AlainBarrios/pen/OEOKgm
// <div class="glitch">
// <div class="glitch__item"></div>
// <div class="glitch__item"></div>
// <div class="glitch__item"></div>
// <div class="glitch__item"></div>
// <div class="glitch__item"></div>
// <h1 class="glitch__title">A-FRAME</h1>
// </div>
}
else {
if (opts.useLogoFillEffect) {
let attributes = Object.assign({
'data-value':'0',
'data-fill-background':opts.logoFillColor,
'data-type':'fill',
'data-img':opts.logoURL,
'data-img-size': `${contrainedImageDimensions[0]},${contrainedImageDimensions[1]}`, // contrainedImageDimensions, //opts.logoSize,
'class': 'ldBar label-center auto a-loader-logo',
'style':`
max-width:${contrainedImageDimensions[0] - 9}px; /* - 9 is because of the loading border*/
max-height:${contrainedImageDimensions[1] - 9}px; /* this constains to a square when maxed out, not sure if this is the right compromise, but anyone is free to override this by passing in custom attributes instead! */
position:relative;
`
}, opts.customLogoLoaderAttributes || {});
anchor.appendChild(createEl('div', attributes));
debug('log','using logo fill effect without glitch...')
logo = new ldBar('.a-loader-logo',{});
}
else {
debug('error',"non-fill-effect not yet implemented")
}
}
if (opts.showTitle) {
debug('warn','if glitch title works, you may want to conditionally move this...')
anchor.appendChild(createEl('p', {id:'a-loader-title',style:opts.titleFontStyle}, opts.titleText))
}
if (opts.showSubtitle) {
anchor.appendChild(
createEl('span', {style:'display:inline!important;text-align:center;'}, opts.subtitleOverride ?
createEl('p', {id:'a-loader-subtitle-2',style:''}, opts.subtitleOverride) :
[
createEl('p', {id:'a-loader-subtitle-1',style:`display:inline!important;font:${opts.font};font-size:10px`}, "built with " ),
createEl('img',{src:aframeLogoDataIMG, id:'a-loader-subtitle-logo',style:"display:inline!important;width:10px"}),
createEl('p', {id:'a-loader-subtitle-2',style:`display:inline!important;font:${opts.font};font-size:10px`}, "-Frame" ),
]
)
)
}
};
function updateSubtitle(text) {
try {
document.querySelector('#a-loader-subtitle-2').innerText = text;
document.querySelector('#a-loader-subtitle-1').style.display = "none";
// document.querySelector('#a-loader-subtitle-logo').style.display = "none";
} catch (e) {
debug('warn','cannot update subtitle',e)
}
};
// {"xmlns":"http://www.w3.org/2000/svg", "width":"350", "height":"20", "viewBox":"0 0 350 20", "x":"175", "y":"10", "text-anchor":"middle", "dominant-baseline":"central", "font-family":"arial"}
function generateFilenameAttributes(filename) {
return Object.assign(opts.customBarLoaderAttributes || {},{
"data-type": 'fill',
"data-fill-background":"white",
"data-img": `data:image/svg+xml,<svg xmlns="${opts.filenamesPresetOptions.xmlns}" width="${opts.filenamesPresetOptions.width}" height="${opts.filenamesPresetOptions.height}" viewBox="${opts.filenamesPresetOptions.viewbox}"><text x="${opts.filenamesPresetOptions.x}" y="${opts.filenamesPresetOptions.y}" text-anchor="${opts.filenamesPresetOptions['text-anchor']}" dominant-baseline="${opts.filenamesPresetOptions['dominant-baseline']}" font-family="${opts.filenamesPresetOptions['font-family']}">${filename}</text></svg>`,
"data-fill-background-extrude": 1.3,
"data-pattern-size": 100,
"data-fill-dir": "ltr",
"data-img-size": "350,20",
// we require:
'class': 'ldBar label-center auto a-loader-logo',
'style':`
position:relative;
height:unset;
`
});
};
let speedometer;
function addStats() {
let stats = [];
let gridTemplateColumns = "";
if (opts.showVisualSpeedometer) {
anchor.appendChild(
createEl('div',{class:`visual-speedometer-container`, style:`max-width:${maxWidth}px;display:${!opts.showGlobalStats?"none":"grid"};grid-template-columns:${calculateStatsBuffer()}px ${opts.showDownloadTotals || opts.showFileSizes ? 40 + 15 + 40 + 30 +"px" : "0px"} 100px;`}, [
createEl('div'), // buffer for image centering
createEl('div'), // buffer that corresponds to file size stats
createEl('div',{class:`ldBar label-center auto visual-speedometer`,'data-preset':'fan','data-value':10,'data-stroke':'data:ldbar/res,gradient(0,1,#a551df,#fd51ad,#ff7f82,#ffb874,#ffeb90)'})
])
)
if (opts.showVisualSpeedometer) speedometer = new ldBar('.visual-speedometer',{});
}
if (opts.showDownloadTotals) {
gridTemplateColumns += `40px 10px 40px 29px ${calculateStatsBuffer()}px `;
let totals = localStorage.cachedSizes ? JSON.parse(localStorage.cachedSizes) : null;
let total;
if (totals) {
total = Object.keys(totals).reduce((memo, key) => memo + totals[key], 0)
}
stats.push(
// createEl('div',{class:`text-totals`, style:"margin-top:10px;"},`--.-- / ${total ? Math.round(total/(10**4))/100 :'--.--'} MB`),
createEl('p',{style:'text-align:left;',class:`total-bytes-down`},`${0}`),
createEl('p',{style:'text-align:center;',class:`total-bytes-slash`},`/`),
createEl('p',{style:'text-align:right;',class:`total-bytes-total`},`${total ? roundToDecimal(total/(10**6),2) :'--.--'}`), // roundToDecimal
createEl('p',{style:'text-align:center;',class:`total-bytes-label`},`MB`),
createEl('div',{}),
)
}
else {
// this isn't great, but we normally do this logic there and put the buffer after the download totals; if those aren't being shown, then we add it here
stats.unshift(createEl('div',{}));
gridTemplateColumns = calculateStatsBuffer()+"px ";
}
if (opts.showTextSpeedometer) {
gridTemplateColumns += "55px 35px ";
stats.push(
createEl('p',{class:`text-speedometer`,style:"text-align:left;padding-left:5px;"},"000.00"),
createEl('p',{class:`text-speedometer-unit`,style:"text-align:right;"}," MB/s"),
//
)
}
if (opts.showTimeElapsed) {
gridTemplateColumns += "150px ";
stats.push(
createEl('p',{class:`text-elapsed`, style:"text-align:center;"},"-- s")
)
}
if (stats.length) {
anchor.appendChild(
createEl('div',{class:'stats-container',style:`display:${!opts.showGlobalStats?"none":"grid"};max-width:${maxWidth}px;white-space:nowrap;text-overflow:clip;grid-template-columns:${gridTemplateColumns}`},stats)
);
anchor.appendChild(createEl('hr',{style:`width:${opts.horizontalRulePercent}%`}))
}
};
function calculateBarBuffer() {
// todo: remove this 89 and make it response, just the value I see the bar being when I checked but that should be adjustable...
if (opts.showBarLoaders && !opts.centeredLoadingBars) {
return 0; // really?
}
let ldBarWidth = opts.showBarLoaders ? 89 : 0,
leftOfBarContentWidth = opts.showFileSizes ? 40 + 15 + 40 + 30 : 0;
debug('log',"bar buffer", maxWidth, ldBarWidth, leftOfBarContentWidth, Math.floor((maxWidth / 2) - (ldBarWidth / 2) - leftOfBarContentWidth));
return Math.max(0,Math.floor((maxWidth / 2) - (ldBarWidth / 2) - leftOfBarContentWidth));
};
function calculateStatsBuffer() {
let ldBarWidth = opts.showVisualSpeedometer ? 89 : 0,
leftOfBarContentWidth = opts.showDownloadTotals ? 40 + 15 + 40 + 30 : 0;
debug('log',"stats buffer", maxWidth, ldBarWidth, leftOfBarContentWidth, Math.floor((maxWidth / 2) - (ldBarWidth / 2) - leftOfBarContentWidth));
return Math.max(0,Math.floor((maxWidth / 2) - (ldBarWidth / 2) - leftOfBarContentWidth));
};
function calculateFilenameWidth() {
if (!opts.showFilenames) return 0;
let ldBarWidth = opts.showBarLoaders ? 89 : 0;
return Math.floor((maxWidth/2) - (ldBarWidth / 2));
}
let fileRetryCounters = {};
function addBar(el, showBar) {
let name = `a-loader-${barCounter}`;
fileRetryCounters[name] = 0;
if (opts.barLoaderPreset === "filenames") {
opts.customBarLoaderAttributes = Object.assign(generateFilenameAttributes(getFilename(el)), opts.customBarLoaderAttributes || {} );
}
let attributes = Object.assign({
'class': `ldBar label-center auto`,
'data-preset': opts.barLoaderPreset,
// 'data-value':'0',
// 'data-fill-background':'red',
// 'data-stroke':'green',
'style':`
position: relative;
height: unset;
padding-left: 5px;
padding-right: 5px;
`
}, opts.customBarLoaderAttributes);
if (!opts.showBarLoaders) attributes.style = "display:none;" + attributes.style;
let barEl = createEl('div', attributes)
barEl.classList.add(name);
let loadIsTrackable = addToGlobalLoadRegister(el, name);
if (loadIsTrackable > 0) {
let gridTemplateColumns = "";
let fileBarEls = [];
let filenameWidth = calculateFilenameWidth(maxWidth, 89);
let buffer = calculateBarBuffer(); // todo: make this not hardcoded, just an experimental amount for now
if (opts.showFileSizes && loadIsTrackable === 1) {
gridTemplateColumns = `${opts.showFileSizes ? `40px 10px 40px 29px ${buffer}px ` : ""} `
fileBarEls.push(createEl('p',{class:`${name}-bytes-down`},`${0}`)); // ...
fileBarEls.push(createEl('p',{class:`${name}-bytes-slash`},`/`)); // ...
fileBarEls.push(createEl('p',{class:`${name}-bytes-total`, style:'text-align:right;'},`${bytesToMegabytes(getFileSize(el),true)}`)); // ...
fileBarEls.push(createEl('p',{class:`${name}-bytes-label`, style:'text-align:center;'},`MB`)); // ...
fileBarEls.push(createEl('div',{style:`min-width:${buffer}px;`})) // add spacer to align loading bars with center of screen
}
else {
gridTemplateColumns = `${buffer}px `;
fileBarEls.push(createEl('div',{style:`min-width:${buffer}px;`})) // add spacer to align loading bars with center of screen
}
// this one always has to go in in current implementation, instead we do display:none if it should hide; todo: improve that
// if (opts.showBarLoaders) {
fileBarEls.push(barEl);
// }
if (opts.showFilenames) {
// note: width:filenameWidth was broken before, so... now that it's fixed, make sure it doesn't break anything. also, text-overflow:ellipses was mispelled, make sure you like it now.
fileBarEls.push( createEl('p',{style:`width:${filenameWidth}px;white-space:nowrap;text-overflow:ellipses;`}, opts.useFilename ? getFilename(el) : el.id) );
}
if (fileBarEls.length) {
gridTemplateColumns += ` ${opts.showBarLoaders ? "89px" : ""} ${filenameWidth ? filenameWidth + "px" : ""}` /* TODO: filenames preset changes this equation, need to handle not having bar there generally*/
// let gridTemplateColumns = `${opts.showFileSizes ? `${buffer}px 40px 15px 40px 30px ` : ""}${opts.showBarLoaders ? `${opts.barLoaderPreset === "filenames" ? 350 : 100}px ` : ""}${opts.showFilenames ? "250px " : ""}`
// NOTE: if you want to contrain text / clip overflow, you need to explicitly set width property.
debug('log','bar columns:',gridTemplateColumns)
anchor.appendChild(
createEl(
'div',
{
class:'bar-container',
style:`
display:${!opts.showFileStats?"none":"grid"};
${opts.fadeLoaderRows ? '-webkit-mask-image: linear-gradient(90deg, #000 90%, transparent);' : ''}
max-width:${maxWidth}px;
overflow:hidden;white-space:nowrap;text-overflow:clip;
grid-template-columns:${gridTemplateColumns}`
},
fileBarEls
)
);
}
let bar = new ldBar(`.${name}`, {});
addEventListeners(el, bar, name);
barCounter++;
}
};
function updateBytes(name, downloaded, outOf) {
if (!opts.showFileSizes) return;
document.querySelector(`.${name}-bytes-down`).innerHTML = `${downloaded}`;
document.querySelector(`.${name}-bytes-total`).innerHTML = `${outOf}`;
}
function fileLoadError(name, evt, el) {
let errorBar = document.querySelector(`.${name}`).parentElement;
errorBar.style.backgroundColor = "red";
errorBar.setAttribute('title',evt.detail.xhr.message);
// debug("log",{AFRAME, 'THREE.Cache':THREE.Cache})
if (fileRetryCounters[name] < opts.fileRetryOnError) {
debug('error','file load retry not yet implemented; for now, forcing a page refresh is recommended');
// how to do this: a-frame probably isn't set up to expect dynamically added elements to a-assets
// but if we want fully compatible use when doing a reload, we'll need to allow the same access-via-ID system...
// need to look into this.
}
else if (opts.skipLoadErrors) {
// this fools aframe into allowing it to continue with scene load
debug('warn','will ignore file error and tell aframe to continue anyways')
evt.target.emit('loaded',{});
}
if (opts.onFileLoadError) {
let url = evt.detail.xhr.message.split('"')[1];
opts.onFileLoadError(getFilename(el), url, evt)
}
}
function getClaimedFileSize(el) {
// <a-asset-item filesize="1.21"></a-asset-item>
// -> 1210000 bytes
let claimedSize = el.getAttribute('filesize');
return claimedSize ? Number(claimedSize) : -1; // (mb = 1000 kb = 1000 b)
}
function getFileSize(el) {
// tries to get claimed size directly on el
// if not available, will use cached size if available
// if not available, with fall back to smoothLogoLoadFactor, which is an imaginary presumed value in bytes to use
let claimed = getClaimedFileSize(el);
const url = el.getAttribute('src');
// debug("log","cached",el,el.getAttribute('src'),getFilename(el))
let cached = localStorage.cachedSizes ? JSON.parse(localStorage.cachedSizes)[url] : -1;
return claimed !== -1 ?
claimed :
cached !== -1 ?
cached :
opts.smoothLogoLoadFactor
}
function addToGlobalLoadRegister(el, name) {
if (el.tagName === "A-ASSET-ITEM") {
globalLoadRegister.bytes[getFilename(el)] = [0, getFileSize(el)];
// first class citizen, we can track
return 1; // thing we're primarily handling right now
}
else if (el.tagName === "TEMPLATE" || el.tagName === "A-MIXIN") {
debug('log',"skipping template")
return 0; // these aren't truly loaded in the same way
}
else if (el.tagName === "IMG" || el.tagName === "VIDEO" || el.tagName === "AUDIO") {
debug('warn',`EXPERIMENTAL: ${el.tagName}`)
// todo: look into it more, but at least an image loaded counter maybe?
// second class citizen, we seem to only get binary states for this, will use 2 for this
return 2; // I think it only supports 0 & 100, but we'll see how it goes
}
else {
debug('error',`UNTRACKED UNKNOWN LOAD ASSET (TODO?): ${el.tagName}`, name, el, el)
return 0;
}
};
function debug(f="log", ...args) {
if (opts.debug.includes(f)) {
console[f]('a-load-screen|',...args);
}
}
function getFilename(el) {
let filename;
try {
let urlChunks = el.attributes.src?.value.split("/");
let lastChunk = urlChunks[urlChunks.length-1];
filename = lastChunk.split("?")[0];
} catch (e) {
return "unknown file";
}
return filename;
};
function getTotalBytes(n) {
// if n = 0, bytes loaded
// if n = 1, bytes to load
// todo: add non-bytes stuff, e.g. images; see
// https://aframe.io/docs/1.3.0/core/asset-management-system.html
return Object.values(globalLoadRegister.bytes)
.reduce((memo, val) => memo + val[n], 0);
}
function roundToDecimal(val, decimalPoints) {
return Math.round(val * (10**decimalPoints))/(10**decimalPoints);
}
let firstLoad = true;
function updateGlobalLoader() {
if (firstLoad) {
firstLoad = false;
firstByteTime = Date.now();
}
let loaded = getTotalBytes(0);
let toLoad = getTotalBytes(1);
if (opts.useLogoFillEffect) logo.set((loaded / toLoad)*100);
updateStats(loaded, toLoad)
if (loaded === toLoad) {
opts.onFilesLoaded();
logAssetsWithFileSizes();
}
}
function bytesToMegabytes(n, clean) { return !clean ? n / 10**6 : roundToDecimal(n / 10**6, 2) }
function logAssetsWithFileSizes() {
let assetsHTMLstring = document.querySelector('a-assets').outerHTML;
if (assetsHTMLstring.includes('filesize=')) {
debug('warn','will not print asset html with filesize attributes because filesize is already present; remove filesize attributes from any a-asset-item to have a new one generated')
return
}
let cachedFileSizes = JSON.parse(localStorage.cachedSizes);
Object.keys(cachedFileSizes).forEach(cachedFilename => {
assetsHTMLstring = assetsHTMLstring.replace(cachedFilename, `${cachedFilename}" filesize="${cachedFileSizes[cachedFilename]}`)
})
debug('log','swap your existing a-assets HTML with the below HTML to ensure correct file sizes instantly on first load for users before first byte has arrived for each file: \n\n\n',assetsHTMLstring)
}
let speedText;
let totalText;
let totalText2
let timeText;
let subtractTime = 0;
let subtractData = 0;
let lastSpeedometerUpdate = 0;
function updateStats(loaded, toLoad) {
let now = Date.now();
let adjustedDataLoaded = loaded - subtractData;
let msLoading = now - firstByteTime;
let adjustedMsLoading = msLoading - subtractTime;
let adjustedMBSLoaded = bytesToMegabytes(adjustedDataLoaded, false);
let adjustedSecondsLoading = adjustedMsLoading / 1000;
let fullSpeed = 100; // MB/s; could make 1000, but then everyone would look bad. :(
let speed = adjustedMBSLoaded / adjustedSecondsLoading;
// if we stop here, we get average download speed across the entire download
// but in reality, the speed goes up as server file connections initiate
// it's more satisfying to see live speeds that aren't held down by the
// average in the beginning, so let's cut out old data from the average
// as we go on
if (adjustedMsLoading > 300) {
// if more than a second has passed since we last removed old data/time count
// then remove half of old data for the next iteration to start clean for the next second
subtractTime = now - firstByteTime;
subtractData = loaded;
}
if (now - lastSpeedometerUpdate > 100) {
lastSpeedometerUpdate = now;
if (opts.showVisualSpeedometer) speedometer.set((speed / fullSpeed) * 100, false);
if (opts.showTextSpeedometer) {
speedText = speedText || document.querySelector('.text-speedometer');
speedText.innerHTML = `${roundToDecimal(speed,1)}`;
}
}
if (opts.showDownloadTotals) {
totalText = totalText || document.querySelector('.total-bytes-down');
totalText.innerHTML = `${roundToDecimal(bytesToMegabytes(loaded, true),2)}`;
totalText2 = totalText2 || document.querySelector('.total-bytes-total');
totalText2.innerHTML = `${roundToDecimal(bytesToMegabytes(toLoad, true),2)}`;
// `--.-- / ${total ? Math.round(total/(10**4))/100 :'--.--'} mb`
}// text-totals
if (opts.showTimeElapsed) {
timeText = timeText || document.querySelector('.text-elapsed');