Collective #500

CSS Nesting Module The draft of a new CSS module that introduces the ability to nest one style rule inside another. Read it This content is sponsored via Thought Leaders Seeking a common language for design & engineering How design and engineering work together Read more

Breaking Boxes With CSS Fragmentation

dreamt up by webguru in Uncategorized | Comments Off on Breaking Boxes With CSS Fragmentation

Breaking Boxes With CSS Fragmentation

Breaking Boxes With CSS Fragmentation

Rachel Andrew



In this article, I’m going to introduce you to the CSS Fragmentation specification. You might never have heard of it, however, if you have ever created a print stylesheet and wanted to control where the content breaks between pages, or multi-column layout and wanted to stop a figure breaking between columns, you have encountered it.

I find that quite often problems people report with multicol are really problems with browser support of fragmentation. After a quick rundown of the properties contained in this specification, I’ll be explaining the current state of browser support and some of the things you can do to get it working as well as it can in your multicol and print projects.

What Is Fragmentation?

Fragmentation in CSS describes the process by which content becomes broken up into different boxes. Currently, we have two places in which we might run into fragmentation on the web: when we print a document, and if we use multi-column layout. These two things are essentially the same. When you print (or save to PDF) a webpage, the content is fragmented into as many pages as are required to print your content.

When you use multicol, the content is fragmented into columns. Each column box is like a page in the paged context. If you think of a set of columns as being much like a set of pages it can be a helpful way to think about multicol and how fragmentation works in it.

If you take a look at the CSS Fragmentation Specification you will see a third fragmented context mentioned — that context is Regions. As there are no current usable implementations of Regions, we won’t be dealing with that in this article, but instead looking at the two contexts that you might come across in your work.

Block And Inline Boxes

I am going to mention block boxes a lot in this article. Every element of your page has a box. Some of those boxes are laid out as blocks: paragraphs, list items, headings. These are said to be participating in a block formatting context. Others are inline such as the words in a paragraph, spans and anchor elements. These participate in an inline formatting context. Put simply, when I refer to a block box, I’m talking about boxes around things like paragraphs. When dealing with fragmentation, it is important to know which kind of box you are dealing with.

For more information on block and inline layout, see the MDN article “Block And Inline Layout In Normal Flow”. It is one of those things that we probably all understand on some level but might not have encountered the terminology of before.

Controlling Breaks

Whether you are creating a print stylesheet, using a specific print user agent to make a PDF,or using multicol, you will sometimes run into problems that look like this.

In the below multicol example, I have some content which I am displaying as three columns. In the middle of the content is a boxed out area, which is being broken across two columns. I don’t want this behavior — I would like the box to stay together.


Three columns with a boxed out area broken across two of them
The box breaks across two columns (Large preview)

To fix this, I add the property break-inside: avoid to the box. The break-inside property controls breaks inside elements when they are in a fragmented context. In a browser which supports this property, the box will now stay in one of the columns. The columns will look less well balanced, however, that is generally a better thing than ending up with the boxout split across columns.

The break-inside property is one of the properties detailed in the fragmentation spec. The full list of properties is as follows:

  • break-before
  • break-after
  • break-inside
  • orphans
  • widows
  • box-decoration-break

Let’s have a look at how these are supposed to work before we move onto what actually happens in browsers.

The break-before And break-after Properties

There are two properties that control breaks between block-level boxes: break-before and break-after. If you have an h2 followed by two paragraphs <p> you have three block boxes and you would use these properties to control the breaks between the heading and first paragraph, or between the two paragraphs.

The properties are used on selectors which target the element you want to break before or after.

For example, you might want your print stylesheet to break onto a new page every time there is a level 2 heading. In this case, you would use break-before: page on the h2 element. This controls the fragmentation and ensures there is always a break before the box of the h2 element.

h2 {
    break-before: page;
}

Another common requirement is to prevent headings ending up as the last thing on a page or column. In this case, you might use break-after with a value of avoid. This should prevent a break directly after the box of the element:

h1, h2, h3, h4 {
    break-after: avoid;
}
Fragments Within Fragments

It is possible that you might have an element that is fragmented nested inside another. For example, having a multicol inside something which is paged. In that case, you might want to control breaks for pages but not for columns, or the other way around. This is why we have values such as page which would always force a break before or after the element but only when the fragment is a page. Or avoid-page which would avoid a break before or after the element only for paged contexts.

The same applies to columns. If you use the value column, this would always force a break before or after that element, but only for multicol contexts. The value avoid-column would prevent a break in multicol contexts.

There is an always value in the Level 4 specification which indicates that you want to break through everything – page or column. However, as a recent addition to the spec it is not currently useful to us.

Additional Values For Paged Media

If you are creating a book or magazine, you have left and right pages. You might want to control breaking in order to force something onto the left or right page of a spread. Therefore, using the following would insert one or two-page breaks before the h2 to ensure it was formatted as a right page.

h2 {
    break-before: right;
}

There are also recto and verso values which relate to page progression as books written in a vertical or right to left language have a different page progression than books written in English. I’m not going to cover these values further in this article as I’m primarily concerned with what is possible from the browser this time.

break-inside

We have already seen an example of the break-inside property. This property controls breaking inside block boxes, e.g. inside a paragraph, heading or a div.

Things that you may not want to break can include a boxout as described above: figures where you do not want the caption detached from the image, tables, lists and so on. Add break-inside: avoid to any container you don’t wish to break in any fragmentation context. If you only wish to avoid breaks between columns use break-inside: avoid-column and between pages break-inside: avoid-page.

The orphans And widows Properties

The orphans and widows properties deal with how many lines should be left before or after a break (either caused by a column or a new page). For example, if I want to avoid a single line being left at the end of a column, I would use the orphans property, as in typography, an orphan is the first line of a paragraph that appears alone at the bottom of a page with the rest of the paragraph broken onto another page. The property should be added to the same element which is fragmenting (in our case, the multicol container).

.container {
    column-count: 3;
    orphans: 2;
}

To control how many lines should be at the top of a column or page after a break, use widows:

.container {
    column-count: 3;
    widows: 2;
}

These properties deal with breaks between inline boxes such as the lines of words inside a paragraph. Therefore, they don’t help in the situation where a heading or other block element is alone at the bottom of a column or page, you need the break properties discussed above for that.

Box Decoration

A final property that may be of interest is the box-decoration-break property. This controls the situation where you have a box with a border broken between two column boxes or pages. Do you want the border to essentially be sliced in half? Or do you want each of the two halves of the box to be wrapped fully in a border?

The first scenario is the default, and is as if you set the box-decoration-break property to slice on the box.

.box {
    box-decoration-break: slice;
}

A box with a border which is broken between columns
A value of slice means the border is effectively sliced in half (Large preview)

To get the second behavior, set box-decoration-break to clone.

.box {
    box-decoration-break: clone;
}

Boxes are completely wrapped in borders
A value of clone means the border is wrapped fully round each fragment of the box (Large preview)

Browser Support For Fragmentation

Now we come to the reason I don’t have a bunch of CodePen examples above to demo all of this to you, and the main reason for my writing this article. Browser support for these properties is not great.

If you are working in Paged Media with a specific user agent such as Prince, then you can enjoy really good support for fragmentation, and will probably find these properties very useful. If you are working with a web browser, either in multicol, creating print stylesheets, or using something like Headless Chrome to generate PDFs, support is somewhat patchy. You’ll find that the browser with the best support is Edge — until it moves to Chromium anyway!

Can I Use isn’t overly helpful with explaining support due to mixing the fragmentation properties in with multicol, then having some separate data for legacy properties. So, as part of the work I’ve been doing for MDN to document the properties and their support, I began testing the actual browser support. What follows is some advice based on that testing.

Legacy And Vendor Prefixed Properties

I can’t go much further without a history lesson. If you find you really need support for fragmentation then you may find some relief in the legacy properties which were originally part of CSS2 (or in some prefixed properties that exist).

In CSS2, there were properties to control page breaking. Multicol didn’t exist at that point, so the only fragmented context was a paged one. This meant that three specific page breaking properties were introduced:

  • page-break-before
  • page-break-after
  • page-break-inside

These work in a similar way to the more generic properties without the page- prefix, controlling breaks before, after and inside boxes. For print stylesheets, you will find that some older browsers which do not support the new break- properties, do support these page prefixed properties. The properties are being treated as aliases for the new properties.

In a 2005 Working Draft of the multicol specification are details of breaking properties for multicol — using properties prefixed with column- (i.e. column-break-before, column-break-after, and column-break-inside). By 2009, these had gone, and a draft was in the multicol specification for unprefixed break properties which eventually made their way into the CSS Fragmentation specification.

However, some vendor prefixed column-specific properties were implemented based on these properties. These are:

  • -webkit-column-break-before
  • -webkit-column-break-after
  • -webkit-column-break-inside

Support For Fragmentation In Multicol

The following is based on testing these features in multicol contexts. I’ve tried to explain what is possible, but do take a look at the CodePens in whichever browsers you have available.

Multicol And break-inside

Support in multicol is best for the break-inside property. Up to date versions of Chrome, Firefox, Edge, and Safari all support break-inside: avoid. So you should find that you can prevent boxes from breaking between columns when using multicol.

Several browsers, with the exception of Firefox, support the -webkit-column-break-inside property, this can be used with a value of avoid and may prevent boxes breaking between columns which do not have support for break-inside.

Firefox supports page-break-inside: avoid in multicol. Therefore, using this property will prevent breaks inside boxes in Firefox browsers prior to Firefox 65.

This means that if you want to prevent breaks between boxes in multicol, using the following CSS will cover as many browsers as possible, going back as far as possible.

.box {
    -webkit-column-break-inside: avoid;
    page-break-inside: avoid;
    break-inside: avoid;
}

As for the column value, explicitly stating that you only want to avoid breaks between columns, and not pages, works in all browsers except Firefox.

The below CodePen rounds up some of these tests in multicol so you can try them for yourself.

Multicol And break-before

In order to prevent breaks before an element, you should be able to use break-before: avoid or break-before: avoid-column. The avoid property has no browser support.

Edge supports break-before: column to always force a break before the box of the element.

Safari, Chrome and Edge also support -webkit-column-break-before: always which will force a break before the box of the element. Therefore, if you want to force a break before the box of an element, you should use:

.box {
    -webkit-column-break-before: always;
    break-before: column;
}

Preventing a break before the box is currently an impossible task. You can play around with some examples of these properties below:

Multicol And break-after

To prevent breaks after an element, to avoid it becoming the last thing at the bottom of a column, you should be able to use break-after: avoid and break-after: avoid-column. The only browser with support for these is Edge.

Edge also supports forcing breaks after an element by using break-after: column, Chrome supports break-after: column and also -webkit-column-break-after: always.

Firefox does not support break-after or any of the prefixed properties to force or allow breaks after a box.

Therefore, other than Edge, you cannot really avoid breaks after a box. If you want to force them, you will get results in some browsers by using the following CSS:

.box {
    -webkit-break-after: always;
    break-after: column;
}

Support When Printing From The Browser

Whether you print directly from your desktop browser or generate PDF files using headless Chrome or some other solution reliant on browser technology doesn’t make any difference. You are reliant on the browser support for the fragmentation properties.

If you create a print stylesheet you will find similar support for the break properties as for multicol, however, to support older browsers you should double up the properties to use the page- prefixed properties.

In modern browsers ,the break-inside property can be used to prevent breaks inside boxes, add the page-break-inside property to add support for older browsers.

.box {
    page-break-inside: avoid;
    break-inside: avoid;
}

To force breaks before a box use break-before:page along with page-break-before: always.

.box {
    page-break-before: always;
    break-before: page;
}

To avoid breaks before a box use break-before: avoid-page along with page-break-before: avoid.

.box {
    page-break-before: avoid;
    break-before: avoid-page;
}

There is better support for the page and avoid-page values than we see for the equivalent multicol values. The majority of modern browsers have support.

To force breaks after a box, use break-after: page along with page-break-after: always.

.box {
    page-break-after: always;
    break-after: page;
}

To prevent breaks after a box use break-after: avoid-page along with page-break-after: avoid.

.box {
    page-break-after: avoid;
    break-after: avoid-page;
}

Widows And Orphans

The widows and orphans properties enjoy good cross-browser support — the only browser without an implementation being Firefox. I would suggest using these when creating a multicol layout or print stylesheet. If they don’t work for some reason, you will get widows and orphans, which isn’t ideal but also isn’t a disaster. If they do work your typography will look all the better for it.

box-decoration-break

The final property of box-decoration-break has support for multicol and print in Firefox. Safari, Chrome and other Chromium-based browsers support -webkit-box-decoration-break, but only on inline elements. So you can clone borders round lines of a sentence for example; they do not have support in the context we are looking at.

In the CodePen below, you can see that testing for -webkit-box-decoration-break: clone with Feature Queries returns true, however, the property has no effect on the border of the box in the multicol context.

Using Fragmentation

As you can see, the current state of fragmentation in browsers is somewhat fragmented! That said, there is a reasonable amount you can achieve and where it fails, the result tends to be suboptimal but not a disaster. Which means it is worth trying.

It is worth noting that being too heavy handed with these properties could result in something other than what you hoped for. If you are working on the web rather than print and force column breaks after every paragraph, then end up with more paragraphs than space for columns, multicol will end up overflowing in the inline direction. It will run out of columns to place your additional paragraphs. Therefore, even where there is support, you still need to test carefully, and remember that less is more in a lot of cases.

More Resources

To read more about the properties head over to MDN, I’ve recently updated the pages there and am also trying to keep the browser compat data up to date. The main page for CSS Fragmentation links to the individual property pages which have further examples, browser compat data and other information about using these properties.

Smashing Editorial
(il)

Source: Smashing Magazine, Breaking Boxes With CSS Fragmentation

Sliding In And Out Of Vue.js

dreamt up by webguru in Uncategorized | Comments Off on Sliding In And Out Of Vue.js

Sliding In And Out Of Vue.js

Sliding In And Out Of Vue.js

Kevin Ball



Vue.js has achieved phenomenal adoption growth over the last few years. It has gone from a barely known open-source library to the second most popular front-end framework (behind only React.js).

One of the biggest reasons for its growth is that Vue is a progressive framework — it allows you to adopt bits and pieces at a time. Don’t need a full single page application? Just embed a component. Don’t want to use a build system? Just drop in a script tag, and you’re up and running.

This progressive nature has made it very easy to begin adopting Vue.js piecemeal, without having to do a big architecture rewrite. However, one thing that is often overlooked is that it’s not just easy to embed Vue.js into sites written with other frameworks, it’s also easy to embed other code inside of Vue.js. While Vue likes to control the DOM, it has lots of escape hatches available to allow for non-Vue JavaScript that also touches the DOM.

This article will explore the different types of third-party JavaScript that you might want to use, what situations you might want to use them inside of a Vue project, and then cover the tools and techniques that work best for embedding each type within Vue. We’ll close with some considerations of the drawbacks of these approaches, and what to consider when deciding if to use them.

This article assumes some familiarity with Vue.js, and the concepts of components and directives. If you are looking for an introduction to Vue and these concepts, you might check out Sarah Drasner’s excellent introduction to Vue.js series or the official Vue Guide.

Types Of Third-Party JavaScript

There are three major types of third-party JavaScript that we’ll look at in order of complexity:

  1. Non-DOM Touching Libraries
  2. Element Augmentation Libraries
  3. Components And Component Libraries

Non-DOM Libraries

The first category of third-party JavaScript is libraries that provide logic in the abstract and have no direct access to the DOM. Tools like moment.js for handling dates or lodash for adding functional programming utilities fall into this category.

These libraries are trivial to integrate into Vue applications, but can be wrapped up in a couple of ways for particularly ergonomic access. These are very commonly used to provide utility functionality, the same as they would in any other type of JavaScript project.

Element Augmentation Libraries

Element augmentation is a time-honored way to add just a bit of functionality to an element. Examples include tasks like lazy-loading images with lozad or adding input masking using Vanilla Masker.

These libraries typically impact a single element at a time, and expect a constrained amount of access to the DOM. They will likely be manipulating that single element, but not adding new elements to the DOM.

These tools typically are tightly scoped in purpose, and relatively straightforward to swap out with other solutions. They’ll often get pulled into a Vue project to avoid re-inventing the wheel.

Components And Component Libraries

These are the big, intensive frameworks and tools like Datatables.net or ZURB Foundation. They create a full-on interactive component, typically with multiple interacting elements.

They are either directly injecting these elements into the DOM or expect a high level of control over the DOM. They were often built with another framework or toolset (both of these examples build their JavaScript on top of jQuery).

These tools provide extensive functionality and can be challenging to replace with a different tool without extensive modifications, so a solution for embedding them within Vue can be key to migrating a large application.

How To Use In Vue

Non-DOM Libraries

Integrating a library that doesn’t touch the DOM into a Vue.js project is relatively trivial. If you’re using JavaScript modules, simply importor require the module as you would in another project. For example:

import moment from 'moment';

Vue.component('my-component', {
  //…
  methods: {
    formatWithMoment(time, formatString) {
      return moment(time).format(formatString);
    },
});

If using global JavaScript, include the script for the library before your Vue project:

One additional common way to layer on a bit more integration is to wrap up your library or functions from the library using a filter or method to make it easy to access from inside your templates.

Vue Filters

Vue Filters are a pattern that allows you to apply text formatting directly inline in a template. Drawing an example from the documentation, you could create a ‘capitalize’ filter and then apply it in your template as follows:

{{myString | capitalize}}

When importing libraries having to do with formatting, you may want to wrap them up as a filter for ease of use. For example, if we are using moment to format all or many of our dates to relative time, we might create a relativeTime filter.

const relativeTime = function(value) {
  if (!value) return '';
  return moment(value).fromNow();
}

We can then add it globally to all Vue instances and components with the Vue.filter method:

Vue.filter(’relativeTime', relativeTime);

Or add it to a particular component using the filters option:

const myComponent = {
  filters: {
    ’relativeTime': relativeTime,
  } 
}

You can play with this on CodePen here:

See the Pen Vue integrations: Moment Relative Value Filter by Kevin Ball.

Element Augmentation Libraries

Element augmentation libraries are slightly more complex to integrate than libraries that don’t touch the DOM — if you’re not careful, Vue and the library can end up at cross purposes, fighting each other for control.

To avoid this, you need to hook the library into Vue’s lifecycle, so it runs after Vue is done manipulating the DOM element, and properly handles updates that Vue instigates.

This could be done in a component, but since these libraries typically touch only a single element at a time, a more flexible approach is to wrap them in a custom directive.

Vue Directives

Vue directives are modifiers that can be used to add behavior to elements in your page. Vue ships with a number of built-in directives that you are likely already comfortable with — things like v-on, v-model, and v-bind. It is also possible to create custom directives that add any sort of behavior to an element — exactly what we’re trying to achieve.

Defining a custom directive is much like defining a component; you create an object with a set of methods corresponding to particular lifecycle hooks, and then add it to Vue either globally by running:

Vue.directive('custom-directive', customDirective);

Or locally in a component by adding it to the directives object in the component:

const myComponent = {
  directives: {
    'custom-directive': customDirective,
  } 
}
Vue Directive Hooks

Vue directives have the following hooks available to define behavior. While you can use all of them in a single directive, it is also not uncommon to only need one or two. They are all optional, so use only what you need.

  • bind(el, binding, vnode)
    Called once and only once, when the directive is first bound to an element. This is a good place for one-time setup work, but be cautious, i.e. the element exists, may not yet actually be in the document.
  • inserted(el, binding, vnode)
    Called when the bound element has been inserted into its parent node. This also does not guarantee presence in the document, but does mean if you need to reference the parent you can.
  • update(el, binding, vnode, oldVnode)
    Called whenever the containing component’s VNode has updated. There are no guarantees that other children of the component will have updated, and the value for the directive may or may not have changed. (You can compare binding.value to binding.oldValue to see and optimize away any unnecessary updates.)
  • componentUpdated(el, binding, vnode, oldVnode)
    Similar to update, but called after all children of the containing component have updated. If the behavior of your directive depends on its peers (e.g. v-else), you would use this hook instead of update.
  • unbind(el, binding, vnode)
    Similar to bind, this is called once and only once, when the directive is unbound from an element. This is a good location for any teardown code.

The arguments to these functions are:

  • el: The element the directive is bound to;
  • binding: An object containing information about the arguments and value of the directive;
  • vnode: The virtual node for this element produced by Vue’s compiler;
  • oldVNode: The previous virtual node, only passed to update and componentUpdated.

More information on these can be found in the Vue Guide on custom directives.

Wrapping The Lozad Library In A Custom Directive

Let’s look at an example of doing this type of wrapping using lozad, a lazy-loading library built using the Intersection Observer API. The API for using lozad is simple: use data-src instead of src on images, and then pass a selector or an element to lozad() and call observe on the object that is returned:

const el = document.querySelector('img');
const observer = lozad(el); 
observer.observe();

We can do this simply inside of a directive using the bind hook.

const lozadDirective = {
  bind(el, binding) {
    el.setAttribute('data-src', binding.value) ;
    let observer = lozad(el);
    observer.observe();
  }
}
Vue.directive('lozad', lozadDirective)

With this in place, we can change images to lazy load by simply passing the source as a string into the v-lozad directive:

<img v-lozad="'https://placekitten.com/100/100'" />

You can observe this at work in this CodePen:

See the Pen Vue integrations: Lozad Directive Just Bind by Kevin Ball).

We’re not quite done yet though! While this works for an initial load, what happens if the value of the source is dynamic, and Vue changes it? This can be triggered in the pen by clicking the “Swap Sources” button. If we only implement bind, the values for data-src and src are not changed when we want them to be!

To implement this, we need to add an updated hook:

const lozadDirective = {
  bind(el, binding) {
    el.setAttribute('data-src', binding.value) ;
    let observer = lozad(el);
    observer.observe();
  },
  update(el, binding) {
    if (binding.oldValue !== binding.value) {
      el.setAttribute('data-src', binding.value);
      if (el.getAttribute('data-loaded') === 'true') {
        el.setAttribute('src', binding.value);
      }
    }
  }
}

With this in place, we’re set! Our directive now updates everything lozad touches whenever Vue updates. The final version can be found in this pen:

See the Pen Vue integrations: Lozad Directive With Updates by Kevin Ball.

Components And Component Libraries

The most complex third-party JavaScript to integrate is that which controls entire regions of the DOM, full-on components and component libraries. These tools expect to be able to create and destroy elements, manipulate them, and more.

For these, the best way to pull them into Vue is to wrap them in a dedicated component, and make extensive use of Vue’s lifecycle hooks to manage initialization, passing data in, and handling events and callbacks.

Our goal is to completely abstract away the details of the third-party library, so that the rest of our Vue code can interact with our wrapping component like a native Vue component.

Component Lifecycle Hooks

To wrap around a more complex component, we’ll need to be familiar with the full complement of lifecycle hooks available to us in a component. Those hooks are:

  • beforeCreate()
    Called before the component is instantiated. Pretty rarely used, but useful if we’re integrating profiling or something similar.
  • created()
    Called after the component is instantiated, but before it is added to the DOM. Useful if we have any one-off setup that doesn’t require the DOM.
  • beforeMount()
    Called just before the component is mounted in the DOM. (Also pretty rarely used.)
  • mounted()
    Called once the component is placed into the DOM. For components and component libraries that assume DOM presence, this is one of our most commonly used hooks.
  • beforeUpdate()
    Called when Vue is about to update the rendered template. Pretty rarely used, but again useful if integrating profiling.
  • updated()
    Called when Vue has finished updating the template. Useful for any re-instantiation that is needed.
  • beforeDestroy()
    Called before Vue tears down a component. A perfect location to call any destruction or deallocation methods on our third-party component
  • destroyed()
    Called after Vue has torn down a component.
Wrapping A Component, One Hook At A Time

Let’s take a look at the popular jquery-multiselect library. There exist many fine multiselect components already written in Vue, but this example gives us a nice combination: complicated enough to be interesting, simple enough to be easy to understand.

The first place to start when implementing a third-party component wrapper is with the mounted hook. Since the third-party component likely expects the DOM to exist before it takes charge of it, this is where you will hook in to initialize it.

For example, to start wrapping jquery-multiselect, we could write:

mounted() { 
  $(this.$el).multiselect();
}

You can see this functioning in this CodePen:

This is looking pretty good for a start. If there were any teardown we needed to do, we could also add a beforeDestroy hook, but this library does not have any teardown methods that we need to invoke.

Translating Callbacks To Events

The next thing we want to do with this library is add the ability to notify our Vue application when the user selects items. The jquery-multiselect library enables this via callbacks called afterSelect and afterDeselect, but to make this more vue-like, we’ll have those callbacks emit events. We could wrap those callbacks naively as follows:

mounted() { 
  $(this.$el).multiSelect({
     afterSelect: (values) => this.$emit('select', values),
     afterDeselect: (values) => this.$emit('deselect', values)
   });
}

However, if we insert a logger in the event listeners, we’ll see that this does not provide us a very vue-like interface. After each select or deselect, we receive a list of the values that have changed, but to be more vue-like, we should probably emit a change event with the current list.

We also don’t have a very vue-like way to set values. Instead of this naive approach then, we should look at using these tools to implement something like the v-model approach that Vue provides for native select elements.

Implementing v-model

To implement v-model on a component, we need to enable two things: accepting a value prop that will accept an array and set the appropriate options as selected, and then emit an input event on change that passes the new complete array.

There are four pieces to handle here: initial setup for a particular value, propagate any changes made up to the parent, and handle any changes to value starting outside the component, and finally handle any changes to the content in the slot (the options list).

Let’s approach them one at a time.

  1. Setup With A Value Prop
    First, we need to teach our component to accept a value prop, and then when we instantiate the multiselect we will tell it which values to select.
    export default {
      props: {
        value: Array,
        default: [],
      },
      mounted() { 
        $(this.$el).multiSelect();
        $(this.$el).multiSelect('select', this.value);
      },
    }
    
  2. Handle Internal Changes
    To handle changes occurring due to the user interacting with the multiselect, we can go back to the callbacks we explored before — but ‘less naively’ this time. Instead of simply emitting what they send us, we want to turn a new array that takes into account our original value and the change made.
    mounted() { 
      $(this.$el).multiSelect({
        afterSelect: (values) => this.$emit('input', [...new Set(this.value.concat(values))]),
        afterDeselect: (values) => this.$emit('input', this.value.filter(x => !values.includes(x))),
      });
      $(this.$el).multiSelect('select', this.value);
    },
    

    Those callback functions might look a little dense, so let’s break them down a little.

    The afterSelect handler concatenates the newly selected value with our existing values, but then just to make sure there are no duplicates, it converts it to a Set (guarantees uniqueness) and then a destructuring to turn it back to an array.

    The afterDeselect handler simply filters out any deselected values from the current value list in order to emit a new list.

  3. Handling External Updates To Value
    The next thing we need to do is to update the selected values in the UI whenever the value prop changes. This involves translating from a declarative change to the props into an imperative change utilizing the functions available on multiselect. The simplest way to do this is to utilize a watcher on our value prop:
    watch:
      // don’t actually use this version. See why below
      value() {
        $(this.$el).multiselect('select', this.value);
      }
    }
    

    However, there’s a catch! Because triggering that select will actually result in our onSelect handler, and thus use updating values. If we do this naive watcher, we will end up in an infinite loop.

    Luckily,for us, Vue gives us the ability to see the old as well as the new values. We can compare them, and only trigger the select if the value has changed. Array comparisons can get tricky in JavaScript, but for this example, we’ll take advantage of the fact that our arrays are simple (not containing objects) and use JSON stringify to do the comparison. After taking into account that we need to also deselect any that options that have been removed, our final watcher looks like this:

    watch: {
        value(newValue, oldValue) {
          if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
            $(this.$el).multiSelect('deselect_all');
            $(this.$el).multiSelect('select', this.value);
          }
        }
      },
    
  4. Handling External Updates To Slot
    We have one last thing that we need to handle: our multiselect is currently utilizing option elements passed in via a slot. If that set of options changes, we need to tell the multiselect to refresh itself, otherwise the new options don’t show up. Luckily, we have both an easy API for this in multiselect (the ’refresh’ function and an obvious Vue hook to hook into) updated. Handling this last case is as simple as:
    updated() {
      $(this.$el).multiSelect(’refresh');
    },
    

    You can see a working version of this component wrapper in this CodePen:

    See the Pen Vue integrations: Multiselect Wrapper with v-model by Kevin Ball.

Drawbacks And Other Considerations

Now that we’ve looked at how straightforward it is to utilize third-party JavaScript within Vue, it’s worth discussing drawback of these approaches, and when it appropriate to use them.

Performance Implications

One of the primary drawbacks of utilizing third-party JavaScript that is not written for Vue within Vue is performance — particularly when pulling in components and component libraries or things built using entire additional frameworks. Using this approach can result in a lot of additional JavaScript that needs to be downloaded and parsed by the browser before the user can interact with our application.

For example, by using the multiselect component, we developed above means pulling in not only that component’s code, but all of jQuery as well. That can double the amount of framework related JavaScript our users will have download, just for this one component! Clearly finding a component built natively with Vue.js would be better.

Additionally, when there are large mismatches between the APIs used by third-party libraries and the declarative approach that Vue takes, you may find yourself implementing patterns that result in a lot of extra execution time. Also using the multiselect example, we had to refresh the component (requiring looking at a whole bunch of the DOM) every time a slot changed, while a Vue-native component could utilize Vue’s virtual DOM to be much more efficient in its updates.

When To Use

Utilizing third-party libraries can save you a ton of development time, and often means you’re able to use well-maintained and tested software that you don’t have the expertise to build. The primary drawback is performance, particularly when bringing in large frameworks like jQuery.

For libraries that don’t have those large dependencies, and particularly those that don’t heavily manipulate the DOM, there’s no real reason to favor Vue-specific libraries over more generic ones. Because Vue makes it so easy to pull in other JavaScript, you should go based on your feature and performance needs, simply picking the best tool for the job, without worrying about something Vue-specific.

For more extensive component frameworks, there are three primary cases in which you’d want to pull them in.

  1. Prototyping
    In this case, speed of iteration matters far more than user performance; use whatever gets the job done fastest.
  2. Migrating an existing site.
    If you’re migrating from an existing site to Vue, being able to wrap whatever framework you’re already using within Vue will give you a graceful migration path so you can gradually pull out the old code piece by piece, without having to do a big bang rewrite.
  3. When the functionality simply isn’t available yet in a Vue component.
    If you have a specific and challenging requirement you need to meet, for which a third-party library exists but there isn’t a Vue specific component, by all means consider wrapping the library that does exist.


When there are large mismatches between the APIs used by third-party libraries and the declarative approach that Vue takes, you may find yourself implementing patterns that result in a lot of extra execution time.

Examples In The Wild

The first two of these patterns are used all over the open-source ecosystem, so there are a number of different examples you can investigate. Since wrapping an entire complex component or component library tends to be more of a stopgap/migration solution, I haven’t found as many examples of that in the wild, but there are a couple out there, and I’ve used this approach for clients occasionally as requirements have dictated. Here is a quick example of each:

  1. Vue-moment wraps the moment.js library and creates a set of handy Vue filters;
  2. Awesome-mask wraps the vanilla-masker library and creates a directive for masked inputs;
  3. Vue2-foundation wraps up the ZURB Foundation component library inside of Vue components.

Conclusion

The popularity of Vue.js shows no signs of slowing down, with a huge amount of credit being due to the framework’s progressive approach. By enabling incremental adoption, Vue’s progressive nature means that individuals can start using it here and there, a bit at a time, without having to do massive rewrites.

As we’ve looked at here, that progressive nature extends in the other direction as well. Just as you can embed Vue bit by bit in another application, you can embed other libraries bit by bit inside of Vue.

Need some piece of functionality that hasn’t been ported to a Vue component yet? Pull it in, wrap it up, and you’re good to go.

Further Reading on SmashingMag:

Smashing Editorial
(rb, ra, il)

Source: Smashing Magazine, Sliding In And Out Of Vue.js

Collective #495

dreamt up by webguru in Uncategorized | Comments Off on Collective #495





C495_videoplayer

Onelineplayer

A free web video player without branding and quality loss that loads 2x faster than others while supporting HQ previews.

Check it out



C495_newsletter

Tech Productivity

Tech Productivity is a short weekly newsletter for tech professionals with productivity-related tools, articles, and other resources. By Louis Lazaris.

Check it out








C495_personalweb

personal-website

A repository that gives you the code you’ll need to kickstart a personal website that showcases your work as a software developer.

Check it out


C495_silo

Silo

A daring and refreshing layout and design. With dark mode option.

Check it out







Collective #495 was written by Pedro Botelho and published on Codrops.


Source: Codrops, Collective #495

When Is A Button Not A Button?

dreamt up by webguru in Uncategorized | Comments Off on When Is A Button Not A Button?

When Is A Button Not A Button?

When Is A Button Not A Button?

Vadim Makeev



Let’s say you have a part of an interface that the user clicks and something happens. Sounds like a button to me, but let’s call it a “clicky thing” for now. I know, you’re confident that it’s a button too: It’s rounded and stands out with a nice tomato color, asking to be interacted with. But let’s think about it for a moment. It’ll save time in the long run, I promise.


Tomato button-like thing with ‘Something’ text on it.
Design for your ‘clicky thing’ (Large preview)

What if the text in this clicky thing was “Read more”, and clicking it led the user to an article on another page? Hmm. And what if there was a blue underlined word, “Close”, that closes the popup dialog? Is it a link just because it’s blue and underlined? Of course not.


Button-like link and link-like button
The link or button dilemma (Large preview)

Whoa! It seems like there’s no way to tell if it’s a link or a button just by looking at it. That’s crazy! We need to understand what this thing does before choosing the right element. But what if we don’t know what it does just yet or are simply confused? Well, there’s a handy flow chart for us:


Flow chart: It’s a button. If not, then it’s a link. That’s it.
A scientific flow chart for choosing the right element (Large preview)
  1. It’s a button.
  2. If not, then it’s a link.
  3. That’s it.

So, is everything a button? No, but you can always start with a button for almost any element that can be clicked or interacted with in a similar way. And if it’s lacking something, like navigation to another page, use a link instead. And no, a pointer is not a reason to make it <a href>. We have cursor: pointer for that.


Focused tomato button with ‘Something’ text on it
Don’t forget to provide focus styles. (Large preview)

All right, it’s a <button> button — we agree on that. Let’s put it in our template and style it according to the design: some padding, rounding, a tomato fill, white text, and even some focus styles. Oh, that’s so nice of you.

<button type="button" class="button">
    Something
</button>
<style>
    .button {
        display: inline-block;
        padding: 10px 20px;
        border-radius: 20px;
        background-color: tomato;
        color: white;
    }

    .button:focus {
        outline: none;
        box-shadow: 0 0 0 5px #006AE3;
    }
</style>

That didn’t take long. You wanted to build it quickly and grab some lunch because you’re hungry. Ok, let’s see how it looks and get going.


Ugly-looking tomato button, rendered in a browser
Sometimes the browser is not your best friend. (Large preview)

Oh my god! Something is wrong with the browser. Why is this button so ugly? The text is tiny, even though we have explicitly set the body to 16px, and even the font-family is wrong. The rounded border with a silly pseudo-shadow is so retro that it’s not even a trend yet.

Ahh, it’s the browser’s default styling. You need to carefully undo it or even add Normalize.css or Reset.css… or you could just use a

and forget about it. Isn’t solving problems quickly what they pay you for? You’re hungry and this isn’t helping at all. But you’re a professional: Pull yourself together and think.

What’s the difference between a

Source: Smashing Magazine, When Is A Button Not A Button?

Improving WordPress Code With Modern PHP

dreamt up by webguru in Uncategorized | Comments Off on Improving WordPress Code With Modern PHP

Improving WordPress Code With Modern PHP

Improving WordPress Code With Modern PHP

Leonardo Losoviz



WordPress was born fifteen years ago, and because it has historically preserved backwards compatibility, newer versions of its code couldn’t make full use of the latest capabilities offered by the newer versions of PHP. While the latest version of PHP is 7.3.2, WordPress still offers support up to PHP 5.2.4.

But those days will soon be over! WordPress will be upgrading its minimum PHP version support, bumping up to PHP 5.6 in April 2019, and PHP 7 in December 2019 (if everything goes according to plan). We can then finally start using PHP’s imperative programming capabilities without fear of breaking our clients’ sites. Hurray!

Because WordPress’ fifteen years of functional code have influenced how developers have built with WordPress, our sites, themes and plugins may be littered with less-than-optimal code that can gladly receive an upgrade.

This article is composed of two parts:

  1. Most relevant new features
    Further features have been added to PHP versions 5.3, 5.4, 5.5, 5.6 and 7.0 (notice that there is no PHP 6) and we’ll explore the most relevant ones.
  2. Building better software
    We’ll take a closer look through these features and how they are able to help us build better software.

Let’s start by exploring PHP’s “new” features.

Classes, OOP, SOLID And Design Patterns

Classes and objects were added to PHP 5, so WordPress already makes use of these features, however, not very extensively or comprehensively: The paradigm of coding in WordPress is mostly functional programming (performing computations by calling functions devoid of application state) instead of object-oriented programming (OOP) (performing computations by manipulating objects’ state). Hence I also describe classes and objects and how to use them through OOP.

OOP is ideal for producing modular applications: Classes allow the creation of components, each of which can implement a specific functionality and interact with other components, and can provide customization through its encapsulated properties and inheritance, enabling a high degree of code reusability. As a consequence, the application is cheaper to test and maintain, since individual features can be isolated from the application and dealt with on their own; there is also a boost of productivity since the developer can use already-developed components and avoid reinventing the wheel for each application.

A class has properties and functions, which can be given visibility by usingprivate (accessible only from within the defining class), protected (accessible from within the defining class and its ancestor and inheriting classes) and public (accessible from everywhere). From within a function, we can access the class’ properties by prepending their names with $this->:

class Person {

  protected $name;
  
  public function __construct($name) {
    $this->name = $name;
  }

  public function getIntroduction() {
    return sprintf(
      __('My name is %s'),
      $this->name
    );
  }
}

A class is instantiated into an object through the new keyword, after which we can access its properties and functions through ->:

$person = new Person('Pedro');
echo $person->getIntroduction(); 
// This prints "My name is Pedro"

An inheriting class can override the public and protected functions from its ancestor classes, and access the ancestor functions by prepending them with parent:::

class WorkerPerson extends Person {

  protected $occupation;
  
  public function __construct($name, $occupation) {

    parent::__construct($name);
    $this->occupation = $occupation;
  }

  public function getIntroduction() {
    return sprintf(
      __('%s and my occupation is %s'),
      parent::getIntroduction(),
      $this->occupation
    );
  }
}

$worker = new WorkerPerson('Pedro', 'web development');
echo $worker->getIntroduction();
// This prints "My name is Pedro and my occupation is web development"

A method can be made abstract, meaning that it must be implemented by an inheriting class. A class containing an abstract method must be made abstract itself, meaning that it cannot instantiated; only the class implementing the abstract method can be instantiated:

abstract class Person {
  
  abstract public function getName();

  public function getIntroduction() {
    return sprintf(
      __('My name is %s'),
      $this->getName()
    );
  }
}
// Person cannot be instantiated

class Manuel extends Person {
  
  public function getName() {
    return 'Manuel';
  }
}

// Manuel can be instantiated
$manuel = new Manuel();

Classes can also define static methods and properties, which live under the class itself and not under an instantiation of the class as an object. These are accessed through self:: from within the class, and through the name of the class + :: from outside it:

class Factory {

  protected static $instances = [];
  public static function registerInstance($handle, $instance) {
    self::$instances[$handle] = $instance;
  }
  public static function getInstance($handle) {
    return self::$instances[$handle];
  }
}

$engine = Factory::getInstance('Engine');

To make the most out of OOP, we can use the SOLID principles to establish a sound yet easily customizable foundation for the application, and design patterns to solve specific problems in a tried-and-tested way. Design patterns are standardized and well documented, enabling developers to understand how different components in the application relate to each other, and provide a way to structure the application in an orderly fashion which helps avoid the use of global variables (such as global $wpdb) that pollute the global environment.

Namespaces

Namespaces were added to PHP 5.3, hence they are currently missing altogether from the WordPress core.

Namespaces allow organizing the codebase structurally to avoid conflicts when different items have the same name — in a fashion similar to operating system directories which allow to have different files with the same name as long as they are stored in different directories. Namespaces do the same encapsulation trick for PHP items (such as classes, traits, and interfaces) avoiding collisions when different items have the same name by placing them on different namespaces.

Namespaces are a must when interacting with third-party libraries since we can’t control how their items will be named, leading to potential collisions when using standard names such as “File”, “Logger” or “Uploader” for our items. Moreover, even within a single project, namespaces prevent class names from becoming extremely long as to avoid clashes with other classes, which could result in names such as “MyProject_Controller_FileUpload”.

Namespaces are defined using the keyword namespace (placed on the line immediately after the opening <?php) and can span several levels or subnamespaces (similar to having several subdirectories where placing a file), which are separated using a :

<?php
namespace CoolSoftImageResizerControllers;

class ImageUpload {

}

To access the above class, we need to fully qualify its name including its namespace (and starting with ):

$imageUpload = new CoolSoftImageResizerControllersImageUpload();

Or we can also import the class into the current context, after which we can reference the class by its name directly:

use CoolSoftImageResizerControllersImageUpload;
$imageUpload = new ImageUpload();

By naming namespaces following established conventions, we can get additional benefits. For instance, by following the PHP Standards Recommendation PSR-4, the application can use Composer’s autoloading mechanism for loading files, thus decreasing complexity and adding frictionless interoperability among dependencies. This convention establishes to include the vendor name (e.g. the company’s name) as the top subnamespace, optionally followed by the package name, and only then followed by an internal structure in which each subnamespace corresponds to a directory with the same name. The result maps 1 to 1 the physical location of the file in the drive with the namespace of the element defined in the file.

Traits

Traits were added to PHP 5.4, hence they are currently missing altogether from the WordPress core.

PHP supports single inheritance, so a subclass is derived from a single parent class, and not from multiple ones. Hence, classes that do not extend from one another can’t reuse code through class inheritance. Traits is a mechanism that enables horizontal composition of behavior, making it possible to reuse code among classes which live in different class hierarchies.

A trait is similar to a class, however, it can’t be instantiated on its own. Instead, the code defined inside a trait can be thought of as being “copied and pasted” into the composing class on compilation time.

A trait is defined using the trait keyword, after which it can be imported to any class through the use keyword. In the example below, two completely unrelated classes Person and Shop can reuse the same code through a trait Addressable:

trait Addressable {

  protected $address;
  
  public function getAddress() {
    return $this->address;
  }
  
  public function setAddress($address) {
    $this->address = $address;
  }
}

class Person {

  use Addressable;
}

class Shop {

  use Addressable;
}

$person = new Person('Juan Carlos');
$person->setAddress('Obelisco, Buenos Aires');

A class can also compose more than one trait:

trait Exportable {
  
  public class exportToCSV($filename) {
    // Iterate all properties and export them to a CSV file
  }
}

class Person {

  use Addressable, Exportable;
}

Traits can also be composed of other traits, define abstract methods, and offer a conflict resolution mechanism when two or more composed traits have the same function name, among other features.

Interfaces

Interfaces were added to PHP 5, so WordPress already makes use of this feature, however, extremely sparingly: the core includes less than ten interfaces in total!

Interfaces allow creating code which specifies which methods must be implemented, yet without having to define how these methods are actually implemented. They are useful for defining contracts among components, which leads to better modularity and maintainability of the application: A class implementing an interface can be a black box of code, and as long as the signatures of the functions in the interface do not change, the code can be upgraded at will without producing breaking changes, which can help prevent the accumulation of technical debt. In addition, they can help reduce vendor lock-in, by allowing to swap the implementation of some interface to that of a different vendor. As a consequence, it is imperative to code the application against interfaces instead of implementations (and defining which are the actual implementations through dependency injection).

Interfaces are defined using the interface keyword, and must list down just the signature of its methods (i.e. without having their contents defined), which must have visibility public (by default, adding no visibility keyword also makes it public):

interface FileStorage {

  function save($filename, $contents);
  function readContents($filename);
}

A class defines that it implements the interface through the implements keyword:

class LocalDriveFileStorage implements FileStorage {

  function save($filename, $contents) {
    // Implement logic
  }
  function readContents($filename) {
    // Implement logic
  }
}

A class can implement more than one interface, separating them with ,:

interface AWSService {
  function getRegion();
}

class S3FileStorage implements FileStorage, AWSService {

  function save($filename, $contents) {
    // Implement logic
  }
  function readContents($filename) {
    // Implement logic
  }
  function getRegion() {
    return 'us-east-1';
  }
}

Since an interface declares the intent of what a component is supposed to do, it is extremely important to name interfaces appropriately.

Closures

Closures were added to PHP 5.3, hence they are currently missing altogether from the WordPress core.

Closures is a mechanism for implementing anonymous functions, which helps declutter the global namespace from single-use (or seldom-used) functions. Technically speaking, closures are instances of class Closure, however, in practice, we can most likely be blissfully unaware of this fact without any harm.

Before closures, whenever passing a function as an argument to another function, we had to define the function in advance and pass its name as the argument:

function duplicate($price) {
  return $price*2;
}
$touristPrices = array_map('duplicate', $localPrices);

With closures, an anonymous (i.e. without a name) function can already be passed directly as a parameter:

$touristPrices = array_map(function($price) {
  return $price*2;
}, $localPrices);

Closures can import variables to its context through the use keyword:

$factor = 2;
$touristPrices = array_map(function($price) use($factor) {
  return $price*$factor;
}, $localPrices);

Generators

Generators were added to PHP 5.5, hence they are currently missing altogether from the WordPress core.

Generators provide an easy way to implement simple iterators. A generator allows to write code that uses foreach to iterate over a set of data without needing to build an array in memory. A generator function is the same as a normal function, except that instead of returning once, it can yield as many times as it needs to in order to provide the values to be iterated over.

function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
}
foreach (xrange(1, 9, 2) as $number) {
    echo "$number ";
}
// This prints: 1 3 5 7 9 

Argument And Return Type Declarations

Different argument type declarations were introduced in different versions of PHP: WordPress is already able to declare interfaces and arrays (which it does not: I barely found one instance of a function declaring an array as parameter in core, and no interfaces), and will soon be able to declare callables (added in PHP 5.4) and scalar types: bool, float, int and string (added in PHP 7.0). Return type declarations were added to PHP 7.0.

Argument type declarations allow functions to declare of what specific type must an argument be. The validation is executed at call time, throwing an exception if the type of the argument is not the declared one. Return type declarations are the same concept, however, they specify the type of value that will be returned from the function. Type declarations are useful to make the intent of the function easier to understand and to avoid runtime errors from receiving or returning an unexpected type.

The argument type is declared before the argument variable name, and the return type is declared after the arguments, preceded by ::

function foo(boolean $bar): int {

}

Scalar argument type declarations have two options: coercive and strict. In coercive mode, if the wrong type is passed as a parameter, it will be converted to the right type. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string. In strict mode, only a variable of the exact type of declaration will be accepted.

Coercive mode is the default. To enable strict mode, we must add a declare statement used with the strict_types declaration:

declare(strict_types=1);
function foo(boolean $bar) {

}

New Syntax And Operators

WordPress can already identify variable-length argument lists through function func_num_args. Starting from PHP 5.6, we can use the ... token to denote that the function accepts a variable number of arguments, and these arguments will be passed into the given variable as an array:

function sum(...$numbers) {
  $sum = 0;
  foreach ($numbers as $number) {
    $sum += $number;
  }
  return $sum;
}

Starting from PHP 5.6, constants can involve scalar expressions involving numeric and string literals instead of just static values, and also arrays:

const SUM = 37 + 2; // A scalar expression
const LETTERS = ['a', 'b', 'c']; // An array

Starting from PHP 7.0, arrays can also be defined using define:

define('LETTERS', ['a', 'b', 'c']);

PHP 7.0 added a couple of new operators: the Null coalescing operator (??) and the Spaceship operator (<=>).

The Null coalescing operator ?? is syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise, it returns its second operand.

$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
// $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

The Spaceship operator <=> is used for comparing two expressions, returning -1, 0 or 1 when the first operand is respectively less than, equal to, or greater than the second operand.

echo 1  2; // returns -1
echo 1  1; // returns 0
echo 2  1; // returns 1

These are the most important new features added to PHP spanning versions 5.3 to 7.0. The list of the additional new features, not listed in this article, can be obtained by browsing PHP’s documentation on migrating from version to version.

Next, we analyze how we can make the most out of all these new features, and from recent trends in web development, to produce better software.

PHP Standards Recommendations

The PHP Standards Recommendations was created by a group of PHP developers from popular frameworks and libraries, attempting to establish conventions so that different projects can be integrated more seamlessly and different teams can work better with each other. The recommendations are not static: existing recommendations may be deprecated and newer ones created to take their place, and new ones are released on an ongoing basis.

The current recommendations are the following:

Group Recommendation Description
Coding Styles
Standardized formatting reduces the cognitive friction when reading code from other authors
PSR-1 Basic Coding Standard
PSR-2 Coding Style Guide
Autoloading
Autoloaders remove the complexity of including files by mapping namespaces to file system paths
PSR-4 Improved Autoloading
Interfaces
Interfaces simplify the sharing of code between projects by following expected contracts
PSR-3 Logger Interface
PSR-6 Caching Interface
PSR-11 Container Interface
PSR-13 Hypermedia Links
PSR-16 Simple Cache
HTTP
Interoperable standards and interfaces to have an agnostic approach to handling HTTP requests and responses, both on client and server side
PSR-7 HTTP Message Interfaces
PSR-15 HTTP Handlers
PSR-17 HTTP Factories
PSR-18 HTTP Client

Think And Code In Components

Components make it possible to use the best features from a framework without being locked-in to the framework itself. For instance, Symfony has been released as a set of reusable PHP components that can be installed independently of the Symfony framework; Laravel, another PHP framework, makes use of several Symfony components, and released its own set of reusable components that can be used by any PHP project.

All of these components are published in Packagist, a repository of public PHP packages, and can be easily added to any PHP project through Composer, an extremely popular dependency manager for PHP.

WordPress should be part of such a virtuous development cycle. Unfortunately, the WordPress core itself is not built using components (as evidenced by the almost total absence of interfaces) and, moreover, it doesn’t even have the composer.json file required to enable installing WordPress through Composer. This is because the WordPress community hasn’t agreed whether WordPress is a site’s dependency (in which case installing it through Composer would be justified) or if it is the site itself (in which case Composer may not be the right tool for the job).

In my opinion, if we are to expect WordPress to stay relevant for the next fifteen years (at least WordPress as a backend CMS), then WordPress must be recognized as a site’s dependency and made available for installation through Composer. The reason is very simple: with barely a single command in the terminal, Composer enables to declare and install a project’s dependencies from the thousands of packages published in Packagist, making it possible to create extremely-powerful PHP applications in no time, and developers love working this way. If WordPress doesn’t adapt to this model, it may lose the support from the development community and fall into oblivion, as much as FTP fell out of favor after the introduction of Git-based deployments.

I would argue that the release of Gutenberg already demonstrates that WordPress is a site dependency and not the site itself: Gutenberg treats WordPress as a headless CMS, and can operate with other backend systems too, as Drupal Gutenberg exemplifies. Hence, Gutenberg makes it clear that the CMS powering a site can be swappable, hence it should be treated as a dependency. Moreover, Gutenberg itself is intended to be based on JavaScript components released through npm (as explained by core committer Adam Silverstein), so if the WordPress client is expected to manage its JavaScript packages through the npm package manager, then why not extend this logic to the backend in order to manage PHP dependencies through Composer?

Now the good news: There is no need to wait for this issue to be resolved since it is already possible to treat WordPress as a site’s dependency and install it through Composer. John P. Bloch has mirrored WordPress core in Git, added a composer.json file, and released it in Packagist, and Roots’ Bedrock provides a package to install WordPress with a customized folder structure with support for modern development tools and an enhanced security. And themes and plugins are covered too; as long as they have been listed on the WordPress theme and plugin directories, they are available under WordPress Packagist.

As a consequence, it is a sensible option to create WordPress code not thinking in terms of themes and plugins, but thinking in terms of components, making them available through Packagist to be used by any PHP project, and additionally packaged and released as themes and plugins for the specific use of WordPress. If the component needs to interact with WordPress APIs, then these APIs can be abstracted behind an interface which, if the need arises, can be implemented for other CMSs too.

Adding A Template Engine To Improve The View Layer

If we follow through the recommendation of thinking and coding in components, and treat WordPress as a site’s dependency other than the site itself, then our projects can break free from the boundaries imposed by WordPress and import ideas and tools taken from other frameworks.

Rendering HTML content on the server-side is a case in point, which is done through plain PHP templates. This view layer can be enhanced through template engines Twig (by Symfony) and Blade (by Laravel), which provide a very concise syntax and powerful features that give it an advantage over plain PHP templates. In particular, Gutenberg’s dynamic blocks can easily benefit from these template engines, since their process to render the block’s HTML on the server-side is decoupled from WordPress’ template hierarchy architecture.

Architect The Application For The General Use

Coding against interfaces, and thinking in terms of components, allows us to architect an application for general use and customize it for the specific use that we need to deliver, instead of coding just for the specific use for each project we have. Even though this approach is more costly in the short term (it involves extra work), it pays off in the long term when additional projects can be delivered with lower efforts from just customizing a general-use application.

For this approach to be effective, the following considerations must be taken into account:

Avoid Fixed Dependencies (As Much As Possible)

jQuery and Bootstrap (or Foundation, or <–insert your favorite library here–>) could’ve been considered must-haves a few years ago, however, they have been steadily losing ground against vanilla JS and newer native CSS features. Hence, a general-use project coded five years ago which depended on these libraries may not be suitable nowadays anymore. Hence, as a general rule of thumb, the lower the amount of fixed dependencies on third-party libraries, the more up-to-date it will prove to be for the long term.

Progressive Enhancement Of Functionalities

WordPress is a full-blown CMS system which includes user management, hence support for user management is included out of the box. However, not every WordPress site requires user management. Hence, our application should take this into account, and work optimally on each scenario: support user management whenever required, but do not load the corresponding assets whenever it is not. This approach can also work gradually: Say that a client requires to implement a Contact us form but has no budget, so we code it using a free plugin with limited features, and another client has the budget to buy the license from a commercial plugin offering better features. Then, we can code our functionality to default to a very basic functionality, and increasingly use the features from whichever is the most-capable plugin available in the system.

Continuous Code And Documentation Review

By periodically reviewing our previously-written code and its documentation, we can validate if it is either up-to-date concerning new conventions and technologies and, if it is not, take measures to upgrade it before the technical debt becomes too expensive to overcome and we need to code it all over again from scratch.

Recommended reading: Be Watchful: PHP And WordPress Functions That Can Make Your Site Insecure

Attempt To Minimize Problems But Be Prepared When They Happen

No software is ever 100% perfect: the bugs are always there, we just haven’t found them yet. As such, we need to make sure that, once the problems arise, they are easy to fix.

Make It Simple

Complex software cannot be maintained in the long term: Not just because other team members may not understand it, but also because the person who coded it may not understand his/her own complex code a few years down the road. So producing simple software must be a priority, more since only simple software can be correct and fast.

Failing On Compile Time Is Better Than On Runtime

If a piece of code can be validated against errors at either compile time or runtime time, then we should prioritize the compile time solution, so the error can arise and be dealt with in the development stage and before the application reaches production. For instance, both const and define are used for defining constants, however, whereas const is validated at compile time, define is validated at runtime. So, whenever possible, using const is preferable over define.

Following this recommendation, hooking WordPress functions contained in classes can be enhanced by passing the actual class as a parameter instead of a string with the class name. In the example below, if class Foo is renamed, whereas the second hook will produce a compilation error, the first hook will fail on runtime, hence the second hook is better:

class Foo {
  public static function bar()

  }
}

add_action('init', ['Foo', 'bar']); // Not so good
add_action('init', [Foo::class, 'bar']); // Much better

For the same reason as above, we should avoid using global variables (such as global $wpdb): these not only pollute the global context and are not easy to track where they originate from, but also, if they get renamed, the error will be produced on runtime. As a solution, we can use a Dependency Injection Container to obtain an instance of the required object.

Dealing With Errors/Exceptions

We can create an architecture of Exception objects, so that the application can react appropriately according to each particular problem, to either recover from it whenever possible or show a helpful error message to the user whenever not, and in general to log the error for the admin to fix the problem. And always protect your users from the white screen of death: All uncaught Errors and Exceptions can be intercepted through function set_exception_handler to print a non-scary error message on screen.

Adopt Build Tools

Build tools can save a lot of time by automating tasks which are very tedious to execute manually. WordPress doesn’t offer integration with any specific build tool, so the task of incorporating these to the project will fall entirely on the developer.

There are different tools for accomplishing different purposes. For instance, there are build tools to execute tasks for compressing and resizing images, minifying JS and CSS files, and copying files to a directory for producing a release, such as Webpack, Grunt and Gulp; other tools help create the scaffolding of a project, which is helpful for producing the folder structure for our themes or plugins, such as Yeoman. Indeed, with so many tools around, browsing articles comparing the different available tools will help find the most suitable one for our needs.

In some cases, though, there are no build tools that can achieve exactly what our project needs, so we may need to code our own build tool as an extension to the project itself. For instance, I have done this to generate the service-worker.js file to add support for Service Workers in WordPress.

Conclusion

Due to its strong emphasis on keeping backwards compatibility, extended even up to PHP 5.2.4, WordPress has not been able to benefit from the latest features added to PHP, and this fact has made WordPress become a not-very-exciting platform to code for among many developers.

Fortunately, these gloomy days may soon be over, and WordPress may become a shiny and exciting platform to code for once again: The requirement of PHP 7.0+ starting in December 2019 will make plenty of PHP features available, enabling developers to produce more powerful and more performant software. In this article, we reviewed the most important newly-available PHP features and how to make the most out of them.

The recent release of Gutenberg could be a sign of the good times to come: even if Gutenberg itself has not been fully accepted by the community, at least it demonstrates a willingness to incorporate the latest technologies (such as React and Webpack) into the core. This turn of events makes me wonder: If the frontend can get such a makeover, why not extend it to the backend? Once WordPress requires at least PHP 7.0, the upgrade to modern tools and methodologies can accelerate: As much as npm became the JavaScript package manager of choice, why not making Composer become the official PHP dependency manager? If blocks are the new unit for building sites in the frontend, why not use PHP components as the unit for incorporating functionalities into the backend? And finally, if Gutenberg treats WordPress as a swappable backend CMS, why not already recognize that WordPress is a site dependency and not the site itself? I’ll leave these open questions for you to reflect upon and ponder about.

Smashing Editorial
(rb, ra, il)

Source: Smashing Magazine, Improving WordPress Code With Modern PHP

Collective #494

dreamt up by webguru in Uncategorized | Comments Off on Collective #494







C494_svgicon

Iconsvg

A tool to simplify the process of finding and generating common SVG icons for your project.

Check it out




C494_amino

Amino

A live CSS editor for writing user style sheets. Customize your favorite sites, save and sync your styles.

Check it out










Screen-Shot-2019-02-21-at-16.09.50

An in-depth journey into how Node works. By Jamie Corkhill.

Read it






Collective #494 was written by Pedro Botelho and published on Codrops.


Source: Codrops, Collective #494

Including Animation In Your Design System

dreamt up by webguru in Uncategorized | Comments Off on Including Animation In Your Design System

Including Animation In Your Design System

Including Animation In Your Design System

Val Head



(This article is sponsored by Adobe.) Design systems come in all shapes and sizes, but as Sparkbox’s design system survey noted, not all of them include guidelines for animation. Sure, some teams may have decided that motion wasn’t something their product needed guidance on, but I suspect that in some cases motion was left out because they weren’t sure what to include.

In the past few years, I’ve talked with many teams and designers who admit they think motion is something they should address, but they just aren’t sure how. If you’re in that boat, you’re in luck. This article is all about what to include in a set of motion guidelines for your design system and how to pull it off.

Why Animation?

Animation is an important design tool for both UX and brand messaging. Just like typography and color, the animation you use says something about your product and its personality. So, when it’s not addressed in a design system, that system essentially leaves that area of UI design tooling unaccounted for. Then people following the design system either do whatever they want with animation—which can lead to a strange mish-mash of animation execution across the experience—or, they just don’t use animation at all because they don’t have time to figure out all the details themselves. Neither case is ideal.

Having a clear stance on how animation is used (or not used) in your design system can help ensure your brand is using animation consistently and effectively while also helping your team work faster. Let’s dig in to get started on a set of motion guidelines for your design system.

The Groundwork: Defining What You Need To Cover

First, Talk To People

As Jina Anne says, “Design systems are for people.” I’ve often heard the advice that talking to the people who will be using the design system you’re creating is key to making a design system people will actually use. That holds true for the guidelines you create around animation too. The biggest thing you can gain from this is finding out what they need and what to focus on. This helps you set an appropriate scope for what you need to cover in your guidelines. No one wants to spend hours on extensive guidelines that address more than your team will ever actually need. That wouldn’t be any fun (or use).

Your team may not tell you about their animation pain points unprompted, but that doesn’t mean they don’t have any. Set up some user interviews (the users of your design system) and ask them about where they get stuck with animation. Ask them how/if they use animation, and where animation falls in their design process. Ask them about what they wish they had to help with the pain points they encounter. Most importantly, listen to how they talk about using animation in their work and what goes well or not so well.

While every team is different, the concerns and questions I’ve heard most often when doing this research are things like: “How do I know an animation is good, or fits with our brand?”, “How can I convey the animation details to our engineers effectively?”,or “Our developers always say there’s no time to implement the animations we design.”

You’ve probably guessed where I’m going with this, but all of those concerns are things you can help provide answers to in your motion guidelines. And you can use the questions and pain points that come up most often to guide and focus your motion guideline efforts.

Reference Other Systems

Not every design system has to be public, but it’s great that so many of them are. They make for a helpful resource when planning your design system, and they can be useful research for your design system’s motion guidelines too. (In fact, we’ll be referencing a few them in this very article.)

Using other motion sections as reference for your own design system is very helpful, but I don’t recommend adopting another brand’s motion guidelines wholesale in place of your own. No, not even if it’s Material Design’s motion guidelines.

Material Design’s motion section is Google’s take on motion guidelines. A good one, yes, but its aim is to show you how to animate the Google way. That’s perfect if you’re making something for the Google ecosystem (or intentionally wanting to seem like you are). But it’s not a good fit when that’s not your goal. You wouldn’t use another brand’s colors or typeface on your product, so don’t just follow another brand’s motion guidelines either.

The most effective design systems contain a branded point of view unique to them—things that make their design system more specific to the product they’re for—along with common design best practices. Spend a little time researching and reading through other systems’ motion guidelines, and you start to get a feel for which parts are best practices and which parts are customized to that brand or product’s point of view. Then you can decide which best practices you might also like to include in your guidelines, as well as where to customize the guidelines for your product.

For example, using ease-ins for exits and ease-outs for entrances is a common best practice for UI animation. But the exact ease-in or ease-out curve is usually customized to a brand’s intended message and personality.

To quote Dan Mall:

“This is the kind of thing a design system should have guidelines for: perspective, point of view, extending creative direction to everyone that decides to build something with the design system. That stuff should be baked in.”

I totally agree.

The Two Main Sections Of A Design System’s Motion Guidelines

There’s no specific rule out there stating that you must have these two sections, but I’ve found this breakdown to be an effective way to approach the motion guidelines I’ve worked on. And I’ve also noticed that most design systems out there that address motion have these two categories as well, so it seems to be an approach that works for others too.

The two main sections are: principles and implementation. Principles are typically high-level statements that explain how that brand uses motion. They’re the big picture point of view or design intention behind why the brand uses animation and their perspective on it. The implementation section focuses on how to carry out those principles practically in design and/or code. It serves as the building blocks of animation for the design system, and the amount of detail they cover varies based on brand needs.

Motion Principles

The principles section is where to state your brand values around animation. They’re the high-level principles to measure design decisions against, and a place to state some specific definitions or values around animation. Principles often tend to focus on the “why” of using animation within a particular design system and the UX-driven purpose they serve. In many cases, design systems list these under the heading of Principles in their motion section. However, you can see the concept of principles present in ones that don’t include a specific section for them as well.

Your motion principles can be modeled after existing global design principles that your brand might have, extrapolated from things like voice and tone guidelines, or even be inferred from looking at your product’s existing UI animations in a motion audit.

Let’s look at some examples to get a better idea of how these play out. Microsoft’s Fluent design system lists their motion principles as being physical, functional, continuous, and contextual. They include a short description and illustration of each to explain how it applies to UI animation.


Screenshot of the Fluent’s first motion principle
A segment of Fluent’s motion principles page (Large preview)

Audi doesn’t have a separate principles section, but they start off their animation section with a declaration of why they use animation, which is setting the stage for what sort of motion is to be used in the design system, just like a principle would. They state:

“We stand for dynamic premium mobility. As such, movements in the Audi look have a typically dynamic character.”

While developing the motion section for Spectrum, Adobe’s design system, we opted for a principles section to match the pattern used in other sections of the system. Within Spectrum, animation aims to be purposeful, intuitive, and seamless.

Note: Spectrum does not have a publicly available site at the time of writing.


Spectrum’s motion principles of purposeful, intuitive and seamless
Spectrum’s guiding motion principles for UI animation (Large preview)

No matter how you decide to present them, your design system’s animation principles can be used to both establish the system’s expectation around animation and to evaluate potential future UI animation for the product(s) the design system is applied to. For example, if a designer following the Fluent design system wanted to introduce a large bouncing animation into a component, there could be discussion around whether that meets the motion principles. (Does it fit the principles of functional and continuous?) Then a decision could be made as to whether or not that particular animation warranted breaking from the stated principles, or if the animation should be redesigned to fit the principles.

This helps to keep the design discussions away from the “do you like it?” or personal opinion realm and gives a structure for evaluating animation in a more pragmatic design-oriented way. That’s my favorite advantage of having declared motion principles; they make discussing animation meaningfully so much easier, even for people who don’t have a lot of animation experience.

Quick Tip: For more motion principles references, check out Photon’s motion principles, Material Design motion principles and Carbon’s motion principles. There are also others out there, but these are a good start.

Implementation

Motion principles are great for some high-level guidance, but without some details on exactly how to implement them, you’ll be missing the biggest time-saving benefits of including animation in your design system. The implementation section (though rarely actually titled as such) helps to answer many of the “how” and
“what” questions your team has around animation. The objective is to provide smart defaults for anyone following the design system. That way, instead of spending ages playing around with durations and easing for every animation, they can use the smart defaults you’ve provided in the guidelines and be on their way. It’s a huge timesaver that also makes your UI animation much more consistent across the board.

The implementation guidelines are where a lot of design systems diverge in their approach and coverage. The amount of detail you include and the topics you cover in these guidelines will depend on how big of a role animation plays in your design efforts and what your team needs. For example, Photon’s implementation section includes just one duration and one easing curve, while Material Design’s includes individual sections on duration and easing as well as additional pages full of implementation details.

There’s no perfect length for a motion section; it’s more about covering the details your team needs than hitting a specific number of pages or rules. Some of the animation building blocks to consider including in your motion guidelines are:

The first three in the list are the main ways we customize or style animation. Variations in the properties, durations, and easings used for animation can drastically affect how animations come across. (And the last one is a way of packing up the first three.)

Let’s dig into each in more detail, and for each of these I’ll point out some of the common best practices and where there’s room for your own customized interpretation.

Durations, Ranges, And Rhythm

Duration has to do with how long animations should be, and when we’re talking about UI animation, these values tend to be very short. It’s amazing how much information we can convey in fractions of a second! This is a key aspect of animation, so every design system with motion guidelines covers it, but they do it in a variety of ways.

Some of the best practices around duration that you’ll see addressed in most motion guidelines include:

  • Shorter durations should be used for simpler effects and animationsof relatively small-sized (such as fades or color changes);
  • Longer durations should be used for more complex effects andanimations of larger relative scale (such as page transitions or moving objects on and offscreen);
  • Optimal timing can change based on viewport size.
    While the specifics of each set of guidelines varies — sometimes even greatly — you’ll see these common best practices in almost all of them. Different systems have different definitions of exactly what “short” or “long” durations are, and go into varying amounts of detail on the difference between the two. Also, while it’s more of a design system thing than an animation best practice, providing design tokens for your specified duration values is a useful thing to consider here as well.

Carbon provides a short table of ranges of duration values based on the type of animation in question. While Material Design breaks down recommendations on duration speed in categories based on the complexity of the animation, as well as by the relative area covered by the animation. Pluralsight takes a different approach and provides a set of keywords for different durations paired with cute animals.


An animated illustration and data table for guidance on Carbon’s animation duration
Carbon’s illustration and table sorted by interaction type give guidance on what durations to use for UI animation within the system. (Large preview)

Animals ranging from a snail to a cheetah to represent possible animation durations
Pluarsight’s design system lists durations, animals and design tokens for each of its duration options. (Large preview)

Easing Values

My number one advice for easing guidelines is to create your own customized curves and don’t just use the CSS defaults. This is the most effective way to build some consistent motion association for your brand and as Sarah Drasner puts it: build “motion equity.” You’ll be on solid ground with just three curves: a custom eas-out, ease-in, and ease-in-out. And there’s always the option to add more if needed.

Quick Tip: If you’re totally stumped on where to start on easing curves, check out the Penner Easing equations on easings.net. These are designed to give you some nice looking motion and are grouped in threes for easy use. They’re much more expressive and flexible than the CSS defaults. Using a set of these in your motion guidelines can be a great place to start.


Six sets of easing curves that vary in their range of speed changes for an animation
A few of the Penner Easing Equations illustrated as cubic-bezier curves. (Large preview)
Essential Easing Functions

I recommend defining the three core easing curves because that will cover all your main easing needs for various animations.

  • Ease-in
    This curve is the one that accelerates as it begins any movement which reads well for moving an object out of view.
  • Ease-out
    This curve causes objects to decelerate before stopping which makes for a more natural feeling way to bring objects into view.
  • Ease-in-out
    As the name suggests, this curve combines the features of the first two and is best for moving elements from point to point.

With these three custom curves, you’ll have almost all your animation needs covered.


One curve for accelerating into the action, one for decelerating out of the action, and one for doing both
The three main types of curves most motion guidelines include (Large preview)

For Spectrum, we did exactly that and created three custom easing curves along with recommendations on which kinds of animation to use each for. (We came up with these curves through looking at existing animation and experimenting with some motion studies.)

Carbon and Pluralsight take a similar approach, designating three curves with suggested uses, as well as designating one as the default curve to use when in doubt. In some cases, you might only feel the need to have one custom easing curve (like Photon does) defining one curve for use across all animations.


The ease-out curve for Spectrum
One of Spectrum’s three custom easing curves (Large preview)

Along with the easing curves, it’s helpful to provide some supporting information like associated design tokens, language-specific code (for CSS, JS, iOS and/or Android), or After Effects keyframe velocities depending on which tools your team uses. This adds to the ease of use and helps make following the smart defaults in your motion guidelines the path of least resistance.

A visual illustration of the curve and interactive examples of the curve are also a big plus for quickly demonstrating how the easing curves work and what they look like. Never underestimate the power of showing instead of telling. (Or showing along with telling!)

Easing Hierarchy

Including a hierarchy of easing is one way you can take things a little further than the three core custom curves. This can be especially useful for brands that use motion as a core method of conveying their design message. Just like with type, you may want a way to make certain animation stand out more than others. Animations that stand out more strongly can be used to emphasize a particular point or interaction. In these cases, structuring your easing curves so that you have one that is more dramatic to stand out from the others can be a useful technique.

Off To A Good Start

At this point, armed with principles plus your durations and easing sections, you have a solid set of motion guidelines. That might be all you need for a version one of your motion guidelines, or for a brand that doesn’t rely heavily on motion in its design. If you’re pressed for time, establishing smart defaults for durations and easing will get far enough to see the benefits of establishing motion guidelines and save your team time.

Named Effects

Providing a listing of named effects or a library of animations to use can be a useful thing to have in your motion guidelines. Not all design system’s motion guidelines have these, some opt to bake the animation guidelines into their components instead (or as well), and some just don’t need this level of detail.

One word of caution on these though: more isn’t always better. It might look cool to have a huge library of animations as part of your design system, but the more effects you list, the more time and effort it will take to maintain those effects. To avoid creating a huge time sink for you and your team, I’d suggest making any collection of named effects as small as you possibly can.

There tend to be two approaches to providing a library of effects in motion guidelines. One approach is the way the Lightning design system does it, providing a library of small animation effects (molecules of animation, if you will) that can be used individually or composed together to build up more complex animations.


A listing of small named animations that can be composed into more complex effects
A few of Lightning Design System’s named animation library (Large preview)

The other approach is to provide more comprehensive and purpose-specific effects like Audi does for its show and hide, transform, shift, and superimposing effects and Fluent does for its page transition effects. For either approach, providing the design rationale and specific code implementations for each is useful.

Quick Tip: If you’re looking for additional motion guidelines for research, Adele is a design system collection that lets you filter by topics like motion, and styleguides.io is always a great resource for finding public design systems too.

Other Places Motion Might Come Up In Your Design System

Design systems come in all shapes and sizes. And in many cases these animation guidelines are also baked into the DNA or components of your design systems. Digging into how to do that is beyond the scope of what we’re covering here, but I do want to note that can also be useful to include animation information on component-specific pages instead of in a named effects section. It all depends on what works best for your team and your design system.

Additionally, it might be useful to call out performance and accessibility considerations for animation either in those sections of your design system, in guidelines for components, or in the motion section itself. Performance and accessibility goals affect all aspects of our design work, and animation is no exception there.

Some Parting Thoughts

I hope this article has helped to show that including motion guidelines in your design system can be incredibly useful, and helped to demystify the process of creating one. Addressing animation in your design system can be beneficial to the consistency of your product’s design and doesn’t have to be an overly time-consuming effort.

As you’re working on your motion guidelines, I encourage you to work in stages instead of waiting for your motion guidelines to be perfect. Shipping a version one with the intention of adding to it and updating it is much easier on you, the person or people authoring the guidelines, and can help you make sure you’re creating guidelines that are useful.

As hard as it can be to share something that you know is missing some detail, it can be hugely useful to ship a version one of your motion guidelines then talk to your team again to see how the first version of the guidelines has helped them and which pain points are still a factor. This iterative approach can go far towards making your guidelines cover the most relevant topics, and lets you adapt them to your team’s needs. Both are good for having a system that’s useful and avoiding unnecessary extra effort.

Smashing Editorial
(il)

This article is part of the UX design series sponsored by Adobe. Adobe XD is made for a fast and fluid UX design process, as it lets you go from idea to prototype faster. Design, prototype and share — all in one app. You can check out more inspiring projects created with Adobe XD on Behance, and also sign up for the Adobe experience design newsletter to stay updated and informed on the latest trends and insights for UX/UI design.

Source: Smashing Magazine, Including Animation In Your Design System

Get Started With Node: An Introduction To APIs, HTTP And ES6+ JavaScript

dreamt up by webguru in Uncategorized | Comments Off on Get Started With Node: An Introduction To APIs, HTTP And ES6+ JavaScript

Get Started With Node: An Introduction To APIs, HTTP And ES6+ JavaScript

Get Started With Node: An Introduction To APIs, HTTP And ES6+ JavaScript

Jamie Corkhill



You’ve probably heard of Node.js as being an “asynchronous JavaScript runtime built on Chrome’s V8 JavaScript engine”, and that it “uses an event-driven, non-blocking I/O model that makes it lightweight and efficient”. But for some, that is not the greatest of explanations.

What is Node in the first place? What exactly does it mean for Node to be “asynchronous”, and how does that differ from “synchronous”? What is the meaning “event-driven” and “non-blocking” anyway, and how does Node fit into the bigger picture of applications, Internet networks, and servers?

We’ll attempt to answer all of these questions and more throughout this series as we take an in-depth look at the inner workings of Node, learn about the HyperText Transfer Protocol, APIs, and JSON, and build our very own Bookshelf API utilizing MongoDB, Express, Lodash, Mocha, and Handlebars.

What Is Node.js

Node is only an environment, or runtime, within which to run normal JavaScript (with minor differences) outside of the browser. We can use it to build desktop applications (with frameworks like Electron), write web or app servers, and more.

Blocking/Non-Blocking And Synchronous/Asynchronous

Suppose we are making a database call to retrieve properties about a user. That call is going to take time, and if the request is “blocking”, then that means it will block the execution of our program until the call is complete. In this case, we made a “synchronous” request since it ended up blocking the thread.

So, a synchronous operation blocks a process or thread until that operation is complete, leaving the thread in a “wait state”. An asynchronous operation, on the other hand, is non-blocking. It permits execution of the thread to proceed regardless of the time it takes for the operation to complete or the result it completes with, and no part of the thread falls into a wait state at any point.

Let’s look at another example of a synchronous call that blocks a thread. Suppose we are building an application that compares the results of two Weather APIs to find their percent difference in temperature. In a blocking manner, we make a call to Weather API One and wait for the result. Once we get a result, we call Weather API Two and wait for its result. Don’t worry at this point if you are not familiar with APIs. We’ll be covering them in an upcoming section. For now, just think of an API as the medium through which two computers may communicate with one another.


A graphic depicting the fact Synchronous Operations take a long time complete
Time progression of synchronous blocking operations (Large preview)

Allow me to note, it’s important to recognize that not all synchronous calls are necessarily blocking. If a synchronous operation can manage to complete without blocking the thread or causing a wait state, it was non-blocking. Most of the time, synchronous calls will be blocking, and the time they take to complete will depend on a variety of factors, such as the speed of the API’s servers, the end user’s internet connection download speed, etc.

In the case of the image above, we had to wait quite a while to retrieve the first results from API One. Thereafter, we had to wait equally as long to get a response from API Two. While waiting for both responses, the user would notice our application hang — the UI would literally lock up — and that would be bad for User Experience.

In the case of a non-blocking call, we’d have something like this:


A graphic depicting the fact that Asynchronous Non-Blocking Operations are almost 50 percent faster
Time progression of asynchronous non-blocking operations (Large preview)

You can clearly see how much faster we concluded execution. Rather than wait on API One and then wait on API Two, we could wait for both of them to complete at the same time and achieve our results almost 50% faster. Notice, once we called API One and started waiting for its response, we also called API Two and began waiting for its response at the same time as One.

At this point, before moving into more concrete and tangible examples, it is important to mention that, for ease, the term “Synchronous” is generally shortened to “Sync”, and the term “Asynchronous” is generally shortened to “Async”. You will see this notation used in method/function names.

Callback Functions

You might be wondering, “if we can handle a call asynchronously, how do we know when that call is finished and we have a response?” Generally, we pass in as an argument to our async method a callback function, and that method will “call back” that function at a later time with a response. I’m using ES5 functions here, but we’ll update to ES6 standards later.

function asyncAddFunction(a, b, callback) {
  callback(a + b); //This callback is the one passed in to the function call below.
}

asyncAddFunction(2, 4, function(sum) {
  //Here we have the sum, 2 + 4 = 6.
});

Such a function is called a “Higher-Order Function” since it takes a function (our callback) as an argument. Alternatively, a callback function might take in an error object and a response object as arguments, and present them when the async function is complete. We’ll see this later with Express. When we called asyncAddFunction(...), you’ll notice we supplied a callback function for the callback parameter from the method definition. This function is an anonymous function (it does not have a name) and is written using the Expression Syntax. The method definition, on the other hand, is a function statement. It’s not anonymous because it actually has a name (that being “asyncAddFunction”).

Some may note confusion since, in the method definition, we do supply a name, that being “callback”. However, the anonymous function passed in as the third parameter to asyncAddFunction(...) does not know about the name, and so it remains anonymous. We also can’t execute that function at a later point by name, we’d have to go through the async calling function again to fire it.

As an example of a synchronous call, we can use the Node.js readFileSync(...) method. Again, we’ll be moving to ES6+ later.

var fs = require('fs');
var data = fs.readFileSync('/example.txt'); // The thread will be blocked here until complete.

If we were doing this asynchronously, we’d pass in a callback function which would fire when the async operation was complete.

var fs = require('fs');
var data = fs.readFile('/example.txt', function(err, data) { //Move on, this will fire when ready.
  if(err) return console.log('Error: ', err);
  console.log('Data: ', data); // Assume var data is defined above.
});
// Keep executing below, don’t wait on the data.

If you have never seen return used in that manner before, we are just saying to stop function execution so we don’t print the data object if the error object is defined. We could also have just wrapped the log statement in an else clause.

Like our asyncAddFunction(...), the code behind the fs.readFile(...) function would be something along the lines of:

function readFile(path, callback) {
 // Behind the scenes code to read a file stream.
 // The data variable is defined up here.
 callback(undefined, data); //Or, callback(err, undefined);
}

Allow us to look at one last implementation of an async function call. This will help to solidify the idea of callback functions being fired at a later point in time, and it will help us to understand the execution of a typical Node.js program.

setTimeout(function {
  // ...
}, 1000);

The setTimeout(...) method takes a callback function for the first parameter which will be fired after the number of milliseconds specified as the second argument has occurred.

Let’s look at a more complex example:

console.log('Initiated program.');

setTimeout(function {
  console.log('3000 ms (3 sec) have passed.');
}, 3000);

setTimeout(function {
  console.log('0 ms (0 sec) have passed.');
}, 0);

setTimeout(function {
  console.log('1000 ms (1 sec) has passed.');
}, 1000);

console.log('Terminated program');

The output we receive is:

Initiated program.
Terminated program.
0 ms (0 sec) have passed.
1000 ms (1 sec) has passed.
3000 ms (3 sec) have passed.

You can see that the first log statement runs as expected. Instantaneously, the last log statement prints to the screen, for that happens before 0 seconds have surpassed after the second setTimeout(...). Immediately thereafter, the second, third, and first setTimeout(...) methods execute.

If Node.js was not non-blocking, we’d see the first log statement, wait 3 seconds to see the next, instantaneously see the third (the 0-second setTimeout(...), and then have to wait one more second to see the last two log statements. The non-blocking nature of Node makes all timers start counting down from the moment the program is executed, rather than the order in which they are typed. You may want to look into Node APIs, the Callstack, and the Event Loop for more information about how Node works under the hood.

It is important to note that just because you see a callback function does not necessarily mean there is an asynchronous call in the code. We called the asyncAddFunction(…) method above “async” because we are assuming the operation takes time to complete — such as making a call to a server. In reality, the process of adding two numbers is not async, and so that would actually be an example of using a callback function in a fashion that does not actually block the thread.

Promises Over Callbacks

Callbacks can quickly become messy in JavaScript, especially multiple nested callbacks. We are familiar with passing a callback as an argument to a function, but Promises allow us to tack, or attach, a callback to an object returned from a function. This would allow us to handle multiple async calls in a more elegant manner.

As an example, suppose we are making an API call, and our function, not so uniquely named ‘makeAPICall(...)’, takes a URL and a callback.

Our function, makeAPICall(...), would be defined as

function makeAPICall(path, callback) {
  // Attempt to make API call to path argument.
  // ...
  callback(undefined, res); // Or, callback(err, undefined); depending upon the API’s response.
}

and we would call it with:

makeAPICall('/example', function(err1, res1) {
  if(err1) return console.log('Error: ', err1);
  // ...
});

If we wanted to make another API call using the response from the first, we would have to nest both callbacks. Suppose I need to inject the userName property from the res1 object into the path of the second API call. We would have:

makeAPICall('/example', function(err1, res1) {
  if(err1) return console.log('Error: ', err1);
  makeAPICall('/newExample/' + res1.userName, function(err2, res2) {
    if(err2) return console.log('Error: ', err2);
    console.log(res2);
  });
});

Note: The ES6+ method to inject the res1.userName property rather than string concatenation would be to use “Template Strings”. That way, rather than encapsulate our string in quotes (‘, or “), we would use backticks (), located beneath the Escape key on your keyboard. Then, we would use the notation ${} to embed any JS expression inside the brackets. In the end, our earlier path would be: /newExample/${res.UserName}, wrapped in backticks.

It is clear to see that this method of nesting callbacks can quickly become quite inelegant, so-called the “JavaScript Pyramid of Doom”. Jumping in, if we were using promises rather than callbacks, we could refactor our code from the first example as such:

makeAPICall('/example').then(function(res) { // Success callback.
  // ...
}, function(err) { // Failure callback.
  console.log('Error:', err);
});

The first argument to the then() function is our success callback, and the second argument is our failure callback. Alternatively, we could lose the second argument to .then(), and call .catch() instead. Arguments to .then() are optional, and calling .catch() would be equivalent to .then(successCallback, null).

Using .catch(), we have:

makeAPICall('/example').then(function(res) { // Success callback.
  // ...
}).catch(function(err) {  // Failure Callback
  console.log('Error: ', err);
});

We can also restructure this for readability:

makeAPICall('/example')
  .then(function(res) {
    // ...
  })
  .catch(function(err) {
    console.log('Error: ', err);
  });

It is important to note that we can’t just tack a .then() call on to any function and expect it to work. The function we are calling has to actually return a promise, a promise that will fire the .then() when that async operation is complete. In this case, makeAPICall(...) will do it’s thing, firing either the then() block or the catch() block when completed.

To make makeAPICall(...) return a Promise, we assign a function to a variable, where that function is the Promise constructor. Promises can be either fulfilled or rejected, where fulfilled means that the action relating to the promise completed successfully, and rejected meaning the opposite. Once the promise is either fulfilled or rejected, we say it has settled, and while waiting for it to settle, perhaps during an async call, we say that the promise is pending.

The Promise constructor takes in one callback function as an argument, which receives two parameters — resolve and reject, which we will call at a later point in time to fire either the success callback in .then(), or the .then() failure callback, or .catch(), if provided.

Here is an example of what this looks like:

var examplePromise = new Promise(function(resolve, reject) {
  // Do whatever we are going to do and then make the appropiate call below:
  resolve('Happy!'); // — Everything worked.
  reject('Sad!'); // — We noticed that something went wrong.
}):

Then, we can use:

examplePromise.then(/* Both callback functions in here */);
// Or, the success callback in .then() and the failure callback in .catch().

Notice, however, that examplePromise can’t take any arguments. That kind of defeats the purpose, so we can return a promise instead.

function makeAPICall(path) {
  return new Promise(function(resolve, reject) {
    // Make our async API call here.
    if (/* All is good */) return resolve(res); //res is the response, would be defined above.
    else return reject(err); //err is error, would be defined above.
  });
}

Promises really shine to improve the structure, and subsequently, elegance, of our code with the concept of “Promise Chaining”. This would allow us to return a new Promise inside a .then() clause, so we could attach a second .then() thereafter, which would fire the appropriate callback from the second promise.

Refactoring our multi API URL call above with Promises, we get:

makeAPICall('/example').then(function(res) { // First response callback. Fires on success to '/example' call.
  return makeAPICall(`/newExample/${res.UserName}`); // Returning new call allows for Promise Chaining.
}, function(err) { // First failure callback. Fires if there is a failure calling with '/example'.
  console.log('Error:', err);
}).then(function(res) { // Second response callback. Fires on success to returned '/newExample/...' call.
  console.log(res);
}, function(err) { // Second failure callback. Fire if there is a failure calling with '/newExample/...'
  console.log('Error:', err);
});

Notice that we first call makeAPICall('/example'). That returns a promise, and so we attach a .then(). Inside that then(), we return a new call to makeAPICall(...), which, in and of itself, as seen earlier, returns a promise, permitting us chain on a new .then() after the first.

Like above, we can restructure this for readability, and remove the failure callbacks for a generic catch() all clause. Then, we can follow the DRY Principle (Don’t Repeat Yourself), and only have to implement error handling once.

makeAPICall('/example')
  .then(function(res) { // Like earlier, fires with success and response from '/example'.
    return makeAPICall(`/newExample/${res.UserName}`); // Returning here lets us chain on a new .then().
   })
  .then(function(res) { // Like earlier, fires with success and response from '/newExample'.
    console.log(res);
   })
  .catch(function(err) { // Generic catch all method. Fires if there is an err with either earlier call.
    console.log('Error: ', err);
   });

Note that the success and failure callbacks in .then() only fire for the status of the individual Promise that .then() corresponds to. The catch block, however, will catch any errors that fire in any of the .then()s.

ES6 Const vs. Let

Throughout all of our examples, we have been employing ES5 functions and the old var keyword. While millions of lines of code still run today employing those ES5 methods, it is useful to update to current ES6+ standards, and we’ll refactor some of our code above. Let’s start with const and let.

You might be used to declaring a variable with the var keyword:

var pi = 3.14;

With ES6+ standards, we could make that either

let pi = 3.14;

or

const pi = 3.14;

where const means “constant” — a value that cannot be reassigned to later. (Except for object properties — we’ll cover that soon. Also, variables declared const are not immutable, only the reference to the variable is.)

In old JavaScript, block scopes, such as those in if, while, {}. for, etc. did not affect var in any way, and this is quite different to more statically typed languages like Java or C++. That is, the scope of var is the entire enclosing function — and that could be global (if placed outside a function), or local (if placed within a function). To demonstrate this, see the following example:

function myFunction() {
  var num = 5;
  console.log(num); // 5
  console.log('--');
  for(var i = 0; i < 10; i++)
  {
    var num = i;
    console.log(num); //num becomes 0 — 9
  }
  console.log('--');
  console.log(num); // 9
  console.log(i); // 10
}

myFunction();

Output:

5
---
0
1 2 3 ... 7 8 9
---
9
10

The important thing to notice here is that defining a new var num inside the for scope directly affected the var num outside and above the for. This is because var’s scope is always that of the enclosing function, and not a block.

Again, by default, var i inside for() defaults to myFunction’s scope, and so we can access i outside the loop and get 10.

In terms of assigning values to variables, let is equivalent to var, it’s just that let has block scoping, and so the anomalies that occurred with var above will not happen.

function myFunction() {
  let num = 5;
  console.log(num); // 5
  for(let i = 0; i < 10; i++)
  {
    let num = i;
    console.log('--');
    console.log(num); // num becomes 0 — 9
  }
  console.log('--');
  console.log(num); // 5
  console.log(i); // undefined, ReferenceError
}

Looking at the const keyword, you can see that we attain an error if we try to reassign to it:

const c = 299792458; // Fact: The constant "c" is the speed of light in a vacuum in meters per second.
c = 10; // TypeError: Assignment to constant variable.

Things become interesting when we assign a const variable to an object:

const myObject = {
  name: 'Jane Doe'
};

// This is illegal: TypeError: Assignment to constant variable.
myObject = {
  name: 'John Doe'
};

// This is legal. console.log(myObject.name) -> John Doe
myObject.name = 'John Doe';

As you can see, only the reference in memory to the object assigned to a const object is immutable, not the value its self.

ES6 Arrow Functions

You might be used to creating a function like this:

function printHelloWorld() {
  console.log('Hello, World!');
}

With arrow functions, that would become:

const printHelloWorld = () => {
  console.log('Hello, World!');
};

Suppose we have a simple function that returns the square of a number:

const squareNumber = (x) => {
  return x * x;
}

squareNumber(5); // We can call an arrow function like an ES5 functions. Returns 25.

You can see that, just like with ES5 functions, we can take in arguments with parentheses, we can use normal return statements, and we can call the function just like any other.

It’s important to note that, while parentheses are required if our function takes no arguments (like with printHelloWorld() above), we can drop the parentheses if it only takes one, so our earlier squareNumber() method definition can be rewritten as:

const squareNumber = x => { // Notice we have dropped the parentheses for we only take in one argument.
  return x * x;
}

Whether you choose to encapsulate a single argument in parentheses or not is a matter of personal taste, and you will likely see developers use both methods.

Finally, if we only want to implicitly return one expression, as with squareNumber(...) above, we can put the return statement in line with the method signature:

const squareNumber = x => x * x;

That is,

const test = (a, b, c) => expression

is the same as

const test = (a, b, c) => { return expression }

Note, when using the above shorthand to implicitly return an object, things become obscure. What stops JavaScript from believing the brackets within which we are required to encapsulate our object is not our function body? To get around this, we wrap the object’s brackets in parentheses. This explicitly lets JavaScript know that we are indeed returning an object, and we are not just defining a body.

const test = () => ({ pi: 3.14 }); // Spaces between brackets are a formality to make the code look cleaner.

To help solidify the concept of ES6 functions, we’ll refactor some of our earlier code allowing us to compare the differences between both notations.

asyncAddFunction(...), from above, could be refactored from:

function asyncAddFunction(a, b, callback){
  callback(a + b);
}

to:

const aysncAddFunction = (a, b, callback) => {
  callback(a + b);
};

or even to:

const aysncAddFunction = (a, b, callback) => callback(a + b); // This will return callback(a + b).

When calling the function, we could pass an arrow function in for the callback:

asyncAddFunction(10, 12, sum => { // No parentheses because we only take one argument.
  console.log(sum);
}

It is clear to see how this method improves code readability. To show you just one case, we can take our old ES5 Promise based example above, and refactor it to use arrow functions.

makeAPICall('/example')
  .then(res => makeAPICall(`/newExample/${res.UserName}`))
  .then(res => console.log(res))
  .catch(err => console.log('Error: ', err));

Now, there are some caveats with arrow functions. For one, they do not bind a this keyword. Suppose I have the following object:

const Person = {
  name: 'John Doe',
  greeting: () => {
    console.log(`Hi. My name is ${this.name}.`);
  }
}

You might expect a call to Person.greeting() will return “Hi. My name is John Doe.” Instead, we get: “Hi. My name is undefined.” That is because arrow functions do not have a this, and so attempting to use this inside an arrow function defaults to the this of the enclosing scope, and the enclosing scope of the Person object is window, in the browser, or module.exports in Node.

To prove this, if we use the same object again, but set the name property of the global this to something like ‘Jane Doe’, then this.name in the arrow function returns ‘Jane Doe’, because the global this is within the enclosing scope, or is the parent of the Person object.

this.name = 'Jane Doe';

const Person = {
  name: 'John Doe',
  greeting: () => {
    console.log(`Hi. My name is ${this.name}.`);
  }
}

Person.greeting(); // Hi. My name is Jane Doe

This is known as ‘Lexical Scoping’, and we can get around it by using the so-called ‘Short Syntax’, which is where we lose the colon and the arrow as to refactor our object as such:

const Person = {
  name: 'John Doe',
  greeting() {
    console.log(`Hi. My name is ${this.name}.`);
  }
}

Person.greeting() //Hi. My name is John Doe.

ES6 Classes

While JavaScript never supported classes, you could always emulate them with objects like the above. EcmaScript 6 provides support for classes using the class and new keywords:

class Person {
   constructor(name) {
      this.name = name;
   }
   greeting() {
      console.log(`Hi. My name is ${this.name}.`);
   }
}

const person = new Person(‘John’);
person.greeting(); // Hi. My name is John.

The constructor function gets called automatically when using the new keyword, into which we can pass arguments to initially set up the object. This should be familiar to any reader who has experience with more statically typed object-oriented programming languages like Java, C++, and C#.

Without going into too much detail about OOP concepts, another such paradigm is “inheritance”, which is to allow one class to inherit from another. A class called Car, for example, will be very general — containing such methods as “stop”, “start”, etc., as all cars need. A sub-set of the class called SportsCar, then, might inherit fundamental operations from Car and override anything it needs custom. We could denote such a class as follows:

class Car {
   constructor(licensePlateNumber) {
      this.licensePlateNumber = licensePlateNumber;
   }
   start() {}
   stop() {}
   getLicensePlate() {
      return this.licensePlateNumber;
   }
   // …
}


class SportsCar extends Car {
   constructor(engineRevCount, licensePlateNumber) {
      super(licensePlateNumber); // Pass licensePlateNumber up to the parent class.
      this.engineRevCount = engineRevCount;
   }
   start() {
      super.start();
   }
   stop() {
      super.stop();
   }
   getLicensePlate() {
      return super.getLicensePlate();
   }
   getEngineRevCount() {
      return this.engineRevCount;
   }
}

You can clearly see that the super keyword allows us to access properties and methods from the parent, or super, class.

JavaScript Events

An Event is an action that occurs to which you have the ability to respond. Suppose you are building a login form for your application. When the user presses the “submit” button, you can react to that event via an “event handler” in your code — typically a function. When this function is defined as the event handler, we say we are “registering an event handler”. The event handler for the submit button click will likely check the formatting of the input provided by the user, sanitize it to prevent such attacks as SQL Injections or Cross Site Scripting (please be aware that no code on the client-side can ever be considered safe. Always sanitize data on the server — never trust anything from the browser), and then check to see if that username and password combination exits within a database to authenticate a user and serve them a token.

Since this is an article about Node, we’ll focus on the Node Event Model.

We can use the events module from Node to emit and react to specific events. Any object that emits an event is an instance of the EventEmitter class.

We can emit an event by calling the emit() method and we listen for that event via the on() method, both of which are exposed through the EventEmitter class.

const EventEmitter = require('events');

const myEmitter = new EventEmitter();

With myEmitter now an instance of the EventEmitter class, we can access emit() and on():

const EventEmitter = require('events');

const myEmitter = new EventEmitter();

myEmitter.on('someEvent', () => {
  console.log('The "someEvent" event was fired (emitted)');
});

myEmitter.emit('someEvent'); // This will call the callback function above.

The second parameter to myEmitter.on() is the callback function that will fire when the event is emitted — this is the event handler. The first parameter is the name of the event, which can be anything we like, although the camelCase naming convention is recommended.

Additionally, the event handler can take any number of arguments, which are passed down when the event is emitted:

const EventEmitter = require('events');

const myEmitter = new EventEmitter();

myEmitter.on('someEvent', (data) => {
  console.log(`The "someEvent" event was fired (emitted) with data: ${data}`);
});

myEmitter.emit('someEvent', 'This is the data payload');

By using inheritance, we can expose the emit() and on() methods from ‘EventEmitter’ to any class. This is done by creating a Node.js class, and using the extends reserved keyword to inherit the properties available on EventEmitter:

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {
  // This is my class. I can emit events from a MyEmitter object.
}

Suppose we are building a vehicle collision notification program that receives data from gyroscopes, accelerometers, and pressure gauges on the car’s hull. When a vehicle collides with an object, those external sensors will detect the crash, executing the collide(...) function and passing to it the aggregated sensor data as a nice JavaScript Object. This function will emit a collision event, notifying the vendor of the crash.

const EventEmitter = require('events');

class Vehicle extends EventEmitter {
  collide(collisionStatistics) {
    this.emit('collision', collisionStatistics)
  }
}

const myVehicle = new Vehicle();
myVehicle.on('collision', collisionStatistics => {
  console.log('WARNING! Vehicle Impact Detected: ', collisionStatistics);
  notifyVendor(collisionStatistics);
});

myVehicle.collide({ ... });

This is a convoluted example for we could just put the code within the event handler inside the collide function of the class, but it demonstrates how the Node Event Model functions nonetheless. Note that some tutorials will show the util.inherits() method of permitting an object to emit events. That has been deprecated in favor of ES6 Classes and extends.

The Node Package Manager

When programming with Node and JavaScript, it’ll be quite common to hear about npm. Npm is a package manager which does just that — permits the downloading of third-party packages that solve common problems in JavaScript. Other solutions, such as Yarn, Npx, Grunt, and Bower exist as well, but in this section, we’ll focus only on npm and how you can install dependencies for your application through a simple Command Line Interface (CLI) using it.

Let’s start simple, with just npm. Visit the NpmJS homepage to view all of the packages available from NPM. When you start a new project that will depend on NPM Packages, you’ll have to run npm init through the terminal in your project’s root directory. You will be asked a series of questions which will be used to create a package.json file. This file stores all of your dependencies — modules that your application depends on to function, scripts — pre-defined terminal commands to run tests, build the project, start the development server, etc., and more.

To install a package, simply run npm install [package-name] --save. The save flag will ensure the package and its version is logged in the package.json file. Since npm version 5, dependencies are saved by default, so --save may be omitted. You will also notice a new node_modules folder, containing the code for that package you just installed. This can also be shortened to just npm i [package-name]. As a helpful note, the node_modules folder should never be included in a GitHub repository due to its size. Whenever you clone a repo from GitHub (or any other version management system), be sure to run the command npm install to go out and fetch all the packages defined in the package.json file, creating the node_modules directory automatically. You can also install a package at a specific version: npm i [package-name]@1.10.1 --save, for example.

Removing a package is similar to installing one: npm remove [package-name].

You can also install a package globally. This package will be available across all projects, not just the one your working on. You do this with the -g flag after npm i [package-name]. This is commonly used for CLIs, such as Google Firebase and Heroku. Despite the ease this method presents, it is generally considered bad practice to install packages globally, for they are not saved in the package.json file, and if another developer attempts to use your project, they won’t attain all the required dependencies from npm install.

APIs & JSON

APIs are a very common paradigm in programming, and even if you are just starting out in your career as a developer, APIs and their usage, especially in web and mobile development, will likely come up more often than not.

An API is an Application Programming Interface, and it is basically a method by which two decoupled systems may communicate with each other. In more technical terms, an API permits a system or computer program (usually a server) to receive requests and send appropriate responses (to a client, also known as a host).

Suppose you are building a weather application. You need a way to geocode a user’s address into a latitude and longitude, and then a way to attain the current or forecasted weather at that particular location.

As a developer, you want to focus on building your app and monetizing it, not putting the infrastructure in place to geocode addresses or placing weather stations in every city.

Luckily for you, companies like Google and OpenWeatherMap have already put that infrastructure in place, you just need a way to talk to it — that is where the API comes in. While, as of now, we have developed a very abstract and ambiguous definition of the API, bear with me. We’ll be getting to tangible examples soon.

Now, it costs money for companies to develop, maintain, and secure that aforementioned infrastructure, and so it is common for corporations to sell you access to their API. This is done with that is known as an API key, a unique alphanumeric identifier associating you, the developer, with the API. Every time you ask the API to send you data, you pass along your API key. The server can then authenticate you and keep track of how many API calls you are making, and you will be charged appropriately. The API key also permits Rate-Limiting or API Call Throttling (a method of throttling the number of API calls in a certain timeframe as to not overwhelm the server, preventing DOS attacks — Denial of Service). Most companies, however, will provide a free quota, giving you, as an example, 25,000 free API calls a day before charging you.

Up to this point, we have established that an API is a method by which two computer programs can communicate with each other. If a server is storing data, such as a website, and your browser makes a request to download the code for that site, that was the API in action.

Let us look at a more tangible example, and then we’ll look at a more real-world, technical one. Suppose you are eating out at a restaurant for dinner. You are equivalent to the client, sitting at the table, and the chef in the back is equivalent to the server.

Since you will never directly talk to the chef, there is no way for him/her to receive your request (for what order you would like to make) or for him/her to provide you with your meal once you order it. We need someone in the middle. In this case, it’s the waiter, analogous to the API. The API provides a medium with which you (the client) may talk to the server (the chef), as well as a set of rules for how that communication should be made (the menu — one meal is allowed two sides, etc.)

Now, how do you actually talk to the API (the waiter)? You might speak English, but the chef might speak Spanish. Is the waiter expected to know both languages to translate? What if a third person comes in who only speaks Mandarin? What then? Well, all clients and servers have to agree to speak a common language, and in computer programming, that language is JSON, pronounced JAY-sun, and it stands for JavaScript Object Notation.

At this point, we don’t quite know what JSON looks like. It’s not a computer programming language, it’s just, well, a language, like English or Spanish, that everyone (everyone being computers) understands on a guaranteed basis. It’s guaranteed because it’s a standard, notably RFC 8259, the JavaScript Object Notation (JSON) Data Interchange Format by the Internet Engineering Task Force (IETF).

Even without formal knowledge of what JSON actually is and what it looks like (we’ll see in an upcoming article in this series), we can go ahead introduce a technical example operating on the Internet today that employs APIs and JSON. APIs and JSON are not just something you can choose to use, it’s not equivalent to one out of a thousand JavaScript frameworks you can pick to do the same thing. It is THE standard for data exchange on the web.

Suppose you are building a travel website that compares prices for aircraft, rental car, and hotel ticket prices. Let us walk through, step-by-step, on a high level, how we would build such an application. Of course, we need our User Interface, the front-end, but that is out of scope for this article.

We want to provide our users with the lowest price booking method. Well, that means we need to somehow attain all possible booking prices, and then compare all of the elements in that set (perhaps we store them in an array) to find the smallest element (known as the infimum in mathematics.)

How will we get this data? Well, suppose all of the booking sites have a database full of prices. Those sites will provide an API, which exposes the data in those databases for use by you. You will call each API for each site to attain all possible booking prices, store them in your own array, find the lowest or minimum element of that array, and then provide the price and booking link to your user. We’ll ask the API to query its database for the price in JSON, and it will respond with said price in JSON to us. We can then use, or parse, that accordingly. We have to parse it because APIs will return JSON as a string, not the actual JavaScript data type of JSON. This might not make sense now, and that’s okay. We’ll be covering it more in a future article.

Also, note that just because something is called an API does not necessarily mean it operates on the web and sends and receives JSON. The Java API, for example, is just the list of classes, packages, and interfaces that are part of the Java Development Kit (JDK), providing programming functionality to the programmer.

Okay. We know we can talk to a program running on a server by way of an Application Programming Interface, and we know that the common language with which we do this is known as JSON. But in the web development and networking world, everything has a protocol. What do we actually do to make an API call, and what does that look like code-wise? That’s where HTTP Requests enter the picture, the HyperText Transfer Protocol, defining how messages are formatted and transmitted across the Internet. Once we have an understanding of HTTP (and HTTP verbs, you’ll see that in the next section), we can look into actual JavaScript frameworks and methods (like fetch()) offered by the JavaScript API (similar to the Java API), that actually allow us to make API calls.

HTTP And HTTP Requests

HTTP is the HyperText Transfer Protocol. It is the underlying protocol that determines how messages are formatted as they are transmitted and received across the web. Let’s think about what happens when, for example, you attempt to load the home page of Smashing Magazine in your web browser.

You type the website URL (Uniform Resource Locator) in the URL bar, where the DNS server (Domain Name Server, out of scope for this article) resolves the URL into the appropriate IP Address. The browser makes a request, called a GET Request, to the Web Server to, well, GET the underlying HTML behind the site. The Web Server will respond with a message such as “OK”, and then will go ahead and send the HTML down to the browser where it will be parsed and rendered accordingly.

There are a few things to note here. First, the GET Request, and then the “OK” response. Suppose you have a specific database, and you want to write an API to expose that database to your users. Suppose the database contains books the user wants to read (as it will in a future article in this series). Then there are four fundamental operations your user may want to perform on this database, that is, Create a record, Read a record, Update a record, or Delete a record, known collectively as CRUD operations.

Let’s look at the Read operation for a moment. Without incorrectly assimilating or conflating the notion of a web server and a database, that Read operation is very similar to your web browser attempting to get the site from the server, just as to read a record is to get the record from the database.

This is known as an HTTP Request. You are making a request to some server somewhere to get some data, and, as such, the request is appropriately named “GET”, capitalization being a standard way to denote such requests.

What about the Create portion of CRUD? Well, when talking about HTTP Requests, that is known as a POST request. Just as you might post a message on a social media platform, you might also post a new record to a database.

CRUD’s Update allows us to use either a PUT or PATCH Request in order to update a resource. HTTP’s PUT will either create a new record or will update/replace the old one.

Let’s look at this a bit more in detail, and then we’ll get to PATCH.

An API generally works by making HTTP requests to specific routes in a URL. Suppose we are making an API to talk to a DB containing a user’s booklist. Then we might be able to view those books at the URL .../books. A POST requests to .../books will create a new book with whatever properties you define (think id, title, ISBN, author, publishing data, etc.) at the .../books route. It doesn’t matter what the underlying data structure is that stores all the books at .../books right now. We just care that the API exposes that endpoint (accessed through the route) to manipulate data. The prior sentence was key: A POST request creates a new book at the ...books/ route. The difference between PUT and POST, then, is that PUT will create a new book (as with POST) if no such book exists, or, it will replace an existing book if the book already exists within that aforementioned data structure.

Suppose each book has the following properties: id, title, ISBN, author, hasRead (boolean).

Then to add a new book, as seen earlier, we would make a POST request to .../books. If we wanted to completely update or replace a book, we would make a PUT request to .../books/id where id is the ID of the book we want to replace.

While PUT completely replaces an existing book, PATCH updates something having to do with a specific book, perhaps modifying the hasRead boolean property we defined above — so we’d make a PATCH request to …/books/id sending along the new data.

It can be difficult to see the meaning of this right now, for thus far, we’ve established everything in theory but haven’t seen any tangible code that actually makes an HTTP request. We shall, however, get to that soon, covering GET in this article, ad the rest in a future article.

There is one last fundamental CRUD operation and it’s called Delete. As you would expect, the name of such an HTTP Request is “DELETE”, and it works much the same as PATCH, requiring the book’s ID be provided in a route.

We have learned thus far, then, that routes are specific URLs to which you make an HTTP Request, and that endpoints are functions the API provides, doing something to the data it exposes. That is, the endpoint is a programming language function located on the other end of the route, and it performs whatever HTTP Request you specified. We also learned that there exist such terms as POST, GET, PUT, PATCH, DELETE, and more (known as HTTP verbs) that actually specify what requests you are making to the API. Like JSON, these HTTP Request Methods are Internet standards as defined by the Internet Engineering Task Force (IETF), most notably, RFC 7231, Section Four: Request Methods, and RFC 5789, Section Two: Patch Method, where RFC is an acronym for Request for Comments.

So, we might make a GET request to the URL .../books/id where the ID passed in is known as a parameter. We could make a POST, PUT, or PATCH request to .../books to create a resource or to .../books/id to modify/replace/update a resource. And we can also make a DELETE request to .../books/id to delete a specific book.

A full list of HTTP Request Methods can be found here.

It is also important to note that after making an HTTP Request, we’ll receive a response. The specific response is determined by how we build the API, but you should always receive a status code. Earlier, we said that when your web browser requests the HTML from the web server, it’ll respond with “OK”. That is known as an HTTP Status Code, more specifically, HTTP 200 OK. The status code just specifies how the operation or action specified in the endpoint (remember, that’s our function that does all the work) completed. HTTP Status Codes are sent back by the server, and there are probably many you are familiar with, such as 404 Not Found (the resource or file could not be found, this would be like making a GET request to .../books/id where no such ID exists.)

A complete list of HTTP Status Codes can be found here.

MongoDB

MongoDB is a non-relational, NoSQL database similar to the Firebase Real-time Database. You will talk to the database via a Node package such as the MongoDB Native Driver or Mongoose.

In MongoDB, data is stored in JSON, which is quite different from relational databases such as MySQL, PostgreSQL, or SQLite. Both are called databases, with SQL Tables called Collections, SQL Table Rows called Documents, and SQL Table Columns called Fields.

We will use the MongoDB Database in an upcoming article in this series when we create our very first Bookshelf API. The fundamental CRUD Operations listed above can be performed on a MongoDB Database.

It’s recommended that you read through the MongoDB Docs to learn how to create a live database on an Atlas Cluster and make CRUD Operations to it with the MongoDB Native Driver. In the next article of this series, we will learn how to set up a local database and a cloud production database.

Building A Command Line Node Application

When building out an application, you will see many authors dump their entire code base at the beginning of the article, and then attempt to explain each line thereafter. In this text, I’ll take a different approach. I’ll explain my code line-by-line, building the app as we go. I won’t worry about modularity or performance, I won’t split the codebase into separate files, and I won’t follow the DRY Principle or attempt to make the code reusable. When just learning, it is useful to make things as simple as possible, and so that is the approach I will take here.

Let us be clear about what we are building. We won’t be concerned with user input, and so we won’t make use of packages like Yargs. We also won’t be building our own API. That will come in a later article in this series when we make use of the Express Web Application Framework. I take this approach as to not conflate Node.js with the power of Express and APIs since most tutorials do. Rather, I’ll provide one method (of many) by which to call and receive data from an external API which utilizes a third-party JavaScript library. The API we’ll be calling is a Weather API, which we’ll access from Node and dump its output to the terminal, perhaps with some formatting, known as “pretty-printing”. I’ll cover the entire process, including how to set up the API and attain API Key, the steps of which provide the correct results as of January 2019.

We’ll be using the OpenWeatherMap API for this project, so to get started, navigate to the OpenWeatherMap sign-up page and create an account with the form. Once logged in, find the API Keys menu item on the dashboard page (located over here). If you just created an account, you’ll have to pick a name for your API Key and hit “Generate”. It could take at least 2 hours for your new API Key to be functional and associated with your account.

Before we start building out the application, we’ll visit the API Documentation to learn how to format our API Key. In this project, we’ll be specifying a zip code and a country code to attain the weather information at that location.

From the docs, we can see that the method by which we do this is to provide the following URL:

api.openweathermap.org/data/2.5/weather?zip={zip code},{country code}

Into which we could input data:

api.openweathermap.org/data/2.5/weather?zip=94040,us

Now, before we can actually attain relevant data from this API, we’ll need to provide our new API Key as a query parameter:

api.openweathermap.org/data/2.5/weather?zip=94040,us&appid={YOUR_API_KEY}

For now, copy that URL into a new tab in your web browser, replacing the {YOUR_API_KEY} placeholder with the API Key you obtained earlier when you registered for an account.

The text you can see is actually JSON — the agreed upon language of the web as discussed earlier.

To inspect this further, hit Ctrl + Shift + I in Google Chrome to open the Chrome Developer tools, and then navigate to the Network tab. At present, there should be no data here.


Empty Chrome Dev Tools Network Tab
The empty Google Chrome Developer Tools(Large preview)

To actually monitor network data, reload the page, and watch the tab be populated with useful information. Click the first link as depicted in the image below.


Populated Chrome Dev Tools Network Tab
The populated Google Chrome Developer Tools (Large preview)

Once you click on that link, we can actually view HTTP specific information, such as the headers. Headers are sent in the response from the API (you can also, in some cases, send your own headers to the API, or you can even create your own custom headers (often prefixed with x-) to send back when building your own API), and just contain extra information that either the client or server may need.

In this case, you can see that we made an HTTP GET Request to the API, and it responded with an HTTP Status 200 OK. You can also see that the data sent back was in JSON, as listed under the “Response Headers” section.


Google Dev Tools depicting the Headers from the API response
Headers in the response from the API (Large preview)

If you hit the preview tab, you can actually view the JSON as a JavaScript Object. The text version you can see in your browser is a string, for JSON is always transmitted and received across the web as a string. That’s why we have to parse the JSON in our code, to get it into a more readable format — in this case (and in pretty much every case) — a JavaScript Object.

You can also use the Google Chrome Extension “JSON View” to do this automatically.

To start building out our application, I’ll open a terminal and make a new root directory and then cd into it. Once inside, I’ll create a new app.js file, run npm init to generate a package.json file with the default settings, and then open Visual Studio Code.

mkdir command-line-weather-app && cd command-line-weather-app
touch app.js
npm init
code .

Thereafter, I’ll download Axios, verify it has been added to my package.json file, and note that the node_modules folder has been created successfully.

In the browser, you can see that we made a GET Request by hand by manually typing the proper URL into the URL Bar. Axios is what will allow me to do that inside of Node.

Starting now, all of the following code will be located inside of the app.js file, each snippet placed one after the other.

The first thing I’ll do is require the Axios package we installed earlier with

const axios = require('axios');

We now have access to Axios, and can make relevant HTTP Requests, via the axios constant.

Generally, our API calls will be dynamic — in this case, we might want to inject different zip codes and country codes into our URL. So, I’ll be creating constant variables for each part of the URL, and then put them together with ES6 Template Strings. First, we have the part of our URL that will never change as well as our API Key:

const API_URL = 'https://api.openweathermap.org/data/2.5/weather?zip=';
const API_KEY = 'Your API Key Here';

I’ll also assign our zip code and country code. Since we are not expecting user input and are rather hard coding the data, I’ll make these constant as well, although, in many cases, it will be more useful to use let.

const LOCATION_ZIP_CODE = '90001';
const COUNTRY_CODE = 'us';

We now need to put these variables together into one URL to which we can use Axios to make GET Requests to:

const ENTIRE_API_URL = `${API_URL}${LOCATION_ZIP_CODE},${COUNTRY_CODE}&appid=${API_KEY}`;

Here is the contents of our app.js file up to this point:

const axios = require('axios');

// API specific settings.
const API_URL = 'https://api.openweathermap.org/data/2.5/weather?zip=';
const API_KEY = 'Your API Key Here';

const LOCATION_ZIP_CODE = '90001';
const COUNTRY_CODE = 'us';

const ENTIRE_API_URL = `${API_URL}${LOCATION_ZIP_CODE},${COUNTRY_CODE}&appid=${API_KEY}`;

All that is left to do is to actually use axios to make a GET Request to that URL. For that, we’ll use the get(url) method provided by axios.

axios.get(ENTIRE_API_URL)

axios.get(...) actually returns a Promise, and the success callback function will take in a response argument which will allow us to access the response from the API — the same thing you saw in the browser. I’ll also add a .catch() clause to catch any errors.

axios.get(ENTIRE_API_URL)
    .then(response => console.log(response))
    .catch(error => console.log('Error', error));

If we now run this code with node app.js in the terminal, you will be able to see the full response we get back. However, suppose you just want to see the temperature for that zip code — then most of that data in the response is not useful to you. Axios actually returns the response from the API in the data object, which is a property of the response. That means the response from the server is actually located at response.data, so let’s print that instead in the callback function: console.log(response.data).

Now, we said that web servers always deal with JSON as a string, and that is true. You might notice, however, that response.data is already an object (evident by running console.log(typeof response.data)) — we didn’t have to parse it with JSON.parse(). That is because Axios already takes care of this for us behind the scenes.

The output in the terminal from running console.log(response.data) can be formatted — “pretty-printed” — by running console.log(JSON.stringify(response.data, undefined, 2)). JSON.stringify() converts a JSON object into a string, and take in the object, a filter, and the number of characters by which to indent by when printing. You can see the response this provides:

{
  "coord": {
    "lon": -118.24,
    "lat": 33.97
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 288.21,
    "pressure": 1022,
    "humidity": 15,
    "temp_min": 286.15,
    "temp_max": 289.75
  },
  "visibility": 16093,
  "wind": {
    "speed": 2.1,
    "deg": 110
  },
  "clouds": {
    "all": 1
  },
  "dt": 1546459080,
  "sys": {
    "type": 1,
    "id": 4361,
    "message": 0.0072,
    "country": "US",
    "sunrise": 1546441120,
    "sunset": 1546476978
  },
  "id": 420003677,
  "name": "Lynwood",
  "cod": 200
}

Now, it is clear to see that the temperature we are looking for is located on the main property of the response.data object, so we can access it by calling response.data.main.temp. Let’s look at out application’s code up to now:

const axios = require('axios');

// API specific settings.
const API_URL = 'https://api.openweathermap.org/data/2.5/weather?zip=';
const API_KEY = 'Your API Key Here';

const LOCATION_ZIP_CODE = '90001';
const COUNTRY_CODE = 'us';

const ENTIRE_API_URL = `${API_URL}${LOCATION_ZIP_CODE},${COUNTRY_CODE}&appid=${API_KEY}`;

axios.get(ENTIRE_API_URL)
    .then(response => console.log(response.data.main.temp))
    .catch(error => console.log('Error', error));

The temperature we get back is actually in Kelvin, which is a temperature scale generally used in Physics, Chemistry, and Thermodynamics due to the fact that it provides an “absolute zero” point, which is the temperature at which all thermal motion of all inner particles cease. We just need to convert this to Fahrenheit or Celcius with the formulas below:

F = K * 9/5 &mdash; 459.67
C = K &mdash; 273.15

Let’s update our success callback to print the new data with this conversion. We’ll also add in a proper sentence for the purposes of User Experience:

axios.get(ENTIRE_API_URL)
    .then(response => {
        // Getting the current temperature and the city from the response object.
        const kelvinTemperature = response.data.main.temp;
        const cityName = response.data.name;
        const countryName = response.data.sys.country;

        // Making K to F and K to C conversions.
        const fahrenheitTemperature = (kelvinTemperature * 9/5) — 459.67;
        const celciusTemperature = kelvinTemperature — 273.15;

        // Building the final message.
        const message = (
            `Right now, in 
            ${cityName}, ${countryName} the current temperature is 
            ${fahrenheitTemperature.toFixed(2)} deg F or 
            ${celciusTemperature.toFixed(2)} deg C.`.replace(/s+/g, ' ')
        );

        console.log(message);
    })
    .catch(error => console.log('Error', error));

The parentheses around the message variable are not required, they just look nice — similar to when working with JSX in React. The backslashes stop the template string from formatting a new line, and the replace() String prototype method gets rid of white space using Regular Expressions (RegEx). The toFixed() Number prototype methods rounds a float to a specific number of decimal places — in this case, two.

With that, our final app.js looks as follows:

const axios = require('axios');

// API specific settings.
const API_URL = 'https://api.openweathermap.org/data/2.5/weather?zip=';
const API_KEY = 'Your API Key Here';

const LOCATION_ZIP_CODE = '90001';
const COUNTRY_CODE = 'us';

const ENTIRE_API_URL = `${API_URL}${LOCATION_ZIP_CODE},${COUNTRY_CODE}&appid=${API_KEY}`;

axios.get(ENTIRE_API_URL)
    .then(response => {
        // Getting the current temperature and the city from the response object.
        const kelvinTemperature = response.data.main.temp;
        const cityName = response.data.name;
        const countryName = response.data.sys.country;

        // Making K to F and K to C conversions.
        const fahrenheitTemperature = (kelvinTemperature * 9/5) — 459.67;
        const celciusTemperature = kelvinTemperature — 273.15;

        // Building the final message.
        const message = (
            `Right now, in 
            ${cityName}, ${countryName} the current temperature is 
            ${fahrenheitTemperature.toFixed(2)} deg F or 
            ${celciusTemperature.toFixed(2)} deg C.`.replace(/s+/g, ' ')
        );

        console.log(message);
    })
    .catch(error => console.log('Error', error));

Conclusion

We have learned a lot about how Node works in this article, from the differences between synchronous and asynchronous requests, to callback functions, to new ES6 features, events, package managers, APIs, JSON, and the HyperText Transfer Protocol, Non-Relational Databases, and we even built our own command line application utilizing most of that new found knowledge.

In future articles in this series, we’ll take an in-depth look at the Call Stack, the Event Loop, and Node APIs, we’ll talk about Cross-Origin Resource Sharing (CORS), and we’ll build a Full Stack Bookshelf API utilizing databases, endpoints, user authentication, tokens, server-side template rendering, and more.

From here, start building your own Node applications, read the Node documentation, go out and find interesting APIs or Node Modules and implement them yourself. The world is your oyster and you have at your fingertips access to the largest network of knowledge on the planet — the Internet. Use it to your advantage.

Further Reading on SmashingMag:

Smashing Editorial
(dm, ra, il)

Source: Smashing Magazine, Get Started With Node: An Introduction To APIs, HTTP And ES6+ JavaScript

Styling An Angular Application With Bootstrap

dreamt up by webguru in Uncategorized | Comments Off on Styling An Angular Application With Bootstrap

Styling An Angular Application With Bootstrap

Styling An Angular Application With Bootstrap

Ahmed Bouchefra



In case you’ve already tried building a web application with Angular 7, it’s time to kick it up a notch. Let’s see how we can integrate Bootstrap CSS styles and JavaScript files with an Angular project generated using the Angular CLI, and how to use form controls and classes to create beautiful forms and how to style HTML tables using Table styles.

For the Angular part, we’ll be creating a simple client-side application for creating and listing contacts. Each contact has an ID, name, email, and description, and we’ll be using a simple data service that stores the contacts in a TypeScript array. You can use an advanced in-memory API instead. (Check out “A Complete Guide To Routing In Angular”.)

Note: You can get the source code of this tutorial from this GitHub repository and see the live example over here.

Requirements

Before we start creating the demo application, let’s see the requirements needed for this tutorial.

Basically, you will need the following:

  • Node.js and NPM installed (you can simply head on over to the official website and download the binaries for your system),
  • Familiarity with TypeScript,
  • Working experience of Angular,
  • Basic knowledge of CSS and HTML.

Installing Angular CLI

Let’s start by installing the latest version of Angular CLI. In your terminal, run the following command:

$ npm install -g @angular/cli

At the time writing, v7.0.3 of Angular CLI is installed. If you have the CLI already installed, you can make sure you have the latest version by using this command:

$ ng --version

Creating A Project

Once you have Angular CLI installed, let’s use it to generate an Angular 7 project by running the following command:

$ ng new angular-bootstrap-demo

The CLI will then ask you:

Would you like to add Angular routing?

Press Y. Next, it will ask you:

Which stylesheet format would you like to use?

Choose “CSS”.

Adding Bootstrap

After creating the project, you need to install Bootstrap 4 and integrate it with your Angular project.

First, navigate inside your project’s root folder:

$ cd angular-bootstrap-demo

Next, install Bootstrap 4 and jQuery from npm:

$ npm install --save bootstrap jquery

(In this case, bootstrap v4.2.1 and jquery v3.3.1 are installed.)

Finally, open the angular.json file and add the file paths of Bootstrap CSS and JS files as well as jQuery to the styles and scripts arrays under the build target:

"architect": {
  "build": {
    [...], 
    "styles": [
      "src/styles.css", 
        "node_modules/bootstrap/dist/css/bootstrap.min.css"
      ],
      "scripts": [
        "node_modules/jquery/dist/jquery.min.js",
        "node_modules/bootstrap/dist/js/bootstrap.min.js"
      ]
    },

Check out how to add Bootstrap to an Angular 6 project for options on how to integrate Bootstrap with Angular.

Adding A Data Service

After creating a project and adding Bootstrap 4, we’ll create an Angular service that will be used to provide some demo data to display in our application.

In your terminal, run the following command to generate a service:

$ ng generate service data

This will create two src/app/data.service.spec.ts and src/app/data.service.ts files.

Open src/app/data.service.ts and replace its contents with the following:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  contacts = [
    {id: 1, name: "Contact 001", description: "Contact 001 des", email: "c001@email.com"},
    {id: 2, name: "Contact 002", description: "Contact 002 des", email: "c002@email.com"},
    {id: 3, name: "Contact 003", description: "Contact 003 des", email: "c003@email.com"},
    {id: 4, name: "Contact 004", description: "Contact 004 des", email: "c004@email.com"}
  ];

  constructor() { }

  public getContacts():Array{
    return this.contacts;
  }
  public createContact(contact: {id, name, description, email}){
    this.contacts.push(contact);
  }
}

We add a contacts array with some demo contacts, a getContacts() method which returns the contacts and a createContact() which append a new contact to the contacts array.

Adding Components

After creating the data service, next we need to create some components for our application. In your terminal, run:

$ ng generate component home
$ ng generate component contact-create
$ ng generate component contact-list

Next, we’ll add these components to the routing module to enable navigation in our application. Open the src/app/app-routing.module.ts file and replace its contents with the following:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ContactListComponent } from './contact-list/contact-list.component';
import { ContactCreateComponent } from './contact-create/contact-create.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {path:  "", pathMatch:  "full",redirectTo:  "home"},
  {path: "home", component: HomeComponent},
  {path: "contact-create", component: ContactCreateComponent},
  {path: "contact-list", component: ContactListComponent}  
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

We use the redirectTo property of the router’s path to redirect users to the home page when they visit our application.

Next, let’s create the header and footer components:

$ ng generate component header
$ ng generate component footer

Open the src/app/header/header.component.html file and add the following code:

<nav class="navbar navbar-expand-md bg-dark navbar-dark fixed-top">
  <a class="navbar-brand" href="#">Angular Bootstrap Demo</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse"
    aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  
</nav>

A navigation bar will be created with Bootstrap 4, and we’ll use the routerLink directive to link to different components.

Use the .navbar, .navbar-expand{-sm|-md|-lg|-xl} and .navbar-dark classes to create Bootstrap navigation bars. (For more information about nav bars, check out Bootstrap’s documentation on “Navbar”.

Next, open the src/app/header/header.component.css file and add:


.nav-item{
    padding:2px;
    margin-left: 7px;
}

Next, open the src/app/footer/footer.component.html file and add:

<footer>
  <p  class="text-xs-center">© Copyright 2019. All rights reserved.</p>
</footer>

Open the src/app/footer/footer.component.css file and add:


footer {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 1rem;
    text-align: center;
}

Next, open the src/app/app.component.html file and replace its contents with the following:

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

We’re creating an application shell by using the header and footer components which means that they will be present on every page of our application. The only part that will be changed is what will be inserted in the router outlet (check out “The Application Shell” on the Angular website for more information).

Adding A Bootstrap Jumbotron

According to the Bootstrap docs:

“A Jumbotron is a lightweight, flexible component that can optionally extend the entire viewport to showcase key marketing messages on your site.”

Let’s add a Jumbotron component to our home page. Open the src/app/home/home.component.html file and add:

Angular Bootstrap Demo

This demo shows how to integrate Bootstrap 4 with Angular 7

View tutorial

The .jumbotron class is used to create a Bootstrap Jumbotron.

Adding A List Component: Using A Bootstrap Table

Now let’s create a component-to-list data from the data service and use a Bootstrap 4 table to display tabular data.

First, open the src/app/contact-list/contact-list.component.ts file and inject the data service then call the getContacts() method to get data when the component is initialized:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-contact-list',
  templateUrl: './contact-list.component.html',
  styleUrls: ['./contact-list.component.css']
})
export class ContactListComponent implements OnInit {

  contacts;
  selectedContact;
  
  constructor(public dataService: DataService) { }

  ngOnInit() {
    this.contacts = this.dataService.getContacts();    
  }
  public selectContact(contact){
    this.selectedContact = contact;
  }
}

We added two variables contactsand selectedContact which hold the set of contacts and the selected contact. And a selectContact() method which assigns the selected contact to the selectedContact variable.

Open the src/app/contact-list/contact-list.component.html file and add:

# Name Email Actions
{{ contact.id }} {{ contact.name }} {{ contact.email }}
# {{selectedContact.id}}

{{selectedContact.name}}

{{selectedContact.description}}

</div> </div>

We simply loop through the contacts array and display each contact details and a button to select a contact. If the contact is selected, a Bootstrap 4 Card with more information will be displayed.

This is the definition of a Card from Bootstrap 4 docs:

“A card is a flexible and extensible content container. It includes options for headers and footers, a wide variety of content, contextual background colors, and powerful display options. If you’re familiar with Bootstrap 3, cards replace our old panels, wells, and thumbnails. Similar functionality to those components is available as modifier classes for cards.”

We use the .table and .table-hover classes to create Bootstrap-styled tables, the .card, .card-block, .card-title and .card-text classes to create cards. (For more information, check out Tables and Cards.)

Adding A Create Component: Using Bootstrap Form Controls And Classes

Let’s now add a form to our contact-create component. First, we need to import the FormsModule in our main application module. Open the src/app/app.module.ts file, import FormsModule from @angular/forms, and add it to the imports array:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule } from '@angular/forms';

/* ... */

@NgModule({
  declarations: [
  /* ... */
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Next, open the src/app/contact-create/contact-create.component.ts file and replace its contents with the following:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-contact-create',
  templateUrl: './contact-create.component.html',
  styleUrls: ['./contact-create.component.css']
})
export class ContactCreateComponent implements OnInit {

  contact : {id, name, description, email} = {id: null, name: "", description: "", email: ""};
  
  constructor(public dataService: DataService) { }

  ngOnInit() {
  }
  
  createContact(){
    console.log(this.contact);
    this.dataService.createContact(this.contact);
    this.contact = {id: null, name: "", description: "", email: ""};

  }
}

Next, open the src/app/contact-create/contact-create.component.html file and add the following code:

Enter your contact’s ID Enter your contact’s name Enter your contact’s email Enter your contact’s description
</form> <button class="btn btn-primary" (click)="createContact()">Create contact</button> </div> </div> </div> </div>

We use the .form-group, .form-control classes to create a Bootstrap-styled form (check out “Forms” for more information).

We use the ngModel directive to bind the form fields to the components’ variable. For data binding to properly work, you need to give each form field a name.

Recommended reading: Managing Image Breakpoints With Angular by Tamas Piros

Running The Angular Application

At this step, let’s run the application and see if everything works as expected. Head over to your terminal, make sure you are in the root folder of your project then run the following command:

$ ng serve

A live-reload development server will be running from the http://localhost:4200 address. Open your web browser and navigate to that address. You should see the following interface:


Angular Bootstrap demo: Home page
(Large preview)

If you navigate to the Contacts page, you should see:


Angular Bootstrap Demo: Contacts Page
(Large preview)

If you navigate to the “Create contact” page, you should see:


Angular Bootstrap Demo: Create contact page
(Large preview)

Conclusion

In this tutorial, we’ve seen how to create a simple Angular application with a Bootstrap interface. You can find the complete source code on GitHub and see the live example here.

Smashing Editorial
(dm, il)

Source: Smashing Magazine, Styling An Angular Application With Bootstrap

Collective #493

dreamt up by webguru in Uncategorized | Comments Off on Collective #493



C493_leon

Leon

Leon is an open-source personal assistant who can live on your server.

Check it out












C493_meteorite

Meteorite

Like an assistant for your GitHub notifications, Meteorite helps you to focus on the most important issues and pull requests.

Check it out





C493_7

Get Ready for Priority Hints

Read about the new experimental feature known as Priority Hints now available through an Origin Trial in Chrome Beta which will allow you to tell the browser how resources should be prioritized.

Read it




C493_pong

Pong

Grégoire Divaret-Chauveau made a fun variation of Pong, where you are the ball.

Check it out



Collective #493 was written by Pedro Botelho and published on Codrops.


Source: Codrops, Collective #493