Mohsen Azimi

JavaScript and mobile web

String Direction in JavaScript

My weekend project is a NPM module for detecting text direction in JavaScript. Detecting text direction is useful when we are working with bi-directional(bidi) text or when we have users with different languages using our app.

For example, a textarea element can be smart and changes it’s dir to rtl attribute when it sees right-to-left content in it. This demo in JSBin shows how it can work.

Demo

Using the module is pretty easy. You can either expose getDirection method to String.prototype or use it directly.

Using it directly

1
2
3
4
var stringDirection = require('string-direction');

stringDirection.getDirection("Hello, world!"); // 'ltr'
stringDirection.getDirection("سلام دنیا"); // 'rtl'

Patching String object

1
2
3
4
require('string-direction').patch();

"Hello, world!".getDirection(); // "ltr"
"سلام دنیا".getDirection(); // "rtl"

String Direction module can be used in browser and NodeJS environment. You can find it in NPM registry or in Github.

If you found any issues, please file one in Github.

My JS1K Submission

Submission

Today I’ve submitted my cody to JS1K contest. My submission is a math formula graphing tool that accepts complex math formulas and print it’s graph on a canvas. User can zoom in and out with mouse wheel and also pan with mouse click and drag. Math formulas can get complex with sin, cos, ^, tan, etc.

My submission: Math formula graphing tool

Developer tool

I’ve also created a small tool using Node.js to monitor my JavaScript file length and refresh the browser in the fly on file changes. You can find this tool here at Github.  

How Did I Use Node.js to Remotely Control My Google TV

I have a Google TV which I love it! I can browse web in my TV that is awesome but I don’t really want to interact with my TV, I just want to watch videos on my big screen. I love the fact that I can send YouTube videos to my Google TV. I usually use my laptop when I’m in front of TV and I wanted to send videos from browser to Google TV. I wrote a simple Node.js server to receive videos from browser and send them to Google TV. A Google Chrome extension made it easy to send videos right from right click menu

A web app in Google tv which is a Socket.IO client with a full screen video element receive videos and play them.

I also binded Google TV’s custom buttons (Play, FFW, etc) to video player and now I can easily send videos from my browser to Google TV. Pairing chrome extension and Google TV client is not very user friendly at the moment. It needs a little hacking. As soon as I do final touchups and make it easy to pair I will publish both source code and chrome extension.

Quick Sprite: A Tool for Creating CSS Sprite Images in Browser

Today I am releasing my sprite generator tool that is generating CSS sprite image and it’s CSS code inside the browser. Check it out here

About Sprite Images

CSS sprites help reducing down number of HTTP requests for small images and icons used in a website. The idea of using a sprite image is to use one single image that includes  many small images sitting next to each other in the sprite image. Then we show any individual image sing positioning and cropping techniques in our favorite software. In the web we use CSS top position and crop sprite image in order to show an individual image. We set background image of an element to our sprite image and then set the width, height and position of background to make our desired icon/image visible and rest of sprite image invisible.

Making Sprite Using An Automated Process

Usually web developers use Photoshop to make a sprite image. While using Photoshop do the job it’s slow, expensive and not very scalable. Imagine if you want to make a sprite image from 100 small icons. The other problem with high quantity of images is that developers have to calculate position of each individual icon and then set it in their CSS code. Using an automated process for generating sprite image and also CSS code necessary for that sprite image sounded like a good idea to me so I decided to make the tool for it.

Making sprite image inside the browser

There are some sprite generators that generate sprite images as a web service. None of ones I’ve found generating CSS code for the sprite image and all of them using server side image rendering technology that requires you to upload your images to server  and download the result after server is done with processing.

 Quick Sprite

I made my own sprite builder using HTML5 technologies. This sprite builder doesn’t rely on server side image processing and works all in front end. It also generate CSS code developer may need for it’s sprite. All background-position properties are calculated and there is no need for eyeballing pixels in Photoshop to find out exact position of an icon! It generates width and height and even background-image property for each image. CSS classes are guessed based on each image file name. User can select between camel case and dash separated class names. Using Quick Sprite is very easy, you just drag your images in the app and it generates sprite image and CSS code in a second! You can drag out the result image our download it using the provided download link.

Technology Stack

I’ve used Backbone.js to organize my views and collection. While it wan’t necessary to use Backbone but it helped me to rapidly develop this app. To generate sprite image I used a <canvas> element to draw images on it and take out result from canvas. I’ve used drag and drop API, File Blob, anchor tag download attribute and all good stuff from HTML5.

Browser support

It works perfect in Chrome and Safari but CSS code didn’t show up in when I tried it out in Firefox. I didn’t try it in IE or Opera.

What is next?

CSS code is machine generated and will not be your perfect code to put in production so you may want to edit it. My plan is to use Code Mirror for syntax highlighting and code editing in CSS code block. Making sprite of big images could be slow and app freezes while processing images. It’s because images processing happens in sam thread as DOM (no surprise here!). Solution to this is using Web Workers but problem is I lose DOM in workers. I’m using DOM (canvas) to process images. Right now I am investigating on re-implementing CanvasRenderingContext2D.prototype.drawImage and CanvasRenderingContext2D.prototype.getImageData in a web worker. If I could do that then I can transfer each image binary data individually to worker and let worker combine those into a big ImageData object and transfer it back to original window. This might not be as easy as it looks but is not impossible. Right now the app render images below each other in a very tall and thin sprite (width of sprite is based on widest image). Maybe people want to stack their images in sprite horizontally or like a grid .Actually PNG file size will not change if we stack images differently (say like a grid) but having smaller numbers for background-position is a plus.

The App

Here is the app

Underscore.js Deep Pluck Mixin

pluck() method is a convenience version of a common use case of map() that is fetching a property from a collection. I thought it would be great if we could use pluck() to access deeper objects and properties in a collection and made this mixin that make deep plucking possible:

_.mixin({
    pluck: function(obj, key) {
        if (key.indexOf(".") === -1) {
            return _.map(obj, function(value){ return value[key]; });
        }
        var keys = key.split(".").reverse();
        while(keys.length) {
            obj = _.pluck(obj, keys[keys.length - 1]);
            keys.pop();
        }
        return obj;
    }
});

Now it is easy to pluck a property from a collection that have a deep hierarchy

//Example
var myCollection = [
	{ a: { b: { c: { d: { e: { f: "first"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "second" } } } } } },
	{ a: { b: { c: { d: { e: { f: "third"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "forth"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "fifth"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "sixth"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "seventh"} } } } } },
];

_(myCollection).pluck("a.b.c.d.e.f");
// returns: 
["first", "second", "third", "forth", "fifth", "sixth", "seventh"]

Chrome Developer Tools Dark Theme

Today I have developed a very nice dark theme for Chrome developer tools using CSS filter property. All I did was just adding -webkit-filter: invert(1); to developer tools html tag and some tweaks to make everything looks good. It works very well and make every page in dev tools dark.

You can find code on Github and here are some screenshots.

Windows 8 “Loose” Tiles Animations With CSS3

What is a loose tile?

In Metro design language when we show a list of tiles that are representing options to choose to a user, we want to give user a feeling of an unstable state. This means user should not stay at such page/state for a long time because in Metro design language content is center of user experience and we want to let user reach content she want as soon as possible. Metro gives this unstable state feeling by making tiles react to touch/click like they are not firmly sticked in their place. If you ever used Windows 8 you know how does it feel

Using CSS3 Transforms

I used CSS3 transforms to rotate tiles around X and Y axises and JavaScript to determine which axis and which direction I should rotate the tile.

CSS for different axis and directions of rotations based on point of interaction:

.top:active {
	-webkit-transform: rotateX(10deg);
	-moz-transform: rotateX(10deg);
	-ms-transform: rotateX(10deg);
	-o-transform: rotateX(10deg);
	transform: rotateX(10deg);
}
.bottom:active {
	-webkit-transform: rotateX(-10deg);
	-moz-transform: rotateX(-10deg);
	-ms-transform: rotateX(-10deg);
	-o-transform: rotateX(-10deg);
	transform: rotateX(-10deg);
}
.left:active {
	-webkit-transform: rotateY(-10deg);
	-moz-transform: rotateY(-10deg);
	-ms-transform: rotateY(-10deg);
	-o-transform: rotateY(-10deg);
	transform: rotateY(-10deg);
}
.right:active {
	-webkit-transform: rotateY(10deg);
	-moz-transform: rotateY(10deg);
	-ms-transform: rotateY(10deg);
	-o-transform: rotateY(10deg);
	transform: rotateY(10deg);
}
.center:active {
	-webkit-transform: scale(0.96);
	-moz-transform: scale(0.96);
	-ms-transform: scale(0.96);
	-o-transform: scale(0.96);
	transform: scale(0.96);
}

JavaScript Code to apply proper CSS class based on mouse position:

function mousemoveHandler (event) {
 	var regions = {
		top: {
			x1: this.offsetLeft + this.offsetWidth * 1/3,
			x2: this.offsetLeft + this.offsetWidth * 2/3,
			y1: this.offsetTop,
			y2: this.offsetTop + this.offsetHeight * 1/3
		},
		right: {
			x1: this.offsetLeft + this.offsetWidth * 2/3,
			x2: this.offsetLeft + this.offsetWidth,
			y1: this.offsetTop,
			y2: this.offsetTop + this.offsetHeight 
		},
		bottom: {
			x1: this.offsetLeft + this.offsetWidth * 1/3,
			x2: this.offsetLeft + this.offsetWidth * 2/3,
			y1: this.offsetTop + this.offsetHeight * 2/3,
			y2: this.offsetTop + this.offsetHeight
		},
		left: {
			x1: this.offsetLeft,
			x2: this.offsetLeft + this.offsetWidth * 1/3,
			y1: this.offsetTop,
			y2: this.offsetTop + this.offsetHeight 
		},
		center: {
			x1: this.offsetLeft + this.offsetWidth * 1/3,
			x2: this.offsetLeft + this.offsetWidth * 2/3,
			y1: this.offsetTop + this.offsetHeight * 1/3,
			y2: this.offsetTop + this.offsetHeight * 2/3
		}
	};

	for (var region in regions) {
		this.classList.remove(region);
		if (regions[region].x1 < event.pageX && event.pageX < regions[region].x2 &&
			regions[region].y1 < event.pageY && event.pageY < regions[region].y2) {
			this.classList.add(region);
		}
	}

	this.parentElement.style.webkitPerspectiveOriginX = this.offsetLeft + this.offsetWidth / 2 + "px";
	this.parentElement.style.webkitPerspectiveOriginY = this.offsetTop + this.offsetHeight / 2 + "px";
}

Demo

Here is demo of loose tiles: Loose Tiles

Unfreeze a JavaScript Object

Object.prototype.freeze

Object.freeze() can easily make an object un-editable. After you freeze an object you can not touch it’s properties. Deleting or changing frozen objects doesn’t throw an error but doen’t take effect either.

var o = {val: 1};
Object.freeze(o);
o.val = 2; // this will not make any change to `o`
Object.isFrozen(o); // true
o.val === 1; // true

Why do we need to unfreeze an object?

It seems strange to freeze an object at first place and then try to unfreeze it afterwards. But in some situations you don’t have control over all codebase and you face frozen objects that and you want to change that object for reasons like debugging, testing, etc.

For example I was writing Jasmine tests for my WinJS application and Jasmine’s spy() method was not able spy on frozen WinJS objects methods. Windows doesn’t allow developers to touch WinJS code.

Freezing an object is the ultimate form of lock-down. Once an object has been frozen it cannot be unfrozen - nor can it be tampered in any manner.

How to unfreeze?

Basically you can not unfreeze an object using JavaScript language methods. There is no Object.unfreeze() Method. Unfortunately a “copy” of the frozen Object is frozen too:

var o = {val: 1};
Object.freeze(o);
var _o = o;
Object.isFrozen(_o) // true

Solution is to clone the frozen object and work with that object instead. By creating a brand new object and filling all properties from original(frozen) object to it we get equal object that is not frozen.

var obj = {val: 1, max: 10};
Object.freeze(obj)
var _obj = {};
for (var prop in obj) {
   if(obj.hasOwnProperty(prop)) {
      _obj[prop] = obj[prop];
   }
}
Object.isFrozen(_obj); //false
//now you can replace original object with the unfrozen one
obj = _obj;

Converting Images to HTML Code

I was thinking to a workaround for showing images in email clients that block images. I found out that most of email clients are rendering HTML code. Based on this fact we can show images by hacking HTML code to show each pixel of image as a HTML element and then make background color of that element equal to color of pixel we are presenting. Of course HTML elements should be 1px by 1px without any border, margin or padding. I started prototyping my idea and after a little bit of tweaking I was able to generate HTML code that is actually renders final result just like original image, pixel per pixel. I used HTML5 canvas element to read image pixels. This means the whole process can happen inside the browser! I created a Github repo here to demonstrate my work. I will optimize the code to make it usable in production. Using the web app is as easy as dragging an image from your desktop in the browser when the app is open in your browser. Please test with an small image. Processing big images takes more than usual. I’ve tried sending the processing to a Web Worker but unfortunately web workers don’t run JavaScript in window scope and therefore there is no HTML Canvas element in worker environment to use for image analyzing. Try the web app here.

Making a Simple Todo App Using Backbone.js

I decided to create a tutorial for starting with Backbonejs. I created this simple app to write the tutorial based on it but when I started writing tutorial I found out I’m not a real tutorial writer. So I put the code in Github and live example here and regret making a tutorial. Maybe I create the tutorial in future.