-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathWordHighlightToolbar.uc.js
1148 lines (1084 loc) · 38 KB
/
WordHighlightToolbar.uc.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
// ==UserScript==
// @name WordHighlightToolbar.uc.js
// @description word highlight toolbar.
// @namespace http://d.hatena.ne.jp/Griever/
// @author Griever
// @license MIT License
// @compatibility Firefox 17
// @charset UTF-8
// @include main
// @version 0.0.7
// @note 增加延迟及 super_preloader 加载下一页高亮的支持 By ywzhaiqi
// @note 0.0.7 ツールバーが自動で消えないことがあったのを修正
// @note 0.0.6 アイコンを作って検索時の強調を ON/OFF できるようにした
// @note 0.0.6 背面のタブを複数開いた際の引き継ぎを修正
// @note 0.0.5 大幅に変更(変更し過ぎてどこを変更したのかすら忘れた)
// @note 0.0.5 外部からイベントでハイライトできるようにした
// @note 0.0.5 "戻る"動作にツールバーが連動するようにした
// @note 0.0.5 色を選んで強調できるようにしてみた
// @note 0.0.5 ツールバーが無駄にスペースをとる場合があるのを修正
// @note 0.0.5
// ==/UserScript==
(function(CSS){
"use strict";
if (window.gWHT) {
window.gWHT.destroy();
delete window.gWHT;
}
const UID = Math.random().toString(36).slice(-8);
const PREFIX = 'wordhighlight-toolbar-';
const CLASS_ICON = PREFIX + 'icon';
const CLASS_ITEM = PREFIX + 'item';
const CLASS_SPAN = PREFIX + 'span';
const CLASS_INDEX = PREFIX + 'index';
const EVENT_RESPONSE = 'RESPONSE_' + UID;
var GET_KEYWORD = true;
var enableBooklink = true; // 来自 booklink.me 的百度搜索不要高亮。
var wmap = new WeakMap();
window.gWHT = {
DEBUG: false,
SITEINFO: [
/**
url URL。正規表現。keyword, input が無い場合は $1 がキーワードになる。
keyword キーワード。スペース区切り。省略可。
input 検索ボックスの CSS Selector。
**/
{
url: '^https?://\\w+\\.google\\.[a-z.]+/search',
input: 'input[name="q"]'
},
{
url: '^http?://[\\w.]+\\.yahoo\\.co\\.jp/search',
input: 'input[name="p"]'
},
{
url: '^https?://\\w+\\.bing\\.com/search',
input: 'input[name="q"]'
},
{
url: '^http://[\\w.]+\\.nicovideo\\.jp/(?:search|tag)/.*',
input: '#search_united, #bar_search'
},
//百度
{
url: '^https?://\\w+\\.baidu\\.com/(?:s|baidu)\\?',
input: 'input[name="wd"]'
},
//DuckDuckGo
{
url: '^https?://duckduckgo\\.com/',
input: 'input[name="q"]'
},
{
url: '^https?://developer\\.mozilla\\.org/.*/search',
input: 'input[name="q"][value]'
},
// {// MICROFORMAT
// url: '^https?://.*[?&](?:q|word|keyword|search|query|search_query)=([^&]+)',
// input: 'input[type="text"]:-moz-any([name="q"],[name="word"],[name="keyword"],[name="search"],[name="query"],[name="search_query"]), input[type="search"]'
// },
],
FIND_FOUND : 0,
FIND_NOTFOUND: 1,
FIND_WRAPPED : 2,
sound: Cc["@mozilla.org/sound;1"].createInstance(Ci.nsISound),
getWins: getWins,
checkDoc: checkDoc,
getFocusedWindow: getFocusedWindow,
getRangeAll: getRangeAll,
wmap:wmap,
tabhistory: {},
get prefs() {
delete this.prefs;
return this.prefs = Services.prefs.getBranch("WordHighlightToolbar.");
},
get GET_KEYWORD() GET_KEYWORD,
set GET_KEYWORD(bool) {
bool = !!bool;
var icon = $(PREFIX + "icon");
if (icon) {
icon.setAttribute("state", bool ? "enable" : "disable");
icon.setAttribute("tooltiptext", bool ? "\u5F00\u542F" : "\u5173\u95ED");
}
return GET_KEYWORD = bool;
},
init: function() {
this.xulstyle = addStyle(CSS);
/*
var icon = $("urlbar-icons").appendChild(document.createElement("image"));
icon.setAttribute("id", PREFIX + "icon");
icon.setAttribute("class", PREFIX + "icon");
icon.setAttribute("onclick", "gWHT.GET_KEYWORD = !gWHT.GET_KEYWORD");
icon.setAttribute("context", "");
icon.setAttribute("style", "padding: 0px 2px;");
*/
var bb = document.getElementById("appcontent");
var container = bb.appendChild(document.createElement("hbox"));
container.setAttribute("id", PREFIX + "box");
container.setAttribute("style", "max-height: 24px;");
//container.setAttribute("ordinal", "0");
this.container = container;
var sep = document.getElementById("context-viewpartialsource-selection");
var menu = sep.parentNode.insertBefore(document.createElement("menu"), sep);
menu.setAttribute("label", "\u9AD8\u4EAE\u5173\u952E\u8BCD");//ハイライト
menu.setAttribute("id", PREFIX + "highlight");
menu.setAttribute("class", CLASS_ICON + " menu-iconic");
menu.setAttribute("accesskey", "H");
menu.setAttribute("onclick", "\
if (event.target != this) return;\
closeMenus(this);\
if (event.button === 0) gWHT.highlightWord();\
else if (event.button === 1) gWHT.highlightWordAuto();\
");
var menupopup = menu.appendChild(document.createElement("menupopup"));
var menuitem = menupopup.appendChild(document.createElement("menuitem"));
menuitem.setAttribute("class", CLASS_ICON + " menuitem-iconic");
menuitem.setAttribute("label", "\u9AD8\u4EAE"); //ハイライト
menuitem.setAttribute("accesskey", "H");
menuitem.setAttribute("oncommand", "gWHT.highlightWord();");
var menuitem = menupopup.appendChild(document.createElement("menuitem"));
menuitem.setAttribute("class", CLASS_ICON + " menuitem-iconic");
menuitem.setAttribute("label", "\u5206\u8272\u9AD8\u4EAE\u4E0D\u540C\u5173\u952E\u8BCD");//単語を探してハイライト
menuitem.setAttribute("oncommand", "gWHT.highlightWordAuto();");
var cp = menupopup.appendChild(document.createElement("colorpicker"));
cp.setAttribute("onclick", "\
closeMenus(this);\
var word = getBrowserSelection();\
setTimeout(function(){\
gWHT.addWord({ word: word, bgcolor: this.color, bold: true });\
}.bind(this), 10);\
");
try {
this.GET_KEYWORD = this.prefs.getBoolPref("GET_KEYWORD");
} catch (e) {
this.GET_KEYWORD = GET_KEYWORD;
}
gBrowser.mPanelContainer.addEventListener("DOMContentLoaded", this, false);
// gBrowser.mPanelContainer.addEventListener("click", this, false);
// gBrowser.mPanelContainer.addEventListener("dragend", this, false);
gBrowser.mPanelContainer.addEventListener("pageshow", this, false);
gBrowser.mPanelContainer.addEventListener(EVENT_RESPONSE, this, true);
gBrowser.mPanelContainer.addEventListener("WordHighlightToolbarAddWord", this, false, true);
gBrowser.mPanelContainer.addEventListener("WordHighlightToolbarRemoveWord", this, false, true);
gBrowser.mTabContainer.addEventListener("TabOpen", this, false);
gBrowser.mTabContainer.addEventListener("TabSelect", this, false);
gBrowser.mTabContainer.addEventListener("TabClose", this, false);
document.getElementById("contentAreaContextMenu").addEventListener("popupshowing", this, false);
window.addEventListener("unload", this, false);
},
uninit: function() {
gBrowser.mPanelContainer.removeEventListener("DOMContentLoaded", this, false);
// gBrowser.mPanelContainer.removeEventListener("click", this, false);
// gBrowser.mPanelContainer.removeEventListener("dragend", this, false);
gBrowser.mPanelContainer.removeEventListener("pageshow", this, false);
gBrowser.mPanelContainer.removeEventListener(EVENT_RESPONSE, this, true);
gBrowser.mPanelContainer.removeEventListener("WordHighlightToolbarAddWord", this, false);
gBrowser.mPanelContainer.removeEventListener("WordHighlightToolbarRemoveWord", this, false);
gBrowser.mTabContainer.removeEventListener("TabOpen", this, false);
gBrowser.mTabContainer.removeEventListener("TabSelect", this, false);
gBrowser.mTabContainer.removeEventListener("TabClose", this, false);
document.getElementById("contentAreaContextMenu").removeEventListener("popupshowing", this, false);
window.removeEventListener("unload", this, false);
this.prefs.setBoolPref("GET_KEYWORD", this.GET_KEYWORD);
},
destroy: function() {
[PREFIX + "icon", PREFIX + "box", PREFIX + "highlight"].forEach(function(id){
var elem = $(id);
if (elem) elem.parentNode.removeChild(elem);
}, this);
this.uninit();
if (this.xulstyle) this.xulstyle.parentNode.removeChild(this.xulstyle);
},
handleEvent: function(event) {
switch(event.type) {
case "click":
this.lastClickedTime = new Date().getTime();
break;
case "dragend":
var dt = event.dataTransfer;
if (dt) {
if (dt.types.contains("text/x-moz-place")) return;
if (!dt.types.contains("text/x-moz-url")) return;
}
this.lastClickedTime = new Date().getTime();
break;
case "DOMContentLoaded":
if (!this.GET_KEYWORD) return;
var doc = event.target;
var win = doc.defaultView;
// frame 内では動作しない
if (win != win.parent) return;
// HTMLDocument じゃない場合
if (!checkDoc(doc)) return;
this.delayLaunch(doc, win);
setTimeout(function(self, doc, win){
self.fixAutoPage(doc, win);
}, 1000, this, doc, win)
break;
case "pageshow":
var doc = event.target;
var win = doc.defaultView;
if (win != win.parent) return;
this.updateToolbar( wmap.get(doc) );
break;
case EVENT_RESPONSE:
event.stopPropagation();
this.onResponse(event);
break;
case "WordHighlightToolbarAddWord":
var { target, type, detail } = event;
debug(type, detail);
if (!detail) return;
var doc = target.ownerDocument || target;
var range;
if (doc != target) {
range = doc.createRange();
range.selectNode(target);
}
this.addWord(detail, false, range);
break;
case "WordHighlightToolbarRemoveWord":
var { target, type, detail } = event;
debug(type, detail);
var doc = target.ownerDocument || target;
if (!doc.wht) return;
var words = Array.isArray(detail) ? detail : [detail];
words.forEach(function(word) doc.wht.removeWord(word));
break;
case "TabSelect":
var doc = event.target.linkedBrowser.contentDocument;
var toolbar = wmap.get(doc);
this.updateToolbar(toolbar);
break;
case "TabOpen":
var tab = event.target;
tab.whtOwner = gBrowser.mCurrentTab;
tab.whtTime = new Date().getTime();
break;
case "TabClose":
delete this.tabhistory[event.target.linkedPanel];
break;
case "popupshowing":
if (event.target != event.currentTarget) return;
var {isTextSelected, onTextInput, target} = gContextMenu;
gContextMenu.showItem(PREFIX + "highlight", isTextSelected && !onTextInput);
break;
case "unload":
this.uninit();
break;
}
},
delayLaunch: function(doc, win){
if(enableBooklink && doc.URL.indexOf("baidu.com") > -1 && doc.referrer.indexOf("booklink.me") > -1){
return;
}
var self = this;
var keywords = this.GET_KEYWORD ? this.getKeyword(this.SITEINFO, doc) : [];
var SyntaxHighlighter = win.wrappedJSObject.SyntaxHighlighter;
if(typeof SyntaxHighlighter != "undefined"){
win.addEventListener("load", function(){
setTimeout(function(){
self.launch(doc, keywords);
}, 500);
doc.removeEventListener("load", arguments.callee, false);
}, false);
return;
}
this.launch(doc, keywords);
},
fixAutoPage: function(doc, win){
if(!checkDoc(doc)) return;
var _bodyHeight = doc.body.clientHeight;
// 创建观察者对象
var observer = new win.MutationObserver(function(mutations){
if(mutations[0].addedNodes && doc.body.clientHeight > _bodyHeight){
debug("MutationObserver addedNodes");
_bodyHeight = doc.body.clientHeight;
setTimeout(function(){
gWHT.recoveryToolbar();
}, 200);
}
});
observer.observe(doc, {childList: true, subtree: true});
},
onResponse: function(event) {
var { target, detail: { name, args } } = event;
debug(name, args, target);
var doc = target.ownerDocument || target;
var win = doc.defaultView;
var topWin = win.top;
if ('initialized' === name) {
doc.addEventListener("dragend", this, false);
doc.addEventListener("click", this, false);
var tab = gBrowser._getTabForContentWindow(topWin);
var linkedPanel = tab.linkedPanel;
var { index, count } = tab.linkedBrowser.docShell.sessionHistory;
this.tabhistory[linkedPanel][index] = doc.wht.items;
return;
}
var toolbar = wmap.get(topWin.document);
if (!toolbar) {
toolbar = this.addToolbar();
wmap.set(doc, toolbar);
wmap.set(topWin.document, toolbar);
}
if ('highlight' === name || 'highlightAll' === name) {
var itemArr = args.length > 0 ? args : Object.keys(doc.wht.items).map(function(key) doc.wht.items[key]);
itemArr.forEach(function(item) {
var button = toolbar.querySelector('.' + CLASS_ITEM + '[index="'+ item.index +'"]');
button = this.addButton(toolbar, item, button);
}, this);
this.updateToolbar(toolbar);
return;
}
if ('lowlight' === name) {
var item = args[0];
var button = toolbar.querySelector('.' + CLASS_ITEM + '[index="'+ item.index +'"]');
if (button) {
button.parentNode.removeChild(button);
}
return;
}
if ('lowlightAll' === name) {
var range = document.createRange();
range.selectNodeContents(toolbar.getElementsByTagName('arrowscrollbox')[0]);
range.deleteContents();
//delete this.tabhistory[linkedPanel][index];
return;
}
},
_launch: function(doc, tab) {
if (!tab) {
tab = gBrowser._getTabForContentWindow(doc.defaultView.top);
}
var linkedPanel = tab.linkedPanel;
var { count, index } = tab.linkedBrowser.docShell.sessionHistory;
var tabhis = this.tabhistory[linkedPanel] || (this.tabhistory[linkedPanel] = []);
if (!doc.wht) {
doc.wht = new this.ContentClass(doc);
tabhis[index] = doc.wht.items;
if (tabhis.length > count) {
tabhis.splice(count);
}
}
},
launch: function(doc, keywords) {
var win = doc.defaultView;
var tab = gBrowser._getTabForContentWindow(win.top);
var linkedPanel = tab.linkedPanel;
// loadType 1=Bookmark, 2=Reload, 4=History, 4>other
var { loadType, sessionHistory: { count, index } } = tab.linkedBrowser.docShell;
var tabhis = this.tabhistory[linkedPanel] || (this.tabhistory[linkedPanel] = []);
var newtabflag = (tab.whtTime || Infinity) - this.lastClickedTime < 250; // newtab from user.
tab.whtTime = Infinity;
keywords || (keywords = []);
let hikitugi = [];
let hiki_for_items = function(items, boldOnly) {
Object.keys(items).map(function(key) {
var item = items[key];
if (boldOnly && !item.bold) return;
hikitugi.push({
word: item.word,
//index: item.index,
bgcolor: item.bgcolor,
fgcolor: item.fgcolor,
bold: item.bold,
});
})
}
if (newtabflag) { // newtab from user.
if (tab.whtOwner) {
let ownhis = this.tabhistory[tab.whtOwner.linkedPanel];
if (ownhis) {
let items = ownhis[tab.whtOwner.linkedBrowser.docShell.sessionHistory.index];
if (items) {
hiki_for_items(items, keywords.length > 0);
}
}
}
tab.whtOwner = null;
} else if (loadType === 2) { // reload
var items = tabhis[index];
if (items) {
hiki_for_items(items, keywords.length > 0);
}
} else if (loadType > 1) { // currenttab for user
var items = tabhis[index-1] || tabhis[index];
if (items) {
hiki_for_items(items, keywords.length > 0);
}
}
// debug([doc.URL + '\n'
// ,'loadType:' + loadType,'newtabflag:' + newtabflag
// ,'keywords:[' + keywords + ']'
// ,'hikitugi:[' + hikitugi.map(function(o) o.word) + ']'
// ].join(', '));
if (keywords.length || hikitugi.length) {
this._launch(doc, tab);
doc.wht.addWord(keywords.concat(hikitugi));
}
},
launchFrame: function(doc) {
},
updateToolbar: function(toolbar) {
if (this.updateTimer) clearTimeout(this.updateTimer);
this.updateTimer = setTimeout(function() {
var toolbar = toolbar || wmap.get(content.document);
if (toolbar && toolbar.parentNode) {
return;
}
var range = document.createRange();
range.selectNodeContents(this.container);
if (toolbar) {
range.collapse(true);
range.insertNode(toolbar);
range.selectNodeContents(this.container);
range.setStartAfter(toolbar);
}
range.deleteContents();
}.bind(this), 150);
},
updateToolbar_: function(toolbar) {
if (toolbar && toolbar.parentNode) {
return;
}
var range = document.createRange();
range.selectNodeContents(this.container);
range.deleteContents();
if (toolbar)
range.insertNode(toolbar);
},
addToolbar: function() {
var toolbar = document.createElement("hbox");
toolbar.setAttribute("class", PREFIX + "toolbar");
toolbar.setAttribute("flex", "1");
var box = toolbar.appendChild(document.createElement("arrowscrollbox"));
box.setAttribute("class", PREFIX + "arrowscrollbox");
box.setAttribute("flex", "1");
box.setAttribute("orient", "horizontal");
box.setAttribute("ordinal", "5");
var closebutton = toolbar.appendChild(document.createElement("toolbarbutton"));
closebutton.setAttribute("class", PREFIX + "closebutton tabs-closebutton");
closebutton.setAttribute("oncommand", "gWHT.destroyToolbar();");
closebutton.setAttribute("ordinal", "1");
var reloadbutton = toolbar.appendChild(document.createElement("toolbarbutton"));
reloadbutton.setAttribute("class", PREFIX + "reloadbutton");
reloadbutton.setAttribute("tooltiptext", "\u5237\u65B0");//ワードをハイライトし直す
reloadbutton.setAttribute("ordinal", "10");
reloadbutton.setAttribute("oncommand", "gWHT.recoveryToolbar();");
var addbutton = toolbar.appendChild(document.createElement("toolbarbutton"));
addbutton.setAttribute("class", PREFIX + "addbutton");
addbutton.setAttribute("tooltiptext", "\u6DFB\u52A0\u5173\u952E\u8BCD");//ワードを追加
addbutton.setAttribute("ordinal", "10");
addbutton.setAttribute("oncommand", "gWHT.addWord();");
return toolbar;
},
destroyToolbar: function() {
var win = getFocusedWindow();
var doc = win.document;
if (doc.wht) {
doc.wht.lowlightAll();
}
this.updateToolbar();
},
recoveryToolbar: function() {
var win = getFocusedWindow();
var doc = win.document;
if (doc.wht) {
doc.wht.highlightAll();
// マッチしなかったワードを削除
Object.keys(doc.wht.items).forEach(function(key){
var item = doc.wht.items[key];
if (item.length === 0)
doc.wht.removeWord(item.word);
}, this);
}
},
addButton: function(toolbar, aItem, aButton) {
var button = aButton;
if (!button) {
button = document.createElement('toolbarbutton');
button.style.setProperty('-moz-appearance', 'none', 'important');
button.setAttribute('oncommand', 'gWHT.find(this.getAttribute("word"), event.shiftKey);');
button.setAttribute('onDOMMouseScroll', 'event.stopPropagation(); gWHT.find(this.getAttribute("word"), event.detail < 0);');
button.setAttribute('onclick', 'if (event.button != 1) return; this.hidden = true; gWHT.removeWord(this.getAttribute("word"));');
button.setAttribute('class', CLASS_ITEM);
button.setAttribute('tooltiptext', [
'\u5355\u51FB/\u6EDA\u8F6E\u5411\u4E0B - \u8F6C\u5230\u4E0B\u4E00\u4E2A\u9AD8\u4EAE\u5904',//クリック or ホイールダウンで次を検索
'Shift+\u5355\u51FB/\u6EDA\u8F6E\u5411\u4E0A - \u8F6C\u5230\u4E0A\u4E00\u4E2A',//Shift+クリック or ホイールアップで前を検索
'\u4E2D\u952E\u5355\u51FB - \u53D6\u6D88\u9AD8\u4EAE\u6548\u679C'].join('\n'));//ホイールクリックで削除
toolbar.getElementsByTagName('arrowscrollbox')[0].appendChild(button);
}
button.style.setProperty('color', aItem.fgcolor, 'important');
button.style.setProperty('background-color', aItem.bgcolor, 'important');
button.setAttribute('word', aItem.word);
button.setAttribute('index', aItem.index);
button.setAttribute('bgcolor', aItem.bgcolor);
button.setAttribute('fgcolor', aItem.fgcolor);
button.setAttribute('length', aItem.length);
button.setAttribute('label', aItem.word + '(' + aItem.length + ')');
button.setAttribute('hidden', 'false');
if (aItem.bold) {
button.setAttribute('bold', aItem.bold);
button.style.setProperty('font-weight', 'bold', 'important');
} else {
button.style.removeProperty('font-weight');
}
return button;
},
highlightWord: function() {
var keywords = getRangeAll().map(function(r) r.toString());
if (keywords.length)
this.addWord(keywords, true);
},
highlightWordAuto: function() {
var keywords = getRangeAll().join(' ').match(this.tangoReg) || [];
if (keywords.length)
this.addWord(keywords, true);
},
addWord: function(aWord, aBold, aRange) {
if (!aWord) {
aWord = prompt('', getBrowserSelection());
aBold = true;
}
if (!aWord) return;
var keywords = Array.isArray(aWord) ? aWord : [aWord];
var doc, win;
if (aRange) {
doc = aRange.startContainer.ownerDocument;
win = doc.defaultView;
} else {
win = getFocusedWindow();
doc = win.document;
}
if (!doc.wht) {
win.getSelection().removeAllRanges();
this._launch(doc);
}
keywords = keywords.map(function(str){
return typeof str === "string" ? str.trim() : str;
});
doc.wht.addWord(keywords, aBold, aRange);
},
removeWord: function(aWord) {
if (!aWord) return;
var doc = getFocusedWindow().document;
if (!doc.wht) return;
doc.wht.removeWord(aWord);
},
getLength: function(aWord, aWin) {
var w = aWord.toLowerCase();
var len = 0;
getWins(aWin).forEach(function(win) {
var doc = win.document;
if (!doc.wht) return;
var item = doc.wht.items[w];
if (item)
len += item.length;
}, this);
return len;
},
get tangoReg() {
if (this._tangoReg) return this._tangoReg;
var arr = [
"[\\u4E00-\\u9FA0]{2,}" // 漢字
,"[\\u4E00-\\u9FA0][\\u3040-\\u309F]+" // 漢字1文字+ひらがな
,"[\\u30A0-\\u30FA\\u30FC]{2,}" // カタカナ
,"[\\uFF41-\\uFF5A\\uFF21-\\uFF3A\\uFF10-\\uFF19]{2,}" // 全角英数数字(小文字、大文字、数字)
,"[\\w%$\\@#+]{5,}"
,"\\d[\\d.,]+"
,"\\w[\\w.]+"
];
return this._tangoReg = new RegExp(arr.join('|'), 'g');
},
get kukuriReg() {
if (this._kukuriReg) return this._kukuriReg;
var obj = {
'"': '"',
"'": "'",
'\uFF3B': '\uFF3D',//[]
'\u3010': '\u3011',//【】
'\u300E': '\u300F',//『』
'\uFF08': '\uFF09',//()
'\u201D': '\u201D',// ””
'\u2019': '\u2019',// ’’
};
var arr = Object.keys(obj).map(function(key) '\\' + key + '[^\\n\\'+ obj[key] +']{2,}\\' + obj[key]);
return this._kukuriReg = new RegExp(arr.join('|'), 'g');
},
getKeyword: function (list, aDoc) {
if (!list) list = this.SITEINFO;
var locationHref = aDoc.location.href;
for (let [index, info] in Iterator(list)) {
try {
var exp = info.url_regexp || (info.url_regexp = new RegExp(info.url));
if ( !exp.test(locationHref) ) continue;
if (info.keyword)
return Array.isArray(info.keyword) ? info.keyword : info.keyword.split(/\s+/);
if (info.input) {
var input = aDoc.querySelector(info.input);
if (input && input.value && /\S/.test(input.value))
return this.clean(input.value);
} else if (RegExp.$1) {
try {
return this.clean(decodeURIComponent(RegExp.$1));
} catch (e) {}
return this.clean(RegExp.$1);
}
} catch(e) {
log('error at ' + e);
}
}
return [];
},
clean: function clean(str) {
var res = [];
var kukuri = str.match(this.kukuriReg);
if (kukuri) {
[].push.apply(res, kukuri.map(function(w) w.slice(1,-1)));
str = str.replace(this.kukuriReg, ' ');
}
str = str.replace(/\b(?:(?:all)?(?:inurl|inanchor)|link|cache|related|info|site|filetype|daterange|movie|weather|blogurl):\S*/g, "");
str = str.replace(/\b(?:AND|OR)\b|\s\-\S+/g, " ")
str = str.replace(/(?:all)?(?:intitle|intext):/g, " ");
//str = (' ' + str + ' ').replace(/\s\-\S+|(?:(?:all)?(?:inurl|intitle|intext|inanchor)|link|cache|related|info|site|filetype|daterange|movie|weather|blogurl)\:\S*|\s(?:AND|OR)\s/g, ' ');
// \x20-\x29 !"#$%&'()*+,-./ \x3A-\x40 :;<=>?@ \x5B-\x60 [\]^_` x7B-\x7E {|}~
var tango = str.match(/[^\x20-\x29\x3B-\x3F\x5B-\x5E\x60\x7B-\x7E\s]{2,}/g);
if (tango) {
[].push.apply(res, tango/*.sort(function(a,b) b.length - a.length)*/);
}
return res.filter(function(e,i,a) e && a.indexOf(e) === i);
},
find: function(aWord, isBack) {
var res;
var fastFind = gBrowser.fastFind;
if (fastFind.searchString != aWord) {
res = fastFind.find(aWord, false);
if (isBack) {
res = fastFind.findAgain(isBack, false);
}
} else {
res = fastFind.findAgain(isBack, false);
}
if (res === this.FIND_NOTFOUND)
return this.sound.beep();
if (res === this.FIND_WRAPPED)
this.sound.beep();
var win = fastFind.currentWindow;
if (!win) return;
var sel = win.getSelection();
var node = sel.getRangeAt(0).startContainer;
var span = node.parentNode;
if (!span.classList.contains(CLASS_SPAN)) return;
sel.collapse(node, 1);
span.style.setProperty('outline', '4px solid #36F', 'important');
win.setTimeout(function () {
span.style.removeProperty('outline');
}, 400);
},
};
window.gWHT.ContentClass = function(){ this.init.apply(this, arguments) };
window.gWHT.ContentClass.prototype = {
finder: Cc["@mozilla.org/embedcomp/rangefind;1"].createInstance().QueryInterface(Ci.nsIFind),
styles: [
['hsl( 60, 100%, 80%)','#000'] // bgcolor, textcolor
,['hsl(120, 100%, 80%)','#000']
,['hsl(180, 100%, 80%)','#000']
,['hsl(240, 100%, 80%)','#000']
,['hsl(300, 100%, 80%)','#000']
,['hsl(360, 100%, 80%)','#000']
,['hsl( 30, 100%, 80%)','#000']
,['hsl( 90, 100%, 80%)','#000']
,['hsl(150, 100%, 80%)','#000']
,['hsl(210, 100%, 80%)','#000']
,['hsl(270, 100%, 80%)','#000']
,['hsl(330, 100%, 80%)','#000']
],
css: [
'font: inherit !important;'
,'margin: 0px !important;'
,'padding: 0px !important;'
,'border: none !important;'
,'text-shadow: none !important;'
].join(' '),
throughSelector: ['textarea', 'input', '.' + CLASS_SPAN].map(function(w) w+', '+w+' *').join(','),
init: function(doc, keywords) {
this.doc = doc;
this.win = doc.defaultView;
this.body = doc.body,
this.items = {};
this.finder.findBackwards = false; /* 後ろから前に向かって検索するか */
this.finder.caseSensitive = false; /* 大文字小文字を区別するか */
this.isEmpty = true; // TreeWalker で無駄に探さない為のフラグ
if (keywords) {
this.initItems(keywords);
}
this.doc.addEventListener("keypress", this, false);
this.doc.addEventListener("GM_AutoPagerizeNextPageLoaded", this, false);
this.fireEvent('initialized', this.doc);
},
handleEvent: function(event) {
switch (event.type) {
case "keypress":
if (event.target instanceof HTMLTextAreaElement ||
event.target instanceof HTMLSelectElement ||
event.target instanceof HTMLInputElement && (event.target.mozIsTextField(false)))
return;
var {charCode, ctrlKey, shiftKey, altKey} = event;
if ((charCode === 78 || charCode === 110) && !ctrlKey && !altKey) {
this.find(shiftKey);
event.preventDefault();
event.stopPropagation();
}
break;
case "GM_AutoPagerizeNextPageLoaded":
// AutoPagerizeの最後の区切り以降のRangeを取得
var sep = this.doc.querySelectorAll('.autopagerize_page_separator, .autopagerize_page_info');
sep = sep[sep.length-1];
if (!sep) return;
var range = this.doc.createRange();
if (sep.parentNode.localName == 'td') {
range.setStartAfter(sep.parentNode.parentNode);
range.setEndAfter(sep.parentNode.parentNode.parentNode);
} else {
range.setStartAfter(sep);
range.setEndAfter(sep.parentNode.lastChild);
}
this.highlightAll(range);
break;
}
},
initItem: function(aWord, aBold, aBG, aFG, aIndex) {
if (!aWord) return null;
if (typeof aWord === 'object') {
aBold = aWord.bold;
aBG = aWord.bgcolor;
aFG = aWord.fgcolor;
aIndex = aWord.index;
aWord = aWord.word;
if (!aWord) return null;
}
var w = aWord.toLowerCase();
if (this.items[w]) return null;
var index = typeof aIndex == 'number' && aIndex != NaN ? aIndex : this.newIndexOf();
var [bg, fg] = this.styles[index % this.styles.length];
if (aBG) {
bg = aBG;
fg = aFG || rgb2bw(aBG);
}
var obj = this.items[w] = {
word: aWord,
index: index,
bgcolor: bg,
fgcolor: fg,
bold: !!aBold,
length: 0,
};
Object.defineProperty(obj, 'toString', {
enumerable: false,
value: function() {
return '[' + this.index + ':' + this.length + ':' + this.word + ']';
}
});
return obj;
},
initItems: function(array, aBold) {
return array.map(function(aWord, index) {
return this.initItem(aWord, aBold);
}, this);
},
_highlight: function(aItem, aRange) {
this.finder.findBackwards = false; /* 後ろから前に向かって検索するか */
var doc = this.doc;
var range = aRange;
if (!range) {
range = doc.createRange();
range.selectNodeContents(this.body);
}
var sRange = range.cloneRange();
sRange.collapse(true);
var eRange = range.cloneRange();
eRange.collapse(false);
// タイマーを使わなくて良いおまじない
// http://piro.sakura.ne.jp/latest/blosxom/mozilla/xul/2010-07-06_dynamic.htm
doc.documentElement.clientHeight;
var rangeArr = [];
var len = 0;
for (var retRange = null;
retRange = this.finder.Find(aItem.word, range, sRange, eRange);
sRange = retRange.cloneRange(), sRange.collapse(false)) {
rangeArr[++len] = retRange;
}
if (len > 0) {
var temp = doc.createElementNS("http://www.w3.org/1999/xhtml", "font");
temp.setAttribute("style", this.css +
'background-color: ' + aItem.bgcolor + ' !important;' +
'color: ' + aItem.fgcolor + ' !important;');
temp.setAttribute("class", CLASS_SPAN + ' ' + CLASS_INDEX + aItem.index);
len = 0;
rangeArr.forEach(function(range){
var node = range.startContainer;
if (node.nodeType != 1)
node = node.parentNode;
if (node.mozMatchesSelector(this.throughSelector)) {
if (node.classList.contains( CLASS_INDEX + aItem.index ))
++len;
return;
}
node = range.endContainer;
if (node.nodeType != 1)
node = node.parentNode;
if (node.mozMatchesSelector(this.throughSelector)) {
if (node.classList.contains( CLASS_INDEX + aItem.index ))
++len;
return;
}
var span = temp.cloneNode(false);
try {
range.surroundContents(span);
++len;
return;
} catch (e) {}
try {// 範囲内の要素を細切れにしてでも強調する。行儀が悪い
span.appendChild(range.extractContents());
range.insertNode(span);
++len;
return;
} catch (e) {}
}, this);
}
if (aRange)
aItem.length += len;
else
aItem.length = len;
if (aItem.length)
this.isEmpty = false;
},
_lowlight: function(aItem) {
var doc = this.doc;
$A(doc.getElementsByClassName(CLASS_INDEX + aItem.index)).forEach(function(elem){
var range = doc.createRange();
range.selectNodeContents(elem);
var df = range.extractContents();
range.setStartBefore(elem);
range.insertNode(df);
range.selectNode(elem);
range.deleteContents();
}, this);
aItem.length = 0;
if (Object.keys(this.items).length === 0)
this.isEmpty = true;
},
highlightAll: function(aRange) {
Object.keys(this.items).forEach(function(key){
this._highlight(this.items[key], aRange);
}, this);
this.fireEvent('highlightAll', this.doc);
},
lowlightAll: function() {
var doc = this.doc;
$A(doc.getElementsByClassName(CLASS_SPAN)).forEach(function(elem){
var range = doc.createRange();
range.selectNodeContents(elem);
var df = range.extractContents();
range.setStartBefore(elem);
range.insertNode(df);
range.selectNode(elem);
range.deleteContents();
}, this);
Object.keys(this.items).forEach(function(key){
delete this.items[key];
}, this);
this.isEmpty = true;
this.fireEvent('lowlightAll', this.doc);
},
addWord: function(aWord, aBold, aRange) {
var itemArr = Array.isArray(aWord) ? this.initItems(aWord, aBold) : [this.initItem(aWord, aBold)];
itemArr = itemArr.filter(function(item) {
if (item) {
this._highlight(item, aRange);
return true;
}
}, this);
if (itemArr.length) {
var args = ['highlight', this.doc].concat(itemArr);
this.fireEvent.apply(this, args);
}
},
removeWord: function(aWord) {
var w = aWord.toLowerCase();
var obj = this.items[w];
if (obj) {
this._lowlight(obj);
this.fireEvent('lowlight', this.doc, obj);
}
delete this.items[w];
},
newIndexOf: function() {
// index プロパティの欠番を探す
var arr = [];
Object.keys(this.items).forEach(function(key) arr[this.items[key].index] = true, this);
for (var i = 0, len = arr.length; i < len; i++) {
if (!arr[i]) return i;
};
return arr.length;
},
find: function(isPrev) {
if (this.isEmpty) {
debug('強調されていないようなので検索しません');
return;
}
var tw = this.tw;
if (!tw) {
let fn = function(node) {
if (node.classList.contains(CLASS_SPAN)) {
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_SKIP;
}
tw = this.tw = this.doc.createTreeWalker(this.doc.body, NodeFilter.SHOW_ELEMENT, fn, false);
}
// ツリーの現在地を最後にクリックした位置に合わせる
var sel = this.win.getSelection();
if (sel.focusNode) {
var n = isPrev ? sel.anchorNode : sel.focusNode;
var o = isPrev ? sel.anchorOffset : sel.focusOffset;