Thursday, April 19, 2018

How to Build a Serverless, CMS-powered Angular Application

Angular has taken off in popularity and is in widespread use. Developed and maintained by Google engineers, Angular has found a place all across dynamic web applications and is an increasingly in-demand platform.

Angular offers the advantages of a large and enthusiastic community and outstanding MVC that doesn’t require developers to spend valuable time writing code to put multiple MVC components back together again. In short, Angular is a robust and comprehensive web application framework for front-end development that is unit-testing ready, making it the tool of choice for many developers.

If you’re using Angular, you may run into the need for content management capability — a blog being one example. Adding a CMS to an Angular app may seem daunting, especially if you’re trying to integrate it into a traditional CMS like Wordpress, but there’s a new breed of API-based CMS that greatly simplifies things. ButterCMS is one example of a SaaS-based headless CMS that provides a hosted CMS dashboard and content API that you query from your Angular application. This means you don’t need to spin up any new infrastructure to add a CMS to your Angular app.

This tutorial will demonstrate how to build a CMS-powered Angular application that has marketing pages (customer case studies), a blog, and FAQ, all powered via an API. No servers needed!

Installation

First, you’ll get started by installing the Angular CLI.

npm install -g @angular/cli</td>

Set up a new Angular project using Angular CLI. By default, Angular CLI uses CSS styling, so adding the --style=scss flag tells Angular CLI to use SCSS instead:

ng new hello-buttercms-project --style=scss
cd hello-buttercms-project

Install Angular Material and Angular Material related package:

npm install --save @angular/material @angular/cdk
npm install --save @angular/animations

Install ButterCMS. Run this in your command line:

npm install buttercms --save

Butter can also be loaded using a CDN:

<script src="https://cdnjs.buttercms.com/buttercms-1.1.1.min.js"></script>

Quickly Get Started

Open the project in your code editor of choice. Under src/app create a directory called _services.

We create a file called butterCMS.service.js. This allows us to have your API Token in one place and not accidentally alter it.

import * as Butter from 'buttercms';

export const butterService = Butter('b60a008584313ed21803780bc9208557b3b49fbb');

You’ll import this file into any component we want to use ButterCMS.

For a Quickstart, go to src/app/hello-you/hello-you.component.ts and import butterService:

import {butterService} from '../_services';

Inside the HelloYouComponent create methods:

fetchPosts() {
  butter.post.list({
    page: 1,
    page_size: 10
  })
  .then((res) => {
    console.log('Content from ButterCMS')
    console.log(res)
  })
}

Now call this method when the component is loaded by adding it to the OnInit lifecycle hook:

ngOnInit() {
  this.fetchPosts();
}

This API request fetches your blog posts. Your account comes with one example post, which you'll see in the response.

Next, create another method to retrieve the Homepage Headline Content Field:

fetchHeadline() {
  butter.content.retrieve(['homepage_headline'])
    .then((res) => {
      console.log('Headline from ButterCMS')
      console.log(res)
    })
}

Add this method to the OnInit lifecycle hook.

ngOnInit() {
  this.fetchPosts();
  this.fetchHeadline();
}

This API request fetches homepage headline content. You can set up your own custom content fields to manage any kind of content you need.

Add Marketing Pages

Setting up CMS-powered pages is a simple, three-step process:

  1. Define the Page Type
  2. Create a page
  3. Integrate into your application

Define Page

First, create a Page Type to represent your Customer Case Study pages. Next, define the fields you want for your customer case studies. With your Page Type defined, you can now create the first case study page. Specify the name and URL of the page, and then populate the content of the page.

With your page defined, the ButterCMS API will return it in JSON format like this:

Continue reading %How to Build a Serverless, CMS-powered Angular Application%


by Jake Lumetta via SitePoint

Reliable UX & UI Tools for Your Projects in 2018

Content is an integral part of a site's overall UX. Its constituent components are arranged to help visitors go where they want to go and take the actions they want to take. They are chosen to entice visitors to go where the designer wants them to go as well.

This approach is sometimes successful and sometimes not. It takes special skills to consistently create quality UX. Consequently, the demand for designers with those skills is great and it is growing.

You may feel you have those skills, along with the experience to use them effectively. Then you should have no trouble finding a well-paying job. If you invest in the right tools, you should do even better.

One or more of the top UI/UX tools described in this post will serve you admirably. You're invited to check them out to see for yourself.

1. Mason

Mason

Prototyping is a popular and widespread digital and web design technique, and rapid prototyping is a favored approach of many. While prototyping brings several benefits to the table, the practice can also contribute to overhead expenses and the use of prototypes do not necessarily guarantee pixel-perfect, developer-ready designs.

How many times have you handed off a design for a login flow, a registration experience or a feed feature, only to have the final product not match your spec? Plus, you had to wait on a deployment cycle to see what it would look like.

Mason has a better way. With this powerful tool, you can create, manipulate, and deploy web and mobile features at a building block level—all without a single line of code. Mason's simple visual interface enables you to design real software and digital features without having to rely on creating mockups or prototypes to hand off to production. Connect your API endpoints, drop the Mason-generated code into your app codebase, and boom: you're live.

Build without the overhead costs and time associated with prototyping, QA inspections, providing manual documentation, and in some cases post-deployment modifications and maintenance. Then, edit directly in the Mason builder—new CTA, new copy, new images, and much more—and publish your changes in real-time.

2. Overflow

Overflow

Flowcharting helps designers share design ideas with others and deploy products that work as expected. Few if any designers, however, can use flowcharts effectively to directly support UX design, which is where Overflow enters the picture.

Overflow provides you with the means to create flowcharts and diagrams based on user needs and expectations. These flowcharts are meant to tell a story, and telling a story is key to creating a quality UX. User-oriented flow diagrams can also pack a punch when shared with others for feedback or comment because of the useful and valuable information they can contain.

Overflow is a cross-platform tool that is currently in beta testing. It is being introduced by PROTOIO Inc., the creator of the popular Proto.io web design tool. Overflow is also the world's first user flow diagramming tool tailored for designers. To inquire about early access, visit overflow.io, or Overflow on Twitter or Facebook.

3. UXPin

UXPin

UXPin assists teams and companies of all sizes in designing, sharing, and testing prototypes with the ultimate objective of delivering development-ready designs. This powerful tool prepares and organizes design components, syncs them with code, and implements the controls necessary to ensure design consistency throughout a product.

With UXPin, manually-produced documentation is not required. Whatever data and information developers need to complete a project is automatically generated and attached each design element. UXPin also features an inspect tool to verify that each product, once deployed, exactly matches each design in all respects.

With UXPin Design Systems, UXPin ensures that the whole design you've worked so hard to build will not be subject to undesirable changes or modifications. And your team can put controls in place to ensure UX and visual consistency across the entire product.

4. PowerMockup

PowerMockup

PowerMockup is specifically for PowerPoint users! Although experienced PowerPoint users are generally capable of designing truly amazing and captivating presentations, their ability to create interactive prototypes without having to rely on a different platform is another story.

PowerMockup's library of shapes and design elements changes all that. It's simply a matter of transferring elements onto a PowerPoint screen and invoking slider and animation functions to create a highly-effective interactive prototype.

5. Creately

Creately

Creately is a diagramming, flowcharting, wireframing, and collaboration-supportive toolkit. It is designed to visually support UX designers in a way that helps them go about their work more efficiently.

Mind-mapping tools that support brainstorming activities and professionally-designed templates designed to get projects underway are included in the package. Creately addresses one of the more challenging website-building areas, UX design.

6. Fluid UI

Fluid UI

Fluid UI allows you to easily and quickly create desktop, mobile, website and app prototypes thanks to its extensive component libraries.

Distributed design teams will find Fluid UI's collaboration features particularly helpful, as will individual designers and project managers, as this feature-rich tool enables them to communicate via messaging, interactive video presentations, and live chat.

7. Visual Inspector

Visual Inspector

With Visual Inspector, you can easily investigate and resolve live website UI problems or issues and communicate your findings and results with others in real-time. No coding is required to make needed changes, or to list or download webpage colors, fonts, or other assets – images, banners, etc.

Visual Inspector can be used on any type of website, and it also integrates with WordPress and 23 different communications platforms. Lifetime access to this unique UI tool is currently available for $49.

Conclusion

Although these UI/UX tools take various approaches, all are highly effective at what they can do. If you're a firm believer in rapid prototyping, there's something here for you. If a new and different approach to web design might appeal to you, there's something here as well.

User flow diagrams can make UX design less of a challenge. If you're a dedicated PowerPoint user, you are lucky. This is because you can stop looking for a separate prototype-building platform.

Continue reading %Reliable UX & UI Tools for Your Projects in 2018%


by SitePoint Team via SitePoint

Mindfulness at Work: 5 Ways to Improve Your Productivity

This article was originally published on monday.com. Thank you for supporting the partners who make SitePoint possible.

Mindfulness is all the rage these days. Rooted in ancient Buddhist tradition, it’s now respected by the scientific community as an effective way to fight anxiety, treat heart disease, lower blood pressure, reduce chronic pain, and improve sleep.

And perhaps unsurprisingly, mindfulness at work is now a huge trend as well. Research shows that mindfulness at work can improve your focus, attention, and ability to work under stress—all great assets in the workplace these days.

What is mindfulness, exactly? Simply put, it’s focusing your awareness on the present moment. Not thinking about the hectic morning you had, worrying about a presentation you have to give this afternoon, or planning what you’ll cook for dinner tonight. Instead, it’s paying attention to what you’re feeling, thinking, and seeing right now, without judgment. There’s no “right” or “wrong” way to think or feel.

While mindfulness is straightforward, it’s far from easy. We listed five ways for you to practice mindfulness at work. Not only will it reduce your stress and make you happier, it’ll also boost your productivity and help you achieve more every day without working longer hours.

1. Prioritize your tasks and projects for the next day

The day has come to an end and you’re about to go home. Before you do, take a few minutes to see what you’ve managed to accomplish and what is left for tomorrow.

Try to organize your to-dos by these three criteria: priority, focus level required, and how long each task will take. Many people are most productive first thing in the morning, so start your day with the most important and demanding tasks. (See: Eat that Frog.) Then work on medium-priority assignments, and save your least demanding tasks for later in the day. That way, you can accomplish more each day and rest assured you’ll always get the most important things done.

2. Start your day with meditation

Many times you arrive to work, but you aren’t really present. Traffic was terrible, you had an argument with your partner, your kid is sick, your banker has tried to call you three times, and your dog peed on the carpet just as you were walking out of the house. You’re sitting down in front of your computer to start the day, but your thoughts are anywhere but here.

Continue reading %Mindfulness at Work: 5 Ways to Improve Your Productivity%


by SitePoint Team via SitePoint

Introduction to the Fetch API

In this article, we’ll learn what the new Fetch API looks like, what problems it solves, and the most practical way to retrieve remote data inside your web page using the fetch() function.

For years, XMLHttpRequest has been web developers’ trusted sidekick. Whether directly or under the hood, XMLHttpRequest has enabled Ajax and a whole new type of interactive experience, from Gmail to Facebook.

However, XMLHttpRequest is slowly being superseded by the Fetch API. Both can be used to make network requests, but the Fetch API is Promise-based, which enables a cleaner, more concise syntax and helps keep you out of callback hell.

The Fetch API

The Fetch API provides a fetch() method defined on the window object, which you can use to perform requests. This method returns a Promise that you can use to retrieve the response of the request.

The fetch method only has one mandatory argument, which is the URL of the resource you wish to fetch. A very basic example would look something like the following. This fetches the top five posts from r/javascript on Reddit:

fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
.then(res => console.log(res));

If you inspect the response in your browser’s console, you should see a Response object with several properties:

{
  body: ReadableStream
  bodyUsed: false
  headers: Headers {}
  ok: true
  redirected: false
  status: 200
  statusText: ""
  type: "cors"
  url: "https://www.reddit.com/top/.json?count=5"
}

It seems that the request was successful, but where are our top five posts? Let’s find out.

Loading JSON

We can’t block the user interface waiting until the request finishes. That’s why fetch() returns a Promise, an object which represents a future result. In the above example, we’re using the then method to wait for the server’s response and log it to the console.

Now let’s see how we can extract the JSON payload from that response once the request completes:

fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
.then(res => res.json())
.then(json => console.log(json));

We start the request by calling fetch(). When the promise is fulfilled, it returns a Response object, which exposes a json method. Within the first then() we can call this json method to return the response body as JSON.

However, the json method also returns a promise, which means we need to chain on another then(), before the JSON response is logged to the console.

And why does json() return a promise? Because HTTP allows you to stream content to the client chunk by chunk, so even if the browser receives a response from the server, the content body might not all be there yet!

Async … await

The .then() syntax is nice, but a more concise way to process promises in 2018 is using async … await — a new syntax introduced by ES2017. Using async Ú await means that we can mark a function as async, then wait for the promise to complete with the await keyword, and access the result as a normal object. Async functions are supported in all modern browsers (not IE or Opera Mini) and Node.js 7.6+.

Here’s what the above example would look like (slightly expanded) using async … await:

async function fetchTopFive(sub) {
  const URL = `https://www.reddit.com/r/${sub}/top/.json?limit=5`;
  const fetchResult = fetch(URL)
  const response = await fetchResult;
  const jsonData = await response.json();
  console.log(jsonData);
}

fetchTopFive('javascript');

Not much has changed. Apart from the fact that we’ve created an async function, to which we’re passing the name of the subreddit, we’re now awaiting the result of calling fetch(), then using await again to retrieve the JSON from the response.

That’s the basic workflow, but things involving remote services doesn’t always go smoothly.

Continue reading %Introduction to the Fetch API%


by Ludovico Fischer via SitePoint

10 Lodash Features You Can Replace with ES6

Right now, Lodash is the most depended-on npm package, but if you're using ES6, you might not actually need it.

In this article, we're going to look at using native collection methods with arrow functions and other new ES6 features to help us cut corners around many popular use cases.

1. Map, Filter, Reduce

These collection methods make transforming data a breeze and with near universal support. We can pair them with arrow functions to help us write terse alternatives to the implementations offered by Lodash:

_.map([1, 2, 3], function(n) { return n * 3; });
// [3, 6, 9]
_.reduce([1, 2, 3], function(total, n) { return total + n; }, 0);
// 6
_.filter([1, 2, 3], function(n) { return n <= 2; });
// [1, 2]

// becomes

[1, 2, 3].map(n => n * 3);
[1, 2, 3].reduce((total, n) => total + n);
[1, 2, 3].filter(n => n <= 2);

It doesn't stop here, either. If we're using a modern browser, we can also use find, some, every and reduceRight too.

2. Head & Tail

Destructuring syntax allows us to get the head and tail of a list without utility functions:

_.head([1, 2, 3]);
// 1
_.tail([1, 2, 3]);
// [2, 3]

// becomes

const [head, ...tail] = [1, 2, 3];

It's also possible to get the initial elements and the last element in a similar way:

_.initial([1, 2, 3]);
// -> [1, 2]
_.last([1, 2, 3]);
// 3

// becomes

const [last, ...initial] = [1, 2, 3].reverse();

If you find it annoying that reverse mutates the data structure, then you can use the spread operator to clone the array before calling reverse:

const xs = [1, 2, 3];
const [last, ...initial] = [...xs].reverse();

3. Rest and Spread

The rest and spread functions allow us to define and invoke functions that accept a variable number of arguments. ES6 introduced dedicated syntaxes for both of these operations:

var say = _.rest(function(what, names) {
  var last = _.last(names);
  var initial = _.initial(names);
  var finalSeparator = (_.size(names) > 1 ? ', & ' : '');
  return what + ' ' + initial.join(', ') +
    finalSeparator + _.last(names);
});

say('hello', 'fred', 'barney', 'pebbles');
// "hello fred, barney, & pebbles"

// becomes

const say = (what, ...names) => {
  const [last, ...initial] = names.reverse();
  const finalSeparator = (names.length > 1 ? ', &' : '');
  return `${what} ${initial.join(', ')} ${finalSeparator} ${last}`;
};

say('hello', 'fred', 'barney', 'pebbles');
// "hello fred, barney, & pebbles"

4. Curry

Without a higher-level language such as [TypeScript][5] or [Flow][6], we can't give our functions type signatures, which makes currying quite difficult. When we receive curried functions, it's hard to know how many arguments have already been supplied, and which we’ll need to provide next. With arrow functions, we can define curried functions explicitly, making them easier to understand for other programmers:

function add(a, b) {
  return a + b;
}
var curriedAdd = _.curry(add);
var add2 = curriedAdd(2);
add2(1);
// 3

// becomes

const add = a => b => a + b;
const add2 = add(2);
add2(1);
// 3

These explicitly curried arrow functions are particularly important for debugging:

var lodashAdd = _.curry(function(a, b) {
  return a + b;
});
var add3 = lodashAdd(3);
console.log(add3.length)
// 0
console.log(add3);
// function (a, b) {
// /* [wrapped with _.curry & _.partial] */
//   return a + b;
// }

// becomes

const es6Add = a => b => a + b;
const add3 = es6Add(3);
console.log(add3.length);
// 1
console.log(add3);
// function b => a + b

If we're using a functional library like lodash/fp or ramda, we can also use arrows to remove the need for the auto-curry style:

_.map(_.prop('name'))(people);

// becomes

people.map(person => person.name);

Continue reading %10 Lodash Features You Can Replace with ES6%


by Dan Prince via SitePoint

Auto-Update Your WordPress Salts With WP-Salts-Update-CLI

How to Set Up a Full-Text Search Using Scout in Laravel

Full-text search is crucial for allowing users to navigate content-rich websites. In this post, I'll show you how to implement full-text search for a Laravel app. In fact, we'll use the Laravel Scout library, which makes implementation of full-text search easy and fun.

What exactly is the Laravel Scout? The official documentation sums it up like this:

Laravel Scout provides a simple, driver-based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.

Basically, Laravel Scout is a library that manages manipulation of the index whenever there's a change in the model data. The place where the data will be indexed depends on the driver that you've configured with the Scout library.

As of now, the Scout library supports Algolia, a cloud-based search engine API, and that's what we'll use in this article to demonstrate the full-text search implementation.

We'll start by installing the Scout and Algolia server libraries, and as we move on we'll go through a real-world example to demonstrate how you could index and search your data.

Server Configurations

In this section, we're going to install the dependencies that are required in order to make the Scout library work with Laravel. After installation, we'll need to go through quite a bit of configuration so that Laravel can detect the Scout library.

Let's go ahead and install the Scout library using Composer.

That's pretty much it as far as the Scout library installation is concerned. Now that we've installed the Scout library, let's make sure that Laravel knows about it.

Working with Laravel, you're probably aware of the concept of a service provider, which allows you to configure services in your application. Thus, whenever you want to enable a new service in your Laravel application, you just need to add an associated service provider entry in the config/app.php.

If you're not familiar with Laravel service providers yet, I would strongly recommend that you do yourself a favor and go through this introductory article that explains the basics of service providers in Laravel.

  • Laravel
    How to Register & Use Laravel Service Providers
    Sajal Soni

In our case, we just need to add the ScoutServiceProvider provider to the list of service providers in config/app.php, as shown in the following snippet.

Now, Laravel is aware of the ScoutServiceProvider service provider. The Scout library comes with a configuration file that allows us to set API credentials.

Let's go ahead and publish the assets provided by the Scout library using the following command.

As you can see, it has copied the vendor/laravel/scout/config/scout.php file to config/scout.php.

Next, go ahead and create an account with Algolia as we'll need API credentials in the first place. Once you have the API information, let's go ahead and configure the necessary settings in the config/scout.php file, as shown in the following snippet.

Note that we've set the value of SCOUT_DRIVER to algolia driver. Thus, it's required that you configure the necessary settings for the Algolia driver at the end of the file. Basically, you just need to set the id and secret that you've got from the Algolia account.

As you can see, we're fetching values from environment variables. So let's make sure that we set the following variables in the .env file properly.

Finally, we need to install the Algolia PHP SDK, which will be used to interact with the Algolia using APIs. Let's install it using the composer as shown in the following snippet.

And with that, we've installed all the dependencies that are necessary in order to post and index data to the Algolia service.

Make Models Indexable and Searchable

In the previous section, we did all the hard work to set up the Scout and Algolia libraries so that we could index and search data using the Algolia search service.

In this section, we'll go through an example that demonstrates how you could index the existing data and retrieve search results from Algolia. I assume that you have a default Post model in your application that we'll use in our example.

The first thing that we'll need to do is to add the Laravel\Scout\Searchable trait to the Post model. That makes the Post model searchable; Laravel synchronizes post records with the Algolia index every time the post record is added, updated, or deleted.

With that, the Post model is search-friendly!

Next, we would like to configure the fields that should get indexed in the first place. Of course, you don't want to index all the fields of your model in Algolia to keep it effective and lightweight. In fact, more often than not, you won't need it.

You can add the toSearchableArray in the model class to configure the fields that'll be indexed.

Now, we're ready to import and index existing Post records into Algolia. In fact, the Scout library makes this easy by providing the following artisan command.

That should import all the records of the Post model in a single go! They are indexed as soon as they're imported, so we're ready to query records already. Go ahead and explore the Algolia dashboard to see the imported records and other utilities.

How It Works Altogether

In this section, we'll create an example that demonstrates how to perform search and CRUD operations that are synced in real time with the Algolia index.

Go ahead and create the app/Http/Controllers/SearchController.php file with the following contents.

Of course, we need to add the associated routes as well.

Let's go through the query method to see how to perform a search in Algolia.

Recall that we made the Post model searchable by adding the Searchable trait. Thus, the Post model can use the search method to retrieve records from the Algolia index. In the above example, we're trying to fetch records that match the title keyword.

Next, there's the add method that imitates the workflow of adding a new post record.

There's nothing fancy in the above code; it just creates a new post record using the Post model. But the Post model implements the Searchable trait, so Laravel does some extra work this time around by indexing the newly created record in Algolia. So as you can see, the indexing is done in real time.

Finally, there's the delete method. Let's go through it as well.

As you would have expected, the record is deleted right away from the Algolia index as soon as it's deleted from the database.

Basically, there's no extra effort required from your side if you want to make existing models searchable. Everything is handled by the Scout library using model observers.

And that also brings us to the end of this article!

Conclusion

Today, we discussed how you can implement full-text search in Laravel using the Laravel Scout library. In the process, we went through the necessary installations and a real-world example to demonstrate it.

Feel free to ask if you have any queries or doubts using the comment feed below!


by Sajal Soni via Envato Tuts+ Code