Basic Tips in Finding a Suitable Web Host

Post pobrano z: Basic Tips in Finding a Suitable Web Host

Statistics show that more than 30,000 sites are hacked each day, and this shows a problem that could be traced back to the security measures applied by the sites and their hosts. Choosing a good hosting provider is a decision that will help to prevent security breaches that might cause the site a big loss. You need to choose a hosting provider that will ensure regular backups and offer several layers of security to make it difficult for hackers to get through and access important files of your site.

Here are some basic tips you need to consider to choose the right web host:

Read web hosting reviews

The best place to start when you are searching for a suitable web host is reading reviews of the best web hosts. Sites like Hosting Foundry offer insightful and objective reviews of the leading web hosts, and they highlight features like security and bandwidth allocation for different packages. Choosing your web host from the list of the best companies will guarantee you access to important security features, and you will also enjoy good bandwidth allocation and speed.

Backup plans

It is important to stress that the company should have a good backup plan that will allow you to restore your site in the event of a hacking attempt. There are hosts that don’t offer this feature even as an opt-in, and this means you may lose your data permanently if someone manages to access your files.

Security features

Security is something you should not negotiate about when it comes to choosing a reliable hosting provider. A good web host should have reliable security infrastructure that is designed to shield the site against all kinds of attacks. Some of the security features you should look at include SSL certification mechanisms and firewalls. Strong security features will not only shield the site from attackers, it will also allow users to surf with confidence that their data cannot be stolen because their connections are encrypted.

Customer support

How good is the customer support of the company? This is an important factor as it will determine your experience with the company. Sometimes you will have a serious issue that can only be resolve by the technical team of the company, so the best solution would be to approach them for quick help. There are web hosts with a history of sluggish support team, so avoid those if you don’t want to inconvenience users.

Server uptime scores/reliability

A 24/7 operating web host is ideal if you would like to keep your site online and serve users without challenges. Check the server uptime score of the web host before you choose them for your project. Even one minute without connection to your site would hurt your business, especially if you expect to receive heavy traffic.

The first step in establishing a strong website is choosing the right web host. This is a decision that will determine the security and reliability your site will get, so ensure to read reviews about leading hosts to choose the one that offers the features you prefer to use on your site.

Understanding React `setState`

Post pobrano z: Understanding React `setState`

React components can, and often do, have state. State can be anything, but think of things like whether a user is logged in or not and displaying the correct username based on which account is active. Or an array of blog posts. Or if a modal is open or not and which tab within it is active.

React components with state render UI based on that state. When the state of components changes, so does the component UI.

That makes understanding when and how to change the state of your component important. At the end of this tutorial, you should know how setState works, and be able to avoid common pitfalls that many of us hit when when learning React.

Workings of `setState()`

setState() is the only legitimate way to update state after the initial state setup. Let’s say we have a search component and want to display the search term a user submits.

Here’s the setup:

import React, { Component } from 'react'

class Search extends Component {
  constructor(props) {
    super(props)

    state = {
      searchTerm: ''
    }
  }
}

We’re passing an empty string as a value and, to update the state of searchTerm, we have to call setState().

setState({ searchTerm: event.target.value })

Here, we’re passing an object to setState(). The object contains the part of the state we want to update which, in this case, is the value of searchTerm. React takes this value and merges it into the object that needs it. It’s sort of like the Search component asks what it should use for the value of searchTerm and setState() responds with an answer.

This is basically kicking off a process that React calls reconciliation. The reconciliation process is the way React updates the DOM, by making changes to the component based on the change in state. When the request to setState() is triggered, React creates a new tree containing the reactive elements in the component (along with the updated state). This tree is used to figure out how the Search component’s UI should change in response to the state change by comparing it with the elements of the previous tree. React knows which changes to implement and will only update the parts of the DOM where necessary. This is why React is fast.

That sounds like a lot, but to sum up the flow:

  • We have a search component that displays a search term
  • That search term is currently empty
  • The user submits a search term
  • That term is captured and stored by setState as a value
  • Reconciliation takes place and React notices the change in value
  • React instructs the search component to update the value and the search term is merged in

The reconciliation process does not necessarily change the entire tree, except in a situation where the root of the tree is changed like this:

// old
<div>
  <Search />
</div>

// new
<span>
  <Search />
</span>

All <div> tags become <span> tags and the whole component tree will be updated as a result.

The rule of thumb is to never mutate state directly. Always use setState() to change state. Modifying state directly, like the snippet below will not cause the component to re-render.

// do not do this
this.state = {
  searchTerm: event.target.value
}

Passing a Function to `setState()`

To demonstrate this idea further, let’s create a simple counter that increments and decrements on click.

See the Pen setState Pen by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

Let’s register the component and define the markup for the UI:

class App extends React.Component {

state = { count: 0 }

handleIncrement = () => {
  this.setState({ count: this.state.count + 1 })
}

handleDecrement = () => {
  this.setState({ count: this.state.count - 1 })
}
  render() {
    return (
      <div>
        <div>
          {this.state.count}
        </div>
        <button onClick={this.handleIncrement}>Increment by 1</button>
        <button onClick={this.handleDecrement}>Decrement by 1</button>
      </div>
    )
  }
}

At this point, the counter simply increments or decrements the count by 1 on each click.

But what if we wanted to increment or decrement by 3 instead? We could try to call setState() three times in the handleDecrement and handleIncrement functions like this:

handleIncrement = () => {
  this.setState({ count: this.state.count + 1 })
  this.setState({ count: this.state.count + 1 })
  this.setState({ count: this.state.count + 1 })
}

handleDecrement = () => {
  this.setState({ count: this.state.count - 1 })
  this.setState({ count: this.state.count - 1 })
  this.setState({ count: this.state.count - 1 })
}

If you are coding along at home, you might be surprised to find that doesn’t work.

The above code snippet is equivalent to:

Object.assign(  
  {},
  { count: this.state.count + 1 },
  { count: this.state.count + 1 },
  { count: this.state.count + 1 },
)

Object.assign() is used to copy data from a source object to a target object. If the data being copied from the source to the target all have same keys, like in our example, the last object wins. Here’s a simpler version of how Object.assign() works;

let count = 3

const object = Object.assign({}, 
  {count: count + 1}, 
  {count: count + 2}, 
  {count: count + 3}
);

console.log(object);
// output: Object { count: 6 }

So instead of the call happening three times, it happens just once. This can be fixed by passing a function to setState(). Just as you pass objects to setState(), you can also pass functions, and that is the way out of the situation above.

If we edit the handleIncrement function to look like this:

handleIncrement = () => {
  this.setState((prevState) => ({ count: prevState.count + 1 }))
  this.setState((prevState) => ({ count: prevState.count + 1 }))
  this.setState((prevState) => ({ count: prevState.count + 1 }))
}

…we can now increment count three times with one click.

In this case, instead of merging, React queues the function calls in the order they are made and updates the entire state ones it is done. This updates the state of count to 3 instead of 1.

Access Previous State Using Updater

When building React applications, there are times when you’ll want to calculate state based the component’s previous state. You cannot always trust this.state to hold the correct state immediately after calling setState(), as it is always equal to the state rendered on the screen.

Let’s go back to our counter example to see how this works. Let’s say we have a function that decrements our count by 1. This function looks like this:

changeCount = () => {
  this.setState({ count: this.state.count - 1})
}

What we want is the ability to decrement by 3. The changeCount() function is called three times in a function that handles the click event, like this.

handleDecrement = () => {
  this.changeCount()
  this.changeCount()
  this.changeCount()
}

Each time the button to decrement is clicked, the count will decrement by 1 instead of 3. This is because the this.state.count does not get updated until the component has been re-rendered. The solution is to use an updater. An updater allows you access the current state and put it to use immediately to update other items. So the changeCount() function will look like this.

changeCount = () => {
  this.setState((prevState) => {
    return { count: prevState.count - 1}
  })
}

Now we are not depending on the result of this.state. The states of count are built on each other so we are able to access the correct state which changes with each call to changeCount().

setState() should be treated asynchronously — in other words, do not always expect that the state has changed after calling setState().

Wrapping Up

When working with setState(), these are the major things you should know:

  • Update to a component state should be done using setState()
  • You can pass an object or a function to setState()
  • Pass a function when you can to update state multiple times
  • Do not depend on this.state immediately after calling setState() and make use of the updater function instead.

The post Understanding React `setState` appeared first on CSS-Tricks.

Web designers, are you keeping up with the website navigation trends?  

Post pobrano z: Web designers, are you keeping up with the website navigation trends?  

Your ability to build a website with a friendly navigation scheme just got a whole lot easier. We had a long and grueling journey through various navigation schemes. As a result, the need for responsive web design has shown us what is important and not overly complicated.

This, in turn, has given rise to a new set of best practices. Best practices we probably should have been following all along. These best practices subscribe to a minimalist line of thought. The latter is focused on the main goal of each website page.

Check these top 5 best practices out.

Best Practice #1: Implement a navigation scheme that helps a visitor get to her main goal

Visitors are often curious to see what’s new on a website. Sometimes, being able to quickly take in the latest news or updates is of great importance to them. Show what’s new up front and highlight it as such.

An attention-getting image on the home page accompanied by a CTA is an excellent way to do this.

BeClothing

A visitor might be confronted with a choice when browsing a website is quite large or complex. In this case, it can be easy for that person to get lost. A search bar at the top of the page or several CTAs placed at strategic locations can help. These can prevent this from happening and point the visitor in the right direction.

BeDietitian2

“Read More” is one good option.

BeWanderer

Best Practice #2: Always let the visitor know his or her current location

Implementing a current location element is a gold standard for website navigation.

Today’s increasingly complex eCommerce sites are good examples. It can be all too easy for users to get lost. Especially in the case of megamenus leading to a host of different product categories. A solution? Keep track of where the user currently is, where he or she has been, and where you anticipate the user might go next.

Use a contrasting color for the current location indicator. Like this, you can show users where at the website they are at the moment.

BePizza3

A mini-map of a user’s journey is one way to help the user trace back his or her steps:

BeCompany

A fixed menu on top of the page can help a user decide where to go next to further explore the website.

BeAccountant2

Best Practice #3: Use standard icons and lingo

Creativity is an asset every web designer needs. Creativity should be encouraged – except for website navigation. Cleverly designed icons can serve the same purpose as misplaced street signs. They can easily send a user off on a wild goose chase.

If you want to entertain your visitors, direct your creativity to other areas other. Stick to familiar navigation structures and elements.

How about a Hamburger menu for example? Yes! This versatile menu type can consolidate a lot of useful information on a page.

BeGSMServices

Or, maybe a cleverly shaped menu with random clickable areas? No! Menus are not there to entertain, nor should they be designed to make a user have to think.

How about a bold logo that takes you back to Home when you click it? Always a good idea.

BeCarWash

An animated logo that warps you into another dimension? No! Animated logos can be irritating, distracting, and add little or no value.

Best Practice #4: Don’t exceed 7 menu items

If you go beyond 7 menu items, people will have trouble remembering things. A crisp, clean menu is almost always user-friendly and is also good for ranking. A link serves the same purpose as a menu item, so don’t load a page down with links either, especially the home page.

“For Him” and “For Her” is all you need on this home page.

BeDenim

Stick to the most important things for the user and place their two key attractions on the top and at the bottom of the list.

BeBistro2

Best Practice #5: Choose the menu type according to the amount of content

Mindlessly following what others are doing is not recommended. This is the rule even when they appear to be following best practices.

The reason? Your website will generally have a different amount of content than other websites. You need to go with a menu type that’s a good match for the amount of content you have.

A single navigation bar may be all that’s needed. For a small shoe store specializing in seasonal wear or limited editions, this is perfect.

BeShoes

On the other hand, your online store might sell 100 or more brands of clothing for people of all ages and sizes. Then, you’ll be better served using a well-structured megamenu. A vertical collapsible menu is a good option, too.

BeStore

BeTheme – A Simple Solution

How to best cope with changing website navigation standards? Do that by sticking to simple, easy-to-follow best practices that tend to be evergreen. The easiest way to do this is to use pre-built websites. At the same time, you can keep up with web design best practices in general.

BeTheme has the largest selection of these in the industry – more than 320. They’re aligned with user expectations for every industry sector and niche.

BeMusic2

BeHerbal

Summary

Here’s a wrap-up of the website navigation best practices covered in this article:

  • Point a visitor toward her primary objective on every page
  • Make certain the visitor knows where she is at all times, where she has been, and where she is likely to go
  • Use standard icons and lingo so as not to mislead or confuse the user
  • Limit menu items to seven to avoid overwhelming the user
  • Base your menu type in accordance with the amount of content in your website
  • Use pre-built websites. They make navigating a piece of cake.

Grid to Flex

Post pobrano z: Grid to Flex

Una Kravets shows how to make layouts in CSS Grid with flexbox fallbacks for browsers that don’t support those grid properties just yet. Una writes:

CSS grid is AMAZING! However, if you need to support users of IE11 and below, or Edge 15 and below, grid won’t really work as you expect…This site is a solution for you so you can start to progressively enhance without fear!

The site is a provides examples using common layouts and component patterns, including code snippets. For example:

See the Pen Grid To Flex — Example 1 by Una Kravets (@una) on CodePen.

Direct Link to ArticlePermalink

The post Grid to Flex appeared first on CSS-Tricks.

JAMstack Comments

Post pobrano z: JAMstack Comments

JAMstack sites are often seen as being static. A more accurate mental model for them would be that they are sites which have the ability to be hosted statically. The difference might seem semantic, but thanks to the rise of many tools and services which simplify running a build and deploying to static hosting infrastructure, such sites can feel much fresher and dynamic than you might imagine, while still capable of being served from static hosting infrastructure, with all the benefits that brings.

A feature often used as an example of why a site cannot be hosted statically is comments. A comments engine needs to handle submissions, allow for moderation, and is by its very nature, „dynamic”.

Comment systems are generally thought of as quite dynamic content

Thanks to the growing ecosystem of tools available for JAMstack sites, there are solutions to this. Let’s look at an example which you could use on your own site, which:

  • Does not depend on client-side JavaScript
  • Could work with any static site generator
  • Includes moderation
  • Sends notifications when new comments need moderating
  • Bakes the comments into your site, so that they load quickly and appear in searches

This example makes use of some of the features of Netlify, a platform for automating, deploying and hosting web projects, but many of the principles could be used with other platforms.

You can see the example site here.

Stashing our content

We’ll create 2 forms to receive all of our comments at the different stages of their journey from commenter to content. When Netlify sees a <form>, it creates a unique data store for the data the form collects. We’ll make great use of that.

  • Form 1) A queue to hold all of the new comment submissions. In other words, a store to hold all comments awaiting moderation.
  • Form 2) Contains all approved comments.

The act of moderation will be somebody looking at each new submission and deciding, „yep!” or „nope!”. Those that get nope-d will be deleted from the queue. Those that are approved will be posted over to the approved comments form.

All of the comments in the approved comments form are used by our static site generator in subsequent site builds thanks to the API access Netlify gives to the submissions in our forms.

The comment form

Each page includes an HTML <form>. By adding the boolean attribute of netlify to any HTML form element in your site, Netlify will automatically generate an API for your form, and gathers all of the submissions to it for you. You’ll also be able to access the submissions via that API later. Handy!

The comments <form> on each page will look a lot like this (some classes and extra copy omitted for clarity):

<form netlify name="comments-queue" action="/thanks">
  <input name="path" type="hidden" value="{{ page.url }}">
  <p>
    <label for="name">Your name</label>
    <input type="text" name="name" id="name">
  </p>
  <p>
    <label for="email">Your email</label>
    <input type="email" name="email" id="email">
  </p>
  <p>
    <label for="comment">Your comment</label>
    <textarea name="comment" id="comment"></textarea>
  </p>
  <p>
    <button type="submit">Post your comment</button>
  </p>
</form>

You’ll may notice that the form also includes a type="hidden" field to let us know which page on the site this comment is for. Our static site generator populates that for us when the site is generated, and well use it later when deciding which comments should be shown on which page.

Submissions and notifications

When a new comment is posted via the comment form, Netlify not only stashes that for us, but can also send a notification. That could be:

  • an email
  • a Slack notification
  • a webhook of our choosing.

These give us the chance to automate things a little.

New submissions result in a notification being posted to Slack. We’ll get to see what was submitted and to which page right there in our Slack client.

To make things extra slick, we can massage that notification a little to include some action buttons. One button to delete the comment, one to approve it. Approving a new comment from a Slack notification on your phone while riding the bus feels good.

We can’t make those buttons work without running a little bit of logic which, we can do in a Lambda function. Netlify recently added support for Lambda functions too, making the process of writing and deploying Lambdas part of the same deployment process. You’ll not need to go rummaging around in Amazon’s AWS configuration settings.

We’ll use one Lambda function to add some buttons to our Slack notification, and another Lambda function to handle the actions of clicking either of those buttons.

Bring the comments into the site

With a freshly approved comment being posted to our approved comments form, we are back to using the submission event triggers that Netlify provides. Every time something is posted to the approved comments form, we’ll want to include it in the site, so we have Netlify automatically rebuild and deploy our site.

Most static site generators have some notion of data files. Jekyll uses files in a [_data] directory, Hugo has a similar data directory. This example is using Eleventy as its static site generator which has a similar concept. We’ll make use of this.

Each time we run our site build, whether in our local development environment or within Netlify through their automated builds, the first step is to pull all of our external data into local data files which our SSG can then use. We do that with a Gulp task.

Armed with a `comments.json` file which we have populated from a call to Netlify’s form submission API which grabbed all of our approved comments, our SSG can now build the site as normal and bake the correct comments right into the HTML of our pages.

Some benefits

Well that was fun, but why bother?

Yes, you could use something like Disqus to add comments to a statically hosted site via a few lines of JavaScript. But that adds an external JavaScript dependency and results in the comments about your content living far away from the content itself. And it’s only available once the JavaScript has loaded, pulled in the data and then injected it into your site.

Whereas this method results in comments that are baked right into the content of your site. They’ll show up in searches on Google and they will load as part of your site without the need for any client-side JavaScript.

Even better, they’ll be available for you to commit right into your code repository with the rest of your content, giving you more peace of mind and portability in the future.

The example site and all of its code are available to explore. You can try submitting comments if you like (although poor old Phil will need to moderate any comments on this example site before they appear, but that will just make him feel loved).

Better still, you can clone this example and deploy your own version to Netlify with just a few clicks. The example site explains how.

Just show me behind the scenes right now!

If you’d want to take a look at how things behave for the moderator of a site using this system without grabbing a copy of your own, this short video will walk through a comment being made, moderated and incorporated into the site.

The post JAMstack Comments appeared first on CSS-Tricks.

Server-Side Visualization With Nightmare

Post pobrano z: Server-Side Visualization With Nightmare

This is an extract from chapter 11 of Ashley Davis’s book Data Wrangling with JavaScript now available on the Manning Early Access Program. I absolutely love this idea as there is so much data visualization stuff on the web that relies on fully functioning client side JavaScript and potentially more API calls. It’s not nearly as robust, accessible, or syndicatable as it could be. If you bring that data visualization back to the server, you can bring progressive enhancement to the party. All example code and data can be found on GitHub.

When doing exploratory coding or data analysis in Node.js it is very useful to be able to render a visualization from our data. If we were working in browser-based JavaScript we could choose any one of the many charting, graphics, and visualization libraries. Unfortunately, under Node.js, we don’t have any viable options, so how otherwise can we achieve this?

We could try something like faking the DOM under Node.js, but I found a better way. We can make our browser-based visualization libraries work for us under Node.js using a headless browser. This is a browser that has no user interface. You can think of it as a browser that is invisible.

I use Nightmare under Node.js to capture visualizations to PNG and PDF files and it works really well!

The headless browser

When we think of a web-browser we usually think of the graphical software that we interact with on a day to day basis when browsing the web. Normally we interact with such a browser directly, viewing it with our eyes and controlling it with our mouse and keyboard as shown in Figure 1.

Figure 1: The normal state of affairs: our visualization renders in a browser and the user interacts directly with the browser

A headless browser on the other hand is a web-browser that has no graphical user interface and no direct means for us to control it. You might ask what is the use of a browser that we can’t directly see or interact with.

Well, as developers we would typically use a headless browser for automating and testing web sites. Let’s say that you have created a web page and you want to run a suite of automated tests against it to prove that it works as expected. The test suite is automated, which means it is controlled from code and this means that we need to drive the browser from code.

We use a headless browser for automated testing because we don’t need to directly see or interact with the web page that is being tested. Viewing such an automated test in progress is unnecessary, all we need to know is if the test passed or failed — and if it failed we would like to know why. Indeed, having a GUI for the browser under test would actually be a hindrance for a continuous-integration or continuous-deployment server, where many such tests can run in parallel.

So headless browsers are often used for automated testing of our web pages, but they are also incredibly useful for capturing browser-based visualizations and outputting them to PNG images or PDF files. To make this work we need a web server and a visualization, we must then write code to instance a headless browser and point it at our web server. Our code then instructs the headless browser to take a screenshot of the web page and save it to our file system as a PNG or PDF file.

Figure 2: We can use a headless browser under Node.js to capture our visualization to a static image file

Nightmare is my headless browser of choice. It is a Node.js library (installed via npm) that is built on Electron. Electron is a framework normally used for building cross-platform desktop apps that are based on web-technologies.

Why Nightmare?

It’s called Nightmare, but it’s definitely not a Nightmare to use. In fact, it’s the simplest and most convenient headless browser that I’ve used. It automatically includes Electron, so to get started we simply install Nightmare into our Node.js project as follows:

npm install --save nightmare

That’s all we need to install Nightmare and we can start using it immediately from JavaScript!

Nightmare comes with almost everything we need: A scripting library with an embedded headless browser. It also includes the communication mechanism to control the headless browser from Node.js. For the most part it’s seamless and well-integrated to Node.js.

Electron is built on Node.js and Chromium and maintained by GitHub and is the basis for a number of popular desktop applications.

Here are the reasons that I choose to use Nightmare over any other headless browser:

  • Electron is very stable.
  • Electron has good performance.
  • The API is simple and easy to learn.
  • There is no complicated configuration (just start using it).
  • It is very well integrated with Node.js.

Nightmare and Electron

When you install Nightmare via npm it automatically comes with an embedded version of Electron. So, we can say that Nightmare is not just a library for controlling a headless browser, it effectively is the headless browser. This is another reason I like Nightmare. With some of the other headless browsers, the control library is separate, or it’s worse than that and they don’t have a Node.js control library at all. In the worst case, you have to roll your own communication mechanism to control the headless browser.

Nightmare creates an instance of the Electron process using the Node.js child_process module. It then uses inter-process communication and a custom protocol to control the Electron instance. The relationship is shown in Figure 3.

Figure 3: Nightmare allows us to control Electron running as a headless browser

Our process: Capturing visualizations with Nightmare

So what is the process of capturing a visualization to an image file? This is what we are aiming at:

  1. Acquire data.
  2. Start a local web server to host our visualization
  3. Inject our data into the web server
  4. Instance a headless browser and point it at our local web server
  5. Wait for the visualization to be displayed
  6. Capture a screenshot of the visualization to an image file
  7. Shutdown the headless browser
  8. Shutdown the local web server

Prepare a visualization to render

The first thing we need is to have a visualization. Figure 4 shows the chart we’ll work with. This a chart of New York City yearly average temperature for the past 200 years.

Figure 4: Average yearly temperature in New York City for the past 200 years

To run this code you need Node.js installed. For this first example we’ll also use live-server (any web server will do) to test the visualization (because we haven’t created our Node.js web server yet), install live server as follows:

npm install -g live-server

Then you can clone the example code repo for this blog post:

git clone https://github.com/Data-Wrangling-with-JavaScript/nodejs-visualization-example

Now go into the repo, install dependencies and run the example using live-server

cd nodejs-visualization-example/basic-visualization
bower install
live-server

When you run live-server your browser should automatically open and you should see the chart from Figure 4.

It’s a good idea to check that your visualization works directly in a browser before you try and capture it in a headless browser; there could easily be something wrong with it and problems are much easier to troubleshoot in a real browser than in the headless browser. live-server has live reload built-in, so now you have a nice little setup here when you can edit and improve the chart interactively before you try to capture it under Node.js.

This simple line chart was constructed with C3. Please take a look over the example code and maybe look at some of the examples in the C3 gallery to learn more about C3.

Starting the web server

To host our visualization, we need a web server. It’s not quite enough that we have a web server, we also need to be able to dynamically start and stop it. Listing 1 shows the code for our web server.

Listing 1 – Code for a simple web server that can be started and stopped

const express = require('express');
const path = require('path');
 
module.exports = {
  start: () => { // Export a start function so we can start the web server on demand.
    return new Promise((resolve, reject) => {
      const app = express();

      const staticFilesPath = path.join(__dirname, "public"); // Make our 'public' sub-directory accessible via HTTP. 
      const staticFilesMiddleWare = express.static(staticFilesPath);
      app.use('/', staticFilesMiddleWare);
     
      const server = app.listen(3000, err => { // Start the web server!
        if (err) {
          reject(err); // Error occurred while starting web server.
        }
        else {
          resolve(server); // Web server started ok.
        }
      });                        
    });
  }
}

The code module in listing 1 exports a start function that we can call to kickstart our web server. This technique, being able to start and stop our web server, is also very useful for doing automated integration testing on a web site. Imagine that you want to start your web server, run some tests against it and then stop it at the end.

So now we have our browser-based visualization and we have a web server that can be started and stopped on demand. These are the raw ingredients we need for capturing server-side visualizations. Let’s mix it up with Nightmare!

Rendering the web page to an image

Now let’s flesh out the code to capture a screenshot of the visualization with Nightmare. Listing 2 shows the code that instances Nightmare, points it at our web server and then takes the screenshot.

Listing 2 – Capturing our chart to an image file using Nightmare

const webServer = require('./web-server.js');
const Nightmare = require('nightmare');
 
webServer.start() // Start the web server.
.then(server => {
  const outputImagePath = "./output/nyc-temperatures.png";

  const nightmare = new Nightmare(); // Create the Nightmare instance.
  return nightmare.goto("http://localhost:3000") // Point the browser at the web server we just started.
    .wait("svg") // Wait until the chart appears on screen.
    .screenshot(outputImagePath) // Capture a screenshot to an image file.
    .end() // End the Nightmare session. Any queued operations are completed and the headless browser is terminated.
    .then(() => server.close()); // Stop the web server when we are done.
})
.then(() => {
  console.log("All done :)");
})
.catch(err => {
  console.error("Something went wrong :(");
  console.error(err);
});

Note the use of the goto function, this is what actually directs the browser to load our visualization.

Web pages usually take some time to load. That’s probably not going to be very long, especially as we are running a local web server, but still we face the danger of taking a screenshot of the headless browser before or during its initial paint. That’s why we must call the wait function to wait until the chart’s <svg> element appears in the browser’s DOM before we call the screenshot function.

Eventually, the end function is called. Up until now we have effectively built a list of commands to send to the headless browser. The end function actually sends the commands to the browser, which takes the screenshot and outputs the file nyc-temperatures.png. After the image file has been captured we finish up by shutting down the web server.

You can find the completed code under the capture-visualization sub-directory in the repo. Go into the sub-directory and install dependencies:

cd nodejs-visualization-example/capture-visualization
cd public 
bower install
cd ..
npm install
live-server

Now you can try the code for yourself:

node index.js

This has been an extract from chapter 11 of Data Wrangling with JavaScript now available on the Manning Early Access Program. Please use this discount code fccdavis3 for a 37% discount. Please check The Data Wrangler for new updates on the book.

The post Server-Side Visualization With Nightmare appeared first on CSS-Tricks.

How to Create a Furry Cheshire Cat Inspired Text Effect in Adobe Illustrator

Post pobrano z: How to Create a Furry Cheshire Cat Inspired Text Effect in Adobe Illustrator

Final product image
What You’ll Be Creating

Follow
this tutorial and learn how to create a Cheshire Cat inspired text
effect in Adobe Illustrator. You will learn a new way to create the
appearance of fur and also use a Pattern brush to add extra fur for a
more detailed look. And this tutorial would not be complete without a
cheesy cat grin. Let’s start!

If
you are looking for more text effects or cartoon characters, be sure
to check out GraphicRiver and you’ll surely find what you are looking
for there. 

Tutorial
Assets

To
complete the tutorial, you will need the following assets:

1. How
to Open a New Document

Launch
Illustrator
and
open a blank document. Type a name for your file, set the
dimensions, and then set
Pixels
as
Units
and
RGB
as
Color
Mode

Next,
go to
Edit
> Preferences > General
and
set the
Keyboard
Increment
to
1
px
and
while there, go to
Units
to
make sure they are set as in the following image. I usually work with
these settings, and they will help you throughout the drawing process. 

how to open new illustrator document

2. How
to Create and Distort the Text

Step
1

Grab
the Type Tool (T) and write “MEOW” on your artboard using the
Jungle Fever Font, size of 160 pt. Choose Expand Appearance from the
Object menu to get the individual letters and Ungroup
(Shift-Control-G)
if necessary. 

how to write the Meow text

Step
2

Focus
on the letter “M”. Use the Delete Anchor Point Tool (-) to delete
some of the points at the top to obtain a straight edge (1). Now,
take the Pen Tool (P) and draw a shape like the one below to simulate the Cheshire Cat’s tufts of fur (2). Continue with the shape of the ears
and send them to the back (3). 

how to distort the letter M

Step
3

Focus
on the letter “W”. Use the Add Anchor Point Tool (+) to add an
extra point at the top of the left leg and distort the shape to
simulate another tuft of fur (1). 

Switch
to the Pen Tool (P) and draw the shape of the tail (2). After that,
select the letter along with the tail and press Unite in the
Pathfinder panel to merge them into a single shape (3). 

how to distort the letter W

Step
4

Rotate
and move the letter “E” closer to the letter “M” (1). Next,
delete the existing letter “O” and draw an egg-like shape instead
(2). Scale up the letter “W” 
 a little, rotate it, and move it over
the letter “O” (3). At this point, the text is ready.

how to arrange the text

3. How
to Create the Stripes on the Text

Step
1

Use
the Pen Tool (P) to draw a few paths over the letter “M” and drag
some of them over the letter “E” as well to create a continuous
look (the green paths). Use Width Profile 1 to stroke these paths
and choose different Stroke Weights of 14 pt, 12 pt, and even 10 pt

how to draw stripes on letter M

Step
2

Focus
on the letter “E”. First, make copies of the three green paths
that go over both letters because you will need the duplicates later.
After that, draw more paths to cover the free areas (the blue paths).
Use Width Profile 1 again and choose different Stroke Weights of
12 pt and 18 pt

how to draw stripes on letter E

Step
3

Now,
focus on the letter “O” and draw four paths with a 10, 12, and
14 pt Stroke (1). Next, draw a long path that goes over the letter
“W” as well, and leave some free space in the bottom left corner for
the cheesy Cheshire Cat grin (2).

Continue
to draw more wavy paths over the letter “W”, and don’t forget to
duplicate the green one for later (3). 

how to draw stripes on letter O and W

Step
4

Let’s
go back to the letter “M”. Select all the paths and choose Expand
Appearance
from the Object menu to turn them from strokes into fills.
Do not release and go to Object > Compound Path > Make
(Control-8)
(1). Make a copy in front of the resulting compound path
for later use.

Copy
and
Paste
in Front (Control-F)

the letter “M”; then select this copy along with the striped
compound path and press Minus Front in the Pathfinder panel (2). If
you get a group of shapes as a result, also go to Object >
Compound Path > Make (Control-8)
. Fill the newly obtained compound
path with gray for the moment (3). 

how to create the pink fur compound path for letter M

Step
5

Select
the original pink letter and then Copy and
Paste
in Front (Control-F)

again. While this copy stays selected, also select the copy of the
striped compound path made in the previous step and press Intersect
in the Pathfinder panel (1). If you get a group of shapes as the
result, go to Object > Compound Path > Make (Control-8). You
will obtain a new striped compound path (2). 

how to create the pink striped fur compound path for letter M

Step
6

Focus
on the letter “E” and select all the paths that go over it (1).
Choose Expand Appearance from the Object menu to turn them into fills
and then go to Object > Compound Path > Make (Control-8). Make
a copy in front of the resulting striped compound path.

Select
the pink letter and then Copy and
Paste
in Front (Control-F)
.
Keep this copy selected along with the striped compound path and
press Minus Front on the Pathfinder panel. Also go to Object >
Compound Path > Make (Control-8)
and fill the resulting shape with
gray (2).

Make
another copy in front of the pink letter. While this copy stays
selected, also select the copy of the striped compound path made
earlier and press Intersect on the Pathfinder panel. If you get a
group of shapes as the result, go to Object > Compound Path >
Make (Control-8)
. You will obtain a new striped compound path (3). 

how to create the fur compound paths for letter E

Step
7

Follow
the technique explained above and apply it for the letters “O”
and “W” as well to get the compound paths that you need. 

how to create all fur compound paths

4. How
to Create the Furry Look

Step
1

Focus
on the letter “O”. Select the gray compound path obtained earlier
and change the fill color to a darker shade. Next, go to Effect >
Sketch > Reticulation
and apply the settings shown (1). Choose
Expand Appearance from the Object menu to expand the effect, and then
go to Object > Image Trace > Make. Do not release, and choose
High Fidelity Photo as the Preset and Expand from the Control panel. 

Use the Direct Selection Tool (A) to select only the white square
around the letter and delete it (2). As a result, you will have a
complex group of tiny gray shapes (3). 

how to apply Reticulation effect and Trace for letter O

Step
2

Fill
the group of tiny shapes with the linear gradient shown at a -60
degrees Angle
(1). Next, go to Effect > Distort & Transform >
Pucker & Bloat
and apply a -140% Pucker effect to get the furry
look. Drag the Pucker & Bloat effect applied under Contents in
the Appearance panel for a better result (2).

While
the group of shapes is still selected, go to the Appearance panel and
double click on Contents to see the attributes. Select the existing
Fill attribute and then go to Effect > Stylize > Drop Shadow.
Apply the settings shown and hit OK (3). This will add more depth to
the fur. 

how to create the pink fur on letter O

Step
3

Now,
select the striped compound path and replace the fill color (1).

Make
a copy in front of this shape, fill it with gray, and apply the
Reticulation effect using the same settings (2).

Choose
Expand Appearance from the Object menu to expand the effect and then
go to Object > Image Trace > Make. Select High Fidelity Photo
as the Preset and Expand from the Control panel just like before, and
then delete the white square. You will get a new group of tiny random
gray shapes (3). 

how to apply Reticulation effect and Trace for stripes letter O

Step
4

Fill
the newly obtained group of tiny shapes with the linear gradient
shown at a -45 degrees Angle (1). Apply a -140% Pucker effect again, and after that, drag the effect under Contents in the Appearance panel
(2).

While
the group is still selected, open the Contents to see the attributes
and apply a Drop Shadow effect using the same settings in order to
add more depth (3). 

how to create the purple striped fur on letter O

Step
5

If
you take a closer look, you will be able to see the shapes that are
behind the fur, and they are too sharp. Let’s fix that.

Select
the pink letter that was in the back all along and, while the existing
Fill attribute stays selected in the Appearance panel, go to Effect >
Path > Offset Path
and apply an Offset of -1 px to make the shape
slightly smaller. Next, go to Effect > Stylize > Inner Glow and
apply the settings shown; then go to Effect > Blur > Gaussian
Blur
and apply a Radius of 2 px (1).

Now,
select the purple striped compound path behind the purple fur and
apply the same effects to obtain smooth, blurry edges (2). You can see
the end result in the image below (3). 

how to create smooth blurry edges for letter O

Step
6

Now,
focus on the letter “E” and apply the same technique. First,
create the pink fur, starting from the gray compound path and the
Reticulation effect (1). Next, replace the blue fill color of the
striped compound path with purple and make a copy in front (2). To
this copy, apply the Reticulation effect and then create the purple
fur as explained earlier (3). At the end, don’t forget to create the
smooth, blurry edges for the original pink letter and the purple
stripes that are in the back (4).

Repeat
the same things for the letter “W”. 

how to create fur on letter E O and W

Step
7

For
the letter “M”, after you create the fur on the actual letter (1), let’s work on the shapes above. Select the fur tufts shape and apply
the Offset Path, Inner Glow and Gaussian Blur effects using the same
settings as for the purple striped compound paths earlier in the
tutorial (2). Make a copy in front of this shape, remove all existing
appearances, and apply the
Reticulation
effect followed by Image Trace and the Pucker & Bloat effect to create the
fur (3). 

how to create fur on tufts shape for letter M

Step
8

Repeat
the same technique and create the pink fur on the ears. 

how to create fur on ear shapes for letter M

Step
9

At
this point, the Cheshire Cat inspired text effect should look like the following image. 

finished pink and purple fur for Meow text

5. How
to Add Extra Fur Around the Text

Step
1

Select
the original pink letter “M” and then Copy and Paste in Back
(Control-B)
to make a copy of it. Remove all existing appearances
(1). Go to File > Scripts > Round Any Corner and apply a Radius
of 10 in order to get the rounded corners. This script works better
than the Round Corners effect. 
You
can find more information about the Round Any Corner Script and how to
install and use it in the 
20
Free and Useful Adobe Illustrator Scripts
 tutorial.

Give
it a 1 pt light pink Stroke and use the Grass Pattern Brush that you
can find in the Brush Libraries Menu > Borders >
Borders_Novelty
. Open the Stroke Options window from the Appearance
panel, drag the Scale slider to 20%, and set the Colorization Method
to Tints and Shades. This will make the grass smaller, like fur, and it will take the color of the stroke, which in this case is pink. If the tips
of the brush don’t go outwards, also check the Flip Across option
(2). 

how to add extra fur around letter M

Step
2

While
this copy of the letter is still selected, add a New Stroke at the
top of the Appearance panel and use the Grass Pattern Brush again.
This time, set the color to a darker pink (1). Open the Stroke Options
window, drag the Scale slider to 40%, and set the Colorization Method
to Tints and Shades. You can see the result in the image below (2). 

how to add more fur around letter M

Step
3

Now,
select the fur tufts shape and make a copy in back. Remove the
existing appearances and then apply the Round Any Corner Script. To
this shape, apply the two Stroke attributes using the Grass Pattern
Brush
and the same settings (1).

Repeat
the same thing for the ear shapes (2).

You
can even save this “Edge Fur Graphic Style” in the Graphic Styles
panel and apply it more easily to the other letters. 

how to add extra fur around tufts and ear shapes

Step
4

Apply
the same technique for the letters “E”, “O”, and “W”, and
add extra fur around the letters. 

how to add extra fur around letters E O and W

6. How
to Add Shadow to the Furry Text

Step
1

Let’s
create a complex compound path. Focus on the letter “O”, select
the original pink shape, and then Copy and Paste in Place
(Shift-Control-V)
. Remove all existing appearances and give it any
fill color (1). Hide this shape for the moment.

Select
the purple fur group and Copy and Paste in Place (Shift-Control-V) to
make a copy of it. Double click on Contents in the Appearance panel
to see the attributes and delete the Drop Shadow effect. Now, go to
Object > Expand Appearance in order to expand the Pucker &
Bloat
effect. Do not release the group and press Unite in the
Pathfinder panel (2); then go to Object > Compound Path > Make
(Control-8)
. Fill the resulting striped fur compound path with blue
for the moment (3). 

how to create a striped fur compound path for letter O

Step
2

Next,
select the pink fur group and Copy and Paste in Place
(Shift-Control-V)
to make a copy of it. Delete the Drop Shadow effect
in the Appearance panel and then go to Object > Expand Appearance
to expand the Pucker & Bloat effect (1). Press Unite in the
Pathfinder panel followed by Object > Compound Path > Make
(Control-8)
and you will obtain the green complex compound path (2).
Hide it for now. 

how to create a complex fur compound path for letter O

Step
3

Next,
select the copy of the letter “O” stroked with the Grass Pattern
Brush
and then Copy and Paste in Place (Shift-Control-V) to make a
copy of it (1). Go to Object > Expand Appearance to expand the
brushes (2); then press Unite in the Pathfinder panel followed by
Object > Compound Path > Make (Control-8). Fill the resulting
compound path with gray for the moment (3). 

how to create the edge fur compound path for letter O

Step
4

Unhide
the pink, blue, green, and gray compound paths that you have obtained
in the previous three steps (1) and keep them selected. Press Unite
in the Pathfinder panel, and then go to Object > Compound Path >
Make (Control-8)
. We’ll use this newly obtained shape to create the
shadow (2). 

how to create the shadow shape for letter O

Step
5

Follow
the steps explained above and create the other shapes that you need
(1). Move all four shapes into a New Layer under the text effect and
fill them with purple. Go to Effect > Stylize > Drop Shadow and
apply the settings shown (2).

how to create shadow for Meow text

Step
6

Select
the four shapes from the previous step, and then Copy and Paste in
Back (Control-B)
to make copies of them. While they are still
selected, go to Object > Compound Path > Make (Control-8) to
merge them into a single compound path (1). Remove the Drop Shadow
effect and replace it with the Outer Glow effect (2). 

how to add more shadow around Meow text

Step
7

Take
the Pen Tool (P) and draw a path where the letter “M” touches “E” and where “O” touches “W”. Send the first path
behind the letter “M” but in front of the letter “E”; and
send the second path behind the letter “W” but in front of “O”
(1).

Give
them both a 3 pt black Stroke and use Width Profile 1 in the
Stroke panel. Next, apply a 3 px Gaussian Blur and reduce the Opacity
to 50% (2). 

how to add shadow between Meow letters

7. How
to Create the Cheesy Cheshire Cat Grin

Step
1

Use
the Pen Tool (P) to draw the shape of the smile on the letter “O”.
Give it a white fill and then go to Effect > Stylize > Outer
Glow
and apply the settings shown. Also, add a 2 pt Outside Stroke
and use the linear gradient shown. 

how to draw the cheesy cat smile shape on letter O

Step
2

With
the smile shape still selected, add a New Fill at the bottom of the
Appearance panel and use black as the color. While this Fill
attribute stays selected, go to Effect > Distort & Transform >
Transform
and apply a -3 px Vertical Move. Set the Blending Mode to
Overlay and you will get a thin shadow at the top of the smile (1).

With
the smile shape still selected, add another black Fill attribute at
the bottom of the Appearance panel and then apply a 3 px Vertical
Move
. Set the Blending Mode to Overlay and you will get a thin shadow
at the bottom of the smile (2). 

how to add shadow around cheesy cat smile

Step
3

Use
the Pen Tool (P) of the Line Segment Tool (\) to draw a bunch of
short paths to define the teeth (1). Give all of them a 2 pt light
gray Stroke and use the Tapered Blend Art Brush. Add a New Stroke at
the top of the Appearance panel and use the same brush, but choose a
darker shade of gray and reduce the Stroke Weight at 0.2 pt (2).
I’ve
shown how to create and save this useful blend brush in the How to Create a Candy Monster Character 
tutorial
(section 10).

Select
the smile shape and then Copy and Paste in Place (Shift-Control-V) to
make a copy of it. Set it to stroke-none and fill-none. While this
copy stays selected, also select the lines and go to Object >
Clipping Mask > Make (Control-7)
(3). 

how to define the teeth on cheesy cat smile

Step
4

Use
the Pen Tool (P) to draw a few short paths following the edge around
the mouth and apply the two Stroke attributes using the Grass Pattern
Brush
and the same settings as for the extra fur around the edges of
the letters earlier in the tutorial (1).

While
all the paths stay selected, go to Object > Expand Appearance in
order to expand the brushes, and then Group (Control-G) them and apply
the Drop Shadow effect (2). 

how to add extra fur around cheesy cat smile

Step
5

Select
the smile shape, go to Object > Path > Offset Path, and apply an
Offset
of 2 px. Now, select the bigger shape that you have obtained
and bring it in front of everything by going to Object > Arrange >
Bring to Front (Shift-Control-])
. Set this shape to stroke-none and
fill-none (1).

Now,
select the small groups of fur around the mouth along with the copy
of the smile and go to Object > Clipping Mask > Make (Control-7)
(2). At this point, the cheesy grin is ready. 

how to mask extra fur around cheesy cat smile

Congratulations!
You’re Done

Here
is the final image of the Cheshire Cat inspired text effect. This was
challenging and fun to create. I hope you enjoyed it and that you
learned new techniques. Don’t forget to share an image with us if you
decide to recreate it. 

Cheshire Cat inspired text effect final image

Agregator najlepszych postów o designie, webdesignie, cssie i Internecie