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

Saturday, March 08, 2014

what's in the avatar?

since even @paul_irish yesterday asked me about it, here the story of my avatar.

http://www.3site.eu/images/webreflection.jpg

Spoiler: Nothing To Do With Tech

This is one of those posts where you won't find anything techie, nothing to learn, think of, or related to what I do daily on my life so ... feel free to abandon this page if you are not interested in knowing what's on my avatar, and no offense will be taken :-)

Another Blurry Precedent

If you are asking me "why is that blurry?" I'll tell you later on, however the first time I thought about using this image I had similar reaction: "is it OK to use a blurry image as avatar?"
One of the most inspiring developers I've learned from in my past is Dean Edwards. Since Dean never bothered to change his blurry avatar, and I've no idea how many asked him about that, I thought it was OK to actually chose an avatar, no matter what it is, and stick with it as long as you want ... the face? Well, I am not even slightly as photogenic as Paul, or even the blurry Dean, plus I suck at making selfies so can you just keep recognizing me behind that non-sense image?
If you can, then it's time to tell the what, the when, and the why :-)

Keep Dreaming

One of the best friends of my childhood has always been an inspiration for me: he is a traveler, a dreamer, a story teller, a funny company or a shoulder to cry on, and last few years also a great father of 2 wonderful children.
We called him "the actor" since basically ever because of his ability to mimic people, imaginary characters out of books and fables, and also put yourself into a different surrounding because of the unexpected acting he'll might just start doing without any notice.

That was his vocation, and that is what he has studied for, dreamed about, sacrificed, to actually concretely become a real theater actor.

Acting ain't easy life, neither an easy income ... not everyone in the field does Hollywood movies and you could find thousands struggling to reach the end of the month but no matter what, they'll keep the show up!
In few words, this very dear friend never gave up and even if we are thousand kilometers from each other, he is ultra busy, and we actually have zero time to interact with each other or simply spend an evening together, I keep following his life achievements with shows he's creating with his wife too since both are wonderful actors, and have many story to tell you in a show, or during their teaching.

A Special Event

Not only I was happy knowing that my friend was getting married, I also believe that wedding was one of the best I've ever been in my entire life.
Family and friends were the one that prepared the entire wedding cooking, making cocktails, serving food and drinks, dancing folkloristic songs and even playing live music on the stage!
Yes, that has been for me one of the happiest moment of my life for a person I always admired and an event that was probably the most anti-formality wedding I could imagine within Italian culture ... OK it was never ending, and I was drunk as fuck, but when I took that picture behind a crowd of good old friends, hard to group again all together, old friends that were having fun at one of the best organized events I've been ... well, all I can say is that every time I re-think about that day, I feel that happy time again.

... After That

I kept following my dreams, keep trying and studying harder, improving my skills, writing post and Open Source software every time I could, exploring new countries, changing few companies, getting married with the most wonderful girl I've ever met and I am still running behind all achievements this friend of mine already completed ... damn it Luca, I really wish that all of us will never stop running!

Sunday, February 23, 2014

goto didn't fail;

it actually worked pretty well, and this is just my quick take on the infamous goto fail; security issue Apple had recently, an issue perfectly explained in this Adam Langley Weblog post.

what is wrong, in a sentence

Citing Adam Langley, here in my opinion exactly what is wrong in the modern software industry:
If I compile with -Wall (enable all warnings), neither GCC 4.8.2 or Clang 3.3 from Xcode make a peep about the dead code. That's surprising to me ...
Do you see that? Adam trusted the compiler to solve logic problems for him, without even mentioning for a second that a basic test would have shown the problem against an expected output apparently impossible to reach/obtain.
Bear in mind this post is not about Adam and the fact I am surprised too his example didn't warn, but that sentence represents way properly the common thinking in the actual industry, IMO (so please Adam don't take it personally, thanks).

syntax has nothing to do with security

every programming language has its own syntax gotchas, but this does not mean that every program is written badly or it can fail. The amount of criticism behind brackets, indentation, parenthesis, or the goto statement, even from the wired post, is embarhassing:
Using “goto” statements in any form has long been considered a poor programming practice, though everyone does it anyway.
It's way too easy to blame a statement and make this story a light emphasis on how bad is goto and everyone using it should burn in hell ... I wouldn't even be surprised if Apple will remove such statement from everywhere in XCode so that can go along with what really went wrong in this story ...
Truth is, an accidental early function return would have caused exactly same problem, stop blaming goto then!

missing tests and 100% code coverage

everyone knows testing might be hard and time consuming, but it does not matter how respected is your OS timeline if all your software does is to easily expose stuff due lack of time to test the most basic part of the security data exchange ... do you know what I mean?

a gently myth buster on SW development

just to remember what is not SW development about ... shall we?
  1. compilers and compiled languages do not automatically make your software secure; you can type by accident the function/method detractMoney(amount) twice and let the user with 200% less money ... now tell her it was her paying twice by accident ...
  2. linter do not make your code safer neither; indeed linters are more about code readability and practices, these have nothing to do with security and specially in JS world you must be a fool to think that varname === undefined will solve anything in your code
  3. tests are not an option, and for gosh sake this must be 120% true when "enterprise" or security related code is in place. It does not matter how cool is your programming language or the tool you are using to build your software, until you have a very high/good code coverage via any sort of test you can think of, you might be, at that point, good to go but it won't be never late to add a test or be sure that something else, just a change, didn't cause a regression
Before I've met great developers that couldn't stress more about testing everything, I've worked for companies that didn't care about tests, used the classic excuse "we have no time for that" or believed that the programming language, since compiled, was better than JavaScript and error/disaster prone by default because of types or some magic death code elimination.

This is bullshit, and I don't expect such kind of bullshit from #1 corporates that will silently pass behind the scene covered by simplification of a problem that has never been caused by missing brackets, parenthesis, or a goto statement.

Get real and solve your real problems, 'cause your scanned finger prints smells already rotten knowing that SSL abc wasn't triply reviewed, and passed to production miserably without a good code coverage for it.

Thanks for listening!
P.S. this case was just too fuzzed to not be used as example where tests outperform compilers and linters but this post has really nothing strictly to do with Apple itself! Any company/corporate lacking tests (unit, integration, smoke, etc) could easily fail in security, as well as everything else, problems

Thursday, February 20, 2014

the underestimated problem about script async attribute

While authoritative bloggers seems to suggest script async attribute as the holy grail on HTML documents for non blocking JavaScript overall performance, you might probably know async behavior is not necessarily desired at all, here I'll try to explain why.

first of all: why script async

Before talking badly about this attribute, it's necessary to understand reasons behind.
async attribute aim is to not block network traffic.
Differently from deferred, where the order of scripts is preserved and the fact scripts will be parsed and executed before the DOMContentLoaded event would be regularly fired, async scripts download and parse might occur at any time before or after the DOMContentLoaded as well as the onload event have been already fired.

<script async="shenanigans">

Yes, if your library, framework, utility, entire Web App, relies for some reason to the DOMContentLoaded event listener, or even the classic window.onload event, in order to initialize anything, such attribute will not guarantee that behavior at all: it's the other way round!
If the script tag is on top of the head of your page, the only place where defer or async make sense in order to not block the download of anything else in the page, it might be executed while the document is still donwloading as well as after everything else, in terms of DOM, has been interpreted already.
This situation is the most common one and not the less probable as you might think, 'cause the moment your script tag is interpreted, is the moment the browser knows already the content of the page.
From that point, to trigger a DOMContentLoaded event takes really nothing, milliseconds speaking.
If your script add that listener after, your script will never be triggered.

fixing the DOMContentLoaded

Long time ago, DOMContentLoaded in Firefox was the revolution for scripting initialization ... today this event looks ugly and unreliable, with its capital letters in the event type description, its past in the verb form compared with load which is not loaded indeed, and at the same time is the most used event ever for anything that would like to operate before the user.
In this universal common case, it's ridiculous that such event, happened in the past as Loaded would suggest, will never trigger again in the document unless somebody manually tries to do so, screwing all libraries, frameworks, or application logic, that forgot to removeEventListener once such event used for initialization has been fired ... you know what I mean?

Once For All: Fixed!

This script has no license on purpose ... I don't really care if you remember me once you used this script on top of your page and inline, I really don't want you to even think about this post once you can sleep well thinking the DOMContentLoaded event triggered your initialization script ... really, just use this script for reliability sake and forget about problems related to asynchronously loaded scripts and libraries.
Anything that will trust such event, will be triggered ... and yes, all CSP can be used as well without problems so ... no excuses, just enjoy!

Wednesday, February 19, 2014

quick repo updates

  • ./testardo sandbox.scrollTo(element) now works so well it can be tested with testardo itself
  • IE8 now supports XMLHttpRequest addEventListener, removeEventListener, and dispatch(event) on readystatechange event, normalized as well as everything else
  • eddy.js now passes all tests in IE8 too thanks to previous update plus it fixes a problem with obj.boundTo(method) weirdly unspotted before (huge bug that needs latest update)
For all Bower related projects, tags and versions should have been updated too.
Take care!

Monday, February 10, 2014

trapping an ES6 Proxy inside a with statement

restyle.js from Andrea Giammarchi on Vimeo.

update 2 to play with(restyle.properties){...} having a closure for variables and functions ... here an example ;-)

update I've been putting together explained ideas in both Proxy and a restyle.properties version that should work already in every ES5 capable environment.
Both files share the same alpha utilities file that can and will be enriched from time to time!
You can test current status directly in this page and you can also click the parsed area to have a link to share.
See how natural it feels? .. Now, imagine all browser prefixes are automagically added and you could also write around functions and variables to reuse code as you can already do in restyle ;-)
enjoy
too good and too powerful to be left ignored as pattern, while testing handy ways to make web developers life easier with a tool born for that as restyle is, I couldn't stop admiring how powerful is a with statement when a Proxy is passed as argument.

Next Tooling Level

Seriously, have a look at this Proxy:
var CSSProxy = new Proxy(
  {
    // borrowed from from eddy.js
    // https://github.com/WebReflection/eddy
    boundTo: function (method) {
      return this.$[method] || (
        this.$[method] = this._[method].bind(this)
      );
    },
    // CSS properties that clash with window
    special: /^(?:top|scroll)$/,
    // common camelCase RegExp
    find: /([a-z])([A-Z])/g,
    // common camelCase to camel-case replacement
    replace: function (m, $1, $2) {
      return $1 + '-' + $2.toLowerCase();
    },
    // a collection of already bound methods
    // it avoids blowed RAM for no reason
    // as eddy.js boundTo method does by default
    $: {},
    // the target.utility namespace
    _: {
      // in this case an hex example
      hex: function (r, g, b) {
        return '#'.concat(
          ('0' + r.toString(16)).slice(-2),
          ('0' + g.toString(16)).slice(-2),
          ('0' + b.toString(16)).slice(-2)
        );
      },
      // to write directly url('path.ext')
      url: function(src) {
        return 'url("' + src + '");'
      }
    }
  },
  // the proxy
  {
    // inside a with, everything that is not there
    // will be checked here
    has: function (target, name) {
      return  window.hasOwnProperty(name) ?
          target.special.test(name) : true;
    },
    // when .has(name) returns true ...
    get: function (target, name, receiver) {
      // either it's a method from here
      return target._.hasOwnProperty(name) ?
        // and it should be bound
        target.boundTo(name) :
        // or is a value name
        name.replace(
          target.find,
          target.replace
        );
    }
  }
);

The What And The How

Imagine you are writing through JS some CSS property for a server side/node.js pre-processor ...
with (CSSProxy) {
  console.log({
    // r, g, b to HEX value
    color: hex(100, 50, 150),   // #643296
    textAlign: center,          // 'center'
    backgroundRepeat: noRepeat, // 'no-repeat'
    content: noCloseQuote       // 'no-close-quote'
  });
}
Now, combine this with restyle(object) power:
with (CSSProxy) {
  var myApp = restyle({
    'html, body': {
      color: red,
      background: {
        image: url("image.png"),
        color: black,
        position: top
      }
    },
    section: {
      overflow: hidden,
      display: block,
    
    }
  });
}
Now, I don't know what you think but I believe this combination kicks every other CSS via JS processor out of the competition!

P.S. yeah, this is freaking cool stuff I am pretty sure somebody will complain about and shut it down as it was already for the awesome with statement :-(
ES3 FTW!

Saturday, February 08, 2014

restyle.js - a simplified CSS approach

Before you think about "yet another CSS preprocessor", I'd like to inform you that I've asked around to few common, well known, CSS or general web developers and it looks like this little script was still missing ... once you'll realize what is this about, you'll probably wonder yourself "how come nobody has done this already?".
My idea is that somebody probably did but I am not sure in 0.8KB minzipped and compatible with both server and client down to IE6 ... so here I am talking about restyle.

update Published object specifications explaining how the object is parsed and what will produce.
P.S. yes, absurd.js inspired somehow restyle except absurd.js won't work in your browser at runtime (yet?) does way more in about 26KB (~9KB gzipped) while restyle does not implement any magic.
Please read F.A.Q. to know more or check the restyle VS absurd page with basic features compared.

restyle.js

restyle is a function that provided a JS object creates and place in the DOM its CSS representation, using by default all possible prefixes. i.e.
var addedStyle = restyle({
  body: {
    color: '#FFF',
    background: {
      image: 'url(bla.bla)',
      color: '#000'
    }
  }
});
will result in this CSS, the string only in node.js world, a whole object in the DOM/browser world.
body {
  color: #FFF;
  background-image: url(bla.bla);
  background-color: #000;
}
to remove this new style at any time in DOM/browsers:
addedStyle.remove();
this is nothing impressive with standard styles but it becomes very handy when prefixes are in place.
restyle({
  'div > button:first-child': {
    transform: 'rotate(30deg)'
  }
}, ['moz', 'webkit']);
will become
div > button:first-child {
  -webkit-transform: rotate(30deg);
  -moz-transform: rotate(30deg);
  transform: rotate(30deg);
}
while the following
restyle({
  'body > div': {
    animation: {
      name: 'spin',
      duration: '4s'
    }
  },
  '@keyframes spin': {
    from: {
      transform: 'rotate(0deg)'
    },
    to: {
      transform: 'rotate(360deg)'
    }
  }
});
will become this
body > div{
  -webkit-animation-name:spin;
  -moz-animation-name:spin;
  -ms-animation-name:spin;
  -o-animation-name:spin;
  animation-name:spin;
  -webkit-animation-duration:4s;
  -moz-animation-duration:4s;
  -ms-animation-duration:4s;
  -o-animation-duration:4s;
  animation-duration:4s;
}
@-webkit-keyframes spin{
  from{
    -webkit-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -webkit-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@-moz-keyframes spin{
  from{
    -moz-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -moz-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@-ms-keyframes spin{
  from{
    -ms-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -ms-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@-o-keyframes spin{
  from{
    -o-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -o-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@keyframes spin{
  from{
    -webkit-transform:rotate(0deg);
    -moz-transform:rotate(0deg);
    -ms-transform:rotate(0deg);
    -o-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -webkit-transform:rotate(360deg);
    -moz-transform:rotate(360deg);
    -ms-transform:rotate(360deg);
    -o-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
and so on ... this has few advantages if done at runtime:
  • it simplifies prefixes hell effortless
  • it confines all new changes in one style element that can be dropped at any time
  • it can associate or create complex styles inline for custom components preserving size
  • it is compatible with runtime/dynamic properties for any sort of screen/case/device
Used without prefixes on the server side, it can be a pre-processor of the pre-processor, able to use variables at runtime in a JS way, instead of using SASS and company.

Moar Info and Conclusions

Everything open sourced in github, restyle is also an npm and a bower module.
If you think you got everything already, feel free to test some syntax or verify if it works for your browser at runtime ... and that's correct, it should work even in IE6 ;-)
enjoy

following

there are experiments in place able to make restyle magic, follow up in the next post if you want to know more.

update on why the DOM result has so many prefixes?

Every time we write CSS for other browsers vendors too we are creating useless noise in the file for the current browser. This is because we don't serve the CSS file accordingly with the current browser, we simply define all prefixes hoping one will be used from the current visiting browser.
Since no concrete size will be compromise when used at runtime, restyle, by default, has exactly the same careless behavior: it just create prefixes for everything simply trusting the normal browser behavior that what should work and be understood via prefix will work, everything else will be ignored, where last non prefixed version should be prevalent.
There is no way to feature detect properly weird or early CSS behaviors per each vendor, it will blow the code size and complicate the logic resulting in a non so present, past, and future proof behavior as the current one.
That said, you can pass the Array you want if at runtime you think all those prefixes are pointless, restyle purpose is to keep it simple and work ...
Although, if you have any hint on how to do this properly everywhere without adding more than 3 lines of code to the source :P I'll be happy to listen to you ;)
In node.js case, you should probably use a more complex preprocessor after creating CSS via restyle with the benefit that used logic can be applied eventually at runtime too.

Saturday, February 01, 2014

eddy.js goes promisish

This is a quick one about the tiny library I am using the most for personal projects: eddy.js

Promised Events

eddy makes the creation of event driven logic and application the easiest possible you can imagine.
var obj = {};

// at any time, in any place
obj.on('event', doSomething);
The unobtrusive, memory safe and lazily attached EventTarget logic you can even overwrite whenever you like to anywhere in your code, cannot solve tasks in a way ES6 Promises would.

... but what if I told you ...

... that jQuery nailed it in a similar way since ever?

.when(something, happened)

A very basic example of this new method is a classic document.ready approach indeed:
// even if lazily loaded!
document.when('ready', function(e){
  console.log('we are ready to go');
});

// later, even loaded asynchronously
// with or without AMD
document.when('ready', initLibrary);
Even if manually dispatched, handlers that has been fired once will not fire again unless re-attached but even doing so, these won't be fired twice if previously attached.
The best of both worlds, where listeners are stored by reference once, without the possibility to be fired more than once.
.once() is indeed the closest example to .when() except once adds a new listener, if not previously added, regardless the operation happened already in the past.
With this .when() method we are sure that the very first time the event happens, every other listener could benefit from that result.

result but no implicit reject

The "fulfill" part of this concept is provided by the way we dispatch the event either with .trigger('DOM-like', details) or .emit('node-like', null, value).
Any listener will receive the event or value passed the very first time the fulfill occurs but there is no way to understand a rejected value if not analyzing arguments.
A reject can be easily simulated indeed via .trigger('DOM-like', new Error('problem')) or .emit('node-like', new Error('problem'), null) so that any listener could handle failures.

improved .boundTo()

Another small change to library has been enriching Object#boundTo() signature so that it is possible to assign if not present once and at runtime.
I've found myself repeating this kind of pattern over and over:
obj.on('evt',
  obj.someMethod || (
  obj.someMethod = function(e) {
    // everything I need
  }
));
With the current improvement to boundTo, which I found more appropriate than creating another method for all objects, we can simply do this:
obj.on(
  'evt',
  obj.boundTo('someMethod', function(e) {
    // everything I need
  })
);
Above code will assign the second function argument only once and only if someMethod has not been assigned already. If a bound version is not required, then we could go in a less elegant way and either use the initial approach I've showed or simply addressing the property after:
obj.on(
  'evt',
  // not the bound version
  obj.boundTo('someMethod', function(e) {
    // everything I need
  }).someMethod // there it is!
);
The method does not create indeed a bound copy of the function as property, it rather addresses it once per property.

boundTo(Caveat)

It's very simple to create a foot-gun. If we address two different functions with the same property name only the first one will be used and never the last. In this case is highly recommended to delete obj.someMethod before using again boundTo ease.

Summary

eddy.js is becoming addictive and I am holding back myself every time I'd like to add some new cool thing trying to avoid mistakes old libraries did and keeping it simple and unobtrusive but I strongly suggest you to give it a shot.
Enjoy!

Wednesday, January 22, 2014

testardo - A Browser Agnostic JS Web Driver

you might think there are already so many solutions out there for testing browsers on real domains or real network interactions ... well, let me tell you why this is unfortunately not the reality until the point I show you ./testardo in action, bear with me please!

Selenium Ain't Portable

Despite being a wonderful project, Selenium WebDriver is great for Desktop but its Mobile Browser Version counter part is limited in terms of both supported platforms and supported browsers per platform.
In few words, Selenium is not suitable for all Mobile, Tablets, and Desktop browsers plus it requires knowledge of more than just JavaScript which is luckily, or unfortunately for others, the only programming language every browser understands today or did understand yesterday as well as the main one learned by Web Developers.

Simulators Are Liars

If you still trust simulators through your debugging tool, I've got a bad news for you: these are simply unreliable!
Starting from the real way events are dispatched and devices behaves compared with the browser engine you are testing on your Desktop, simulators might not be even able to give you a close scenario.
Look at this Chrome Bug to start with, for example, then realize also code behind your mobile browser is far from close to the one you are likely running on Desktop.
Not only unreliable then, simulators also give you a very fake idea of how performance will be, once landed on a real device.

Pay For Browser Testing ... No Thanks!

If testing is already something many companies and developers do not even invest some time that will inevitably pay back in both the short and the long term, imagine them investing time and money to have some test that will inevitably suffer cross browser and platform compatibility ... basically all available options I've considered and dropped these days.

Thanks Addy Anyway!

Addy Osmani has written excellent articles about testing, provided slides, examples, videos, but still there's not a complete solution.
While I really appreciate the work Addy is doing for the whole community about this field and for both client and server side world, I am pretty sure he would agree with me there's still not a simple to configure, simple to use, zero-stress config, and zero-spent money, testing solutions that satisfy the Web in its integrity, and for every old or modern device.

Episode IV - A New Hope

Considering Addy slides on Mobile Web Development Workflow, I will use same comparison points he used for those tools ... still talking about what testardo is, and what it can do at this stage.
  • [+] Free!
  • [+] Cross Platform
  • [+] Supports live reload
  • [+] Remote Inspect where supported
  • [+] Easily see how each change you save looks across devices
  • [+] Work with any modern AND not so modern Desktop and Mobile browser
  • [+] Does NOT Require you to install a package or extension
  • [+] Allows to match up scrolling and input
  • [+] Change urls and domain without needing to do that on devices
  • [-] Loads page into iframe
Long story short, almost every "plus" in Addy slides was actually a goal to reach with ./testardo, plus more:
  • [+] Loads external pages within a specific domain session
  • [+] Works and notifies even remotely
  • [+] If specified, it sends emails to the specified address and only once in order to not bother much if you are far away from "your free-time project" over the week end.
  • [+] It's entirely written in JavaScript and JavaScript is the only thing you need to know
  • [+] It allows you to inject before each test one or more external library as dependency (jQuery or others)
  • [+] It simulates as much as possible real DOM events triggered by users (note: at this time only the writing has been tested properly)
  • [+] It gives you an instant feedback with a green, yellow, or red with the eventual Error message notifying success, waiting for, or failure and the reason
  • [+] ... MOAR COMING ...
not convinced yet? Still no clue what is all this about?

testardo Live Demo

OK, the warning here is: take this video as a quick demo with a crappy setup as my home Wi-Fi router is, and considering testardo is at version 0.1.0 at the time I write this, thank you for your understanding :-)
So, here the video!

testardo - a browser and OS agnostic JS driver from Andrea Giammarchi on Vimeo.

Where, What, and How

So, everything is Open Source in Github and you are very welcome to contribute and help any way you can.
The single file you need is the built one but if you have node.js and npm installed, this is al you need to use testardo:
npm install -g testardo
After this, you should be able to run cross platform any test you want, where each test should be a module exports, similar to the one showed in this example.
I am trying to write a much better and complete documentation, right now you can find basically all you want to know and all you need inside the file itself, or simply running testardo without arguments.

Thank You All for your patience and Happy Testing!