Face Tracking, tcomb

08 Aug 2014 | By Alex Young | Comments | Tags graphics webcam

JavaScript Face Tracking

Konrad Dzwinel sent in a JavaScript Face Tracking Demo that demonstrates how to use getUserMedia with tracking.js to track your face and add an image based on the position. It also uses gif.js to generate GIFs, and Imgur’s API to upload the images.

Konrad made a video about the project with more details about each of the libraries and how you can use them.

tcomb

tcomb (GitHub: gcanti / tcomb, License: MIT, npm: tcomb) by Giulio Canti is a library for making types and combinators. You can use it for validating input or perhaps even lightweight models.

It supports JavaScript primitive type checking, structs, unions, tuples, and subtypes. This is an example of a struct:

var Product = struct({
  name: Str,                  // a REQUIRED string
  description: maybe(Str),    // an OPTIONAL string (can be `null`)
  homepage: Url,              // a SUBTYPE of string representing an URL
  shippings: list(Shipping),  // a LIST of shipping methods
  category: Category,         // a string in [Audio, Video] (ENUM)
  price: union(Num, Price),   // price expressed in dollars OR in another currency (UNION)
  dim: tuple([Num, Num])      // width x height (TUPLE)
});

The project is tested with Mocha, and the readme and homepage have lots of examples.

p5.js

07 Aug 2014 | By Alex Young | Comments | Tags processing graphics

p5.js

I’m a big fan of Processing, and I’ve made lots of my own weird and wonderful graphical sketches over the years. p5.js (GitHub: lmccart/p5.js, License: GPL) by Lauren McCarthy is an entirely new library that’s inspired by Processing. It doesn’t currently have an integrated IDE, but the authors are working on it. The documentation shows how to use Sublime Text for p5.js development.

Sketches made with p5.js have setup and draw functions. There are globally available methods that provide handy drawing commands:

function setup() {
  createCanvas(640, 480);
}

function draw() {
  if (mouseIsPressed) {
    fill(0);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 80, 80);
}

If you’ve ever seen Processing before then this should be familiar. In fact, there’s a Processing transition article for people with Processing experience.

There are some p5 libraries, like p5.dom for HTML5 manipulation and p5.sound for audio.

The advantage of p5.js over Processing.js is your scripts can use native JavaScript. However, because it uses global methods and special variables (like ellipse() and mouseIsPressed) then it feels more like a domain specific language than a reusable JavaScript library that’s safe to drop into an existing project.

For people that love JavaScript and Processing it’s definitely worth trying out, and I hope people will create more libraries for it. Also, if you’re trying to learn Processing or p5.js then check out The Nature of Code!

Node Roundup: V8 Vulnerability, git-promise, awesome-nodejs

06 Aug 2014 | By Alex Young | Comments | Tags node modules security git

V8 Memory Corruption

The versions of V8 included with Node 0.8 and 0.10 were found to have a memory corruption vulnerability. The issue was discovered by a security specialist, and then a core Node contributor worked with the V8 team to fix the problem. More details can be found in the V8 Memory Corruption and Stack Overflow post on the Node blog.

That means Node 0.8.28 and Node 0.10.30 have been released which both include a fix. 0.10.30 also has some changes to several core modules, including buffer, streams, and child process.

git-promise

git-promise (GitHub: piuccio / git-promise, License: MIT, npm: git-promise) by Fabio Crisci is a promise-based wrapper for Git:

var git = require('git-promise');

git('rev-parse --abbrev-ref HEAD').then(function(branch) {
  console.log(branch); // This is your current branch
});

The readme has more advanced examples, like finding the commit where master diverged from your current branch. Fabio has included some tests written with nodeunit.

awesome-nodejs

Sindre Sorhus sent in awesome-nodejs, a curated list of Node modules and resources. It’s a handy list to check if you’re looking for a module and are overwhelmed by choice, or not sure where to start on a topic.

There’s also an awesome list of awesome lists, which leads to awesome-javascript, and then back again.

Touch Emulator, Input by Font Bureau

05 Aug 2014 | By Alex Young | Comments | Tags libraries ui mobile fonts

Touch Emulator

When working with iOS applications, the gesture shortcuts in the simulator quickly become second nature. Sometimes I use the iOS Simulator for web development purely to check responsive designs, mainly because it starts up more quickly than the Android emulator. Touch Emulator (GitHub: hammerjs / touchemulator, License: MIT) from Hammer.js is a way to emulate multi-touch events on the desktop, based on the W3C specifications.

Once it’s installed you can listen for events in the standard way:

document.body.addEventListener('touchstart', log, false);
document.body.addEventListener('touchmove', log, false);
document.body.addEventListener('touchend', log, false);

The demo is what reminded me of the iOS Simulator – you can press shift to fake a second touch point, which allows pinch to zoom to work.

Input by Font Bureau

Input

I recently had a spate of font experimentation in Visual Studio. I’m typically a terminal/Vim user, so I’m not used to the way Windows handles font rendering. Since then I’ve been tweaking my fonts everywhere, although I keep ending up back on Menlo or Meslo.

André Mora sent in Font Bureau’s Input typeface:

Input is a flexible system of fonts designed specifically for code by David Jonathan Ross. It offers both monospaced and proportional fonts, all with a large range of widths, weights, and styles for richer code formatting.

There’s an interesting page with more details about Input, called Questioning Monotheism:

Monospaced fonts aren’t great for setting normal text, but they have become the de facto standard for setting code. Since all characters are constrained to the same fixed width, the page becomes a grid of characters, and the mechanics of typesetting are drastically simplified. However, this comes at an aesthetic cost: wide characters are forced to squeeze; narrow characters are forced to stretch. Uppercase letters look skinny next to lowercase, and bold characters don’t have enough room to get very bold.

It goes on to present several arguments about how to position text for code:

By mixing typographic variation with the power of syntax highlighting, by composing text that transcends a fixed-width grid, and by choosing and combining multiple font styles, we can end all up with code and data that is ultimately easier to read and write.

You can download Input for private use, or license it for commercial publications (including websites).

t3, Blast.js

04 Aug 2014 | By Alex Young | Comments | Tags libraries ui graphics gl text-parsing

t3

t3 (GitHub: maurizzzio / t3, License: MIT, Bower: t3) by Mauricio Poppe is a boilerplate for creating three.js projects. It’s inspired by Jerome Etienne’s three.js boilerplate, and supports:

  • Modules following the UMD pattern
  • Integration with dat.gui
  • Micro scene handler
  • Micro camera manager
  • Keyboard manager
  • Themes

If you’re looking for a framework to get started making a WebGL game or demo, then this might be a good way to quickly make something fun.

Blast.js

Blast.js

Blast.js (GitHub: julianshapiro / blast, License: MIT) by Julian Shapiro is a typographic manipulation library. It “blasts apart” text using delimiters, which can include character, word, sentence, and element. You could use it to animate text, or style it in some way

The documentation has visualisation for each delimiter, so you can easily see what each does. I can see it being useful in situations where you want to create carefully positioned magazine-like layouts, or reflow effects for responsive designs.

ng-polymer-elements, Easy CSS Animations

01 Aug 2014 | By Alex Young | Comments | Tags libraries graphics animation angularjs polymer

ng-polymer-elements

ng-polymer-elements (GitHub: GabiAxel / ng-polymer-elements, License: MIT) by Gabriel Axel is a library for mapping between AngularJS models and Polymer data-bindings.

It comes with support for various components, including core-input, paper-input, paper-checkbox, and paper-toast. As an example, binding the Angular scope’s myText property to Polymer’s paper-input looks like this:

<paper-input ng-model="myText"></paper-input>

You can extend the supported components by adding mappings to window.NG_POLYMER_ELEMENTS_EXTENDED_MAPPINGS. There’s an example of this in the readme.

Easy CSS Animations

Erica Salvaneschi wrote Easy CSS Animations, which demonstrates how to animate illustration-based web designs with CSS. The animations are subtle but interesting – I like the ones that persist after the initial page load.

CSS animations are an excellent way to make web pages look cool with relatively little effort. We used animations in our recent Windows Beta release page to bring our designer’s creative doodles to life. Since then we’ve released Papers 3 for Windows and created more pages with subtle animations.

We’ve extracted the CSS for you and shared it in this GitHub repository: mekentosj/blog-windows-animations.

She’s included some tips about using Retina.js, and basic drawing with CSS borders.

Natural Language Parsing with Retext

31 Jul 2014 | By Alex Young | Comments | Tags parsing text

Retext (GitHub: wooorm / retext, License: MIT, npm: retext) by Titus Wormer is an extensible module for analysing and manipulating natural language text. It’s built on two other modules by the same author. One is TextOM, which provides an object system for manipulating text, and the other is ParseLatin.

Given some text, ParseLatin returns syntax trees:

parseLatin.parse('A simple sentence.');
/*
 * ˅ Object
 *    ˃ children: Array[1]
 *      type: "RootNode"
 *    ˃ __proto__: Object
 */

These trees can then be processed as required. You can iterate over nodes or search them for values, it’s a bit like a DOM for plain text (or syntax/grammar).

The Retext module has lots of plugins. One example is an implementation of the Metaphone algorithmretext-double-metaphone. There’s also a short-code emoji parser, so you can actually build tightly focused text-processing modules with Retext. Another similar plugin is a typographic parsing library, which converts ASCII to HTML entities.

One cool use of Retext would be natural language date parsing, which is something that in my experience always ends up in a horrible mess of regular expressions. The author is still looking for a “retext-date” implementation, so it would be interesting to see what that looks like in Retext.

Node Roundup: Building Node.js Together, node-libnmap, httpolyglot

30 Jul 2014 | By Alex Young | Comments | Tags node modules libraries network security http

Building Node.js Together

TJ Fontaine wrote about Node from a release management perspective on the official Node blog, in Building Node.js Together. It covers documentation, code quality, and the growing team of core contributors and contributors that are employed full-time to work on Node:

For instance, Chris Dickinson was recently hired to work full time on Node.js, and has expressed interest in working on the current and future state of streams. But it’s not who employs Chris that makes him an ideal candidate, but it will be the quality of his contributions, and his understanding of the ethos of Node.js. That’s how we find members of the team.

node-libnmap

The evilscan module uses JavaScript to enumerate over TCP ports. node-libnmap (GitHub: jas- / node-libnmap, License: MIT, npm: node-libnmap) by Jason Gerfen is an alternative that uses the nmap binary.

It will return results as JavaScript objects, so you should be able to process the output fairly easily. A basic scan looks like this:

var libnmap = require('libnmap');

var opts = {
  range: ['localhost', '10.0.2.0/24', '192.168.2.0/25']
}

libnmap.nmap('scan', opts, function(err, report){
  if (err) throw err
  report.forEach(function(item){
    console.log(item[0])
  });
});

httpolyglot

httpolyglot (GitHub: mscdex / httpolyglot, License: MIT, npm: httpolyglot) by Brian White allows you to start a server that accepts both HTTP and HTTPS connections on the same port.

It works by sniffing the first byte of the stream to see if TLS is required:

var firstByte = data[0];
socket.unshift(data);
if (firstByte < 32 || firstByte >= 127) {
  // tls/ssl
  this._tlsHandler(socket);
} else
  this.__httpSocketHandler(socket);

BitcoinJS 1.0

29 Jul 2014 | By Alex Young | Comments | Tags bitcoin libraries

BitcoinJS 1.0 (GitHub: bitcoinjs / bitcoinjs-lib, License: MIT, npm: bitcoinjs-lib) has been released. This is a library for working with Bitcoins. For example, Bitcoin.ECKey.makeRandom can be used to generate a new address, and you can create transactions with new Bitcoin.Transaction().

The API is clean and easy to learn, and it comes with a test suite. It depends on crypto-js and some modules for working with base 58 encoding. Typed arrays are used to ensure it has solid performance.

BitcoinJS is a popular module, and is used by some popular Bitcoin-related services, including Hive Wallet, Blockchain.info, and BitAddress.

It comes with support for browsers, so you can use it in client-side code as well as Node.

The 1.0 release signifies a milestone that the author has been working on since 2011. For more details, see the 1.0 announcement.

Blockies, Angular Debaser

28 Jul 2014 | By Alex Young | Comments | Tags libraries ui graphics angularjs testing

Blockies

Blockies (GitHub: download13 / blockies, License: WTFPL) by Erin Dachtler is a small library that generates avatars based on a random seed and colour.

var icon = blockies.create({
  seed: 'randstring',
  color: '#dfe',
  size: 15,
  scale: 3
});

The arguments are all optional, and the output is a canvas element that you can insert into a container. The resulting images look a bit like the default GitHub avatars.

Angular Debaser

Angular Debaser (GitHub: decipherinc / angular-debaser, License: MIT) by Christopher Hiller is a library designed to cut down the amount of boilerplate required to test AngularJS projects.

When a module depends on a lot of services, then it can require a lot of stubs to test. To get around that, Debaser provides a more succinct syntax:

]
debaser()
  .module('donny.pizzajoint.admin')
  .object('Settings', {
    location_id: 1
  })
  .object('User').withFunc('getAll').returns([])
  .object('Pizza').withFunc('getAll').returns([])
  .object('Toppings').withFunc('getAll').returns({})
  .object('Sides').withFunc('getAll').returns([])
  .object('Orders').withFunc('getPreviousWeek').returns([])
  .object('Deliveries').withFunc('getPreviousWeek').returns([])
  .debase();

It uses angular-mocks, which is “ngMock” from the main AngularJS project.

TypeScript Log, Supplemental

25 Jul 2014 | By Alex Young | Comments | Tags typescript languages microsoft libraries

This week on DailyJS every post is about TypeScript! This article is a roundup of interesting TypeScript libraries.

This is the end of TypeScript week on DailyJS. I’ve been going through my email archives looking for TypeScript-related things that people have sent in. Here is a selection! As always, please share anything TypeScript (or JavaScript) related with me by going to contact.dailyjs.com.

VCL.JS

VCL.JS (GitHub: vclteam / VCL.JS, License: Apache 2.0) is a component-based web framework. The built-in components are based on Bootstrap, so the UI code should be quite easy to work with if you’ve used Bootstrap before.

It has deep Visual Studio integration, so Microsoft developers should be able to get started quickly. It even supports data binding and AMD for client-side code.

EndGate

I’m intrigued by EndGate, a game framework for HTML5 games written in TypeScript. It has APIs for input, graphics, animations (tweening), and collision detection.

There’s a tutorial that explains how to use collisions and tweens. It seems to focus on map-based 2D games, which usually work well in browsers anyway.

asyncawait

One of the big things in C# 5.0 was the async modifier and await operator. These keywords allow C# code to be asynchronous, without callbacks or delegate methods.

The asyncawait module for Node is inspired by this API. You can await asynchronous methods, so you get to use non-blocking APIs with synchronous convenience:

var foo = async (function() {
    var resultA = await (firstAsyncCall());
    var resultB = await (secondAsyncCallUsing(resultA));
    var resultC = await (thirdAsyncCallUsing(resultB));
    return doSomethingWith(resultC);
});

This module is based on two great projects: node-fibers and bluebird, but it’s written with TypeScript:

TypeScript: asyncawait is written in TypeScript (look in the src folder), and includes a type declaration file. TypeScript makes JavaScript development faster, less error-prone, more scaleable, and generally more pleasant.

TypeScript's Compiler

24 Jul 2014 | By Alex Young | Comments | Tags typescript languages microsoft

This week on DailyJS every post is about TypeScript! This article is all about TypeScript's compiler.

This week a new TypeScript compiler was announced, along with the move of the project to GitHub.

Our work to date on the new compiler has been very promising. At its current level of completeness, the new compiler is able to compile existing real-world TypeScript code 5x faster than the currently shipping compiler. These results are still early. Once the compiler has reached parity, we’ll be able to report out a more complete picture of the performance improvements.

You might be wondering how the TypeScript compiler works. The source can be found at GitHub: Microsoft/TypeScript, and is written in TypeScript. It’s structured using features and idioms commonly used in TypeScript, like services and generics.

There’s a parser, scanner, and the infrastructure needed to work with command-line options and files. The parser generates nodes that are used by an “emitter” that produces the desired output. You’ll see a lot of switch statements matching on enums that relate to language constructs.

Comparison with Other Compilers

The CoffeeScript parser is generated from a Jison file – so unlike TypeScript it has an additional context free grammar file. There are attempts at writing Jison-based TypeScript compilers, which are interesting to look at. LiveScript is also based on Jison.

ClojureScript’s compiler transforms ClojureScript into JavaScript. Originally ClojureScript was written in Clojure, and I’m not sure if it’s self-hosted yet. There was a fork that is self-hosted, however.

Automation

One issue with JavaScript compilers is the fact you have to recompile files to JavaScript whenever you make a change. Fortunately, tsc has a --watch option, so you can write tsc -w file.ts to watch for changes on file.ts. This can easily be used with a module like nodemon to automatically restart the Node process (if you’re using Node) as well.

There are also Grunt and Gulp plugins for TypeScript:

Conclusion

It’s interesting that there seems to be three main approaches to transpiling JavaScript:

  • Parser based on a context-free grammar
  • Self-hosted hand-written parser
  • External language

If someone had showed me TypeScript I would have assumed it was written with a CLR-based language, so it’s cool that it’s self-hosted and able to easily run without Microsoft’s development tools.

TypeFramework: A TypeScript Web Framework

23 Jul 2014 | By Alex Young | Comments | Tags typescript languages microsoft

This week on DailyJS every post is about TypeScript! This post is about TypeFramework, a possibly Rails inspired web framwork aimed at TypeScript developers.

One of the aims of TypeScript is to help you write large applications. In Node, the popular idiom is “small modules” – programs are composed from small packages with APIs based on patterns found in Node’s core modules. That means EventEmitter, streams, callbacks with the error-first signature, and modules that return a single function.

This can work well, but people still seem to struggle to maintain larger web applications. Surely a TypeScript MVC framework offers insights on how to structure larger projects?

TypeFramework (GitHub: zekelevu / typeframework, License: MIT, npm: typeframework) by Zeke Kievel is built on Express. It has controllers, models, views, routing, and configuration. The models are based on the Waterline ORM, and they look like this:

class User extends TF.Model {
  name: string;
  email: string;
  age?: number;
}

app.addModel(User);

The chainable API is quite nice:

User.find()
  .where({ name: 'John' })
  .skip(10)
  .limit(5)
  .done((err, users: User[]) => { /* callback */ });

Everything looks very much like a lightweight Rails. It will probably help C# developers who want to write things that run on Node, or Rails developers who are transitioning to Node.

What I’d really like to see is a more MVVM-style framework with interfaces for code contracts, services, and ReactiveUI-style APIs. I’d prefer skinny models so I can avoid putting business logic in them and use my own persistance layer. I think TypeScript is perfectly suited to this, but I haven’t yet found such a framework.

TypeScript Week

22 Jul 2014 | By Alex Young | Comments | Tags typescript languages microsoft

This week on DailyJS every post is about TypeScript! The first post introduces the language, and the growing TypeScript community.

TypeScript might not be as popular as CoffeeScript, but it seems to be catching on with a highly productive niche of developers that are building interesting open source projects. TypeScript is very much of the new school of Microsoft developers: it embraces Node, open standards, open source, while building on interesting influences from Microsoft Research and .NET.

If you’re excited by technologies like C# 5.0’s asynchronous support and ReactiveUI, then TypeScript will help you to be more productive with JavaScript. There’s even Visual Studio support! If you’re from a JavaScript client-side or server-side background, however, then it might be harder to appreciate why TypeScript is interesting.

The first thing to consider is that TypeScript adopts ideas from ECMAScript 6, while compiling down to ES3. This includes features like classes, modules, and a succinct lambda syntax:

var deck = {
  suits: ["hearts", "spades", "clubs", "diamonds"],
  cards: Array(52),
  createCardPicker: function() {
    return () => {
      var pickedCard = Math.floor(Math.random() * 52);
      var pickedSuit = Math.floor(pickedCard / 13);
      return { suit: this.suits[pickedSuit], card: pickedCard % 13 };
    }
  }
}

In this example, the lambda is introduced with () =>. This should be familiar to C# developers, but for the rest of us it feels quite new. There’s a subtle difference to using function() {}, however – lambdas capture this in a more intuitive way than standard JavaScript. In this example, this.suits is possible because the lambda binds to the containing object rather than window.

TypeScript allows you to write classes with the class keyword and inherit with the extends keyword. There’s more, though: generics are supported. Again, the syntax looks like C#, using angle brackets to denote the generic type parameter:

class GenericNumber<T> {
  zeroValue: T;
  add: (x: T, y: T) => T;
}

var myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

C# is statically typed, which means… I’m not really qualified to go into a discussion about type systems, so here’s a quote from MSDN:

C# is a strongly-typed language. Every variable and constant has a type, as does every expression that evaluates to a value. Every method signature specifies a type for each input parameter and for the return value. The .NET Framework class library defines a set of built-in numeric types as well as more complex types that represent a wide variety of logical constructs, such as the file system, network connections, collections and arrays of objects, and dates. A typical C# program uses types from the class library as well as user-defined types that model the concepts that are specific to the program’s problem domain.

When working with C#, the IDE is able to infer a huge amount of information about your classes and methods. It scales up nicely on large projects, which means you can be productive despite the build/run cycle.

In fact, TypeScript was inspired by the need to develop tools for using JavaScript on large projects within Microsoft. That means to use TypeScript you’ll have to get used to thinking about types, but it has benefits for writing code that can be partially verified by a compiler, and adhere to contracts (defined by “interfaces”).

To interoperate with JavaScript libraries, TypeScript supports hybrid types. You can even write your own declaration files that tell the TypeScript compiler how to handle a JavaScript library.

With classes, modules, lambdas, and type hints, you might be wondering how TypeScript will fit in with the future of JavaScript now that we know some of these things are coming to ES6. Apparently Microsoft have stated that TypeScript will be adapted as JavaScript changes. I don’t know what kind of backwards incompatibilities this might cause, so it’ll be interesting to see how they handle updates to the language specification.

I’ve seen a lot of negative press about Windows 8 and Microsoft’s mobile efforts, but if you’re completely outside of the Microsoft ecosystem then I think you should learn more about TypeScript. Microsoft have contributed to Node, and the adoption of asynchronous and reactive programming in C# has transformed how people write software for Microsoft’s platforms. The developer tools, languages, and libraries are worth learning about and may help you to write better JavaScript in general. Don’t write them off just because it’s fashionable to complain about Modern UI!

If you’re still confused about TypeScript, get started on the Wikipedia page. It introduces some history behind the language. For more about the language, see the language spec. You can also find tutorials on typescriptlang.org, and I found the handbook useful for mentally mapping between JavaScript, C#, and TypeScript.

Simplifying Conditional Statements with Is

21 Jul 2014 | By Alex Young | Comments | Tags modules libraries functional

Is (GitHub: jumpkick-studios / Is, License: MIT) by Alex Bogartz cuts down conditional statements with a more declarative API. It’s inspired by the Maybe monad pattern.

The author compares a lengthy, nested conditional statement to his chainable alternative:

new Is(foo)
  .isLongerThan(0)
  .equals('bar')
  .not().equals('bar2')
  .then(() => {
    console.log('success')
  })
  .catch(() => {
    throw new Error('bad foo');
  });

The main library’s source and tests are written with TypeScript, which means it looks very similar to standard JavaScript with the addition of type hints and succinct lambda expressions. You don’t have to use TypeScript to use it, but I think it reads quite nicely that way.

One nice feature of this library is you can avoid the need for checking for undefined values. For example, given var foo = { bar: undefined }:

new Is(foo.bar)
  .isLongerThan(3)
  .catch(() => {
    console.log('Please provide "bar"');
  })

The code in catch will run even if foo.bar is undefined.

Undo with Object.observe

18 Jul 2014 | By Alex Young | Comments | Tags libraries browser dom

Polgár András sent in LazyJsonUndoRedo (GitHub: azazdeaz / LazyJsonUndoRedo, npm: lazy-json-undo-redo, Bower: LazyJsonUndoRedo), which uses ES6’s Object.observe to bless undo and redo support on arbitrary JavaScript objects. That means if you’ve got a rich UI component you can add intuitive undo support.

There’s a demo that shows a graphical maze which supports undo and redo that illustrates the concept nicely. It sets the maze’s map object to use LazyJsonUndoRedo, and whitelists some special objects:

var ljur = new LazyJsonUndoRedo();
ljur.setWhitelist(map, ['data', 'objectMap', 'objectData', 'width', 
  'height', 'name', 'gridSize', 'showGrid', 'showWalls']);
ljur.observeTree(map);

var gui = new dat.GUI();
gui.add({ undo: function() { ljur.undo(); } }, 'undo');
gui.add({ redo: function() { ljur.redo(); } }, 'redo');

Object.observe is supported in the latest stable Chrome, and there’s a Polymer shim for older browsers. The shim should work in IE 9 and above.

Internally, LazyJsonUndoRedo uses an array to store changes and a pointer so objects can be fetched as required.

DOM Manipulation with Cash

17 Jul 2014 | By Alex Young | Comments | Tags libraries browser dom

Cash (GitHub: sudo-js / cash, License: MIT) by Rob Robbins at TaskRabbit, is a lightweight library for working with the DOM. It uses $ to provide access to an abstracted NodeList. It’s chainable, and supports events, CSS manipulation, and attributes.

For example, given var things = document.querySelectorAll('div'), you could change the class attributes like this:

$(things).q.forEach(function(el) { el.classList.remove('example'); });

Or add an event handler:

$(things).on('click', function() {
  // One of the things was clicked
});

The init method that runs whenever you call $() checks to see if the argument is an array, NodeList, or HTMLCollection. When it’s not an array, slice.call is used to map the elements to an array. The idea is to make this method as fast as possible so it’s safe to call it whenever you need access to a list of elements.

The new TaskRabbit site has been developed using micro libraries, and this is the library they used make working with the DOM more succinct. If you go to taskrabbit.com you should be able to run something like $(document.querySelectorAll('p')).q to see it in action.

If you’re avoiding larger frameworks and trying to find the perfect DOM querying and manipulation library, then take a look at the source – it’s fairly easy to see what’s going on. There’s annotated source, and the project itself is fairly easy to read because it uses a Node build script to generate the final framework from separate files. There are even detailed tests in the spec directory.

Node Roundup: npm CLI Roadmap, Nodemailer, Jasmine-Utils

16 Jul 2014 | By Alex Young | Comments | Tags node npm modules libraries jasmine testing email

npm CLI Roadmap

On the npm blog, there’s a post about the command-line tool’s roadmap:

The first piece of redesign work we’re tackling is the npm cache. … The next goal is to turn it into a module with no dependencies on the rest of npm or npmconf and to test the heck out of it. As npm moves to being a part of the toolchain of front-end developers (who are more interested in shipping features than figuring out what’s going on with their OS), it’s time to work on making npm easier to understand when things go wrong.

The article also mentions a better search interface, which I’d like to see because the current CLI search implementation is inflexible. It’s interesting to read about how the project is evolving away from Isaac’s original lightweight implementation intended for experts – the team behind the project has recognised that npm is used by a diverse range of developers.

Nodemailer

Nodemailer (GitHub: andris9 / Nodemailer), License: MIT, npm: nodemailer 1.0 is out! This is a complete rewrite, and partly breaks backwards compatibility so you may need to upgrade carefully:

The new version allows you to write custom plugins for manipulating the outgoing messages. It is also possible to send huge attachments with ease (in the size of tens of gigabytes) thanks to the Streams2 support - even though no one probably needs to send such attachments since probably no e-mail server would accepts these.

Jasmine-Utils

Jasmine-Utils (GitHub: mjeanroy / jasmine-utils, License: MIT, npm: jasmine-utils) by Mickael Jeanroy is a set of custom matchers for Jasmine. They’re grouped around types, like toBeABoolean and toBeDateBefore. Methods are included for booleans, strings, arrays, dates, objects and functions:

it('should check that an object contains keys', function() {
  var obj = {
    id: 1,
    name: 'foo'
  };

  expect(obj).toHaveKeys('id', 'name');
  expect(obj).not.toHaveKeys('foo', 'bar');
});

It also includes some handy spy methods, like jasmine.spyAll and jasmine.spyIf. These allow objects to be watched to ensure the expected methods are run.

The project includes a huge amount of matchers, so if you’re using Jasmine you may want to check it out.

VanillaMasker, jsTag

15 Jul 2014 | By Alex Young | Comments | Tags jquery angularjs ui

VanillaMasker

VanillaMasker (GitHub: BankFacil / vanilla-masker, License: MIT) by Caio Ribeiro Pereira is a small library for masking input elements with formats. It supports money, numbers, and custom patterns.

For example, a simple date mask would look like this:

masker.toPattern(12122000, "99/99/9999");

It doesn’t have any dependencies (hence “vanilla”), unless you want to build it locally.

jsTag

jsTag (GitHub: eranhirs / jsTag, License: MIT, Bower: jsTag) by Eran Hirsch is an AngularJS library for handling rich tag input fields. To use it, add a js-tag element to your HTML, and then add the js-tag-options directive for specifying a placeholder and default tag values.

You can also access it in JavaScript like this:

demoApp.controller('CustomizedController', ['$scope', function($scope) {
  // Export jsTag's options
  $scope.jsTagOptions = {
    'texts': {
      'inputPlaceHolder': 'Type text here'
    },
    'defaultTags': ['Default Tag #1', 'Default Tag #2']
  };
}]);

The documentation includes an example of using it with Twitter’s typeahead.js project.

An Alternative to AMD: CMD

14 Jul 2014 | By Alex Young | Comments | Tags modules amd harmony

By now most of us use AMD or CommonJS as our module API. With Harmony on the horizon, there doesn’t seem to be much need to innovate where libraries like RequireJS have established a niche. Despite this, John Wu sent me his module loader that can be found in his project wd.js.

This approach uses a chainable API which allows modules to be loaded asynchronously in a browser-friendly way, without AMD’s less fluent syntax:

wd.module('core.util')
  .require('core.bar')
  .require('core.foo')
  .body(function() {
    // foo and bar are now loaded
  });

John calls this style CMD, which stands for Chainable Module Definition. Although it seems like an obvious idea, it’s new to me and I think it fits in well with other modern JavaScript libraries.