Skip to content

Instantly share code, notes, and snippets.

@elgreg
Created November 8, 2017 18:42
Show Gist options
  • Save elgreg/50387f1e850306eaf5ca3d444538c64c to your computer and use it in GitHub Desktop.
Save elgreg/50387f1e850306eaf5ca3d444538c64c to your computer and use it in GitHub Desktop.
The contenscript behind the 140 extension for Twitter by Slate
'use strict';
$(document).ready(function(){
var styles = '<style> .twttr140RadialRed { color:red !important; stroke:red !important;} </style>';
$('head').append(styles);
var $tweetModal = $('.modal-tweet-form-container .RichEditor-scrollContainer');
var $homeTimeLine = $('#tweet-box-home-timeline');
var tweetMax = 140;
//binding keyup/down events on the contenteditable div
$tweetModal.on('keyup, keydown', (e) => check_charcount(e, $tweetModal));
$homeTimeLine.on('keyup, keydown', (e) => check_charcount(e, $homeTimeLine));
function check_charcount(e, $el){
// TODO: Allow twitter link rules
console.log(e.which);
if( (
// 0-z and some -+/*
(e.which >= 48 && e.which <= 111) ||
// ;=,-, etc
(e.which >=186 && e.which <= 222) )
&& $el.text().length > tweetMax)
{
// TODO allow copy/paste
e.preventDefault();
$('.js-radial-counter *').addClass('twttr140RadialRed');
// TODO: throb counter
} else {
$('.js-radial-counter *').removeClass('twttr140RadialRed');
}
}
var touched = [];
const getTweetLength = ($el) =>{
// Get total length
let totalLength = $el.text().length;
let links = $el.find('a');
let totalLinks = links.length;
let linksLength = 0;
if(totalLinks > 0){
linksLength = links.text().length;
// Twitter counts links as 23 characters
totalLength = totalLength - linksLength + (23 * totalLinks);
}
return totalLength;
}
// Limit all tweets to first 140 characters, then ellipsis
// TODO: Links should only count as 23 characters
const checkTweets = () => {
$('.tweet-text').each(function(index){
if(touched.includes(this)){
return;
};
let el = $(this);
touched.push(this);
if(getTweetLength(el) > 140){
// el.css({'backgroundColor':'rgba(226,121,177,0.1)'});
var elHtml = el.html();
el.on('click', '.restTweet', (e) => {
el.html(elHtml);
});
el.text(el.text().split('').slice(0,140).join('') + ' ');
el.append('<a class="restTweet" style="color:red">X</a>');
}
});
}
window.setInterval( checkTweets, 2000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment