Skip to content

Instantly share code, notes, and snippets.

@forabi
Last active April 11, 2016 17:50
Show Gist options
  • Save forabi/b64abbdf4362aed5fd63 to your computer and use it in GitHub Desktop.
Save forabi/b64abbdf4362aed5fd63 to your computer and use it in GitHub Desktop.
Fix text direction for RTL articles on Pocket and file previews on GitHub and GitLab
// ==UserScript==
// @name Auto-RTL
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Fixes layout direction (RTL/LTR) for text on various websites
// @author You
// @match https://gitlab.com/*
// @match https://github.com/*
// @match http*://getpocket.com/beta/read/*
// @match http*://getpocket.com/read/*
// @grant none
// ==/UserScript==
/* jshint -W097 */
'use strict';
(function fixPreviews() {
const rtl = /[\u060C-\u06FE\uFB50-\uFEFC]/gi;
function dir(text, threshold) {
threshold = threshold || 0.2;
const matches = text.match(rtl);
const count = matches ? matches.length : 0;
return count / text.length > threshold ? 'rtl' : 'ltr';
}
const setDir = (node) => {
switch (node.nodeName) {
case 'CODE':
case 'PRE':
node.setAttribute('dir', 'ltr');
break;
default:
var r = dir(node.textContent.substring(0, 100));
node.setAttribute('dir', r);
if (r === 'rtl') {
node.style.textAlign = 'right';
}
return;
}
};
var target = document.body;
var observer = new MutationObserver(function() {
document.querySelectorAll('.file-content.wiki *, .markdown-body *, .reader_content *').forEach(setDir);
});
var config = { attributes: false, childList: true, characterData: true };
observer.observe(target, config);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment