-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathMain.mjs
567 lines (497 loc) · 14.3 KB
/
Main.mjs
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
import Neo from './Neo.mjs';
import * as core from './core/_export.mjs';
import DomAccess from './main/DomAccess.mjs';
import DomEvents from './main/DomEvents.mjs';
import Observable from './core/Observable.mjs';
import WorkerManager from './worker/Manager.mjs';
/**
* @class Neo.Main
* @extends Neo.core.Base
* @singleton
*/
class Main extends core.Base {
/**
* True automatically applies the core.Observable mixin
* @member {Boolean} observable=true
* @static
*/
static observable = true
static config = {
/**
* @member {String} className='Neo.Main'
* @protected
*/
className: 'Neo.Main',
/**
* @member {String} mode='read'
* @protected
*/
mode: 'read',
/**
* @member {Object} openWindows={}
* @protected
*/
openWindows: {},
/**
* @member {Array} readQueue=[]
* @protected
*/
readQueue: [],
/**
* Remote method access for other workers
* @member {Object} remote={app: [//...]}
* @protected
*/
remote: {
app: [
'alert',
'editRoute',
'getByPath',
'getWindowData',
'importAddon',
'log',
'redirectTo',
'reloadWindow',
'setNeoConfig',
'setRoute',
'windowClose',
'windowCloseAll',
'windowMoveTo',
'windowOpen',
'windowResizeTo'
]
},
/**
* @member {Boolean} running=false
* @protected
*/
running: false,
/**
* @member {Boolean} showFps=false
*/
showFps: false,
/**
* @member {Boolean} singleton=true
* @protected
*/
singleton: true,
/**
* @member {Number} timeLimit=15
*/
timeLimit: 15,
/**
* should be dev only
* @member {Number} totalFrameCount=0
* @protected
*/
totalFrameCount: 0,
/**
* @member {Array} updateQueue=[]
* @protected
*/
updateQueue: [],
/**
* @member {Array} writeQueue=[]
* @protected
*/
writeQueue: []
}
/**
* @param {Object} config
*/
construct(config) {
super.construct(config);
let me = this;
WorkerManager.on({
'automount' : me.onRender,
'message:mountDom' : me.onMountDom,
'message:updateDom': me.onUpdateDom,
'updateVdom' : me.onUpdateVdom,
scope : me
});
DomEvents.on('domContentLoaded', me.onDomContentLoaded, me);
if (document.readyState !== 'loading') {
DomEvents.onDomContentLoaded()
}
}
/**
* Workers can not trigger alert(), so we need remote method access.
* @param {Object} data
* @param {String} data.message
*/
alert(data) {
alert(data.message)
}
/**
* Edit the location.hash value
* A value of null will remove the given key.
* @param {Object} data
*/
editRoute(data) {
let hashObj = DomEvents.parseHash(window.location.hash.substr(1)),
hashArr = [];
if (typeof data === 'string') {
data = DomEvents.parseHash(data)
}
Object.assign(hashObj, data);
Object.entries(hashObj).forEach(([key, value]) => {
if (value !== null) {
hashArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
}
});
window.location.hash = hashArr.join('&')
}
/**
* Request specific accessible window attributes by path into the app worker.
* Keep in mind that this excludes anything DOM related or instances.
* In case your path matches a method, you can also pass params for it.
* @example:
* Neo.Main.getByPath({path: 'navigator.language'}).then(data => {})
* @example:
* Neo.Main.getByPath({path: 'CSS.supports', params: ['display: flex']}).then(data => {})
* @param {Object} data
* @param {Array} data.params=[]
* @param {String} data.path
* @returns {*}
*/
getByPath({params=[], path}) {
let target = Neo.nsWithArrays(path);
return Neo.isFunction(target) ? target(...params) : target
}
/**
* window.screen is not spreadable
* @returns {Object}
*/
getWindowData() {
let win = window,
{screen} = win;
return {
innerHeight: win.innerHeight,
innerWidth : win.innerWidth,
outerHeight: win.outerHeight,
outerWidth : win.outerWidth,
screen: {
availHeight: screen.availHeight,
availLeft : screen.availLeft,
availTop : screen.availTop,
availWidth : screen.availWidth,
colorDepth : screen.colorDepth,
height : screen.height,
orientation: {angle: screen.orientation?.angle, type: screen.orientation?.type},
pixelDepth : screen.pixelDepth,
width : screen.width
},
screenLeft: win.screenLeft,
screenTop : win.screenTop
}
}
/**
* Import main thread addons at run-time from within the app worker
* @param {Object} data
* @param {String} data.name
* @returns {Boolean}
*/
async importAddon(data) {
let {name} = data,
module;
if (name.startsWith('WS/')) {
module = await import(`../../../src/main/addon/${name.substring(3)}.mjs`)
} else {
module = await import(`./main/addon/${name}.mjs`)
}
this.registerAddon(module.default);
await this.timeout(20); // Wait until remotes are registered
return true
}
/**
* Remote console access to main threads.
* You can use appName or windowId to target specific windows.
* @param {Object} data
* @param {String} [data.appName]
* @param {String} data.value
* @param {String} [data.method] defaults to 'log'
* @param {Number} [data.windowId]
* @returns {Boolean}
*/
log(data) {
console[data.method || 'log'](data.value);
return true
}
/**
*
*/
async onDomContentLoaded() {
let me = this,
{config} = Neo,
{mainThreadAddons} = config,
imports = [],
modules;
DomAccess.onDomContentLoaded();
// we need different publicPath values for the main thread inside the webpack based dist envs,
// depending on the hierarchy level of the app entry point
if (config.environment !== 'development') {
__webpack_require__.p = config.basePath.substring(6)
}
// intended for the online examples where we need an easy way to add GA to every generated app
if (config.useGoogleAnalytics && !mainThreadAddons.includes('AnalyticsByGoogle')) {
mainThreadAddons.push('AnalyticsByGoogle')
}
if ((
config.useServiceWorker === true ||
config.useServiceWorker === config.environment
) &&
!mainThreadAddons.includes('ServiceWorker')
) {
mainThreadAddons.push('ServiceWorker')
}
mainThreadAddons.forEach(addon => {
if (addon.startsWith('WS/')) {
imports.push(import(`../../../src/main/addon/${addon.substring(3)}.mjs`))
} else {
imports.push(import(`./main/addon/${addon}.mjs`))
}
});
modules = await Promise.all(imports);
me.addon = {};
modules.forEach(module => {
me.registerAddon(module.default)
});
WorkerManager.onWorkerConstructed({
origin: 'main'
})
}
/**
* @param {Object} data
*/
onMountDom(data) {
this.queueWrite(data);
WorkerManager.sendMessage(data.origin || 'app', {
action : 'reply',
replyId: data.id,
success: true
})
}
/**
* @param {Object} data
*/
onRender(data) {
data.data.replyId = data.replyId;
this.queueWrite(data.data)
}
/**
* @param {Object} data
*/
onUpdateDom(data) {
this.queueUpdate(data)
}
/**
* @param {Object} data
*/
onUpdateVdom(data) {
data.data.replyId = data.replyId;
this.queueUpdate(data.data)
}
/**
* @param {Object[]} queue
* @param {Date} start
* @returns {Number}
* @protected
*/
processQueue(queue, start) {
let me = this,
limit = me.timeLimit,
operation;
while (operation = queue.shift()) {
if (new Date() - start > limit) {
queue.unshift(operation);
return requestAnimationFrame(me.renderFrame.bind(me))
} else {
DomAccess[me.mode](operation);
WorkerManager.resolveDomOperationPromise(operation.replyId)
}
}
}
/**
* @param {Object} data
* @protected
*/
queueRead(data) {
let me = this;
me.readQueue.push(data);
if (!me.running) {
me.running = true;
requestAnimationFrame(me.renderFrame.bind(me))
}
}
/**
* @param {Object} data
* @protected
*/
queueUpdate(data) {
let me = this;
me.updateQueue.push(data);
if (!me.running) {
me.running = true;
requestAnimationFrame(me.renderFrame.bind(me))
}
}
/**
* @param data
* @protected
*/
queueWrite(data) {
let me = this;
me.writeQueue.push(data);
if (!me.running) {
me.running = true;
requestAnimationFrame(me.renderFrame.bind(me))
}
}
/**
* @param {Object} data
* @param {String} data.url
*/
redirectTo(data) {
window.location.href = data.url
}
/**
* Helper method to register main thread addons
* @param {Neo.core.Base} addon Can either be a neo class or instance
*/
registerAddon(addon) {
if (Neo.typeOf(addon) === 'NeoClass') {
// Addons could get imported multiple times. Ensure to only create an instance once.
if (Neo.typeOf(Neo.ns(addon.prototype.className)) !== 'NeoInstance') {
addon = Neo.create(addon)
}
// Main thread addons need to get registered as singletons inside the neo namespace
Neo.applyToGlobalNs(addon)
}
this.addon[addon.constructor.name] = addon
}
/**
* @param {Object} data
*/
reloadWindow(data) {
location.reload()
}
/**
* Triggers the different DOM operation queues
* @protected
*/
renderFrame() {
let me = this,
read = me.readQueue,
update = me.updateQueue,
write = me.writeQueue,
reading = me.mode === 'read',
start = new Date();
if (Neo.config.logDeltaUpdates) {
me.totalFrameCount++;
console.log('Total Frames: ' + me.totalFrameCount)
}
if (reading || !write.length) {
me.mode = 'read';
if (me.processQueue(read, start)) {
return
}
}
if (update.length) {
me.mode = 'update';
if (me.processQueue(update, start)) {
return
}
}
if (write.length) {
me.mode = 'write';
if (me.processQueue(write, start)) {
return
}
}
me.running = false
}
/**
* Change a Neo.config from the app worker
* @param {Object} data
* @param {String} data.key
* @param {*} data.value
*/
setNeoConfig(data) {
let {key, value} = data;
Neo.config[key] = data.value;
key === 'renderCountDeltas' && DomAccess.set({[key]: value})
}
/**
* Change the location.hash value
* @param {Object} data
* @param {String} data.value
*/
setRoute(data) {
window.location.hash = data.value
}
/**
* Closes popup windows
* @param {Object} data
* @param {String|String[]} data.names
*/
windowClose(data) {
if (!Array.isArray(data.names)) {
data.names = [data.names]
}
data.names.forEach(name => {
this.openWindows[name]?.close();
delete this.openWindows[name]
})
}
/**
* Closes all popup windows
* @param {Object} data
*/
windowCloseAll(data) {
Object.values(this.openWindows).forEach(value => {
console.log(value);
value.close()
});
this.openWindows = {}
}
/**
* Move a popup window
* @param {Object} data
* @param {String} data.windowName
* @param {String} data.x
* @param {String} data.y
*/
windowMoveTo(data) {
this.openWindows[data.windowName]?.moveTo(data.x, data.y)
}
/**
* Open a new popup window and return if successfull
* @param {Object} data
* @param {String} data.url
* @param {String} data.windowFeatures
* @param {String} data.windowName
* @return {Boolean}
*/
windowOpen(data) {
let openedWindow = window.open(data.url, data.windowName, data.windowFeatures),
success = !!openedWindow;
if (success) {
this.openWindows[data.windowName] = openedWindow
}
return success
}
/**
* Move a popup window
* @param {Object} data
* @param {Number} [data.height]
* @param {Number} [data.width]
* @param {String} data.windowName
*/
windowResizeTo(data) {
let win = this.openWindows[data.windowName],
height = data.height || win.outerHeight,
width = data.width || win.outerWidth;
win.resizeTo(width, height)
}
}
export default Neo.setupClass(Main);