Apr 01 2009

3

Javascript Obfuscation

Category: Javascript

In recent weeks my plate has been full as I plan for a big move. When I get stressed I usually play a game of chess to help relax a bit. Last night I took a different approach. I created my own brain teaser. I haven’t played golf with the following code yet, so the code isn’t optimized and it could be greatly reduced. The code is in pure javascript, no libraries, but it does require a decent javascript engine to handle forEach, map etc. Sorry IE.

(function() {
    var r = function(a) {
        if (a == undefined) return t;
        isNaN(a) ? (function(){
        t = [a.match(/.{5}/g).map(function(p) {
             return parseInt(p, 33).toString(10);
         	}).join('').match(/.{6}/g).map(function(p) {
             	return parseInt(p, 7).toString(17);
         	}).join('').match(/.{4}/g).reverse().map(function(p) {
             	var a = p.split('');
             	return a[1] + a[3] + a[0] + a[2];
         	}).join('')].map(function(p) {
             	var a = p.match(/.{2}/g);
             	a.forEach(function(c, i) { b[i % 3].push(c); });
             	return b[2].join('') + b[0].join('') + b[1].join('');
         	})[0].match(/.{2}/g).map(function(p) {
             	var x = p.split('');
             	return String.fromCharCode(parseInt(x[1] + x[0], 17).toString(10));
         	}).join('');
        })() : (function(){
            d = a.toString().split(''); l = d.length; p = t.split('');
            if (l == 3) { d.forEach(function(i) { p.push(p[i]); }); t = p.join(''); }
	    	else { t = d.map(function(i){ return p[i];}).join('') + p.join(''); }
        })();
        return arguments.callee;
    }, t = '', a, p, b = [[], [], []],c,i,d,l;
    return r;
})()('sbuq1iunojjo8q7')(165)(12)();

Spoiler:

Continue reading “Javascript Obfuscation”


Mar 05 2009

2

MooDocs TextMate Command

Category: UtilitiesTags: , ,

José Prado just released the MooDocs Coda plug-in . The plug-in allows Coda to parse MooTools Classes and generates a Markdown formatted template ready to fill in with details. I took his great work and modified it for TextMate.

I packaged it as a single command that installs into the Javascript bundle. I also assigned <command>-D to the command, for even quicker generation. One minor thing I fixed with the code was the parsing of the class name. There were a few cases where classes are created without var and have a ‘dot’ in the name. Like Fx.Morph or Drag.Move.

You are still required to end your classes like so:

var MyClass = new Class({
 
 
});//end

Download MooDocs for TextMate

Update:

MooDocs for TextMate has been moved to a github repo

Tags: , ,


Feb 25 2009

14

Lasso.Crop Preview

After releasing the “magnetic poetry” demo I have been working hard trying to make the code more reusable for all. In the process there has been a name change from Rubberband to Lasso. The original Rubberband code has been a great source of inspiration, but not much is left of it. I have completely gutted it reworking a lot of the internal logic.

First, the eye candy ;-)

Continue reading “Lasso.Crop Preview”

Tags: , ,


Feb 17 2009

4

Writing Mootool Classes. Things I’ve learned.

Category: MootoolsTags:

With the release of my demo last week I have had many requests to make a public API. In the process of doing so I have run into a lot of things with classes that I haven’t encountered before. This has led to quite a bit of frustration because of my lack of understanding in properly using the framework. In hopes to save someone else time, below is a list of tips that may help you from making the same mistakes as I did. This list mainly applies to developers that are trying to create reusable classes. If you’re developing classes that wrap application behavior most of these gotchas don’t apply.

1) Using Jan’s Binds mutator can save a ton of time. When dealing with Classes that extend other classes execution order becomes critical. Binds can take a lot of this worry away.

2) When developing an abstract class that other classes can Implement even if it has options do not include ‘options’ in the class. When Implemented it will blow away your previously set options. Fun times.

3) Extends and Implements do not play well together when the base class, extended class and the implemented class all have initialize functions. I might be doing something wrong here but it looks like the Implement class always wins, and you loose access to ‘this.parent()’.

4) Keep track of your events! Make sure you have the ability to detach them. Again Jan’s Binds can help with this.

Update:

Jan’s version of bind doesn’t work in 1.2 Check out Aaron’s which does.

Aaron write:

The key to Implements is to think of them as add-ons, not inheritance. It would be like having a mixin for your car that adds wheels. If your car had wheels, you wouldn’t need it. So “Implements: Wheels” adds wheels. Classes that are meant to be mixins shouldn’t have any members that are already in use (like options or initialize). This is different than Extends. Extends in our car analogy would be the Model T followed by the 57 Corvette. Corvette inherits from Model T numerous things and adds additional items and can refer to elements in its inheritance chain. But Model T, Corvette, and Ferrari all Implements: Wheels. If you Implements: Wheels onto Model T, you don’t need to do it to Corvette and Ferrari, because they inherit from Model T.

Tags:


Feb 13 2009

0

Visual Sorting Explained

Category: Mootools, UtilitiesTags: , , ,

I am getting the impression that my previous post was a bit esoteric. It has some valid uses and I want to help visualize how you might use the ‘visualSort’ method on Elements.

Lets first take a look at the demo I put up.

In the above image we have selected 5 elements. As you can see none of them are aligned and they actually overlap. However, the human eye discerns that there are 2 lines of elements. 3 on the top row, 2 on the bottom. The ‘visualSort’ method allows you to see elements like a users would in your code.

How visualSort solves this problem is two fold. First, it takes all the elements and sorts them by the ‘top’ coordinate. Once this sort is complete a second sort is performed. The first element is grabbed and an index is made based off the ‘tolerance’ (defaults to .5 or 50%). What this means is the height of the element is taken and multiplied by the ‘tolerance’. This result is added to the to the top value to get a tolerance range.

For example if chocolate had a top of 10px and was 20px in height. The tolerance would be within 10-20px. Any following element that has a top pixel within this range will be added to the same row. As an element is added to a row they are sorted by the left pixel to make sure they are in the correct order. If an element is not within that range a new row is created along with a new tolerance. The cycle repeats until all elements have been processed.

Continue reading “Visual Sorting Explained”

Tags: , , ,


Feb 13 2009

1

Visual Sorting

Category: Mootools, UtilitiesTags: , , ,

As promised I have been cleaning up the code to my most recent demo. I will be releasing a much more polished API along with documentation in the near future. Stay tuned.

I just completed one of the biggest headaches. Visual sorting. This allows DOM elements to be sorted in the same way humans would visually. I tried to make this as simple as possible to use.

I extended ‘Elements’ with a new method ‘visualSort’. The tricky part with a visual sort is the fuzzy logic needed to handle elements being offset. If you play with the demo you will get a feel for what I am talking about. In the demo, there is no need for pixel perfect alignment of elements to be considered on the same row. To require this would make the UI completely useless. To have this kind of fuzzy range matching ‘visualSort’ has a tolerance parameter. This allows you to define how much elements can be offset before it is considered a new ‘row’. Currently, tolerance defaults to .5 (50%). I also established a second parameter ‘flatten’. If set to true the sorted list will be flattened and returned as an Elements object. Currently ‘visualSort’ defaults to false which returns a multidimensional array.

In writing this code I tried to optimize the sorting as much as possible. I see a few places that can be tweaked but overall it should be fast. I didn’t use any sort() methods. I handle all my own sorting as I iterate through the elements. Feel free to ask questions about the logic or code.

Enjoy! My Brain still hurts.

 
Elements.implement({
 
	visualSort : function(tolerance,flatten){
 
		var tolerance = (tolerance) || .5;
		var idx = [], el, c1, c2, placed;
 
		for(var i = 0, l = this.length; i < l; i++){
			el = this[i]; c1 = el.getCoordinates();
			if(!i) idx[0] = [el, c1];
			else {
				j = 0; placed = false;
				while(j < i && !placed ){
					c2 = idx[j][1];
					if(c1.top < c2.top) placed = true;
					else j++;
				}
				idx.splice(j,0,[el,c1]);
			}
		}
 
		var rows = [], row = 0, sorted = [], slen, threshold;
		for(i = 0; i < l; i++){
			c1 = idx[i][1];
			if(!i){
				rows[row] = [c1.top,(c1.top + c1.height*tolerance)];
				sorted[row] = [ idx[i] ];
			}
			else {
				threshold = rows[row];
				if((threshold[0] <= c1.top) && (c1.top <= threshold[1]) ){
					j = 0; placed = false; slen = sorted[row].length;
					while(j < slen && !placed){
						c2 = sorted[row][j][1];
						if(c1.left < c2.left) placed = true;
						else j++
					}
					sorted[row].splice(j,0,idx[i]);
				} else {
					row++;
					rows[row] = [c1.top,(c1.top + c1.height*tolerance)];
					sorted[row] = [idx[i]];
				}
			}
		}
 
		var result = [];
		for(i = 0, l = sorted.length; i < l; i++){
			result[i] = [];
			for(j = 0, len = sorted[i].length; j < len; j++){
				result[i][j] = sorted[i][j][0];
			}
		}
 
		if(flatten) return $$(result.flatten());
		return result;
 
	}
 
});

Example Usage:

var sorted = $$('your selector').visualSort(.7);

I believe the value of this will be seen in Drag and Drop interfaces and layout managers. It could have some potential use for serializing specific components. If you find a use for it please share.

The demo has been updated with this code, it works in IE now.

Tags: , , ,


Feb 09 2009

13

Advanced UI component using Rubberband and Drag.Group

I knew after posting Drag.Group I needed to get a demo up quickly. The code is not completely refined yet so use at your own risk. I will be making updates over the next couple of days and will keep you posted.

A while back ago I posted an update to the Rubberband class. Its hard to understand the class unless you actually use it. One of the limitations that I found was the use of draggable elements. The coordinate locations were not updated and as a result the rubberband feature didn’t work.

I have made steps to add this functionality in place, currently the API is a bit broken and I am cleaning up how the coordinates are stored. In the meantime, I am providing a proof of concept.

Enjoy the demo!
Continue reading “Advanced UI component using Rubberband and Drag.Group”

Tags: , , , ,


Feb 09 2009

3

Drag.Group for Mootools

Category: UtilitiesTags:
Update

Check out the demo.

I have been playing around with creating more advanced UI components recently. I ran into the need to be able to drag multiple items at a time. I created the following classes to solve my problem. It is important to know that this code is still in alpha stages and is just a proof of concept for now. I will posting a bit later how I use this to create a UI component.

Drag.Group = new Class({
 
	Implements : [Options],
 
	options : {
		'active' : true,
		'store' : 'drag-group-item',
		'filter' : $lambda(true),
		'drag' : {}
	},
 
	elements : [],
 
	initialize : function(options){
		this.setOptions(options);
	},
 
	add : function(el,options){
		var drag = new Drag.Group.Item(el, this, $merge(this.options.drag,options))
		el.store(this.options.store, drag );
		this.elements.push(el);
		return drag;
	},
 
	start : function(el,event){
		if(!this.options.active || !this.options.filter(el)) 
			el.retrieve(this.options.store).start(event,true);
		else {
			this.elements.filter(this.options.filter).each(function(match){
				match.retrieve(this.options.store).start(event,true);
			},this);
		}
	}
});
 
Drag.Group.Item = new Class({
 
	Extends : Drag.Move,
 
	initialize : function(el,group,options){
		this.group = group;
		this.parent(el,options);
	},
 
	start : function(event,alerted){
		if(alerted) this.parent(event);
		else this.group.start(this.element,event);
	}
 
});

Drag.Group has the following options:

  • active : boolean ( if active grouping behavior is performed, else default Drag.Move)
  • store : string ( used to store the custom drag obj on the element )
  • filter : function ( takes one parameter (element). return true or false if it is part of the active drag group
  • drag : object ( default drag options for newly created items see Drag )

Usage :

var drag_group = new Drag.Group({
  'filter' : function(item){ return item.hasClass('active'); }
});
 
drag_group.add(el);

The ‘add’ method takes an optional second parameter which is a ‘Drag.Move’ options object. This allows for overriding the drag behavior on a single element. ‘add’ is currently limited to only taking one element at a time. I will add array support later.

My biggest concern with the current interface is the number of ‘document’ events that get created. I haven’t noticed any real issues in testing.

I will be following up with demos and extensions soon.

Tags:


Feb 07 2009

6

Insights from Link Nudging

Category: Javascript, MootoolsTags: ,

Someone recently posted the question “Mootools link nudging?”. I honestly wasn’t familar with the term, at first I thought it was an SEO trick. I fired up google and quickly learned it was a css padding animation trick. I saw that David Walsh did a version in

jquery

$('a.nudge').hover(function() { //mouse in  
	$(this).animate({ paddingLeft: '20px' }, 400);  
}, function() { //mouse out  
	$(this).animate({ paddingLeft: 0 }, 400);  
});

and mootools.

$$('a.nudge').each(function(el) {    
	var fx = new Fx.Morph(el,{ duration:300, link:'cancel' });  
	el.addEvents({  
		'mouseenter': function() { fx.start({ 'padding-left': 20 }); },  
		'mouseleave': function() { fx.start({ 'padding-left': 0 }); }  
	});  
});

I first noticed that the mootools code could be more “moo”.

‘$$’ returns an ‘Elements’ object. Elements acts like an array but extended with ‘$’ (’Element’). Mootools has the generic ’set’ function for setting a multitude of things on each element. The ’set’ properties can be customized or added by extending ‘Element.Properties’.

Continue reading “Insights from Link Nudging”

Tags: ,


Dec 18 2008

6

Compressed JSON Requests

Category: UtilitiesTags: , ,

I rarely find myself in a place where I am writing javascript applications that use AJAX in its pure form. I have long abandoned the ‘X’ and replaced it with ‘J’ (JSON). When working with Javascript, it just makes sense to return JSON. Smaller footprint, easier parsing and an easier structure are all advantages I have gained since using JSON.

In a recent project I found myself unhappy with the large size of my result sets. The data I was returning was tabular data, in the form of objects for each row. I was returning a result set of 50, with 19 fields each. What I realized is if I augment my result set I could get a form of compression.

// uncompressed
JSON = {
  data : [
     { field1 : 'data1', field2 : 'data2', field3 : 'data3' },
     { field1 : 'data4', field2 : 'data5', field3 : 'data6' },
     .....
  ]
};
 
//compressed
JSON = {
    data : [ 'data1','data2','data3','data4','data5','data6' ],
    keys : [ 'field1', 'field2', 'field3' ]
};

I merged all my values into a single array and store all my fields in a separate array. Returning a key value pair for each result cost me 8800 byte (8.6kb). Ripping the fields out and putting them in a separate array cost me 186 bytes. Total savings 8.4kb.

Now I have a much more compressed JSON file, but the structure is different and now harder to work with. So I implement a solution in Mootools to make the decompression transparent.
Continue reading “Compressed JSON Requests”

Tags: , ,


Next Page »