Node Roundup: 0.11.3, Busboy, connect-mongostore, Chance

03 Jul 2013 | By Alex Young | Comments | Tags node modules html forms middleware testing sessions connect
You can send in your Node projects for review through our contact form.

Node 0.11.3

Node 0.11.3 was released last week, which was a fairly large update: libuv, c-ares, and v8 were all updated. The debugger now breaks on uncaught exceptions, and there were changes to enable dtrace for libuv’s probes (if enabled). The underlying implementation for buffers has undergone major changes as well – I’ve picked out a few commits here that discuss the updates:

It looks like these changes should make the buffer implementation more robust. I’ve checked out Node 0.11.x and 0.10.x on my local machine and run make bench-buffer against both, so far 0.11 doesn’t look conclusively faster, but I haven’t been particularly scientific about the process yet.

Busboy

Busboy (GitHub: mscdex / busboy, License: MIT, npm: busboy) by Brian White is a streaming HTML form data parser. It uses the Dicer module to parse multipart fields, and also uses a stream parser for urlencoded fields.

The busboy API allows limits to be placed on the incoming data. The Busboy constructor accepts an options object which may include a limits property. Limits can include fieldNameSize, fieldSize, files, and more – see the readme for full documentation. These options mostly default to Infinity, apart from fieldNameSize which is 100 bytes.

Tests are included, and it should be possible to use it as Express middleware fairly easily.

connect-mongostore

How do you decide which session middleware to use? Use cookies during early development then quickly search npm for something that uses your database? Me too! But there are better options out there and it’s worth taking a bit of time to research them. Ilya Shaisultanov sent in connect-mongostore (GitHub: diversario / connect-mongostore, License: MIT) which is an attempt to write a cleaner session store that takes advantages of features like replica sets, and has test coverage.

Chance

Chance

Chance (GitHub: victorquinn / chancejs, License: MIT, npm: chance) by Victor Quinn is a library for generating random stings, numbers, and even things that are useful for test data like address elements and names.

It works in browsers and Node, and has a simple constructor-based API:

var Chance = require('chance');
var chance = new Chance();
chance.name({ middle: true });

jQuery Roundup: minimit-anima, loda-button

02 Jul 2013 | By Alex Young | Comments | Tags jquery plugins icons animations css3
Note: You can send your plugins and articles in for review through our contact form.

minimit-anima

minimit-anima

minimit-anima (GitHub: minimit / minimit-anima, License: MIT, jQuery: minimit-anima) by Riccardo Caroli is an animation plugin that uses hardware accelerated CSS3 animations with fallbacks for older browsers. The API is queue-based like jQuery’s standard animation API. The following example specified an easeOut of 400ms:

$(this).anima({ x: 20, y: 20 }, 400);

Hardware acceleration can be triggered by adding the z co-ordinate and perspective properties:

$(this).anima({ x: 200, z: 0, perspective: 1000 }, 800);

The API has other features, like delaying animations with delayAnima(ms), clearing the queue with clearAnima, and stopping the current animation with stopAnima. Any CSS property can be animated, along with shortcuts for scale[X|Y|Z], rotate, and skew.

loda-button

loda-button

loda-button (GitHub: lugolabs / loda-button) by Artan is a small plugin that animates the icon in a button while an asynchronous operation is performed. The recommended markup uses anchors and spans:

<a href="#" class="loda-btn">
  <span aria-hidden="true" class="loda-icon icon-mail"></span>
  Mail
</a>

And requires a bit of JavaScript to set it up:

var lodaBtn = $('#loda-btn').lodaButton();

The animation can be triggered by passing start to the button:

lodaBtn.lodaButton('start');

The icon fonts are IcoMoon by Keyamoon.

Echotube, Community Updates

01 Jul 2013 | By Alex Young | Comments | Tags media google community backbone.js

Echotube

Echotube

Echotube (GitHub: orizens / echoes, License: MIT) by Oren Farhi is a Backbone.js and RequireJS YouTube media manager. It’s open source, and the code is all JavaScript, so you can easily see how the author has structured the Backbone code around YouTube’s API.

The design is derived from Bootstrap, but there are a lot of custom widgets and CSS transitions which keep it feeling original. Also, Jasmine tests have been included, which is interesting because it seems like a slightly awkward thing to test.

If you’re looking for fully-fleshed out Backbone/RequireJS applications to learn from then give it a look.

Community Updates

I occasionally receive messages about major updates to libraries and products that I don’t always write about, but I thought it would be nice to start publishing those as well. If you read about BromBone – a service that provided access to headless browsers – then you might be interested to hear that BromBone is now a service for bringing better SEO to single page apps. It works by adding redirects to yoursite.brombone.com based on the crawler’s user agent. The documentation has a simple .htaccess file which will work for Apache.

Also of note is Vincent Voyer’s lazyload script has been updated to 2.0:

Feel free to contact us about your module/script/app’s major updates and I shall endeavour to find space to write about it.

RobotsConf, DownDoc, opensemanticapi

28 Jun 2013 | By Alex Young | Comments | Tags robots events markdown google node

RobotsConf

RobotsConf

RobotsConf will take place on December 6th in Florida, and is a hardware-focused event aimed at developers who use high-level languages like JavaScript. Organised by Chris Williams (aka @voodootikigod), RobotsConf is a practical event to get you started in the Maker Movement:

If you are a Ruby, Python, JS or any other high level language developer that is interested in the Maker Movement, but unsure where to start – this event is designed for you. We will have experts in each high level language in attendance and available as well as many of the incredible makers who are already changing the world. With hands-on sessions covering drones, 3D Printing, microcontrollers, and the Internet of Things, this is the only two day event that will take you from a software developer to a Maker.

It’s organised by the JSConf team, so you know you’ll be in safe hands! Tickets start at $550 for early birds, and then $750 for a regular ticket.

DownDoc

If you followed my Backbone.js Google Tasks tutorials then you’ll know all about the wonders of gapi. DownDoc (GitHub: marksteve / downdoc, License: MIT) by Mark Steve Samson uses another Google API to store Markdown documents in Google Drive. If you’re tired of working with Word-like documents, then why not give it a try? It’s entirely browser-based, and the original source is pretty much a single CoffeeScript file.

opensemanticapi

opensemanticapi (GitHub: monbro / opensemanticapi, License: MIT) by Michael Klein is a “semantic wording database” made with Node and Redis. After leaving it running for a few hours it will have downloaded enough data to produce interesting results. Michael has some examples in the project’s readme, for example:

// http://localhost:8080/relations/ship

["midshipmen", "aboard", "ships", "rating", "master", "served", "seaman", "sea", "officers", "santa", "sailing", "cadets", "able", "sail", "navigation", "lieutenant", "hms", "expected", "yahoo", "storm", "rated", "promotion", "maría", "lewis", "false", "era", "boys", "wind", "voyage", "volunteer", "servants", "required", "passing", "palos"]

One thing that interests me about this is as a brainstorming tool for authors, as an alternative to a thesaurus.

Build Your Own Twitter-Clone with Sproute

27 Jun 2013 | By Louis Stowasser | Comments | Tags tutorials mongodb
Louis Stowasser is the creator of Crafty, and has worked at Mozilla. This tutorial is about Sproute, a commercial web framework that's similar to Meteor. DailyJS readers can download Sproute for free with the discount code dailyjs.

Sproute

Application development on the web is not easy. You need to understand server-side languages, databases, performance, security… the list goes on. It can take months to develop even simple applications. Sproute is a new kind of web framework that allows you to create apps in minutes.

In this tutorial we will be creating a mini-Twitter clone complete with a feed, login/register and profile page. It shall be called “Critter”.

Sproute is currently available on a commercial license to fund further development. Use the discount code dailyjs to get it free or contact us at contact@sproute.io.

The structure of a Sproute app is as follows:

  • Views: HTML pages with embedded template tags to request and display data.
  • Models: JSON object to define what the data looks like.
  • Controller: A mapping from URLs to Views using routes.

Setup

After installation you will need to edit config.json. Add a name property:

{
  "name": "critter"
}

This will create a Mongo database called critter.

The Feed

This will be a view that lists the micro-blog posts by a user. Create a view under the views/ directory called feed.sprt. .sprt is the default extension for views, you may change this in the config.json file.

To get the data from the Mongo database, we need to use the template language; in particular the tag get. All data is read, updated, created and deleted through an HTTP interface prefixed with /data/ so we must construct a URL to get the post data.

This will retrieve every row in the posts collection. Generally we want a feed of a particular user so we need to filter the results by username.

A few things to explain here. First of all the two parts to the URL will filter the results where the field name equals the value.

Secondly _creatorName is an in-built field so whenever a row is created, Sproute will automatically add some metadata about the row; in this case the username who created the post.

Lastly, params.user is a placeholder from a route in the controller that points to this view.

{
  "/:user": "feed"
}

This route means anything requested after / will render the view feed.sprt and put the value in the params object under the key user. Let’s use an example:

GET http://example.com/louisstow
params.user == "louisstow"

So now that we have all the post data under a given user, we need to render it by looping over each post. We do this with the template tag each and some HTML.

Before we run this, we’re missing one little piece. We’re requesting data from a collection called posts which doesn’t currently exist. We need to define it as a model to ensure some data integrity.

Models are defined as JSON files under the models/ directory. Create a file called posts.json. Sproute will create a collection for each model using the filename. Inside the model, we should define the field we will be using.

{
  "content": {"type": "String"}
}

Yep, that’s it. The model tells Sproute that the posts collection has a content field of type string (text). Everything else we use is an in-built field. You can add some more constraints in here such as minimum and maximum length. Maybe we could limit it to 140 characters ;).

Posting a Micro-Blog

Now that we can display the data, let’s make sure we can create it via some HTML in feed.sprt:

Plain old HTML is enough to insert data in Sproute by setting the action to the HTTP interface and the method to post.

Notice the query variable goto. It’s a nice feature that will redirect the user after doing the action, you will see it used in a few other end-points throughout the project. We also use self.url to get the current page to redirect to.

User Accounts

Sproute has user accounts built in. You just have to create the front-end including the login and register page. Create two views, login.sprt and register.sprt.

Send a POST request to /api/login with the username and password to create a session and log that user in.

Send a POST request to /api/register with the desired username, password and any other values you want stored with the user to create a new user row. This does not log them in.

Logging the user out is as simple as visiting /api/logout.

We can restrict HTML from rendering in our views if the user is not logged in. The form to post a micro-blog should only appear for users who are logged in:

The Home Page

Our controller doesn’t handle the index or home page. Add another route before the feed and create a view called home.sprt.

{
  "/": "home",
  "/:user": "feed"
}

What to put on the home page? This is up to you, maybe a bit of a splash page to introduce the reader to your new micro-blog. Maybe we want to show off some of the users.

Secure It

After creating a fully functioning micro-blog, the next step is to lock it down. Right now anyone can create a post whether or not they are logged in. There is a nice feature in Sproute where you can specify a route (just like the controller) and who can access it. It’s defined in permissions.json.

Let’s evaluate our product and decide what we need to secure. We don’t want just anybody creating a post, we want them at least to be members, so let’s add that restriction:

{
  "POST /data/posts": "member"
}

member is a default user type. You can create your own user types by overriding the in-built users model. There are also special user types:

  • owner: Give access to the logged in user where the _creator field matches their user ID.
  • stranger: Give access to a user who is not logged in.
  • anyone: No restriction.

For anyone to create a post, they must be logged in. We also need to make sure not just anybody can delete or edit the posts.

{
  "POST /data/posts": "member",
  "DELETE /data/posts": "admin",
  "DELETE /data/posts/*": "owner",
  "POST /data/posts/*": "owner"
}

An entire collection can be wiped by sending a DELETE request to /data/<collection> so add a restriction that only admin accounts can do that.

Let the creators be able to remove their own posts through DELETE /data/posts/*. Similarly let them edit their own posts.

Conclusion

The end! Hopefully this tutorial has taught you a few things about using the Sproute framework and how simple it is to build dynamic websites. Visit http://sproute.io to see all the other web applications you can build in minutes.

Node Roundup: CampJS, bower-registry, Helmsman

26 Jun 2013 | By Alex Young | Comments | Tags node modules events command-line bower
You can send in your Node projects for review through our contact form.

CampJS

CampJS August

CampJS will be held in the Gold Coast, Australia, on August 9th to 12th. TJ Holowaychuk will be attending, and also Angelina Fabbro.

If you’re interested, tickets start at AU$320. DailyJS readers can get a $25 discount by using the code DAILYJS.

bower-registry

If you’re looking to set up your own Bower registry, then take a look at bower-registry (GitHub: neoziro / bower-registry, License: MIT, npm: bower-registry) by Greg Bergé. This is an Express web application that stores data in Redis, but the author notes it could be easily adapted to support other databases like MongoDB and PostgreSQL.

Running bower-registry -d redis on the command-line will start a server. Other options can be viewed by typing bower-registry -h. The app can also be loaded as a Node module, and require('bower-registry').Registry is the Express app instance.

Helmsman

Helmsman (GitHub: mattmcmanus / node-helmsman, License: MIT, npm: helmsman) by Matt McManus is an opinionated command-line application development kit. The interface style is based on Git’s subcommands:

A common setup for command line applications is <command> <subcommand> <arguments/options> (for example: git commit -m 'message'). Rather than having a giant file that switches or if elses over each potential subcommand, it’s much neater to store each subcommand in it’s own file (bin/command,bin/command-subcomand, bin/command-subcommand2, etc). Doing this however introduces some annoying manual steps which helmsman hopes to solve.

The subcommand-style API is based on metadata exposed through exports. If the file is run directly rather than loaded with require, then your script should run as it would normally:

#!/usr/bin/env node

// 1. To expose the metadata simply `exports.command`
exports.command = {
  description: 'Show current worker counts and their pids'
};

// 2. Then make sure it only runs when it's directly called:
if (require.main === module) {
  // Parse options and run the magic
}

jQuery Roundup: Backbone Associations, bootstrap-wysihtml5

25 Jun 2013 | By Alex Young | Comments | Tags jquery plugins bootstrap backbone.js text wysiwyg
Note: You can send your plugins and articles in for review through our contact form.

Backbone Associations

Backbone Associations (GitHub: dhruvaray / backbone-associations, License: MIT, bower: backbone-associations) by Dhruva Ray is a plugin for one-to-one and one-to-many associations between models and collections:

applications can listen to any kind of change (change, add, remove, reset, sort, destroy) in this hierarchy using standard Backbone events and respond to them. (views can re-render for example). The implementation strives to be tiny (2.2KB), easy-to-understand, light-weight and fast.

Once the plugin has been loaded, models can be defined using Backbone.AssociatedModel, and then relationships can be set up with Backbone.One and Backbone.Many.

var Product = Backbone.AssociatedModel.extend({
});

var User = Backbone.AssociatedModel.extend({
  relations: [{
    type: Backbone.Many,
    key: 'locations',
    relatedModel: Product
  }]
});

The reversed association is automatically inferred, so a product could be set for a user. Values can be traversed using fully qualified paths as well:

emp.get('works_for.controls[0].locations[0].zip');

Fully qualified paths can also be used to assign event listeners:

emp.on('change:works_for.locations[*]', cb);

The author has written up a full tutorial for Backbone Associations, and has included unit tests and full documentation.

bootstrap-wysihtml5

bootstrap-wysihtml5 (GitHub: jhollingworth / bootstrap-wysihtml5/, License: MIT, bower: bootstrap-wysihtml5) by James Hollingworth is an amazing text editor component. It’s highlight consistent with Bootstrap’s design, and has many features you may take for granted when editing text, like the usual keyboard shortcuts.

Trantor Liu sent in his fork, trantorLiu/bootstrap-editor, which pairs up the project with jQuery-File-Upload. This adds support for things like upload progress, drag and drop, and cross-domain uploads. Trantor notes that the demo won’t currently work because there’s no server-side support, but he’s provided instructions on how to set it up locally.

JS-Git Update, X-editable

24 Jun 2013 | By Alex Young | Comments | Tags bootstrap ui widgets git

JS-Git

JS-Git logo

Tim Caswell’s JS-Git project has gone through the proof-of-concept stage, and he’s now reached an impasse where he’s looking for more funding. There’s a JS-Git repository that has specifications for the core parts of the project. This includes interfaces for how backends can be written, including details on using HTML5 APIs or a real file system with Node.

The Git Database specification defines how objects and refs should be stored, based on ECMAScript syntax. The beginnings of a reference implementation can be found in fs-db.js, which uses Node’s fs module.

The new fundraising campaign, run on BountySource, aims to raise $30,000 to enable Tim to work on the project full time to move the project closer to his main goals. This includes cloning remote repositories to local storage over http, git, or ssh, making and committing local changes offline, and pushing changes back to remote repositories. The target platforms are ChromeOS, Firefox OS, Windows RT WinJS, and HTML5 web apps.

It’s an ambitious project, but Tim admits in the BountySource posting that he won’t reach 100% completion. The effort reminds me of a JavaScript-centric version of libgit2, and has particular relevance for anyone interested in bringing native development tools to new web-based platforms like ChromeOS.

X-editable

X-editable

X-editable (GitHub: vitalets / x-editable, License: MIT, bower: x-editable) by Vitaliy Potapov is an in-place editing library that works with Bootstrap, jQuery UI, and jQuery. It can display a popup for a simple text field, or richer input widgets like date selectors.

I like to use it with data attributes, so I have simple markup that drives the keys and values for various UI elements, and then a generic RESTful API that the data is persisted to. I’ve been using it for Bootstrap CMS-style interfaces, with a Grunt/bower build environment, and it’s been solid so far. The author has included tests and documentation.

Backbone and Azure, Yass.js, grunt-stripmq

21 Jun 2013 | By Alex Young | Comments | Tags backbone.js mobile css grunt

Backbone Adapter for Azure

Olivier Bloch sent in a Backbone adapter for Windows Azure (GitHub: MSOpenTech / backbone-azure-mobile-services, License: Apache 2.0). It’s distributed by Microsoft Open Technologies, and syncs data with the Windows Azure Mobile Data Service.

If you’re interested in trying out the server-side API without Backbone.js, I noticed there’s a tutorial here: Get started with data in Mobile Services.

To use Azure with Backbone, all you need to do is include the adapter, an additional JavaScript file provided by Microsoft, and some settings for your collections:

var People = Backbone.Collection.extend({
  client: client,
  table: 'Table1',
  model: Person
});

The authors have included build scripts (Grunt) and tests (Jasmine).

Yass.js

Yass.js (GitHub: EightMedia / yass.js, License: MIT) by Jorik Tangelder is an adaptive image script that adds support for srcset tailored to mobile browsers. Once yass.js has been added after the last image on a page, it will ensure the optimum image is loaded.

It’s currently very small (less than 500 bytes when compressed), and has been tested in Chrome 28, Android 4.2, IOS6, BlackBerry10 and IE6.

grunt-stripmq

grunt-stripmq (GitHub: jtangelder / grunt-stripmq, License: MIT, npm: grunt-stripmq) also by Jorik Tangelder is a “mobile-first CSS fallback”:

A Grunt task to generate a fallback version of your fancy mobile first stylesheet. Since IE9 doesn’t support media queries, you can use a JavaScript like respond.js to enable this, or generate a fallback version with this task.

So if you’ve invested a lot of time developing modern, mobile-optimised sites, then you should be able to jam them through Grunt to spit out something desktop-friendly.

MV* and Local Storage

20 Jun 2013 | By Alex Young | Comments | Tags frameworks mv* localStorage

Most AngularJS and Backbone.js projects that I’ve worked on have persisted data to a remote API. What about those times when storing data in the browser is sufficient? Enterprising developers have added support for localStorage to some MVC frameworks, but before dropping one of these plugins or libraries into your project you need to know a little background about the API and its limitations.

Browser Support

If you’re already set on building a modern, single page web application, legacy browser support probably isn’t a huge deal. The Can I use Web Storage page shows most browsers we typically target are supported. It refers to “name/value pairs” because it’s talking about the localStorage API.

The localStorage API

If you’ve never used it before, then you can think of window.localStorage as a key/value store for strings. You can stick any JavaScript value you like in there, but a string will be returned on retrieval.

window.localStorage.setItem('age', 18);
window.localStorage.getItem('age');
// "18"

This means you should think carefully about what data you store. Aspirations of creating a browser-based Photoshop backed by localStorage isn’t architecturally sensible – it would be nice if binary data could be stored, but for now you’ll have to make do with strings.

The storage limit in most browsers is 5 MB, which probably doesn’t sound like much, but it’s actually 1000 times more than is supported by cookies.

AngularJS

There are examples of apps that use localStorage on the AngularJS blog. One that I downloaded and picked apart was FoodMe by Igor Minar. In FoodMe, Igor creates a localStorage service which basically just wraps window.localStorage so it can be loaded with dependency injection. The $scope is then watched, and a string version of a given record is dumped into localStorage using JSON.stringify:

foodMeApp.factory('customer', function($rootScope, localStorage) {
  var LOCAL_STORAGE_ID = 'fmCustomer';
  var customerString = localStorage[LOCAL_STORAGE_ID];

  var customer = customerString ? JSON.parse(customerString) : {
    name: undefined,
    address: undefined
  };

  $rootScope.$watch(function() { return customer; }, function() {
    localStorage[LOCAL_STORAGE_ID] = JSON.stringify(customer);
  }, true);

  return customer;
});

The record is loaded from localStorage, and serialised using JSON.parse and JSON.stringify. Notice that Igor has used the object-style API: localStorage.setItem(key, value) and localStorage[key] = value are equivalent.

Backbone.js

Jerome Gravel-Niquet created Backbone.localStorage (GitHub: jeromegn / Backbone.localStorage, License: MIT, bower: backbone.localStorage), which allows collections to store data with localStorage. It’s a drop-in solution – barely any configuration is required. All you need to do is add a localStorage property to your collection classes.

Backbone.localStorage has tests, and the author is still updating it. GitHub currently lists 31 contributors.

Knockout

This isn’t meant to be an exhaustive review of localStorage libraries, but I thought I’d also mention Knockout. knockout.localStorage (GitHub: jimrhoskins / knockout.localStorage) by Jim Hoskins makes ko.observable and ko.observableArray objects able to persist data to localStorage. You’ll need to specify a persist property which includes the key to store the observable’s data under.

It’s not quite as well-maintained or tested as Backbone.localStorage, but it does the job. There are some open pull requests that add things like AMD support.

Events

The Web Storage specification also defines a “storage” event. It fires when data changes, but you can’t stop it unlike other DOM events. This might make a more convenient bridge to data-binding frameworks.

Sync

If you’ve made an amazing single page app that persists data to localStorage, and you’re interested in adding a server-side API so users can save and sync data, what do you do? Well, step back and redefine the problem. Since localStorage is limited in size, why not use it like a caching layer? Your application could store data locally until a server is available, which suits a lot of use-cases, including mobile deployment. This is exactly what Backbone Caching Sync by Yiorgis Gozadinos does.

Cache

Another use people have found for localStorage is caching client-side assets. One example of this is basket.js by Addy Osmani.

Bing and Google Search make extensive use of localStorage for stashing SCRIPT blocks that are used on subsequent page views. None of the other top sites from my previous post use localStorage in this way. Are Bing and Google Search onto something? Yes, definitely.

Summary

If you need to persist data, localStorage can slot into data-binding and MVC/MVVC frameworks rather nicely. There are libraries out there, but with JSON.parse and JSON.stringify it’s trivial to store data. For applications with a server, then localStorage can be used as a temporary cache, which has the added benefit of helping support devices with intermittent network access.

Node Roundup: Node 0.10.12, grunt-micro, connect-prerenderer

19 Jun 2013 | By Alex Young | Comments | Tags node modules cluster grunt connect express
You can send in your Node projects for review through our contact form.

Node 0.10.12

Node 0.10.12 was released yesterday. This version updates v8 and npm, and has a fix for the net module.

One minor change that I liked was readline now supports CTRL-L for clearing the screen – that means Node’s command-line interface will do this as well. Before hitting CTRL-L did nothing, which wasn’t very intuitive if you’re used to using readline tools.

grunt-micro

If size is important to you, then you’ll like grunt-micro (GitHub: markdalgleish / grunt-micro, License: MIT, npm: grunt-micro) by Mark Dalgleish. This Grunt plugin ensures a script is smaller than a given size. Mark suggests this is useful for client-side authors that have size claims in their project documentation, but it could be useful for other things, like warning about asset sizes in mobile projects.

connect-prerenderer

connect-prerenderer (GitHub: dai-shi / connect-prerenderer, License: BSD, npm: connect-prerenderer) by Daishi Kato is middleware for pre-rendering content to support systems that don’t interact well with Ajax-heavy interfaces. This is ideal for improving the SEO of a site.

The author has paid special attention to AngularJS – the documentation includes some Angular client-side code that adds support for the module.

jQuery Roundup: Magnific Popup, blend.js

18 Jun 2013 | By Alex Young | Comments | Tags jquery plugins graphics images lightbox
Note: You can send your plugins and articles in for review through our contact form.

Magnific Popup

Magnific Popup

Magnific Popup (GitHub: dimsemenov / Magnific-Popup, License: MIT, jQuery: magnific-popup) by Dmitry Semenov is a responsive lightbox plugin that should work with mobile devices and also Zepto.js. It’s modular and has a build tool so you can generate a build that only includes the features you need. Sass is used for CSS, so you could easily customise the styles to suit your project.

Keyboard shortcuts are supported, the arrow keys and escape allow images to be navigated – see the gallery demo for an example of this.

A lot of the work is done by CSS, which means high DPI displays are supported:

Default controls are made with pure CSS, without external graphics. For the main image there is a built in way to provide appropriate source for different pixel density displays.

Content other than images is supported as well. The documentation has examples of using Magnific Popup with Google Maps and videos. For more information, see the Magnific documentation.

blend.js

blend.js (GitHub: qur2 / blend.js, License: MIT) by Aurélien Scoubeau applies effects to images using Canvas. The effects themselves are functions that receive pixels. Processing is applied to sections of the image in a two-dimensional grid.

Custom parameters can be passed to blending functions:

// Create some effects that will use additional arguments
var colorfx = blend.cfx(function(color, context) { return context; });
var anglefx = blend.pfx(function(angle, radius, pixels) { return pixels; });

blender.fx(colorfx, 'rgb(255, 123, 123)').fx(anglefx, [Math.PI, .25]);
blender.fx(colorfx, '#FFF', '#AAA', '#666', '#111');

// Null is used to skip zones
blender.fx(colorfx, '#FFF', null, null, '#111');

// Update the image
blender.update();

There are some bundled effects as well: desaturate, neutralize, vignette, and contrast. These can be found under blend.fx.

The author has included Mocha tests which can be ran in a browser here: blend.js/test.html.

Backbone Fetch Cache, Backbone.VirtualCollection, WTCSS

17 Jun 2013 | By Alex Young | Comments | Tags backbone.js plugins

Backbone Fetch Cache

Backbone Fetch Cache (GitHub: mrappleton / backbone-fetch-cache) by Andy Appleton caches Backbone’s collection and model fetch requests. Data is stored in localStorage to speed up rendering. This is useful for caching Ajax requests with APIs that don’t allow control over response cache headers.

The plugin supports preloading data with the prefill option which can be passed to fetch, and the author has included some Jasmine tests.

Backbone.VirtualCollection

Backbone.VirtualCollection (GitHub: p3drosola / Backbone.VirtualCollection, License: MIT, npm: backbone-virtual-collection) by Pedro Solá allows Backbone.Marionette’s CollectionViews and CompositeViews to be used with instances of Backbone.Collection. This allows collections to be projected and sorted.

This example is from the project’s documentation:

var virtual_collection = new Backbone.VirtualCollection(tasks_collection, function (task) {
  return task.get('user_id') == 13;
});

var view = new TaskListView({
  collection: virtual_collection
});

The project has Mocha tests and some details on its philosophy in the readme.

WTCSS

WTCSS

WTCSS (GitHub: benfoxall / wtcss, License: MIT) by Ben Foxall uses PhantomJS to analyse the CSS on a page, then attempts to visually indicate where each rule applies to using a Canvas overlay.

It looks impressive – there are demos on the project’s homepage, and I suspect it could form the basis for a more advanced CSS analysis and debugging tool.

Data.IO, CoffyScript, Circular Progress

14 Jun 2013 | By Alex Young | Comments | Tags browser libraries ES6 coffeescript Canvas

Data.IO

Data.IO (GitHub: scttnlsn / data.io, License: MIT, npm: data.io) by Scott Nelson is a library for bidirectional syncing over Socket.IO. It has server-side resources which encapsulate logic and persistence. Resources are stacks of composable middleware functions that sync client requests. The client-side component is comparatively lightweight – it’s lower-level than Backbone.js, so I suspect it could be used with any data binding library.

Data.IO allows you to keep core business logic on the server, while easily subscribing to data in the client. It’s a bit like Backbone.js and Express, but purpose-built for working with data syncing.

CoffyScript

CoffyScript (GitHub: loveencounterflow / coffy-script) by “loveencounterflow” is a port of CoffeeScript that adds support for yield from ES6:

If you have never programmed with iterators and generators, you may imagine as a ‘resumable return’ for starters. For the more technically oriented, ES6 defines generators as “First-class coroutines, represented as objects encapsulating suspended execution contexts (i.e., function activations).” Well, maybe ‘resumable return’ is not so bad after all.

# Using a star after the arrow 'licenses' the use of `yield` in the function body;
# it basically says: this is not an ordinary function, this is a generator function:
count = ->*
  yield 1
  yield 2
  yield 3

# Calling a generator function returns a generator:
counting_generator = count()

# Now that we have a generator, we can call one of its methods, `next`:
log counting_generator.next()   # prints: { value: 1, done: false }

# ...and we can go on doing so until the generator becomes exhausted:
log counting_generator.next()   # prints: { value: 2, done: false }
log counting_generator.next()   # prints: { value: 3, done: false }
log counting_generator.next()   # prints: { value: undefined, done: true }
log counting_generator.next()   # throws an error saying "Generator has already finished"

The documentation in the readme is thorough, and explores various aspects of working with yield. For example: How Not to Yield to Callback Hell: Serializing Control Flow.

Circular Progress

Circular Progress

Circular Progress (GitHub: neoziro / circular-progress, License: MIT, bower: circular-progress) by Greg Bergé is a progress widget with no dependencies. Given a Canvas element, it’ll show a circular representation of a process’s progress:

var progress = new CircularProgress({
  radius: 70,
  strokeStyle: 'black',
  lineCap: 'round',
  lineWidth: 4
});

document.body.appendChild(progress.el);
progress.update(40);

AngularJS: Iterators and Filters

13 Jun 2013 | By Alex Young | Comments | Tags angularjs angularfeeds mvc bower

AngularJS has a rich expression-based system for filtering and ordering data based on predicates. The orderBy filter can be used with the ng-repeat directive:

<ul>
  <li ng-repeat="item in stories | orderBy:predicate:date"><a href=""></a></li>
</ul>

Today we’re going to use orderBy inside a controller using dependency injection to organise multiple feeds into a river of news sorted by date.

Iterating in Controllers

Before sorting and displaying stories, we need to collect them into a suitable data structure. An array will suffice (app/scripts/controllers/main.js):

$scope.stories = [];

Next we need to append stories to this collection, but only if they haven’t already been added. Let’s use a function to encapsulate that away from fetching stories:

$scope.fetchFeed = function(feed) {
  feed.items = [];

  var apiUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'";
  apiUrl += encodeURIComponent(feed.url);
  apiUrl += "'%20and%20itemPath%3D'feed.entry'&format=json&diagnostics=true&callback=JSON_CALLBACK";

  $http.jsonp(apiUrl).
    success(function(data) {
      if (data.query.results) {
        feed.items = data.query.results.entry;
      }
      addStories(feed.items);

The addStories function just needs to loop over each feed item to determine if it’s already been added to $scope.stories. The angular.forEach API in module ng is the perfect way to do this:

function addStories(stories) {
  var changed = false;
  angular.forEach(stories, function(story, key) {
    if (!storyInCollection(story)) {
      $scope.stories.push(story);
      changed = true;
    }
  });
}

As you can see, forEach accepts an array and a function to call for each item. The storyInCollection function now needs to loop over each existing story to see if it’s already been added. Figuring out which story is unique is easy because feeds have an id value:

function storyInCollection(story) {
  for (var i = 0; i < $scope.stories.length; i++) {
    if ($scope.stories[i].id === story.id) {
      return true;
    }
  }
  return false;
}

Storing Data

Now we’ve got a list of stories in our scope, we need to sort them by date just like a real feed reader. Whenever addStories changes the list of stories we should sort it. AngularJS doesn’t really have any fancy functional methods like map or some, which you can find in ECMAScript 5 anyway, but it does provide API access to the filtering and sorting modules that are typically used in templates.

To access this functionality you’ll need to load $filter:

angular.module('djsreaderApp')
  .controller('MainCtrl', function($scope, $http, $timeout, $filter) {

$filter will return a function that knows how to sort or filter arrays. That means you need to call it with the name of the desired method, then call the value returned with an array and an expression: $filter(filter)(array, expression). To add sorting to our feeds, call $filter()() and update the $scope.stories array:

// At the end of addStories
if (changed) {
  $scope.stories = $filter('orderBy')($scope.stories, 'date');
}

The only thing left to do is update the template in app/views/mail.html:

<ul>
  <li ng-repeat="item in stories"><a href=""></a></li>
</ul>

If you add multiple feeds using the app’s web interface you should see them combined into a river of news.

Conclusion

The river of news view

You can find this code in commit ff4d6a6.

Node Roundup: evilscan, pm2, connectr

12 Jun 2013 | By Alex Young | Comments | Tags node modules security network cluster express connect
You can send in your Node projects for review through our contact form.

evilscan

It’s finally here, TCP port scanning in Node! evilscan (GitHub: eviltik / evilscan, License: GPLv3, npm: evilscan) by Michel Soisson is a command-line tool, and has several interesting features, like control over the amount of concurrency, geolocation information, banner grabbing, and JSON output.

The author is focusing on connect scans, but is interested in adding SYN scans and UDP support. He’s looking for contributors, and the project includes tests written with Mocha and Chai, so you really have no excuse not to help out! I think it’s great to see well-tested security-related modules.

pm2

pm2

pm2 (GitHub: Unitech / pm2, License: MIT, npm: pm2) by Alexandre Strzelewicz is a command-line process manager for Node. It can be used to start a program as a cluster of processes, and then monitor the cluster’s health, monitor the server itself (CPU/RAM/etc.), keep processes alive, log exceptions, and throttle programs that stop too quickly.

It also has tests written with Mocha, documentation, and examples.

connectr

connectr (GitHub: olalonde / connectr, License: MIT, npm: connectr) by Olivier Lalonde is a wrapper for Connect that allows middleware to be inserted at arbitrary points in the stack. That means you can add middleware before existing middleware.

It has a simple API: the before and after methods insert new middleware relative to other middleware, and it’s also possible to add middleware to the top of the stack with first, or even based on an index.

jQuery Roundup: Go Flat!

11 Jun 2013 | By Alex Young | Comments | Tags jquery plugins jqueryui design
Note: You can send your plugins and articles in for review through our contact form.

Apple’s iOS 7 was announced yesterday, with a divisive flat-design-inspired interface. Some have called it out for having inconsistent icons, and others have praised it for exploring the z-axis.

Designmodo's Flat UI.

Flat design isn’t new to the web. A few months ago, Designmodo’s Flat UI burst onto the scene, grabbing a huge amount of attention on Hacker News and reddit. Bootstrap 3 also has a decidedly flat and minimal aesthetic.

jQuery Mobile Flat-UI Theme is based on Designmodo’s project, and brings some of these design conventions over to jQuery Mobile.

If you’re looking to really take a bite out of Apple’s iOS 7 design, the use of transparency effects might edge you closer to Jony Ive’s aesthetic. You could use something like Blur.js (GitHub: jakiestfu / Blur.js) to get a jQuery plugin API for transparency, or just write the relevant CSS by hand.

Although themes and plugins are useful, the focus of modern flat design seems to be on colours. Choosing a suitable palette can be difficult, but there are shortcuts. I liked Daniel Jalkut’s post on Adobe’s Kuler – the iPhone app can be used to generate colour palettes from the camera, which Daniel describes as “granting superpowers to users”.

For more inspiration, plenty of flat design gallery sites have started to spring up – fltdsgn.com is one that I’ve enjoyed flicking through.

As interesting as Apple, Google, and Microsoft’s recent shift to flat design has been, doesn’t it seem a little bit reminiscent of the past?

You can't get flatter than this! Source: Operating System Interface Design Between 1981-2009.

Easystar.js, Boolasync, Synchroscope

10 Jun 2013 | By Alex Young | Comments | Tags angularjs libraries node async

Easystar.js

easystar

Easystar.js (GitHub: prettymuchbryce / easystarjs, License: MIT) by Bryce Neal is an A* pathfinding API. Given a map of tiles, easystar will find a path through traversable tiles on the grid:

var easystar = new EasyStar.js();
var grid = [[0,0,1,0,0],
            [0,0,1,0,0],
            [0,0,1,0,0],
            [0,0,1,0,0],
            [0,0,0,0,0]];

easystar.setGrid(grid);
easystar.setAcceptableTiles([0]);

easystar.findPath(0, 0, 4, 0, function(path)) {
  if (path === null) {
    console.log('Path was not found.');
  } else {
    console.log('Path was found. The first Point is:', path[0]);
  }
});

easystar.setIterationsPerCalculation(1000); 
easystar.calculate()

The readme has a full breakdown of the methods used in this example, and installation instructions.

Boolasync

Boolasync (GitHub: olalonde / boolasync, License: MIT, npm: boolasync) by Olivier Lalonde is a module for composing logic using chained calls to asynchronous functions:

fn1.and(fn2).or(fn3).and(fn4.orNot(fn5).and(fn6)).eval(function(err, res) {
  if (err) return console.error(err);
  if (res) {
    console.log('The expression evaluated to true.');
  } else {
    console.log('The expression evaluated to false.');
  }
});

It supports optional “monkey patching” which adds boolean logic methods to Function.prototype. Olivier has included Mocha tests and a roadmap for future features.

synchroscope

synchroscope (GitHub: dtinth / synchroscope, License: MIT, npm: synchroscope) by Thai Pangsakulyanont allows the scope to be shared between multiple AngularJS clients. It works by sending data encoded using JSON.stringify over Socket.IO.

There’s a synchroscope instance running on Nodejitsu so you can try out examples using jsFiddle and similar services. The author has asked Nodejitsu for an open source drone but is currently waiting for a response. He’s got two demos running: AngularJS Todos and Tic Tac Toe Game.

The bundled server stores everything in-memory, so it doesn’t currently scale across multiple processes. I imagine the server could easily be modified to use a database or perhaps pub/sub.

On the client the API is surprisingly minimal – once the $ync dependency has been added, data can be shared from $scope by calling $ync($scope, keys, room). It seems like an idiomatic way to make real-time web applications with AngularJS.

AngularJS and SVG

07 Jun 2013 | By John Munsch | Comments | Tags angularjs svg tutorials guest-post

John Munsch is a professional software developer with over 26 years of experience. These days he's building modern web app front ends with AngularJS after a couple of years spent doing the same kind of work with Backbone.js, Underscore.js, and Handlebars.js.

For some reason odd reason everybody thinks he's a front end guy these days despite most of his career being spent in the Java, C++, and C world.

This article was originally published at johnmunsch.wordpress.com/.

I’ve long been a fan of using SVG (Scalable Vector Graphics) to do images that I can change easily on the fly. When I say “long been a fan” I mean that when I first started doing it I hand wrote some SVG as XML to show a donation bar we needed for GameDev.net and I had a program that would change the amount thus far donated on the bar and run it through an early version of the Java Batik library to spit out a JPEG file we could put on the website. It was crude, but it sure beat making a new graphic two or three times a day.

Years later things have gotten a lot easier. Modern browsers have advanced to the point where you can include an SVG image in the page as easily as referring to them in an img tag like so, <img src=”something.svg”/>, or just dumping some SVG code straight into the middle of the HTML for your page like this <svg>…lots of vector graphics…</svg>. And editing? Why would you edit by hand anymore when Adobe Illustrator can generate SVG files of your drawings for you, or if you have no budget for such nice tools, Inkscape does a pretty good job and costs nothing.

So it occurred to me the other day that it would be interesting to see if I could use AngularJS and its ability to rewrite HTML on the fly and combine that with SVG in the browser to rewrite SVG on the fly. The answer is, it not only works, it’s downright easy to do so. I’ve provided a couple of different examples to show just how easy it is to so.

Example 1: SVG with AngularJS Model Values

Getting an image to start with was pretty easy. I went to The Noun Project and grabbed an icon of the sun I liked. It was provided by an unknown author in this case. The icon came in SVG format so all I did with it in Inkscape was add a little color and some text that showed the temperature. Then I saved that as a “Plain SVG” file rather than an “Inkscape SVG” file. It might have worked as well with the latter but I didn’t want any surprises.

Editing an SVG icon.

I then popped over to an HTML file I had generated and imported it with an image link like this:

<img alt="" src="images/sunshine_plus_temp.svg" />

I then hand edited the SVG file and found where the text for the temperature and replaced it with an AngularJS model variable reference. So:

<tspan sodipodi:role="line" id="tspan4542" x="97.124313" y="52.063747">87°</tspan>

became:

<tspan sodipodi:role="line" id="tspan4542" x="97.124313" y="52.063747">°</tspan>

The <img> way of loading the SVG had to change because AngularJS wasn’t going to replace a variable inside an image for me. So I simply pasted the contents of the sunshine_plus_temp.svg right into the middle of a page already setup for AngularJS and put the temp variable into my $scope. It worked like a charm. With an input field tied to the model variable, as I typed, the SVG graphic was automatically updated with the new value.

My final touch was to externalize the SVG file. Nobody wants to edit an HTML file with half a dozen or more embedded lumps of SVG in there. It could quickly turn into an unreadable mess. And, as I already observed, <img> won’t work either. Ah, but AngularJS jumps to the fore again because it has it’s ng-include directive. All I had to do was this:

<span ng-include="'images/sunshine_plus_temp.svg'"></span>

and AngularJS was including the image where I needed it and binding the variable to the model for real-time update. Here’s the final version of the code I came up with for my first example, note the second set of quotes inside the ng-include to tell it not to interpret the string inside there, it’s just a string to use directly:

  <div>
    <p>Example 1: Text updated on the fly in an SVG graphic via AngularJS.</p>
    <span ng-include="'images/sunshine_plus_temp.svg'"></span>
  </div>
  <label>Temperature</label> <input type="text" ng-model="temp"/>

It’s worth noting that Inkscape is still perfectly capable of editing the SVG file even after the change I made and I guess I could have just made the change within Inkscape in the first place and never bothered opening up the file to manually change it with a text editor.

Editing an SVG icon that has been modified by AngularJS.

Example 2: Incorporating an Image

We don’t really need a second example here, the first one showed pretty much everything but I wanted to show how easily images incorporate into SVG and help you achieve results that would be much much harder to do with other techniques. In this example I took a slides icon by Diego Naive, from The Noun Project, overlaid an image on top of it, and then overlaid a glossy reflection on top of half the slide, just to show that the image is fully incorporated by the graphic and can easily be rotated, have graphics on top of it, underneath it, etc. Stuff that would require a lot of work to do with many other techniques.

Again, I tested it out and edited the final SVG file to add a variable reference, in this case to instead of the specific file reference that I had added with Inkscape. This time, I will say that it does not edit nearly as well in Inkscape after the edit because it doesn’t know where to find an image named ””. Within the Inkscape editor you just see an error box where the image should be. Not perfect, but not debilitating either.

Here’s a page with links to both examples and to the GitHub repository with all the code for both: http://johnmunsch.github.io/AngularJSExamples/

AngularJS: Form Validation

06 Jun 2013 | By Alex Young | Comments | Tags angularjs angularfeeds mvc bower

This week we’re going to look at form validation with AngularJS. Angular has several directives that support form field validation, and they’re based on the HTML5 form validators. You can specify that a field is required, a certain size, a certain type, and should match a given pattern.

URL Validation

Chrome's validation message

This tutorial series is about a feed reader, so it’s lucky that one of the standard HTML5 validators is for checking URLs. It can be used by adding the type="url" attribute to an input. Angular supports this through the input url directive. It takes various options, of which we’re interested in required and ng-model.

The ng-model directive allows the input to be linked to a model, but any Angular expression can be used. The form directive allows forms to be managed with Angular, and bound to controllers.

Just by adding a form and an input with type="url" will result in some basic validation support (in app/views/main.html):

<form name="newFeed">
  URL: <input size="80" name="url" ng-model="newFeed.url" type="url" required>
  <button ng-click="addFeed(newFeed)">Add Feed</button>
</form>

However, this won’t quite work with the controller code that I wrote in the previous parts because addFeed isn’t set up to check validation.

Checking Validation State

In a controller, a bound value can be interrogated for the validation status by checking the $valid property. The previous addFeed, in app/scripts/controllers/main.js, can be changed as follows:

$scope.addFeed = function(feed) {
  if (feed.$valid) {
    // Copy this feed instance and reset the URL in the form
    $scope.feeds.push(feed);
    $scope.newFeed.url = {};
  }
};

This should work, but it does one thing wrong: $scope.newFeed.url can’t be reset by assigning it to an object literal, because newFeed is now decorated with internal properties to support validation. Instead, copy the new object, and reset the values in newFeed:

$scope.addFeed = function(feed) {
  if (feed.$valid) {
    // Copy this feed instance and reset the URL in the form
    var newFeed = angular.copy(feed);
    $scope.feeds.push(newFeed);
    $scope.fetchFeed(newFeed);
    $scope.newFeed.url = '';
  }
};

Fighting with HTML5

We should probably add error messages that are cross-browser compatible. To do that, you can use the ng-show directive:

<form name="newFeed" novalidate>
  URL: <input size="80" name="url" ng-model="newFeed.url" type="url" required>
  <button ng-click="addFeed(newFeed)">Add Feed</button>
  <span class="error" ng-show="newFeed.$error.required">Required!</span>
  <span class="error" ng-show="newFeed.$error.url">Invalid URL format!</span>
</form>

The ngShow directive can conditionally show part of the DOM based on an Angular expression – in this case the validation results are checked. Incidentally, validation results can be found in the $error property fo the model.

Also notice that I added the novalidate attribute to the form; if you don’t do this HTML5 validations will still kick in, which causes confusing behaviour.

Disabling the Button

Another nice touch is to use ng-disabled to disable the button when an invalid URL has been entered. The ngDisabled directive takes an Angular expression, like the previous directives discussed here:

<form name="newFeed" novalidate>
  URL: <input size="80" name="url" ng-model="newFeed.url" type="url" required>
  <button ng-disabled="!newFeed.$valid" ng-click="addFeed(newFeed)">Add Feed</button>
  <span class="error" ng-show="newFeed.$error.required">Required!</span>
  <span class="error" ng-show="newFeed.$error.url">Invalid URL format!</span>
</form>

The difference here is I’ve used ! to negate the expression: !newFeed.$valid. Yes, it’s really that easy!

Conclusion

There’s more to expressions than simple model-based truth tests – you can do pretty much anything short of control flow statements. For more, see Angular Developer Guide, Expressions.

The latest commit for this project was 0dcc996.