Friday, September 8, 2017

Detecting Twitter's Night Mode

So the Night Mode option in the Twitter mobile application was added to the vastly superior website at some point recently, and I immediately switched over to using it as soon as I became aware of its availability.  However, I quickly noticed that it had a slight flaw I wanted to fix: the remaining character count that shows while you type your meaningless drivel doesn't contrast too well with the background at a certain point (between 20 and 11 characters remaining, inclusive).

Being a web site, this kind of thing should be relatively easy to fix with a user style, right?  Well, it turns out it's not quite that simple.  In their infinite wisdom, Twitter doesn't provide an easy way for CSS to detect that Night Mode is enabled.  Once I discovered that there was no easy way out, my focus shifted to investigating how they do the CSS change.  I arrived at a single line of JavaScript whose result would tell me whether or not Night Mode is enabled.
var isNightMode = ( document.querySelector( 'link[rel="stylesheet"][href*="nightmode"]' ) !== null );
All that remained was to write a user script containing this line of code, and wrap it up with some logic to add a CSS class to the page's body tag.  Along the way, I realized two things and took them into account:
  • The user can toggle Night Mode at any time after the page loads, and the toggle happens asynchronously.
  • The toggle actually happens in two steps behind the scenes, and the visual changes don't happen until the second step.
Basically, my code needed to detect when the user toggles Night Mode on or off, and add or remove the CSS class accordingly (and at the right time).  I've declared the resulting code to be release-worthy and chucked it up on my pastebin.  If you're making your own user style for Twitter, this script will add a CSS class (.night-mode) to the page's body tag, allowing you to easily detect Night Mode from your user style and apply whatever CSS suits your fancy.  If you distribute your user style, don't forget to tell people that they'll need this script for your Night Mode changes to be visible!

No comments:

Post a Comment

I moderate comments because when Blogger originally implemented a spam filter it wouldn't work without comment moderation enabled. So if your comment doesn't show up right away, that would be why.