-
Notifications
You must be signed in to change notification settings - Fork 814
/
Copy pathcontent.js
2264 lines (2098 loc) · 178 KB
/
content.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
loadJQuery();
addPrototypeMethods();
// --- Get infos about this script file ---
var scriptElement = document.querySelector('script[src$="static/content.js"]');
var scriptDir = scriptElement.src.substr(0, scriptElement.src.lastIndexOf('/'));
// --- User data ---
var user = {
fontSize: 1.0,
clickTab: 0,
displaySidebar: true,
colorTheme: 0
}
// --- Cached data ---
// To have the data remain while navigating through the docs, it'll be stored into
// window.name. This is done because CHM doesn't support
// window.localStorage/sessionStorage or cookies.
var cache = {
colorTheme: user.colorTheme,
scriptDir: scriptDir,
fontSize: user.fontSize,
forceNoFrame: false,
forceNoScript: false,
clickTab: user.clickTab,
displaySidebar: user.displaySidebar,
sidebarWidth: '18em',
RightIsFocused: true,
toc_clickItem: 0,
toc_scrollPos: 0,
index_filter:-1,
index_input: "",
index_clickItem: 0,
index_scrollPos: 0,
search_data: {},
search_highlightWords: false,
search_input: "",
search_clickItem: 0,
search_scrollPos: 0,
load: function() {
try {
var data = JSON.parse(window.name);
} catch(e) {
return false;
}
if (data.scriptDir != scriptDir)
return false;
$.extend(this, data);
return true;
},
save: function() {
window.name = JSON.stringify(this);
},
set: function(prop, value) {
this[prop] = value;
try {
postMessageToFrame('updateCache', [prop, value])
} catch(e) {}
return value;
}
};
// --- Main Execute Area ---
// Set global variables:
var forceNoScript = forceNoScript || false;
var isCacheLoaded = cache.load();
var workingDir = getWorkingDir();
var relPath = location.href.replace(workingDir, '');
var equivPath = $('meta[name|="ahk:equiv"]').prop('content');
var isInsideCHM = (location.href.search(/::/) > 0) ? 1 : 0;
var supportsHistory = (history.replaceState) && !isInsideCHM;
var isFrameCapable = !cache.forceNoFrame && (isInsideCHM || supportsHistory);
var isInsideFrame = (window.self !== window.top);
var isSearchBot = navigator.userAgent.match(/googlebot|bingbot|slurp/i);
var isTouch = !!("ontouchstart" in window) || !!(navigator.msMaxTouchPoints);
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; // Opera 8.0+
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; // At least Safari 3+: "[object HTMLElementConstructor]"
var isIE = /*@cc_on!@*/false || !!document.documentMode; // Internet Explorer 6-11
var isIE8 = !-[1,]; // Internet Explorer 8 or below
var isEdge = !isIE && !!window.StyleMedia; // Edge 20+
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.csi); // Chrome 1+
var isBlink = (isChrome || isOpera) && !!window.CSS; // Blink engine detection
var structure = new ctor_structure;
var toc = new ctor_toc;
var index = new ctor_index;
var search = new ctor_search;
var features = new ctor_features;
var translate = {dataPath: scriptDir + '/source/data_translate.js'};
var deprecate = {dataPath: scriptDir + '/source/data_deprecate.js'};
scriptElement.insertAdjacentHTML('afterend', structure.metaViewport);
var isPhone = (document.documentElement.clientWidth <= 600);
(function() {
// Exit the script if the user is a search bot. This is done because we want
// to prevent the search bot from parsing the elements added via javascript,
// otherwise the search results would be distorted:
if (isSearchBot)
return;
// Exit the script on sites which doesn't need the sidebar:
if (forceNoScript || cache.forceNoScript)
return;
// Special treatments for pages inside a frame:
if (isFrameCapable)
{
if (isInsideFrame)
{
$('head').append('<style>body {font-size:' + cache.fontSize + 'em}</style>');
normalizeParentURL = function() {
postMessageToParent('normalizeURL', [$.extend({}, window.location), document.title, supportsHistory ? history.state : null, equivPath]);
if (cache.toc_clickItem)
if (supportsHistory)
history.replaceState({toc_clickItem: cache.toc_clickItem}, null, null);
cache.set('toc_clickItem', 0);
}
normalizeParentURL(); $(window).on('hashchange', normalizeParentURL);
structure.setTheme(cache.colorTheme);
structure.addShortcuts();
structure.addAnchorFlash();
structure.saveCacheBeforeLeaving();
$(document).ready(function() {
$('html').attr({ id: 'right'});
features.add();
});
$(window).on('message onmessage', function(event) {
var data = JSON.parse(event.originalEvent.data);
switch(data[0]) {
case 'updateCache':
if(typeof data[1] === 'object')
$.extend(cache, data[1]);
else
cache[data[1]] = data[2];
break;
case 'highlightWords':
search.highlightWords(data[1]);
break;
case 'scrollToMatch':
search.scrollToMatch(data[1]);
break;
case 'setTheme':
structure.setTheme(data[1]);
break;
}
});
return;
}
else
{
$(window).on('message onmessage', function(event) {
var data = JSON.parse(event.originalEvent.data);
switch(data[0]) {
case 'normalizeURL':
var relPath = data[1].href.replace(workingDir, '');
try {
if (history.replaceState)
history.replaceState(null, null, data[1].href);
}
catch(e) {
if (history.replaceState)
history.replaceState(null, null, "?frame=" + encodeURI(relPath).replace(/#/g, '%23'));
}
document.title = data[2];
if (structure.modifyTools)
structure.modifyTools(relPath, data[4]);
if ($('#left > div.toc li > span.selected a').attr('href') == data[1].href)
break;
else if (data[3]) {
toc.deselect($('#left > div.toc'));
$('#left > div.toc li > span').eq(data[3].toc_clickItem).trigger('select');
}
else
toc.preSelect($('#left > div.toc'), data[1], relPath);
break;
case 'pressKey':
structure.pressKey(data[1]);
break;
}
});
$(window).on('hashchange', function() {
structure.openSite(location.href);
});
}
}
// Add elements for sidebar:
structure.build();
// Get user data:
if (!isCacheLoaded) {
if (isInsideCHM) {
var m = scriptDir.match(/mk:@MSITStore:(.*?)\\[^\\]+\.chm/i);
if (m[1])
loadScript(decodeURI(m[1]) + '\\chm_config.js', function () {
try {
$.extend(cache, overwriteProps(user, config));
setInitialSettings();
} catch (e) {}
});
}
else if (window.localStorage) {
config = JSON.parse(window.localStorage.getItem('config'));
$.extend(cache, overwriteProps(user, config));
setInitialSettings();
}
else if (navigator.cookieEnabled) {
config = document.cookie.match(/config=([^;]+)/);
config && (config = JSON.parse(config[1]));
$.extend(cache, overwriteProps(user, config));
setInitialSettings();
}
}
else
setInitialSettings();
function setInitialSettings() {
// font size
$('head').append('<style>#right .area {font-size:' + cache.fontSize + 'em}</style>');
// color theme
if(cache.colorTheme)
structure.setTheme(cache.colorTheme);
}
// Load current URL into frame:
if (isFrameCapable)
$(document).ready(function() {
document.getElementById('frame').contentWindow.name = JSON.stringify(cache);
structure.openSite(scriptDir + '/../' + (getUrlParameter('frame') || relPath));
});
// Modify the site:
structure.modify();
if (!isFrameCapable)
$(document).ready(features.add);
toc.modify();
index.modify();
search.modify();
})();
// --- Constructor: Table of content ---
function ctor_toc()
{
var self = this;
self.dataPath = scriptDir + '/source/data_toc.js';
self.create = function(input) { // Create and add TOC items.
var ul = document.createElement("ul");
for(var i = 0; i < input.length; i++)
{
var text = input[i][0];
var path = input[i][1];
var subitems = input[i][2];
if (path != '')
{
var el = document.createElement("a");
el.href = workingDir + path;
if (cache.deprecate_data[path])
el.className = "deprecated";
}
else
var el = document.createElement("button");
if (isIE8)
el.innerHTML = text;
else
{
el.setAttribute("data-content", text);
el.setAttribute("aria-label", text);
}
var span = document.createElement("span");
span.innerHTML = el.outerHTML;
var li = document.createElement("li");
li.title = text;
if (cache.deprecate_data[path])
li.title += "\n\n" + T("Deprecated. New scripts should use {0} instead.").format(cache.deprecate_data[path]);
if (subitems != undefined && subitems.length > 0)
{
li.className = "closed";
li.innerHTML = span.outerHTML;
li.innerHTML += self.create(subitems).outerHTML;
}
else
li.innerHTML = span.outerHTML;
ul.innerHTML += li.outerHTML;
}
return ul;
};
// --- Modify the elements of the TOC tab ---
self.modify = function() {
if (!retrieveData(self.dataPath, "toc_data", "tocData", self.modify))
return;
if (!retrieveData(deprecate.dataPath, "deprecate_data", "deprecateData", self.modify))
return;
$toc = $('#left div.toc').html(self.create(cache.toc_data));
$tocList = $toc.find('li > span');
// --- Fold items with subitems ---
$toc.find('li > ul').hide();
// --- Hook up events ---
// Select the item on click:
registerEvent($toc, 'click', 'li > span', function() {
$this = $(this);
cache.set('toc_clickItem', $tocList.index(this));
cache.set('toc_scrollPos', $toc.scrollTop());
// Fold/unfold item with subitems:
if ($this.parent().has("ul").length) {
$this.siblings("ul").slideToggle(100);
$this.closest("li").toggleClass("closed opened");
}
// Higlight and open item with link:
if ($this.has("a").length) {
self.deselect($toc); $this.trigger('select');
structure.openSite($this.children('a').attr('href'));
structure.focusContent();
return false;
}
});
// Highlight the item and parents on select:
registerEvent($toc, 'select', 'li > span', function() {
$this = $(this);
// Highlight the item:
$this.addClass("selected");
// Highlight its parents:
$this.parent("li").has('ul').addClass('highlighted');
$this.parent().parents('li').addClass('highlighted');
// Unfold parent items:
$this.parents("ul").show();
$this.parents("ul").closest("li").removeClass('closed').addClass('opened');
});
// --- Show scrollbar on mouseover ---
if (!isTouch) // if not touch device.
{
$toc.css("overflow", "hidden").hover(function() {
$(this).css("overflow", "auto");
}, function() {
$(this).css("overflow", "hidden");
});
}
self.preSelect($toc, location, relPath);
if (!isFrameCapable)
setTimeout( function() { self.preSelect($toc, location, relPath); }, 0);
};
self.preSelect = function($toc, url, relPath) { // Apply stored settings.
var tocList = $toc.find('li > span');
var clicked = tocList.eq(cache.toc_clickItem);
var relPathNoHash = relPath.replace(url.hash,'');
var found = null;
var foundList = [];
var foundNoHashList = [];
for (var i = 0; i < tocList.length; i++) {
var href = tocList[i].firstChild.href;
if (!href)
continue;
// Search for items which matches the address:
if (href.indexOf(relPath, href.length - relPath.length) !== -1)
foundList.push($(tocList[i]));
// Search for items which matches the address without anchor:
else if (href.indexOf(relPathNoHash, href.length - relPathNoHash.length) !== -1)
foundNoHashList.push($(tocList[i]));
}
if (foundList.length)
found = $(foundList).map($.fn.toArray);
else if (foundNoHashList.length)
found = $(foundNoHashList).map($.fn.toArray);
var el = found;
// If the last clicked item can be found in the matches, use it instead:
if (clicked.is(found))
el = clicked;
else
cache.set('toc_scrollPos', ""); // Force calculated scrolling.
// If items are found:
if (el) {
// Highlight items and parents:
self.deselect($toc); el.trigger('select');
// Scroll to the last match:
if (cache.toc_scrollPos != "" || cache.toc_scrollPos != 0)
$toc.scrollTop(cache.toc_scrollPos);
if (!isScrolledIntoView(el, $toc)) {
el[el.length-1].scrollIntoView(false);
$toc.scrollTop($toc.scrollTop()+100);
}
}
}
self.deselect = function($toc) { // Deselect all items.
$toc.find("span.selected").removeClass("selected");
$toc.find(".highlighted").removeClass("highlighted");
}
}
// --- Constructor: Keyword search ---
function ctor_index()
{
var self = this;
self.dataPath = scriptDir + '/source/data_index.js';
self.create = function(input, filter) { // Create and add the index links.
var output = '';
input.sort(function(a, b) {
var textA = a[0].toLowerCase(), textB = b[0].toLowerCase()
return textA.localeCompare(textB);
});
for (var i = 0, len = input.length; i < len; i++)
{
if (filter != -1 && input[i][2] != filter)
continue;
var a = document.createElement("a");
a.href = workingDir + input[i][1];
a.setAttribute("tabindex", "-1");
if (isIE8)
a.innerHTML = input[i][0];
else
{
a.setAttribute("data-content", input[i][0]);
a.setAttribute("aria-label", input[i][0]);
}
output += a.outerHTML;
}
return output;
};
self.modify = function() { // Modify the elements of the index tab.
if (!retrieveData(self.dataPath, "index_data", "indexData", self.modify))
return;
var $index = $('#left div.index');
var $indexSelect = $index.find('.select select');
var $indexInput = $index.find('.input input');
var $indexList = $index.find('div.list');
// --- Hook up events ---
// Filter list on change:
$indexSelect.on('change', function(e) {
cache.set('index_filter', this.value);
if(this.value == -1)
$(this).addClass('empty');
else
$(this).removeClass('empty');
$indexList.html(self.create(cache.index_data, this.value));
structure.addEventsForListBoxItems($indexList);
});
// Select closest index entry and show color indicator on input:
$indexInput.on('keyup input', function(e) {
var $this = $(this);
var prevInput = cache.index_input; // defaults to undefined
var input = cache.set('index_input', $this.val().toLowerCase());
// if no input, remove color indicator and return:
if (!input) {
$this.removeAttr('class');
return;
}
// Skip subsequent index-matching if we have the same query as the last search, to prevent double execution:
if (input == prevInput)
return;
// Otherwise find the first item which matches the input value:
var indexListChildren = $indexList.children();
var match = self.findMatch(indexListChildren, input);
// Select the found item, scroll to it and add color indicator:
if (match.length) {
match.click();
// Scroll to 5th item below the match to improve readability:
scrollTarget = match.next().next().next().next().next();
if (!scrollTarget.length) { scrollTarget = indexListChildren.last(); };
scrollTarget[0].scrollIntoView(false);
$this.attr('class', 'match'); // 'items found'
}
else
$this.attr('class', 'mismatch'); // 'items not found'
});
$indexSelect.val(cache.index_filter).trigger('change');
self.preSelect($indexList, $indexInput);
if (!isFrameCapable)
setTimeout( function() { self.preSelect($indexList, $indexInput); }, 0);
};
self.findMatch = function(indexListChildren, input) {
var match = {};
if (!input)
return match;
for (var i = 0; i < indexListChildren.length; i++) {
var text = isIE8 ? indexListChildren[i].innerText : indexListChildren[i].getAttribute('data-content');
var listitem = text.substr(0, input.length).toLowerCase();
if (listitem == input) {
match = indexListChildren.eq(i);
break;
}
}
return match;
};
self.preSelect = function($indexList, $indexInput) { // Apply stored settings.
var clicked = $indexList.children().eq(cache.index_clickItem);
$indexInput.val(cache.index_input);
if (cache.index_scrollPos == null)
$indexInput.trigger('keyup');
else
{
$indexList.scrollTop(cache.index_scrollPos);
clicked.click();
}
};
}
// --- Constructor: Full text search ---
function ctor_search()
{
var self = this;
self.dataPath = scriptDir + '/source/data_search.js';
self.modify = function() { // Modify the elements of the search tab.
if (!retrieveData(self.dataPath, "search_index", "SearchIndex", self.modify))
return;
if (!retrieveData(self.dataPath, "search_files", "SearchFiles", self.modify))
return;
if (!retrieveData(self.dataPath, "search_titles", "SearchTitles", self.modify))
return;
var $search = $('#left div.search');
var $searchList = $search.find('div.list');
var $searchInput = $search.find('.input input');
var $searchCheckBox = $search.find('.checkbox input');
// --- Hook up events ---
// Refresh the search list and show color indicator on input:
$searchInput.on('keyup input', function(e) {
var $this = $(this);
var prevInput = cache.search_input; // defaults to undefined
var input = cache.set('search_input', $this.val());
// if no input, empty the search list, remove color indicator and return:
if (!input) {
$searchList.empty();
$this.removeAttr('class');
return;
}
// Skip subsequent search if we have the same query as the last search, to prevent double execution:
if (input == prevInput)
return;
// Otherwise fill the search list:
cache.set('search_data', self.create(input));
$searchList.html(cache.search_data);
structure.addEventsForListBoxItems($searchList);
// Select the first item and add color indicator:
var searchListChildren = $searchList.children();
if (searchListChildren.length) {
searchListChildren.first().click();
cache.set('search_clickItem', 0);
$this.attr('class', 'match'); // 'items found'
}
else
$this.attr('class', 'mismatch'); // 'items not found'
});
self.preSelect($searchList, $searchInput, $searchCheckBox);
if (!isFrameCapable)
setTimeout( function() { self.preSelect($searchList, $searchInput, $searchCheckBox); }, 0);
};
self.preSelect = function($searchList, $searchInput, $searchCheckBox) { // Apply stored settings.
$searchInput.val(cache.search_input);
if (cache.search_scrollPos == null)
$searchInput.trigger('keyup');
else
{
$searchList.html(cache.search_data);
structure.addEventsForListBoxItems($searchList);
$searchList.scrollTop(cache.search_scrollPos);
$searchList.children().eq(cache.search_clickItem).click();
}
$searchCheckBox.prop('checked', cache.search_highlightWords);
};
self.convertToArray = function(SearchText) { // Convert text to array.
// Normalize whitespace:
SearchText = SearchText.toLowerCase().replace(/^ +| +$| +(?= )|\+/, '');
if (SearchText == '')
return '';
else // split and remove undefined or empty strings
return $(SearchText.split(' ')).filter(function(){return (!!this)});
}
self.highlightWords = function(words) {
var content = $(isInsideFrame ? 'body' : '#right .area');
if(words)
{
var qry = self.convertToArray(words);
for (var i = 0; i < qry.length; i++) {
content.highlight(qry[i]);
}
self.scrollToMatch(); // Scroll to first match.
}
else
content.removeHighlight();
}
self.scrollToMatch = function(direction) {
var matches = $(isInsideFrame ? 'body' : '#right .area').find('span.highlight');
if (!matches.length)
return;
var currMatch = matches.filter('.current');
if (currMatch.length)
{
index = matches.index(currMatch) + (direction == 'next' ? 1 : -1);
if (index > matches.length - 1)
index = 0;
else if (index < 0)
index = matches.length - 1;
currMatch.removeClass('current');
}
else
index = 0;
matches.eq(index).addClass('current');
matches.eq(index)[0].scrollIntoView(isIE8 ? true : {block: 'center'});
}
self.create = function(qry) { // Create search list.
var PartialIndex = {};
var RESULT_LIMIT = 50;
qry = self.convertToArray(qry);
if (qry == '')
return
function file_has_all_words(file_index, words, start) {
for ( ; start < words.length; ++start) {
var iw = index_partial(words[start])
if (!iw || iw.indexOf(file_index) == -1)
return false
}
return true
}
// Get each word from index and clone for modification below:
var all_results = []
for (var i = 0; i < qry.length; ++i) {
var t = qry[i].replace(/(\(|\(\))$/,'') // special case for page names ending with ()
var w = index_partial(t)
w = w ? w.slice() : []
all_results[i] = get_results(w)
}
var ranked = rank_results(all_results,qry)
return append_results(ranked);
// Get normal results for each term:
function get_results(w) {
var c = 0
var ret = []
for (var i = 0; i < w.length && c < RESULT_LIMIT; ++i) {
if (!file_has_all_words(w[i], qry, 1))
continue // Skip files which don't have all the words.
c++
var f = cache.search_files[w[i]]
// data.files excludes '.htm' to save space, so add it back:
if (f.indexOf('#') != -1)
f = f.replace('#', '.htm#')
else
f = f + '.htm'
// var ret_i = { u: location.href.replace(/\/docs\/.*/, "/docs/" + f),
var ret_i = { u: f,
t: (cache.search_titles[w[i]] || f) }
ret.push(ret_i)
}
return ret
}
function rank_results(aro,terms) {
// Organize the info:
var aro_k = []
var aro_ua = []
var aro_ka = []
for (var i = 0; i < aro.length; ++i) {
aro_k[i] = []
if (aro[i] === undefined) { continue; }
for (var j = 0; j < aro[i].length; ++j) {
aro_k[i].push(aro[i][j].t)
aro_ka.push(aro[i][j].t)
aro_ua[aro[i][j].t] = aro[i][j].u
}
}
// Assemble list of unique results:
var ukeys = []
for (var i = 0; i < aro_ka.length; ++i)
if (ukeys.indexOf(aro_ka[i]) == -1)
ukeys.push(aro_ka[i])
// The lower the rank the better
// normal ranking (based on page contents):
var uranks = []
for (var i = 0; i < ukeys.length; ++i) {
uranks[ukeys[i]] = []
for (var j = 0; j < aro_k.length; ++j) {
uranks[ukeys[i]][j] = ukeys[i].indexOf(aro_k[j])
}
}
// Added ranking (based on page names)
// and calculate the ranks:
for (var i = 0; i < ukeys.length; ++i){
var name = ukeys[i]
var tmp = uranks[name]
// If the name contains any of the search terms:
if ( anyContains(name.toLowerCase(),terms) ) {
tmp.push(0) // Give it a better rank.
} else {
tmp.push(1,8) // Give it a worse rank, Tweakable!
}
uranks[name] = array_avg(tmp)
}
// Sort results by rank average and finalize:
var ret = []
for (var i = 0; i < ukeys.length; ++i){
var name = ukeys[i]
var url = aro_ua[name]
var avg = uranks[name]
ret.push({n:name,u:url,a:avg})
}
ret.sort(function(a,b){return (a.a - b.a)})
ret.slice(0,RESULT_LIMIT)
return ret
}
function array_avg(arr) {
var sum = 0
var total = arr.length
for (var j = 0; j < arr.length; ++j){
if ( (arr[j] < 0) || (arr[j-1] == arr[j]) )
total -= 1 // Give a worse rank, duplicate ranks are ignored.
else
sum += arr[j]
}
return (sum/total)
}
function anyContains(str, arr) { // http://stackoverflow.com/a/5582640/883015
for (var i = 0, len = arr.length; i < len; ++i) {
if (str.indexOf(arr[i]) != -1)
return 1
}
return 0
}
function append_results(ro) {
var output = '';
for (var t = 0; t < ro.length && t < RESULT_LIMIT; ++t) {
var a = document.createElement("a");
a.href = workingDir + ro[t].u;
a.setAttribute("tabindex", "-1");
if (isIE8)
a.innerHTML = ro[t].n;
else
{
a.setAttribute("data-content", ro[t].n);
a.setAttribute("aria-label", ro[t].n);
}
output += a.outerHTML;
}
return output;
}
function decode_numbers(a) {
// Decode a string of [a-zA-Z] based 'numbers'
var n = []
for (i = 0; i < a.length; i += 2)
n.push(decode_number(a.substr(i, 2)))
return n
}
function decode_number(a) {
// Decode a number encoded by encode_number() in build_search.ahk:
var n = 0, c
for (var i = 0; i < a.length; ++i) {
c = a.charCodeAt(i)
n = n*52 + c - ((c >= 97 && c <= 122) ? 97 : 39)
}
return n
}
function index_whole(word) {
// Return a word from the index, decoding the list of files
// if it hasn't been decoded already:
var files = cache.search_index[word]
if (typeof(files) == "string") {
files = decode_numbers(files)
cache.search_index[word] = files
}
return files
}
function index_partial(word) {
if (word[0] == '+') // + prefix disables partial matching.
return index_whole(word.substr(1))
// Check if we've already indexed this partial word.
var files = PartialIndex[word]
if (files !== undefined)
return files
// Find all words in search.index which *contain* this word
// and cache the result.
files = []
var files_low = []
for (iw in cache.search_index) {
var p = iw.indexOf(word)
if (p != -1)
files.push.apply(p == 0 ? files : files_low, index_whole(iw))
}
files = files.concat(files_low)
var unique = []
for (var i = 0; i < files.length; ++i)
if (unique.indexOf(files[i]) == -1)
unique.push(files[i])
PartialIndex[word] = unique
return unique
}
};
}
// --- Constructor: Navigation structure ---
function ctor_structure()
{
var self = this;
self.metaViewport = '<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">';
self.template = '<div id="body">' +
'<div id="head" role="banner"><button onclick="structure.focusContent();" class="skip-nav" data-translate aria-label="data-content" data-content="Skip navigation"></button><div class="h-area"><div class="h-tabs"><ul><li><button data-translate title="Shortcut: ALT+C" aria-label="Content tab" data-content="C̲ontent"></button></li><li><button data-translate title="Shortcut: ALT+N" aria-label="Index tab" data-content="In̲dex"></button></li><li><button data-translate title="Shortcut: ALT+S" aria-label="Search tab" data-content="S̲earch"></button></li></ul></div><div class="h-tools sidebar"><ul><li class="sidebar"><button title="Hide or show the sidebar" data-translate aria-label="title">Ξ</button></li></ul></div><div class="h-tools online"><ul><li class="home"><a href="' + location.protocol + '//' + location.host + '" title="Go to the homepage" data-translate aria-label="title">Δ</a></li><li class="language"><button data-translate title="Change the language" data-translate aria-label="title" data-content="en"></button><ul class="dropdown languages selected"><li><a href="#" title="English" aria-label="title" data-content="en"></a></li><li><a href="#" title="Deutsch (German)" data-content="de" aria-label="title"></a></li><li><a href="#" title="한국어 (Korean)" aria-label="title" data-content="ko"></a></li><li><a href="#" title="中文 (Chinese)" aria-label="title" data-content="zh"></a></li></ul></li><li class="version"><button title="Change the version" data-translate aria-label="title" data-content="v1"></button><ul class="dropdown versions selected"><li><a href="#" title="AHK v1.1" aria-label="title" data-content="v1"></a></li><li><a href="#" title="AHK v2.0" aria-label="title" data-content="v2"></a></li></ul></li><li class="edit"><a href="#" title="Edit this document on GitHub" data-translate=2 aria-label="title" data-content="E"></a></li></ul></div><div class="h-tools chm"><ul><li class="back"><button title="Go back" data-translate=2 aria-label="title">◄</button></li><li class="forward"><button title="Go forward" data-translate=2 aria-label="title">►</button></li><li class="zoom"><button title="Change the font size" data-translate=2 aria-label="title" data-content="Z"></button></li><li class="print"><button title="Print this document" data-translate=2 aria-label="title" data-content="P"></button></li><li class="browser"><a href="#" target="_blank" title="Open this document in the default browser (requires internet connection). Middle-click to copy the link address." data-translate aria-label="title">¬</a></li></ul></div><div class="h-tools main visible"><ul><li class="color"><button title="Use the dark or light theme" data-translate=2 aria-label="title" data-content="C"></button></li><li class="settings"><button title="Open the help settings" data-translate=2 aria-label="title">Ѕ</button></li></ul></div></div></div>' +
'<div id="main"><div id="left" role="navigation"><div class="toc"></div><div class="index"><div class="input"><input type="search" placeholder="Search" data-translate=2 /></div><div class="select"><select size="1" class="empty"><option value="-1" class="empty" selected data-translate>Filter</option><option value="0" data-translate>Directives</option><option value="1" data-translate>Built-in Variables</option><option value="2" data-translate>Built-in Functions</option><option value="3" data-translate>Control Flow Statements</option><option value="4" data-translate>Operators</option><option value="5" data-translate>Declarations</option><option value="6" data-translate>Commands</option><option value="99" data-translate>Ahk2Exe Compiler</option></select></div><div class="list"></div></div><div class="search"><div class="input"><input type="search" placeholder="Search" data-translate=2 /></div><div class="checkbox"><input type="checkbox" id="highlightWords"><label for="highlightWords" data-translate>Highlight keywords</label><div class="updown" title="Go to previous/next occurrence" data-translate aria-label="title"><div class="up"><div class="triangle-up"></div></div><div class="down"><div class="triangle-down"></div></div></div></div><div class="list"></div></div><div class="load"><div class="lds-dual-ring"></div></div></div><div class="dragbar"></div><div id="right" tabIndex="-1">'+(isFrameCapable?'<iframe frameBorder="0" id="frame" src="" role="main">':'<div class="area" role="main">');
self.template = isIE8 ? self.template.replace(/ data-content="(.*?)">/g, '>$1') : self.template;
self.build = function() { document.write(self.template); }; // Write HTML before DOM is loaded to prevent flickering.
self.modify = function() { // Modify elements added via build.
if (!retrieveData(translate.dataPath, "translate_data", "translateData", self.modify))
return;
// --- If phone, hide and overlap sidebar ---
if (isPhone) { self.displaySidebar(false); $('#left').addClass('phone') }
// --- Add events ---
self.saveCacheBeforeLeaving();
self.addShortcuts();
self.addAnchorFlash();
if (!isFrameCapable)
self.setKeyboardFocus();
if (supportsHistory) {
self.saveSiteStateBeforeLeaving();
self.scrollToPosOnHashChange();
self.saveScrollPosOnScroll();
}
// --- Translate elements with data-translate attribute (value 1 for content only, 2 for attributes only) ---
$('#head').add($('#left')).find('*[data-translate]').each(function() {
var $this = $(this);
var elContent = $this.text();
var attrTitleValue = $this.attr('title');
var attrPlaceholder = $this.attr('placeholder');
var attrAriaLabelValue = $this.attr('aria-label');
var attrDataContentValue = $this.attr('data-content');
var attrDataTranslateValue = $this.attr('data-translate');
if(!attrDataTranslateValue || attrDataTranslateValue == 1)
{
if(elContent != '')
$this.text(T(elContent));
if(typeof attrDataContentValue !== 'undefined')
$this.attr('data-content', T(attrDataContentValue));
}
if(!attrDataTranslateValue || attrDataTranslateValue == 2)
{
if(typeof attrTitleValue !== 'undefined')
$this.attr('title', T(attrTitleValue));
if (typeof attrPlaceholder !== 'undefined')
$this.attr('placeholder', T(attrPlaceholder));
}
if (attrAriaLabelValue)
{
var value = $this.attr(attrAriaLabelValue);
$this.attr("aria-label", T(value || attrAriaLabelValue));
}
});
// --- Show/Hide selection lists on click ---
$('#head .h-tools li:has(.dropdown)').on('click', function() {
$this = $(this);
$dropdown = $this.children('.dropdown');
$('#head .h-tools .dropdown').not($dropdown).animate({height: 'hide'}, 100);
$('#head .h-tools li').not($this).removeClass('selected');
$dropdown.animate({height: 'toggle'}, 100);
$this.toggleClass('selected');
});
// --- Main tools (always visible) ---
var $main = $('#head .h-tools.sidebar').add('#head .h-tools.main');
$main.find('li.sidebar').on('click', function() {
self.displaySidebar(!cache.displaySidebar);
});
$main.find('li.settings').on('click', function() {
structure.openSite(scriptDir + '/../settings.htm');
});
$main.find('li.color').on('click', function() {
cache.set('colorTheme', cache.colorTheme ? 0 : 1);
structure.setTheme(cache.colorTheme);
if (isFrameCapable)
postMessageToFrame('setTheme', [cache.colorTheme]);
});
// --- Online tools (only visible if help is not CHM) ---
var $online = $('#head .h-tools.online');
// Set language code and version:
var lang = T("en"), ver = T("v1");
// language links. Keys are based on ISO 639-1 language name standard:
var link = { 'v1': { 'en': 'https://www.autohotkey.com/docs/',
'de': 'https://ahkde.github.io/docs/',
'ko': 'https://ahkscript.github.io/ko/docs/',
'zh': 'https://wyagd001.github.io/zh-cn/docs/' },
'v2': { 'en': 'https://lexikos.github.io/v2/docs/',
'de': 'https://ahkde.github.io/v2/docs/',
'zh': 'https://wyagd001.github.io/v2/docs/' } }
var $langList = $online.find('ul.languages')
var $verList = $online.find('ul.versions')
self.modifyTools = function(relPath, equivPath) {
// Bug - IE/Edge doesn't turn off list-style if element is hidden:
$langList.add($verList).css("list-style", "none");
// Hide currently selected language and version in the selection lists:
$(isIE8 ? 'a:contains(' + lang + ')' : 'a[data-content=' + lang + ']', $langList).parent().hide();
$(isIE8 ? 'a:contains(' + ver + ')' : 'a[data-content=' + ver + ']', $verList).parent().hide();
// Add the language links:
$langList.find('li').each( function() {
var a = $(this).find('a');
var thisLink = link[ver][isIE8 ? a.text() : a.attr('data-content')];
if (thisLink == null)
$(this).hide(); // Hide language button
else
a.attr('href', thisLink + relPath);
});
// Add the version links:
$verList.find('li').each( function() {
var a = $(this).find('a');
var ver = isIE8 ? a.text() : a.attr('data-content');
var thisLink = link[ver][lang];
// Fallback to default docs:
thisLink = (thisLink == null) ? link[ver]['en'] : thisLink;
a.attr('href', thisLink + (equivPath || relPath));
});
// Hide dropdown list on click with left or middle mouse button:
registerEvent($langList.add($verList), 'mouseup', '', function(e) {
if (e.which == 1 || e.which == 2) {
setTimeout(function() {
$dropdown.animate({height: 'hide'}, 100);
$this.removeClass('selected');
}, 200);
}
});
// 'Edit page on GitHub' button:
$("li.edit > a").attr({
href: T("https://github.com/Lexikos/AutoHotkey_L-Docs/edit/master/docs/") + relPath,
target: "_blank"
});
// --- CHM tools (only visible if help is CHM) ---
var $chm = $('#head .h-tools.chm');
// 'Go back' button:
registerEvent($chm.find('li.back'), 'click', '', function() { history.back(); });
// 'Go forward' button:
registerEvent($chm.find('li.forward'), 'click', '', function() { history.forward(); });
// 'Zoom' button:
registerEvent($chm.find('li.zoom'), 'click', '', function() {
cache.set('fontSize', cache.fontSize + 0.2);
if (cache.fontSize > 1.4)
cache.set('fontSize', 0.6);
$('#frame').contents().find('body').css('font-size', cache.fontSize + 'em');
});
// 'Print' button:
registerEvent($chm.find('li.print'), 'click', '', function() { window.parent.document.getElementById('frame').contentWindow.document.execCommand('print', false, null); });
// 'Open in default browser' button:
btn = $chm.find('li.browser > a').attr('href', link[ver][lang] + relPath);
registerEvent(btn, 'mouseup', '', function(e) {
if (e.which == 2) {
window.clipboardData.setData('Text', this.href);
}
});