-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathhok.ks.js
1473 lines (1201 loc) · 47.4 KB
/
hok.ks.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
// Plugin info {{ =========================================================== //
var PLUGIN_INFO =
<KeySnailPlugin>
<name>HoK</name>
<description>Hit a hint for KeySnail</description>
<description lang="ja">キーボードでリンクを開く</description>
<version>1.4.6</version>
<updateURL>https://github.com/mooz/keysnail/raw/master/plugins/hok.ks.js</updateURL>
<iconURL>https://github.com/mooz/keysnail/raw/master/plugins/icon/hok.icon.png</iconURL>
<author mail="[email protected]" homepage="http://d.hatena.ne.jp/mooz/">mooz</author>
<license>MPL</license>
<minVersion>1.8.0</minVersion>
<include>main</include>
<detail><![CDATA[
=== Usage ===
==== Start HaH ====
Paste code below to your .keysnail.js file.
>|javascript|
key.setViewKey('e', function (aEvent, aArg) {
ext.exec("hok-start-foreground-mode", aArg);
}, 'Hok - Foreground hint mode', true);
key.setViewKey('E', function (aEvent, aArg) {
ext.exec("hok-start-background-mode", aArg);
}, 'HoK - Background hint mode', true);
key.setViewKey(';', function (aEvent, aArg) {
ext.exec("hok-start-extended-mode", aArg);
}, 'HoK - Extented hint mode', true);
key.setViewKey(['C-c', 'C-e'], function (aEvent, aArg) {
ext.exec("hok-start-continuous-mode", aArg);
}, 'Start continuous HaH', true);
key.setViewKey('c', function (aEvent, aArg) {
ext.exec("hok-yank-foreground-mode", aArg);
}, 'Hok - Foreground yank hint mode', true);
||<
In this example, you can start hah by pressing e key in the view mode.
==== Customizing ====
You can change keys for generating hints to paste the code with following form to your .keysnail.js file.
>|javascript|
plugins.options["hok.hint_keys"] = "0123456789";
||<
In this example, you make this plugin to use number keys instead of the alphabets.
Style of the hints can be customized by changing the value of hint_base_style.
>|javascript|
plugins.options["hok.hint_base_style"] = {
"position" : 'absolute',
"z-index" : '2147483647',
"color" : '#000',
"font-family" : 'monospace',
"font-size" : '10pt',
"font-weight" : 'bold',
"line-height" : '10pt',
"padding" : '2px',
"margin" : '0px',
"text-transform" : 'uppercase'
};
||<
Each background color of hints for link, form, focused can be changed by following forms.
>|javascript|
plugins.options["hok.hint_color_link"] = 'rgba(180, 255, 81, 0.7)';
plugins.options["hok.hint_color_form"] = 'rgba(157, 82, 255, 0.7)';
plugins.options["hok.hint_color_focused"] = 'rgba(255, 82, 93, 0.7)';
||<
If you are familiar with the XPath and want this plugin to use arbitrary one, you can set the query.
>|javascript|
plugins.options["hok.selector"] = 'a, textarea, button';
||<
]]></detail>
<detail lang="ja"><![CDATA[
=== 使い方 ===
==== 起動 ====
次のようにして適当なキーへ HoK を割り当てておきましょう。
>|javascript|
key.setViewKey('e', function (aEvent, aArg) {
ext.exec("hok-start-foreground-mode", aArg);
}, 'Hit a Hint を開始', true);
key.setViewKey('E', function (aEvent, aArg) {
ext.exec("hok-start-background-mode", aArg);
}, 'リンクをバックグラウンドで開く Hit a Hint を開始', true);
key.setViewKey(';', function (aEvent, aArg) {
ext.exec("hok-start-extended-mode", aArg);
}, 'HoK - 拡張ヒントモード', true);
key.setViewKey(['C-c', 'C-e'], function (aEvent, aArg) {
ext.exec("hok-start-continuous-mode", aArg);
}, 'リンクを連続して開く Hit a Hint を開始', true);
||<
上記のような設定を .keysnail.js へ記述しておくことにより、ブラウズ画面において e キーを押すことで通常モードの Hit a Hint を開始させることが可能となります。
E を押すことで「タブを背面で開く HaH」を開始させることもできますし、 ; キーを押せば単にリンクをたどるだけでなく、様々なアクションを選ぶことができてしまいます。
ページ内のリンクを一度に開きたいときは hok-start-continuous-mode がきっと役に立つでしょう。一度リンクを開いてもヒントモードが継続されるのです。終了したい時は ESC などのキーを押せば OK です。
==== ポップアップブロックへの対処 ====
HoK でヒントを選択しタブを開こうとしたときポップアップブロックに引っかかってしまうという方は、ロケーションバーに about:config と打ち込んでから dom.popup_allowed_events と入力し、その値に keypress を付け加えてみてください。
==== カスタマイズ ====
ヒントに用いるキーは次のようにして変更することが可能です。
>|javascript|
plugins.options["hok.hint_keys"] = "0123456789";
||<
例えば上記のようなコードを .keysnail.js 内の PRESERVE エリアへ張り付けることで、ヒントに数字キーを使うことが可能となります。
ヒントのスタイルは hint_base_style で設定することが可能です。
>|javascript|
plugins.options["hok.hint_base_style"] = {
"position" : 'absolute',
"z-index" : '2147483647',
"color" : '#000',
"font-family" : 'monospace',
"font-size" : '10pt',
"font-weight" : 'bold',
"line-height" : '10pt',
"padding" : '2px',
"margin" : '0px',
"text-transform" : 'uppercase'
};
||<
ヒントの背景色については hint_color_link, hint_color_form, hint_color_focused の値を変更してください。
>|javascript|
plugins.options["hok.hint_color_link"] = 'rgba(180, 255, 81, 0.9)';
plugins.options["hok.hint_color_form"] = 'rgba(157, 82, 255, 0.9)';
plugins.options["hok.hint_color_candidates"] = 'rgba(240, 82, 93, 0.9)';
plugins.options["hok.hint_color_focused"] = 'rgba(255, 4, 5, 1.0)';
||<
Selectors API を知っていてカスタマイズしたいという方は、次のようにしてヒント取得用のクエリを変更することもできます。
>|javascript|
plugins.options["hok.selector"] = 'a, textarea, button';
||<
=== 拡張ヒントモード ===
次のような設定を .keysnail.js 内に含めておくと、 Vimperator における拡張ヒントモードのようなことを行うことができるようになります。
>|javascript|
key.setViewKey(';', function (aEvent, aArg) {
ext.exec("hok-start-extended-mode", aArg);
}, 'HoK - 拡張ヒントモード', true);
||<
例えばフレームのあるサイトで ; f と入力すれば、そのページ内の任意のフレームへ一発でフォーカスを当てることが出来るようになります。
また ; c と押してからヒントを選択すれば、あたかもその要素の上で右クリックをしたかのような振る舞いをさせることも可能となっています。
それ以外にも様々なアクションが用意されています。拡張ヒントモードで HoK を起動してから TAB を押して、アクションの一覧を確認してみてください。
アクションはユーザが独自に追加することもできます。次のような設定を .keysnail.js 内に張り付けてみてください。
>|javascript|
plugins.options["hok.actions"] = [
['1',
M({ja: "画像の URL をコピー", en: "Copy image's url"}),
function (elem) { command.setClipboardText(elem.src); },
true, false, "img"],
['2',
M({ja: "要素のプロパティを一覧表示", en: "List elements properties"}),
function (elem) { util.listProperty(elem); },
false, true]
];
||<
こうすることにより ; 1 と入力すれば画像にだけヒントがつき、その後選択された画像の src がクリップボードへコピーされるようになります。
ポイントは「アクション毎に Selectros API クエリを設定できる」というところにあります。例えばフレームだけを対象にさせたいのであれば body を設定しておけば良いのですし、画像だけなら img で OK なのです。可能性は無限大ですね。
各アクションは次のような形式となります。
>|javascript|
['キー', '説明', function (elem) { /* elem を使った処理 */ },
/* autoFire を抑制するか */, /* continuous とするか */, 'Selectors API のクエリ']
||<
関数にはヒントを使って選択した要素が渡ります。 elem.href とすればリンクの URL が得られ、 elem.textContent とすればそのリンクのテキストが得られます。画像であれば elem.src としてその URL を得ることも出来ます。
後ろ三つの引数に関しては省略することが可能です。
==== サイト毎にクエリを指定 ====
次のようにして、サイト毎にクエリを追加したり、変更したりすることが可能です。
>|javascript|
plugins.options["hok.local_queries"] = [
["^http://www\\.google\\.(co\\.jp|com)/reader/view/", "*.unselectable, *.link"]
];
||<
こうすることにより、通常は取得できていなかった部分も HoK で選択することができるようになります。
=== 謝辞 ===
このプラグインは以下のブックマークレットと Vimperator の hints.js を参考にして作成されました。
http://d.hatena.ne.jp/Griever/20090223/1235407852
HoK のオリジナル開発者は myuhe さんです。
https://github.com/myuhe
]]></detail>
</KeySnailPlugin>;
// }} ======================================================================= //
// ChangeLog {{ ============================================================= //
//
// ==== 1.2.7 (2011 01/01) ====
//
// * Included very powerful `unique_only` patch from [email protected]
//
// ==== 1.2.5 (2010 02/28) ====
//
// * Made keydown and keypress keys to be prevented (Thx hogelog)
//
// ==== 1.2.4 (2009 11/19) ====
//
// * Made hok export entire context of itself, using __ksSelf__.
//
// ==== 1.2.3 (2009 11/19) ====
//
// * Made user keymap system use keysnails key expression instead of raw keycode.
//
// ==== 1.2.2 (2009 11/17) ====
//
// * Added user keymap system.
//
// ==== 1.2.1 (2009 11/16) ====
//
// * Added site local query system.
//
// ==== 1.2.0 (2009 11/09) ====
//
// * Made HoK use Selectors API again and added XPath option.
//
// ==== 1.1.8 (2009 11/08) ====
//
// * Does not focus when hint keys are inputted.
//
// ==== 1.1.7 (2009 11/08) ====
//
// * Fixed the hints position bug.
// * Made HoK use XPath instead of Selectors API.
//
// ==== 1.1.6 (2009 11/07) ====
//
// * Modified default hint style. Made more elements to be gathered.
//
// ==== 1.1.5 (2009 11/07) ====
//
// * Fixed the silly bug. Images not gathered collectly.
//
// ==== 1.1.4 (2009 11/07) ====
//
// * Made hok immediatly fire When only one hint found.
// * Made hok works correctly in the pages which does not has "document" elemt (like XUL)
// * Added action view source code
// * Refactored the source code
//
// }} ======================================================================= //
// Options {{ =============================================================== //
const pOptions = plugins.setupOptions("hok", {
"hint_keys" : {
preset: 'asdfghjkl',
description: M({
en: "Hints keys (default asdfghjkl)",
ja: "ヒントに使うキー (デフォルトは asdfghjkl)"
}),
type: "string"
},
"unique_fire" : {
preset: true,
description: M({
en: "When current focused hint is unique, auto fire the link or not",
ja: "キーを入力した際、他に候補が無ければ自動的にそのリンクをたどるか (デフォルト: true)"
}),
type: "boolean"
},
"statusbar_feedback" : {
preset: true,
description: M({
en: "Whether display your inputs to the statusbar or not",
ja: "入力したキーをステータスバーへ表示するかどうか (デフォルト: true)"
}),
type: "boolean"
},
"actions" : {
preset: null,
description: M({
en: "Actions for extended hint mode",
ja: "拡張ヒントモード用に独自のアクションを設定"
}),
type: "array"
},
"selector" : {
preset: 'a[href], input:not([type="hidden"]), textarea, iframe, area, select, button, embed,' +
'*[onclick], *[onmouseover], *[onmousedown], *[onmouseup], *[oncommand], *[role="link"], *[role="button"], *[role="menuitem"], *[role="tab"], *[role="checkbox"]',
description: M({
en: "Selectors API Path query",
ja: "ヒントの取得に使う Selectors API クエリ"
}),
type: "string"
},
"local_queries" : {
preset: null,
description: M({
en: "Site local queries",
ja: "サイト毎のクエリ"
}),
type: "array"
},
"hint_color_link" : {
preset: 'rgba(180, 255, 81, 0.90)',
description: M({
en: "Color of the hints for links",
ja: "リンク用ヒントの色"
}),
type: "string"
},
"hint_color_form" : {
preset: 'rgba(155, 174, 255, 0.90)',
description: M({
en: "Color of the hints for forms",
ja: "フォーム用ヒントの色"
}),
type: "string"
},
"hint_color_focused" : {
preset: 'rgba(255, 0, 51, 1.0)',
description: M({
en: "Color of focused hints",
ja: "フォーカスされているヒントの色"
}),
type: "string"
},
"hint_color_candidates" : {
preset: 'rgba(255, 81, 116, 0.90)',
description: M({
en: "Color of candidate hints",
ja: "現在の入力から始まる候補一覧の色"
}),
type: "string"
},
"hide_unmatched_hint" : {
preset: true,
description: M({
en: "Hide unmatched hints or not",
ja: "マッチしないヒントを隠すかどうか"
}),
type: "boolean"
},
"hint_base_style" : {
preset: {
"position" : 'fixed',
"top" : '0',
"left" : '0',
"z-index" : '2147483647',
"color" : '#000',
"font-family" : 'monospace',
"font-size" : '10pt',
"font-weight" : 'bold',
"line-height" : '10pt',
"padding" : '2px',
"margin" : '0px',
"text-transform" : 'uppercase'
},
description: M({
en: "Color of focused hints",
ja: "ヒントのスタイルを設定"
}),
type: "object"
},
"user_keymap" : {
preset: null,
description: M({
en: "Specify user keymap",
ja: "ユーザ定義のキーマップを指定"
}),
type: "object"
},
"unique_only": {
preset: true,
description: M({
en: "Make unique hints only (Free from Enter key)",
ja: "必ずユニークなヒントを生成する (Enter を押す必要が無くなる)"
})
},
"follow_link_nextpattern": {
preset: "\\bnext\\b|\\bnewer\\b|\\bmore\\b|→$|>>$|≫$|»$|^>$|^次|進む|^つぎへ|続"
},
"follow_link_prevpattern": {
preset: "\\bback\\b|\\bprev\\b|\\bprevious\\b|\\bolder|^←|^<<|^≪|^«|^<$|戻る|^もどる|^前.*|^<前"
},
"follow_link_nextrel_selector": {
preset: "a[rel='next']"
},
"follow_link_prevrel_selctor": {
preset: "a[rel='prev']"
},
"follow_link_candidate_selector": {
preset: "a[href], input:not([type='hidden']), button, img[alt]"
}
}, PLUGIN_INFO);
// }} ======================================================================= //
// Misc utils {{ ============================================================ //
// Most functions are borrowed from liberator. Thanks a lot :)
function createMouseEvent(aDocument, aType, aOptions) {
var defaults = {
type : aType,
bubbles : true,
cancelable : true,
view : aDocument.defaultView,
detail : 1,
screenX : 0, screenY : 0,
clientX : 0, clientY : 0,
ctrlKey : false,
altKey : false,
shiftKey : false,
metaKey : false,
button : 0,
relatedTarget : null
};
var event = aDocument.createEvent("MouseEvents");
for (let prop in aOptions)
{
defaults[prop] = aOptions[prop];
}
event.initMouseEvent(
defaults.type,
defaults.bubbles,
defaults.cancelable,
defaults.view,
defaults.detail,
defaults.screenX,
defaults.screenY,
defaults.clientX,
defaults.clientY,
defaults.ctrlKey,
defaults.altKey,
defaults.shiftKey,
defaults.metaKey,
defaults.button,
defaults.relatedTarget
);
return event;
}
const NEW_TAB = 1;
const NEW_BACKGROUND_TAB = 2;
const NEW_WINDOW = 3;
const CURRENT_TAB = 4;
/**
* Fakes a click on a link. from hint.js in liberator
*
* @param {Node} elem The element to click.
* @param {number} where Where to open the link.
*/
function followLink(elem, where) {
let doc = elem.ownerDocument;
let view = doc.defaultView;
let offsetX = 1;
let offsetY = 1;
if (elem instanceof HTMLFrameElement || elem instanceof HTMLIFrameElement)
{
elem.contentWindow.focus();
return;
}
else if (elem instanceof HTMLAreaElement) // for imagemap
{
let coords = elem.getAttribute("coords").split(",");
offsetX = Number(coords[0]) + 1;
offsetY = Number(coords[1]) + 1;
}
let ctrlKey = false, shiftKey = false;
switch (where) {
case NEW_TAB:
case NEW_BACKGROUND_TAB:
ctrlKey = true;
shiftKey = (where != NEW_BACKGROUND_TAB);
break;
case NEW_WINDOW:
shiftKey = true;
break;
case CURRENT_TAB:
break;
default:
display.echoStatusBar("Invalid where argument for followLink()");
}
elem.focus();
// ============================================================ //
try
{
["mousedown", "mouseup", "click"].forEach(
function (event) {
elem.dispatchEvent(
createMouseEvent(doc,
event,
{
screenX: offsetX, screenY: offsetY,
ctrlKey: ctrlKey, shiftKey: shiftKey, metaKey: ctrlKey
}));
});
}
catch (x) {}
}
// Follow previous / next
function followRel(doc, rel, pattern) {
let target = doc.querySelector(rel);
if (target) {
followLink(target, CURRENT_TAB);
return;
}
let relLinkPattern = new RegExp(pattern, "i");
let relLinkCandidates = Array.slice(
doc.querySelectorAll(pOptions["follow_link_candidate_selector"])
);
for (let elem of relLinkCandidates.reverse()) {
if (relLinkPattern.test(elem.textContent) ||
relLinkPattern.test(elem.alt) ||
relLinkPattern.test(elem.title)) {
followLink(elem, CURRENT_TAB);
return;
}
}
}
function openContextMenu(elem) {
document.popupNode = elem;
var menu = document.getElementById("contentAreaContextMenu");
menu.showPopup(elem, -1, -1, "context", "bottomleft", "topleft");
}
function openURI(url, where) {
where = where || CURRENT_TAB;
// decide where to load the first url
switch (where) {
case CURRENT_TAB:
gBrowser.loadURIWithFlags(url, null, null, null, null);
break;
case NEW_BACKGROUND_TAB:
case NEW_TAB:
gBrowser.loadOneTab(url, null, null, null, where == NEW_BACKGROUND_TAB);
break;
}
}
function saveLink(elem, skipPrompt) {
let doc = elem.ownerDocument;
let url = window.makeURLAbsolute(elem.baseURI, elem.href);
let text = elem.textContent;
try {
window.urlSecurityCheck(url, doc.nodePrincipal);
saveURL(url, text, null, true, skipPrompt, makeURI(url, doc.characterSet), doc);
} catch (e) {}
}
function viewSource(url, useExternalEditor) {
url = url || window.content.location.href;
if (useExternalEditor)
{
userscript.editFile(url);
}
else
{
const PREFIX = "view-source:";
if (url.indexOf(PREFIX) == 0)
url = url.substr(PREFIX.length);
else
url = PREFIX + url;
openURI(url);
}
}
// Yank the href of an element
function yank(elem) {
command.setClipboardText(elem.href);
}
function recoverFocus() {
gBrowser.focus();
_content.focus();
}
// }} ======================================================================= //
// HoK object {{ ============================================================ //
var originalSuspendedStatus;
var hok = function () {
var hintKeys = pOptions["hint_keys"];
var hintBaseStyle = pOptions["hint_base_style"];
var hintColorLink = pOptions["hint_color_link"];
var hintColorForm = pOptions["hint_color_form"];
var hintColorFocused = pOptions["hint_color_focused"];
var hintColorCandidates = pOptions["hint_color_candidates"];
var elementColorFocused = pOptions["element_color_focused"];
var keyMap = {};
if (pOptions["user_keymap"])
keyMap = pOptions["user_keymap"];
keyMap["<delete>"] = 'Delete';
keyMap["<backspace>"] = 'Backspace';
keyMap["C-h"] = 'Backspace';
keyMap["RET"] = 'Enter';
keyMap["C-m"] = 'Enter';
var lastFocusedInfo;
// misc options {{ ========================================================== //
var useStatusBarFeedBack = pOptions["statusbar_feedback"];
var supressUniqueFire;
var continuousMode;
// }} ======================================================================= //
var currentAction;
var priorQuery;
var localQuery;
// length of the hint keys like 'asdfghjkl'
var hintKeysLength = null;
var hintContainerId = 'ksHintContainer';
var hintElements = {};
var hintCount;
// unique hint
var hintSpans;
var inputKey = '';
var lastMatchHint = null;
// foo-bar-baz -> fooBarBaz
// -moz-foo-bar-baz -> MozFooBarBaz
function formatPropertyName(name) {
if (!~name.indexOf("-"))
return name;
let ss = name.split("-");
return ss.shift().toLowerCase() +
ss.reduce(function (acc, s) acc + (s ? s[0].toUpperCase() + s.slice(1).toLowerCase() : s), "");
}
// Patches from [email protected]
function createTextHints(amount) {
var reverseHints = {};
var numHints = 0;
var uniqueOnly = pOptions["unique_only"];
function next(hint) {
var l = hint.length;
if (l === 0) {
return hintKeys.charAt(0);
}
var p = hint.substr(0, l - 1);
var n = hintKeys.indexOf(hint.charAt(l - 1)) + 1;
if (n == hintKeysLength) {
var np = next(p);
if (uniqueOnly) {
delete reverseHints[np];
numHints--;
}
return np + hintKeys.charAt(0);
} else {
return p + hintKeys.charAt(n);
}
}
var hint = '';
while (numHints < amount) {
hint = next(hint);
reverseHints[hint] = true;
numHints++;
}
var hints = [];
for (let hint of Object.keys(reverseHints)) {
hints.push(hint);
}
// Note: kind of relies on insertion order
return hints;
}
/**
* Gets the actual offset of an imagemap area. (from liberator)
*
* @param {Object} elem The <area> element.
* @param {number} leftpos The left offset of the image.
* @param {number} toppos The top offset of the image.
* @returns [leftpos, toppos] The updated offsets.
*/
function getAreaOffset(elem, leftpos, toppos)
{
try
{
// Need to add the offset to the area element.
// Always try to find the top-left point, as per liberator default.
let shape = elem.getAttribute("shape").toLowerCase();
let coordstr = elem.getAttribute("coords");
// Technically it should be only commas, but hey
coordstr = coordstr.replace(/\s+[;,]\s+/g, ",").replace(/\s+/g, ",");
let coords = coordstr.split(",").map(Number);
if ((shape == "rect" || shape == "rectangle") && coords.length == 4)
{
leftpos += coords[0];
toppos += coords[1];
}
else if (shape == "circle" && coords.length == 3)
{
leftpos += coords[0] - coords[2] / Math.sqrt(2);
toppos += coords[1] - coords[2] / Math.sqrt(2);
}
else if ((shape == "poly" || shape == "polygon") && coords.length % 2 == 0)
{
let leftbound = Infinity;
let topbound = Infinity;
var i;
// First find the top-left corner of the bounding rectangle (offset from image topleft can be noticably suboptimal)
for (i = 0; i < coords.length; i += 2)
{
leftbound = Math.min(coords[i], leftbound);
topbound = Math.min(coords[i + 1], topbound);
}
let curtop = null;
let curleft = null;
let curdist = Infinity;
// Then find the closest vertex. (we could generalise to nearest point on an edge, but I doubt there is a need)
for (i = 0; i < coords.length; i += 2)
{
let leftoffset = coords[i] - leftbound;
let topoffset = coords[i + 1] - topbound;
let dist = Math.sqrt(leftoffset * leftoffset + topoffset * topoffset);
if (dist < curdist)
{
curdist = dist;
curleft = coords[i];
curtop = coords[i + 1];
}
}
// If we found a satisfactory offset, let's use it.
if (curdist < Infinity)
return [leftpos + curleft, toppos + curtop];
}
} catch (e) {} // badly formed document, or shape == "default" in which case we don't move the hint
return [leftpos, toppos];
}
function getBodyOffsets(body, html, win)
{
// http://d.hatena.ne.jp/edvakf/20100830/1283199419
var style = win.getComputedStyle(body, null),
pos;
if (style && style.position == 'relative') {
var rect = body.getBoundingClientRect();
pos = { x: -rect.left-parseFloat(style.borderLeftWidth), y: -rect.top-parseFloat(style.borderTopWidth) };
} else {
var rect = html.getBoundingClientRect();
pos = { x: -rect.left, y: -rect.top };
}
return [ pos.x, pos.y ];
}
function setHintsText() {
var textHints = createTextHints(hintCount);
for (let i = 0; i < hintCount; i++) {
var span = hintSpans[i];
var hint = textHints[i];
span.appendChild(span.ownerDocument.createTextNode(hint));
hintElements[hint] = span;
}
hintSpans = null;
}
function getBodyForDocument(doc) {
return doc ? doc.body || doc.querySelector("body") || doc.documentElement : null;
}
function drawHints(win) {
var isMain = false;
if (!win) {
isMain = true;
hintSpans = [];
win = window.content;
}
var doc = win.document;
if (!doc)
return;
var html = doc.documentElement;
var body = getBodyForDocument(doc);
if (!body)
{
// process childs only
Array.forEach(win.frames, drawHints);
if (isMain)
setHintsText();
return;
}
var height = win.innerHeight;
var width = win.innerWidth;
var [scrollX, scrollY] = getBodyOffsets(body, html, win);
if (hintBaseStyle.position === "fixed") {
scrollX -= win.scrollX;
scrollY -= win.scrollY;
}
// Arrange hint containers {{ =============================================== //
var fragment = doc.createDocumentFragment();
var hintContainer = doc.createElement('div');
hintContainer.style.position = 'static';
fragment.appendChild(hintContainer);
hintContainer.id = hintContainerId;
// }} ======================================================================= //
// Arrange hints seed {{ ==================================================== //
var hintSpan = doc.createElement('span');
let st = hintSpan.style;
for (let [prop, value] of util.keyValues(hintBaseStyle))
st[formatPropertyName(prop)] = value;
st.backgroundColor = hintColorLink;
// }} ======================================================================= //
var result, elem;
result = doc.querySelectorAll(priorQuery || localQuery || pOptions["selector"]);
var style, rect, hint, span, top, left, ss;
var leftpos, toppos;
for (let i = 0, len = result.length; i < len; ++i) {
elem = result[i];
rect = elem.getClientRects()[0];
if (!rect)
continue;
var r = elem.getBoundingClientRect();
if (!r || r.top > height || r.bottom < 0 || r.left > width || r.right < 0)
continue;
// ========================================================================== //
style = win.getComputedStyle(elem, null);
if (!style || style.visibility !== "visible" || style.display === "none")
continue;
// ========================================================================== //
span = hintSpan.cloneNode(false);
// Set hint position {{ ===================================================== //
leftpos = rect.left > 0 ? rect.left + scrollX : scrollX;
toppos = rect.top > 0 ? rect.top + scrollY : scrollY;
if (elem instanceof HTMLAreaElement)
[leftpos, toppos] = getAreaOffset(elem, leftpos, toppos);
ss = span.style;
ss.left = leftpos + "px";
ss.top = toppos + "px";
// }} ======================================================================= //
if (elem.hasAttribute('href') === false)
ss.backgroundColor = hintColorForm;
span.element = elem;
hintContainer.appendChild(span);
hintSpans.push(span);
hintCount++;
}
if (doc)
body.appendChild(fragment);
Array.forEach(win.frames, drawHints);
if (isMain)
setHintsText();
};
function getHintColor(elem) {
return (elem.hasAttribute('href') === true) ?
hintColorLink : hintColorForm;
}
function getAliveLastMatchHint() {
try {
if (lastMatchHint && lastMatchHint.style)
return lastMatchHint;
} catch (x) {
lastMatchHint = null;
}
return null;
}
function blurHint() {
if (getAliveLastMatchHint())
{