forked from philc/vimium
-
Notifications
You must be signed in to change notification settings - Fork 1
/
vimiumFrontend.js
563 lines (494 loc) · 18.5 KB
/
vimiumFrontend.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
/*
* This content script takes input from its webpage and executes commands locally on behalf of the background
* page. It must be run prior to domReady so that we perform some operations very early, like setting
* the page's zoom level. We tell the background page that we're in domReady and ready to accept normal
* commands by connectiong to a port named "domReady".
*/
var settings = {};
var settingsToLoad = ["scrollStepSize"];
var getCurrentUrlHandlers = []; // function(url)
var keyCodes = { ESC: 27, backspace: 8, deleteKey: 46, enter: 13, space: 32 };
var insertMode = false;
var findMode = false;
var findModeQuery = "";
var findModeQueryHasResults = false;
var keyPort;
var settingPort;
var saveZoomLevelPort;
// Users can disable Vimium on URL patterns via the settings page.
var isEnabledForUrl = true;
// The user's operating system.
var platform;
var currentCompletionKeys;
// TODO(philc): This should be pulled from the extension's storage when the page loads.
var currentZoomLevel = 100;
// This is a mapping of the incorrect keyIdentifiers generated by Webkit on Windows during keydown events to
// the correct identifiers, which are correctly generated on Mac. We require this mapping to properly handle
// these keys on Windows. See https://bugs.webkit.org/show_bug.cgi?id=19906 for more details.
// TODO(philc): Currently we cannot distinguish between e.g. ",<"; we'll need to look at the keyboard event's
// shift key to do so on Windows.
var keyIdentifierCorrectionMap = {
"U+00C0": "U+0060", // `~
"U+00BD": "U+002D", // -_
"U+00BB": "U+003D", // =+
"U+00DB": "U+005B", // [{
"U+00DD": "U+005D", // ]}
"U+00DC": "U+005C", // \|
"U+00BA": "U+003B", // ;:
"U+00DE": "U+0027", // '"
"U+00BC": "U+002C", // ,<
"U+00BE": "U+002E", // .>
"U+00BF": "U+002F" // /?
};
function getSetting(key) {
if (!settingPort)
settingPort = chrome.extension.connect({ name: "getSetting" });
settingPort.postMessage({ key: key });
}
function setSetting(args) { settings[args.key] = args.value; }
/*
* Complete initialization work that sould be done prior to DOMReady, like setting the page's zoom level.
*/
function initializePreDomReady() {
for (var i in settingsToLoad) { getSetting(settingsToLoad[i]); }
var isEnabledForUrlPort = chrome.extension.connect({ name: "isEnabledForUrl" });
isEnabledForUrlPort.postMessage({ url: window.location.toString() });
var getZoomLevelPort = chrome.extension.connect({ name: "getZoomLevel" });
getZoomLevelPort.postMessage({ domain: window.location.host });
refreshCompletionKeys();
// Send the key to the key handler in the background page.
keyPort = chrome.extension.connect({ name: "keyDown" });
if (navigator.userAgent.indexOf("Mac") != -1)
platform = "Mac";
else if (navigator.userAgent.indexOf("Linux") != -1)
platform = "Linux";
else
platform = "Windows";
chrome.extension.onConnect.addListener(function(port, name) {
if (port.name == "executePageCommand") {
port.onMessage.addListener(function(args) {
if (this[args.command]) {
for (var i = 0; i < args.count; i++) { this[args.command].call(); }
}
refreshCompletionKeys(args.completionKeys);
});
}
else if (port.name == "getScrollPosition") {
port.onMessage.addListener(function(args) {
var scrollPort = chrome.extension.connect({ name: "returnScrollPosition" });
scrollPort.postMessage({
scrollX: window.scrollX,
scrollY: window.scrollY,
currentTab: args.currentTab
});
});
} else if (port.name == "setScrollPosition") {
port.onMessage.addListener(function(args) {
if (args.scrollX > 0 || args.scrollY > 0) { window.scrollBy(args.scrollX, args.scrollY); }
});
} else if (port.name == "returnCurrentTabUrl") {
port.onMessage.addListener(function(args) {
if (getCurrentUrlHandlers.length > 0) { getCurrentUrlHandlers.pop()(args.url); }
});
} else if (port.name == "returnZoomLevel") {
port.onMessage.addListener(function(args) {
currentZoomLevel = args.zoomLevel;
if (isEnabledForUrl)
setPageZoomLevel(currentZoomLevel);
});
} else if (port.name == "returnIsEnabledForUrl") {
port.onMessage.addListener(function(args) {
isEnabledForUrl = args.isEnabledForUrl;
if (isEnabledForUrl)
initializeWhenEnabled();
else if (HUD.isReady())
// Quickly hide any HUD we might already be showing, e.g. if we entered insertMode on page load.
HUD.hide();
});
} else if (port.name == "returnSetting") {
port.onMessage.addListener(setSetting);
} else if (port.name == "refreshCompletionKeys") {
port.onMessage.addListener(function (args) {
refreshCompletionKeys(args.completionKeys);
});
} else if (port.name == "HUD") {
port.onMessage.addListener(function(args) {
if (args.timeout && args.timeout > 0) {
HUD.showForDuration(args.message, args.timeout);
} else {
HUD.show(args.message);
}
});
}
});
}
/*
* This is called once the background page has told us that Vimium should be enabled for the current URL.
*/
function initializeWhenEnabled() {
document.addEventListener("keydown", onKeydown, true);
document.addEventListener("focus", onFocusCapturePhase, true);
document.addEventListener("blur", onBlurCapturePhase, true);
enterInsertModeIfElementIsFocused();
}
/*
* Initialization tasks that must wait for the document to be ready.
*/
function initializeOnDomReady() {
if (isEnabledForUrl)
enterInsertModeIfElementIsFocused();
// Tell the background page we're in the dom ready state.
chrome.extension.connect({ name: "domReady" });
};
/*
* Checks the currently focused element of the document and will enter insert mode if that element is focusable.
*/
function enterInsertModeIfElementIsFocused() {
// Enter insert mode automatically if there's already a text box focused.
// TODO(philc): Consider using document.activeElement here instead.
var focusNode = window.getSelection().focusNode;
var focusOffset = window.getSelection().focusOffset;
if (focusNode && focusOffset && focusNode.children.length > focusOffset &&
isInputOrText(focusNode.children[focusOffset]))
enterInsertMode();
}
/*
* Asks the background page to persist the zoom level for the given domain to localStorage.
*/
function saveZoomLevel(domain, zoomLevel) {
if (!saveZoomLevelPort)
saveZoomLevelPort = chrome.extension.connect({ name: "saveZoomLevel" });
saveZoomLevelPort.postMessage({ domain: domain, zoomLevel: zoomLevel });
}
/*
* Zoom in increments of 20%; this matches chrome's CMD+ and CMD- keystrokes.
* Set the zoom style on documentElement because document.body does not exist pre-page load.
*/
function setPageZoomLevel(zoomLevel, showUINotification) {
document.documentElement.style.zoom = zoomLevel + "%";
if (document.body)
HUD.updatePageZoomLevel(zoomLevel);
if (showUINotification)
HUD.showForDuration("Zoom: " + currentZoomLevel + "%", 1000);
}
function zoomIn() {
setPageZoomLevel(currentZoomLevel += 20, true);
saveZoomLevel(window.location.host, currentZoomLevel);
}
function zoomOut() {
setPageZoomLevel(currentZoomLevel -= 20, true);
saveZoomLevel(window.location.host, currentZoomLevel, showUINotification);
}
function scrollToBottom() { window.scrollTo(0, document.body.scrollHeight); }
function scrollToTop() { window.scrollTo(0, 0); }
function scrollUp() { window.scrollBy(0, -1 * settings["scrollStepSize"]); }
function scrollDown() { window.scrollBy(0, settings["scrollStepSize"]); }
function scrollPageUp() { window.scrollBy(0, -6 * settings["scrollStepSize"]); }
function scrollPageDown() { window.scrollBy(0, 6 * settings["scrollStepSize"]); }
function scrollLeft() { window.scrollBy(-1 * settings["scrollStepSize"], 0); }
function scrollRight() { window.scrollBy(settings["scrollStepSize"], 0); }
function reload() { window.location.reload(); }
function goBack() { history.back(); }
function goForward() { history.forward(); }
function toggleViewSource() {
getCurrentUrlHandlers.push(toggleViewSourceCallback);
var getCurrentUrlPort = chrome.extension.connect({ name: "getCurrentTabUrl" });
getCurrentUrlPort.postMessage({});
}
function copyCurrentUrl() {
getCurrentUrlHandlers.push(function (url) { Clipboard.copy(url); });
// TODO(ilya): Convert to sendRequest.
var getCurrentUrlPort = chrome.extension.connect({ name: "getCurrentTabUrl" });
getCurrentUrlPort.postMessage({});
}
function toggleViewSourceCallback(url) {
if (url.substr(0, 12) == "view-source:")
{
window.location.href = url.substr(12, url.length - 12);
}
else { window.location.href = "view-source:" + url; }
}
/**
* Sends everything except i & ESC to the handler in background_page. i & ESC are special because they control
* insert mode which is local state to the page. The key will be are either a single ascii letter or a
* key-modifier pair, e.g. <c-a> for control a.
*
* Note that some keys will only register keydown events and not keystroke events, e.g. ESC.
*/
function onKeydown(event) {
var keyChar = "";
if (linkHintsModeActivated)
return;
// Ignore modifier keys by themselves.
if (event.keyCode > 31) {
var keyIdentifier = event.keyIdentifier;
// On Windows, the keyIdentifiers for non-letter keys are incorrect. See
// https://bugs.webkit.org/show_bug.cgi?id=19906 for more details.
if (platform == "Windows" || platform == "Linux")
keyIdentifier = keyIdentifierCorrectionMap[keyIdentifier] || keyIdentifier;
unicodeKeyInHex = "0x" + keyIdentifier.substring(2);
keyChar = String.fromCharCode(parseInt(unicodeKeyInHex)).toLowerCase();
// Enter insert mode when the user enables the native find interface.
if (keyChar == "f" && !event.shiftKey && ((platform == "Mac" && event.metaKey) ||
(platform != "Mac" && event.ctrlKey)))
{
enterInsertMode();
return;
}
if (event.shiftKey)
keyChar = keyChar.toUpperCase();
if (event.ctrlKey)
keyChar = "<c-" + keyChar + ">";
if (event.metaKey)
keyChar = null;
}
if (insertMode && event.keyCode == keyCodes.ESC)
{
// Note that we can't programmatically blur out of Flash embeds from Javascript.
if (event.srcElement.tagName != "EMBED") {
// Remove focus so the user can't just get himself back into insert mode by typing in the same input box.
if (isInputOrText(event.srcElement)) { event.srcElement.blur(); }
exitInsertMode();
}
}
else if (findMode)
{
if (event.keyCode == keyCodes.ESC)
exitFindMode();
else if (keyChar)
{
handleKeyCharForFindMode(keyChar);
// Don't let the space scroll us if we're searching.
if (event.keyCode == keyCodes.space)
event.preventDefault();
}
// Don't let backspace take us back in history.
else if (event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey)
{
handleDeleteForFindMode();
event.preventDefault();
}
else if (event.keyCode == keyCodes.enter)
handleEnterForFindMode();
}
else if (!insertMode && !findMode) {
if (keyChar) {
if (currentCompletionKeys.indexOf(keyChar) != -1) {
event.preventDefault();
event.stopPropagation();
}
keyPort.postMessage(keyChar);
}
else if (event.keyCode == keyCodes.ESC) {
keyPort.postMessage("<ESC>");
}
}
}
function refreshCompletionKeys(completionKeys) {
if (completionKeys)
currentCompletionKeys = completionKeys;
else
chrome.extension.sendRequest({handler: "getCompletionKeys"}, function (response) {
currentCompletionKeys = response.completionKeys;
});
}
function onFocusCapturePhase(event) {
if (isFocusable(event.target))
enterInsertMode();
}
function onBlurCapturePhase(event) {
if (isFocusable(event.target))
exitInsertMode();
}
/*
* Returns true if the element is focusable. This includes embeds like Flash, which steal the keybaord focus.
*/
function isFocusable(element) { return isInputOrText(element) || element.tagName == "EMBED"; }
/*
* Input or text elements are considered focusable and able to receieve their own keyboard events,
* and will enter enter mode if focused.
* Note: we used to discriminate for text-only inputs, but this is not accurate since all input fields
* can be controlled via the keyboard, particuarlly SELECT combo boxes.
*/
function isInputOrText(target) {
var focusableInputs = ["input", "textarea", "select", "button"];
return focusableInputs.indexOf(target.tagName.toLowerCase()) >= 0;
}
function enterInsertMode() {
insertMode = true;
HUD.show("Insert mode");
}
function exitInsertMode() {
insertMode = false;
HUD.hide();
}
function handleKeyCharForFindMode(keyChar) {
findModeQuery = findModeQuery + keyChar;
performFindInPlace();
showFindModeHUDForQuery();
}
function handleDeleteForFindMode() {
if (findModeQuery.length == 0)
{
exitFindMode();
performFindInPlace();
}
else
{
findModeQuery = findModeQuery.substring(0, findModeQuery.length - 1);
performFindInPlace();
showFindModeHUDForQuery();
}
}
function handleEnterForFindMode() {
exitFindMode();
performFindInPlace();
}
function performFindInPlace() {
var cachedScrollX = window.scrollX;
var cachedScrollY = window.scrollY;
// Search backwards first to "free up" the current word as eligible for the real forward search. This allows
// us to search in place without jumping around between matches as the query grows.
window.find(findModeQuery, false, true, true, false, true, false);
// We need to restore the scroll position because we might've lost the right position by searching
// backwards.
window.scrollTo(cachedScrollX, cachedScrollY);
performFind();
}
function performFind() {
findModeQueryHasResults = window.find(findModeQuery, false, false, true, false, true, false);
}
function performBackwardsFind() {
findModeQueryHasResults = window.find(findModeQuery, false, true, true, false, true, false);
}
function showFindModeHUDForQuery() {
if (findModeQueryHasResults || findModeQuery.length == 0)
HUD.show("/" + insertSpaces(findModeQuery));
else
HUD.show("/" + insertSpaces(findModeQuery + " (No Matches)"));
}
/*
* We need this so that the find mode HUD doesn't match its own searches.
*/
function insertSpaces(query) {
var newQuery = "";
for (var i = 0; i < query.length; i++)
{
if (query[i] == " " || (i + 1 < query.length && query[i + 1] == " "))
newQuery = newQuery + query[i];
else
newQuery = newQuery + query[i] + "<span style=\"font-size: 0px;\"> </span>";
}
return newQuery;
}
function enterFindMode() {
findModeQuery = "";
findMode = true;
HUD.show("/");
}
function exitFindMode() {
findMode = false;
HUD.hide();
}
/*
* A heads-up-display for showing Vimium page operations.
* Note: you cannot interact with the HUD until document.body is available.
*/
HUD = {
_tweenId: -1,
showForDuration: function(text, duration) {
HUD.show(text);
HUD._showForDurationTimerId = setTimeout(function() { HUD.hide(); }, duration);
},
show: function(text) {
clearTimeout(HUD._showForDurationTimerId);
HUD.displayElement().innerHTML = text;
clearInterval(HUD._tweenId);
HUD._tweenId = Tween.fade(HUD.displayElement(), 1.0, 150);
HUD.displayElement().style.display = "";
},
updatePageZoomLevel: function(pageZoomLevel) {
// Since the chrome HUD does not scale with the page's zoom level, neither will this HUD.
HUD.displayElement().style.zoom = (100.0 / pageZoomLevel) * 100 + "%";
},
/*
* Retrieves the HUD HTML element, creating it if necessary.
*/
displayElement: function() {
if (!HUD._displayElement) {
// This is styled to precisely mimick the chrome HUD. Use the "has_popup_and_link_hud.html" test harness
// to tweak these styles to match Chrome's. One limitation of our HUD display is that it doesn't sit
// on top of horizontal scrollbars like Chrome's HUD does.
var element = document.createElement("div");
with (element.style) {
position = "fixed";
bottom = "0px";
color = "black";
// Keep this far enough to the right so that it doesn't collide with the "popups blocked" chrome HUD.
right = "150px";
height = "13px";
maxWidth = "400px";
minWidth = "150px";
textAlign = "left";
backgroundColor = "#ebebeb";
fontWieght = "normal";
fontSize = "11px";
padding = "3px 3px 2px 3px";
border = "1px solid #b3b3b3";
borderRadius = "4px 4px 0 0";
fontFamily = "Lucida Grande, Arial, Sans";
zIndex = 99999999999;
textShadow = "0px 1px 2px #FFF";
lineHeight = "1.0";
opacity = 0;
}
document.body.appendChild(element);
HUD._displayElement = element
HUD.updatePageZoomLevel(currentZoomLevel);
}
return HUD._displayElement;
},
hide: function() {
clearInterval(HUD._tweenId);
HUD._tweenId = Tween.fade(HUD.displayElement(), 0, 150,
function() { HUD.displayElement().display == "none"; });
},
isReady: function() { return document.body != null; }
};
Tween = {
/*
* Fades an element's alpha. Returns a timer ID which can be used to stop the tween via clearInterval.
*/
fade: function(element, toAlpha, duration, onComplete) {
var state = {};
state.duration = duration;
state.startTime = (new Date()).getTime();
state.from = parseInt(element.style.opacity) || 0;
state.to = toAlpha;
state.onUpdate = function(value) {
element.style.opacity = value;
if (value == state.to && onComplete)
onComplete();
};
state.timerId = setInterval(function() { Tween.performTweenStep(state); }, 50);
return state.timerId;
},
performTweenStep: function(state) {
var elapsed = (new Date()).getTime() - state.startTime;
if (elapsed >= state.duration) {
clearInterval(state.timerId);
state.onUpdate(state.to)
} else {
var value = (elapsed / state.duration) * (state.to - state.from) + state.from;
state.onUpdate(value);
}
}
};
// Prevent our content script from being run on iframes -- only allow it to run on the top level DOM "window".
// TODO(philc): We don't want to process multiple keyhandlers etc. when embedded on a page containing IFrames.
// This should be revisited, because sometimes we *do* want to listen inside of the currently focused iframe.
var isIframe = (window.self != window.parent);
if (!isIframe) {
initializePreDomReady();
window.addEventListener("DOMContentLoaded", initializeOnDomReady);
}