-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgaia-navigator.js
665 lines (572 loc) · 20.1 KB
/
gaia-navigator.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
/* Host code. Prefix: gnh
* Host code is essentially private, none of these functions should be called
* outside of this script.
*/
// Whether the current transition is going backwards
var gnhBackwards = false;
// History tracking (TODO: Title tracking)
var gnhNavHistory = {
entries: [],
position: -1
};
var gnhOldFrame = null;
var gnhOldWindow = null;
var gnhOldHasTransitions = false;
var gnhNewFrame = null;
var gnhNewWindow = window;
var gnhNewHasTransitions = false;
var gnhTransitionToDuration = -1;
// If the url given is the same as the current url, this will modify the URL's
// query string slightly so that the iframe will load. Otherwise, loading the
// current URL in an iframe will not work.
function gnh_normaliseUrl(url) {
if (url === location.href) {
if (url.indexOf('?') === -1) {
url = url + '?gaia-navigator=1';
} else {
url = url + '&gaia-navigator=1';
}
}
return url;
}
// Initiate a navigation to a url string
function gnh_navigate(url, prepend) {
// TODO: Handle if a transition starts during another transition?
var newFrame = document.createElement('iframe');
newFrame.className = 'gaia-navigator-iframe';
newFrame.style.visibility = 'hidden';
newFrame.style.position = 'fixed';
newFrame.style.top = '0';
newFrame.style.left = '0';
newFrame.style.border = '0';
newFrame.style.width = '100%';
newFrame.style.height = '100%';
gnhOldFrame = gnhNewFrame ? gnhNewFrame : document.body;
gnhOldWindow = gnhNewWindow;
gnhOldHasTransitions = gnhNewHasTransitions;
prepend ?
document.body.insertBefore(newFrame, document.body.firstChild) :
document.body.appendChild(newFrame);
gnhNewFrame = newFrame;
gnhNewWindow = newFrame.contentWindow;
gnhNewHasTransitions = false;
newFrame.src = gnh_normaliseUrl(url);
}
// Start a transition
function gnh_transition() {
if (!gnhOldFrame) {
console.log('No frame to transition from');
return;
}
var name;
name = gnhBackwards ? 'enter' : 'exit';
gnhOldWindow.postMessage(
{ type: 'client-transition-from',
name: name,
backwards: gnhBackwards }, '*');
name = gnhBackwards ? 'exit' : 'enter';
gnhNewFrame.contentWindow.postMessage(
{ type: 'client-transition-to',
name: name,
backwards: gnhBackwards,
historyLength: gnhNavHistory.entries.length }, '*');
}
window.addEventListener('popstate',
function gnh_hostPopState(e) {
if (e.state && e.state.position === -1) {
// We've hit a user push/replace state, tell the client to fake a
// popstate event on the subframe
gnhNewWindow.postMessage({ type: 'client-popstate',
state: e.state.state }, '*');
return;
}
var delta = (e.state ? e.state.position : 0) - gnhNavHistory.position;
var newPosition = gnhNavHistory.position + delta;
if (!delta || newPosition < 0 ||
newPosition >= gnhNavHistory.entries.length) {
return;
}
gnhBackwards = newPosition < gnhNavHistory.position;
gnhNavHistory.position = newPosition;
gnh_navigate(gnhNavHistory.entries[newPosition].url, gnhBackwards);
});
window.addEventListener('message',
function gnh_hostMessageHandler(e) {
if (e.data.type.indexOf('host-') !== 0) {
return;
}
console.log('Host received message', e.data);
switch (e.data.type) {
case 'host-navigate':
gnhBackwards = false;
// Alter history
if (gnhNavHistory.position >= 0) {
gnhNavHistory.entries =
gnhNavHistory.entries.slice(0, gnhNavHistory.position + 1);
}
gnhNavHistory.entries.push({ title: '', url: e.data.url });
gnhNavHistory.position ++;
gnh_navigate(e.data.url, gnhBackwards);
history.pushState({ position: gnhNavHistory.position }, '', e.data.url);
break;
case 'host-go':
history.go(e.data.delta);
break;
case 'host-pushstate':
history.pushState(
{ position: -1, state: e.data.state }, e.data.title, e.data.url);
break;
case 'host-replacestate':
history.replaceState(
{ position: -1, state: e.data.state }, e.data.title, e.data.url);
break;
case 'host-loaded':
var iframes = document.getElementsByClassName('gaia-navigator-iframe');
if (gnhNavHistory.position === -1) {
var url = gnhNewWindow.location.href;
gnhNavHistory.entries.push({ title: e.data.title, url: url });
gnhNavHistory.position = 0;
} else {
gnhNavHistory.entries[gnhNavHistory.position].title = e.data.title;
}
document.title = e.data.title;
gnhNewHasTransitions = e.data.hasTransitions;
gnh_transition();
break;
case 'host-transition-to-start':
window.requestAnimationFrame(function() {
// Unhide the new frame now it's finished loading and the transition
// has started.
gnhNewFrame.style.visibility = 'visible';
gnhNewFrame.style.zIndex = e.data.zIndex;
// If the old frame doesn't have any transitions, we'll tell it to end
// when the new frame has finished its transition(s).
if (!gnhOldHasTransitions || gnhNewHasTransitions) {
window.setTimeout(function() {
if (!gnhOldHasTransitions) {
gnhOldWindow.postMessage({ type: 'client-transition-from-end',
name: e.data.name === 'exit' ?
'enter' : 'exit',
backwards: gnhBackwards }, '*');
}
if (gnhNewHasTransitions || !gnhOldHasTransitions) {
gnhNewWindow.postMessage({ type: 'client-transition-to-end',
name: e.data.name,
backwards: gnhBackwards }, '*');
}
}, e.data.duration);
}
});
break;
case 'host-transition-from-start':
if (gnhOldFrame !== document.body) {
gnhOldFrame.style.zIndex = e.data.zIndex;
} else if (e.data.zIndex !== 0) {
var child = document.body.firstElementChild;
while (child) {
if (child !== gnhNewFrame && child.style) {
child.style.zIndex = e.data.zIndex;
}
child = child.nextSibling;
}
}
window.requestAnimationFrame(function() {
if (!gnhNewHasTransitions || gnhOldHasTransitions) {
window.setTimeout(function() {
if (!gnhNewHasTransitions) {
gnhNewWindow.postMessage({ type: 'client-transition-to-end',
name: e.data.name === 'exit' ?
'enter' : 'exit',
backwards: gnhBackwards }, '*');
}
if (gnhOldHasTransitions || !gnhNewHasTransitions) {
gnhOldWindow.postMessage({ type: 'client-transition-from-end',
name: e.data.name,
backwards: gnhBackwards }, '*');
}
// We are now a dedicated host, so disconnect the client.
window.postMessage({ type: 'client-disconnect' }, '*');
}, e.data.duration);
}
});
break;
case 'host-transition-to-end':
gnhNewFrame.style.zIndex = '';
break;
case 'host-transition-from-end':
// Remove the old frame/contents from the document
while (document.body.childElementCount > 1) {
if (document.body.firstElementChild !== gnhNewFrame) {
document.body.removeChild(document.body.firstElementChild);
} else {
document.body.removeChild(document.body.children[1]);
}
}
break;
}
});
/* Client code. Prefix: gnc
* Only gnc_get* functions should be called outside of this script.
*/
// History length, as sent by the host which keeps track of history.
var gncHistoryLength = 1;
// Navigation transition style data. Contains arrays of objects of the
// format
// { type: 'enter' | 'exit',
// duration: <milliseconds>,
// zIndex: <integer> | null,
// style: <text>
// }
var gncNavTrans = [];
// Cached length of the string '@navigation-transition'
var gncRuleLength = '@navigation-transition'.length;
/**
* Parses all transition styles. Currently also rewrites anchor links to
* use the gaia-navigator location shim.
*/
window.addEventListener('load',
function gnc_onLoad() {
var i, iLen;
window.removeEventListener('load', gnc_onLoad);
// TODO: Don't do this, use a click handler to intercept?
console.log('Rewriting links');
var anchors = document.getElementsByTagName('a');
for (i = 0, iLen = anchors.length; i < iLen; i++) {
var a = anchors[i];
if (!a.href || !a.href.length || a.href[0] === '#' || a.onclick ||
a.download || a.target || a.href.indexOf('javascript:') === 0) {
continue;
}
a.addEventListener('click', function handleClick(url) {
return function(e) {
e.preventDefault();
window.parent.postMessage({ type: 'host-navigate', url: url }, '*');
}
}(a.href));
a.href = '';
}
console.log('Checking for navigation transition rules');
var extractNavTrans = function(css) {
// TODO: Respect media queries
// TODO: Don't do this character-by-character,
// could be much more efficient
var i, iLen, depth;
var navTran = { start: -1, blockStart: -1, properties: null };
for (i = depth = 0, iLen = css.length; i < iLen; i++) {
if (depth === 0 && css[i] === '@' &&
css.slice(i, i + gncRuleLength + 1).search(
/^@navigation-transition\b/) !== -1) {
navTran.start = i + gncRuleLength;
}
if (css[i] === '{') {
depth ++;
if (navTran.start !== -1 && navTran.blockStart === -1) {
navTran.blockStart = i + 1;
navTran.properties = css.slice(navTran.start, i - 1);
}
} else if (css[i] === '}') {
depth --;
if (depth === 0 && navTran.blockStart !== -1) {
// Write out the properties and rules to the global nav-trans array
var durationMatch = navTran.properties.match(/\b0?\.?\d*m?s\b/);
// TODO: Work out a better way of matching this.
var zIndexMatch = navTran.properties.match(/ -?\d /) ||
navTran.properties.match(/^-?\d /) ||
navTran.properties.match(/ -?\d$/);
var transition = {
type: (navTran.properties.search(/\bexit\b/) !== -1) ?
'exit' : 'enter',
duration: (durationMatch && durationMatch.length) ?
gnc_getDuration(durationMatch[0]) : 0,
zIndex: (zIndexMatch && zIndexMatch.length) ?
parseInt(zIndexMatch[0]) : null,
style: css.slice(navTran.blockStart, i - 1)
};
gncNavTrans.push(transition);
// Reset
navTran.start = -1;
navTran.blockStart = -1;
}
}
}
};
var styles = document.getElementsByTagName('style');
for (i = 0, iLen = styles.length; i < iLen; i++) {
extractNavTrans(styles[i].textContent);
}
var nRequests = 0;
var extStyles = document.getElementsByTagName('link');
for (i = 0, iLen = extStyles.length; i < iLen; i++) {
var link = extStyles[i];
if (link.rel !== 'stylesheet' || !link.href || !link.href.length) {
continue;
}
console.log('Checking for @navigation-transition in external ' +
'stylesheet at ' + link.href);
nRequests ++;
var request = new XMLHttpRequest();
request.open('GET', link.href);
request.overrideMimeType('text/css');
request.onreadystatechange = function(elem) {
return function () {
extractNavTrans(this.responseText);
if (--nRequests === 0) {
window.parent.postMessage(
{ type: 'host-loaded',
title: document.title,
hasTransitions: gncNavTrans.length > 0 }, '*');
}
}
}(link);
request.send();
}
if (nRequests === 0) {
window.parent.postMessage(
{ type: 'host-loaded',
title: document.title,
hasTransitions: gncNavTrans.length > 0 }, '*');
}
});
/**
* Given some CSS duration text (e.g. '100ms', '1s'), and returns that time
* in milliseconds.
*/
function gnc_getDuration(timeText) {
if (!timeText) {
return 0;
}
var duration;
if (timeText.indexOf('ms') !== -1) {
duration = parseInt(timeText);
} else {
duration = Math.round(parseFloat(timeText) * 1000.0);
}
return isNaN(duration) ? 0 : duration;
}
/**
* Start a navigation transition. type is 'enter' or 'exit'.
* Returns an object of the format
* {
* longestDuration: <milliseconds>
* lastZIndex: <integer>
* }
*/
function gnc_transition(type, backwards, to) {
console.log('Running ' + type + ' transition');
var newStyles = [];
var longestDuration = 0;
var lastZIndex = 0;
for (var i = 0, iLen = gncNavTrans.length; i < iLen; i++) {
if (gncNavTrans[i].type !== type) {
continue;
}
var transition = gncNavTrans[i];
if (transition.duration > longestDuration) {
longestDuration = transition.duration;
}
if (transition.zIndex !== null) {
lastZIndex = transition.zIndex;
}
var style = document.createElement('style');
style.appendChild(document.createTextNode(transition.style));
newStyles.push(style);
}
for (i = 0, iLen = newStyles.length; i < iLen; i++) {
document.head.appendChild(newStyles[i]);
}
// Alter the CSS rules to reverse animations when backwards is true
if (backwards) {
console.log('Reversing animation direction of rules');
var nSheets = document.styleSheets.length;
for (var i = nSheets - 1; i >= nSheets - newStyles.length; i--) {
var styleSheet = document.styleSheets[i];
var length = styleSheet.cssRules.length;
for (var j = 0; j < length; j++) {
var rule = styleSheet.cssRules[j].style;
if (!rule) {
continue;
}
if (rule['animation-name'] !== '' ||
rule['animation-direction'] !== '') {
// Switch animation-direction
switch (rule['animation-direction']) {
default:
case 'normal':
rule['animation-direction'] = 'reverse';
break;
case 'reverse':
rule['animation-direction'] = 'normal';
break;
case 'alternate':
rule['animation-direction'] = 'alternate-reverse';
break;
case 'alternate-reverse':
rule['animation-direction'] = 'alternate';
break;
}
}
if (rule['animation-name'] !== '' ||
rule['animation-delay'] !== '') {
// Modify animation-delay
var animDuration = gnc_getDuration(rule['animation-duration']);
var animDelay = gnc_getDuration(rule['animation-delay']);
var newDelay =
Math.max(0, (longestDuration - animDuration) - animDelay);
rule['animation-delay'] = newDelay + 'ms';
}
}
}
}
// Fire transition-start signal
window.dispatchEvent(new CustomEvent('navigation-transition-start',
{ detail: { back: backwards }}));
window.requestAnimationFrame(
function () {
window.setTimeout(function () {
if (to) {
// Remove transition styles
for (i = 0, iLen = newStyles.length; i < iLen; i++) {
document.head.removeChild(newStyles[i]);
}
}
}, longestDuration);
});
return { longestDuration: longestDuration,
lastZIndex: lastZIndex };
}
/**
* Retrieve a shim location object.
*/
function gnc_getLocation() {
var fakeLocation = {};
for (property in location) {
switch (property) {
case 'assign':
fakeLocation[property] = function(uri) {
if (!uri.length) {
return;
}
var url = new URL(location);
try {
url = new URL(uri);
} catch(e) {
url = new URL(location);
url.pathname =
location.pathname.
slice(0, location.pathname.lastIndexOf('/') + 1) + uri;
url.search = '';
}
if (url.origin !== location.origin ||
url.pathname !== location.pathname ||
url.port !== location.port) {
window.parent.postMessage({ type: 'host-navigate',
url: decodeURIComponent(url.href) },
'*');
return;
}
location.assign(uri);
};
break;
case 'href':
Object.defineProperty(fakeLocation, property, {
enumerable: true,
get: function() { return location.href; },
set: function(uri) { this.assign(uri); }
});
break;
default:
fakeLocation[property] = location[property];
}
}
return fakeLocation;
}
/**
* Retrieve a shim history object.
*/
function gnc_getHistory() {
var fakeHistory = {};
for (property in history) {
switch (property) {
case 'length':
Object.defineProperty(fakeHistory, property, {
enumerable: true,
get: function() { return gncHistoryLength; }
});
break;
case 'go':
fakeHistory[property] = function(delta) {
if (!delta || delta === 0) {
gnc_getLocation().reload();
return;
}
window.parent.postMessage({ type: 'host-go', delta: delta }, '*');
};
break;
case 'back':
fakeHistory[property] = function() {
window.parent.postMessage({ type: 'host-go', delta: -1 }, '*');
};
break;
case 'forward':
fakeHistory[property] = function() {
window.parent.postMessage({ type: 'host-go', delta: 1 }, '*');
};
break;
case 'pushState':
fakeHistory[property] = function(state, title, url) {
window.parent.postMessage({ type: 'host-pushstate',
state: state,
title: title,
url: url }, '*');
};
break;
case 'replaceState':
fakeHistory[property] = function(state, title, url) {
window.parent.postMessage({ type: 'host-replacestate',
state: state,
title: title,
url: url }, '*');
};
break;
default:
fakeHistory[property] = history[property];
}
}
return fakeHistory;
}
window.addEventListener('message',
function gnc_handleMessage(e) {
if (e.data.type.indexOf('client-') !== 0) {
return;
}
console.log('Client received message', e.data);
var to = false;
switch (e.data.type) {
case 'client-transition-to':
to = true;
gncHistoryLength = e.data.historyLength;
case 'client-transition-from':
var properties = gnc_transition(e.data.name, e.data.backwards, to);
window.parent.postMessage({ type: to ? 'host-transition-to-start' :
'host-transition-from-start',
name: e.data.name,
duration: properties.longestDuration,
zIndex: properties.lastZIndex }, '*');
break;
case 'client-transition-to-end':
to = true;
case 'client-transition-from-end':
window.dispatchEvent(new CustomEvent('navigation-transition-end',
{ detail: { back: e.data.backwards }}));
window.parent.postMessage({ type: to ? 'host-transition-to-end' :
'host-transition-from-end' }, '*');
break;
case 'client-disconnect':
window.removeEventListener('message', gnc_handleMessage);
break;
case 'client-popstate':
window.dispatchEvent(
new PopStateEvent('popstate', { state: e.data.state }));
break;
}
});