forked from crosswalk-project/crosswalk-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xwalk.js
executable file
·1674 lines (1417 loc) · 56.9 KB
/
xwalk.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
"use strict";
function replace_version_string (str) {
var re, version;
Object.getOwnPropertyNames (versions).forEach (function (channel) {
Object.getOwnPropertyNames (versions[channel]).forEach (function (platform) {
Object.getOwnPropertyNames (versions[channel][platform]).forEach (
function (arch) {
version = versions[channel][platform][arch];
/* Replace ${XWALK-channel-platform-arch} with the version
* number, unless prefixed by ! */
re = new RegExp ('([^!])\\$({|%7b)XWALK-'+channel+'-'+
platform+'-'+arch+'(}|%7d)', 'mig');
str = str.replace (re, '$1' + version);
/* If !${XWALK-channel-platform-arch} is present, strip
* the leading ! and leave just the variable reference */
re = new RegExp ('!(\\$({|%7b)XWALK-'+channel+'-'+
platform+'-'+arch+'(}|%7d))', 'mig');
str = str.replace (re, '$1');
/* Replace ${XWALK-channel-platform-arch-MAJOR}
* with the first number from the version string
* unless prefixed with ! */
var major = version.replace (/^([^.]+)\..*/, '$1');
re = new RegExp ('([^!])\\$({|%7b)XWALK-'+channel+'-'+
platform+'-'+arch+'-MAJOR(}|%7d)', 'mig');
str = str.replace (re, '$1' + major);
/* If !${XWALK-channel-platform-arch-MAJOR} is present, strip
* the leading ! and leave just the variable reference */
re = new RegExp ('!(\\$({|%7b)XWALK-'+channel+'-'+
platform+'-'+arch+'-MAJOR(}|%7d))', 'mig');
str = str.replace (re, '$1');
});
});
});
return str;
}
(function () {
var context = this,
home, page, footer,
viewHeight = 0,
top_menu, column, column_name, xhr = null,
slider, active_uri = '', active_page = '',
active_target = '', sub_link = '',
anchor_scroll_timer = 0, samples_background = null, samples_table = null,
requested_column, requested_page, requested_anchor,
subMenuCloseOnClick = false;
var debug = {
navigation: false,
history: false,
scroll: false
};
// from https://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
var globalEval = function (src) {
// on IE
if (window.execScript) {
window.execScript (src);
return;
}
var fn = function () {
window.eval.call (window, src);
};
fn();
};
window.requestAnimationFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
/*
* popstate is fired when the URL is manually entered with
* an anchor target as well as if the user navigates through
* the history.
*
* If a state is provided with an href, use that to load
* the appropriate page state, otherwise load from the
* window.location.href (if it contains a target)
*/
function onPopState (e) {
var href;
if (debug.history) {
console.log ('popstate: ' + JSON.stringify(e.state));
}
sub_link = '';
if (!e.state || !e.state.href) {
href = window.location.href.replace(/^.*#/, '#').toLowerCase ();
if (!href.match (/^#/)) {
href = '';
}
var columnSelector = '.column[id^="'+
href.replace (/^#([^\/]*).*$/, '$1')+'"]';
var column = document.querySelector (columnSelector);
if (debug.navigation) {
console.log('trying to match column selector: ' + columnSelector);
console.log('column found? ' + (column ? 'yes' : 'no'));
}
if (column) {
navigateTo (href);
} else {
activateColumn ('home');
if (href != '') {
scrollTo (href.replace (/^#/, ''));
}
}
} else {
navigateTo (e.state.href);
}
}
var hide_delay_timeout = 0;
/*
* Hide all columns, and show the one selected
*/
function activateColumn (name) {
var tmp = document.getElementById (name + '-column'), item;
if (!tmp) {
console.warn ('Request to activate non-existent column: ' + name);
return;
}
column = tmp;
column_name = name;
var menuButton = document.querySelector ('.sub-menu-button-container');
if (column.id == 'home-column') {
if (hide_delay_timeout) {
window.clearTimeout (hide_delay_timeout);
} else {
top_menu.classList.add ('hide-delay');
}
hide_delay_timeout = window.setTimeout (function () {
top_menu.classList.remove ('hide-delay');
hide_delay_timeout = 0;
}, 1000);
page.style.removeProperty ('padding-top');
page.style.removeProperty ('paddingTop');
// hide the menu button always
menuButton.setAttribute ('data-hide', 'true');
} else {
if (hide_delay_timeout) {
window.clearTimeout (hide_delay_timeout);
hide_delay_timeout = 0;
top_menu.classList.remove ('hide-delay');
}
page.style['padding-top'] = top_menu.offsetHeight + 'px';
// why, firefox, why?
page.style.paddingTop = top_menu.offsetHeight + 'px';
// show the menu button if width is small enough
menuButton.setAttribute ('data-hide', 'false');
}
if (name != 'home') {
top_menu.style.removeProperty ('opacity');
top_menu.style.top = '0px';
}
/* Only activate if this column isn't already active... */
if (!column.classList.contains ('hidden')) {
return;
}
if (debug.scroll) {
console.log ('Hard scroll to top.');
}
window.scrollTo (0, 0);
Array.prototype.forEach.call (top_menu.querySelectorAll ('#top-menu .active'),
function (el) {
el.classList.remove ('active');
});
item = top_menu.querySelector ('a[href^="#' + column_name + '"]');
item.classList.add ('active');
Array.prototype.forEach.call (
document.querySelectorAll ('.column:not(.hidden)'), function (el) {
page.removeChild (el);
el.classList.add ('hidden');
document.body.appendChild (el);
});
page.appendChild (column);
column.classList.remove ('hidden');
column.style.left = '0px';
column.style.top = top_menu.offsetHeight + 'px';
_onResize ();
}
var pending = 0;
function loadingGraphicStart () {
var indicator = null;
if (pending++ != 0)
return;
/* IF there is a sub-menu displayed then see if the wiki column
* is active. If it is, determine the wiki sub-page requested.
* If not a specific wiki topic (home, history, or pages), then activate
* the 'pages'.
*
* If not in the wiki column then search for any anchor that matches
* the requested page. */
var sub_menu = column.querySelector ('.sub-menu');
if (sub_menu) {
if (column_name == 'wiki') {
if (active_target.match (/^#wiki(\/home)?$/)) {
indicator = sub_menu.querySelector ('#page a[href="#wiki/home"]');
} else if (active_target.match (/^#wiki\/history$/)) {
indicator = sub_menu.querySelector ('#page a[href="#wiki/history"]');
} else {
indicator = sub_menu.querySelector ('#page a[href="#wiki/pages"]');
}
indicator.classList.add ('loading');
}
if (indicator == null) {
/* Add the loading class to all menu anchors that directly reference this exact target */
Array.prototype.forEach.call (
sub_menu.querySelectorAll ('#page a[href="' + active_target + '"]'),
function (el) {
if (debug.navigation) {
console.log ('adding loading mask to: ' + el.getAttribute ('href'));
}
el.classList.add ('loading');
indicator = el;
}
);
}
}
/* If no on-page indicators are showing the loading indicator, then add
* the indicator to the top-menu item that will host the active_target */
if (indicator == null) {
Array.prototype.forEach.call (
document.querySelectorAll (
'#top-menu a[href^="' +
active_target.replace(/^(#[^\/]*).*$/, '$1') + '"]'),
function (el) {
el.classList.add ('loading');
});
}
}
function loadingGraphicStop () {
if (!pending)
return;
pending--;
Array.prototype.forEach.call (
document.querySelectorAll ('.loading'), function (el) {
el.classList.remove ('loading');
});
}
function generate_wiki_page (page, contents) {
var content = document.createElement ('div'),
wiki_body = document.createElement ('div'),
div = document.createElement ('div');
div.innerHTML = contents;
content = div.querySelector ('#wiki-content');
if (!content) {
content = document.createElement ('div');
content.id = 'wiki-content';
var new_wiki_body = document.createElement ('div');
new_wiki_body.id = 'wiki-body';
div.classList.add ('markdown-body');
new_wiki_body.appendChild (div);
content.appendChild (new_wiki_body);
} else {
var last_edit, title = null;
wiki_body = div.querySelector ('#wiki-body .markdown-body');
if (!wiki_body) {
/* Graaarck! No Wiki content returned... */
wiki_body = document.createElement ('div');
wiki_body.innerText = 'Site down';
}
/* If title found in header, move it into the body as an H1
* BUT only if this isn't Home, which is special cased to always
* pull the title from the page content */
if (column_name != 'wiki' || !page.match (/home/i)) {
title = div.querySelector ('#head h1:first-child');
if (title) {
/* Strip any path prefix from the title */
title.innerHTML = title.innerHTML.replace (
/^.*\/([^\/]*)$/, '$1');
wiki_body.insertBefore (title, wiki_body.firstChild);
}
}
/* Inject title in header if not found */
if (!title)
title = wiki_body.querySelector ('h1:first-child');
if (!title) {
/* If there isn't an H1 title, check for an H2 and convert
* to an H2 if found */
title = wiki_body.querySelector ('h2:first-child');
if (title) {
var h1 = document.createElement ('h1');
while (title.firstChild) {
h1.appendChild (title.firstChild);
}
wiki_body.removeChild (title);
title = h1;
wiki_body.insertBefore (title, wiki_body.firstChild);
}
}
/* If wiki entry does not start with a header, add a title */
if (title == null) {
title = document.createElement ('h1');
title.textContent = div.querySelector ('h1.gh-header-title').textContent;
wiki_body.insertBefore (title, wiki_body.firstChild);
}
/* Inject Last Edit in footer */
last_edit = div.querySelector ('.gh-header-meta');
if (last_edit && column_name == 'wiki') {
/* If the only edit was the initial import from 2013-09-01 21:04:08, don't show it.. */
if (last_edit.textContent.search (/2013-09-01 21:04:08/) != -1) {
last_edit.textContent = '';
}
// fix the author link URL
var author_link = last_edit.querySelector('.author');
if (author_link) {
author_link.target = '_blank';
var author_name = author_link.getAttribute('href');
if (author_name) {
var real_link = 'https://github.com' + author_name;
author_link.href = real_link;
}
}
var github_link_wrapper = document.createElement('span');
github_link_wrapper.setAttribute('class', 'github-meta-link');
var github_link = document.createElement ('a');
/* GitHub URL syntax for starting the editing; GitHub flattens
* the wiki structure, so no path structure (vs. Gollum which
* does support a directory structure) */
github_link.href =
'http://github.com/crosswalk-project/crosswalk-website/wiki/' + requested_page;
github_link.textContent = 'source';
github_link.target = '_blank';
github_link.className = '';
// fix the history link URL
var history_link = last_edit.querySelector('.history');
if (history_link) {
real_link = github_link.href + '/_history';
history_link.href = real_link;
history_link.target = '_blank';
}
// add to the content
github_link_wrapper.appendChild(github_link);
last_edit.appendChild (github_link_wrapper);
content.appendChild (last_edit);
}
// remove the elements we don't want on the page
// to fix https://crosswalk-project.org/jira/browse/XWALK-1612
var right_bar = content.querySelector('#wiki-rightbar');
if (right_bar) {
right_bar.parentNode.removeChild(right_bar);
}
}
/* If the content contains the 'missing' class then the Wiki
* request hit a 404 */
if (content.querySelector ('.missing')) {
var referring_page = column.hasAttribute ('referring_page') ?
column.getAttribute ('referring_page') : 'Internal link',
tmp = document.createElement ('div');
tmp.innerHTML = '<h1>Missing Page</h1>' +
'Referring page: ' +
'<a href="#' + column_name + '/' + referring_page + '">' +
'#' + column_name + '/' + referring_page + '</a><br>';
wiki_body.insertBefore (tmp, wiki_body.firstChild);
}
return content;
}
function generate_history_page (page, contents) {
var content = document.createElement ('div'),
wiki_body = document.createElement ('div'),
div = document.createElement ('div');
content.id = 'wiki-content';
wiki_body.id = 'wiki-body';
div.classList.add ('markdown-body');
wiki_body.appendChild (div);
content.appendChild (wiki_body);
try {
var html, events, spans, i, j, time,
date = new Date (),
now = Date.now ();
now += (60 * 60 * 24 * 1000) - now % (60 * 60 * 24 * 1000); // Set to 12:00am tonight
events = JSON.parse (contents);
html = '<h1>Crosswalk Wiki History</h1>';
spans = new Array (
{ /* days */
length: 60 * 60 * 24 * 1000, /* 60s * 60m * 24h = 1 day */
start: now,
end: now - (60 * 60 * 24) * date.getDay () * 1000,
names: null
}, { /* weeks */
length: 60 * 60 * 24 * 7 * 1000, /* 60s * 60m * 24h * 7d = 1 week */
start: now - (60 * 60 * 24) * date.getDay () * 1000,
end: now - (60 * 60 * 24 * 7) * 4 * 1000,
names: new Array ('Last week', ' weeks ago')
}, { /* months */
length: 60 * 60 * 24 * 7 * 4 * 1000, /* 60s * 60m * 24h * 7d * 4w = ~1 month */
start: now - (60 * 60 * 24 ) * date.getDate () * 1000,
end: now - (60 * 60 * 24 * 7 * 4 * 12) * 1000,
names: new Array ('Last month', ' months ago')
}
);
j = 0;
var tracked = [];
spans.forEach (function (span) {
var period = null, period_index = 0, last_period_index = 0, k, e;
while (j < events.length) {
e = events[j];
e.date = parseInt (e.date) * 1000;
/* Events are delivered chronologically, with future events
* (due to timezone) being processed by the first span "Today"
*
* If this events happened farther back in time than this span
* handles exit the while () loop to process the event under
* the next span */
if (e.date <= span.end) {
break;
}
period_index = Math.max (
0, Math.floor ((span.start - e.date) / span.length));
/* Check if this particular file is already listed as being
* edited, and if so, so skip it... */
for (k = 0; k < tracked.length; k++) {
if (e.file == tracked[k])
break;
}
if (k != tracked.length) {
j++;
continue;
}
if (period == null || period_index != last_period_index) {
if (period != null)
html += '</ul>';
if (span.names) {
if (period_index >= span.names.length - 1) {
period = '' + (period_index + 1) +
span.names[span.names.length - 1];
} else {
period = span.names[period_index];
}
} else {
period = new Date(e.date).toDateString ();
}
html += '<h3>' + period + '</h3>';
html += '<ul class="history-list">';
last_period_index = period_index;
}
html += '<li><a href="' + e.file + '">' + e.name + '</a> ';
if (e.end_sha != '') {
html += '<a target="_blank" href="' +
'https://github.com/crosswalk-project/' +
'crosswalk-website/' + e.file +
'/_compare/' + e.end_sha + '..' + e.start_sha +
'"">View changes on GitHub</a>';
} else {
html += '<span>New page</span>';
}
html += '</li>';
tracked.push (e.file);
j++;
}
if (period != null) {
html += '</ul>';
}
});
div.innerHTML = html;
} catch (e) {
console.error(e);
div.textContent = 'Error parsing Wiki History';
}
return content;
}
function content_response (e) {
if (xhr.readyState != XMLHttpRequest.DONE) {
if (debug.navigation) {
console.log (xhr.status);
}
return;
}
loadingGraphicStop ();
/* Replace the currently visible content with the newly received
* content */
activateColumn (column_name);
if (xhr.status != 200) {
var tmp = '<div id="wiki-content"><div id="wiki-body">' +
'<div class="markdown-body">' +
'<h1>Unable to fetch page</h1>' +
'<p><strong>Reason:</strong> <span class="error">' +
xhr.status + ' ' + xhr.statusText + '</span></p>' +
'<p><strong>Response body:</strong></p><p>' + xhr.responseText + '</p>';
if (column.hasAttribute ('referring_page')) {
var referring_page = column.getAttribute ('referring_page');
tmp += '<br>' +
'Referring page: ' +
'<a href="#' + column_name + '/' + referring_page + '">' +
'#' + column_name + '/' + referring_page + '</a><br>';
}
tmp += '</div></div>',
column.querySelector ('.sub-content').innerHTML = tmp;
xhr = null;
return;
}
xhr = null;
/* This is Wiki content generated from Gollum, which means its a full
* HTML page. Load it into a context free div element and then extract
* the node we care about.
* Then insert that node into the current column's sub-content */
var content, href,
sub_page = column.hasAttribute ('loading_page') ?
column.getAttribute ('loading_page') : 'Home';
var response = e.currentTarget.response ?
e.currentTarget.response :
e.currentTarget.responseText;
response = replace_version_string (response);
/* The Wiki History is a dynamically generated JSON list of page edits
* clustered chronologically. However the content on the server may not
* be updated every day, which would result in stale time indicators.
*
* So, the server returns the collected/clustered JSON data, and the
* client then post-filteres it into "current" time periods for display
* to the user.
*/
if (column_name == 'wiki' && sub_page == 'history') {
content = generate_history_page (sub_page, response);
} else {
content = generate_wiki_page (sub_page, response);
}
var div = column.querySelector ('.sub-content');
/* If this was a delayed load, it may have finished after a switch
* to the #home column, in which case there is no sub-content field */
if (!div) {
return;
}
while (div.firstChild)
div.removeChild (div.firstChild);
// pull all the script tags out of the content first
var scriptContents = [];
var scripts = content.getElementsByTagName ('script');
var script;
for (var i = 0; i < scripts.length; i += 1) {
script = scripts[i];
scriptContents.push (script.text);
script.parentNode.removeChild (script);
}
// append the remaining content
div.appendChild (content);
// append a new script element for each script text retrieved
// from the content, and execute in global context
while (scriptContents.length) {
globalEval (scriptContents.shift ());
}
/*
* Wiki link rewriting magic...
*
* 1) Pass ONE
* the Gollum system returns links
* relative to the paths inside of GitHub and Gollum. Some of
* those links have been hand code by Wiki editors.
*
* Our task is to find those URLs and rewrite them to be relative
* to this #wiki system.
*/
var c;
column.removeAttribute ('loading_page');
column.setAttribute ('active_page', sub_page);
Array.prototype.forEach.call (
content.querySelectorAll ('a:not([href^="http"])'), function (link) {
if (!link.hasAttribute ('href'))
return;
href = link.getAttribute ('href');
/* Discard if href contains a protocol:// prefix (for example irc://) */
if (href.match (/^.*:\/\//))
return;
/* Link types people are using in the Wiki is documented at:
*
* https://crosswalk-project.org/#wiki/wiki-link-samples
*/
/* If the URL starts with #, then check if it is a valid column request.
*
* GitHub reformats '#documentation/.*' to '#wiki-documentation/.*'
* We remove the 'wiki-' portion. Some URLs may make it through as
* '#documentation/.*', so we also check for that (and do nothing if
* it matches a column name)
*
* If neither of the above is true, assume it is a local anchor to
* the current page (eg., a header tag in a wiki page)
*/
if (href.match (/^#/)) {
/* If the URL starts with #wiki-{COLUMN} or #{COLUMN}
* then use it (stripping "wiki-" if it was there) */
c = href.replace(/^#(wiki-)?([^\/]*).*$/, '$2');
if (document.querySelector ('.column[id="'+c+'-column"]')) {
link.href = href.replace(/^#wiki-/, '#');
} else {
/* Local anchor to current page */
link.href = '#' + column_name + '/' + sub_page + '/' +
href.replace (/#/, '');
}
} else {
/* The wiki pages on crosswalk-project expect the #wiki/ column prefix.
*
* GitHub:
* Sometimes provides a wiki/ prefix to URLs.
* Sometimes it prefixes pages with 'crosswalk-project/crosswalk-wiki/wiki'
*
* The following corrects for the above, and also converts any
* local anchor references into a path separator (xwalk.js will
* convert the last directory element back into an anchor reference
* in subMenuClick) */
link.href = '#wiki/' + href.replace (/^\/crosswalk-project\/crosswalk-website\/wiki\//, '').
replace (/#/, '/').
replace (/^wiki\//, '');
}
link.addEventListener ('click', subMenuClick);
});
/*
* 2) Pass TWO
* Rewrite IMG src links to be relative to wiki/ instead
* of relative to / (only for wiki content)
*
*/
if (column_name == 'wiki') {
Array.prototype.forEach.call (
content.querySelectorAll ('img:not([src^="http"])'), function (img) {
var src = img.getAttribute ('src');
if (src.match (/^assets/))
src = 'wiki/' + src;
img.src = src;
});
}
/* For all external links, intercept the click and log the event with
* GA prior to invoking the request... */
var links = content.querySelectorAll ('a[href^="http"]');
Array.prototype.forEach.call (links, function (link) {
link.addEventListener ('click', trackAbandonLink);
});
if (column.hasAttribute ('requested_anchor')) {
if (anchor_scroll_timer)
window.clearTimeout (anchor_scroll_timer);
anchor_scroll_timer = window.setTimeout (function () {
scrollTo (column.getAttribute ('requested_anchor'));
}, 250);
} else {
scrollTo (page);
}
_onResize ();
}
function addEventOffset (e) {
if ('offsetX' in e)
return;
var el, ofsX = e.clientX, ofsY = e.clientY;
el = e.currentTarget;
while (el) {
ofsX -= el.offsetLeft;
ofsY -= el.offsetTop;
el = el.offsetParent;
}
e.offsetX = ofsX;
e.offsetY = ofsY;
}
(function (namespace) {
namespace.attachScrollbar = function (scrollable) {
var scroll_bar = scrollable.querySelector ('.scrollbar');
if (scroll_bar) {
calculateScrollbar (scrollable);
return scroll_bar;
}
scroll_bar = document.createElement ('div');
scroll_bar.insertBefore (document.createElement ('div'), null);
scroll_bar.firstChild.classList.add ('scrollbar-thumb');
scroll_bar.classList.add ('scrollbar');
scrollable.appendChild (scroll_bar);
scroll_bar.addEventListener ('click', scrollbarClick, true);
scroll_bar.addEventListener ('mousedown', scrollbarMouseDown, true);
scroll_bar.addEventListener ('selectstart', scrollbarSelectStart, true);
scrollable.addEventListener ('wheel', scrollableWheel, true);
scrollable.addEventListener ('mousewheel', scrollableWheel, true);
scrollable.addEventListener ('touchmove', scrollableTouchMove, true);
scrollable.addEventListener ('touchstart', scrollableTouchStart, true);
scrollable.firstChild.classList.add ('scrollable');
calculateScrollbar (scrollable);
return scroll_bar;
}
namespace.detachScrollbar = function (scrollable) {
var scroll_bar = scrollable.querySelector ('.scrollbar');
if (!scroll_bar)
return;
scroll_bar.removeEventListener ('click', scrollbarClick);
scroll_bar.removeEventListener ('mousedown', scrollbarMouseDown);
scroll_bar.removeEventListener ('selectstart', scrollbarSelectStart);
scrollable.removeEventListener ('wheel', scrollableWheel);
scrollable.removeEventListener ('mousewheel', scrollableWheel);
scrollable.removeEventListener ('touchmove', scrollableTouchMove);
scrollable.removeEventListener ('touchstart', scrollableTouchStart);
scrollable.firstChild.classList.remove ('scrollable');
scroll_bar.parentElement.removeChild (scroll_bar);
}
/* Scrollbar Event Handlers */
var mouseElement = null;
function scrollableWheel (e) {
if (!this.firstChild.classList.contains ('scrollable'))
return;
var y = ((e.wheelDeltaY || -e.deltaY) < 0) ? -1 : +1;
scrollTo (this, this.firstChild.offsetTop + (y * this.offsetHeight * 0.2));
e.preventDefault ();
e.stopPropagation ();
e.stopImmediatePropagation ();
e.cancelBubble = true;
return false;
}
function scrollbarClick (e) {
e.preventDefault ();
}
var start_pos = 0;
function scrollbarMouseMove (e) {
if (mouseElement) {
var perc, el = mouseElement,
scrollable = el.parentElement,
scroll = window.scrollY || window.pageYOffset, y;
y = e.pageY - scroll - start_pos;
/* Determine mouse Y position relative to the scrollable
* area */
do {
y -= el.offsetTop;
el = el.offsetParent;
} while (el);
perc = y / (scrollable.querySelector ('.scrollbar').offsetHeight -
scrollable.querySelector ('.scrollbar .scrollbar-thumb').offsetHeight);
y = scrollable.offsetHeight - scrollable.firstChild.offsetHeight;
y *= perc;
scrollTo (scrollable, y);
}
}
function scrollbarMouseDown (e) {
mouseElement = this;
window.addEventListener ('mousemove', scrollbarMouseMove, false);
window.addEventListener ('mouseup', scrollbarMouseUp, false);
var y, scrollable = this.parentElement;
addEventOffset (e);
var thumb = this.querySelector ('.scrollbar-thumb');
y = e.offsetY + this.offsetTop;
if (y < thumb.offsetTop || y > thumb.offsetTop + thumb.offsetHeight) {
var perc;
perc = y / this.offsetHeight;
y = scrollable.offsetHeight - scrollable.firstChild.offsetHeight;
y *= perc;
scrollTo (scrollable, y);
}
start_pos = e.offsetY - thumb.offsetTop;
e.preventDefault ();
e.stopPropagation ();
e.stopImmediatePropagation ();
e.cancelBubble = true;
return false;
}
function scrollbarMouseUp (e) {
window.removeEventListener ('mousemove', scrollbarMouseMove);
window.removeEventListener ('mouseup', scrollbarMouseUp);
mouseElement = null;
e.preventDefault ();
}
function scrollbarSelectStart (e) {
e.preventDefault ();
e.stopImmediatePropagation ();
e.stopPropagation ();
e.cancelBubble = true;
return false;
}
var touchY = 0;
function calculateScrollbar (scrollable) {
var perc, y, d, scroll_bar, h, scroll_bar_thumb;
d = scrollable.firstChild.offsetHeight - scrollable.offsetHeight;
if (d <= 0)
return;
y = -scrollable.firstChild.offsetTop;
scroll_bar_thumb = scrollable.querySelector ('.scrollbar').firstChild;
h = scrollable.offsetHeight *
scrollable.offsetHeight / scrollable.firstChild.offsetHeight;
y = (scrollable.offsetHeight - scroll_bar_thumb.offsetHeight) * y / d;
scroll_bar_thumb.style.height = h + 'px';
scroll_bar_thumb.style.top = y + 'px';
}
function scrollTo (scrollable, y) {
if (y > 0)
y = 0;
else if (y < scrollable.offsetHeight - scrollable.firstChild.offsetHeight)
y = scrollable.offsetHeight - scrollable.firstChild.offsetHeight;
scrollable.firstChild.style.top = y + 'px';
calculateScrollbar (scrollable);
}
function scrollableTouchMove (e) {
e.preventDefault ();
if (e.touches.length) {
scrollTo (this, this.firstChild.offsetTop + (e.touches[0].pageY - touchY));
touchY = e.touches[0].pageY;
}
}
function scrollableTouchStart (e) {
if (e.touches.length)
touchY = e.touches[0].pageY;
}
}) (window);
function subMenuResize () {
var scroll = window.scrollY || window.pageYOffset;
var sub_menu = column.querySelector ('.sub-menu'), scroll_bar;
if (!sub_menu) {
return;
}
/* Size of the sub_menu is the distance from the bottom of the top_menu
* to the top of the footer, which may be scrolled up */
var y = Math.min (footer.offsetTop - scroll, viewHeight) -
top_menu.offsetHeight;
/* Size the sub-menu container to the maximum sized amount */
sub_menu.parentElement.style.height = y + 'px';
/* If the container is smaller than the sub-menu, attach a scrollbar
* to the sub-menu */
if (sub_menu.offsetHeight > sub_menu.parentElement.clientHeight) {
var scroll_bar = attachScrollbar (sub_menu.parentElement), margin;
margin = Math.ceil (parseFloat (
window.getComputedStyle (scroll_bar).marginLeft) * 2);
scroll_bar.style.left = sub_menu.offsetWidth -
scroll_bar.offsetWidth - margin + 'px';
} else {
detachScrollbar (sub_menu.parentElement);
}
}
function subMenuClick (e) {
var href = this.getAttribute ('href'), open;
e.preventDefault ();
/* If the item being clicked is an item of a sub-menu, or
* the parent of a sub-menu, then toggle the visibility
* of the sub-menu */
if (this.nextSibling && this.nextSibling.classList &&
this.nextSibling.classList.contains ('menu-sub-pages')) {
addEventOffset (e);
if (e.offsetX >= this.offsetWidth - this.offsetHeight)
this.nextSibling.classList.toggle ('off');
else
this.nextSibling.classList.remove ('off');
if (this.nextSibling.classList.contains ('off')) {
open = false;
this.classList.add ('menu-closed');
this.classList.remove ('menu-open');
} else {
open = true;
this.classList.add ('menu-open');
this.classList.remove ('menu-closed');
}
subMenuResize ();
/* If this click is in the open/close button region, return now */
if (e.offsetX >= this.offsetWidth - this.offsetHeight)
return;
/* If the current page is not child of this page, then don't change focus
* to the item if the item is now closed (just return) */
if (!open) {