-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathyo.js
More file actions
582 lines (489 loc) · 15.4 KB
/
yo.js
File metadata and controls
582 lines (489 loc) · 15.4 KB
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
/**
* Yo, the single page dependency management script created by pocketninja for his own amusement
* version 2.0.1
*
* @module Yo
* @returns {object} public functions
*/
function Yo() {
"use strict";
const version = '2.0.1';
// Yo.loadedState.tooltip.{
// loaded: boolean
// loadedFunc: function
// dependedBy: [string],
// dependencies: [string]
// }
/**
* container of the namespace object provided by the user with Yo.init()
* @private
* @var {object} ns
*/
let ns;
let scriptRoot = 'modules';
/**
* Counter for items added for debugging output
* @private
* @var {number} totalScriptsAdded
*/
let totalScriptsAdded = 0;
/**
* Counter for items loaded for debugging output
* @private
* @var {number} totalScriptsLoaded
*/
let totalScriptsLoaded = 0;
/**
* After creating Yo you need to provide it with your main namespace to any level within it. Like "company" or "company.cool.scripts"
*
* @method init
* @param {Object} data - initial organisation data object
* @param {String} data.namespace - where all of your scripts go in the organisation data object
* @param {Boolean} data.debugMode - for outputting scripts and connection when they happen
* @param {Array} data.debugScripts - choose which scripts you want to output data on
*
* @example
* Yo.init({
* namespace: your.script.name.space,
* scriptRoot: 'cheese'
* debugMode: true,
* debugScripts: ['scriptOne', 'scriptTwo']
* });
*/
const init = function(data){
ns = data.namespace || Yo;
Yo.loadedState = {};
if(data.scriptRoot) {
scriptRoot = data.scriptRoot;
}
ns[scriptRoot] = ns[scriptRoot] || {};
ns.debugMode = data.debugMode || false;
ns.debugScripts = data.debugScripts || undefined;
if(ns.debugMode) {
Yo.loadOrder = [];
}
// global dependencies will be added to all
// scripts by default unless specified
ns.globalDependencies = data.globalDependencies || undefined;
};
const isDebugScriptsEmpty = function() {
return isTypeOf('Array', ns.debugScripts) && ns.debugScripts.length < 1;
};
const renderLogOrDebugScript = function(str, fn) {
if(ns.debugMode) {
if(ns.debugScripts === undefined || isDebugScriptsEmpty()) {
fn(str);
}
else if(!isDebugScriptsEmpty()) {
ns.debugScripts.forEach(function(scriptItem) {
if(str.search(scriptItem) > -1) {
fn(str);
}
});
}
}
};
const log = function(str) {
renderLogOrDebugScript(str, function() {
console.log(str);
});
};
const isTypeOf = function(str, obj) {
return '[object ' + str + ']' === Object.prototype.toString.call(obj);
};
/**
* Arguments checker
*
* Take an array of arguments and compare it's type with an array sequence of
* strings type values.
*
* @method argumentChecker
* @param {Array} args List of arguments
* @param {Array} argSequence List of String argument types
*
* @returns {boolean} based on the arguments list being correct
*
*/
const argumentChecker = function(args, argSequence) {
if (args.length !== argSequence.length) return false;
for (let i = 0; i < args.length; i++) {
const val = args[i];
const expected = argSequence[i];
if (!isTypeOf(expected, val)) {
const actualTag = Object.prototype.toString.call(val);
const actualType = actualTag.slice(8, -1);
log(
`argumentChecker: type mismatch at index ${i} - ` +
`expected '${expected}', got '${actualType}' ` +
`(value: ${String(val)})`
);
return false;
}
}
return true;
};
/**
* Gets either an object or false
*
* @method nsGet
* @param {string} _nsStr Script namespace or name
* @param {object} _nsObject Namespace object
* @param {boolean} _getObjectRoot What does this mean !!!?
*
* @returns {Boolean} if the object namespace does'nt exist
* @returns {Object} of the namespace requested
*
*/
const nsGet = function(_nsStr, _nsObject, _getObjectRoot) {
let keyArr;
if (isTypeOf('Array', _nsStr)) {
keyArr = _nsStr[1].split('.');
}
else {
keyArr = _nsStr.split('.');
}
let currentObj = _nsObject;
_getObjectRoot = _getObjectRoot || false;
for(let i = 0; i < keyArr.length; i++) {
if (!currentObj[keyArr[i]]) {
return false;
}
if(_getObjectRoot && (i === keyArr.length - 1)) {
return currentObj;
}
currentObj = currentObj[keyArr[i]];
}
return currentObj;
};
/**
* Set new branches to your namespace tree
* WIll run through the object tree creating
* everything that doesn't exist.
*
* @method nsSet
* @param {string} _nsStr Script namespace or name
* @param {object} _nsObject Namespace object
* @param {boolean} _getObjectRoot What does this mean, find out?!?!?
*
* @returns {object} Section of the object param
*
*/
const nsSet = function(_nsStr, _nsObject, _getObjectRoot) {
let keyArr;
if (isTypeOf('Array', _nsStr)) {
keyArr = _nsStr[1].split('.');
}
else {
keyArr = _nsStr.split('.');
}
let currentObj = _nsObject;
_getObjectRoot = _getObjectRoot || false;
if (keyArr.length < 2) {
if(!currentObj[_nsStr]) {
currentObj[_nsStr] = {};
}
if(_getObjectRoot) {
return _nsObject;
}
return currentObj[_nsStr];
}
else {
for(let i = 0; i < keyArr.length; i++) {
if (!currentObj[keyArr[i]]) {
currentObj[keyArr[i]] = {};
}
if(_getObjectRoot && (i === keyArr.length - 1)) {
return currentObj;
}
currentObj = currentObj[keyArr[i]];
}
}
return currentObj;
};
const load = function(resource) {
// resource can be:
// - .js file → loads as <script>
// - .css file → loads as <link rel="stylesheet">
// - any other URL → loads as <script> by default
const isCss = /\.css$/i.test(resource);
// Shared cache (prevents double loading)
load.cache = load.cache || new Map();
if (load.cache.has(resource)) {
const entry = load.cache.get(resource);
entry.totalCalls++; // add 1 to the total calls to this script
if (entry.loaded) {
return Promise.resolve();
}
// Still loading → wait for it
return new Promise(resolve => {
entry.callbacks.push(resolve);
});
}
// New load
const entry = {
loaded: false,
callbacks: [],
totalCalls: 1 // first init call makes 1 so may as well start with 1
};
load.cache.set(resource, entry);
return new Promise((resolve, reject) => {
let el;
if (isCss) {
el = document.createElement('link');
el.rel = 'stylesheet';
el.href = resource;
} else {
el = document.createElement('script');
el.src = resource;
el.async = true;
}
el.onload = () => {
entry.loaded = true;
resolve();
// Run all waiting callbacks
entry.callbacks.forEach(cb => cb());
entry.callbacks = []; // clean up
if (ns?.debugMode) {
log(`YO.LOAD success: ${resource} (${isCss ? 'CSS' : 'JS'})`);
}
};
el.onerror = (err) => {
load.cache.delete(resource);
reject(err);
if (ns?.debugMode) {
log(`YO.LOAD failed: ${resource}`);
}
};
document.head.appendChild(el);
if (ns?.debugMode) {
log(`YO.LOAD started: ${resource}`);
}
});
};
/**
* For adding new scripts with their own dependencies
*
* @method add
* @param {string} scriptName Script name
* @param {Array} [scriptDependencies=undefined] Script list of dependencies
* @param {function} scriptCallback Script module callback
*
* @example
* Yo.add('WidgetName', ['dependency1', 'dependency2', 'etc'], function() {
* // your code in here
* return {}
* });
*/
const add = function() {
let scriptName;
let scriptDependencies = [];
let scriptCallback;
let hasNoDependencies = true;
const getLoadedState = function(_script) {
return nsGet(_script, Yo.loadedState);
};
const setLoadedState = function(_script, _data) {
Object.assign(nsSet(_script, Yo.loadedState), _data);
};
const activateScript = function(_script) {
const nsLocation = nsSet(_script, ns[scriptRoot], true);
let lastNameSpace = _script.split('.');
lastNameSpace = lastNameSpace[lastNameSpace.length - 1];
if(getLoadedState(_script).loaded) {
nsLocation[lastNameSpace] = getLoadedState(_script).loadedFunc();
// Debugging Section
totalScriptsLoaded += 1;
log('YO.LOADED: ' + _script);
renderLogOrDebugScript(_script, function() {
Yo.loadOrder.push(_script);
});
log('scripts ADDED: ' + totalScriptsAdded + ', LOADED: ' + totalScriptsLoaded);
// After script activation, run the final
// function activating any dependedBy scripts
// if this is the last script in its list.
getLoadedState(_script).runAfterActivation();
}
};
const getScript = function(_script) {
return nsSet(_script, ns[scriptRoot]);
};
const createOrEditLoadedState = function(_data, _script) {
_script = _script || scriptName;
setLoadedState(_script, Object.assign({
loaded: false,
loadedFunc: function(){},
runAfterActivation: function(){},
dependedBy: [],
dependencies: []
}, nsSet(_script, Yo.loadedState) || {}, _data));
};
/**
* Callback added to loadState[scriptName].loadedFunc which is run once all of it's dependencies have loaded
*
* @function pushFunction
* @private
*/
const pushFunction = function() {
createOrEditLoadedState({
loaded: true,
loadedFunc: function() {
log(scriptName + ' called and already loaded');
}
});
const obj = {};
objectToArray(scriptDependencies).map(function(_scriptName) {
obj[_scriptName[0]] = getScript(_scriptName[1]);
});
return scriptCallback.apply(null, [obj]);
// return scriptCallback.apply(null, scriptDependencies.map(function(_scriptName) {
// return getScript(_scriptName);
// }));
};
const checkDependedBy = function() {
const dependedBy = getLoadedState(scriptName).dependedBy;
let otherScript;
// Loop through dependedBy list
for(let i = 0; i < dependedBy.length; i++) {
otherScript = dependedBy[i];
// Each dependedBy has a dependency list, so this removes
// the current script from it's array and then removes the
// dependency from the current script dependedBy
for(let a = 0; a < getLoadedState(otherScript).dependencies.length; a++) {
if (getLoadedState(otherScript).dependencies[a][1] === scriptName) {
getLoadedState(otherScript).dependencies.splice(a, 1);
dependedBy.splice(i, 1);
i--;
log('DEPENDENCY: ' + otherScript + ' dependent on ' + scriptName);
break;
}
}
if (getLoadedState(otherScript).dependencies.length < 1) {
getLoadedState(otherScript).loaded = true;
activateScript(otherScript);
}
}
};
const checkDependencies = function() {
let allDependenciesLoaded = true;
const scriptDependents = getLoadedState(scriptName).dependencies;
let dependencyScript;
let dependencyScriptName;
log('SCRIPTS: ' + scriptName + ' dependent on [' + JSON.toString(scriptDependents) + ']');
log(scriptDependents);
for(let i = 0; i < scriptDependents.length; i++) {
dependencyScript = scriptDependents[i];
dependencyScriptName = dependencyScript[1];
// If script name loadState doesn't
// exist then create one
if(!nsGet(dependencyScriptName, Yo.loadedState)) {
createOrEditLoadedState({}, dependencyScriptName);
}
if(!getLoadedState(dependencyScriptName).loaded) {
log('QUICK TEST');
log(dependencyScriptName);
log(getLoadedState(dependencyScriptName));
log('-------------------');
getLoadedState(dependencyScriptName).dependedBy.push(scriptName);
allDependenciesLoaded = false;
}
else {
scriptDependents.splice(i, 1);
i--;
}
}
if(allDependenciesLoaded) {
getLoadedState(scriptName).loaded = true;
}
};
let hasFunction = true;
const objectHasValue = function (obj, value) {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i += 1) {
if (obj[keys[i]] === value) {
return true;
}
}
return false;
};
const objectIsEmpty = function (obj) {
return Object.keys(obj).length < 1;
};
const objectToArray = function (obj) {
const keys = Object.keys(obj);
const returnList = [];
for (let i = 0; i < keys.length; i += 1) {
returnList.push([keys[i], obj[keys[i]]]);
}
return returnList;
};
if(argumentChecker(arguments, ['String', 'Object', 'Function'])) {
scriptName = arguments[0];
scriptDependencies = arguments[1];
if (ns.globalDependencies) {
scriptDependencies = Object.assign({}, scriptDependencies, ns.globalDependencies);
}
// scriptDependencies = arguments[1];
scriptCallback = arguments[2];
hasNoDependencies = objectIsEmpty(scriptDependencies);
}
else if(argumentChecker(arguments, ['String', 'Function'])) {
scriptName = arguments[0];
scriptCallback = arguments[1];
// This uses global dependencies now
if (ns.globalDependencies !== undefined && !objectHasValue(ns.globalDependencies, scriptName)) {
scriptDependencies = Object.assign({}, ns.globalDependencies);
hasNoDependencies = objectIsEmpty(scriptDependencies);
}
}
else if(argumentChecker(arguments, ['String'])) {
// For window global variables to activate other scripts
scriptName = arguments[0];
hasFunction = false;
}
else {
log('incorrect params added', arguments);
return false;
}
if (!scriptName) {
log('YO.ADD failed: no valid scriptName provided');
return false;
}
// No overriding or duplicate file paths, block here
// if (nsGet(scriptName, Yo.loadedState)) {
// const msg = `Yo.add: Duplicate registration attempt for script "${scriptName}"`;
// console.error(msg);
// throw new Error(msg);
// }
log('YO.ADD: ' + scriptName);
totalScriptsAdded += 1;
if (hasNoDependencies) {
createOrEditLoadedState({
loaded: true,
loadedFunc: scriptCallback
});
if (hasFunction) {
activateScript(scriptName);
}
checkDependedBy();
}
else {
createOrEditLoadedState({
loadedFunc: pushFunction,
dependencies: objectToArray(scriptDependencies),
runAfterActivation: function() {
checkDependedBy();
}
});
checkDependencies();
activateScript(scriptName);
}
};
return {
add: add,
argumentChecker: argumentChecker,
init: init,
isTypeOf: isTypeOf,
load: load,
version: version
}
}