Lazy Loading Routes in React

By yomieluwande

As developers, when we build apps for users on the internet, it is very important to ensure that the app is served to the user in the fastest way possible.

When building React applications, it’s very common to see the size of the app grow largely due to the number of dependencies in use. This happens when a section of the app (or route) might import a large number of components that are not necessary when it first loads. This can reduce the initial load time of the app.

So how do we approach this? How do we make sure that the app only loads what is needed thereby avoiding bloat in the code?

We can do that by utilizing Lazy Loading. Lazy loading is a great way to optimize your site, and it does that by splitting your code at logical breakpoints, and then loading it once the user has done something that requires, or will require, a new block of code. This speeds up the initial load of the application and lightens its overall weight as some blocks may never even be loaded.

In React, we can lazy load components and routes by code splitting using Webpack. By splitting our app into chunks we can load & evaluate only the code that is required for the page rendered.

With all of that being mentioned, let’s go ahead and create a basic React app and demonstrate how we can lazy load routes.

Bootstrap a React app with create-react-app

We’ll be using the create-react-app CLI to bootstrap a new React app. The CLI, which was built by Facebook helps developers by creating a structured React app that works out of the box; no build configuration is needed.

Install the create-react-app tool with this command:

npm install -g create-react-app

Once the installation process has been completed, you can now create a new React app by using the command create-react-app lazy-loading-routes.

This generates a new folder with all the files required to run the React app. You can now run any of the following commands:

npm start
npm run build
npm test

The npm start command runs the app in development mode, the npm run build command builds the app for production to the build folder, and the npm test command runs the test watcher in an interactive mode.

The basic idea of the React app we are building is to have routes/components that use one or two React plugins. Without code splitting, all the React code and plugins in use will be bundled into one JavaScript file, but with code splitting, only the component/plugin needed would be loaded.

This isn’t a concern early on when our app is quite small, but it becomes an issue down the road when the app becomes quite large.

Let’s get back to building the app. The create-react-app CLI generates a working React app for us as mentioned above and that means we can starting building immediately.

First of all, let’s set up the basic routes we’ll be needing for the React app. For routing, we’ll be using react-router. You can add the react-router package to the app by running npm install react-router-dom in the terminal.

Once the installation is complete, we can now begin to create the components that will serve as the routes. For this app, we’ll be using four routes; Home, Maps, Blog, and a catch-all route that serves as a 404 page NotFound.

Navigate to the src folder inside the project directory and run the following commands:

mkdir Home Maps Blog NotFound

That will create a folder for the different components to be used. It’s basically a way to compartmentalize the React app.

Before we create the individual components to be used, let’s edit the App.js file and set up the basic routes. Open up the App.js file and edit with the following code:

// Import React and Component
import React, { Component } from 'react';
import {
    BrowserRouter as Router,
    Route,
    Switch,
    Link
} from 'react-router-dom'

// Import the Home component to be used below
import Home from './Home/Home'
// Import the Maps component to be used below
import Maps from './Maps/Maps'
// Import the Blogs component to be used below
import Blog from './Blog/Blog'
// Import the NotFound component to be used below
import NotFound from './NotFound/NotFound'
 // Import CSS from App.css
import './App.css';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();
class App extends Component {
    render () {
        return (
            <Router history={history}>
                <div>
                    <header className="header">
                        <nav className="navbar container">
                            <div className="navbar-brand">
                                <Link to="/">
                                    <span className="navbar-item">Lazy Loading Routes</span>
                                </Link>
                            </div>

                            <div className="navbar-end">
                                <Link to="/maps">
                                    <span className="navbar-item">Maps</span>
                                </Link>
                                <Link to="/blog">
                                    <span className="navbar-item">Blog</span>
                                </Link>
                            </div>
                        </nav>
                    </header>
                    <section className="content">
                        <Switch>
                            <Route exact path="/" component={Home} />
                            <Route path="/maps" component={Maps} />
                            <Route path="/blog" component={Blog} />
                            <Route path="*" component={NotFound} />
                        </Switch>
                    </section>
                </div>
            </Router>
        )
    }
}

export default App;

In the code block above, we imported React and its Component module using ES6 import, and we also imported BrowserRouter, Route, Switch and Link from react-router.
Inside the render() function, we first created a view which the user can use to navigate the different routes and then the component holds the different routes and the components that responds to them.

The App.css file should be edited with the following code:

.header {
  background-color: #000;
  padding-top: 15px;
}
.navbar {
  background-color: #000;
}
.navbar-item {
  color: white !important;
}
.content {
  margin-top: 50px;
}

Let’s continue with the individual components, navigate into the Home folder and create the following files: Home.js and Home.css. Open up the Home.js file and edit with the following code:

import React, { Component } from 'react'
import './Home.css'
import Button from '../NavButton/NavButton'

class Home extends Component {
    render () {
        return (
            <div className="container">
                <section className="section">
                    <div className="container">
                        <h1 className="title">Lazy Loading</h1>
                        <h2 className="subtitle">
                            A simple app to demonstrate how lazy loading routes in React works.
                        </h2>
                        <section className="bottom">
                            <Button name="Go to About page" link="/about" />
                            <Button name="Go to Blog page" link="/blog" />
                        </section>
                    </div>
                </section>

            </div>
        )
    }
}

export default Home

In the code block above, we basically just created the view for the Home component. A Button component is used, although it is yet to be created in this tutorial, it takes a prop of name and link. We also imported styles from the Home.css file. Let’s write the CSS for that file.

.subtitle {
    margin-top: 10px !important;
}
.bottom {
    margin-top: 300px;
}
.bottom a {
    margin-right: 10px;
}

Next up is the Maps route, The maps page simply shows a Google map of a location using the google-map-react React plugin.
Navigate to the Maps folder and create the following files: Maps.js and Maps.css. Open up the Maps.js file and edit with the following code:

import React, { Component } from 'react'
import './Maps.css'
import GoogleMapReact from 'google-map-react';

const MapsView = ({ text }) => (
    <div style={{
        position: 'relative', color: 'white', background: 'red',
        height: 40, width: 60, top: -20, left: -30, textAlign: 'center', paddingTop: '5px'
    }}>
        {text}
    </div>
);

class Maps extends Component {
    static defaultProps = {
        center: {lat: 6.5244, lng: 3.3792},
        zoom: 11
    };

    render () {
        return (
            <div className="container">
                <p>This page is simply a page that shows a Google Map view of a location. Play around with the coordinates to get a different view</p>
                <div className="map-container">
                    <GoogleMapReact
                        defaultCenter={this.props.center}
                        defaultZoom={this.props.zoom}
                    >
                        <MapsView
                            lat={6.5244}
                            lng={3.3792}
                            text={'Your Location'}
                        />
                    </GoogleMapReact>
                </div>
            </div>
        )
    }
}

export default Maps

In the code block above, we first imported React, and it’s Component module. The google-map-react plugin is also imported. The MapsView() function takes in a parameter of text and puts that text in a div.

The next thing is the ES6 class named Maps that extends the component module from react. Inside the Maps component, we set some default props value by using the defaultProps object and the render() function contains the view and the GoogleMapReact component. If you’d like to read more on the google-map-react plugin, you can do that here.

Let’s write the CSS for the Maps.css file. Open up the file and type in the following:

.map-container {
    height: 400px;
}

The next component is the Blog component, which uses a React plugin called react-markdown to render markdown into pure React components.
Navigate to the Blog folder and create the Blog.js file. Open up the Blog.js file and edit with the following code:

import React, { Component } from 'react'
import ReactMarkdown from 'react-markdown'

class Blog extends Component {
    constructor(props) {
        super(props);

        this.state = {
            markdownSrc: [
                '# Lazy Loading Routes with ReactnnWhy do we need to lazy load routes?.nn* Reduce code bloatn* Avoid loading all components at the same time ',
                'n* React app loads faster',
                'n* Load only the component that is needed and preload the othersn',
                'n## A quotenn<blockquote>n    A man who splits his code ',
                'is a wise man.n</blockquote>nn## How about some code?n',
                '```jsnimport React, { Component } from 'react';nimport asyncComponent from './AsyncComponent'',
                'nnimport {n' +
                '    BrowserRouter as Router,n' +
                '    Route,n' +
                '    Switch,n' +
                '    Linkn' +
                '} from 'react-router-dom'n```nnn'
            ].join(''),

            htmlMode: 'raw'
        };
    }
    render () {
        return (
            <div className="container">
                <ReactMarkdown source={this.state.markdownSrc} />
            </div>
        )
    }
}

export default Blog

In the code block above, we imported the react-markdown plugin and used it to render the markdown in the state.markdownSrc into a pure React component in the render() function.

The last component is the catch-all route, the NotFound route, navigate into the NotFound folder and create the NotFound.js file. Open up the NotFound.js file and edit with the following code:

import React, { Component } from 'react'

class NotFound extends Component {
    render () {
        return (
            <div className="container">
                <p>404</p>
                <p>Page not found - </p>
            </div>
        )
    }
}

export default NotFound

We used a Button component in the Home route above, let’s create the component now. In the src folder, create a folder titled NavButton and then create a file named NavButton.js inside the newly created folder. Open up the NavButton.js file and edit with the following code:

import React from 'react';
import { Link } from 'react-router-dom'

const button = {
    backgroundColor: 'white',
    padding: 10,
    color: 'black',
    borderRadius: 1,
    borderColor: 'black',
    borderWidth: 2,
    borderStyle: 'solid'
}

const Button = (props) => {
    return (
        <Link to={props.link}>
            <span style={button}>{props.name}</span>
        </Link>
    )
}

export default Button

In the code block above, we created a functional stateless component that builds a view for a button. The component is a button that helps with navigation in the React app, and that is achieved by using react-router which is imported at the top of the file.
The Button component takes in two props; link and name. The link prop is used to determine what route to navigate to, and the name prop is used to display a text within the button.

Right now, you can run the app to see the progress. To see the app in development mode, run the command npm start in your terminal and you should see a homepage similar to the one below.

Now that we know the app works fine, let’s do some analysis and see how the app loads all the JavaScript code we’ve written. Run the command npm run build in your terminal to build the app for production.

As you can see from above, all the JavaScript code is bundled into one file main.....js with a relatively small size. This is quite okay but can prove problematic if the size of the JavaScript file becomes too large. Let’s see how we can fix this with code splitting.

Code Splitting

The reason why we are here. How do we implement code splitting in a React app? This can be done by using Webpack and since create-react-app already ships with Webpack, there will be no need for extra config or ejecting create-react-app.

Let’s take a look at the routes setup we defined up there:

import Home from './Home/Home'
import Maps from './Maps/Maps'
import Blog from './Blog/Blog'

<Switch>
    <Route exact path="/" component={HomeComponent} />
    <Route path="/maps" component={MapsComponent} />
    <Route path="/blog" component={BlogComponent} />
    <Route path="*" component={NotFound} />
</Switch>

With the current setup above, the Switch component renders the route that matches the path that users navigate to by using the components above. Because we import all the components at the top, this means that all components are loaded when a user goes to a particular route, even though the rest is not needed at all.

This is where code splitting comes in. Code splitting helps to dynamically import components and only load them whenever they are needed thereby removing unnecessary JavaScript code that’s not needed. So how do we go about code splitting?

Create a file titled AsyncComponent.js in the src folder and edit with the following:

import React, { Component } from "react";
export default function asyncComponent(getComponent) {
    class AsyncComponent extends Component {
        static Component = null;
        state = { Component: AsyncComponent.Component };

        componentWillMount() {
            if (!this.state.Component) {
                getComponent().then(Component => {
                    AsyncComponent.Component = Component
                    this.setState({ Component })
                })
            }
        }
        render() {
            const { Component } = this.state
            if (Component) {
                return <Component {...this.props} />
            }
            return null
        }
    }
    return AsyncComponent;
}

The asyncComponent() function takes a parameter, getComponent which is a function that will dynamically import a given component. It will not be called until the first mount. On componentWillMount, we simply call the getComponent function that is passed in and save the dynamically loaded component in the state. Finally, we conditionally render the component if it has completed loading, if not we simply render null.

Now that we have the asyncComponent down, let’s change how we import the components in the App.js file by importing them dynamically with the asyncComponent() function. The code block below in the App.js file should be replaced with the second code block.

import Home from './Home/Home'
import Maps from './Maps/Maps'
import Blog from './Blog/Blog'
// Dynamically imported components
const Home = asyncComponent(() =>
    import('./Home/Home').then(module => module.default)
)

const Maps = asyncComponent(() =>
    import('./Maps/Maps').then(module => module.default)
)

const Blog = asyncComponent(() =>
    import('./Blog/Blog').then(module => module.default)
)

Your final App.js should look like the code block below:

import React, { Component } from 'react';
import {
    BrowserRouter as Router,
    Route,
    Switch,
    Link
} from 'react-router-dom'

import NotFound from './NotFound/NotFound'
import './App.css';
import createBrowserHistory from 'history/createBrowserHistory';
import asyncComponent from './AsyncComponent'

const Home = asyncComponent(() =>
    import('./Home/Home').then(module => module.default)
)

const Maps = asyncComponent(() =>
    import('./Maps/Maps').then(module => module.default)
)

const Blog = asyncComponent(() =>
    import('./Blog/Blog').then(module => module.default)
)

const history = createBrowserHistory();

class App extends Component {
    render () {
        return (
            <Router history={history}>
                <div>
                    <header className="header">
                        <nav className="navbar container">
                            <div className="navbar-brand">
                                <Link to="/">
                                    <span className="navbar-item">Lazy Loading Routes</span>
                                </Link>
                            </div>

                            <div className="navbar-end">
                                <Link to="/maps">
                                    <span className="navbar-item">Maps</span>
                                </Link>
                                <Link to="/blog">
                                    <span className="navbar-item">Blog</span>
                                </Link>
                            </div>
                        </nav>
                    </header>

                    <section className="content">
                        <Switch>
                            <Route exact path="/" component={Home} />
                            <Route path="/maps" component={Maps} />
                            <Route path="/blog" component={Blog} />
                            <Route path="*" component={NotFound} />
                        </Switch>
                    </section>
                </div>
            </Router>
        )
    }
}

export default App;

Now that we’ve implemented code splitting, let’s do some analysis and see how the app bundles the JavaScript code now. Run the command npm run build in your terminal to build the app for production.

As you can see from above, our code is now being separated into different chunks, and the React will now load only the component needed for a path as opposed to loading everything. That’s the power of code splitting.

Conclusion

In this tutorial, we saw how to avoid code bloat by implementing code splitting. We wrote code to dynamically import components and only load them when needed.

I should mention that if you’d want to avoid all this hassle, you can use the react-loadable plugin. It is a higher order component that takes care of loading components with promises.

If you’d like to see the complete React app and play around with it, you can check it out here.

Source:: scotch.io

Node.js Weekly Update - October 13

By Tamas Kadlecsik

Node.js Weekly Update - October 13

Below you can find RisingStack‘s collection of the most important Node.js updates, projects & tutorials from this week:

Node v8.7.0

These are the latest updates of Node.js v8.7.0:

deps:

  • update npm to 5.4.2
  • upgrade libuv to 1.15.0
  • update V8 to 6.1.534.42

dgram:

  • support for setting dgram socket buffer size

fs:

  • add support O_DSYNC file open constant

util:

  • deprecate obj.inspect for custom inspection

tools, build:

  • there is a fancy new macOS installer

Added new collaborators:

  • bmeurer – Benedikt Meurer
  • kfarnung – Kyle Farnung

How to Perform AWS Security Scanning and Configuration Monitoring?

AWS (Amazon Web Services) provides a robust cloud platform to host your application & infrastructure, but security is something you got to take care of yourself.

There are many incidents where attacker hacks the AWS account and abuse it for their purpose or just for fun. So how do you ensure you’ve taken all the necessary steps to protect an AWS account? Find out from this post!

An Introduction to Mongoose for MongoDB and Node.js

Mongoose is a JavaScript framework that is commonly used in a Node.js application with a MongoDB database.

In this article, you’re going to be introduced to Mongoose and MongoDB, and more importantly you’ll learn where these technologies fit in to your application.

The Future of Microservices Monitoring & Instrumentation

The future of microservices monitoring depends on what kind of solutions become standardized in the industry and what new features will we see in the future that will make your applications much better.

In this article I theorize what are these new monitoring features and what can we expect in 2018.

Storing Geo-Positioning Data with Google Maps, Node.js and MongoDB

The Google Maps API allows you to use most of the features available to create applications with the ability to retrieve the latitude and longitude of an address, add a marker to a map, create an area (a polygon or a circle) and calculate the distance between two points, and more.

How to Set Up Airbrake Error Monitoring for Your JavaScript App

Testing our codes before putting them into production environment is of utmost importance. And we test every possible path a user could follow on every conceivable browser. Right?

Thankfully, there are services out there to help us diagnose and resolve issues that may have slipped through the infinitesimal cracks in our diligent quality testing procedures; Error Monitoring to the rescue!

Deploy a Node.js Bitblog in 3 Steps

In this blogpost, you’ll see how to install and deploy a Bitblog app built on Node.js. Install this blog and monetize your content with crowd-sourced cryptocurrency mining. Think of it as an alternative to advertising and start generating your blog posts today.

Node.js Weekly Update - October 13

Node.js Scaffolding and Habitat Builder

One of the most useful features of Habitat is Scaffolding – these allow you to package your application with Habitat with very minimal code. They enable you to rapidly (within minutes) package an application and export it to whatever format you need.

One of the most popular Habitat Scaffolding is the Node.js Scaffolding. Ready to get started?

How to gracefully handle failures in a Node.js API client

There are two facts of life: you breathe air, and errors will occur in your programs… But don’t you worry, because in this article you’ll be guided through how to add better handling of failures to the ButterCMS JavaScript API client.

By the end of this article, you will hopefully have a better understanding of how to deal with failure in your own API clients.

Node.js User Survey

Take the Node User Survey to help them shape our community and project through 2018.

Build Microservices with Node.js, London November 9th-10th

Are you considering microservices for your organization? Or would you like to understand microservies better, with hands-on experience in Node.js? Then check out our two days of training to master microservices with Node.js.

Previously in the Node.js Weekly Update

In the previous Node.js Weekly Update we collected articles about Trace becoming Keymetrics, how to deploy a REST API using Serverless, Express and Node.js, how to use Nest.js for building Node.js web applications, a crash course on Serverless, how to protect your npm account, and much more.

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

Creating GraphQL Subscriptions in Express

By John Kariuki

Introduction

This section focuses on creating realtime applications using GraphQL, and the best way to achieve that is through subscriptions. The code in this section is a continuation of Part 1 of this series, and I would advise going through it before moving forward. This is a critical and essential part to future implementation of GraphQL subscriptions on a React client using Apollo.

GraphQL subscriptions are a way to push data from the server to the clients that choose to listen to real time messages from the server. Subscriptions are similar to queries in that they specify a set of fields to be delivered to the client, but instead of immediately returning a single response, a result is sent every time data is published to a topic.

A common use case for subscriptions is notifying the client side about particular events, for example the creation of a new object, updated fields and so on.

Setup

We will continue with the same application structure from Part 1.
The process of setting up a GraphQL server with subscriptions involves:

  • Declaring subscriptions in the schema.
  • Setup a PubSub instance that our server will publish new events to.
  • Hook together the PubSub event and the GraphQL subscription.
  • Setting up SubscriptionServer, a transport between the server and the clients.

We will use the PubSub implementation from graphql-subscriptions, and we will connect it to subscribe executor of GraphQL, and publish the data using the subscriptions-transport-ws (a WebSocket server and client library for GraphQL that can be used directly in a JavaScript app or wired up to a fully-featured GraphQL client like Apollo or Relay). The diagram below shows a general overview of the flow of information using subscriptions.

Declaring Subscriptions in the Schema

Adding subscriptions to the schema is similar to adding queries or mutations by specifying the operation type and the operation name. In the following snippet, we declare a subscription and an operation called channelAdded.

// src/schema.js
...
# The subscription root type, specifying what we can subscribe to
type Subscription {
    channelAdded: Channel    # subscription operation.
}
...

Subscription Resolver

We create a resolver just like queries and mutations, but instead of function, we pass an object with a subscribe field and a subscription resolver method. The subscription resolver method must return AsyncIterator, which is provided by the asyncIterator method of your PubSub.

// src/resolvers.js
import { PubSub } from 'graphql-subscriptions';
...
const pubsub = new PubSub(); //create a PubSub instance
const CHANNEL_ADDED_TOPIC = 'newChannel';
export const resolvers = {
...
Mutation: {
    addChannel: (root, args) => {  //Create a mutation to add a new channel.
      const newChannel = { id: String(nextId++), messages: [], name: args.name };
      channels.push(newChannel);
      pubsub.publish(CHANNEL_ADDED_TOPIC, { channelAdded: newChannel });  // publish to a topic
      return newChannel;
    }
  },
  Subscription: {
    channelAdded: {  // create a channelAdded subscription resolver function.
      subscribe: () => pubsub.asyncIterator(CHANNEL_ADDED_TOPIC)  // subscribe to changes in a topic
    }
  }
}

What does the above snippet do?

We construct an instance of PubSub to handle the subscription topics for our application using PubSub from graphql-subscriptions.
In our mutation where we add a new channel, we also publish it to the newChannel topic; it will then be received by clients that are subscribed to this topic.

Finally, we declare a subscription with an operation channelAdded which will map to the same in our schema and returns an AsyncIterator that will emit the messages to send over to the client.

Setting Up a Subscriptions Server

The last step is to add subscription support to our GraphQL server through WebSockets using subscriptions-transport-ws package, since we can’t push frequent updates from the server to the client over HTTP. We begin by importing the necessary packages.

// server.js
...
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
...

We then open the WebSocket in our GraphQL server first by wrapping the Express server with createServer, and then using it to set up a WebSocket to listen to GraphQL subscriptions.

// server.js
// Create an express server.
const server = express();
...
// Wrap the express server.
const ws = createServer(server);
ws.listen(PORT, () => {
  console.log(`GraphQL Server is now running on http://localhost:${PORT}`);

  // Set up the WebSocket for handling GraphQL subscriptions.
  new SubscriptionServer({
    execute,
    subscribe,
    schema
  }, {
    server: ws,
    path: '/subscriptions',
  });
});

We then configure GraphiQL to use the subscriptions web socket we setup.

// server.js
...
server.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
  subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions` // subscriptions endpoint.
}));
...

Testing

We then navigate to http://localhost:7900 in our browser and test out the subscription. We should be presented with the message:

“Your subscription data will appear here after server publication!”

We then open another browser window and create a mutation that creates a new channel. When the mutation operation is successful, we should see the results immediately in the subscription window.

Conclusion

With advancing technology, most users are more comfortable receiving immediate results rather than waiting for reloading pages and this is achieved by the implementation of realtime systems. GraphQL ensures realtime transfer of minimal amount of data. This allows for development of applications that are extremely fast in meeting user needs.

Source:: scotch.io

Overlay Glasses/Masks on Avatars with Vue.js and Cloudinary

By Prosper Otemuyiwa

Deep Learning, a subset of machine learning, helps break down tasks in ways that makes all kinds of machine assists seem possible. With deep learning, it is now possible to do image recognition by machines. Instead of hand-coding software programs with a specific set of instructions to accomplish a particular task, the machine is trained using large amounts of data and algorithms that give it the ability to learn how to perform the task.

Even though you might posses the technical know-how to train models to identify images, and perform some next level facial attribute detection, you now can leverage existing cognitive services to do your bidding.

What We’ll Build

In this article, we’ll build a demo app with Cloudinary and Microsoft Cognitive service in which users can test different glasses and masks to see it looks on them before making a purchase.

Applying deep learning to enhance our business? Yes, we are!

What is Cloudinary?

Cloudinary is a cloud platform that provides solutions for image and video management, including server or client-side upload, a huge range of on-the-fly image and video manipulation options, quick content delivery network (CDN) delivery and powerful asset management options.

Cloudinary enables web and mobile developers to address all of their media management needs with simple bits of code in their favorite programming languages or frameworks, leaving them free to focus primarily on their own product’s value proposition.

Let’s Get Started

Step 1: Create a Cloudinary Account

Sign up for a free Cloudinary account.

Once you are signed up, you will be redirected to the dashboard where you can get your credentials.

Take note of your Cloud name, API Key and API Secret

Step 2: Set Up A Node Server

Initialize a package.json file:

 npm init

Install the following modules:

 npm install express connect-multiparty cloudinary cors body-parser --save

express: We need this module for our API routes
connect-multiparty: Needed for parsing http requests with content-type multipart/form-data
cloudinary: Node SDK for Cloudinary
body-parser: Needed for attaching the request body on express’s req object
cors: Needed for enabling CORS

Step 3: Activate Advanced Facial Attributes Detection Add-on

Go to the dashboard add-ons section. Click on Rekognition Celebrity Detection Add-on and select the Free Plan.

Note: You can change to other plans as your usage increases.

Step 4: Identify Facial Attributes

Create a server.js file in your root directory. Require the dependencies we installed:

const express = require('express');
const app = express();
const multipart = require('connect-multiparty');
const cloudinary = require('cloudinary');
const cors = require('cors');
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

const multipartMiddleware = multipart();

Next, configure Cloudinary:

cloudinary.config({
    cloud_name: 'xxxxxxxx',
    api_key: 'xxxxxxxx',
    api_secret: 'xxxxxxx'
});

Replace xxxxxx with the real values from your dashboard.

Add the route for uploading. Let’s make the route /upload.

app.post('/upload', multipartMiddleware, function(req, res) {
  // Upload to Cloudinary
  cloudinary.v2.uploader.upload(req.files.image.path,
    function(error, result) {
      res.json(result);
    },
    // Specify Transformation & Facial Attributes Detection
    {
      transformation: [
        { width: 700, radius: "max", crop: "scale" },
        { flags: "region_relative", gravity: "adv_eyes", overlay: req.body.item, width: "1.7" }
      ]
    });

Quickly take a look at the overlay parameter. It takes in a value of req.body.item. In this app, the values are either glasses or harlequinmask.

Note: I uploaded two photos to my Cloudinary account and made sure they were renamed glasses and harlequinmask. These are the two images we will use as overlays in this app.

harlequinmask and glasses respectively. Go ahead and upload them to your account too.

The Advanced Facial Attribute Detection add-on detects specific facial attributes, including the exact position of the eyes of each face in a photo. Based on this information, Cloudinary can position overlays on top of all the detected eye pairs in an image.

To smartly overlay the glasses or harlequinmask on top of the detected eye pairs in the image, the user uploads, the overlay parameter is set to the ID of the harlequinmask or glasses image and the gravity parameter is set to adv_eyes. We also set the _regionrelative flag together with a 1.7 width to scale the overlay to 170 percent of the width of the detected eyes, and resize the image to an oval thumbnail with a width of 700 pixels.

Once a user makes a POST request to the /upload route, the route grabs the image file from the HTTP request, uploads to Cloudinary, identifies the pair of eyes and overlays them with whatever option the user chooses (either glasses or harlequinmask) and returns the right URL.

Note: The Advanced Facial Attribute Detection add-on is an integrated face detection solution that utilizes Microsoft Cognitive Services. Microsoft Cognitive Services provides high precision face location detection with state-of-the-art, cloud-based algorithms that can detect up to 64 human faces in an image. The detected faces are returned with rectangles (left, top, width and height) indicating the location of faces in the image in pixels, the exact position details of the eyes, mouth, eyebrows, nose and lips, as well as a series of face-related attributes from each face, such as pose, gender and age.

Test the functionality with Postman.

Step 5: Build the Frontend

We’ll use the progressive framework, [Vue.js] to quickly flesh out the frontend. Let’s get started by installing the CLI:

 npm install -g vue-cli

Next, create a simple Vue project using the Vue CLI tool we installed:

vue init simple productshowcase

Inside the productshowcase directory, create an index.html file and add the following code to it:

<!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
  <div id="app">

    <div class="container" style="margin-top: 3%; margin-left: 2%;">
      <div class="col-md-6">
        <div>
          <div class="col-md-6">
          <img src="http://res.cloudinary.com/unicodeveloper/image/upload/v1505797868/glasses.png" width="200" height="100" />
          <span> Glasses </span>
          </div>
          <div class="col-md-6">
          <img src="http://res.cloudinary.com/unicodeveloper/image/upload/v1505794374/oie_transparent.png" width="200" height="100" />
          <span> Harlequin Mask </span>
          </div>
        </div>

        <hr />

        <form enctype="multipart/form-data" @submit.prevent="onSubmit">
          <div class="form-group">
            <select class="form-control" name="item" v-model="model.item">
              <option disabled value="">Choose an item</option>
              <option value="glasses"> Glasses </option>
              <option value="harlequinmask"> Harlequin Mask </option>
            </select>
          </div>
          <div class="form-group">
            <label for="">File:</label>
            <input type="file" class="form-control" accept="image/*" name="image" v-on:change="upload($event.target.files)">
          </div>
          <div class="form-group">
            <button class="btn btn-primary" >Upload</button>
            {{ loading }}
          </div>
        </form>
      </div>

      <div class="col-md-4">
        <div class="col-md-6" style="margin-top: 20%;">
          <img id="originalface" class="img-responsive" alt="" width="600" height="600">
        </div>
        <div class="col-md-6" style="margin-top: 20%;">
          <img :src="maskedface" class="img-responsive" alt="" width="400" height="400">
        </div>
      </div>
    </div>
  </div>

  <script>
    new Vue({
      el: '#app',
      data: function() {
        return {
          model: {
           text: '',
           image: null,
           item: ''
          },
          maskedface: null,
          loading: '',
        }
      },
      methods: {
        upload: function(files) {
          this.model.image = files[0]
          this.showPreview(files[0]);
        },
        showPreview: function(file) {
          var reader = new FileReader();
          reader.onload = function (e) {
              document.getElementById("originalface").src = e.target.result;
          };
          // read the image file as a data URL.
          reader.readAsDataURL(file);
        },
        onSubmit: function() {
          // Assemble form data
          const formData = new FormData()
          formData.append('image', this.model.image);
          formData.append('item', this.model.item);
          this.loading = "Processing....Please be patient."

          // Post to server
          axios.post('http://localhost:3333/upload', formData)
          .then(res => {
            // Update UI
            this.maskedface = res.data.url
            this.loading = ''
          })
        }
      }
    })
  </script>
</body>
</html>

Now, run the app.

What’s going on here? Don’t be scared, let’s step through the code. First we have a form for uploading of images.

  <form enctype="multipart/form-data" @submit.prevent="onSubmit">
          <div class="form-group">
            <select class="form-control" name="item" v-model="model.item">
              <option disabled value="">Choose an item</option>
              <option value="glasses"> Glasses </option>
              <option value="harlequinmask"> Harlequin Mask </option>
            </select>
          </div>
          <div class="form-group">
            <label for="">File:</label>
            <input type="file" class="form-control" accept="image/*" name="image" v-on:change="upload($event.target.files)">
          </div>
          <div class="form-group">
            <button class="btn btn-primary" >Upload</button>
            {{ loading }}
          </div>
   </form>

We bind the upload form to an upload event handler. There is a change event attached to the select file button. Once a user selects a file, the showPreview method called in the Vue instance below is invoked. This method shows a thumbnail preview of the image about to be uploaded.

Thumbnail preview of the image about to be uploaded.

Check out the methods, model and data properties on our Vue instance.

  new Vue({
      el: '#app',
      data: function() {
        return {
          model: {
           text: '',
           image: null,
           item: ''
          },
          maskedface: null,
          loading: '',
        }
      },
      methods: {
        upload: function(files) {
          this.model.image = files[0]
          this.showPreview(files[0]);
        },
        showPreview: function(file) {
          var reader = new FileReader();
          reader.onload = function (e) {
              document.getElementById("originalface").src = e.target.result;
          };
          // read the image file as a data URL.
          reader.readAsDataURL(file);
        },
        onSubmit: function() {
          // Assemble form data
          const formData = new FormData()
          formData.append('image', this.model.image);
          formData.append('item', this.model.item);
          this.loading = "Processing....Please be patient."

          // Post to server
          axios.post('http://localhost:3333/upload', formData)
          .then(res => {
            // Update UI
            this.maskedface = res.data.url
            this.loading = ''
          })
        }
      }
    })

When the form is submitted, it calls the onSubmit function in our Vue method. The onSubmit method then makes a post request to the backend and returns data back to the frontend.

The data returned is the modified image with the overlay. And this reflects on the UI.

Harlequin Mask selected and an Image of Rihanna uploaded.

Glasses selected and an Image of Christian Nwamba, a.k.a codebeast, uploaded!

Feel free to check out the source code here.

Conclusion

We just performed a facial attribute detection together with an Image overlay transformation with Cloudinary. The options are limitless as to what you can do with the information in this tutorial.

Go forth and enhance your business with products that users will love. And Oh you don’t have to spend time building them, Cloudinary’s got you!

Source:: scotch.io

A Look at Bootstrap 4's New Reset: Reboot.css

By Nicholas Cerminara

Reset

I’ve been wanting to write this article for a long time – since August 25, 2015 to be exact. It’s been in the back of my mind and bugging me forever. I’m glad I’m finally going to sit down and bang this post out despite there probably being a ton of great resources out there on this.

If you don’t already know, Bootstrap is an awesome front-end framework! I’ve been using it for a really long time, and I think it helps out all types of developers. It doesn’t matter if you are front-end or back-end developer, complete noob or an advanced coding robot from the future. Bootstrap is a robust and flexible set of tools that helps you code awesome websites for all use cases.

Bootstrap 4 recently came out of alpha and into Beta after being in it that super-early build for like a year. If you’re thinking, “Wow, it’s taking forever and is still in beta…“, don’t. What the Bootstrap core team is doing is no small task. They’re literally pushing out code that is used by gazillions of people and websites (seriously, like over 20% of the web)! On top of that, CSS exist in a land where every individual developer is super opinionated about the right and wrong way to do things. It’s no easy task.

With all that being said…

Let’s talk about a really neat new feature in Bootstrap 4 called Reboot. In this post, I’ll blab a bit about the history of resets, Bootstrap, some cool features of Reboot, and how you can start using it today.

Reboot.css

Reboot in the simplest terms possible is Bootstrap 4’s “reset”. It’s a little bit different than your typical reset though.

The Eric Meyer Reset

I’m pretty sure the term “reset” first came around when Eric Meyer, a guy who is kind of like the godfather of CSS, came out with a stylesheet to literally reset all browsers to look the exact same. The problem with this is, it really reset things. Literally everything looked the same regardless of the element. Elements like h1s were the same as h2s. This meant front-end people would have to build their own base styles. This is both a good and bad thing.

Many front-end people in the early days would build out their own “resets” on top of this since their base styles stayed consistent. This also unfortunately left some noobs / beginners in the dust who never really grasped the importance of having a base. For example, people who would do something like this:

/* Heading 2 Base Styles */
h2 {
    color: #13335f;
    font-weight: 700;
    margin: 10px 0 20px;
    font-size: 30px;

    FLOAT: LEFT;   /* Just kill me. why.......... */
}

This went on for what felt like forever. If you’re old enough to have lived through these small hustle projects, congratulations on being a survivor. In my humble opinion, a lot of back-end developers hate CSS to this day because of dealing with things like this.

Normalize.css

So after these dark-ages of having to deal with some really messed up stylesheets, a lot of people’s personal “base” resets started becoming popular and shared. The most popular was definitely normalize.css.

Normalize was different because it reset your browser styles and gave you some dead-simple, super pretty base styles. It made building some nice projects a breeze. It gained serious popularity.

Normlalize.css doesn’t use border-box by default though, requiring that you add it somehow. I can’t imagine doing any front-end development without this property. Normalize.css is still active today, widely used, and you can you can still easily swap this. I honestly don’t know why it’s not default for all elements, but I’m sure there’s some good reason since many projects still use normalize as their go-to reset.

Incoming Reboot.css

Now comes Reboot.css. Reboot.css is like a normalize.css 2.0 in my opinion. It has some awesome “reset” type features:

  • It uses box-size: border-box; by default on all elements.
  • “Resets” browser styles for consistent cross-browser development.
  • Keeps a simple and natural base-style on elements.
  • Carries a little bit of an opinion on how to write your CSS for the modern web.
  • Made by the Bootstrap people (lots of trust)

Bootstrap 4 puts all this into a single page making it dead-simple to use.

The Eventual Future of Frameworks

CSS is becoming more and more featured-pack by the day. Things like “Flexbox” or “Grid” are getting wider browser-adoption making frameworks less necessary for doing complex layouts easily.

On top of that, you have some ridiculously cool tools like LESS, SASS/SCSS, and PostCSS becoming the default go-to for writing styles making it easier to automate tedious tasks such as creating a set of button styles.

In enough time, I can easily see frameworks becoming 95% smaller or the birth of a new, super simple, bare-naked framework that gains massive popularity. We’re not quite there yet, but, heck, that might be even be Reboot one day.

Get Started with Reboot.css Now

So, how can we test Reboot.css out now and actually see what the heck it is?

You could go to the Official Bootstrap 4 Documentation and just dig through the docs and get going, or you can just mess with this codepen I made. It has every single element on a single webpage and lets you easily swap out different resets to see the difference.

If you want to just find the CSS and test yourself, check these resources:

Box-Sizing: Border-Box Default

If you read the intro paragraphs, you’ll already know this. Reboot.css uses box-sizing: border-box; by default for all elements. This in my opinion is the most distinguished difference between normalize.css.

So, it’s safe to say it’s “responsive ready” out-of-the-box. Here’s what it looks like at the top of the file:

*,
*::before,
*::after {
    box-sizing: border-box;
}

If you’re familiar with this, it’s taken from Paul Irish‘s arguably super famous post.

Use “rems” for Sizing and Spacing

A Quick REM Demo

REMs are just not for font-sizing, it can be used for all spacing. To show you just how much Reboot.css embraces this, checkout the demo below:

Unit of Measurement Differences Explained

CSS3 introduced a new unit of measurement called rem. There’s kind of a huge debate amongst us nerds on the best use for sizing on the web. These rems have a pretty darn good solution to the whole debate. It all comes down to accessibility for users (resizing of font-sizes / screen-sizes) and maintainability / consistency for front-end developers.

Here it is summarized:

  • px: Good for consistency, bad for accessibility
  • em: Good for accessibility, just okay for maintainability / consistency
  • rem: Good for accessibility, really good for maintainability / consistency

That’s a huge TL;DR: of the whole debate, but there’s a ton of good resources to learn a bit more about units of measurement.

How REMs Work

Let’s assume you know nothing more than pixels as a unit of length. Going to try to break this down in laymen terms without code.

So, you know that 100 pixels is always going to be 100 pixels long regardless if you’re have your operating system show large fonts, are on a 4k monitor, or those 100 pixels are in a 1000 or 5000 pixel sized container. It doesn’t matter. 100 pixels is 100 pixels. This is good for consistency but bad for usability since it doesn’t scale well to user-specifc preferences.

The unit em was first introduced to try and help with this “scaling” issue by being a computed unit of measurement. This means the sizing is always relative to something, in this case the parent. So in a basic example, you could say: “Instead of being 100px long, be 10% of the 1000px long container” or 0.1em“. This way if the container was resized by the user / device / system / whatever it would remain consistent in perceived length.

This is cool, except it gets real crazy when you have an em be relative to another em. Or worse, an em that is relative to an em that is relative to an em. Things get complicated and messy and become impossible to deal with overtime.

I like to think of rems as a simple em. Everything is always relative to the root (aka, the body tag or html tag). So if your root was 1000px, your length is 0.1rem regardless of container, settings, whatever.

Native Font Family

Have you ever designed a website to see slight differences between operating systems? Mac’s probably look the best but sometimes fonts will look not as crisp on Windows?

This is because of how systems render fonts. Reboot.css embraces using whatever their native font stack is to the operating system.

This actually means 2 things.

  1. Near-zero load time for the default font
  2. Uses the font the user wants / looks best for them

Here’s the code. Check-out all the fallbacks!

/* SCSS Variable */
$font-family-sans-serif:
    // Safari for OS X and iOS (San Francisco)
    -apple-system,
    // Chrome >= 56 for OS X (San Francisco), Windows, Linux and Android
    system-ui,
    // Chrome < 56 for OS X (San Francisco)
    BlinkMacSystemFont,
    // Windows
    "Segoe UI",
    // Android
    "Roboto",
    // Basic web fallback
    "Helvetica Neue", Arial, sans-serif !default;

/* CSS */
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";

Margin Top is Dead

Okay, maybe it’s not dead, but reboot.css makes the following elements no longer have any top margin:

  • h1
  • h2
  • h3
  • h4
  • h5
  • h6
  • p
  • ul
  • ol
  • dl
  • pre

This actually makes a ton of sense. I can vouche for this method. I never use margin-top in any of my base css that I have ever done. It makes things fall into place a lot easier when things are CMS powered and the content can be anything. I would even suggest adding table to this list.

Clean, Dead-Simple Base Elements

Reboot also provides a clean and naked style to all common elements. Things like blockquote, tables, forms and much more. This goes a bit more to be able to have clean and simple form fields to get up and running with.

Reboot.css Form Stlyes

Mobile Fast Click

By default Reboot.css uses touch-action: manipulation to speed up any delay that might exist for touch users.

Here’s the full code:

a,
area,
button,
[role="button"],
input:not([type=range]),
label,
select,
summary,
textarea {
  -ms-touch-action: manipulation;
      touch-action: manipulation;
}

You can see that clicking links, buttons, and form fields will be a lot quicker and responsive on touch devices.

Conclusion

Overall, I would say Reboot.css is a great project and continuation of standardizing the modern web with familiar web practices. You can learn more about reboot.css at the following links:

Source:: scotch.io