Showing posts with label Projects. Show all posts
Showing posts with label Projects. Show all posts

Sunday, August 7, 2011

The Lovely Future Of RightJS

Okay, let's make it official, shall we?

Folks, I'm forking RightJS. And before you start screaming like "omg, we all gonna die in here!", calm down, RightJS ain't no going nowhere. The thing I do is future oriented and quite different from RightJS itself. So RightJS will stay where it is, I'm using all the same servers for the fork, so RightJS will be available as long as people use it. And I certainly will apply patches as much as I can.

Just, there will be no RightJS 3.0, RightJS 3.0 will be called lovely.io


So, What's That All Aboot?

Folks, it's not a secret, that monolithic frameworks are dead. Dead as Java. The future is in small, agile and modular libraries and this is where lovely.io starts.

In RightJS we already had kinda modular structure, you could go to the building page and switch off things that you don't need. The problem with this approach is that it is not suitable for the nova-days CDN hosting, all the permutations of a dozen options were blowing the 15k small library into a huge collection of files that weighted several hundreds megabytes and was almost uncacheable. You could host it by uself, but on CDN even if we host it, the chances that another user has the same configurations are slim and it would be pretty much the same as if you host it on your own domain.

Lovely.IO is not really a framework as you might think of a normal javascript framework. It is more like a CDN based package management system. In lovely.io all the RightJS core got split apart on several packages.

* 'core' - basically RigihtJS Class, Events (former Observer), utility functions + some new stuff
* 'dom' - the dom manipulations from RightJS + new jQuery like collections handler
* 'ajax' - new XHR2 based ajax module
* 'cookie' - the cookie module
* 'lang' - JavaScript core extensions
* 'sugar' - syntax sugar for the 'dom' module, things like "something".something() and so on.

Every package is pretty much independent and you can choose what you want. If all you want is 'dom' you just hook it up and it will be just that. If you also like some JavaScript core extensions, then you hook the 'lang' module. Need to do some ajax? Include the ajax module. It's completely up to you what load and what not.

A generic example would look like that

<html>
<head>
<script src="http://cdn.lovely.io/core.js"></script>
<script type="text/javascript">
Lovely(["dom", "ajax", "fx"], function($, ajax) {
ajax.load("/some.url", {
success: function() {
$('#some-element').html(this.text).highlight();
}
});
});
</script>
</head>
</html>

Basically wha happening in there is that you firstly include the lovely.io core package which just 3k of code and provides the modules handling. After that, you can specify the modules you need and once they're loaded (happens asynchronously) your callback function will be called where you can do whatever is it you need to do.

The example above is a bit simplistic. In reality it also automatically handles all internal dependencies, versions and so on. Check out this example, it's a little game, it uses 'dom' and 'cookies', but it also uses another packages like 'timer' and 'hiscore' to function.

This way we are going to have a rubygems like system where anyone can create and share modules, which can relay and reuse each other. All modules including the standard ones will be more or less equal and independent.


Automatic Packages Hosting

Another thing that I'm solving with lovely.io is automatic packages hosting. No more mangling with CDN, demos, documentation and so on. Once you create a package it will be automatically hosted at cdn.lovely.io which sits on Amazon's CloudFront. And it's not just scripts, all your asset images also will be there, automatically and free.

The basic idea is to completely eliminate the process of modules installation. All your package users will have to do is to specify the package name and version in the dependencies, all the reset will be automatically served from the super fast amazon hosting.

Check the mines game I mentioned above. Take a look into the HTML code of the page. It is fairly complex widget, it has some styles and depends on some images, more of that it is a compound widget, the hiscore block is provided by a completely different package. Yet all you have to do to make it working is this

<script type='text/javascript'>
Lovely(["mines-game-1.0.1"], function(Game) {
new Game().insertTo('#game-container');
});
</script>

And it's not all. The micro-modular structure also will provide a big deal of caching optimization. As all the modules are hosted at the same CDN domain, they all will be cached one by one in the user browsers. And because of that the most frequently used packages will be always in cache.

Say a user opens up a page that uses packages A and B, then he goes to a page that uses A, B and C. All he really downloads on the second page is C.


About The Packages

The cool stuff is not over people. Concentrate, because there is more of awesome news!

The other thing is how you actually make the packages. By default there is no JavaScript. Yup, you've heard me. The actual packages code is written in CoffeeScript and SASS (though you can use JavaScript + CSS if you like). Check for example the source code of the mines game from the above. It is all nice and clean now.

How it works? Quite simple. Lovely.IO is not just a hosting. It also has a CLI tool called `lovely` which is much like ruby-on-rails thingy. You can create a project, you can launch a development server and so on.

Then you write your code in whatever you like, and once you're ready do share it with the public, the tool will compile everything in JavaScript, minify using Ugly and push to the lovely.io server. More of that it will automatically use your README and index.html files as landing and demo pages on the server.

You can structure your project as you like, you can have as many files as you like. You can use CoffeeScript or JavaScript, SASS or CSS, or even Stylus. It all doesn't matter for the end result.

Finally you can do the front-side development in a clean and civilized way.



Other Stuff

There is one thing among this awesomeness though. Lovely.IO is an HTML5 oriented thingy, there is no IE < 9 support, not like I couldn't, just it's thankless job to support those old browsers. I don't wanna do that, you don't wanna do that, and the guy next to you don't wanna do that either.

So, in lovely.io there will be no old IE browsers support in the standard packages, plus there is a good chance that I'll be nuking any other packages that will try to provide the old browsers support explicitly.

Basically, this is where I'd like to draw the line between RightJS and LovelyIO. If you need something well tested with old browsers support, use RightJS, it will be around as long as you want it. But, if you're building a modern HTML5/CSS3 application then you might want to consider LovelyIO, this is where all new stuff will go.


Current Status and Future Plans

At the moment Lovely.IO has all the modules from RightJS core + RubyOnRails support module + I've made a bunch of demo projects over here. It appears to be more or less stable (it's based on RightJS after all), but there is no UI yet.

There is also not much of documentation either. I've just opened the registration for early adopters. So if you wanna play with it, please check the main repository, this is where the STL packages live. It's mostly the good old RightJS with a bit of lean towards more standard jQuery behavior for the $ function.

The next step in the project will be automatic documentation hosting for the packages and then I'll start to port UI modules from RightJS, so if you want me to port something specific from RightJS UI, let me know I'll try to make it a priority.


--
Okay, I think that's the whole introduction for now. I'll give you more when I get to the documentation.

Thursday, April 28, 2011

Why Make A Run For It

It has been almost two years since I decided to go public with RightJS and on this occasion I'd like to post some reflections on it.

Those days, thanks to github, it's pretty simple to start an open-source project. You just make a repo, write some awesome stuff and push it under the "I don't owe you shit" license. And I like it, in most cases that's all you really need. But, as fun as it is, there is actually another level to open-source projects. The level, where you decide to get serious about it and go public with your project. With promotions, users, official site, docs, tutorials and so on.

It is not completely necessary to make your project kinda "officially public", in many cases it might be even a bad idea, because that will distract you from the actual programming, but there are several important things in this process, which can be pretty valuable as well. And that's what I'd like to write about today.



It Will Make You A Better Programmer

The trouble with programmers is that we work in this area where most people don't really understand anything. And because of that, at some level, programmers tend to start thinking that they are pretty darn smart and kick ass.

A healthy portion of self-esteem is not a bad thing, it might help you to overcome some small obstacles on your way, but for a programmer as a knowledge worker it is crucial to stay hungry for new information.

And running your project for real, will give you exactly that. If you do something interesting enough, people will respond, they will throw all sorts of ideas at you, they will criticize and they will like (hopefully :)) some parts of your work, which will give you all sorts of new information.

With new information you'll face new problems and discover new ways to solve them, and that will make you better at what you do.



It Will Make You More Organized

It is not a secret that many developers don't like TDD and Tickets. Even the ones that do, often cheat and don't cover everything, don't document bugs and so on.

But, when you start an open project for real, you will have to deal with those things. You will have to handle tickets, document bugs and cover everything you can with tests so that folks who use your code had a hight quality experience.

More of that, most open-source projects, especially individual ones, are just about "scratching your own itch". It is highly doubtful that you will make any real money directly from your project, and as much as you might enjoy the creative process of writing code, at some point, you will have to get pragmatic about what you do.

You will need to start thinking strategically, where is it worth to invest your time and where it's not. And that is a highly valuable skill, not just for developing a software project, but genuinely in life.



It Will Make You Better With People

Well, you know what they say "all programmers are bad with people" :). The thing is, that people are irrational, even the smart ones. And there is only one way to learn how to deal with irrational - by accumulating experience.

One of the hazards of the trade is that programmers spend most of their time with computers, and that's certainly not a good thing for your social skills.

When you run an open-source project you will have to handle contributors and do that nicely. Because contributors are privilege. But as all people have different coding styles, different ways to approach issues and just different personalities, you will learn how to find common grounds with different folks, how to work together and how to coordinate the changes.



Conclusion

I don't want to sound like an open-source project is the most awesome thing that might happen to you. By the end of the day, if you're vicious bastard then all that will help you is an old-fashioned kick in the ass.

But, if you're interested in software-development, if you want to learn why and how the things done, running your own project for real might be very insightful and teach you quite a few things.

Sunday, January 9, 2011

RightJS 2.2 RC Public Test

My dear fellas rightjslings (or whatever the hell we are) I've got some good news for our species! I took a bit of a break from RRTE those holidays and packed ourselves the next major update in the RightJS core, which will go by the number 2.2.0. And I would really like you to play with the thing. Bring some joy and magic in the routine, and start the year with the new shiny toys!

Awrighty, now to the business. You can download the thing from over here (NOTE: there are updates for all the plugins as well).

And as for the changes, there are quite a few of them actually, so let's get through them one by one


Native Fx Support

The first thing that RightJS 2.2 brings is the support of native css-transitions in the visual effects engine. There is not much of changes in the actual API, RightJS will automatically figure everything out and use native features when available.

Currently it runs on Safari, Chrome and FF4. Opera also supports them but I have disabled it for Opera by default, because first of all their thing is buggy (doesn't support say font-size and background-position) and secondly our own, javascript based engine works faster than their native feature :)

Anyhow, if you insist to switch it on in Opera or disable in Webkit/FF4, use the new engine option with your effects, it can be either 'javascript' or 'native'


Class and Wrapper merge

The second biggest change is that the Class and Wrapper units were merged to make an uniformed classes structure where the Class unit is the top parent of everything.

The new Wrapper construction won't work anymore, use the standard new Class calls as you do when you define any other class.


Supercalls On Modules

The other outcome of the Class unit update is that now you can call the $super method not only on inherited classes but with injected modules as well. It kinda looks like that


var Klass = new Class({
method: function() {
return "original";
}
});

Klass.include({
method: function() {
return this.$super() + "+module1";
}
});

Klass.include({
method: function() {
return this.$super() + "+module2";
}
});

new Klass().method(); // -> "original+module1+module2"

This comes very handy when you need to overload some certain methods without using the actual inheritance. Before, we used to use all sorts of old_method hacks, now it's all nice and civilized.


Builtin Mouseenter/Mouseleave Handling

RightJS 2.2 will come with built in mouseenter/mouseleave events handler. As usual it all handled automagically, just use the 'mouseenter' and 'mouseleave' event names and be happy. Works both ways, directly with elements and via UJS.


$('element').onMouseenter('addClass', 'hovered');
$('element').on('mouseleave', 'removeClass', 'hovered');

"div.something".onMouseenter('addClass', 'hovered');



Better UJS

Another major update is that now UJS handlers got triggered by nested elements as well, just like with the normal dom-events. Basically it means that if you say have a structure like that


<div class="something">
Some text in here
<div>some inner element</div>
</div>

If you attach your UJS listener like that


"div.something".onClick('toggleClass', 'clicked');

Then it will get triggered no matter if the user has clicked the div.something element itself or any of its internal elements. No more hacking this stuff around.


Pretty Collections Handling

And one more sweet thing the RightJS 2.2 release will bring. I know you all love the String#on method to handle the UJS features, so I had extended it a bit further. Now you can run basically any Element methods from strings, just like that.


"div.something".addClass('red');
"div.something".removeClass('red');
"div.important".highlight();
"div#some-crap".remove('fade');
....

Those basically shortcuts for $$(css_rule).each('method', args); it finds all the elements matching the rule and calls the method on them.


----

There are more fancy things in there, like various performance optimizations, IE8 was kicked out in the olds module, all CSS3 selectors now work everywhere, and so one and so one. I'll describe everything with the actual release.

For now you just have fun with the new sweet features and come back if you have any troubles.

Wednesday, December 1, 2010

RRTE Status Update

Hey folks! It's been couple of weeks and some of you started to wonder, where's Nik with his RRTE and the world domination, so here is the status update.



As you can see, we are having some serious progress. Most of the things you see on the picture are already working, but I'm trying to explore some possibilities and features.


What's Wrong With the World?

It seems that the design-mode support in browsers is utterly broken. It's ugly, limited, uncomfortable to use and behaves differently in different browsers. Well, just like the whole JavaScript business :)

There is basically two modes how the design-mode works in browsers, the tags mode and the css-mode, in the first one the browser tries to use tags to style the content, in the other one it tries to use styles. The trouble is that IE supports the tags-mode only and FF supports both, but in any case both of them do that wrong.

You see, in the tag mode say they use obsolete FONT tag to style fonts, but in this case FF doesn't support for example proper selections highlighting, they also for example use STRIKE instead of S tag and there is no way specify it. In the css-mode, the browsers try to use things like style="font-weight:bold" instead of the <B> tag pair, which is quite inflexible if not to say idiotic in terms of CSS. It also incorrectly reacts on all sorts of things, like say it will show the U tool "on" when you put your cursor on a link, and you won't be able to switch it off because it's styled with css.

And so one and so one. There is are lots of small and big fuckups like that, and honestly it is quite a mess.


Time To Fix It!

Being an arrogant idiot, I couldn't just pass by this mess, so now I'm building my own engine, which will do precisely what we need on any browser. Basically there are two sets of tools, one of them allows you to work with the style attribute, the other one allows you to format anything with any tag you want, and, what's more important, with any attribute you need, which means that you can use ids and classes as well.

The formatting setting is not limited to the H1-H6, PRE and ADDRESS tags anymore. You can easily specify say things like that

Rte.Formats = {
'h2': "Header 2",
'tt': "Typetext",
'blockquote': "Block quote",
'div.blue': "Blue block",
'div.green': "Green block"
};

Etc, etc. The basic plan is to create some sort of a mixed, truly css-oriented mode. We will use SPAN + style attribute for things like custom colors and fonts, but for everything else use normal tags and classes, so that the editor produced a nice and easy to process and support content.

It's a bit tricky, but we will get through it.


Advanced Tools

The other thing which I'm trying to figure out is how small an RTE can be, or how much features can we squeeze in 10k? Advanced OOP features of RightJS are really helpful in this case, because all the inheritance and functionality injection features allow us to create really compact and flexible code. As you can see I already added the color tools, font name and size tools, formatting options and some other things. At the moment all of that weights about 8k of gzipped code (and that includes all the css).

So I'm trying to add more features in the standard package than I originally planed and see where it will lead us. We might drop some of them into the extensions pack later on, or, if everything will go smoothly, we might not need one and all the standard functionality will be available in the basic build, so that we will have just a core and plugins. Or something like that. Will see.


--
Well, this is basically it for the moment.
To be continued...

Friday, November 12, 2010

RightJS RTE Concept

In case you were wondering why it was quiet around here for last couple of weeks, I'd like to share some stuff I've been secretly working on and what are the future plans.

Basically we are taking a little pause until Mozilla guys sort their stuff out and release FF4 or at least 3.7, which we need to execute our evil plan for RightJS 2.2.

Meanwhile I've been working on this puppy



Yup, it's a RightJS based RTE that will most definitely take over the world, and so you started to want it for xmas, I'd like to put some words in about what's what and stuff.


Meet RRTE The Frameless

One of the major differences from usual RTEs is that our RTE (which goes under the codename RRTE) does not use any frakking frames. Instead, it uses an inlined DIV with contenteditable="true" property.

If now you're wondering what it gives you, then this is what:

Because it's an inlined div, all the content inside of it will follow all the styles on the page, which means no more headache with transferring and applying your styles to some iframe. If you take a look at the picture, you'll see that the header text inside of the editor has exactly the same font and size as the header on the main page. The blockquote and pre tags are also painted through usual CSS right on the page.

Secondly, because it's just a small inlined piece of page, RRTE works and feels much faster than any IFRAME based editors. It is super fast, practically it feels almost like a plain textarea element.

Thirdly, because all widgets in RightJS UI are plain elements, you will be allowed to easily access and manipulate any content right inside of the editor via standard API.


Modular

The second most important feature of RRTE is that it will be modular. Unlike all the other heavy duty RTEs, our RTE, by default will be mainly social networks oriented. It's main purpose will be to work as a lightweight embeddable RTE for all sorts of things like comments and blog posts where you already have all styles in place and just need some nice and shiny thing instead of textareas.

For this reason the default package will contain the main core/engine and provide basic editing tools which you can see on the picture above. Currently it weights just 4k of gzipped code (including stylesheets) and my intention is to keep it under 10k size.

And for all the advanced functionality, like file-pickers, fonts, tables, etc. we will have a separated package, which will turn the editor in a normal heavy duty RTE.


Extendable

As you can see, my plan for RRTE is to extend it via plugins. I don't have any intention to implement everything in it, instead of that RRTE will have a proper OOP design in best RightJS traditions, so that you could make your own tools and extensions, using classes and inheritance. In case if you're wondering how it's gonna look like, here is an example how the Save button is implemented


Rte.Tool.Save = new Class(Rte.Tool, {
shortcut: 'S',

initialize: function(rte) {
this.$super(rte);
if (!rte.textarea.form()) {
this.disable();
}
},

exec: function() {
if (!this.disabled) {
this.rte.textarea.form().submit();
}
}
});

RRTE will provide you with basic tools and open API, so I expect it to be pretty civilized and easy to extend.


What and When

Currently I keep all the fun for myself. This thing is not on github yet, basically because I hack and refactor it alot. Some parts are still quite flimsy and as I don't want you to have a wrong impression about it I'm going to keep it locally for the next week or two.

At the moment it appears to me that I'm done on about 40-50%, but as I'm a bit busy those days it is hard to estimate the exact schedule. Judging by my guts I should push something worth of seeing on github in about couple of weeks and probably will have the first release by the end of November/beginning of December.


This is basically it. Enjoy the news!

--
Oh, and one more thing. I could use some help with a default iconset for this widget. Currently I use some free stuff that I found over the internet, but if you can and willing to draw some particularly cool uber-iconset, that would be much appreciated!

Monday, October 25, 2010

RightJS 2.2 Notes

I'm cooking a new evil plan for RightJS 2.2 release and would like to share some thoughts and notes, so you knew what's going on and where are we heading.


Native Fx

We are living in an interesting moment. Native CSS transitions are finally becoming reality. Safari does it, Chrome does it, Opera does it, FF4 does it (they promised they will include the feature into the 3.7 release). IE9b does not. Rumors has it, the feature will be in the final release, but I have my doubts it will happen.

Anyways, now, when the majority of sane browsers support the feature, I think it's the right time to start using native CSS transitions as a default option for our dom-morph effects. It is faster, simpler and more reliable.


Better UJS

The current implementation of UJS in RightJS works with an event target property only. The trouble with this solution is that when you have something like

<div id="one">first
<div id="two">second
<div id="three">third</div>
</div>
</div>

and you attach an event listener to say the top one

"div#one".onClick(function() {
...
});

it will reacts only if the user clicks on the div#one itself and will successfully ignoring clicks on the inner element. Sometimes that's what you need, but in majority of the cases it creates more confusion than helping.

I'm still thinking about this one, but there is a good chance that the logic will be changed and our UJS will mimic the normal event listeners behavior and react on inner elements as well.

Hey! You will be able to make UJS stuff within UJS stuff! :)


Cookie plugin

At the beginning it seemed like a good idea to have a basic Cookie wrapper out of the box, but later I realized that on majority of my projects I don't use it. Well I assume you have pretty much the same experience.

So I think the cookie module will be kicked out of the core into an officially supported plugin. it's not much, just half a KB of gzipped code, but I guess we can fill this half a K with something more useful in everyday life.


IE8 And Pals

IE8, or as it known in some circles "IE7 on steroids" is kinda of troubling browser. The problem is that on a good half of the pages this darn things automatically falls into IE7 mode and therefore downloads the "olds" module, on the other half, it still has some troubles with native css selectors because some of CSS3 constructions are not supported, which consequentially makes some wonder-people to wonder how "right" right.js exactly is?

Furthermore the change/submit events still don't bubble and we carry quite large chunk of code in the core, to work this thing around.

So I was having that wild thought in my head, that we could ditch IE8 and pals support into the olds module so we could fix those things in there and not bother the core.

Currently, I'm considering the idea of making the line between the old and new browsers right where the CSS transitions support starts, which will effectively drop the whole IE support into the olds module.

That probably will make some jquery folks to moan that we are unfair towards them, but I'm looking into my glass ball and it says that after all the cutting and stitching, RightJS core size could drop below 12k.

Well, at least that the target. Besides there is still a tiny chance that IE9 folks will hear the voice of sanity and add css-transitions into it, then this distinction will be perfectly justified.


---

Anyhow, those are the notes and thoughts. Let me know if you have something on your mind about that

Thursday, September 9, 2010

RightJS 2 jQuerysh Plugin

Hey folks. I had couple of minutes of free time and cooked a fancy plugin for RightJS 2.

It's called 'jQuerysh' and provides the jquery-like behavior for the $() function. You can copypast or build it from over here jquerysh on github

Basically it does three things with the $() function. You can navigate in jquery-style

$('#element-id').onClick('addClass', 'marked');

$('div.class').each('addClass', 'marked');

And you can call the onReady via it, same way as in jQuery

$(function() {
// will be executed when on ready
});

This is pretty much it, might be useful for people who need to work with both jQuery and RightJS.

And yes, it works with RightJS 2 only. Not like I want to make you switch to RJS2 (which I actually want), RJS1 is simply not built for that.

Cheers

Friday, August 27, 2010

RightJS 2 Release Plan Updates

My dear fellas, this lovely Friday's evening I'd like to share with you some updates on the RightJS 2.0 release plan. And yes, by "updates" I mean delays.

No need for dirty swears, because there are two good reasons for that. 1) Rails 3 which should come out any moment now, and 2) upcoming IE 9 beta which is scheduled to September 15th. And as we all know well those funny MS folks, I think you'll agree that it's better to wait couple of weeks rather than pull your hair off later.

And it's not all that bad, there are good news too. I'm almost finished porting the UI modules to RJS 2, which means there well be the RC2 release in about couple of days I think. RC2 will include the core with all the latest updates and all the plugins and widgets ported to the new system. Generally this will be the final version and unless someone find a bug it will go to the actual release as is.

You'll have couple of weeks to play with it until the IE 9 release, and I'll have couple of weeks to brush up the docs, update rightjs.org and rework right-rails. Thinks that should give as a good runaway for a nice and smooth release.

This is about it. Take care!

Tuesday, August 17, 2010

RightJS UI 2 The Battle Plan

Hello people. As I'm currently elbow deep in porting rightjs-ui modules to RightJS 2, I'd like to share some ideas and thoughts behind the changes so you knew what to expect.


RightJS 2 With New UI System

First of all the RightJS 2 release will be not just the core release, there are lots of cool new features and some dramatic changes, so I'm porting all the plugins and ui widgets to the new development approach, and with the RightJS 2 release I'll release updates for all the plugins as well.

This way we will have some sort of a clean slate, and you'll be able to start with all new tools right away.


Widgets === Elements

One of the biggest change in RightJS 2 is those really cool object-oriented dom-wrappers feature, and in the RightJS UI 2 we will take full advantage of it. If in the current system all the widgets are classes with some limited interface, in RightJS UI 2, all the widgets will be inherited from the dom-wrappers, so you will be able to manipulate with them as if they were normal elements.

// say you have a calendar unit
var calendar = new Calendar({
// some options
});

// now you can do anything you want as if it was a normal Element
calendar.insertTo('my-element', 'top');
calendar.addClass('my-calendar');
calendar.set('id', 'my-calendar-id');
calendar.onChange(function() {
// do something about it
});

// you also will be able to access it through the standard navigation methods
$('my-calendar-id'); // -> the 'calendar'
$('my-element').first('div.my-calendar'); // -> the same calendar

// it will be also follow the general inheritance structure
calendar instanceof Calendar; // -> true
calendar instanceof Element; // -> true

You've got the picture, everything you can do with any element on the page you will be able to do with the widgets and do that directly.


Unified Initialization

RightJS UI were growing a bit chaotically during the last year and we have some diverse ways to initialize units. With the new release all of them will work via the same initialization process with the same principles. The rel hacks are gone, instead of that we will use the HTML5 data-widget-name attributes.

<input data-autocompleter="{url: '/some.url'}" />

<input data-calendar="{format: 'US', hideOnClick: true}" />


Meta-framework and Modularity

In current incarnation all the RightJS UI widgets are pretty much independent, which means that we have some duplications here and there, same things work slightly different, not really clean styles and so one.

It's time to refactor the mess, with RightJS UI 2 there will be a meta framework which will provide common bits of elements and styles, like say buttons, panels, spinners, various common functionality and so one. This way we will have a consistent elements behavior over the widgets, plus it will be easier to create new widgets with the common blocks of code already existing.


Unified Stylesheets

The stylesheets also will be cleaned up and unified. There will be common classes for buttons, panels, spinners and so one. One of the reasons is that now we will be able to create skins in a civilized way.

There will be no actual skins with the release, we simply do the preparation work, but the skins constructor is one of the first things to do right after the release.



Summary

As you can see with RightJS 2 release we will bring to the next level not just the core, but the ui modules as well.

I've already ported the Autocompleter and Calendar widgets, you can check it out at the 2.0.0 branch on github. I estimate it will take about a week to port the rest of them to RightJS 2.

After that there will be RC2 release where I'll publish RightJS core and all the modules for tests. And in about a week after that (by the end of August) we shall release.

This is about it.

And btw, if you have thoughts about new features for some of the existing rightjs-ui widgets, that's a really good moment to let me know.

Now that's it.
Take care!

Thursday, August 5, 2010

Prepare Your Project For RightJS 2

Some notes for those lucky of you who already is hooked to RightJS and the ones who think about giving it a try, but afraid that when RightJS 2 will start saving the world, the ones code will go south.

Rule #1 don't panic, despite of all the massive changes in the dom-stack and all the new finest kickassery, the actual API almost didn't change, just instead of real dom-nodes/events/etc you will receive some proxy objects, which have the same exact API. The difference is that you will have no direct access to the dom-unit attributes, so if you want your code to be working both in RightJS 1 and RightJS 2, use the Element#get, #set and #has methods instead.

// instead of this
$(element).id = 'boo-hoo';
var id = $(element).id ? $(element).id : 'default';

// write it like that
$(element).set('id', 'boo-hoo');
var id = $(element).has('id') ? $(element).get('id') : 'default';

If you need to access an element innerHTML use a simple patch like that

Element.include({
html: function() {
return this.innerHTML;
}
});

Later, when you will migrate to the actual RightJS 2, just remove it, RightJS 2 will have this method out of box.


Rule #2 don't access `window` and `document` directly, when you need to access some of the RightJS methods, put them through the same `$()` function first as you do with the dom elements

// instead of those
document.onReady(function() { ... });
window.sizes();

// call it like this
$(document).onReady(function() { ... });
$(window).sizes();


Rule #3 don't use `Form.Element` this unit will be renamed to Input in RightJS 2, so don't touch it or create a simple reference like that

var Input = Form.Element;

and work with the Input object instead.


This is about it. If you follow those three simple rules, all your code should be in working condition when you switch to RightJS 2.

Saturday, July 31, 2010

RightJS 2.0.0-rc Is Out

Okay folks, RightJS 2 came to the point where it has a proper number and the '-rc' suffix in it's name. And here are some notes on the new sweet features we have since the beta release.

You can download the build over here, the archive contains both normal and safe-mode builds.

Generally this is almost the final line, I've finished packing it with new features and this is practically all we will have in the actual 2.0.0 release. There might be some tweaks here and there during the plugins and UI modules porting, but nothing dramatic. So lets check what we've got.


Dom Wrappers

In RightJS 2.0 we have a new kick-ass object oriented dom-wrappers system. Our dom-wrappers are essentially classes, with types, inheritance and all the nice functionality injection features. Currently we have the following wrappers Window, Document, Event, Element, Form and Input, which formerly was known as the Form.Element unit.

Dom-wrappers work transparently and have all the same nice API we had in RightJS 1, the only difference is that instead of the actual dom-element all the methods now operate with dom-wrappers.

$('element-id')  // -> dom wrapper
$$('#css .rule') // -> a list of dom-wrappers

All the dom wrappers are inherited from the same unit called `Wrapper` and have a common property called `_` which refers to the raw dom element, for example

$('element-id')   // -> Element wrapper
$('element-id')._ // -> the actual dom-node

$(window) // -> Window wrapper
$(window)._ // -> the window object

$(document) // -> Document wrapper
$(document)._ // -> the document object

So every time when you fill like it, you can always quickly access to the raw unit the same way across all the wrappers.


Dom-Wrappers Typecasting

As you might noticed we have three types of wrappers for dom-elements, the Form and Input classes are subclasses of the Element class and when you access your dom-elements they dynamically typecasted

var element = $('my-form');
element instanceof Element; // -> true
element instanceof Form; // -> true
element instanceof Input; // -> false

var element = $('my-input');
element instanceof Element; // -> true
element instanceof Input; // -> true
element instanceof Form; // -> false

This way you can check which type of element do you have and you can extend all of them separately


Element.include({
global_method: function() {}
});

Form.include({
forms_only_method: function() {}
});

Input.include({
inputs_only_method: function() {}
});

You even can use polymorphism and use the same method names

And you also can define your own types, for example

Element.Wrappers.TABLE = new Wrapper(Element, {
orderBy: function() {}
});

Later on there will be also private dom-wrappers which you can use in your app without extending the RightJS core and interfere with other applications.


Bubbling Dom-Events

RightJS also received several fixes for the traditionally problematic dom-events like focus, blur, change and submit, now all of them properly bubble on all the supported browsers.

There is nothing kinky about it I didn't use any special event names, just use the usual ones like nothing happened.

$(element).on({
focus: ...,
blur: ...,
change: ...,
submit: ...
});

I also added the custom events bubbling. If in RightJS the custom events didn't go anywhere from the node where you fired it, now they properly bubble up to the document object, so you can take advantage of them using the events-delegation technique.

Speaking of which.


New Events Delegation API

In the later releases of RightJS 1.5 we already had some elements of the events-delegation feature support, now it's time to take it to the next level.

First of all the String unit now has all the same API as Element, so you don't need to learn nothing new, just use what you already know.

"#div .span".on('click', function() {...});
"#div .span".onClick(function() {});
"#div .span".onClick('addClass', 'marked');

// you also can make the normal checks
"#div .span".observes('click'); -> true
"#div .span".observes('mouseover'); -> false

// and you can unbind the listeners the usual way
"#div .span".stopObserving('click', function() {});

Then the Event.delegate and Event.behave methods are gone and instead of them we have a proper events delegation API on dom-wrappers which look like that

$(document).delegate('click', '#css.rule', function() {});
$(document).delegate('click', {
'#css.rule1': function() {},
'#css.rule2': function() {}
....
});

// delegation checks
$(document).delegates('click');
$(document).delegates('click', '#css.rule');

// disabling delegation
$(document).undelegate('click');
$(document).undelegate('click', '#css.rule');

More of that the same API was adde to the Element wrapper so you can attach your delegating listeners at any level of your web-page

$('my-list').delegate('click', {
'li.one-thing': function() {}
'li.another': function() {}
});

This way you can scope the delegation to some block of your document and handle the things locally.

You also can delegate custom events too

$(document).delegate('bingo', {
'#one': function() {}
'#another': function() {}
});

$('one').fire('bingo');
$('another').fire('bingo');

Generally there are no limitations and you handle any sort of events simultaneously via the same api.


$$ Is Back!

As you might noticed I moved the $$ function back. I tried to use the jQuery-like unified $ method but didn't like it and brought the $$ back.

Amen.


Semi-Safe Mode

As you might know RightJS 2.0 will have the safe-mode build, which will hide everything behind a single RightJS object and won't extend a thing on the user's page.

A typical use case would look like that

RightJS.$('element-id').onClick(....);

var MyClass = new RightJS.Class({
...
});

There is also a way to access the language unit extensions by passing variables through the RightJS object

RightJS(['boo', 'hoo', 'doh']).filter('includes', 'oo');
RightJS(4).times(function() { .... });
RightJS('boo hoo').endsWith('hoo');

In the RC release I added a semi-safe API for the non-safe builds, meaning you can put your variables through and access the RightJS units via the RightJS object. This way if you need say to write a plugin that supposed to be working in both safe and non-safe modes, you can simply write it for the safe-mode and it will be working in the non-safe mode too.


JSONP Support

In RightJS 2.0 there is the JSONP format support for the Xhr unit. It all works transparently via the same Xhr API with all the same principles, the only thing is that now you have the jsonp option where you can specify your callback name variable, or simply use true for the default 'callback' value.

new Xhr('/some/url', {
jsonp: 'myCallback',
onSuccess: function() {
// ....
}
}).send();

Xhr.load('/some/url', {jsonp: true});

It even will assign the responseJSON and json varaibles

Xhr.load('/some/url', {
jsonp: true,
onSuccess: function() {
console.log(this.json);
}
});



New Language Level Methods

There are also several new javascript level extensions were added. Object.each, Array#reject (which is useful with calls by name), Array#min, Array#max, Array#sum

Probably something else that I have forgotten.



The Next Steps

Now when the core is finished, there are quite a lot of work with porting the plugins to the new version and reworking the documentation. The site also needs to be reworked to support the new building system.

At the moment I estimate it like 2-3 weeks of work. So the delivery-day is somewhere by the end of summer.

Okay, think that's all I have for know.
Take care!

Tuesday, June 29, 2010

The RightJS DOM-Wrappers Speed

Okay folks, there is your next brainwashing session to keep you hooked to the right stuff.

When I announced that RightJS is switching to dom-wrappers, some of you seems started to panic. "Oh, no!", you said, "RightJS is going down, because native extensions murk dom-wrappers any day at any time!"

Well people, you just haven't seen the right wrappers yet 8). Here is the shot of the new engine in its raw, not fully optimized state.


FF 3.6.6


And so you didn't think that it's just FF, here is a shot in Opera.


Opera 10.54


Don't have a short for IE though, because didn't quite make it there yet, but you can imagine that it will go sky rocket, because there will be no elements extending anymore.

Some of you, young and sharp, might notice that, the ID access went down for a notch. That's all because of you guys, that's because in RightJS 2, you'll have the same $ method behavior as you have in your beloved jQuery, meaning you'll navigate it like that.
$('#boo-hoo'); // -> an element by id
$('div.boo, div.hoo'); // -> elements by the css-rule

There also will be things like $(window) and $(document), so you'll feel yourself like home.

That's about it. Hold on to the next session!

Saturday, June 26, 2010

RightJS Development Status

Hey folks, to keep in touch, some notes on the RightJS development status.

As you probably already know the next step in the RightJS evolution is coming. Currently I do all the fixes and main feature updates in the 'master' branch and all the dramatic changes go into the 'two.o.o' branch. So if you'd like to see what's going on, go and check it out from github.

So what's actually going on?

New building system

First of all I move the source code building system from the amaturish concatenation of some pieces of code to more serious layouts based builds.

What does it mean?

It's fairly simple. Instead of having all sorts of small isolated pieces of code, now we have one global function which isolates the RightJS initialization process inside. It doesn't mean that RightJS now closes its insides like jQuery does. No, all the crazy monkey patching abilities remain in place and it is still an open architecture, but now we don't need to worry about accidentally polluting the global scope with some temporary variables, plus it gives us a great deal of optimization abilities in speed and size.

Secondly, now we use the google's closure compiler to compact the javascript code. It works a bit faster and provides slightly better results than my FrontCompiler.

I haven't finished yet with all the size optimizations yet, but the layout based builds + google-compiler are already giving us some benefits. Despite that I already added quite a few new features and methods, the size of the builds went down at about 1K and goes like 40K of the minified (not packed) code, which is about 15K in gzip.

Then it seems like I'm going to get rid of the albeit-packed builds. The reason is that most of the web-servers those days use gzip compression and in this case there is no significant difference between the packed and minified versions. And as the packed version initializes slower than the minified one I think there is not much of reasons to continue to support it.

In any case, you'll be able to albeit-pack RightJS with FrontCompiler at any moment by yourself.


The Safe Mode

The are another reason for the layouts based builds - the safe-mode development. And currently there are several directions which the safe-mode development goes.

First of all the name spaced mode. Now as RigthJS initializes inside of a layout, it extends the global scope only at the very end. So you can easily have a name spaced build by removing one line of code from the end of the file and all the RightJS global objects will be available in the scope of the RightJS object.

You still will have all the native and dom object extensions with all the benefits and troubles and your code would look like that

with (RightJS) {
var MyClass = new Class({
include: Options,

initialize: function(id) {
this.element = $(id);
}
}
}

Or, if you're against the with calls, like that

var MyClass = new RightJS.Class({
include: RightJS.Options,

initialize: function(id) {
this.element = RightJS.$(id);
}
}


The second direction is so called condom-mode. The idea is that we initialize RightJS in a separated IFrame and then hook up the main window to the functionality via the RightJS object. In this case you have almost complete isolation of the contexts, RightJS won't touch the main window units and you also will have access to the RightJS fancy native extensions like that.

var R = RightJS;

R('boo.hoo').endsWith('hoo');
R(4).times(...);
R(function() { }).bind(...);
R([1,2,3,4]).without(2,3);
R.$('element-id').onClick(....);

RightJS will extend only those dom-elements which you actually work with. So you'll still have the RightJS speed and easy goingness, but you also have the ability to safely implement say widgets on someones page.

The condom mode is mostly ready, it still has some unfinished parts with the window and document access, but all the other things are already working. you can build and play with it in the `two.o.o` branch like so

rake build OPTIONS=safe



The DOM-Wrappers

The condom-mode is just a step to the next level, it is an interesting thing but it still does extend dom-elements you access. So I'm currently working on the next step which is the dom-wrappers.

The idea is to replace the direct dom-elements access with some artificial proxy which will have all the same interface as a normal dom-element but without actually extending the dom-elements themselves. The reasons are obvious, it's a peaceful coexistence with another scripts on the page and better cross-frame scripting abilities/performance.

This feature is still in progress and you'll see the first results in about couple of weeks.

After that, that's it, we release.


The Summary

One way or another, with the 2.0.0 release we should fix the only problem that wrong with the right javascript framework, the safety. We will have normal quick and naughty builds as we have now, but we also will have options with the namespaced and condom modes.

Which means we will have a rock-solid safety against the anxious MSIE or any other browser that will think its smarter than others, and you also will have the ability to use RightJS to develop widgets in the safe-mode.


That's about it.
Have fun!

Friday, May 21, 2010

Making a Colorpicker

The other day I've been implementing this colorpicker widget for RightJS and now I'd like to share some mathematics and mechanics behind the widget.

I won't bore you to death describing the actual layout, just some necessary theory and math. And I also will use RightJS semantics. Well, just because I love it.

The Color Theory

Lets start with a bit of a theory. Every giggling school girl those days knows that any color can be created by a proper mix of three basic colors, red, green and blue. That's a brilliant idea, but the problem is that not many people actually can use it. Personally me, I don't know anyone who can instantly say how much of every color you need to take to create say a color of coffee and milk.

And because of this problem the humanity created another, more natural way of color picking which is based on another three dimensions: tone, saturation and brightness. And the main idea of the colorpicker widget is to convert one system into another.

The Tone Parameter

The tone picker usually looks like a vertical bar and represents the following system of colors.



The principle is that with this tone scale you can have any tints available with full saturation and brightness. Note also that in every point of the scale, one of the colors is always has a zero value, and at least one of them has the full value.

Keep also in mind that this scale is some sort of closed circle, the end on the right is actually joined with the beginning on the left.

The Saturation And Brightness

The saturation and brightness field usually looks like that.



The saturation parameter is zero at the left side and have the full value on the right. The brightness is full at the top and zero at the bottom. This way, you will always have the white color at the top left corner, your current tint color at the top-right corner and a black line at the bottom side.

With those three handlers you also can chose any visible color but in more natural way.

Converting TSB into RGB

The first task of the colorpicker is to convert the tint, saturation and brightness parameters which the user picks into the actual RGB value.

It was proven that the best way of keeping your values in this case is if you keep your TSB parameters in float values of range 0..1 and RGB values in integers of range 0..255. This way you won't have systematic round up errors and it will be working faster.

So your TSB -> RGB script will look like that
var tint = [1, 0.5, 0];
var saturation = 0.6;
var brightness = 0.4;

var color = [0, 0, 0];

for (var i=0; i < 3; i++) {
color[i] = 1 + saturation * (tint[i] - 1);
color[i] = (color[i] * brightness * 255).round();
}
The principle is simple, first we combine the tint and saturation which will give as a raw color in range 0..1, then we apply the brightness parameter and convert the float value into a 0..255 integer.

Converting RGB into STB

The backward conversion is a bit trickier. I've drown a simple picture to help you understand the principle



Say you have some RGB color with values in range of 0..255. Remember our tint picture, where one value is always 1 and another is always 0. So this smaller area between the green and red values is the same thing, if you take it and normalize to the 0..1 range you'll have your clear tint values. The brightness parameter will be the proportion between the brightest color and the 255 value, and your saturation is relation between the minimal color to the maximum.

The script looks like that
// the initial RGB value
var color = [200, 100, 50];

// finding the minimal and maximal values
var color_sorted = color.clone().sort(function(a,b) { return a-b; });
var max = color_sorted[2];
var min = color_sorted[0];

// calculating the brightness and saturation
var brightness = max / 255;
var saturation = 1 - min / (max || 1);

// calculating the tint
var tint = [0, 0, 0];
for (var i=0; i < 3; i++) {
tint[i] = ((!min && !max) || min == max) ? i == 0 ? 1 : 0 :
(color[i] - min) / (max - min);
}
It is pretty much straight forward, but we also have some failsafe conditions like (max || 1) and (!min && !max) in case if all the RGB values are zeros.


HEX to RGB Conversions

And couple more things which you also will need. Converting your 0..255 colors array into HEX and RGB formatted strings back and forth.

Converting an array to a HEX value is simple
'#'+ color.map(function(c) {
return (c < 16 ? '0' : '') + c.toString(16);
}).join('');

Converting RGB string into an array of values looks like that
if (match = /rgb\((\d+),(\d+),(\d+)\)/.exec(value)) {
return [match[1], match[2], match[3]].map('toInt');
}

And converting any HEX color into an array can be done like that
// converting the shortified hex in to the full-length version
if (match = /^#([\da-f])([\da-f])([\da-f])$/.exec(value))
value = '#'+match[1]+match[1]+match[2]+match[2]+match[3]+match[3];

if (match = /#([\da-f]{2})([\da-f]{2})([\da-f]{2})/.exec(value)) {
return [match[1], match[2], match[3]].map('toInt', 16);
}

Well, that all you need to know to make one cool colorpicker of yours.
Enjoy!

Wednesday, April 28, 2010

RightJS vs. MooTools In The Game of Mines

This weekend I had some fun implementing the good old game of mines using RightJS. The result is pretty cute, you should check it out. No, really, you will like it.

The thing is that about year and a half ago I implemented the same exact game using MooTools, you can check it out over here, and well, I have some words to say on this regard.

Okay, I certainly did get better during this last year and you might say that I know RightJS better than MooTools, but here are some numbers. (For the sake of a clean experiment I specifically didn't look into the old code before or during the development and eventually gone in a different approach in the implementation.)

With MooTools I was working on the game almost the whole week, I didn't work full time and as I recall it you could say it were good three, three and a half days of work. The result is 14k build of JavaScript + about 5k of CSS, which is about 19k in total.

In case of RightJS it took me about 6 hours to implement the whole thing from top to bottom, and the result built of JavaScript + CSS is just 9K of code.

Yup, a twice as compact result and about four times less time spent. More of that I believe that RightJS implementation has much cleaner and easy to understand code.

The really sweet things in case of RightJS were the number extensions, simplified collections processing and built in Observer unit. It feels so good and natural to implement game logic with them! I really enjoyed those things!

Well, that's about it.

Monday, March 29, 2010

RightJS + Rails = Love

As the right-rails (the Ruby On Rails plugin for RightJS) was updated recently, lets have another brainwashing session. This time for Rails people.

If you're a kind of a pragmatic developer, you're probably asking yourself "why would I fall in love with this new thing? I already know Prototype and jQuery why would I need something else?", and believe me, I know precisely what you mean.

But ask yourself, being a Rails developer, were you ever happy of doing AJAX features in Rails? No, I mean, not like first two weeks on rails, or things like "it's working". I mean really happy, did you feel funny about Prototype or jQuery? Did they make the butterflies in your stomach fly? Literally.

Think about it. The Prototype support on Rails was always a kind of a flimsy hack and most serious developers don't really use those RJS stuff. And with jQuery you were always left alone to deal with all those kinky JavaScript stuff. That's good if you are a JavaScript guru and know your magic. But what if you are not, and what about the actual Rails business anyway? Did any of the frameworks really helped you in any way to be an actual Ruby/Rails developer?


How Is RightJS Different?

First and most important thing you should know about RightJS is that it was written by a Ruby/Rails developer for Ruby/Rails developers. And despite the fact that from time to time we have all those arrogant promotions and we mock jQuery folks constantly. RightJS is not really about JavaScript itself. It is something quite opposite.

RightJS is all about getting JavaScript off your hair. RightJS is made to help Ruby developers to deal with JavaScript tasks, it reflects Ruby way of handling things, has mostly Ruby syntax and many of its key features are copies of Rails features.

RightJS civilizes JavaScript and brings it closer to Ruby developers.

But we didn't came here to talk about JavaScript, right? What about Rails itself?


Lets Make The Butter Fly

How much time does it take to make a date-time field with a calendar in your framework?

Let me spare you the calculations time and show how it looks like in RightJS + RightRails.

<% form_for(@zing) do |f| %>

<%= f.calendar_field :dead_line %>

<% end %>

Nope. I didn't forget nothing. `calendar_field` is all what it takes. RightRails automatically includes all necessary JavaScript, CSS and I18n modules on your page and initializes the fields, so you don't need to worry about a thing.

More of that, it will automatically swap between builds and source code for JavaScript in production and development modes.

So, would you like some rater or slider on your form?

<%= f.rater_field :rating %>
<%= f.slider_field :completeness %>

Oh, I know! You'd like some autocompleter, right?

<%= f.autocomplete_field :category, :url => categories_path %>

Would you like the autocompleter to be RESTful design and hard-caching friendly? No problem!

<%= f.autocomplete_field :category, :url => "/categories/%{search}.js" %>

Here you go.


And That's Not All

The fun is not over, not by a long shot. The next feature is that RightRails comes with a brand new RJS generator, and that's not just a collection of dummy functions like in the case of the Rails original RJS templates.

The new generator lets you literally write JavaScript in Ruby and more of that it allows you to mix Ruby and JavaScript calls in one flow escaping and transforming variables on fly.

For example this is how the annoying nested forms look like when you make them with RightRails.

<% form_for(@zing) do |f| >

<div id="categories">
<%= render @zing.categories %>
</div>

<%= link_to_function 'add' {|page|
page[:categories].insert(render(Category.new))
} %>

<% end %>

See, the `insert` method is a JavaScript function, the `render` is the ActiveView method, `Category` is your model. All in one flow with automatic types conversion. And it is not just a list of predefined functions, you can literally do whatever you want.

update_page do |page|
page[:todos].update render(@todos)

page[:todos_count].innerHTML = @todos.size + ' Items'

page[:todos].select('li').each do |item|
item.onClick('toggleClass', 'marked')
end

page.json_variable = @todos.to_json
page.items_count = @todos.size
page.list_updated = true

page.alert "There are #{@todos.size} items left on the list"
end

There are no limiatations.

Mommy Look, More Fancy Stuff!

Oh yes mommy, there are! On top of all RightRails has a conventional interface to cover the most common AJAX CRUD operations. Let me show you.

Say here's your remote form

<% remote_form_for(@zing) do |f| %>

<%= f.text_field :name %>
<%= f.file_field :picture %>

<%= f.submit 'Create' %>
<%= image_tag 'spinner.gif', :class => :spinner %>

<% end %>

And here is your controller method

dev create
@zing = Zing.new(params[:zing])
if @zing.save
render rjs.insert(@zing)
else
render rjs.replace_form_for(@zing)
end
end

The `rjs` method provides access to the new RJS generator from the controllers, and `insert` and `replace_form_for` are the AJAX operations interface.

It all works over the Rails conventions, the `insert` method looks for the class of the `@zing` model, finds related partial, renders it and generates a piece of JavaScript that inserts the HTML into an element with the `zings` ID.

The `replace_form_for` method will render a new form with all the error messages for the @zing model and generate JavaScript that will update the form on the page.

RightRails has a collection of such methods for all CRUD operations.

Note also that I've put a file field and a spinner image on the form. RightRails automatically and transparently processes files uploading too, basically there is no difference whether your form has files or not, it all has the same API. And the RightJS when submits a form via AJAX, automatically searches for images with the `spinner` class and uses them as spinners, you don't need to hook them up with callbacks manually.

Summary

I'm not going to indulge you with obvious conclusions, I'll just tell you that I've already used RightJS + RightRails on two production projects and it saved me hell of a lot of time and nerves on JavaScript and AJAX development.

Well, it was designed to.

Tuesday, March 2, 2010

My Top 5 on that RightJS vs. jQuery Question

During the last several months of RightJS promotion, the absolute hit among the questions of 'what?' and 'why?' was understandable the question of what is the difference between RightJS and jQuery.

There were lots of talks about RightJS speed and then more about speed, and then we had some abstract talks about its philosophy and its way among the others and we also have that simple comparison page.

And what I find important in a brainwashing process is systematicness and methodicalness. We did some talks on an abstract matter, we did some talks on the opposite side of scale with performance tests, now lets touch something real. Something in the middle. And probably summarize some previous talks.

So here it is, your next session; my top 5 as I see it at this morning.


1. Syntax

When I'm saying "jQuery is like PHP", first of all I mean the nature of its syntax. When you boil it down to the essence, both of them are just collections of helper functions. And as PHP defines a new kinda language upon C, almost the same way jQuery defines a new language upon JavaScript.

RightJS on the other hand is built right into JavaScript itself. In 90% it is the good old JavaScript, where we bring features from later JavaScript specifications and spice it with some standard features from more serious dynamic languages like Ruby and Python.

As the result, when you learn jQuery, you mostly learn jQuery, I've seen many nice fellas around, who know jQuery quite well, but stuck when they needed to do simplest things in pure JavaScript.

When you learn RightJS, you learn the actual JavaScript, yes we have some funny shortcuts and features that make mature web-developers happily giggling like school girls, but all of them are built upon JavaScript standards.

RightJS makes you do the things in JavaScript and do them right. And because of that, whatever the future brings, your knowledge and skills will remain with you.


2. The Actual STL

When I read someone saying "jQuery is the JavaScript STL", it usually makes me laughing so much, that my neighbors probably think that I've finally went nuts and going to blow off the Kremlin.

Now, don't get me wrong, I have no problems with jQuery's popularity and I respect that. Well, at least, as long as it keeps me away from people who doesn't know the difference between popularity and standards.

jQuery is a DOM DSL at best. First of all it doesn't have anything to do with JavaScript itself, because it's a DOM wrapper, secondly there is nothing standard about jQuery in terms of JavaScript. Take for example a look at the .each() function where the arguments are in just the opposite order than they are in the JavaScript own Array#forEach method.

If you need something that actually follows the standards, you should take a look at RightJS. It brings many standard features from later JavaScript specifications, plus many other none the less standard features from server-side programming languages, for example methods like String#startsWith or Array#random.

The DOM interfaces are just one part of RightJS and it has much more. We even have a build of RightJS without DOM features which you can use on the server-side with Node.js or say writing scripts in Qt.


3. Multiple Paradigms

As jQuery is simply a wrapper over DOM interface, it doesn't give you any alternatives but use its own way of dealing with the things. Yes, you might imagine that you're practicing Lisp in JavaScript, but the reality is that 99% of jQuery code (including jQuery itself) is just a spaghettish pieces of crap.

RightJS on the other hand is not just a DOM wrapper, it is a multi-paradigm framework. We have an advanced OOP stack that allows you to write clean and properly designed applications that are easy to support and refactor. We also have most of the standard FP features, like binding, curring, chains and stuff. We also have some standard native units extensions that are most helpful in procedural programming.

RightJS gives you options and flexibility, so that you could deal with your work in the most effective way.


4. Open Sandbox

Maybe jQuery forces you to write a spaghetti code, but there is a bigger problem. Most of jQuery and its plugins code are closed behind anonymous scopes that makes it impossible to change them part by part.

You know, people are actually already invented OOP, inheritance, functionality injection and other fancy stuff to deal with those sort of things. And that's why in RightJS we have radically opposite architecture.

RightJS is built using proper OOP structures and modules and it represents an open sandbox where virtually everything is accessible and customizable. You can easily bend and tune RightJS for your needs, changing and replacing its parts, adding your own features, methods and so one.

And because of that it is super easy to write any sort of plugins and extensions for RightJS. Take for example a look at the right-rails plugin; couple of dozens of lines of code and RightJS API was completely transformed to have the naming system of Ruby, with underscored syntax and other features.

RightJS gives you the same flexibility and hacker's joy as Ruby or Python.


5. Official Plugins

I'm sure you know what they say "jQuery has a gazillion of plugins that will do everything for you". It kinda reminds me other folks who was saying "Everything in Java has already been done".

Normal people usually add on that "badly".

That gazillion of plugins has actually a pretty nasty back side. The problem is in the closed architecture and inflexibility. For every case there are usually half a dozen of implementations, and quite often the choice is like "bad, bad or bad?". At the end you might spend more time looking for a proper plugin than you could spend writing it yourself, and at the finish your app will look like a Frankenstein, all stitched of different parts.

Yes I know, I know, Frankenstein is a romantic figure in gothic culture, but there is so few romantic in supporting such an app.

With RightJS we don't have the luxury of too many plugins, but we have several good points on that matter too. First of all, many common and frequently used features that you have as plugins for jQuery, are already baked into the RightJS core, like for example, additional form features, Ajax via iframes functionality, cookies and stuff.

Then we have all the standard plugins, like D'n'D, JSON, Behaviors, plus most of the standard UI elements like Calendar, Autocompleter, Tabs, Lightbox, etc. already implemented and served in the official plugins repository.

And what's different about RightJS plugins is that all of them are implemented in the same way, using the same set of rules. All events handling, options, usage principles all are the same. So that if you had experience with one plugin, you will be familiar with the rest of them too.

Then all the plugins follow the open-sandbox principles of the RightJS Core. All of them are implemented using proper OOP approach and can be easily extended using inheritance, functionality injection or even monkey patching if you will.

This way you don't need a dozen of variations of the same plugin, you can easily tweak any standard one to do exactly what you need.

Sunday, January 24, 2010

Terminal Fun, or Why RightJS?

In this article I'd like to share some backstories and ideas that lead me to the development of RightJS. There are some generic texts on the official site, but in this article I'm going to get into some architectural details, thoughts and philosophy that were used as the basis in the development.

It might start to sound a bit philosophical and like RightJS saves the world, so please, be patient, I'm sure you can find some rational ideas behind.

Disclaimer

Despite the fact that I did quite a lot of JavaScript work lately, I'm not really any sort of JavaScript guru. I mostly work as a software developer/designer on the server side and my weapon of choice is Rails.

What I do with RightJS is a mere attempt to build a tool that will fit Ruby/Python developer habits and will be fun to work with.


Philosophy

That might be an arguable point of view, but to me the world is always trying to find a balance. The third low of mechanics says: "every action causes an equal and opposite reaction", and for this reason opposite forces always find a moment of equilibrium, moment where things are balanced.

For example when a body falls though air, the forces of gravity and air friction eventually gets equal and the body stops gaining speed; reaching its terminal velocity. A simple fact, but those two opposite forces combined make things like flight possible.

You might extrapolate and abstract this principle a bit further and take another two opposite things: "fun" and "safety". Abstractly speaking, I guess it is obvious that the more there is safety the less fun it is, and the more fun it is the more it gets dangerous.

Those two follow the same exact principles. And as much it might be honorable and cool to be at one side, with rebels or with the enterprise; the truth and all the magic things always lay somewhere in the middle. And that's what we are trying to do in here.

With RightJS I'm trying to reach that moment of terminal fun.


Back to The Reality

When it comes to JavaScript and safety I'm sure most of developers will think jQuery. On the other side of the scale probably will be Prototype. And I'm sure everyone who ever worked with JavaScript recently, heard lots of talks about the jQuery safe-mode, and how non conflicting it is, and how it lets you easily write plugins and so one.

But the truth is, that wast majority of the people who does those talks, never did write any plugins, never got in really non-solvable conflicting situations, and as the matter of fact they don't know anything but jQuery. They just heard that prototype extensions are dirty, and probably think that hating them makes them look tougher :).

Meanwhile, people were using Prototype for years, there are hundreds of plugins. And yes, big corporations did and still do use it. The reason why people started to switch from Prototype is because it got too fat and slow, not because it is unsafe.

It kinda reminds me the situation with airports. Someone, somewhere did created that shoe-bomb, and now we all have to stand in queues at security checks, take off our shoes and have a walk on a dirty floor.

Is it safer this way? Indeed it is. But if you are not a bad guy, would you like to skip that procedure?

I bet you do.


Between Safety and Fun

So, what about RightJS and that terminal fun thing?

Yes, RightJS does extend prototypes and we do have several global scope units and functions. That's true. But we don't do that blindly creating a crazy mess.

Most of the native unit extensions simply bring methods that already exist in later specifications. Things like String#trim, Array#map, Object.keys, Function#bind. Yes we do add them to the prototype level. But they all behave strictly in the standard way and they _will_ eventually appear in browsers.

I agreed that there might be some desperate people who had a complicated childhood and might implement a non-standard Array#each method and screw the things up. But IMHO, we should let the people learn on their mistakes and that's certainly not the reason to get scared and hide behind some "safe" interfaces. If someone wants he can screw the safe interface just the same way.

On the other side, adding those methods, will give you several advantages, like first of all you can use all those methods right now, without waiting while obsolete browsers will vanish from the face of the Internet. Secondly it will actually prolong your application life, because those methods only going to get into common use, which means your code will be mostly working in future even when RightJS disappear.

Then we do have several other top-level functions and objects. Functions like isString, isArray, isObject, $A they are extremely handy in everyday work and they are real time savers. Those methods all have clean, standard names and behavior, and you need to be a crazy person who don't know what he does, to re-implement them for some radically different purpose.

Yes we do unsafe things with RightJS, but all of them are strictly managed, organized and helpful. This way we balance between total safety and fun/comfort in work.


Deeper Down The Rabbit Hole

Any security comes with its cost, which is usually freedom and flexibility. Yes, I do agreed that having a non-conflicting interface is safe, but on the other side, it hooks your whole application on that interface. And I'm not talking about ridiculous situations, when you use the safe interface only and there are no potential threads for your application. Yes you are safe, but you're hooked to that interface.

We are living in a pretty dynamic environment, and things do get faster and faster. New superior solutions appear every year. So consider this.

Most of Prototype/Mootools code will work on RightJS after trivial and easily programmatically processable fixes. Same for RightJS, because it sticks to the standards in method names and behaviors, it will be really easy to transform RightJS code into Prototype/Mootools, pure DOM or even jQuery if you will.

In case of a safe interface on the other hand, you don't have to change anything and you won't. 99.9% of applications will stuck with it, continuing to drag it around creating a mess of frameworks and interfaces inside of a single application. Take for example Dojo. An excellent framework, but most of applications are trapped with it, because it is too expensive to migrate.

Okay, tomorrow might be a long shot and many applications don't live that long. What about today? There are also things to think about.

RightJS unlike jQuery is not just a DOM-wrapper, it is an actual framework. RightJS does not leaves you alone with pure DOM/JavaScript when you disagree with what's going on. It supports multiple paradigms of development, OOP, FP, procedural style and at any moment you're free to choose how to do your job.

Then, in similarity with languages like Ruby or Python, the whole structure of the framework is open. Unlike solutions with a safe interface RightJS doesn't hide anything inside of closed functions with spaghetti code. Most of the methods are organized in proper OOP structures and can be easily transformed and adjusted one by one.

Another point is that RightJS helps you utilize things like options, events, dom-manipulations, etc. in a single uniformed way. And that's too the part of the terminal fun idea. There are might be dozens of ways of dealing with things outside of the framework and if there are no regulations those things might cause collisions. RightJS provides you a conventional way of dealing with those things, which at one side reduces the likelihood of troubles, and on the other brings consistency across all the applications, making it easier to work with.

--

There are lots of things that RightJS takes care of, but I think it's all out of this article theme and then you can find all of them on the official site.

So for now I guess that's all. Hope I gave you some sense of perspective and food for thoughts on the topic.

Take care,
Nikolay

Friday, January 15, 2010

So, is really jQuery 1.4 30'000 times faster?

Okay, I admit that, when it comes to RightJS promotion, sometimes I do behave like a bastard and have no mercy over women and foreigners. But this jQuery 1.4 celebration is well out of my league! :)

I probably should just shut up about them publishing the release saying it weights 24k, and I've seen people today screaming "oh, it like the good old times!", and then they realize that it says in breakers "(gzipped)" and find out that the actual script weight is 70k. For a comparison, minified the same way Prototype weights 72k.

But why I will never get tired of mocking jQuery users is that performance optimization graph John posted over there http://jquery14.com/day-01/jquery-14. In case they will fix it, I've saved a copy over here.

Basically what it says is that jQuery 1.4 makes 30'000 (oh yeah baby, thirty thousands) times less calls than 1.3.2. Well to be honest in just a few operations. Seeing people making things like that I couldn't resist it and fired up my trusty Shakker, which bluntly compares frameworks performance feature by feature.

So what do we see? They did optimized it awright. Certainly not 30'000 times, more like 30% in average. At least it looks okay in FF



But when you run the test in Safari and Opera, you can see that it actually getting slower in some operations





And that's not the end. This test performs comparison on collections handling. And if you take a look inside of the new "fast" jQuery methods, you'll find out that they simply put collections processing in plain spaghetti JavaScript code. That means that it will and is working fast on collections, but when you process single elements (which is the majority of the cases), those methods will work slower.

This is about it. You can find all my tests code over here Shakker

But good luck with the 2 weeks orgy though 8)

Friday, December 18, 2009

Meet Shakker The Mano-A-Mano JavaScript Performance Testing Suite

I've started this project after several months of using Peter Higgins's TaskSpeed library as the main regression testing utility during the RightJS framework development.

TaskSpeed is a pretty well done library, but many people (including me) were complaining about its tendency to mix different tasks in one, mainly the css-selectors and stuff, so sometimes it wasn't clear what's going on. Another problem was that it provides just a total time as the summary, which is not an exactly clean way of judging about frameworks relative speed.

So I started my own little script, which become a bit bigger script and that one become even bigger one, and bigger and bigger. And now we have for ourselves practically an alternative solution for the TaskSpeed library.

Meet The Shakker!

The first difference between Shakker and TaskSpeed is that, Shakker has a two-level tests structure, the first one drives the test and keeps the data, the second one keeps the actual framework test. This way we have real-live like data separation on one side, and a blunt feature-to-feature comparison on the other. Shakker counts only the actual feature run-time for every framework, skipping utility operations like elements search, preparing collections, and stuff.

Another difference is that, Shakker not just collects the time summary, it collects differences between framework results for every test and then calculates average values between all the tests. It also let you choose one framework and evaluate it against others. This way you can have an approximated relative frameworks speed comparison.

It also keeps the original by-summary results, so that if your love sucks, you always can choose another result.

So what all this gives to you? See for your self. I'm posting results for all the modern browsers below, browsing through them you can actually see now what's going on. For example, you can clearly see, that say RightJS slows down in the building and finding operations under IE7,6 because it has to extend all the nodes manually on those browsers. You also can see where optimizations for jQuery 1.4 go, and you can see how Dojo fastly unbinds event listeners, because it doesn't have an internal events registry and makes the developer keep all the pointers manually. You also can clearly see how RightJS rips off everything under Chrome and Safari, because it doesn't uses any special proxy for dom operations, and uses common Arrays, which those browsers heavily optimize.

Lots of interesting stuff.


Google Chrome



Firefox 3.5.6



Safari 4.0.4



Opera 10.10



Konqueror 4.3.2 (Ubuntu on VMWare)



Internet Explorer 8 (WinXP on VMWare)



Internet Explorer 7(WinXP on VMWare)



Internet Explorer 6(WinXP on VMWare)



All the tests were performed in OS X 1.6.2, on 2Hz macbook with 4GB of memory.