My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Saturday, February 14, 2009

Levenshtein algorithm revisited: 2.5 times faster

First of all one consideration:

JavaScript is SLOW!


Chrome, Safari, Opera, FireFox (Internet Explorer obviously is the only one 2 to 8 times slower!)
It does not matter which tracemonkey or V8 you are using, JS is far away to be fast as C#, C++, C are!

About Levenshtein


If you would like to create a project like BJSpell with a reasonable suggestion, the levenshtein algorithm will trill at some point: it calculates the distance between 1 string to another one. It means that from the word "Gofy" to the word "Goofy", this algo will return 1 character to change replace, or add, before Gofy will become Goofy.

Why Levenshtein


To obtain a suggestion that makes sense, we could use some known algorithm to recognize at least words close to the mistyped one. So far, my suggestion in BJSpell was something truly rude and often useless, but as far as I know there is NO WAY to implement something more clever, using every possible best performances practice.

How to speed up the algorithm


Every "bloody" implementation of this algorithm uses 1 more useless loop to pre-assign values to the multidimensional Array, plus a boring if else instead of ternary operator.
Removing those loops I switched performances from 1.680 seconds to 560, over 100000 computations using C#. The trick is simple: set the Array when you need it!
Here is the code I wrote for JavaScript first and C# after:

// JavaScript
var levenshtein = function(min, split){
// Levenshtein Algorithm Revisited - WebReflection
try{split=!("0")[0]}catch(i){split=true};
return function(a, b){
if(a == b)return 0;
if(!a.length || !b.length)return b.length || a.length;
if(split){a = a.split("");b = b.split("")};
var len1 = a.length + 1,
len2 = b.length + 1,
I = 0,
i = 0,
d = [[0]],
c, j, J;
while(++i < len2)
d[0][i] = i;
i = 0;
while(++i < len1){
J = j = 0;
c = a[I];
d[i] = [i];
while(++j < len2){
d[i][j] = min(d[I][j] + 1, d[i][J] + 1, d[I][J] + (c != b[J]));
++J;
};
++I;
};
return d[len1 - 1][len2 - 1];
}
}(Math.min, false);


// C#
public int levenshtein(string a, string b){
// Levenshtein Algorithm Revisited - WebReflection
if (a == b)
return 0;
if (a.Length == 0 || b.Length == 0)
return a.Length == 0 ? b.Length : a.Length;
int len1 = a.Length + 1,
len2 = b.Length + 1,
I = 0,
i = 0,
c, j, J;
int[,] d = new int[len1, len2];
while(i < len2)
d[0, i] = i++;
i = 0;
while(++i < len1){
J = j = 0;
c = a[I];
d[i, 0] = i;
while(++j < len2){
d[i, j] = Math.Min(Math.Min(d[I, j] + 1, d[i, J] + 1), d[I, J] + (c == b[J] ? 0 : 1));
++J;
};
++I;
};
return d[len1 - 1, len2 - 1];
}


As Summary


Levenshtein algorithm is still too slow if performed via JavaScript but for small dictionaries (up to 5000 words instead of 70000 or more as I tested with the entire en_US vocabulary) is a perfect choice for suggestions.

Have fun with algorithms ... next one? Who knows, probably the soundex :D

Friday, February 13, 2009

After the Array, subclassed String

As I wrote months ago in this documentation about JavaScript prototypal inheritance, subclass native data type is not that simple (almost not possible at all) but since JS is loads of weird bits and bops, I often try to break its documented limits.

It was the Array, some time ago, now it is about time for String.

The concept is similar, if you subclass a native data type its methods will return that native data type like instance, so concat, charAt, toString, etc etc, will return a String unless we do not override every inherited method (so performances wont be that good).

Subclassed String



(function(Function, slice, push){
// from WebReflection: Subclassed String
function String(String){
if(arguments.length) // clever constructor, accepts more than a string as argument
push.apply(this, slice.call(arguments).join("").split(""));
};
String.prototype = new Function;
try{
(new String) + ""; // exception in FireFox
var join = Array.prototype.join;
String.prototype.toString = String.prototype.valueOf = function(){
return join.call(this, "");
};
}catch(e){ // no way to retrieve the length with FireFox
String.prototype.toString = String.prototype.valueOf = function(){
for(var Array = [], i = 0; Array[i] = this[i]; i++);
return Array.join("");
};
};
(window.$ || ($ = {})).String = String; // let's put this in a namespace
})(String, Array.prototype.slice, Array.prototype.push);

That's it, every String.prototype.method should act as it has been called via native String with probably every browser.

Performances


concat, charAt, charCodeAt, toLowerCase, etc, etc will be almost the same of native strings but the constructor will be a bit slower (instances instead of regular "strings").
On the other hand, in every browser the returned instance will be an Array like String, so ...

new $.String("Here", " ", "we", " ", "are!")[0];

will be exactly the char "H" in every compatible browser.

Alternatives?


To create a valid alternative that will NOT be an instanceof String we could use the same Stack trick:

// every browser
(function(Function, join, push){
function String(String){
if(arguments.length)
push.apply(this, slice.call(arguments).join("").split(""));
};
String.prototype.length = 0;
String.prototype.valueOf = String.prototype.toString = function(){
return join.call(this, "");
};
// here we can add every String prototype to the $.String prototype
(window.$ || ($ = {})).String = String;
})(String, Array.prototype.join, Array.prototype.slice, Array.prototype.push);


Have fun ;-)

Tuesday, February 10, 2009

About isNative, is wasting time?

kangax as reply to Diego comment, then Ajaxian as desert with my comments, but three of us completely in the wrong direction.

Why isNative?


As I though and as Diego Perini confirmed, sometimes we would like to trust the environment itself before we act in a certain way.
I wrote about an XMLHttpRequest wrapper for Internet Explorer, but cases are numerous, like a "not compliant" implementation of the Array.prototype.forEach, or others proto, or some injection problems about window.Array, window.String, or who knows what else.
Accordingly, since the JavaScript nature is dynamic, widely dynamic, we would like to be sure that a method is as "specs says" rather than how this or that library implemented it.

Can we trust an unreliable environment?


The first error we all committed was to find the "best way ever" to understand if a function/method has been changed, without considering the fact that the function isNative itself could be a fake!
No matter how good is our way to discover the native code because isNative(this, "isNative"); will ironically return false every time.
A way to partially solve the problem is the usage of const but this keyword makes sense only for FireFox and Safari, so Opera and even worse case Internet Explorer will not be able to create an immutable function.

/*@cc_on var // @*/ const
isNative = function(){
// whatever You need
};

Above snippet, described in one of my old posts, will let us create an immutable function only for certain browsers, but the isNative problem, as I said, will persist for IE, Opera, and probably other browsers as well.

About proposed solutions, plus mine


Both kangax and Diego have written a couple of functions, the first one created a sandbox via iframe while the second one a string sniff.
Both solutions are not that perfect because of iframes or because a function toString method coul be changed arbitrary, since functions are objects as well.
My solution has probably some side effect as well, but unless smebody will be able to demonstrate that it could be hacked, which was for Diego case, I will consider my proposal the most reliable without iframes.

function isNative(object, method){
var r = !!object && !/undefined|string/.test(typeof object[method]);
if(r){
var toString = (method = object[method]).toString;
try{ // necessary for native functions (alert, as example)
delete method.toString;
r = method.toString !== Object.prototype.toString && /\[.+?\]/.test(method);
if(method.toString != toString)
method.toString = toString;
}catch(e){
r = true;
}
};
return r;
};

Come on, break it and demonstrate that as I said, JavaScript is 100% unreliable programming language ;-)

P.S. this discussion remind me those days me and kentaromiura were trying to find a way to solve eval injections, we gave up after a week of tries hacking our code by our own :D

Monday, February 09, 2009

JavaScript, Bear in Mind DOM Methods

We all like the jQuery code style where the instance is returned almost everywhere, but we often forget about DOM methods that do the same and ages before whatever library. I rarely spot some "returned instance" trick in daily posts or even famous libraries.
Here a couple of example:

// daily way ...
var div = document.createElement("div");
document.body.appendChild(div);

// easy way
var div = document.body.appendChild(document.createElement("div"));


// boring way
var div = document.createElement("div");
div.appendChild(document.createTextNode("test"));
document.body.appendChild(div);

// funny way
var div = document.body.appendChild(
document.createElement("div")
).appendChild(
document.createTextNode("test")
).parentNode
;

... on and on, there are several methods used on daily basis that do not consider returned values. So, why don't we like to use them?

var el = document.createElement("div"),
div = document.createElement("div");
alert([
el === document.documentElement.appendChild(el), // el in the DOM
el === el.parentNode.removeChild(el), // el removed
div === document.documentElement.appendChild(div), // div in the DOM
div === div.parentNode.replaceChild(el, div), // div removed, el in the DOM
div === el.parentNode.insertBefore(div, el) // both in the DOM, div returned
].join("\n"));

As summary, try to find a leak possibility with this:

with((document.body || document.documentElement)
.appendChild(
document.createElement("div")
)
.appendChild(
document.createTextNode("not")
)) parentNode
.insertBefore(
document.createTextNode("Why "),
parentNode.firstChild
)
.parentNode
.appendChild(
document.createTextNode(" ?")
)
;

Not even a single variable declared, three elements inserted in a specific node of the DOM and in a different order :D

Sunday, February 08, 2009

Advertisement revolution? A first try for Android, iPhone, and PCs

Introduction


Nowadays, we read news about new libraries, technologies, etc etc, but there is an area in this Web 2.0 era which seems to be "stuck" since big G introduced AdSense: a new way to deliver advertisement, compatible with new devices such as Google Android and Apple iPhone.
Even if Google proposes AdSense for mobiles as well, we know that those simple text boxes do not cope properly with Android and iPhone innovative web browsers.
This is why I have though about a new way to show ads, unobtrusive, cross-browser, and in a way even funny, with less than 2Kb minified and gzipped code, library independent, with everything inside its own closure ;-)

Ad 2.0 Introduction


The iframe below perfectly represents my idea of mobile advertisement, idea that I will explain better a bit further down. Every 10 seconds, a little banner comes up at the bottom of the screen, and it persists for 2 seconds before it disappears. The number of bunners can be from 1 till unlimited, in this case, just 3.

The page above has been written by me and inspired by x.facebook layout and colors, one of the best mobile implementations I have ever seen so far.
You can surf the content of the above iframe with almost every XHTML 1.0 Compliant browser, included FireFox, Safari, Chrome, Internet Explorer, etc etc. but it is ideal for Google Android or Apple iPhone, whatever mode you are using (portrait or landscape) and with a fixed bottom ad that comes up every N seconds and shown for other N seconds, parameters that I could easily customize directly via url, as well as colors and banners (now simply fakes).

A new idea? Only for mobile!


What we miss so far for mobiles are CSS "position:fixed" in iPhone, solved via my ad 2.0 code, and an advertisement system able to appear and disappear with transparency effects and in a Web 2.0 Stylish way. After a couple of hours of neck-breaking, here I am with a football match alike advertisement, something that makes sense in Web 2.0 since the tendency leans towards not refreshing a page in order to rotate displayed banners (concept I introduced ages ago in packed.it project page, a site entirely based on Ajax and where AdSense content is not static).

So basically, since even Facebook with their Ads policy did not introduce a nice way to show some "interesting stuff", I asked myself: what could be the best way to introduce ads without annoying people, without being obtrusive with whatever library, easy to click on touch-screens, and without boring long texts/big spaces since in this mobile era pixels are truly precious?
The fixed bar is entirely a link, it is extremely easy to click with both iPhone and Android, while the advertisement concept is just this: can you sell something with a 32x32 icon plus a summary or a funny sentence able to capture mobile surfers attention? Then in this case, Ad 2.0 does half the work, thanks to its appearing/disappearing effect plus transparency and customizable colors, and the rest is up to your marketing ability ;-)

Here there's a static shot of Ad 2.0 script:


I know a lot of you are thinking: OMG! Advertisement even in my mobile? You are evil! ... well, it is just a simple idea but I am sure we will have ads in our mobile sites soon - so, in my opinion, it is just a matter of time, and the way to show it.

Any comment or suggestion will be more than appreciated, have a nice week.

P.S. Does anybody know how to contact some guy in Facebook?

Friday, February 06, 2009

Another experiment inspired by Google Buttons

I found this post from Ajaxian extremely interesting, and I decided to try to create a better version, if it is possible, of Google Buttons 3.1

The result is not perfect, still alpha, and just for fun, but compatibility seems to be great while multiple buttons visualizations (horizontal or vertical) is extremely simple: write links beside each other, or add a couple of rules for vertical version.



States are hover, active, selected, represented via JavaScript events (onmouseover, onmousedown, onmouseup).
As I said this is just an experiment, but I think as is it is not that bad ... maybeI am wrong :D

Thursday, February 05, 2009

Hunspell for JavaScript ? A quick and dirty one: BJSpell

Somebody asked me to implement a web based spell check without plug-ins or specific browsers requirement (we all know banks security policies, for example, every plug-in could be dangerous but maybe they are still using the most un-secure browser still available these days: Internet Explorer 6 ... )

My answer, straight on: Guys, there is nothing available in pure JavaScript, but I can investigate about it

That's it, a couple of searches via Google, and nothing as expected ... but hey, wait a minute: what's about FireFox spell checker plug in and Open Office project? Here we are, Hunspell is the answer!



BJSpell Project


In a full day of self brain storming, history background cases study, and code, plus debug and tests, I created BJSpell, a basic, fast, cross browser, and runtime implementation capable to underline bad words using a pre compiled Hunspell compatible dictionary (one or more).
The reason I avoided the usage of the classic "click here for the spell checker" is server stress, since the idea was to bring the spell check inside text-areas without polling with short of big texts the server and every N seconds or, the worst case scenario, on every "onkeyup" textarea event!

Pure JavaScript


To create the little speller I used JavaScript on both client and server side. In the project page you can browse the trunk branch and have a look to BJSpell.Jaxer.html page, based on Jaxer (ok, ok ... I know, just another excuse to test my PAMPA-J project ... )

A real world example page


I created a folder in my website with a BJSpell demonstration page ... wait for the cursor in the right area and try, for example, to write something like "... let's try some weirf word ..."

If you have FireFox spell check plugin with english dictionary, you will difficulty spot the difference between the left textarea and the produced output in the right div ... but what the plug-in does not do, is to show you a couple of alternatives, or close words, instead of the wrong one

What's next?


The project is in beta status, so I need your help to debug it and to understand if it has been worthy and if it is truly a good compromise between performances and result. The suggestion is not perfect, truly quick and dirty, just a basic and incomplete implementation, so we will see how and if the project will go on ;-)

Monday, February 02, 2009

PHP static as virtual self, what else for parent?

I find the static keyword in PHP 5.3 absolutely useful, but I instantly felt into a dilemma: what about parent?

With static it is possible to refer to a generic class static property, without referring the class where the method has been declared.
Here there is a simple example:

class Numbers {
public static $value = 0;
public static function getValue(){
return static::$value;
}
}

class One extends Number {
public static $value = 1;
}

class Two extends Number {
public static $value = 2;
}

$one = new One;
$two = new Two;
$one->getValue(); // 1
$two->getValue(); // 2

Above example shows how static behaves when an instance calls a method which uses static keyword.
Whatever subclass it is, we will always obtain the defined value (if any, otherwise the inherited one) as expected.

But what about parent behavior?

If we use parent inside a method it is like using self, the parent keyword will always refers to the parent class, if any, of the method which contains the parent keyword. If we add a function like this in the Numbers class:

public static function getParentValue(){
return parent::$value;
}

every subclass wont be able to show the Numbers $value and an error will be generated instead.

To obtain the desired result we have to use the ReflectionClass:

// class Numbers ...
public static function getParentValue(){
$class = new ReflectionClass($this);
return $class->getParentClass()->getStaticPropertyValue('$value');
}

Above code is much slower than parent::$value because of the instance creation plus its method call for each ReflectionClass instance ($this plus the one returned by getParentClass)

Now, the question is: is it truly necessary? Will we have other ways to retrieve a "static parent" from a method?

Wednesday, January 28, 2009

32 bytes, ehr ... 9, ehr ... 7!!! to know if your browser is IE

Update another clever trick from comments, which I will explain later:

if(!+"\v1") // true only in IE
if("\v"=="v")// true only in IE
try{IE=window=!1}catch(e){IE=!0}

it works, doesn't it?

The reason is simple, if we consider "\v" as a vertical space, browsers interpreter that check in this way:

!(+
1
)

where "not one" is always false, considering that 0 is always casted as false, and every other number is casted as true.

Internet Explorer will ignore the vertical space, trying to cast a "v" character into a number, thanks to the sign (plus or minus, it does not matter)

// How IE interpreters the code
!(+"v")

// where
isNaN(+"v") === true
// and where NaN is implicitly casted as false


About conditional comments


I read a lot of comments in both Ajaxian and other places ... well, guys, this is a trick as conditional comment is.
The day IE will interpret correctly the "\v" character, Opera or some other browser could implement conditional comments as well.
That's my simple point of view:
conditional comments could be stripped out from minifiers (not MyMin) and make code difficult do understand or maintain while this 7 bytes trick is portable, minifier/packer safe, and extremely easy to maintain (the day IE will be able to return a false, we'll have solved almost every cross browser problem thanks to JS2 but just in case, all we need to do, will be a simple replace with the isIE.Next trick)


Note this trick is library/hack proof. If you think that execScript check is enough, for example, consider this: top["execScript"]=null and/or libraries that implements execScript for other browsers.

Tuesday, January 27, 2009

png to gif transformation - an excellent free solution via PHP GD2

Why we still need png to gif in our web pages


There a couple of valid plugins for different libraries able to manage "silently" png transparency in order to fix those browsers (cough: IE6) that are still used, for god knows which reason, but not able to understand properly the alpha channel. The problem is that these plugins cause overhead in our pages and for each png images, which is nearly a non-sense since these plugins fix old browsers whose performances have never been brilliant!
Especially for modern GUIs, where little icons are widely used, these plugins could make the application incredibly slow.
If we could choose old good GIF instead of png, 'till the end of those browsers, the problem will not exist and performances will be acceptable.

PNG 2 GIF, simple? ... not, really!


First of all a couple of search via Google brought me in "free but you have to pay anyway" applications through some open source, simple, but not that nice, program language solution, incompatible with modern interpreters or not able to produce a good quality result.
The problem is basically this one: alpha channel is something amazing, but it changes border colors if we are putting the png over a bright background rather than a dark one.
For this reason it is really difficult to obtain a valid GIF copy of the original PNG feel using common transformers, since the main difference is given by our cool theme that can be bright or dark.
Thanks to PHP and its distributed GD2 library, I have been able to create a good compromise between pixelated borders and our chose theme.

png2gif, the php/gd2 way



function png2gif($pngs, $background = array(255, 255, 255), $dest = 'gif'){
// by WebReflection
foreach($pngs as $png){
$size = getimagesize($png);
$img = imagecreatefrompng($png);
$image = imagecreatetruecolor($width = $size[0], $height = $size[1]);
imagefill($image, 0, 0, $bgcolor = imagecolorallocate($image, $background[0], $background[1], $background[2]));
imagecopyresampled($image, $img, 0, 0, 0, 0, $width, $height, $width, $height);
imagecolortransparent($image, $bgcolor);
imagegif($image, str_ireplace('.png', '.gif', $dest.DIRECTORY_SEPARATOR.basename($png)), 100);
imagedestroy($image);
}
}

// example
png2gif(glob("icons/*.png"));

That's it, you copy and paste an entire directory into, for example, an icons folder, and you call the function passing the list of files contained in that directory.
Parameters are the file list itself, the background color, and finally the destination folder to put transformed png into gif, by default the dir "gif".
The main difference between this function and every other method I found, is that borders are gracefully adapted to your main theme, by default a bright one with white background.
In this way you can choose how borders should be readapted instead of black borders for alpha problems, or cutted one. Even circle icons result are, in my opinion, brilliant!
The array should contain R,G,B integer values, from 0 to 255, where array(0,0,0) is black and array(255,255,255) is white, the default background theme.

You can try this function to convert most common icons theme, and please tell me if the result was not good enough ;-)

P.S. for PHP maniacas, the imagecopyresampled gd2 function has been the only one able to merge properly the png into chose background color ... I don't want to tell you how long did it take to find this kind of solution (passing via pixel by pixel color allocation ... omg!)

IE8 RC1 - Faster SunSpider? It does not matter!

Just a quick post about IE.Next - SunSpider could score a bit better (not compared with other browsers) but the render speed, css direct/text visualization, plus events propagation, is about 2 times slower than beta 2 and 7

Guys ... just 3 words: what the hell!

Monday, January 26, 2009

PAMPA-J calls for tests

More downloads, and as usual more problems caused by different configurations.
I would like to leave a single official 1.0 release in Google Code PAMPA-J Project page but I need your tests to do this.

Test I would like to perform with your configurations:

  • PAMPA starts (default configuration: Apache, MySQL, PHP, Jaxer)

  • PAMPA works from every folder (Desktop, Documents, others)

  • PAMPA closes processes on stop and/or exit

  • PAMPA works from network as well (old version could be launched from another PC without problems and respecting paths)


All above tests passed without problems for me, but I would like to be sure it works properly in other environments. Would you help me? Cheers :-)

Saturday, January 24, 2009

PAMPA 1.0 - Jaxer included!

Update - Windows Home Fixed!
Version 1.0b contains hot fixes for Window$ Home Edition plus some little change to make PAMPA more robust than before during process managment.
If you already downloaded version 1.0 you can download only the Tray executable and rename it as PAMPA.exe

Please tell me if you have still problems, hoping this b version will be the final 'till 1.1 ;-)

Update
Final Version 1.0 now served via Google Code ;-)



I am proud to announce the first Release Candidate final 1.0 release of my tiny precious PAMPA, jumped from version 0.7 to 1.0 and rewrote from the scratch considering every suggestion its users gave me during these years (project born in 2006 and completely revisited for version 1.0)

What is PAMPA-J


PAMPA means Portable Apache, MySQL, and PHP Application, in this release with Aptana Jaxer included!
(shell I consider PAMPA-J a portable Aptana Cloud?)

What does it mean: Portable


PAMPA is the first customizable and portable WAMP environment that includes Jaxer and that is completely free (but of course donations are always appreciated).
You can launch PAMPA from an USB driver, a CD-ROM (without native database write capabilities), an external Hard Disk, your Hard Disk itself, configuring MySQL data folders, session folders via php.ini, Apache folders, Jaxer folders, and reading logs, changing configuration, in a truly simple way.

Where is it?


For some reason Google Code policy is to ask sourceforge about projects with the same name, so in Google Code I had to change PAMPA project name into PAMPA-J, considering that somebody created an empty PAMPA project in sourceforge 1 year ago, while PAMPA exists at least since February 2006 ... anyway, the link I provided already should not show the RC release yet, while this one, directly from the svn, is the unofficial Release Candidate 1 Direct Download

How does it work?


All you need to do is to choose a folder to decompress PAMPA and then launch PAMPA.exe from that folder, wherever it is.
The result, by default, should be a fully configured Apache, MySQL, PHP, and Jaxer environment for your Window$ 2000/XP/Vista/7 Operating System.
I am working to create a better "splash page" to introduce PAMPA, but right now the Release Candidate shows simply the Document Root with links for some file, Jaxer public folder included ;-)

What's in



  • Apache 2.2.11

  • MySQL 5.1.30-community

  • PHP 5.3.0 alpha 3 (RC1)

  • Jaxer 1.0.2.4347

  • phpMyAdmin 3.1.2



Why all this effort for a Release Candidate?
Because I am looking forward for your feedback, in order to release the first portable WAMP plus Jaxer environment with all you need to develop for your own or for distributions your applications and with all you need (in a reasonable way :D)


PAMPA-J is out, have fun! 8-)

Friday, January 23, 2009

Quick Tip: C# GZip content

A quick post with a simple trick that let us reduce instantly every Ajax interaction over our C#.NET application:

[-] public void GZResponse() {
if(-1 < Convert.ToString(Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip")){
Response.AddHeader("Content-Encoding", "gzip");
Response.Filter = new System.IO.Compression.GZipStream(
Response.Filter,
System.IO.Compression.CompressionMode.Compress
);
}
}

The good part is that precedent code, whenever we were using Response.Write, became automatically compatible. Above code could be used to serve JavaScript or css files too:


[+] public void GZResponse(){}

[-] protected void Page_Load(object sender, EventArgs e)
{
GZResponse();
Response.AddHeader("Content-Type", "text/javascript");
Response.WriteFile("jquery.min.js");
}


That's it :-)

P.S. for file serving I suggest a cache system for pre gzipped files

Thursday, January 15, 2009

ellipse and circle for canvas 2d context

These days I am working inside an ExtJS panel to create some sophisticated drawing stuff, and I discovered (too late ...) that there is almost nothing in canvas 2d context to draw circle or ellipse.

That's why I have extended Google excanvas library and/or native canvas 2d context prototype to let us create circles and ellipse in the same simple way we can create rectangles.

Here the extended proto:

(function(){
// Andrea Giammarchi - Mit Style License
var extend = {
// Circle methods
circle:function(aX, aY, aDiameter){
this.ellipse(aX, aY, aDiameter, aDiameter);
},
fillCircle:function(aX, aY, aDiameter){
this.beginPath();
this.circle(aX, aY, aDiameter);
this.fill();
},
strokeCircle:function(aX, aY, aDiameter){
this.beginPath();
this.circle(aX, aY, aDiameter);
this.stroke();
},
// Ellipse methods
ellipse:function(aX, aY, aWidth, aHeight){
var hB = (aWidth / 2) * .5522848,
vB = (aHeight / 2) * .5522848,
eX = aX + aWidth,
eY = aY + aHeight,
mX = aX + aWidth / 2,
mY = aY + aHeight / 2;
this.moveTo(aX, mY);
this.bezierCurveTo(aX, mY - vB, mX - hB, aY, mX, aY);
this.bezierCurveTo(mX + hB, aY, eX, mY - vB, eX, mY);
this.bezierCurveTo(eX, mY + vB, mX + hB, eY, mX, eY);
this.bezierCurveTo(mX - hB, eY, aX, mY + vB, aX, mY);
this.closePath();
},
fillEllipse:function(aX, aY, aWidth, aHeight){
this.beginPath();
this.ellipse(aX, aY, aWidth, aHeight);
this.fill();
},
strokeEllipse:function(aX, aY, aWidth, aHeight){
this.beginPath();
this.ellipse(aX, aY, aWidth, aHeight);
this.stroke();
}
};
for(var key in extend)
CanvasRenderingContext2D.prototype[key] = extend[key];
if(!this.G_vmlCanvasManager)
G_vmlCanvasManager = {init:function(){}, initElement:function(el){return el}};
})();


The last part is to obtain the same behavior with any browser and runtime create canvas:

var myCanvas = G_vmlCanvasManager.initElement(document.createElement("canvas"));


SImple and efficient? I hope so, since I spent more than a couple of minutes to be able to create a perfect circle via 1/4 of a rectangle (square ... but how could I remember the bloody constant to do that?) :P

P.S. I remind you that the simplest function to create a circle via a center is canvas.arc(x, y, radius, 0, Math.PI*2); and that this proto create a circle inside a specified square but ithout the same arc performances ( anyway, runtime rendering in IE and my personal version of excanvas even faster than FireFox 3 ... anybody interested? :-) )

Saturday, January 10, 2009

Internet Explorer Object watch

Update
As Luke suggested, there is a method remove in the watcher that should solver leaks problem while the new version should be supported by most recent Opera, Safari, FireFox, and Internet Explorer.
Main updates:

  • the watcher is always another object and not the original one

  • to safely destroy the watcher use its destroy method and then delete it


----------------------------------------------


We all complain about IE and its non-standard attitude, this time I would like to introduce a non standard feature, as Object.prototype.watch is, for Internet Explorer.

What is watch and why we need it


The watch method allows validation, control, monitoring, over a generic object.
This means that we can control properties assignment with one, or more, callbacks.

var man = {};
man.watch("name", function(propertyName, oldValue, newValue){
// propertyName: name
// oldValue: undefined if it is the first time, the old one otherwise
// newValue: new assigned value
return "Mr " + newValue;
});

man.name = "Andrea";
alert(man.name); // Mr Andrea


watch for Internet Explorer, about my implementation


I used a weird strategy to implement this feature in Internet Explorer and it is based on DOM and its IE feature called onpropertychange.
Accordingly, it was not possible to create an Object.prototype.watch, while it was simple to implement a createWatcher callback.

(function(watch, unwatch){
createWatcher = watch && unwatch ?
// Andrea Giammarchi - Mit Style License
function(Object){
var handlers = [];
return {
destroy:function(){
handlers.forEach(function(prop){
unwatch.call(this, prop);
}, this);
delete handlers;
},
watch:function(prop, handler){
if(-1 === handlers.indexOf(prop))
handlers.push(prop);
watch.call(this, prop, function(prop, prevValue, newValue){
return Object[prop] = handler.call(Object, prop, prevValue, newValue);
});
},
unwatch:function(prop){
var i = handlers.indexOf(prop);
if(-1 !== i){
unwatch.call(this, prop);
handlers.splice(i, 1);
};
}
}
}:(Object.prototype.__defineSetter__?
function(Object){
var handlers = [];
return {
destroy:function(){
handlers.forEach(function(prop){
delete this[prop];
}, this);
delete handlers;
},
watch:function(prop, handler){
if(-1 === handlers.indexOf(prop))
handlers.push(prop);
if(!this.__lookupGetter__(prop))
this.__defineGetter__(prop, function(){return Object[prop]});
this.__defineSetter__(prop, function(newValue){
Object[prop] = handler.call(Object, prop, Object[prop], newValue);
});
},
unwatch:function(prop){
var i = handlers.indexOf(prop);
if(-1 !== i){
delete this[prop];
handlers.splice(i, 1);
};
}
};
}:
function(Object){
function onpropertychange(){
var prop = event.propertyName,
newValue = empty[prop]
prevValue = Object[prop],
handler = handlers[prop];
if(handler)
attachEvent(detachEvent()[prop] = Object[prop] = handler.call(Object, prop, prevValue, newValue));
};
function attachEvent(){empty.attachEvent("onpropertychange", onpropertychange)};
function detachEvent(){empty.detachEvent("onpropertychange", onpropertychange);return empty};
var empty = document.createElement("empty"), handlers = {};
empty.destroy = function(){
detachEvent();
empty.parentNode.removeChild(empty);
empty = handlers = null;
};
empty.watch = function(prop, handler){handlers[prop] = handler};
empty.unwatch = function(prop){delete handlers[prop]};
attachEvent();
return (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(empty);
}
)
;
})(Object.prototype.watch, Object.prototype.unwatch);

A first example, based on precedent one, is this one:

var // original object
man = {},

// create its watcher
manWatcher = createWatcher(man);

manWatcher.watch("name", function(propertyName, oldValue, newValue){
return "Mr " + newValue;
});

// assign name property
manWatcher.name = "Andrea";

// retrieve original object property
alert(man.name); // Mr Andrea

Another example is based on validation, or better, a one shot assignment over the watcher:

var obj = {},
watcher = createWatcher(obj);

watcher.watch("test", function(prop, oldValue, newValue){
return oldValue === undefined ? newValue : oldValue;
});

watcher.test = "one assignment";
watcher.test = "never again";

alert(obj.test); // one assignment

Cool?

About limits


The main one is that the for in loop will not work as expected over a watcher element because it is a DOM node and it will expose every property.
Another one could be about memory leaks and/or low execution, since there are a couple of things to do during assignment.
The good part is that the watcher and the watched will have the same property value, except for those attributes that we cannot modify in a DOM node (style, for example).

Last but not least, happy new year! :D

Wednesday, December 24, 2008

External selectors as engines and how to create your own library

With "Sizzle event", the challenge about libraries will move from the coolest/fastest selector engine into the coolest/fastest way to use it for library purpose.

Since Sizzle will be just one of them, thanks to our natural behavior ( read: re-create the wheel ) it is possible that there will be more selector engines around the net.

So, why we could not create our own library that does just what we need and nothing else, maintaining a decent size and performing like a jaguar :D ???

Here a truly basic example about how to create your own library, basing it over a generic selector engine or generic library (or just its engine, if you prefer one)

// our wonderful library constructor
function myQuery(){
// just in case we prefer another name for the constructor
// this code is "name proof"
var callee = arguments.callee;
return this instanceof callee ?
this :
callee.prototype.init.apply(new callee, arguments)
;
};

// add some native prototype to created array like instances
// a common pattern for DOM based libraries
with(Array.prototype)
myQuery.prototype = {
constructor:myQuery,
length:0,
pop:pop,
push:push,
shift:shift,
slice:slice,
sort:sort,
splice:splice,
unshift:unshift
};

// add "not standard yet array prototypes", if necessary, or our own cool proottypes
myQuery.prototype.forEach = Array.prototype.forEach || function(Function, self){
for(var i = 0, length = this.length; i < length; i++)
(i in this) && Function.call(self, this[i], i, this);
};

// define the init prototype to use the pre defined engine
myQuery.prototype.init = function(){
var self = this.engine.apply(null, arguments);
this.push.apply(this, self instanceof Array ? self : this.slice.call(self, 0));
return this;
};

// define the engine for this library
myQuery.prototype.engine = Sizzle; // or jQuery

onload = function(){

// enjoy your lib
myQuery(".foo .bar").forEach(function(HTMLElement){
HTMLElement.innerHTML = "Hello Lib!";
});

};


Summary


The main limit is the engine itself, or better, arguments that the engin could accept.
If we change engine and this accepts different arguments or same arguments in a different way, we need to change every call to our library but at least everything else will work without problems.
For this reason it is reasonble to choose a common engine arguments model, like Sizzle, for example, presuming other engine will accept the same list of options and will produce an array like result.
Am I suggesting to avoid famous/common library? Absolutely no, I simply think the selector engine is the most important thing for whatever DOM purpose library :-)

Tuesday, December 23, 2008

Visual Studio 2008 - The good part

... whatever I said in the precedent post, at least VS9 let us extend it and create macros as well.

Unfortunately, I could not create a macro in C# so I had to use a language that I do not like at all, Visual Basic, and the result is an alpha macro that allows us to create "more clever" regions and outline for brackets as well.

More clever regions


There is another macro that goes around since Visual Studio 2005 but it has some bug and/or problem with nested regions plus it does not allow us to write directly in the region what the region is about

//#region whatever
...
//#endregion

--- to obtain
//#region whatever[...]

--- instead of
// another "boring" comment over the region
[...]

At the same time that macro put every region, nested or not, at the beginning of the line. It is not such a big problem, but I prefer this version.


Brackets outline


This is absolutely experimental and there are hundreds of problems, but for a couple of files it is doing its job.


What's next


Christmas, holidays, relax, if it is possible, and a better parser (a char by char via VB, I cannot even imagine me doing it!!!) so be patience please, and enjoy this alpha release :)

' JavaScript macro for bits and bops alpha version
' by Andrea Giammarchi - WebReflection.blogspot.com

Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Collections

Public Module JSMacros

Sub OutlineBrackets()
Outline("Brackets")
End Sub

Sub OutlineRegions()
Outline("Regions")
End Sub

Private Function Outline(ByVal what As String)
Dim REGION_START As String = "//#region"
Dim REGION_END As String = "//#endregion"
If what = "Brackets" Then
REGION_START = "{"
REGION_END = "}"
ElseIf what = "Regions" Then
REGION_START = "//#region"
REGION_END = "//#endregion"
End If
Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Dim selections As ArrayList = New ArrayList
Dim regions As Stack
Dim current As Stack
Dim endIndex As Integer
Dim startIndex As Integer
Dim text As String
selection.StartOfDocument()
selection.SelectAll()
text = selection.Text
If text.Chars(text.Length - 1) <> vbCr Then
selection.EndOfDocument()
selection.Insert(vbCr)
text += vbCr
End If
regions = FindRegions(text, REGION_START, REGION_END)
If what = "Brackets" Then
OutlineBracketsLoop(REGION_START, REGION_END, regions, selections, text, 0, 0, 0, regions.Count(), New Stack)
ElseIf what = "Regions" Then
OutlineRegionsLoop(REGION_START, REGION_END, regions, selections, text, 0, 0, 0, regions.Count(), New Stack)
End If
SetOutline(selection, selections)
selection.StartOfDocument()
End Function

Private Function CalcLineNumber(ByRef text As String, ByVal i As Integer)
Dim lineNumber As Integer = 1
While 0 < i
i -= 1
If text.Chars(i) = vbCr Then
lineNumber += 1
End If
End While
Return lineNumber
End Function

Private Function FindPosition(ByRef text As String, ByVal i As Integer)
Dim position As Integer = 0
While 0 < i
i -= 1
position += 1
If i = 0 Or text.Chars(i) = vbCr Then
Exit While
End If
End While
Return position
End Function

Private Function FindRegions(ByRef text As String, ByRef REGION_START As String, ByRef REGION_END As String)
Dim result As Stack = New Stack()
Dim pos As Stack = New Stack(2)
Dim startIndex As Integer = 0
Dim endIndex As Integer
Dim index As Integer = 0
Dim subValue As String = ""
Do
startIndex = text.IndexOf(REGION_START, startIndex)
If startIndex = -1 Then
Exit Do
End If
pos.Push(startIndex)
startIndex = startIndex + REGION_START.Length
index = startIndex
endIndex = text.IndexOf(REGION_END, startIndex)
If endIndex = -1 Then
MsgBox("Endless Region")
Exit Do
End If
Do
index = text.IndexOf(REGION_START, index)
If index = -1 Or endIndex < index Then
pos.Push(endIndex)
result.Push(pos)
pos = New Stack(2)
Exit Do
Else
endIndex = text.IndexOf(REGION_END, endIndex + REGION_END.Length)
index = index + REGION_START.Length
End If
Loop
Loop
Return result
End Function

Private Function OutlineBracketsLoop(ByRef REGION_START As String, ByRef REGION_END As String, ByRef regions As Stack, ByRef selections As ArrayList, ByRef text As String, ByVal startIndex As Integer, ByVal endIndex As Integer, ByVal i As Integer, ByVal length As Integer, ByVal current As Stack)
Dim startLine As Integer
Dim endLine As Integer
While i < length
current = regions.Pop
endIndex = current.Pop
startIndex = current.Pop
startLine = CalcLineNumber(text, startIndex)
endLine = CalcLineNumber(text, endIndex)
If startLine < endLine Then
selections.Add(startLine)
selections.Add(FindPosition(text, startIndex) - 1)
selections.Add(endLine)
selections.Add(FindPosition(text, endIndex))
End If
i += 1
End While
End Function

Private Function OutlineRegionsLoop(ByRef REGION_START As String, ByRef REGION_END As String, ByRef regions As Stack, ByRef selections As ArrayList, ByRef text As String, ByVal startIndex As Integer, ByVal endIndex As Integer, ByVal i As Integer, ByVal length As Integer, ByVal current As Stack)
Dim tmpIndex As Integer
While i < length
current = regions.Pop
endIndex = current.Pop
startIndex = current.Pop
tmpIndex = startIndex + REGION_START.Length
selections.Add(CalcLineNumber(text, startIndex))
selections.Add(1 + FindPosition(text, startIndex) + REGION_START.Length + text.Substring(tmpIndex, text.IndexOf(vbCr, startIndex) - tmpIndex).Length)
selections.Add(CalcLineNumber(text, endIndex) + 1)
selections.Add(1)
i += 1
End While
End Function

Private Function SetOutline(ByRef selection As EnvDTE.TextSelection, ByRef selections As ArrayList)
Dim i As Integer = 0
Dim length As Integer = selections.Count()
While i < length
selection.MoveToLineAndOffset(selections.Item(i), selections.Item(i + 1))
selection.MoveToLineAndOffset(selections.Item(i + 2), selections.Item(i + 3), True)
selection.OutlineSection()
i += 4
End While
End Function

End Module

Saturday, December 20, 2008

Visual Studio 2008 and JavaScript: the worst couple ever

We are using Visual Studio 2008 Team Edition at work and it is great for our C# plus SQLServer application, but I am working entirely with JavaScript and every time my files grow up "too much" I start having headache scrolling up and down thousands of line of code.

A basic function that even a small editor like Notepad++ has, the plus/minus sign to close functions closures, does not exists.

You should try to create your own macro, in VB "of course", and call it every time.
As alternative, I added the file extension js in the option with HTML Editor as default editor to let me do something like this

//#region MyConstructor <script>

... my code

//#endregion </stript>

Above start and end comment allows me to close code blocks and everything inside will be highlighted because the editor consider it as an HTML JavaScript tag:
it's true, HTML has open/close blocks while JavaScript does not.

The "fantastic" debugger is nothing that better than the one you can find inside Internet Explorer 8, the only point is that it is integrated with the rest of the project so you can debug both JavaScript and C# at the same time ... without this big effort.

I use FireBug and/or Chrome console indeed, since I do not need to monitor C# that much, and that's it, client side debug feature completely useless under IE ( and I downloaded the version 8 beta 2 yesterday so I can use its debugger instead of launching another local server for client side debug ... )

The intellisense sucks, it does not work automatically as is for C# or other languages or as is for Eclipse or Aptana, you have to put useless syntax in the top of the file to tell the big IDE where are other files.

The suggestion is so clever that if you have a property whose name starts with el, the IDE will autmatically put an else

myObject.else // by the ide


The internal parser does not recognize properly functions as objects, and inheritance is not part of the suggestion ... you should try to disable it if you want to code faster instead of correct IDE suggestions.

In few words, I still wonder why Microsoft is doing everything to discourage the usage of JavaScript and I can't wait to find a valid alternative to integrate my JavaScript projects into source control without being constricted to use the best IDE for C# and the worst ever for JavaScript: Visual Studio 2008

Kind Regards

Wednesday, December 17, 2008

outerHTML for almost every browser ... if you need it ...

We all have to deal with memory leaks problem and apparently a good way to be sure that an HTMLElement has been removed from its "flow" is the outerHTML assignemnt (thanks Ariel for the suggestion)

element.outerHTML = "";
element = null;

If the element is not a document.body or another body parent node, Internet Explorer will "extract" that element from its context, if any, and if there are no other references for that element the null assignment will, theoretically, complete the opera, hopefully solving memory leaks problem for that node as well ...


To remove ... but to replace too ...


Every library has a "swap" or replace method to quickly change an element, but even if we all know that innerHTML is the fastest way to insert content, few libraries use outerHTML to replace nodes, that as far as I know, should be "that fast" in IE as innerHTML is:

// traditional swap, the DOM way
function swap(oldNode, newNode){
var parentNode = oldNode.parentNode;
parentNode.insertBefore(newNode, oldNode);
parentNode.removeChild(oldNode);
};

// spaghetti swap, the outerHTML way
function swap(oldNode, newNode){
oldNode.outerHTML = newNode.outerHTML;
};



outerHTML ... both get and set



try{
HTMLElement.prototype.__defineGetter__.length;
(function(body, removeChild){
HTMLElement.prototype.__defineGetter__(
"outerHTML",
function(){
var self = body.appendChild(this.cloneNode(true)),
outerHTML = body.innerHTML;
body.removeChild(self);
return outerHTML;
}
);
HTMLElement.prototype.__defineSetter__(
"outerHTML",
function(String){
if(!String)
removeChild(this);
else if(this.parentNode){
body.innerHTML = String;
while(body.firstChild)
this.parentNode.insertBefore(body.firstChild, this);
removeChild(this);
body.innerHTML = "";
};
}
);
})(
document.createElement("body"),
function(HTMLElement){if(HTMLElement.parentNode)HTMLElement.parentNode.removeChild(HTMLElement);}
);
}catch(e){};



Conclusion


pro and cons are the same of innerHTML and the reference is lost as is for Internet Explorer, whenever we decide to use this dirty approach to remove or change elements in the DOM. A last example?

function change(strong){
strong.outerHTML = "not strong anymore";
strong = null;
};
onload = function(){
document.body.innerHTML = "click";
};

Saturday, December 06, 2008

A fast and crossbrowser function to make an Array

An absolutely common task present in almost every library, is to transform a generic collection/list of objects or DOM Elements into a friendly Array.

Cases Scenario



  • It is possible to apply directly an Array.prototype.slice call to quickly return an Array

  • It is not possible at all apply every kind of Array prototype to the list



Cases scenario detection


When we execute a piece of JavaScript in a web page, we can assume that we have at least one DOM element in that page, as the script itself for example, so it is always possible to obtain a collection of elements calling document.getElementsByTagName("script") or a generic ("*") in this case probably superflous considering the latter assumption.

Cross browser and fast makeArray proposal



var makeArray = function(push, slice){
try{
// Andrea Giammarchi proposal
slice.call(document.getElementsByTagName("script"), 0);
return function(array, results){
array = array instanceof Array ? array : slice.call(array, 0);
results ? push.apply(results, array) : results = array;
return results
}
}catch(e){
return function(array, results){
if(!(array instanceof Array))
for(var ret = [], i = 0, length = array.length; i < length; i++)
ret[i] = array[i];
else
var ret = array;
results ? push.apply(results, ret) : results = ret;
return results
}
}
}(Array.prototype.push, Array.prototype.slice);


Summary


The try catch is executed only once, the Array prototypes are cached once as well to guarantee cross libraries compatibility. The function is assigned differently for those browsers that can apply the slice prototype to the collection and those that cannot (mainly Internet Explorer).
Accepted parameters are two, inspired by Sizzle function, to allow us to concatenate elements into a collection.

The collection is transformed into an Array only if necessary, since it does not make sense to perform a slice call in every case.

Compatiblity? It should be every browser that supports try and catch statement :-)

Wednesday, December 03, 2008

Stressfull procedure? Distribute your task!

Have you never been in troubles with frozen GIFs or unresponsive HTML?
Sometimes JavaScript could be used to perform really stressful task and a loop, a for in, or an each, could not be fast enough to make your DOM responsive.

What we need in this case is simply a closure to make sure references are consistent and our job will end up in the correct order.

This is a probably silly but I hope interesting function to make the DOM and generally the page more responsive:

Time = {
setTimeout:function(Stack, delay){
var self = this;
if(!delay)
delay = 1;
if(!(Stack instanceof Array))
Stack = [Stack];
setTimeout(function(){
Stack.shift().call(self);
if(0 < Stack.length)
setTimeout(arguments.callee, delay);
}, delay);
}
};

We can call this functon in different ways, stating from the demo:

Time.setTimeout([
function(){
alert("Hello");
},
function(){
alert("Distributed");
},
function(){
alert("Work");
}
]);

untill its more meaningful usage:

var distributed = [];
$("whatever").each(function(i, dom){
distributed.push(function(){
// your stuff to do with i or dom element
});
});
distributed.push(function(){
// your stuff to do after the each call
});
Time.setTimeout(distributed);

Another trick? The usage of the scope injected by each function:

$("whatever").each(function(i, dom){
var self = this;
distributed.push(function(){
return function(){
// your stuff to do with i or dom element
}.call(self);
});
});

Closures against Responsiveness


People expect usability, we expect performances ... at the same time we would like to be able to show a progress, something, that indicate that the page is not completely blocked.

This is a simple way to solve the problem, portable enough, and customizable via closures ... I hope you'll enjoy it :)

Tuesday, November 18, 2008

Ext JS - How to hack the JsonReader

I have a new job ( hooooray?! ) and I suggested Ext JS framework as web UI to focus more about Ajax, XML + XSLT data interactions rather than problems with CSS, events delegations, etc ... and I guess I am doing well, so well, that here I am with a simple tiny trick to hack an Ext.data.JsonReader instance, specially the root and the totalProperty params:

// directly from Ext JS 2.2 API site
// http://extjs.com/deploy/dev/docs/

new Ext.data.JsonReader({
totalProperty: "results", // The property which contains the total dataset size (optional)
root: "rows", // The property which contains an Array of row objects
id: "id" // The property within each row object that provides an ID for the record (optional)
})

Especially for the paginator toolbar, the JsonReader is a must to surf a big amount of data without stressing too much both server and client sides.

One nice feature, or one clever way to make the root node customizable, is the usage of evaluated code via a new Function call.

If the root property ontains a dot, that property is retrieved via nested objec properties.


...
root:"items[0].myList",
...

Thanks to this feature, it is possible to pre parse and pre generate the list that will be assigned as root Array, the one used inside the Grid, DataView, or whatever.Component is managing your interactions.

The trick to pass the returned object to an arbitrary function is this:

...
root:"toString.length||callback(obj)",
...

The callback suppose to be a valid function with a global scope that will return a filtered list of objects compatible with the column model or the data manager we chose.

The trick is based on their regexp that checks simply a dot or a square bracket "[" in the passed string.

That's it, let me discover better tricky stuff in the source and I'll post them :D

Thursday, October 30, 2008

3, 2, ... 1, ... Coming Soon!

Guys, I can't wait for Ubuntu 8.10 and what's up in the website?
The countdown now shows a "Coming Soon" message ... I mean, a little news about when is that difficult?


I know there is a kernel problem since 27 October, and i hope you updated are updating the release to fix that problem with the 8.10 ... but shall you tell us more?
Kind Regards

And thank You :)

Tuesday, October 28, 2008

jQuery plug-in distributed elements via If, ElseIf, and Else

After a couple of instant and consecutive releases, I ended up with a plug-in that fits minified into 240 bytes :)

Here is the official plug-in page, while this is the example page and this is the summary:

;jQuery.fn.extend({
// Andrea Giammarchi - Mit Style Licence - V0.2
If:function(fn){
var __If__ = this.__If__ || this,
$ = __If__.filter(fn);
$.__If__ = __If__.filter(function(){return !~$.index(this)});
return $;
},
Else:function(){
return this.__If__;
},
Do:jQuery.fn.each
}); jQuery.fn.ElseIf = jQuery.fn.If;

Monday, October 27, 2008

jQuery If, ElseIf, and Else plugin

Update
Guys, I have to admit I created silly prototypes while all I need were much more simpler than I though :) Enjoy last version!
-------------------------------------

Try to imagine a page like this one:

<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</body>


.. and now try to imagine something like this:

function oddNumbers(){
// return true if element contain an odd number
return $(this).text() & 1;
};

$(function(){
$("div")
.If(function(){return $(this).text() == "3" || $(this).text() == "5"})
.text("match the 3 or 5 check")
.ElseIf(oddNumbers)
.text("odd numbers")
.ElseIf(function(){return $(this).text() == 2})
.Do(function(){ // if you need a closure ...
$(this).text("text is equal 2");
})
.ElseIf(function(){return $(this).text() == 6})
.text("match the 6 condition")
.Else()
.text("this is 4 or 8");
;
})


... now, try to imagine I created a plugin like this:


;jQuery.fn.extend({
// Andrea Giammarchi - Mit Style Licence - V0.1f
If:function(fn){
var $ = this.filter(fn);
$.__If__ = this.filter(function(){return !~$.index(this)});
return $;
},
ElseIf:function(fn){
var $ = this.__If__.filter(fn);
$.__If__ = this.__If__.filter(function(){return !~$.index(this)});
return $;
},
Else:function(){
return this.__If__;
},
Do:jQuery.fn.each
});


... and now try to enjoy it :D

Kind Regards

Thursday, October 23, 2008

Subclassing JavaScript Native String

Just a quick post about subclassing native String constructor.
All we need is to redefine valueOf and toString methods.

function $String(__value__){
this.length = (this.__value__ = __value__ || "").length;
};
with($String.prototype = new String)
toString = valueOf = function(){return this.__value__};

With incoming V8, TraceMonkey, Squirrelfish, and other (if any ...) advanced engines that transforms repeated code into machine one, performances wont be a problem anymore and everybdy could create its own implementation of the String.

Of course, these statements will be preserved:

var s = new $String("abc");
s instanceof String; // true
s.constructor === String; // true

while typeof will return an object but we can easily use another method such:

$String.prototype.type = function(){
return "string";
};

alert(typeof s); // object
alert(s && s.type()); // string

concat as other native methods willl work, but returned object, unfortunatly, wont be a $String.

Wednesday, October 22, 2008

Big Douglas begetObject revisited recycling a unique function

With the precedent post I realized I wrote a really tricky way to extend inline a function.Next code is the snippet summary:

MyExtendedConstructor.prototype = function(Function){
var callee = arguments.callee;
if(!(this instanceof callee)){
callee.prototype = Function.prototype;
return new callee;
}
}(MyBaseConstructor);

Above code uses the closure itself to create the intermediate constructor.
The reason i chose this way to operate that task was: why should I use another function when I already have one that is the closure itself?

Well done, one function instead of two ... but wait a second, why should I create a different function everytime instead of recycle a single one?

Douglas Crockford begetObject concept


In one of His historical posts, Big Douglas describes simple JavaScript inheritance and object cloning using an intermediate constructor. This is the Object.create function:

Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};

Above snippets is still used in I do not know how many JavaScript libraries or code over the net, to extends constructor prototypes or to create a clone of a generic object.

The snippet is clever, powerful, "perfect" for its purpose, but it creates many functions for each object and your JS engine, as your RAM, has not shields to prevent its aggressiveness when you use thousands of times that snippet.

This is a benchmark function example:

function bench(create){
for(var original = {test:"test"}, o = create(original), i = 0, time = new Date; i < 500000; i++)
o = create(o);
return new Date - time;
};

If we test above function with Douglas Object.create one, the result will be something like:

FireFox 3.0.3 - Intel Core2 6600 @ 2.40 - 2GB DDR2 RAM
------------------------------------------------------
Memory: 121.676 Kb
CPU: 50% (not responding)
Elapsed time: 1769 ms



Object.create revisited version


Next snippet is my revisited version of that function:

Object.create = function(Function){
// WebReflection Revision
return function(Object){
Function.prototype = Object;
return new Function;
}}(function(){});

these are advantages about recycling the function:

  • memory should not be increased, the function is one

  • execution speed should be faster, no functions created for each call

  • apparently, not a single behaviour different from the good old snippet


While these are results with the same configuration:

FireFox 3.0.3 - Intel Core2 6600 @ 2.40 - 2GB DDR2 RAM
------------------------------------------------------
Memory: 37.332 Kb
CPU: 35% (responding)
Elapsed time: 855 ms

Seems to be quite impressive, isn't it? Results are tremendously different with Internet Explorer, where the good old way lets the browser ask if it is the case to stop the script: thousands of milliseconds against approximately 1200 with my revision.

Not only to clone


I tested my revision to extend constructors as well, and everything seems to be absolutely fine. This is the function, based on the precedent one:

Function.extend = function(A, B){
A.prototype = Object.create(B.prototype);
A.prototype.constructor = A;
};

// Usage Example
Function.extend(MyExtendedConstructor, MyConstructor);


Why does it work?


Everything is about the clone strategy itself. When we clone an object, it does not matter that the original one is modified, the cloned will be an object a part.
Since the constructor used to create the clone is private, and since it is never modified by the function itself, it does not matter how many times we reassign its prototype, since the only important thing is when we create an instance with new keyword. That instance wont loose its inherited methods or properties.
As example:

function A(){};
A.prototype = {sayHello:function(){alert("Hello")}};
var a = new A;

// prototype redefinition
A.prototype = {};

alert(a instanceof A); // FALSE
a.sayHello(); // Hello

As I said, when variable a is created, it inherits everything from A.prototype and, of course, if A.prototype inherits from another constructor, the chain is respected and classic inheritance emulated. Using the unique function inside that closure, we are doing something like this:

function A(){}; // generic constructor

function Intermediate(){}; // intermediate function
Intermediate.prototype = {sayHello:function(){alert("Hello")}};

// assign the prototype creating an instance
// the instance does not loose its methods
// inherited during its constructor
A.prototype = new Intermediate;

var a = new A;

// we are changing the constructor prototype
// but A.prototype is an instance of the precedent one
Intermediate.prototype = {};

// the method is still there
a.sayHello();

// the prototype has not been changed
// when created it inherited precedent
// methods or variables
var b = new A;
b.sayHello();



Conclusion


In my opinion there aren't side effect but only performances and memory consumption improvements for every browser.
I do not know why I did not think about this way to recycle that function before, but for sure I will never use a new intermediate constructor again, unless somebody will post valid reasons to do it.
Finally, if everybody knew about this tricky way to recycle the constructor, I am sorry, I am late.

a new Relator object plus unshared private variables

This is a Robert Nyman's post dedicated reply, about JavaScript inheritance and alternatives and private variables.

First of all, I would like to say thanks to Robert for both interesting articles He is writing about JS inheritance, and a link to a personal comment which aim was to bring there my "old" documentation about classical JavaScript inheritance and usage of prototype, closures, and public, privileged, or private, scope when we create a constructor.

About


Last Rob's post talk about private variables, describing them as shared, if present outside the constructor, and valid only for singleton instances.
This is true, and could cause a lot of headache if we are not truly understanding closures and prototype shared methods behaviour, but there is a way to use this peculiarity about shared private variables to create dedicated private variables.

Before I will write about it, let's look into a generic shared private variable example:

Click = function(){
// closure for private methods / variables

// private shared variable
var _total = 0;

// returned constructor + prototype
function Click(){};
Click.prototype.add = function(){
_total++;
};
Click.prototype.getTotal = function(){
return _total;
};
return Click
}();

var left = new Click,
right = new Click;

left.add();
alert(right.getTotal()); // 1

Above example shows that if a variable is created outside the constructor and prototype shared methods use that variable, every call to one of those method from a generic instance will modify that single private variable, created once inside that closure. To obtain a private variable we need privileged methods:

Click = function(){ // privileged methods
var _total = 0;
this.add = function(){
_total++;
};
this.getTotal = function(){
return _total;
};
};

var left = new Click,
right = new Click;

left.add();
alert(right.getTotal()); // 0

As discussed before in my doc, in robert's posts, and everywhere else in the web, privileged methods create many functions for each instance, and with big projects this is not good for both memory and CPU usage.

new Relator object and unshared private variables


The Relator is an object capable to relate a generic variable with a clear object, without modifying the original variable.
The classic example is this:

var myNum = 123;
Relator.set(myNum).description = "I am number 123";
alert(myNum.description); // undefined
alert(Relator.get(myNum).description); // "I am number 123"

Since with Relator it is possible to create a unique relation between a generic object and a private Object, it was natural for me to think that a private variable could be a Relator like object using this as unique relationship.
The new version of my Relator still respect the precedent API, being a Relator itself, but is now able to return a new object Relator like that could be used, as example, inside a closure.

// new Relator can create a Relator like object with method "$"
PrivateRelator = function(Relator){
// Relator argument is a new Relator like object
// present only in this scope
return {
get:function(what){
var value = Relator.get(what);
return value && value.value;
},
set:function(what, value){
Relator.set(what).value = value;
}
}
}(Relator.$()); // create a new Relator

Relator.set(window).value = "Hello World";
Relator.get(window).value; // Hello world
PrivateRelator.get(window); // undefined
PrivateRelator.set(window, "Hello Private World");
PrivateRelator.get(window); // Hello Private World
Relator.get(window).value; // Hello World

The good part of Relator is that the stored variable, if it is an object, is stored by reference, and we can assign more than a private unique relationship between a single object and our extra informations.
The same pattern could be easily re-adapted to create a shared private variables:

Person = function(){

// private methods
function _getName(){
return _private.get(this).name
};
function _setName(name){
_private.get(this).name = name;
};

// private variable, shared by every function in this scope
var _private = Relator.$();

// constructor + prototype
function Person(){
// bridge to _private shared variable
_private.set(this);
};
Person.prototype.getName = function(){
return _getName.call(this);
};
Person.prototype.setName = function(name){
_setName.call(this, name);
};
return Person;

}();

// extended constructor
function Enhanced(){
// necessary to save
// this instance into _private variable
// accessible only via Person scope
Person.call(this);
};
(function(){ // quick runtime extend
var callee = arguments.callee;
if(this instanceof callee)return;
callee.prototype = Person.prototype;
Enhanced.prototype = new callee;
})();


var me = new Person(),
rob = new Enhanced();

me.setName("Andrea");
rob.setName("Robert");

alert([me.getName(), rob.getName()]);
// Andrea,Robert


Conclusion


Sometime a limitation could be easily managed to obtain desired result.
In this case, thanks to JavaScript closures and its prototype nature, the shared variable become a sort of bridge to obtain private variables for each instance.
It is important to understand that even if we extend the base constructor, every new instance will still persist into original _private variable, inside the Person scope, unless we do not specify a different one, redefining every method that use that variable as well:

(function(_private){
Enhanced = function(){
_private.set(this);
};
(function(){ // quick runtime extend
var callee = arguments.callee;
if(this instanceof callee)return;
callee.prototype = Person.prototype;
Enhanced.prototype = new callee;
})();
Enhanced.prototype.getName = function(){
return _private.get(this).name
};
Enhanced.prototype.setName = function(name){
_private.get(this).name = name;
};
})(Relator.$());


See you soon ;)

Wednesday, October 08, 2008

JavaScript bits and bops :-)

This post is about a couple of probably useful JavaScript functions, that on daily basis could make our code smarter ;)

String.prototype.Replace


Ok, ok, a prototype into a native constructor is not a good start point, but this one, strings dedicated, is probably one of those "must have" protos, a Replace with multiple inputs, as is for PHP.

String.prototype.Replace = function(replace){return function(RegExp, String){
if(!(RegExp instanceof Array))
RegExp = [RegExp];
if(!(String instanceof Array))
String = [String];
for(var result = this, i = 0, l = 0, index = RegExp.length, length = String.length; i < index; i++)
result = replace.call(result, RegExp[i], String[l < length ? l++ : l - 1]);
return result;
}}(String.prototype.replace);

With above prototype it is possible to search and replace with multiple RegExps and multiple replacements. The proto works as native replace one, but it is possible to perform a replace like this as well:

"abc".Replace([/a/, /b/, /c/], "d"); // ddd
"abc".Replace([/a/, /b/, /c/], ["c", "a", "b"]); // cab
"abc".Replace([/a/, /b/, /c/], ["d", function(){return "e"}]); // dee

Tricky enough?


A meanwhile function pattern


Sometime we need two arguments for a generic callback, but sometime we need to do something between the first argument and the second one.
A common generic example could be a time based callback, where we need to get a start time, to perform an operation, and then an end time.
With a simple pattern like this one:


function meanWhile(before, after){
if(2 < arguments.length)
after = arguments[arguments.length - 1];
// do stuff ... return other stuff
return after - before;
};

We are able to execute a couple of interesting operations.
A timing example is this one:

function bigLoop(){
for(var i = 0, max = arguments[0] || 1000000; i < max; i++);
};
meanWhile(new Date, bigLoop(), new Date); // 180 or less if your PC is faster
meanWhile(new Date, bigLoop(), bigLoop(), new Date); // 360 or less ...

Can you imagine better applications?

P.S. It's long time I do not post guys, sorry but it's really a busy period :)

Wednesday, September 17, 2008

jSmile 0.4 - Stand alone Version

nic comment:
hey. thank u for that awesome plugin. how can i download the smilie package? i want to host them on my webspace because i want to be independet from other hosters.

I have recently updated my jQuery plugin, called jSmile, and the biggest news is that it does not require anymore external resources.

Thanks to inline uri data, the script now comes "full optionals", or better, with base64 encoded GIFs images included.

Instead of external CSS classes, images, and cross host dependencies, jSmile can now easily be integrated in every http or https site, and without network delays.

Its size is obviously bigger than before, but using a minifier and gzip compression, it fits perfectly under 7Kb.

Compatibility



  • Chrome

  • FireFox

  • Internet Explorer 8

  • Opera

  • Safari

  • WebKit



Enjoy ;)

Tuesday, September 09, 2008

Internet Explorer Security Hole - A Better Example

Again, about the security hole I talked about last posts, but this time with a really simple example.

How does the example work



  • Open Internet Explorer, whatever version

  • Go in this page

  • Write a fake user name and a fake password, or a fake email address and a password

  • Click Submit



What does the example do



  • Emulates user actions via javascripts

  • with some version of IE, it could be able to grab both fields values

  • in any case, it demonstrates you that every site could steal your compiled fields in every other site, if the autocomplete option is not forced to be disabled



What could do a malicious, and hidden, code



  • steal your data

  • steal your email

  • steal your credit card information (a really famous company, as example, suffers this problem, so somebody could steal credit cards details of million of people)

  • steal your details

  • steal your searches via common search engines

  • etc, etc



More details in my old post I wrote last Saturday, the one that few people read carefully, understanding what was going on.

This is not a new bug, it exists, and I knew it, since 2004 or before, when banks did not use security checks, yet.

Kind Regards, and please choose another browser until Microsoft will not fix this problem for every IE.

Monday, September 08, 2008

Internet Explorer 6, 7, or 8 exposes users data via JavaScript

Ok, ok, I know these are Google Chrome dedicated days, but how can be possible that my last post did not receive attention at all?

Maybe with this title somebody will read more carefully what I wrote few days ago ... or maybe not, who knows? :?

Thursday, September 04, 2008

Security Basis, and an Internet Explorer data stealer

It has been about 4 years, or more, that I know about this problem, but for some reason I did not talk about it, scared by possible reactions.

In other words, I was waiting for some noise over the net, or some fix from Microsoft, but nothing is happening.

Actually, Microsoft is working hard on Internet Explorer 8, but the problem I am talking about, is still present ... so, I suppose it is time to tell you how dangerous this IE "feature" could be, and how dangerous could be to forget a little detail in a form, like the autocomplete attribute.

The magic autocomplete option


Every browser tries to make our net life as simple as possible, and when we start inserting data in an input field, it suggests us a couple of words or, if the name of that field is unique enough, directly the most probable word, name, or number, we are going to insert.
To perform this operation, we could start typing the name, or simply use the down arrow button to open the list of options, and choose, usually, the first one.

More magic than ever


In some old Internet Explorer versions, like the the 6th one, when we are filling out a login form, we simply need to insert the name, or email, and the password field will be magically populated.
This means that with 3 buttons, 2 down arrows, and 1 enter, we can perform a login.

Magic IE JavaScript


Internet Explorer allows JavaScript developers to fire events simulating user mode.
This means that if we have a focus on an input field, and we fire the keydown event, with down arrow code, the suggested list of options will magically appear.
At the same time, if we repeat the procedure, the first option is highlighted, and if we repeat the procedure again, the second option and so the third one, if any.
More beautiful, is that if we fire the event another time, this time using the enter code, the field will be populated.

How to steal information from the Internet Explorer users


Accordingly, if a malicious website is replicating a form, which user has filled out ones on a genuine website and a dedicated JavaScript starts automatically interacting with the replicated form, the Internet Explorer will silently expose user's information, previously used in "who knows" how many different websites.
A simple, well organized process could try different combinations N times, saving results in an object, or an array, and then sending that information via ajax or a basic get request to a server, allowing the malicious developer to save and reuse that information.

A real world example


To show you what I am talking about, I have created a simplified version of the described script.
Most important things to remember:

  • any displayed information, if any, will not be saved, but only displayed in an alert window, so with my example your data is still your one

  • only Internet Explorer, as far as I know, allows JS developers to create such malicious code to embed in a webpage (that's why I posted about FireFox crash, few days ago :))

  • apparently, IE8, and probably 7 too, do not let developers steal entire login information


To perform this test, you need to use Internet Explorer. If you have never used, or used it only to debug or develop some web applications, please try to login into your favourite web services, for example Gmail.
After that you can directly test my safe example page, and wait few seconds to know if my application was able to get your email account, or whatever else information.

Which websites expose user information?


I am sure this problem is not a secret for Microsoft IE Team, since in every login form, starting from hotmail, they force the atocomplete option to off.
Therefore, it is not possible to steal, for example, hotmail emails, but if you use the same address to login in to another website, which for some reason does not implement the autocomplete off option, it becomes obvious how thousands of spammers can obtain our email addresses in such an easy way.
Gmail login service (surprise!) does not implement the autocomplete off option, so if we use Internet Explorer to login into latter service, our Gmail account name could be easily exposed.
The worst case scenario ever, is represented by Credit Card Forms, where if nobody though about this "little security problem", our Account Name, Credit Card, Verification Code, and whatever else private information, could be grabbed by malicious websites, without us noticing it.
Of course, the expiration date is not that simple to retrieve, but what a powerful weapon this IE feature can be to enhance phishing?
Just try to imagine a page, with similar URL, that already contains all information, but misses only the expiration date, requiring user verification.

As Summary


Other browsers probably know about this problem, since nobody lets JavaScript interact with webpages in the real user mode.
The fix I can simply suggest, is to disable the autocomplete option in Internet Explorer or, even better, change the browser to be sure that if we are inputting our details on a website, that information will not be readable from any other website without our authorization.

Have a nice week end :P

Tuesday, September 02, 2008

Google Chrome Fix

Update 2008/09/04
I have created a new version that should be able to recognise the correct Google directory in every supported windows, and not only English version.

Please do not hesitate to tell me if the created link for No Sandbox Option is not creating it properly, thank you.

Google Chrome Fix Multi Language OS
-----------------------

I successfully tested the new browser in my laptop, while today I had some headache at work.

This is the reason I created in few minutes a simple Windows Application that let you choose which option you want to solve crashes during Google Chrome startup:

The application failed to initialize properly (0x00000005). Press Ok to terminate application.


Please note that the registry fix option changes a key that should solve Symantec problems, but it is not clear if this key could change security level for those PC that use Symantec end point protection, or similar softwares.

In every other case, the GUI create a link to launch Chrome without multiple sandbox, and if I am not wrong, it should mean that multi tab will not be multi thread.

Here you can find the project page, where there is a download section and an executable file.

Thanks to AutoIt developers, and ~d-bliss for the icon.

Enjoy :)