Skip to content

Instantly share code, notes, and snippets.

@ingramchen
Created January 23, 2023 11:44
Show Gist options
  • Save ingramchen/87b5a41aea1aeecd0d6d4f40e8f67cc6 to your computer and use it in GitHub Desktop.
Save ingramchen/87b5a41aea1aeecd0d6d4f40e8f67cc6 to your computer and use it in GitHub Desktop.
tampermonkey ptt hjkl keyboard
// ==UserScript==
// @name ptt hjkl keyboard
// @namespace http://tampermonkey.net/
// @version 0.1
// @description right hand keyboard to navigate term.ptt.cc
// @author Ingram Chen
// @match https://term.ptt.cc/
// @icon https://www.google.com/s2/favicons?sz=64&domain=ptt.cc
// @grant none
// ==/UserScript==
/**
Press x to disable navigation mode
Press Esc to enable navigation mode
Use `:` as help replacement
see handleKeys() for more keymapping, customize for your own needs.
*/
(function() {
'use strict';
function sendKey(key, keyCode) {
let type = "keydown";
if (key.length === 1) {
type = "keypress";
}
window.dispatchEvent(new KeyboardEvent(type, {
keyCode: keyCode,
key: key
}));
//console.debug(event.target);
}
function stopKey(event, key) {
if (event.key === key) {
event.stopPropagation();
event.preventDefault();
console.debug(`stopped ${key}`);
return true;
}
return false;
}
function switchKey(event, fromKey, toKey, toKeyCode) {
if (stopKey(event, fromKey)) {
sendKey(toKey, toKeyCode);
}
}
let triggering = false;
function handleKeys(event) {
try {
if (triggering) {
return;
}
triggering = true;
switchKey(event, 'h', 'ArrowLeft', 37);
switchKey(event, ':', 'h', 72); // `:` replace as help
switchKey(event, '8', 'Home', 36);
switchKey(event, 'i', 'End', 35);
switchKey(event, '9', 'PageUp', 33);
switchKey(event, 'o', 'PageDown', 34);
} finally {
triggering = false;
}
}
let enabled = true;
function handleMode(event) {
if (event.key === 'x') {
//推文開始時關閉
enabled = false;
return;
}
if (event.key === `Escape`) {
//Esc 重新開始
enabled = true;
return;
}
if (!enabled) {
return;
}
handleKeys(event);
}
document.addEventListener("keydown", (event)=> {
handleMode(event);
}, true);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment