WDS2013, flyLabel.js

01 Nov 2013 | By Alex Young | Comments | Tags animation jquery webgl

Web Directions South 2013 Opening Titles

WDS2013

Hugh Kennedy sent in the Web Directions South 2013 Opening Titles (GitHub: smallmultiples / south.im, MIT, MPL and Creative Commons). This is an extremely impressive WebGL animation complete with a cool soundtrack. It’s partly demoscene inspired, but also reminds me of Darwinia.

The code’s open source, mostly MIT with a couple of files under the Mozilla Public License and assets under Creative Commons.

Done in collaboration with Small Multiples’ (http://small.mu) Jack Zhao and François Robichet, it’s pushing some of the newer browser APIs quite a bit - WebGL, IndexedDB, Web Audio, Web Workers, etc.

flyLabel.js

flyLabel.js (GitHub: athaeryn / flyLabel.js, License: MIT) by Mike Anderson is a jQuery plugin that adds fancy animations to form labels. It uses CSS animations, and has a simple JavaScript API. Mike’s example uses Modernizr:

if (Modernizr.input.placeholder) {
  $('body').flyLabels();
}

New Features in npm: Part 2

31 Oct 2013 | By Robert Kowalski | Comments | Tags node npm
Node has one of the best package managers around: npm. Every month a lot of features are added to npm. Here are some new features as of 1.3.12.

Default Homepage URLs

Many projects use the same URL for their homepage and GitHub page. As of 1.3.12, you do not have to define the homepage property in your package.json – if you have a GitHub URL as the repository field the homepage will default to the GitHub page.

For example, this:

"repository": {
  "type": "git",
  "url": "git@github.com:robertkowalski/npm-registry-mock.git"
},

will result in the homepage field being set to http://github.com/robertkowalski/npm-registry-mock.

Outdated Upate

npm outdated shows the latest compatible version of each module according to your package.json definition. The updated version of this command, which you can use with npm 1.3.12, will also show the very latest version, even if it is not compatible with your package.json definitions.

These will show as latest:

underscore node_modules/underscore current=1.3.1 wanted=1.3.3 latest=1.5.1

Conclusion

With a new version of npm (and also Node) a ton of features and bug fixes arrive, so you should always be up to date. Fortunately, you just have to to get the latest Node version each time, as the latest npm versions are bundled into each node release.

You can find me on Twitter @robinson_k and GitHub at robertkowalski.

Node Roundup: 0.11.8, tabby, Nixt

30 Oct 2013 | By Alex Young | Comments | Tags node modules substack node-web testing command-line

Node 0.11.8

The core developers are cranking the handle again and firing out releases. Today Node 0.11.8 was released, which upgrades uv and V8. There’s a new buf.toArrayBuffer API, debugger improvements, and core module fixes.

I saw 0.11.8 announced on Twitter, and the author hinted at more frequent unstable releases.

tabby

If it’s not TJ Holowaychuk it’s Substack. I don’t believe it’s possible to write a weekly column about Node without mentioning one of them at least once. Substack just released a client-side project called tabby (GitHub: substack / tabby, License: MIT, npm: tabby), a module for creating web applications with tabs using progressive enhancement techniques.

Why is this notable? Well, Substack has been ranting about Node’s module system and client-side code. He wants you to stop mucking about and require(). Tabby blends the browser and Node by using WebSockets, and makes judicious use of Node’s core modules and streams.

For something focused on client-side code, it uses an interesting cocktail of modules. The inherits module provides browser-friendly inheritance, whilst still being compatible with util.inherits. And trumpet is used for parsing and transforming streaming HTML using CSS selectors. In the documentation, Substack recommends using hyperspace for rendering.

Looking through the examples, it definitely feels like idiomatic Node. I can imagine this style scaling up well to a larger web application.

Nixt

Nixt

Test code readability can bring huge gains when maintaining projects. Tests should communicate intent, and the longer they don’t need heavy modification the happier everyone will be. I generally find myself writing DSL-like methods for tests that reduce code duplication, particularly in the set-up phase.

With that in mind, it’s interesting to see Nixt (GitHub: vesln / nixt, License: MIT, npm: nixt) by Veselin Todorov. This is a module for testing command-line applications. It’s based around expectations, which reminds me of good old Expect.

Nixt works well asynchronously because it supports middleware for ordering execution. It can be used with a test harness like Mocha, and allows you to define custom expectations, which is where your application-specific DSL-like test helpers come in.

Although I’m probably guilty of using Node for command-line scripts that could be done with a shell script (I write my share of shell script too though), Nixt seems like a great way to test them, particularly as people often forget to test such scripts.

Script Roundup: jWebAudio, Scrolling Component

29 Oct 2013 | By Alex Young | Comments | Tags jquery plugins browser audio scrolling
Note: You can send your scripts and articles in for review through our contact form.

jWebAudio

jWebAudio (GitHub: 01org / jWebAudio, License: Apache 2.0) by Wenli Zhang and published by Intel’s Open Source Technology Center is an audio library focused on games:

Web Audio seeks to process and synthesize audio in web applications. jWebAudio keeps the technical details of Web Audio under the hood and makes it easier to control your audio.

It has a jQuery API and also a framework-agnostic JavaScript API. Playing a set of sounds looks like this:

$('.sound').each(function() {
  var $this = $(this);
  var url = $this.data('sound');
  $(this).jWebAudio('addSoundSource', {
    url: url,
    preLoad: true,
    callback: function() {
      $this.jWebAudio('play');
    }
  });
});

jWebAudio also supports synthesis and effects:

Sound effects include telephonize and cathedral currently. And you may create new sound effects using the combination of LOWPASS, HIGHPASS, BANDPASS, LOWSHELF, HIGHSHELF, PEAKING, NOTCH, ALLPASS.

There’s a demo here: jWebAudio demo.

Wenli also writes about JavaScript. Here’s a post about the gruesome details of Number, parseFloat, and parseInt: Converting To Numbers In JavaScript.

Scrolling.js Component

Guille Paz sent in Scrolling.js Component (GitHub: pazguille / scrolling, License: MIT, component: pazguille/scrolling). It allows you to decouple scrolling from callbacks to avoid generating too many scroll events (the old debouncing issue):

var scrolling = require('scrolling');

scrolling(document.querySelector('#box'), callback);

The project is distributed as a component, and has a demo on the homepage.

HiDPI Canvas Polyfill, formatter.js

28 Oct 2013 | By Alex Young | Comments | Tags browser canvas polyfills

HiDPI Canvas Polyfill

Don’t you just hate it when a cool canvas animation suddenly goes blurry? HiDPI Canvas Polyfill by Jonathan Johnson scales the canvas so the PPI is right, avoiding unsightly blurring. Jonathan notes that Safari is currently the only browser that does this properly.

I don’t know if the author was inspired by How do I fix blurry text in my HTML5 canvas? on Stack Overflow, but the solution looks similar to MyNameIsKo’s answer.

Jonathan has gone further by including tests, and he’s included a Grunt build script as well.

Jonathan also sent in BubbleChart (GitHub: jondavidjohn / bubblechart, License: Apache 2.0, npm: bubblechart) which is an interactive visualisation for two dimensional data.

formatter.js

formatter.js (GitHub: firstopinion / formatter.js, License: MIT) by Jarid Margolin helps you to define custom form fields. The examples given are a credit card form and a telephone number entry. The script can insert text as the user types, so the credit card form inserts hypens, and the telephone number uses the US-style format with brackets and a single hyphen.

The API looks like this, but there’s a jQuery wrapper as well:

new Formatter(document.getElementById('credit-input'), {
  pattern: '9999-9999-9999-9999'
});

The project includes tests that can be run with npm, and there are examples here: formatter.js demos.

How Apple Could Fix iWork: JavaScript

25 Oct 2013 | By Alex Young | Comments | Tags apple essays embedding

Apple and JavaScript

Apple recently updated iWork and removed a whole bunch of features. The company where I work makes a popular Mac application, and the removal of AppleScript from iWork caused a backlash from customers who rely on this feature for integration between our program, and Pages and Numbers.

AppleScript wasn’t ideal, but it did the job. Now we’re left in the dark, and as Apple are being typically opaque about adding it back we’re not sure what to do. The way it worked before was with scripting bridge, and although SBApplication is still around, Pages and Numbers no longer have it.

Scripting Bridge

Scripting Bridge provides an Objective-C API for sending and receiving Apple events, so you can take control of applications in Objective-C. It can be used to bridge another scripting language. JSTalk is one such example:

JSTalk is a scripting language for Mac OS X built on top of JavaScript, with a bridge to Apple’s Cocoa libraries. You can use it to communicate with other applications just like AppleScript does

JSTalk is built on top of Apple’s JavaScriptCore, the same JavaScript engine that powers Safari. So when you write in JSTalk, you are really writing JavaScript.

There’s also JavaScript Bindings for C and Objective-C. This uses SpiderMonkey to interpret your JavaScript, and bindings for Objective-C. You can even subclass native objects with JavaScript.

From my perspective as a JavaScript and Node specialist who does some Objective-C on the side, these projects have their appeal. It would be better if JavaScript was the default, though.

JavaScriptCore

Apple makes JavaScriptCore available to Mac and iOS developers with an Objective-C API. This quote is from Owen Mathews at Big Nerd Ranch:

JavaScriptCore gives developers deep access to the full JavaScript runtime from Objective-C. You can syntax-check and execute scripts, access variables, receive callbacks, and share Objective-C objects, making possible a wide range of interactions. (One caveat: on iOS, there is currently no way to access the UIWebView’s runtime, so unfortunately it’s not possible to tie into web apps at this level.)

Post Scripting Bridge

Now Apple have removed Scripting Bridge from iWork, it made me want to rethink application scripting. What would it be like to run JavaScript in an application? It would be much like browser DOM scripting, except the document would be a Keynote or Pages file.

When we wrote AppleScript in the past we wanted to modify a document without having to understand how to parse its format. There’s an element of driving the application, but also handling an abstracted version of the document rather than the underlying proprietary format. It’s probably easier to say “make words that match this regular expression bold” than it is to write a parser for Pages documents.

I recently wrote about the importance of embedded JavaScript, and I think Apple could gain a lot by adding JavaScript APIs to their applications. It would be more agnostic than AppleScript or VBScript, which can be used with Microsoft Office. If I could somehow insert myself into the nexus of all Apple development and advocate JavaScript I would, but I don’t have that kind of power, so perhaps someone reading this will!

Introduction to ChocolateChip-UI

24 Oct 2013 | By Robert Biggs | Comments | Tags browser tutorials ui
This post is a tutorial about ChoculateChip-UI from Sourcebits Inc.

We’re going to look at how to throw together a simple navigable app with the ChocolateChip-UI framework. This will require familiarity with HTML. You don’t need to be good with CSS or even know how to write JavaScript. ChocolateChip-UI provides functionality out of the box to provide functionality for Web apps.

ChocolateChip-UI uses a particular combination of simple tags to define the structures that make up a mobile app. These are: nav, article, section, ul, li, div, aside, span, p and h1 through h5.

To follow along, download the framework and grab the folder “chui”. This contains the files that comprise ChocolateChip-UI. We’re going to use three files: chocolatechip-3.0.4.min.js, chui-3.0.4.min.js and chui-ios-3.0.4.min.js.

To make a Web page behave like an app in the browser, we need to first provide some meta tags. Here is the basic skeleton with appropriate meta tags and links to the ChocolateChip-UI resources:

<!doctype html>
<html lang="en">
<head>
  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="msapplication-tap-highlight" content="no">
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="chui/chui.ios-3.0.4.min.css">
  <script src="chui/chocolatechip-3.0.4.min.js"></script>
  <script src="chui/chui-3.0.4.min.js"></script>
</head>
<body>
</body>
</html>

The app will reside inside of the body tag. When you look at the screen of a mobile devices, you notice that most apps use two main parts to present everything on the screen: a nav bar and everything below that. ChocolateChip-UI uses a combination of a nav tag and an article tag to create each screen of the app. Since we’re going to make a navigable app, we’ll need to put together a number of screen, each consisting of a nav and article.

The first screen will be the current view, and all others with be upcoming. ChocolateChip-UI designates this navigation status using two classes: “current” and “next”.

Every nav will have at least an h1, which is the title that appears in the navigation bar. Let’s start building this. We’ll need to create a navigation bar and an article. ChocolateChip-UI forces the article to fill the screen. Every article should have one child – a section tag. All the content will go in the section. It will automatically provide inertia scrolling when the user swipes.

Every article tag must have a unique id. This is used during navigation so that ChocolateChip-UI knows where to go and where to return to. If you find at some time that your app is not going to where you want or not returning properly, check that your articles have the ids they need and that you have all uses of them spelled identically.

Here is the basic app shell.

<!doctype html>
<html lang="en">
<head>
  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="msapplication-tap-highlight" content="no">
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="chui/chui.ios-3.0.4.min.css">
  <script src="chui/chocolatechip-3.0.4.min.js"></script>
  <script src="chui/chui-3.0.4.min.js"></script>
</head>
<body>
  <nav class="current">
    <h1>Fruits</h1>
  </nav>
  <article class="current" id="fruits">
    <section></section>
  </article>
</body>
</html>

You’ll notice that when it loads in the browser, the title appears in a nav bar, but there is nothing below that. ChocolateChip-UI uses unordered lists with the class list to display tabular data. We can give the list a title by putting an h2 right before the list. To display data in each list item, we use an h3 as the title and an h4 as the subtitle and a paragraph tag as the item detail. If we put the class nav on a list item, we get the right facing caret that iOS uses to indicate a navigable item.

Source code, part 3

To make this list able to navigate to other articles, we need to indicate where each list item should go. We do this using an HTML5 data attribute: data-goto. We give it the id of the article to which it will go. This will result in automatic navigation when the article that it points to exists.

This example includes the data- attributes:

Source code, part 4

Here’s what the navigation list should look like so far:

Navigation list

Now we need to add an article with the id for each fruit: apples, oranges, bananas, mangos and avocados. We’ll also want to provide a nav with an h1 with the title of each fruit. Because these navs and articles are not current in navigation, we need to explicitly give them the class next. This will put them out of view until the navigation occurs.

Source code, part 5

This creates a navigable app, except for one problem. After the user selects a fruit and the app navigates to that screen, there is no way to get back. We can provide a way back by adding a back button in each nav bar right before the title.

Source code, part 6

Detail page of Navigation list

To complete our simple app we just need to add a list to each of the fruit articles. We can use the same pattern we used on the main article.

Source code, part 7

To support Android or Windows Phone 8, you just need to switch out the reference in the CSS link: chui/chui.ios-3.0.4.min.css. Change ios for android or win.

Of course, this is just the most basic setup for an app. In real life you would want to get data dynamically through Ajax requests and output it to your app using templates. Sounds like another article.

Node Roundup: HTTP DoS Fixed, Flocon, Trans

23 Oct 2013 | By Alex Young | Comments | Tags node modules uuid json

Node DoS Fixes

This week two maintenance releases of Node were rolled out to fix a DoS vulnerability in the HTTP module.

Flocon

I seem to find myself generating a lot of unique IDs lately. Flocon (GitHub: Yosee / flocon, License: MIT, npm: flocon) from Yosee is a 64-bit unique ID generator, written in C++. It’s currently considered experimental by the authors but comes with unit tests.

Flocon returns IDs synchronously as strings with flocon.snow(), and the algorithm used is based on Twitter’s Snowflake service.

There are also some benchmarks of the flocon module so you can compare it to other projects.

Trans

Gabriel Adomnicai sent in “trans” (GitHub: gabesoft / trans, License: MIT, npm: trans), a module for transforming objects. Given some JSON, trans can group and modify objects by using a chainable API:

var trans = require('trans');
var data = [
  { a: { b: 'fbc' }, c: 1 }
, { a: { b: 'foo' }, c: 3 }
, { a: { b: 'fde' }, c: 2 }
, { a: { b: 'def' }, c: 3 }
, { a: { b: 'ghk' }, c: 4 }
];

trans(data)
  .group('a.b', 'c', ['charAt', 0], 'toUpperCase')
  .sortf('value')
  .sort('key')
  .value();

/*
[ { key: 'D', value: [ 3 ] },
  { key: 'F', value: [ 1, 2, 3 ] },
  { key: 'G', value: [ 4 ] } ]
*/

Each of the methods is documented in the readme, and Gabriel has included tests as well.

Script Roundup: Handpicked jQuery, Firepoker, Enyo 2.3

22 Oct 2013 | By Alex Young | Comments | Tags jquery plugins angular apps cdn
Note: You can send your scripts and articles in for review through our contact form.

Handpicked jQuery Plugins

The Handpicked jQuery Plugins site by David Higgins has been updated to the third version. He’s also released code.jque.re, which has links to resources served from MaxCDN. All of the plugins have MaxCDN links as well.

The site gets increasingly lean and mean over time. Outdated plugins get removed, and new ones take their place. The colors change, the CDN gets better, and more new fans download the repo each day to experiment with the plugins.

Firepoker

Firepoker

Firepoker (GitHub: Wizehive / Firepoker, License: MIT) by Everton Yoshitani is a “Scrum poker” game used for estimating user stories.

In planning poker, members of the group make estimates by playing numbered cards face-down to the table, instead of speaking them aloud. The cards are revealed, and the estimates are then discussed. By hiding the figures in this way, the group can avoid the cognitive bias of anchoring, where the first number spoken aloud sets a precedent for subsequent estimates.

It’s built with AngularJS and Firebase. It comes with a Grunt build script, so you can run a local development server to check it out easily.

The Firebase integration seems lightweight and easy to follow – if you look at main.js you can see how AngularFire is used.

If you’re looking for an AngularJS/Firebase example app, then take a look at the source for Firepoker.

Let’s Make a Framework Chronological List

Uri sent in a chronological list of the Let’s Make a Framework posts, because DailyJS is really just a static site so sometimes it’s a bit hard to make sense of long running article series:

http://jsbin.com/AduboCI/2

Enyo 2.3.0

Ben Combee sent in a post about Enyo 2.3.0-pre.10:

If you’ve been following Enyo, you’ve probably noticed that it has been a while since our last public release. From the outside it may appear that the pace of Enyo development has slowed, but appearances can be deceiving — it has actually been an exceptionally busy, productive year for the Enyo team.

So what have we been up to? For starters, we’ve been doing some exciting UI work to support an upcoming LG product release. We can’t share this work with you just yet, but it will ultimately be open-sourced alongside our other Enyo libraries. We’ve also been pushing forward on the Ares IDE, with our HP team members playing a leading role.

Enyo 2.3 should improve data bindings, data layers, and adds the enyo.Application kind which is an entry point that can be used to organise data and functionality across the entire application.

The blog post explains how to get the prerelease and start using it.

Why Don't You Use Tap?

21 Oct 2013 | By Alex Young | Comments | Tags node libraries testing

I always write tests for my Node projects, and I default to using Mocha. It’s popular with DailyJS readers and good at what it does. About two years ago Isaac Schlueter published tap, which is an implementation of the Test Anything Protocol. I wrote about it back in 2010, but haven’t used it very often.

The TAP will appeal to you if you’ve ever had to deal with “corporate” CI servers and overcomplicated XML protocols. The protocol is inherently simple, so it’s easy to both produce and consume it. That means you can write tools that do things with tests, and plug tools together.

Also there are browser-friendly modules out there. Tape by Substack is a tap-producing test harness that works in browsers thanks to Browserify.

One thing I like about Isaac’s tap module is the tests feel natively asynchronous. The TAP itself is based around streams of test data, so it’s no surprise that it fits in well with Node. However, it’s the API that I really like: every test case must be ended with .end(), or the number of assertions is declared with .plan(n).

Why is declaring the number of assertions (tests) useful? Well, in Node projects we tend to nest asynchronous calls, so it makes sense to ensure assertions were run at all. I’ve seen many tests over the years that had assertions that would never be reached, yet the tests still passed because there was no way to express this.

Another thing I like about the Isaac’s tap module is the tests can be run with node test_file.js, because the module has to be loaded like this:

var test = require('tap').test;

test('make sure the thingie is a thing', function(t) {
  t.equal(thingie, 'thing', 'thingie should be thing');
  t.type(thingie, 'string', 'type of thingie is string');
  t.end();
});

Because test is loaded from the tap module, we can run the test with the Node command-line binary, or use Isaac’s provided tap command which collates results with the tap-results module.

Also, assertions are included in the t instance, so everything is neatly organised.

I’ve noticed that some prominent Node developers like Substack continue to use the TAP, but I feel like it’s fallen out of favour in the Node community. So, I want to inspire a TAP renaissance. Give it a try, and see how it compares with your preferred test framework.

AngularJS 1.2

18 Oct 2013 | By Alex Young | Comments | Tags angularjs browser mvc

RC3 for AngularJS 1.2 was announced recently, with the news that the official 1.2 release should be out next week. There’s a full changelog at the AngularJS GitHub repository.

This release has some major changes: ngAnimate has been rewritten, $q gets a shorthand for error handlers (.catch), forms can now be addressed with $scope.ctrl.form instead of $scope.ctrl.form, and jQuery 1.10.x is supported.

Some annoyances have been fixed as well. $httpBackend can set headers with falsy values, $log no longer prints undefined in IE, and numberFilter will use toFixed() to ensure that large numbers are formatted as expected rather than using scientific notation. There are many more bug fixes documented in the changelog.

This release will introduce breaking changes. Promise unwrapping has been deprecated:

This is a feature that didn’t prove to be wildly useful or popular, primarily because of the dichotomy between data access in templates (accessed as raw values) and controller code (accessed as promises).

Here’s an interesting one: inputs cannot have a name of hasOwnProperty:

Before, inputs whose name was “hasOwnProperty” were quietly ignored and not added to the scope. Now a badname exception is thrown.

The biggest changes are due to the ngAnimate rewrite. The latest documentation for that is available here: lastSuccessfulBuild/ngAnimate.

The animate service will automatically apply two CSS classes to the animated element and these two CSS classes are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported and can be used to play along with this naming structure.

JavaScript animations are also supported:

JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits the element’s CSS class attribute value and then run the matching animation event function.

From what I can tell the breaking changes sound sensible, so it looks like most projects will just need to verify the use of the animate service.

ES6 Generator Performance in V8

17 Oct 2013 | By Daishi Kato | Comments | Tags node modules npm es6
This is a guest post written by Daishi Kato.

Node’s getting ES6 generators – otherwise known as the yield keyword. For those who are not familiar with generators, here is a simple example that will yield a value up to five times when onetofive is called.

function* onetofive() {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  return 5;
}

It’s hard to see why that’s useful until we introduce a loop. We can call onetofive repeatedly like this:

function run() {
  var iterator = onetofive();
  obj = {};
  // Assuming obj.done is a boolean
  while (!obj.done) {
    obj = iterator.next();
    // do something with obj.value
    // ex. console.log(obj.value);
  }
}

See what’s happening? We’re able to use a standard loop keyword yet provide an asynchronous API.

When I ran this a million times, it took 360ms. Now, I know yield is much more descriptive and you can even send a value back, but we should compare it to the equivalent hand-written generator code.

function onetofive() {
  var array = [1, 2, 3, 4, 5];
  var index = 0;
  var iterator = {
    next: function() {
      return { value: array[index++], done: array.length <= index };
    }
  };
  return iterator;
}

Running this version with the previous condition took 265ms, which is comparable or a little faster.

The reason why I was investigating generators is because I am interested in how yield can be used to write tail-recursive code.

Let’s look at this idea in more detail. The following is a factorial function in a tail-recursive manner.

function fact_tail(x) {
  var fact_tail_sub = function(x, r) {
    if (x === 0) {
      return r;
    } else {
      return fact_tail_sub(x - 1, x * r);
    }
  };
  return fact_tail_sub(x, 1);
}

It’s relatively easy to follow, but it will consume a call stack for each sub function call. TCO (Tail Call Optimization) avoids such consumption, and we can use yield for TCO like the following:

function fact_tail_loop(x) {
  var fact_tail_sub = function* (x, r) {
    if (x === 0) {
      return r;
    } else {
      yield fact_tail_sub(x - 1, x * r);
    }
  };
  var c = fact_tail_sub(x, 1);
  var d = {};
  while (!d.done) {
    d = c.next();
    c = d.value;
  }
  return d.value;
}

Here there is no recursive call and it doesn’t exhaust the call stack. Note the similarity of fact_tail_sub with the previous example.

When I ran it several times with different values of x, it took 217ms. That isn’t bad, but I can do it a little differently without yield:

function fact_tail_loop2(x) {
  var LoopCont = function(f) {
    this.f = f;
  };

  var fact_tail_sub = function(x, r) {
    if (x === 0) {
      return r;
    } else {
      return new LoopCont(function() {
        return fact_tail_sub(x - 1, x * r);
      });
    }
  };

  var c = fact_tail_sub(x, 1);
  while (c instanceof LoopCont) {
    c = c.f();
  }

  return c;
}

This is harder to understand, but the behavior is similar to the previous code. When I ran it with the same condition as the previous example, it took 63ms, which is much faster. By the way, this transformation is exactly what is done in https://github.com/dai-shi/continuation.js.

My observation at this point is that the code using yield doesn’t improve performance compared to the code which is carefully written like a generator. However, the performance characteristics might change if the optimization of generators goes well in V8 – and I hope it will.

* The evaluation is done with node-v0.11.5 on Intel Core2 Duo@3GHz PC.

Node Roundup: Browser Tests

16 Oct 2013 | By Alex Young | Comments | Tags node modules npm testing

I wanted to write about Substack’s Testling project, but then coincidentally Chris Scribner sent in his Browser Harness project. Let’s look at both to see how they shape up.

Testling

Testling (GitHub: substack / testling, License: MIT, npm: testling) is a tool for running tests in local instances of browsers. It works by using browserify – this allows Node modules to be used in browsers.

Browserify

But what’s really going on? Follow Testling’s source into browser/prelude.js and you’ll find xhr-write-stream. Also, Testling uses browser-launcher which allows browsers to be launched headlessly through Xvfb or PhantomJS.

I installed browserify and testling then ran browserify test.js | testling and it opened Chrome and ran my tests. I wasn’t sure how to make Testling run it headlessly, or run it in a different browser, but apparently if you define a "testling" field in your package.json it should pick up your desired browser settings from there. Read more in testling field documentation.

Browser Harness

Browser Harness (GitHub: scriby / browser-harness, License: MIT, npm: browser-harness) takes a different approach. It uses client-side code to listen for commands to run tests. It currently uses NowJS for communication, but the author wants to replace it with Socket.IO.

It requires a file to be served from the domain of the site being tested, and has a few other limitations which are documented in the readme file.

The harness has built-in support for fibers, so if you install asyncblock you can write tests in a blocking style.

The example in the documentation uses Mocha, but the author notes that other test frameworks should work as well.

Script Roundup: Dolly.js, ngProgress

15 Oct 2013 | By Alex Young | Comments | Tags jquery plugins angular
Note: You can send your scripts and articles in for review through our contact form.

Dolly.js

Dolly.js (GitHub: LunarLogic / dolly.js, License: MIT) from Lunar Logic is a jQuery UI widget for cloning fields in tables. It works like Excel and does not make any assumptions about the underlying data structure. Rows and cells can be constrained with selectors, and the API is event-based so you can hook up listeners to cloned events.

$(cell).dolly({
  rowSelector: 'div.row',
  cellSelector: 'div.cell'
});

ngProgress

ngProgress (GitHub: voronianski / ngprogress-lite, License: MIT) by Dmitri Voronianski is a port of NProgress for AngularJS applications. NProgress looks like the Chrome for Android progress bar which is a glowing blue line that grows to fill the top of the page.

The ngProgress demo page allows you to see how it works with buttons for each API call, for example: .set(0.4) and .inc(). This is the perfect way to give people feedback when your AngularJS app makes Ajax requests to the server.

Ghost: A Blogging Platform

14 Oct 2013 | By Alex Young | Comments | Tags node modules apps gbnc

Ghost

Ghost (GitHub: TryGhost / Ghost, License: MIT) is a blogging platform built with Node and Express. It uses CasperJS for testing, and Bookshelf.js for the ORM layer.

Ghost started out as a Kickstarter project, with the aim of bettering WordPress. Ghost is run by a non-profit organisation, and released the source code today under the MIT license. Ghost is also run as a service, so you can create an account at ghost.org and try it out without having to install it.

However, fortunately it is pretty easy to install: npm install --production and npm start should get it running. It’s easy because Bookshelf.js is database agnostic, so if your system has SQLite then it should be able to use it to store posts and users.

Event better, the fact Bookshelf.js is based around Backbone.js means you should be able to start hacking Ghost without much trouble. If you’ve done any work with Express and Backbone.js then Ghost’s source will be eminently hackable.

The project is split into client and server code, and it uses popular patterns like promises, Express route separation, and Express middleware.

The architecture of the project has been shaped by the need to allow people to easily install and theme Ghost blogs, which means it deviates from the typical Express applications I write which are bespoke services. The focus on theming came from the need to create a similar designer-friendly ecosystem that WordPress has, and already on launch themes and services that sell themes are available. You can read more about this in Ghost Launches to The Public.

The fact the project started off as a Kickstarter project with hundreds of eager alpha testers means it already feels mature. And unlike many open source projects it has a dedicated team and a business model behind it, so it’s definitely off to a promising start. I recommend giving it a look over if you’re an Express developer or just tired of your own blogging platform.

Espruino: JavaScript Hardware Hacking

11 Oct 2013 | By Alex Young | Comments | Tags node modules hardware gbnc

Espruino

Espruino is a cheap and tiny microcontroller that can be scripted with JavaScript. That means you can use JavaScript and an Arduino-inspired API to communicate with sensors, motors, and LCD displays. Rather than using Arduino’s Processing-derived IDE, or Node modules to communicate with Arduino, you can use something designed with JavaScript in mind from the ground up.

There’s an official Espruino board, but there are also compatible boards that you can use. The Espruino firmware can be installed on the other boards manually, so if you’ve already dabbled with microcontrollers you should be able to get a compatible board loaded up and ready to run. The Espruino hardware reference has more details.

The Raspberry Pi has some IO pins (the GPIO connector), but microcontroller-based boards like the Espruino use much less power. That means you could leave a board running on batteries for a significant amount of time.

The project was successfully funded on Kickstarter, where they raised £100,710.

If you want to flash a compatible microcontroller check out Espruino’s downloads page. If you want to see the source, go to espruino / Espruino. It contains a JavaScript lexer and parser, because the author (Gordon Williams) found V8 and SpiderMonkey used too much RAM to run on the chips he wanted to target. Have a look at the C source code if you’re interested in seeing how it works.

Beams: Streams with Computation

10 Oct 2013 | By Alex Young | Comments | Tags node modules npm gbnc

Beam (GitHub: darach / beam-js, License: MIT, npm: beam) by Darach Ennis is a module for performing computation on streamed data.

Beams are like streams, in that they support pipes but are lightweight and work with in memory types without buffering, copying, parsing.

Beams have some interesting properties:

  • Events are executed in order
  • Events can be filtered
  • Beams can be branched and joined together

Example

I’ve taken one of Darach’s basic examples and interleaved it with comments to explain the major concepts. The goal is to pipe numbers through an operator that can square numbers.

First, load the module and create a sink.

var Beam = require('beam');
var sink = Beam.Sink();

sink.on('data', function(data) {
  console.log('d:', data);
});

Sinks emit a 'data' event whenever data is received, so they can be used to capture results. Operators can be used to transform data – this example just squares each value:

var square = Beam.Operator.transform(function(x) { return x * x; });

Sources can be connected to sinks with pipe, much like streams:

var source = Beam.Source();
source.pipe(square).pipe(sink);

Values can be sent to a source with push:

for (var i = 0; i <= 10; i++) {
  source.push(i);
}

This example introduces sinks, sources, and operators, but it doesn’t even scratch the surface of what Darach is aiming for with Beams. The next step is to define a filter and declare a pipe that uses it:

var even = Beam.Operator.filter(function(x) { return x % 2 == 0; });
source.pipe(even).pipe(square).pipe(sink);

Now only even numbers will be squared. The Beams module also has built-in functions, which you can find in Beam.bifs. These are operators and filters that you can use to filter and compare values in beams:

var mod2 = source.pipe(b.mod(2))
mod2.pipe(b.eq(0)).pipe(sink1);
mod2.pipe(b.eq(1)).pipe(sink2);

To see all of the defined Bifs, see _beam_bifs.js.

Node Roundup: Great British Node Conference Edition

09 Oct 2013 | By Alex Young | Comments | Tags node modules npm events gbnc

Yesterday was the Great British Node Conference, which took place in London at the Shoreditch Works Village Hall. Speakers included Julian Gruber, Darach Ennis, Anton Whalley, and Tim Ruffles.

I did a talk about Node’s internals that went from the JavaScript core modules down to some libuv basics, with the aim of encouraging the audience to look at Node’s source for themselves. I want to break this talk down into a deeper analysis of uv and V8 while still remaining relevant to JavaScript developers.

Substack

Substack did a short talk about abstract syntax trees, Browserify, and a project he’s working on to remove unreachable code. He mentioned testling, which I haven’t seen before – it’s another way to run headless browser tests. I was recently trying to rethink the way I do this, so I’m going to give it a try.

Milo Mordaunt and Harry Dalton did an interesting talk about some games they created based on British government data. One of the games used Max Ogden’s voxel-engine project.

In the audience I talked to Sven Lito who is one of the creators of Hoodie. Hoodie is a noBackend project that aims to make web applications easier to build. It reminded me of Meteor, but my initial impression was that it’s more closely reliant and influenced by the Node community, so I’d like to spend more time looking at it.

Over the next week or so I’ll write a little bit more about the projects and technologies I learned about at the conference.

jQuery Roundup: Ideal Forms 3, httpinvoke, jquery.brightness.js

08 Oct 2013 | By Alex Young | Comments | Tags browser server node

Ideal Forms 3

Ideal Forms 3 (GitHub: elclanrs / jq-idealforms, License: GPL/MIT) by Cedric Ruiz is a library for working with responsive HTML5 forms. It uses JavaScript to adapt form controls to the size of the container, so it works without using media queries. It supports keyboard shortcuts, custom checkboxes and file inputs, and a date picker.

The CSS now uses Stylus, and it uses classes in the HTML markup for denoting field types.

httpinvoke

httpinvoke (GitHub: jakutis / httpinvoke, License: MIT, npm: httpinvoke, bower: httpinvoke) by Vytautas Jakutis is a module for making HTTP requests that works with Node and browsers. It’s designed with a focus on promises, and Node’s callback-style API:

httpinvoke('http://example.org', 'GET').then(function(res) {
  console.log('Success', res.body, res.statusCode, res.headers);
}, function(err) {
  console.log('Failure', err);
});

The readme has full documentation for each API style and the accepted options. It’s unit tested, and also available through Bower.

jquery.brightness.js

jquery.brightness.js is a small plugin by Kozo Yamagata that detects CSS background colours and returns the brightness. Calling $(selector).brightness() returns either 'light' or 'dark'. It’s distributed as a Gist as it’s a short and sweet little snippet.

Harp

07 Oct 2013 | By Alex Young | Comments | Tags browser server node

Harp

Alex Griekspoor sent me Harp (GitHub: sintaxi / harp, License: MIT, npm: harp) by Brock Whitten, a static web server with a focus on client-side scripting. It’s built on connect, but shifts the responsibility of building client-side projects to the server:

I wanted a lightweight web server that was powerful enough for me to abandon web frameworks for dead simple front-end publishing.

It’ll run as a command-line tool or Node module, so you can fit it into existing projects and use it for local development.

If you look at the source it’s mostly based around middleware. A major chunk of this is terraform, a preprocessor that handles partials, layouts, metadata, and caching. Terraform is available through npm, so you could use it from outside of Harp.

I’ve worked with single page web apps that are entirely server independent, or traditional client/server applications. This approach mixes both of these paradigms, and seems to be generating a lot of interest. I found a recent Hacker News thread about it, and an introductory blog post that explains the development history so far.