Monday, January 25, 2016

Preparing for ECMAScript 6: Symbols and Their Uses

While ES2015 has introduced many language features that have been on developers' wish lists for some time, there are some new features that are less well known and understood, and the benefits of which are much less clear. One such feature is the symbol. The symbol is a new primitive type, a unique token that is guaranteed never to clash with another symbol. In this sense, you could think of them as a kind of UUID (Universally Unique Identifier). Let's look at how they work, and what we can do with them (Note: all examples in this article have been tested in the latest versions of Chrome and Firefox for Linux, but the behavior may vary from browser to browser or when using tools such as Firebug).

Creating New Symbols

[author_more]

Creating new symbols is very straightforward and is simply a case of calling the Symbol function. Note that this is a just a standard function and not an object constructor. Trying to call it with the new operator will result in a TypeError. Every time you call the Symbol function, you will get a new and completely unique value.

let foo = Symbol();
let bar = Symbol();

foo === bar
// <-- false

Symbols can also be created with a label, by passing a string as the first argument. The label does not affect the value of the symbol, but is useful for debugging, and is shown if the symbol's toString() method is called. It's possible to create multiple symbols with the same label, but there's no advantage to doing so and this would probably just lead to confusion.

let foo = Symbol('baz');
let bar = Symbol('baz');

foo === bar
// <-- false
console.log(foo);
// <-- Symbol(baz)

What Can I Do With Them?

Symbols could often be a good replacement for strings or integers as class/module constants:

class Application {
  constructor(mode) {
    switch (mode) {
      case Application.DEV:
        // Set up app for development environment
        break;
      case Application.PROD:
        // Set up app for production environment
        break;
      case default:
        throw new Error('Invalid application mode: ' + mode);
    }
  }
}

Application.DEV = Symbol('dev');
Application.PROD = Symbol('prod');

// Example use
let app = new Application(Application.DEV);

String and integers are not unique values; values such as the number 2 or the string 'development', for example, could also be in use elsewhere in the program for different purposes. Using symbols means we can be more confident about the value being supplied.

Another interesting use of symbols is as object property keys. If you've ever used a JavaScript object as a hashmap (an associative array in PHP terms, or dictionary in Python) you'll be familiar with getting/setting properties using the bracket notation:

let data = [];

data['name'] = 'Ted Mosby';
data['nickname'] = 'Teddy Westside';
data['city'] = 'New York';

Continue reading %Preparing for ECMAScript 6: Symbols and Their Uses%


by Nilson Jacques via SitePoint

Web Design Weekly #219

Headlines

The Web Is Okay

Wise words from Charlotte Spencer about remaining calm why the world of web development goes crazy. (charlotteis.co.uk)

Responsive Email Designer App

Creating responsive emails is a huge plus for individuals and companies today. With more than 50% of emails initially being opened and read on smartphones and tablets, a solid responsive design is pretty much a necessity. Check it out today. (mightydeals.com)

Articles

Leaner Responsive Images With Client Hints

In this article Jon Arne Sæterås looks into how Client Hints can reduce both image size and verbosity of the responsive images markup. (smashingmagazine.com)

The woes of date input

The HTML5 date input is far from perfect and in this post Ian Devlin explains some of the the outstanding quirks that we should be aware of.  (html5doctor.com)

Everything I know about responsive web typography with CSS

A great article by Zell Weekeat that explore various techniques for achieving good web typography. He also has a nice introduction into using Typi, which is a handy Sass library for making your life easier. (zell-weekeat.com)

Designing A Product Page Layout with Flexbox

Levin Mejia, who is Designer Advocate at Shopify, shares about Shopify starting to use flexbox in new themes they develop. (css-tricks.com)

Critical Web Fonts

Zach Leatherman revisits the history of web font loading and takes a look into the future. (zachleat.com)

How to Create Visually Effective Calls-To-Action (rafaltomal.com)

Subgrids Considered Essential (meyerweb.com)

Tools / Resources

Why I Left Gulp and Grunt for npm Scripts

Cory House explains how he has found Gulp and Grunt to be unnecessary abstractions, whereas npm scripts are plenty powerful and often easier to live with. (medium.com)

Setting up HTTP/2

Alexander Surma follows up on his Chrome Dev Summit talk with an in-depth article on how to go about setting up HTTP/2 today. (surma.link)

Web accessibility tools round-up

Carlin Scuderi takes a look at some of the tools available that make our lives and the lives of people with a disability a bit easier. (medium.com)

SVGnest

An open source vector nesting tool developed by Jack Qiao which helps rearrange SVG shapes to take up as little space as possible. (github.com)

Awesome npm

A large selection on npm resources and tips put together by the community. (github.com)

22 Essential CSS Recipes (ipestov.com)

Inspiration

How I Shrank my CSS by 84kb by Refactoring with ITCSS (jordankoschei.com)

Designing a mobile app flow diagram in Sketch (youtube.com)

Cinema Seat Preview Experiment (tympanus.net)

Jobs

Design Engineer at Help Scout

As a design engineer at Help Scout, it’s your job to create not only a pixel-perfect experience for customers, but to do so by writing front-end code that’s clean, performant and consistent with the standards we’ve established as a team. Along with four other tight-knit designers on the team, you’ll be responsible for moving our brand and user experience forward. (helpscout.net)

Web Developer at Dropbox

Our Engineering team is architecting a family of products that handle over a billion files a day. We take on the complexities of technology that affect everyday life, so that people can get back to living and doing their best work. If you are keen to work on something that impacts the world, we would love to hear from you. (dropbox.com)

Need to find passionate developers? Why not advertise in the next newsletter

Last but not least…

10 Years of Web Inspector (webkit.org)

A simple cursor game written in CSS (victordarras.fr)

The post Web Design Weekly #219 appeared first on Web Design Weekly.


by Jake Bresnehan via Web Design Weekly

Using Modern CSS to Build a Responsive Image Grid

Building custom responsive layouts is always exciting. This article examines a technique that we can use to take full control of the distance between grid columns. To demonstrate this, I’ll use the example of a responsive image gallery.

Building a Responsive Layout

To begin with, let’s assume on large screens our gallery should look something like this:

Required layout for large screens

On smaller screens (i.e. <50em), it should have the following appearance:

Required layout for small screens

The markup is simple:

[code language="html"]
<div>
<a href="path-to-the-image">
<figure>
<img src="path-to-the-image" alt="">
</figure>
</a>

<!-- other anchors here ... -->

</div>
[/code]

As you probably already know, we can take advantage of different layout methods for generating the desired result. Before I examine two of those possible methods, let’s take note of our initial requirements (see previous visualizations):

  • I want a 2-column layout on medium screens and smaller (i.e. <50em), and a 4-column layout on large screens (50em or above).
  • The distance between columns should be 8px.

Using inline-block

I’ll first use the display:inline-block method to build our gallery. Consider the following CSS:

[code language="css"]
div {
font-size: 0;
}

a {
font-size: 16px;
display: inline-block;
margin-bottom: 8px;
width: calc(50% - 4px);
margin-right: 8px;
}

a:nth-of-type(2n) {
margin-right: 0;
}

@media screen and (min-width: 50em) {
a {
width: calc(25% - 6px);
}

a:nth-of-type(2n) {
margin-right: 8px;
}

a:nth-of-type(4n) {
margin-right: 0;
}
}
[/code]

Here’s an explanation of what I’ve done:

By default, there’s a space between inline-block elements. One way to override this is to set the font size of the parent element to zero. This might also require that we reset the font size of any child elements (not necessary in our case).

On small screens I have a 2-column layout and I specify 8px of space between columns.

The width of our columns is calculated as follows:

  • Total space between columns per row = 1 * 8px => 8px. The derived value is 8px and not 16px because I remove the right margin for every second column on small screens.
  • The width of each column = calc(50% - 4px). The value 4px derived by calculating: Total space between columns per row / Number of columns per row (8px / 2 => 4px).

2 column layout

On large screens I have a 4-column layout and I specify 8px space between columns. So, the width of our columns is calculated as follows:

Continue reading %Using Modern CSS to Build a Responsive Image Grid%


by George Martsoukos via SitePoint

How to Make Your Web App Smarter with Image Recognition

Clarifai is an API which provides image and video recognition that is incredibly simple to use and a whole lot of fun to implement. In this article, we will explore dragging and dropping images from around the web into a simple web app that will read them and tell us what it believes they are.

In this demo, we will be using Node.js for the server and a relatively basic front end that uses jQuery for AJAX requests. If you aren't strong in Node.js, that should be okay as long as you are at a level where you are comfortable running npm install to pull in modules and node app.js in the command line to get your web app going. You won't need to customize too much within it and might learn a thing or two in the end by getting the existing code running!

The Code

All of the sample code for this demo is available on GitHub.

Getting Started

To get started, we go to the Clarifai home page and click the "Sign up now" button on the top right:

Clarifai Homepage

Sign up with your email and details:

Clarifai's signup page

We want to create a new application, so we head to the application screen by clicking the "Applications" menu item on the left.

Creating a new application in Clarifai

Clarifai won't allow us to create an application just yet, as we need to choose a plan:

Finding the choose a plan button

Lets choose a plan so we can get things going. For our demo, the free plan should be more than suitable. We can upgrade later if needed:

Choosing a Clarifai plan

We are now allowed to create an application, to do so we can either click the "Applications" menu item on the left or the "create an Application" link:

Navigating back to create an application

Click the "Create a New Application" button:

The "Create a new application button"

We give our new application a name (e.g. "Image Recognizer"), leave the default model as is and set our language (we have kept it on English, you may prefer a different language!). To finish, click "Create Application":

Creating a Clarifai application

Our new application details should now appear. The two most important bits we will want to copy somewhere safe are our "Client ID" and "Client Secret" — we will need these to access Clarifai on our server that we will set up next.

Finding your Clarifai keys

Setting Up Our Node.js Server

Clarifai has a Node.js client we can use to interface with its service available on GitHub. Download the repo to your computer. In particular, we want the clarifai_node.js file.

Create a directory for your Node server and add the `clarifai_node.js` JavaScript file into the root directory.

Our Node.js server functions will be within a JavaScript file called app.js. This is where we will manage our Clarifai powered image recognition requests. app.js has the following JavaScript:

[code language="js"]
var Clarifai = require("./clarifai_node.js"),
express = require("express"),
app = express(),
server = require("http").Server(app),
bodyParser = require("body-parser"),
port = process.env.PORT || 5000;

app.use(bodyParser.json());

Clarifai.initAPI("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET");

function identifyClarifaiError(err) {
// Default error function from Clarifai we won't go into but you can find it in the GitHub download of this code!
}

app.post("/examineImage", function(req, resp) {
var imageURL = req.body.imageRequested;
console.log("Response was ", imageURL);

Clarifai.tagURL(imageURL, "Image from browser", commonResultHandler);

function commonResultHandler(err, res) {
if (err != null) {
identifyClarifaiError(err);
}
else {
if (typeof res["status_code"] === "string" &&
(res["status_code"] === "OK" || res["status_code"] === "PARTIAL_ERROR")) {

if (res["results"][0]["status_code"] === "OK") {
var tags = res["results"][0].result["tag"]["classes"];
console.log("Tags found were: ", tags);
resp.send(tags);
}
else {
console.log("We had an error... Details: " +
" docid=" + res.results[0].docid +
" local_id=" + res.results[0].local_id +
" status_code="+res.results[0].status_code +
" error = " + res.results[0]["result"]["error"]);

resp.send("Error: " + res.results[0]["result"]["error"]);
}
}
}
}
});

app.get("/", function(request, response) {
response.sendFile(__dirname + "/public/index.html");
});

app.get(/^(.+)$/, function(req, res) {
res.sendFile(__dirname + "/public/" + req.params[0]);
});

app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send("Something broke!");
});

server.listen(port, function() {
console.log("Listening on " + port);
});
[/code]

A large proportion of the code is basic Node express server functionality which we won't cover in this article, if you aren't quite sure these parts mean, you can leave them as is and just enjoy a running Node server.

The bits which relate specifically to Clarifai begin with our line of code that includes our clarifai_node.js file:

[code language="js"]
var Clarifai = require("./clarifai_node.js"),
[/code]

The next line which uses Clarifai starts out initialization of the API. It gives us access to the API using the client ID and client secret which we copied somewhere safe earlier. Paste them into the appropriate spots:

[code language="js"]
Clarifai.initAPI("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET");
[/code]

We then have a POST request which the Node server will look out for and respond to. This request expects to receive a web URL for an image within our POST body called imageRequested when accessed via /examineImage. It logs whatever URL it finds into our console:

[code language="js"]
app.post("/examineImage", function(req, resp) {
var imageURL = req.body.imageRequested;
console.log("Response was ", imageURL);
[/code]

We then run a function from the Clarifai Node API Client called tagURL(). This function takes three parameters — the image URL we want Clarifai to examine, a name we give the image (you could potentially change this name and adapt it from the URL if you wanted but to keep it simple we've kept it as a generic name for all) and the callback function once it has run:

[code language="js"]
Clarifai.tagURL(imageURL, "Image from browser", commonResultHandler);
[/code]

Continue reading %How to Make Your Web App Smarter with Image Recognition%


by Patrick Catanzariti via SitePoint

Building a Multi-step Registration Form for WordPress

The default login, registration and password reset forms included in WordPress (outside the website developed with it) often do not conform to the design and branding of the site.

In the past when WordPress was a blogging engine, this was fine. WordPress has since evolved into a content management system, leading to an ever increasing demand for custom login, registration and password reset forms.

In this tutorial, we'll learn how to build a WordPress multi-step registration form using a plugin that I've developed called ProfilePress.

It is worth noting that we've previously covered how to build custom login, registration and password reset forms with ProfilePress and a tabbed login and signup widget.

Below is the design of the multi-step registration form which we will have built by the end of this tutorial.

See the Pen Multi Step Registration Form with Progress Bar using jQuery and CSS3 by Agbonghama Collins (@collizo4sky) on CodePen.

If you want to jump ahead of this tutorial, here is a live demo of the form in a WordPress powered site.

Continue reading %Building a Multi-step Registration Form for WordPress%


by Agbonghama Collins via SitePoint

Command Buses Demystified: A Look at the Tactician Package

Command Buses have been getting a lot of community attention lately. The topic can be quite overwhelming at first when trying to understand all the concepts and terminology, but in essence - what a Command Bus does is actually incredibly simple.

In this article, we’ll take a closer look at variations of the Command Pattern; their components; what a Command Bus is; and an example application using the Tactician package.

Hero Image?

Overview

So, what exactly is a Command Bus?

Command Pattern

The role of the Command Bus is to ensure the transport of a Command to its Handler. The Command Bus receives a Command, which is nothing more than a message describing intent, and passes this onto a Handler which is then responsible for performing the expected behavior. This process can therefore be looked upon as a call to the Service Layer - where the Command Bus does the plumbing of the message in-between.

Before the introduction of the Command Bus, Service Layers were often a collection of classes without a standard way of being invoked. Command Buses solve this problem by providing a consistent interface and better defining the boundary between two layers. The standard interface also makes it possible for additional functionality to be added by wrapping with decorators, or by adding middleware.

Therefore, there can be more to a Command Bus than calling a Service Layer. Basic implementations may only locate a Handler based on naming conventions, but more complex configurations may pass a Command through a pipeline. Pipelines can perform additional behavior, such as: wrapping the behavior in a transaction; sending the Command over a network; or perhaps some queueing and logging.

Continue reading %Command Buses Demystified: A Look at the Tactician Package%


by Andrew Cairns via SitePoint

Moonflower – Linea Light Group

Moonflower - Linea Light Group

One Pager with a dot navigation to slide between sections promoting a new decorating lighting system called "Moonflower" by Linea Light Group.

by Rob Hope via One Page Love