forked from mozilla/prospector
/
bootstrap.js
1837 lines (1505 loc) · 56.9 KB
/
bootstrap.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
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is AwesomeBar HD.
*
* The Initial Developer of the Original Code is The Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Edward Lee <edilee@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
"use strict";
const global = this;
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/AddonManager.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
// Keep a reference to the top level providers data
let allProviders;
// Keep a reference to the add-on object for various uses like disabling
let gAddon;
// Keep track of how often what part of the interface is used
let usage;
// Keep track whether delete or backspace was pressed
let deleting = false;
// Get and set preferences under the prospector pref branch
XPCOMUtils.defineLazyGetter(global, "prefs", function() {
Cu.import("resource://services-sync/ext/Preferences.js");
return new Preferences("extensions.prospector.awesomeBarHD.");
});
// Remove existing Firefox UI and add in custom AwesomeBar HD
function addAwesomeBarHD(window) {
let {async, change, createNode} = makeWindowHelpers(window);
let {document, gBrowser, gIdentityHandler, gURLBar} = window;
// Get references to existing UI elements
let origIdentity = gIdentityHandler._identityBox;
let origInput = gURLBar.mInputField;
// Add an icon to indicate the active category
let iconBox = createNode("box");
iconBox.setAttribute("align", "center");
iconBox.setAttribute("collapsed", true);
iconBox.setAttribute("id", "identity-box");
origIdentity.parentNode.insertBefore(iconBox, origIdentity.nextSibling);
unload(function() {
iconBox.parentNode.removeChild(iconBox);
});
let providerIcon = createNode("image");
providerIcon.setAttribute("id", "page-proxy-favicon");
iconBox.appendChild(providerIcon);
// Show providers at the icon if something is active
providerIcon.handleMouse = function() {
let {active} = categoryBox;
if (active == null)
return;
active.context.openAt(providerIcon);
};
providerIcon.addEventListener("click", providerIcon.handleMouse, false);
providerIcon.addEventListener("mouseover", providerIcon.handleMouse, false);
// Add stuff around the original urlbar input box
let urlbarStack = createNode("stack");
origInput.parentNode.insertBefore(urlbarStack, origInput.nextSibling);
urlbarStack.setAttribute("flex", 1);
urlbarStack.style.overflow = "hidden";
unload(function() {
urlbarStack.parentNode.removeChild(urlbarStack);
});
// Create a dummy label that is invisible but has width to size text
let textSizer = createNode("label");
urlbarStack.appendChild(textSizer);
textSizer.setAttribute("left", 0);
textSizer.style.margin = 0;
textSizer.style.opacity = 0;
// Create a browser to prefetch search results
let prefetcher = createNode("browser");
prefetcher.setAttribute("autocompletepopup", gBrowser.getAttribute("autocompletepopup"));
prefetcher.setAttribute("collapsed", true);
prefetcher.setAttribute("contextmenu", gBrowser.getAttribute("contentcontextmenu"));
prefetcher.setAttribute("tooltip", gBrowser.getAttribute("contenttooltip"));
prefetcher.setAttribute("type", "content");
gBrowser.appendChild(prefetcher);
// Generate the url for the category and provider and prefetch if necessary
prefetcher.load = function(category, index) {
// Use the default index/provider if we don't have one
let {defaultIndex, providers} = category.categoryData;
if (index == null)
index = defaultIndex;
// Determine the space character to replace in the query
const termRegex = /{search(.)terms}/;
let {url} = providers[index];
let spaceChar = url.match(termRegex)[1];
// Strip off the keyword based on the current active category
let {value} = hdInput;
if (categoryBox.active != goCategory) {
value = encodeURIComponent(value.replace(/^[^:]*:\s*/, ""));
value = value.replace(/%20/g, spaceChar);
}
// Fill in the search term with the current query
url = url.replace(termRegex, value);
// Prefetch the search results if not going to a page
if (category != goCategory) {
// Only prefetch if we have something new
if (prefetcher.lastUrl != url) {
prefetcher.loadURI(url);
prefetcher.lastUrl = url;
}
}
return url;
};
// Only prefetch if currently prefetching
prefetcher.loadIfSearching = function(category, index) {
if (categoryBox.active != goCategory)
prefetcher.load(category, index);
};
// Save the prefetched page to a tab in the browser
prefetcher.persistTo = function(targetTab) {
let targetBrowser = targetTab.linkedBrowser;
targetBrowser.stop();
// Unhook our progress listener
let selectedIndex = targetTab._tPos;
const filter = gBrowser.mTabFilters[selectedIndex];
let tabListener = gBrowser.mTabListeners[selectedIndex];
targetBrowser.webProgress.removeProgressListener(filter);
filter.removeProgressListener(tabListener);
let tabListenerBlank = tabListener.mBlank;
// Restore current registered open URI
let previewURI = prefetcher.currentURI;
let openPage = gBrowser._placesAutocomplete;
if (targetBrowser.registeredOpenURI) {
openPage.unregisterOpenPage(targetBrowser.registeredOpenURI);
delete targetBrowser.registeredOpenURI;
}
openPage.registerOpenPage(previewURI);
targetBrowser.registeredOpenURI = previewURI;
// Save the last history entry from the preview if it has loaded
let history = prefetcher.sessionHistory.QueryInterface(Ci.nsISHistoryInternal);
let lastEntry;
if (history.count > 0) {
lastEntry = history.getEntryAtIndex(history.index, false);
history.PurgeHistory(history.count);
}
// Copy over the history from the target browser if it's not empty
let origHistory = targetBrowser.sessionHistory;
for (let i = 0; i <= origHistory.index; i++) {
let origEntry = origHistory.getEntryAtIndex(i, false);
if (origEntry.URI.spec != "about:blank")
history.addEntry(origEntry, true);
}
// Add the last entry from the preview; in-progress preview will add itself
if (lastEntry != null)
history.addEntry(lastEntry, true);
// Swap the docshells then fix up various properties
targetBrowser.swapDocShells(prefetcher);
targetBrowser.webNavigation.sessionHistory = history;
targetBrowser.attachFormFill();
gBrowser.setTabTitle(targetTab);
gBrowser.updateCurrentBrowser(true);
gBrowser.useDefaultIcon(targetTab);
// Restore the progress listener
tabListener = gBrowser.mTabProgressListener(targetTab, targetBrowser, tabListenerBlank);
gBrowser.mTabListeners[selectedIndex] = tabListener;
filter.addProgressListener(tabListener, Ci.nsIWebProgress.NOTIFY_ALL);
targetBrowser.webProgress.addProgressListener(filter, Ci.nsIWebProgress.NOTIFY_ALL);
// Forget what was prefetched as it's now gone
prefetcher.lastUrl = null;
};
unload(function() {
prefetcher.parentNode.removeChild(prefetcher);
});
// Prevent errors from browser.js/xul when it gets unexpected title changes
prefetcher.addEventListener("DOMTitleChanged", function(event) {
event.stopPropagation();
}, true);
// Add an area to show a list of categories
let categoryBox = createNode("hbox");
urlbarStack.appendChild(categoryBox);
categoryBox.setAttribute("flex", 1);
categoryBox.setAttribute("pack", "end");
categoryBox.style.cursor = "text";
categoryBox.style.overflow = "hidden";
categoryBox.style.pointerEvents = "none";
//Helper function to convert url to name.
function firstCapital(word) {
if(word!= null)
return word.substr(0,1).toUpperCase()+word.substr(1);
else
return "";
}
function makeWord(url) {
return firstCapital(url.replace("www.","").replace(/^(https:\/\/|http:\/\/)+/,"").split(".")[0]);
}
//Figure out if the current input text is activating any provider of category.
function checkInputForProviders(label,shortValue) {
let {categoryData} = label;
let {providers} = categoryData;
for(let i=0;i<providers.length;i++){
let {url, name} = providers[i];
if (shortValue == makeWord(url).toLowerCase().slice(0,shortValue.length) || shortValue == makeWord(name).toLowerCase().slice(0,shortValue.length))
return i;
}
return -1;
}
//Show category suggestion as we type
function suggestCategory() {
let {complete} = categoryBox;
if(complete == null)
return;
let {providers, defaultIndex, keyword} = complete.categoryData;
let {value, selectionStart} = hdInput;
let {url, name} = providers[defaultIndex];
if(keyword.slice(0, selectionStart) == value.slice(0, selectionStart)) {
hdInput.value = keyword;
hdInput.setSelectionRange(selectionStart, keyword.length);
}
else if(makeWord(url).toLowerCase().slice(0, selectionStart) == value.slice(0,selectionStart)) {
hdInput.value = makeWord(url).toLowerCase();
hdInput.setSelectionRange(selectionStart, makeWord(url).length);
}
else {
hdInput.value = makeWord(name).toLowerCase();
hdInput.setSelectionRange(selectionStart, makeWord(name).length);
}
//Reflect the hdInput value back to gURLBar
let {value, selectionStart, selectionEnd} = hdInput;
origInput.value= value;
origInput.setSelectionRange(selectionStart,selectionEnd);
}
// Look for deletes to handle them better on input
listen(window, gURLBar.parentNode, "keypress", function(event) {
switch (event.keyCode) {
case event.DOM_VK_BACK_SPACE:
case event.DOM_VK_DELETE:
deleting = true;
break;
}
});
// Activate a category with an optional provider index
categoryBox.activate = function(categoryNode, index) {
usage.activate++;
// Most likely don't want to search the current url, so remove on activate
let {selectionEnd, selectionStart, value} = hdInput;
if (value == getURI().spec)
value = "";
// Remove any active query terms when activating another
let query = value;
if (categoryBox.active != goCategory)
query = query.replace(/^[^:]*:\s*/, "");
// Remove the short keyword from the query on tab complete
let {category, keyword} = categoryNode.categoryData;
let shortKeyword = keyword.slice(0, selectionStart);
let shortQuery = query.slice(0, selectionStart);
if (shortKeyword != "" && shortQuery == shortKeyword) {
query = query.slice(selectionEnd);
sendEvent("complete", category);
}
// Update the text with the active keyword
hdInput.value = keyword;
let {complete} = categoryBox;
//If we were not completing to a category, then add the query also.
if (complete == null) {
hdInput.value+=query;
// Highlight the completed keyword if there's a query
let {length} = keyword;
hdInput.setSelectionRange(query == "" ? length : 0, length);
}
// Switch to a particular provider if necessary
if (index != null)
categoryNode.setIndex(index);
// Update the autocomplete results now that we've activated
categoryBox.processInput();
gURLBar.mController.handleText();
hdInput.focus();
};
// Immediately go to the result page if there's something to search
categoryBox.activateAndGo = function(categoryNode, index) {
usage.activateAndGo++;
// Remember if there's completely no input
let empty = hdInput.value == "";
categoryBox.activate(categoryNode, index);
// Animate in the now filled-in category towards the left
if (empty && usage.emptyClick++ < 3) {
let maxOffset = categoryNode.boxObject.x - urlbarStack.boxObject.x;
let maxSteps = 10;
let step = 0;
// Hide the category box and animate in the text
categoryBox.collapsed = true;
let animate = function() {
// Restore the original look
if (step == maxSteps) {
categoryBox.collapsed = false;
hdInput.removeAttribute("left");
return;
}
// Figure out where to position the text
let frac = step++ / maxSteps;
hdInput.setAttribute("left", maxOffset * (1 - Math.pow(frac, 3)));
async(animate, 40);
};
animate();
}
// Only go if it's not just blank
let {value} = hdInput;
if (value.search(/:\s*\S/) == -1)
return;
usage.activateAndWent++;
if (!empty)
usage.providerSwitch++;
gURLBar.handleCommand();
};
// Select the keyword if the cursor is in the keyword
categoryBox.checkSelection = function() {
if (categoryBox.active == goCategory)
return;
// Move the selection boundaries if they're inside the keyword
let {selectionEnd, selectionStart, value} = hdInput;
let queryStart = value.match(/^[^:]*:\s*/)[0].length;
if (selectionStart <= queryStart)
hdInput.selectionStart = 0;
if (selectionEnd < queryStart)
hdInput.selectionEnd = queryStart;
};
// Look through the input to decide what category could be activated
categoryBox.prepareNext = function() {
// Try finding a category to complete
let {active} = categoryBox;
categoryBox.complete = null;
// See if there's any potential category to complete with tab
let {selectionStart, value} = hdInput;
let shortValue = value.slice(0, selectionStart);
let {length} = shortValue;
if (length > 0 && active == goCategory) {
Array.some(categoryBox.childNodes, function(label) {
// Skip non-categories and the current active
let {categoryData} = label;
if (categoryData == null || label == active || categoryData.hidden == true)
return;
let {keyword} = categoryData;
if (keyword == "")
return;
if (shortValue == keyword.slice(0, length)) {
categoryBox.complete = label;
return true;
}
let index = checkInputForProviders(label,shortValue);
if (index >= 0) {
categoryBox.complete = label;
categoryBox.complete.categoryData.defaultIndex = index;
return true;
}
});
}
let temp = categoryBox.active.nextSibling.nextSibling;
// Prepare a next visible category and wrap if at the very end
while (temp && temp.categoryData.hidden) {
temp = temp.nextSibling.nextSibling;
}
if (!temp)
temp = goCategory;
categoryBox.next = temp;
let temp = (categoryBox.active != goCategory) ?
categoryBox.active.previousSibling.previousSibling : categoryBox.lastChild.previousSibling;
// Prepare a previous category unless already at the beginning and category not hidden
while (temp && temp.categoryData.hidden && temp != goCategory) {
temp = temp.previousSibling.previousSibling;
}
categoryBox.prev = temp;
};
// Figure out if the current input text is activating a category
categoryBox.processInput = function() {
// Figure out what's the active category based on the input
let {value} = hdInput;
let inputParts = value.match(/^([^:]*):\s*(.*?)$/);
categoryBox.active = goCategory;
if (inputParts != null) {
let inputKeyword = inputParts[1];
Array.some(categoryBox.childNodes, function(label) {
let {categoryData} = label;
if (categoryData == null || categoryData.hidden == true)
return;
let {keyword} = categoryData;
if (keyword == "")
return;
if (inputKeyword == keyword.slice(0, inputKeyword.length)) {
categoryBox.active = label;
return true;
}
let index = checkInputForProviders(label,inputKeyword);
if (index >= 0) {
categoryBox.active = label;
categoryBox.active.categoryData.defaultIndex = index;
return true;
}
});
}
// Update the UI now that we've figured out various states
categoryBox.prepareNext();
categoryBox.updateLook();
// Convert the input into a url for the location bar and prefetch
let {active} = categoryBox;
gURLBar.value = prefetcher.load(active);
// Only show results for going to a history page
gURLBar.popup.collapsed = active != goCategory;
// Save the input value to restore later if necessary
gBrowser.selectedTab.HDinput = value;
gBrowser.selectedTab.HDinputtedAt = Date.now();
};
// Clear out various state of the current input
categoryBox.reset = function() {
categoryBox.active = null;
categoryBox.complete = null;
categoryBox.next = null;
categoryBox.hover = null;
categoryBox.prev = null;
categoryBox.updateLook();
};
// Differently color certain categories depending on state
categoryBox.updateLook = function() {
// Restore some UI like the identity box
let {active, hover} = categoryBox;
if (active == null) {
gBrowser.selectedTab.HDinput = "";
hdInput.value = "";
}
// Prepare the UI for showing an active category
else {
let {defaultIndex, providers} = active.categoryData;
let {icon} = providers[defaultIndex];
if (icon == null)
providerIcon.removeAttribute("src");
else
providerIcon.setAttribute("src", icon);
}
// Check if the input looks like a url
let {value} = hdInput;
let likeUrl = value.indexOf(" ") == -1 && value.indexOf("/") != -1;
// Calculate the width of the input text plus some padding
textSizer.setAttribute("value", value);
let inputWidth = textSizer.boxObject.width + 5;
// Go through each label and style it appropriately
let focused = gURLBar.hasAttribute("focused");
let doActive = focused || value != "";
Array.forEach(categoryBox.childNodes, function(label) {
let {categoryData, style} = label;
let color = "#999";
let line = false;
if (label == active && doActive)
color = "#090";
else if (focused || label == hover) {
color = "#00f";
line = true;
}
style.color = color;
style.textDecoration = line && categoryData != null ? "underline" : "";
});
// Hide the url parts if it's about:blank or active
let isBlank = getURI().spec == "about:blank";
let hideUrl = isBlank || doActive;
urlBox.collapsed = hideUrl;
// Hide categories for long url inputs or when showing url parts
categoryBox.collapsed = likeUrl || !hideUrl;
// Show the next category if focus is in the box
if (focused && !likeUrl)
tabPanel.showNextCategory();
else
tabPanel.hidePopup();
// Show the original identity box when inactive
origIdentity.collapsed = doActive;
iconBox.collapsed = !doActive;
// Figure out if we should blank out the categories and separators
if (!categoryBox.collapsed) {
Array.forEach(categoryBox.childNodes, function(label) {
if (label.categoryData == null)
return;
// Make it transparent if its left side would cover text
let fromLeft = label.boxObject.x - categoryBox.boxObject.x;
let opacity = fromLeft < inputWidth ? 0 : 1;
label.style.opacity = opacity;
label.nextSibling.style.opacity = opacity;
});
}
};
// Pointing away removes the go category highlight
categoryBox.addEventListener("mouseout", function(event) {
if (event.target != categoryBox)
return;
categoryBox.hover = null;
categoryBox.updateLook();
}, false);
// Indicate the default behavior of a click is go
categoryBox.addEventListener("mouseover", function(event) {
if (event.target != categoryBox)
return;
if (gURLBar.hasAttribute("focused"))
return;
categoryBox.hover = goCategory;
categoryBox.updateLook();
}, false);
// Select the text to edit for a website
categoryBox.addEventListener("click", function(event) {
if (event.target != categoryBox && event.target != goCategory)
return;
hdInput.focus();
hdInput.select();
}, false);
// Create a category label
function addCategory(categoryData) {
let {category, keyword, providers, text} = categoryData;
let categoryNode = createNode("hbox");
categoryBox.appendChild(categoryNode);
categoryNode.style.cursor = "pointer";
categoryNode.style.marginRight = "-1px";
categoryNode.style.pointerEvents = "auto";
categoryNode.categoryData = categoryData;
let image = createNode("image");
categoryNode.appendChild(image);
image.setAttribute("src", providers[categoryData.defaultIndex].icon);
image.style.pointerEvents = "none";
let label = createNode("label");
categoryNode.appendChild(label);
label.setAttribute("value", text);
label.style.margin = 0;
label.style.pointerEvents = "none";
// Allow changing the default index and updating the UI for it
categoryNode.setIndex = function(index) {
if (categoryData.defaultIndex == index)
return;
let {icon, name} = providers[index];
categoryData.defaultIndex = index;
image.setAttribute("src", icon);
sendEvent("set " + category, name);
};
// Show or reshow the menu when clicking the label
function onClick() {
context.openAt(categoryNode);
}
// Open the context menu when moving over the related labels
let hoverTimer;
function onMove() {
// Already have a timer active, so nothing to do
if (hoverTimer != null)
return;
// Start a timer to delay showing the menu
hoverTimer = async(function() {
hoverTimer = null;
// Only show the menu if this label is still being pointed at
if (categoryBox.hover != categoryNode)
return;
context.openAt(categoryNode);
}, 100);
}
// Handle the mouse moving in or out of the related labels
function onMouse({type, relatedTarget}) {
// Ignore events between the two related labels
if (relatedTarget == categoryNode || relatedTarget == comma)
return;
// Keep track of what is currently being hovered
categoryBox.hover = type == "mouseover" ? categoryNode : null;
// Keep the original look of the hover if the menu is open
if (context.state != "open")
categoryBox.updateLook();
}
categoryNode.addEventListener("click", onClick, false);
categoryNode.addEventListener("mousemove", onMove, false);
categoryNode.addEventListener("mouseout", onMouse, false);
categoryNode.addEventListener("mouseover", onMouse, false);
// Add a comma after each category
let comma = createNode("label");
categoryBox.appendChild(comma);
comma.separator = true;
comma.style.margin = 0;
comma.style.pointerEvents = "auto";
comma.addEventListener("click", onClick, false);
comma.addEventListener("mousemove", onMove, false);
comma.addEventListener("mouseout", onMouse, false);
comma.addEventListener("mouseover", onMouse, false);
// Prepare a popup to show category providers
let context = createNode("menupopup");
categoryNode.context = context;
document.getElementById("mainPopupSet").appendChild(context);
// Add a menuitem that knows how to switch to the provider
providers.forEach(function({icon, name}, index) {
let provider = createNode("menuitem");
provider.setAttribute("class", "menuitem-iconic");
provider.setAttribute("image", icon);
provider.setAttribute("label", name);
context.appendChild(provider);
provider.addEventListener("command", function() {
usage.clickProvider++;
categoryBox.activateAndGo(categoryNode, index);
}, false);
// Prefetch in-case the provider is selected
provider.addEventListener("mouseover", function() {
prefetcher.loadIfSearching(categoryNode, index);
}, false);
return provider;
});
context.appendChild(createNode("menuseparator"));
// Allow switching from text to icons
let switchToIcon = createNode("menuitem");
context.appendChild(switchToIcon);
switchToIcon.setAttribute("label", "Show an icon instead of '" + text + "'");
switchToIcon.addEventListener("command", function() {
switchTo(true);
sendEvent("icon", category);
}, false);
// Allow switching from icons to text
let switchToText = createNode("menuitem");
context.appendChild(switchToText);
switchToText.setAttribute("label", "Show '" + text + "' instead of an icon");
switchToText.addEventListener("command", function() {
switchTo(false);
sendEvent("text", category);
}, false);
// Save the state and update the UI to show icons or text
function switchTo(icon) {
categoryData.showIcon = icon;
switchToIcon.collapsed = icon;
switchToText.collapsed = !icon;
image.collapsed = !icon;
label.collapsed = icon;
fixSeparators();
}
// Hide one of the switch commands depending on if icons are shown
switchTo(categoryData.showIcon);
// Allow the whole category to be hidden from the UI
let hideCategory = createNode("menuitem");
context.appendChild(hideCategory);
hideCategory.setAttribute("label", "Hide this category");
hideCategory.addEventListener("command", function() {
hideShowCategory(true);
sendEvent("hide", category);
}, false);
// Allow the whole category to be restored from the UI
let showCategory = createNode("menuitem");
context.appendChild(showCategory);
showCategory.setAttribute("label", "Show this category");
showCategory.addEventListener("command", function() {
hideShowCategory(false);
sendEvent("show", category);
}, false);
// Save the state and update the UI to hide or show the category
function hideShowCategory(hide) {
categoryData.hidden = hide;
categoryNode.collapsed = hide;
comma.collapsed = hide;
hideCategory.collapsed = hide;
showCategory.collapsed = !hide;
fixSeparators();
}
// Hide the category if necessary
hideShowCategory(categoryData.hidden);
// Allow opening the context under a node
context.openAt = function(node) {
if (isInactive())
return;
if (context.state == "open")
return;
if (category == "go")
return;
context.updateChecked();
context.openPopup(node, "after_start", isMac ? -21 : 0);
};
// Correctly mark which item is the default
context.updateChecked = function() {
let {defaultIndex} = categoryData;
Array.forEach(context.childNodes, function(item, index) {
if (index == defaultIndex)
item.setAttribute("checked", true);
else
item.removeAttribute("checked");
});
};
context.updateChecked();
unload(function() {
context.parentNode.removeChild(context);
});
// Track when the menu disappears to maybe activate
let unOver;
context.addEventListener("popuphiding", function() {
unOver();
// Assume dismiss of the popup by clicking on the label is to activate
if (categoryBox.hover == categoryNode) {
usage.clickCategory++;
categoryBox.activateAndGo(categoryNode);
}
// Make sure the original input is prefetched
else
categoryBox.processInput();
}, false);
// Prepare to dismiss for various reasons
context.addEventListener("popupshowing", function() {
// Automatically hide the popup when pointing away
unOver = listen(window, window, "mouseover", function(event) {
// Allow pointing at the category label
switch (event.originalTarget) {
case categoryNode:
case comma:
return;
}
// Allow pointing at the menu
let {target} = event;
if (target == context)
return;
// And the menu items
if (target.parentNode == context)
return;
// Must have pointed away allowed items, so dismiss
context.hidePopup();
});
// Prefetch in preparation of a click on the label to dismiss
prefetcher.loadIfSearching(categoryNode);
}, false);
return categoryNode;
}
// Add each category to the UI and remember some special categories
allProviders.forEach(addCategory);
let goCategory = categoryBox.firstChild;
let searchCategory = goCategory.nextSibling.nextSibling;
categoryBox.lastChild.setAttribute("value", ".");
// Make sure every separator is a comma except the last visible one
function fixSeparators() {
let lastSeparator;
Array.forEach(categoryBox.childNodes, function(node) {
if (node.collapsed || !node.separator)
return;
// Put a comma after a text category, otherwise just a space
let {showIcon} = node.previousSibling.categoryData;
node.setAttribute("value", showIcon ? " " : ", ");
lastSeparator = node;
});
// If we have a visible last separator, make it a period
if (lastSeparator != null)
lastSeparator.setAttribute("value", ".");
}
fixSeparators();
// For now hide the go category
goCategory.setAttribute("collapsed", true);
goCategory.nextSibling.setAttribute("collapsed", true);
// Copy most of the original input field
let hdInput = origInput.cloneNode(false);
urlbarStack.insertBefore(hdInput, categoryBox);
// Hide the original input
change(origInput.style, "maxWidth", 0);
change(origInput.style, "overflow", "hidden");
hdInput.removeAttribute("onblur");
hdInput.removeAttribute("onfocus");
hdInput.removeAttribute("placeholder");
hdInput.addEventListener("blur", function() {
let url = getURI().spec;
if (hdInput.value == url) {
hdInput.value = "";
categoryBox.processInput();
}
else
categoryBox.updateLook();
// Make sure revert various state to get the right page proxy state
gBrowser.userTypedValue = null;
window.URLBarSetURI();
}, false);
hdInput.addEventListener("click", function() {
categoryBox.checkSelection();
}, false);
hdInput.addEventListener("focus", function() {
gURLBar.setAttribute("focused", true);
categoryBox.processInput();
}, false);
// Watch for inputs to handle from keyboard and from other add-ons
hdInput.addEventListener("input", function() {
// Don't try suggesting a keyword when the user wants to delete
if (deleting) {
deleting = false;
return;
}
// Copy over the new value and selection if it changed while not searching
let {HDlastValue, selectionEnd, selectionStart, value} = origInput;
if (HDlastValue != value) {
hdInput.value = value;
hdInput.setSelectionRange(selectionStart, selectionEnd);
}
categoryBox.processInput();
suggestCategory();
}, false);
// Allow escaping out of the input
hdInput.addEventListener("keydown", function(event) {
if (event.keyCode != event.DOM_VK_ESCAPE)
return;
// Keep the focus in the input box instead of blurring
event.preventDefault();
// Return focus to the browser if already empty
if (hdInput.value == "")
gBrowser.selectedBrowser.focus();
// Empty out the input on first escape
else {
hdInput.value = "";
categoryBox.processInput();
}
}, false);
// Detect cursor movements to auto-select the keyword
hdInput.addEventListener("keypress", function(event) {