Skip to content

Instantly share code, notes, and snippets.

@kt0
Last active May 13, 2020 21:37
Show Gist options
  • Save kt0/bf9ccfd11979b77cab06 to your computer and use it in GitHub Desktop.
Save kt0/bf9ccfd11979b77cab06 to your computer and use it in GitHub Desktop.
TweetDeck autortl
// ==UserScript==
// @name TweetDeck RTL checker
// @namespace http://twitter.com/keykakito
// @description TweetDeck RTL checker
// @include https://tweetdeck.twitter.com/
// @version 0.2
// @grant none
// ==/UserScript==
(function() {
var charsRegexp = /[\u0590-\u083F]|[\u08A0-\u08FF]|[\uFB1D-\uFDFF]|[\uFE70-\uFEFF]/mg,
urlRegexp = /(https?|ftp):\/\/[^\s\/$.?#].[^\s]*/gi,
mentionRegexp = /(\s|^)(@[a-zA-Z][a-zA-Z0-9_]{3,21})/g;
function isRTL(originalText){
var start, text, treshold, match;
if (!originalText) return false;
text = originalText.replace(mentionRegexp, '').replace(urlRegexp, '')
start = text.search(charsRegexp);
if (start === -1) return false;
match = text.match(charsRegexp);
treshold = text.search(charsRegexp) === 0 ? 5 : 2
return match && match.length >= text.length / treshold
};
function nodeCheck(tweet) {
if ( isRTL(tweet.textContent) ) {
tweet.classList.add('tweet-text-rtl')
}
tweet.setAttribute('data-checked', true)
}
var arrEach = Array.prototype.forEach
function each(arr, method) { arrEach.call(arr, method) }
function query(q) {return document.querySelectorAll(q) }
/* http://davidwalsh.name/javascript-debounce-function */
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function checkRtlText() {
this.style.direction = isRTL(this.value) ? 'rtl' : 'ltr'
}
function checkRtl(box) {
box.addEventListener('keyup', debounce(checkRtlText.bind(box), 100), true)
box.setAttribute('data-checked', true)
}
function timeoutCheck(){
each(query('.js-tweet-text:not([data-checked]),.js-quoted-tweet-text:not([data-checked])'), nodeCheck)
each(query('.compose-text:not([data-checked])'), checkRtl)
}
function check() {
setTimeout(timeoutCheck, 4)
}
(function(css) {
var style;
style = document.createElement('style');
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
})('.tweet-text-rtl{ direction:rtl; text-align:right;} .link-complex {direction: ltr !important; unicode-bidi:embed;}')
document.addEventListener("DOMNodeInserted", check, true);
check()
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment