Use Your Web Dev Skills to Build a Desktop App with Electron

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible. Electron is a framework for building cross-platform desktop applications with web technologies like JavaScript, HTML, and CSS. It was created for GitHub’s Atom editor and has achieved widespread adoption since. Electron powers several apps that […]

The post Use Your Web Dev Skills to Build a Desktop App with Electron appeared first on SitePoint.


Source: Sitepoint

Building A PWA Using Angular 6

Building A PWA Using Angular 6

Building A PWA Using Angular 6

Ahmed Bouchefra

2018-09-20T13:35:23+02:00
2018-09-20T11:42:41+00:00

In this tutorial, we’ll be using the latest Angular 6 to build a PWA by implementing the core tenets that make a PWA. We’ll start by creating a front-end web application that consumes a JSON API. For this matter, we’ll be using the Angular HttpClient module to send HTTP requests to a statically JSON API generated from the Simplified JavaScript Jargon GitHub repository. We’ll also use Material Design for building the UI via the Angular Material package.

Next, we’ll use the “Audits” panel (Lighthouse) from Chrome DevTools to analyze our web application against the core tenets of PWAs. Finally, we’ll explain and add the PWA features to our web application according to the “Progressive Web App” section in the Lighthouse report.

Before we start implementing our PWA, let’s first introduce PWAs and Lighthouse.

Recommended reading: Native And PWA: Choices, Not Challengers!

What’s A PWA?

A Progressive Web App or PWA is a web application that has a set of capabilities (similar to native apps) which provide an app-like experience to users. PWAs need to meet a set of essential requirements that we’ll see next. PWAs are similar to native apps but are deployed and accessible from web servers via URLs, so we don’t need to go through app stores.

A PWA needs to be:

  • Progressive
    Work for every user, regardless of browser choice, because they are built with progressive enhancement as a core tenet.
  • Responsive
    Fit any form factor, desktop, mobile, tablet, or whatever is next.
  • Connectivity independent
    Enhanced with service workers to work offline or on low-quality networks.
  • App-like
    Use the app-shell model to provide app-style navigation and interactions.
  • Fresh
    Always up-to-date thanks to the service worker update process.
  • Safe
    Served via HTTPS to prevent snooping and ensure content has not been tampered with.
  • Discoverable
    Are identifiable as “applications” thanks to W3C manifests and service worker registration scope allowing search engines to find them.
  • Re-engageable
    Make re-engagement easy through features like push notifications.
  • Installable
    Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store.
  • Linkable
    Easily share via URL and not require complex installation.

Introducing Lighthouse

Lighthouse is an open-source auditing tool created by Google which can be used to audit websites and applications for accessibility performance, SEO, best practices and PWA features.

You can access Lighthouse from the Audit tab in Chrome DevTools as a module in Node.js or as a CLI tool. You can use Lighthouse by providing an URL and then running the audits which will provide you with a report containing the auditing results which are basically suggestions on how you can improve your web application.

Installing Angular CLI v6 And Generating A Project

In this section, we’ll install the latest version of Angular CLI then we’ll use it to create a new Angular 6 project.

Angular CLI requires Node.js >= 8.9+ so first make sure you have the required version installed by running the following command:

$ node -v

Node.js version
Checking Node version. (Large preview)

In case you don’t have Node.js installed, you can simply head on to the official Node download page and grab the Node binaries for your system.

Now, you can go ahead and install the latest version of Angular CLI by running:

$ npm install -g @angular/cli 

Note: Depending on your npm configuration, you may need to add _sudo_ to install packages globally.

You can generate your Angular 6 project by running the following command in your terminal:

$ ng new pwademo

This will create a project with a structure that looks like:


Angular project structure
Angular project structure. (Large preview)

Most work that’s done will be inside the src/ folder that contains the source code of the application.

Creating The Angular Application

After generating a project, we’ll build a web application that consumes a JSON API and displays the items on the home page. We’ll use the HttpClient service for sending HTTP requests and Angular Material for building the UI.

Adding Angular Material

Thanks to Angular CLI v6 and the new ng add command, adding Angular Material to your project is only one command away. You just need to run the following command from your terminal:

$ cd pwademo
$ ng add @angular/material

Adding Angular Material
Adding Angular Material. (Large preview)

You can see from the screenshot that the command installs the required package from npm and update a bunch of files for setting up Angular Material in your project which previously needed manual updates.

Setting Up HttpClient And Consuming The JSON API

Now, let’s setup the Angular project to use HttpClient for sending HTTP requests. First, you need to import the HttpClientModule module in the main application module in the src/app/app.module.ts file:

/*...*/
import { HttpClientModule } from  '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
/*...*/
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export  class  AppModule { }

That’s it. We can now inject and use HttpClient in any component or service that belongs to the main module.

For demo purposes, we’ll consume a statically generated JSON API from the Simplified JavaScript Jargon GitHub repository. If you are consuming any other resource, make sure you have CORS enabled so the browser doesn’t disallow reading the remote resource due to the Same Origin Policy.

Let’s create a service that interfaces with the API. Inside your project folder, run:

$ ng g service api

This will create a service called ApiService in the src/app/api.service.ts file.

Now open the src/app/api.service.ts file and update it to reflect the following changes:

import { Injectable } from  '@angular/core';
import { HttpClient } from  '@angular/common/http';
import { Observable } from  'rxjs';

export  interface  Item{
name:  string;
description:  string;
url:  string;
html:  string;
markdown:  string;
}

@Injectable({
providedIn:  'root'
})

export  class  ApiService {
private  dataURL:  string  =  "https://www.techiediaries.com/api/data.json";
constructor(private  httpClient:  HttpClient) {}
fetch():  Observable<Item[]>{
return <Observable<Item[]>this.httpClient.get(this.dataURL);
}
}

We first imported the HttpClient and Observable classes then injected the HttpClient in the constructor as httpClient and added a fetch() method which calls the get() method of HttpClient (for sending an HTTP GET request to our JSON endpoint) and returns an Observable that we can subscribe to later.

We also declared an Item interface which represents a single item of the returned JSON data.

Next import this service from the application component. Open the src/app/app.component.ts file and add:

import { Component, OnInit } from  '@angular/core';
import { ApiService } from  './api.service';
import { Item } from  './api.service';

@Component({
selector:  'app-root',
templateUrl:  './app.component.html',
styleUrls: ['./app.component.css']
})
export  class  AppComponent  implements  OnInit{
title  =  'pwademo';
items:  Array<Item>;
constructor(private  apiService:  ApiService){
}
ngOnInit(){
this.fetchData();
}
fetchData(){
this.apiService.fetch().subscribe((data:  Array<Item>)=>{
console.log(data);
this.items  =  data;
}, (err)=>{
console.log(err);
});
}
}

We import the ApiService that we created before and we inject it as apiService, we also import the Item class which represents a single item of our JSON data and we declare the items variable of type Array<Item> which will hold the fetched items.

Next, we add a fetchData() method which calls our fetch() method that we defined in the ApiService which returns an Observable. We simply subscribe to this observable in order to send a GET request to our JSON endpoint and get the response data that we finally assign to the items array.

We call the fetchData() method in the ngOnInit() life-cycle event so it will be called once the AppComponent component is initialized.

Adding The Application UI

Our application UI will consist of a navigation bar and the skeleton of the page which will be created with Angular Material.

Before using an Angular Material component, you’ll need to import its module. Each Material component belongs to its own module.

Open the src/app/app.module.ts file and add the following imports:

/*...*/
import { MatToolbarModule } from  '@angular/material/toolbar';
import { MatCardModule } from  '@angular/material/card';
import { MatButtonModule } from  '@angular/material/button';

@NgModule({
declarations: [
AppComponent
],
imports: [
/*...*/
MatToolbarModule,
MatCardModule,
MatButtonModule
],
providers: [],
bootstrap: [AppComponent]
})
export  class  AppModule { }

We import modules for toolbar, card and button components and we add them to the imports array of the AppModule.

Next, open the src/app/app.component.html file, delete what’s in there and add:

<mat-toolbar  color="primary">
<mat-toolbar-row>
<span>JS-jargon</span>
</mat-toolbar-row>
</mat-toolbar>
<main>
<mat-card *ngFor="let item of items">
<mat-card-header>
<mat-card-title>{{item.name}}</mat-card-title>
</mat-card-header>
<mat-card-content>
{{item.description}}
</mat-card-content>
<mat-card-actions>
<a  mat-raised-button  href="{{item.url}}"  color="primary">More</a>
</mat-card-actions>
</mat-card>
</main>

We use Material components to create the UI. The <mat-toolbar> component is used to create a Material toolbar and the <mat-card> component is used to create a Material card etc.

We iterate over the items array which gets populated by the fetchData() method when the component is initialized, and display items as Material cards. Each card contains the name, description and a link for more information (The link is styled as a Material button using the mat-raised-button directive).

This is a screenshot of the application:


Demo Application
Demo Application. (Large preview)

Building The Application For Production

Typically, when checking your application for PWA features you should first build it for production because most PWA features are not added in development. For example, you don’t want to have service workers and caching enabled in development since you will periodically need to update the files.

Let’s build the application for production using the following command:

$ ng build --prod

The production build will be available from the dist/pwademo folder. We can use a tool like http-server to serve it.

First, install http-server using the following command:

$ npm i -g http-server

You can then run it using the following command:

$ cd dist/pwademo
$ http-server -o

The -o option will automatically open the default browser in your system and navigate to the http://127.0.0.1:8080/ address where our web application is available.

Analyzing The Application Using Lighthouse

Let’s now analyze our application using Lighthouse. First, launch Chrome and visit our application address http://127.0.0.1:8080/.

Next, open Developer Tools or press Ctrl + Shift + I and click on the Audit panel.


Perform an audit
Perform an audit. (Large preview)

You preferably need to set the Emulation to Mobile instead of Desktop to emulate a mobile environment. Next, click on Perform an audit… blue button. You’ll have a dialog opened in which you need to choose the types of the audits you want to perform against your web application. Un-check all types but Progressive Web App and click the Run audit button.


Progressive Web App Audits
Progressive Web App Audits. (Large preview)

Wait for the Lighthouse to generate the report. This is a screenshot of the result at this stage:


Initial PWA Report
Initial Report. (Large preview)

Lighthouse performs a series of checks which validate the aspects of a Progressive Web App specified by the PWA Checklist.
We get an initial score of 36100 that’s because we have some audits passed.

Our application has 7 failed audits mainly related to Service Workers, Progressive Enhancement, HTTPS and Web App Manifest which are the core aspects of a PWA.

Registering A Service Worker

The first two failed audits (“Does not register a service worker” and “Does not respond with a 200 when offline”) are related to Service Workers and caching. So what’s a service worker?

A service worker is a feature that’s available on modern browsers which can be used as a network proxy that lets your application intercept network requests to cache assets and data. This could be used for implementing PWA features such as offline support and Push notifications etc.

To pass these audits we simply need to register a service worker and use it to cache files locally. When offline, the SW should return the locally cached version of the file. We’ll see a bit later how to add that with one CLI command.

Recommended reading: Making A Service Worker: A Case Study

Progressive Enhancement

The third failed audit (“Does not provide fallback content when JavaScript is not available”) is related to Progressive Enhancement which is an essential aspect of a PWA and It simply refers to the capability of PWAs to run on different browsers but provide advanced features if they’re available. One simple example of PE is the use of the <noscript> HTML tag that informs users of the need to enable JavaScript to run the application in case It’s not enabled:

<noscript>
Please enable JavaScript to run this application.
</noscript>

HTTPS

The fourth failed audit (“Does not redirect HTTP traffic to HTTPS”) is related to HTTPS which is also a core aspect of PWAs (service workers can be only served from secure origins, except for localhost). The “Uses HTTPS” audit itself is considered as passed by Lighthouse since we’re auditing localhost but once you use an actual host you need a SSL certificate. You can get a free SSL certificate from different services such as Let’s Encrypt, Cloudflare, Firebase or Netlify etc.

The Web App Manifest

The three failed audits (“User will not be prompted to Install the Web App”, “Is not configured for a custom Splash Screen” and “Address bar does not match brand colors”) are related to a missing Web App Manifest which is a file in JSON format that provides the name, description, icons and other information required by a PWA. It lets users install the web app on the home screen just like native apps without going through an app store.

You need to provide a web app manifest and reference it from the index.html file using a <link> tag with rel property set to manifest. We’ll see next how we can do that automatically with one CLI command.

Implementing PWA Features

Angular CLI v6 allows you to quickly add PWA features to an existing Angular application. You can turn your application into a PWA by simply running the following command in your terminal from the root of the project:

$ ng add @angular/pwa

The command automatically adds PWA features to our Angular application, such as:

  • A manifest.json file,
  • Different sizes of icons in the src/assets/icons folder,
  • The ngsw-worker.js service worker.

Open the dist/ folder which contains the production build. You’ll find various files but let’s concentrate on the files related to PWA features that we mentioned above:

A manifest.json file was added with the following content:

{
    "name": "pwademo",
    "short_name": "pwademo",
    "theme_color": "#1976d2",
    "background_color": "#fafafa",
    "display": "standalone",
    "scope": "/",
    "start_url": "/",
    "icons": [
        {
        "src": "assets/icons/icon-72x72.png",
        "sizes": "72x72",
        "type": "image/png"
    },
    {
        "src": "assets/icons/icon-96x96.png",
        "sizes": "96x96",
        "type": "image/png"
    },
    {
        "src": "assets/icons/icon-128x128.png",
        "sizes": "128x128",
        "type": "image/png"
    },
    {
        "src": "assets/icons/icon-144x144.png",
        "sizes": "144x144",
        "type": "image/png"
    },
    {
        "src": "assets/icons/icon-152x152.png",
        "sizes": "152x152",
        "type": "image/png"
    },
    {
        "src": "assets/icons/icon-192x192.png",
        "sizes": "192x192",
        "type": "image/png"
    },
    {
        "src": "assets/icons/icon-384x384.png",
        "sizes": "384x384",
        "type": "image/png"
    },
    {
        "src": "assets/icons/icon-512x512.png",
        "sizes": "512x512",
        "type": "image/png"
    }
    ]
}

As you can see, the added manifest.json file has all the information required by a PWA such as the name, description and start_url etc.


Angular project structure
Angular project structure. (Large preview)

The manifest.json file, links to icons with different sizes, that were also added automatically in the assets/icons folder. You will, of course, need to change those icons with your own once you are ready to build the final version of your PWA.


Angular project structure
Angular project structure. (Large preview)

In the index.html file, the manifest.json file is referenced using:

<link  rel="manifest"  href="manifest.json">

The ngsw-worker.js file, was also automatically added, which contains the service worker. The code to install this service worker is automatically inserted in the src/app/app.module.ts file:

...
import { ServiceWorkerModule } from  '@angular/service-worker';

@NgModule({
declarations: [
AppComponent
],

imports: [
...
ServiceWorkerModule.register('/ngsw-worker.js', { enabled:  environment.production })
],

The @angular/service-worker is installed by the ng add command and added as a dependency to pwademo/package.json:

"dependencies": {
...
"@angular/service-worker": "^6.1.0"
}

The service worker build support is also enabled in the CLI. In the angular.json file a "serviceWorker": true configuration option is added.

In the index.html file a meta tag for theme-color with a value of #1976d2 is added (It also corresponds to the theme_color value in the manifest.json file):

<meta  name="theme-color"  content="#1976d2">

The theme color tells the browser what color to tint UI elements such as the address bar.

Adding the theme color to both the index.html and manifest.json files fixes the Address Bar Matches Brand Colors audit.

The Service Worker Configuration File

Another file src/ngsw-config.json is added to the project but It’s not a required file for PWAs. It’s a configuration file which allows you to specify which files and data URLs the Angular service worker should cache and how it should update the cached files and data. You can find all details about this file from the official docs.

Note: As of this writing, with the latest 6.1.3 previous ng add @angular/pwa command will fail with this error: Path “/ngsw-config.json” already exists so for now the solution is to downgrade @angular/cli and @angular/pwa to version 6.0.8.

Simply run the following commands in your project:

$ npm i @angular/cli@6.0.8
$ ng i @angular/pwa@6.0.8
$ ng add @angular/pwa

Now let’s re-run the audits against our local PWA hosted locally. This is the new PWA score:


Initial PWA Report
PWA Report. (Large preview)

The Angular CLI doesn’t automatically add the JavaScript fallback code we mentioned in the Progressive Enhancement section so open the src/index.html file and add it:

<noscript>
Please enable JavaScript to run this application.
</noscript>

Next, rebuild your application and re-run the audits. This is the result now:


Initial PWA Report
PWA Report. (Large preview)

We have only one failed audit which is related to HTTPS redirect. We need to host the application and configure HTTP to HTTPS redirect.

Let’s now run the audits against a hosted and secured version of our PWA.


PWA Final Report
PWA Final Report. (Large preview)

We get a score of 100100 which means we’ve successfully implemented all core tenets of PWAs.

You can get the final code of this demo PWA from this GitHub repository.

Conclusion

In this tutorial, we’ve built a simple Angular application and have turned it into a PWA using Angular CLI. We used Google’s Lighthouse to audit our application for PWA features and explained various core tenets of PWAs such as Service Workers for adding offline support and push notifications. The Web Manifest file for enabling add-to-home-screen and splash screen features, Progressive Enhancement as well as HTTPS .

You may also need to manually check for other items highlighted (under the “Additional items to manually check” section) but not automatically checked by Lighthouse. These checks are required by the baseline PWA Checklist by Google. They do not affect the PWA score but it’s important that you verify them manually. For example, you need to make sure your site works cross-browser and that each page has a URL which is important for the purpose of shareability on social media.

Since PWAs are also about other aspects such as better perceived performance and accessibility, you can also use Lighthouse for auditing your PWA (or any general website) for these aspects and improve it as needed.

Smashing Editorial
(rb, ra, yk, il)


Source: Smashing Magazine

Growing a Business Is About the Customer, Not the Product

Gary Tramer is the co-founder of successful sales engine enterprises SearchWords and LeadChat, and most recently PoweredLocal, a wireless marketing and data analysis automation system. As an expert in sales, lead generation and conversion maximization, Gary is the perfect person to talk to about how businesses create and grow customer bases.

You Should Never Build a Product Before You Sell It

The first thing most people think about when launching a new enterprise is what they’ll be selling, but what they should really be focusing on is who they’ll be selling to. Although your product is important, no matter how good it is, if people aren’t interest in buying it, then your business is likely going to struggle.

When Gary Tramer first became an entrepreneur, the term “start-up” hadn’t even been popularized yet. All he had to rely on for launching a business were past models, all of which told him that a business plan and a well-developed product were the ways to achieve success.

But after spending over $200,000 on development and none on marketing, all Gary and his business partner had achieved was an amazing product that nobody has ever used. The lesson learned was painful but important: never build something before you sell it.

But that doesn’t mean you should give up either.

The hardest part of starting a new business is figuring out why people should care and, more importantly, why they would want to spend their money on it.

Using his personal experience as a door-to-door salesperson, Gary began his first successful enterprise, SearchWords, by signing clients up to SEO packages before he had even created an operating team — testing the product’s viability long before it ever existed.

After three months he had gained over 600 clients that had paid upfront, and three years later that client base had grown to over 6000.

But Gary and his partners soon had a “mass realization” that trying to sell something that directly competed with giant companies like Google probably wasn’t going to work in the long run.

They decided to dig a little deeper, and discovered that one of the main operating issues for SearchWords was converting website visits into actual purchases. And after building a solid client base first, they created a second successful business (LeadChat) out of fixing that problem for people.

Then they did it again by identifying a problem with the LeadChat model — but this time for an ecommerce business.

People asked us “What’s the secret to making ecommerce work?”, and the secret was that Facebook allowed us to target people quite uniquely … We also had an email database that we were growing [so] that we could re-market to people, and we knew everyone visiting the website by using web cookies.

This experience taught Gary Tramer something fundamental about what a successful business looks like. You need customers, but you also need to know them – and collecting data is the best way to achieve that.

The post Growing a Business Is About the Customer, Not the Product appeared first on SitePoint.


Source: Sitepoint

Visual Studio Live Share Can Do That?

Visual Studio Live Share Can Do That?

Visual Studio Live Share Can Do That?

Burke Holland

2018-09-19T13:30:17+02:00
2018-09-19T11:39:28+00:00

A few months ago, Microsoft released its free Visual Studio (VS) Live Share service. VS Live Share is Google Docs level collaboration for code. Multiple developers can collaborate on the same file at the same time without ever leaving their own editor.

After the release of Live Share, I realized that many of us have resigned ourselves to being isolated in our code and we’re not even aware that there are better ways to work with a service like VS Live Share. This is partly because we are stuck in old habits and partly because we just aren’t aware of what all VS Live Share can do. That last part I can help with!

In this article, we’ll go over the features and best practices for VS Live Share that make developer collaboration as easy as being an “Anonymous Hippo.”


list of anonymous animals in Google Docs
Google Docs has an interesting way of handling anonymous participants (Large preview)

Share Your Code

Live Share comes as an extension for both Visual Studio and Visual Studio Code (VS Code). In this article, we’re going to focus on VS Code.


vs code live share extension readme page
(Large preview)

You can also install it via the VS Live Share Extension Pack, which includes the following extensions, all of which we are going to cover in this article…

  • VS Live Share
  • VS Live Share Audio
  • Slack Chat extension

Once the extension is installed, you will need to log in to the VS Live Share service. You can do that by opening the Command Palette Ctrl/Cmd + Shift + P and select “Sign In With Browser”. If you don’t log in and you try and start a new sharing session, you will be prompted to log in at that time.


vs code command palette showing option to sign in with browser
Use the VS Code Command Palette to start a new Live Share session (Large preview)

There are several ways to kick off a VS Live Share session. You can do it from the Command Palette, you can click that “Share” button in the bottom toolbar, or you can use the VS Live Share explorer view in the Sidebar.


vs code with boxes drawn around the different parts of the UI that can be used to start a live share session
There are a myriad of ways to start a new VS Live Share session (Large preview)

A link is copied to your clipboard. You can then send that link to others, and they can join your Live Share session — provided they are using VS Code as well. Which, aren’t we all?

Now you can collaborate just like you were working on a regular old Word document:

The other person can not only see your code, but they can edit it, save it, execute it and even debug it. For you, they show up as a cursor with a name on it. You show up in their editor the same way.

The VS Live Share Explorer

The VS Live Share explorer shows up as a new icon in the Action Bar — which is that bar of icons on the far right of my screen (the far left of yours for default Action Bar placement). This is a sort of “ground zero” for everything VS Live Share. From here, you can start sessions, end them, share terminals, servers, and see who is connected.


vs live share viewlet
The VS Live Share Explorer is a heads-up view of all things Live Share (Large preview)

It’s a good idea to bind a keyboard shortcut to this VS Live Share Explorer view so that you can quickly toggle between that and your files. You can do this by pressing Ctrl/Cmd + K (or Ctrl/Cmd + S) and then searching for “Show Live Share”. I bound mine to Ctrl/Cmd + L, which doesn’t seem to be bound to anything else. I find this shortcut to be intuitive (L for Live Share) and easy to hit on the keyboard.


the keyboard binding screen in vs code with a binding created for the vs live share viewlet
You can create a binding for the VS Live Share Explorer viewlet (Large preview)

Share Code Read-Only

When you start a new sharing session, you will be notified thusly and asked if you would like to share your workspace read-only. If you select read-only, people will be able to see your code and follow your movements, but they will not be able to interact.


vs code notification prompting user to choose read-only sharing
Sharing sessions are read-write by default, but you can make them read-only (Large preview)

This mode is useful when you are sharing with someone that you don’t necessarily trust — maybe a vendor, partner or an estranged ex.

It’s also particularly useful for instructors. Note that at the time of this writing, VS Live Share is locked to 5 concurrent users. Since you probably are going to want more than that in read-only mode, especially if you’re teaching a group, you can up the limit to 30 by adding the following line to your User Settings file: Ctrl/Cmd + ,.

"liveshare.features": "experimental"

Change The Default Join Behavior

Anyone with the link can join your Live Share session. When they join, you’ll see a pop-up letting you know. Likewise, when they disconnect, you get notified. This is the default behavior for VS Live Share.


vs code notification with the name of the person who has joined the live share session
VS Code will alert you whenever someone joins your session (Large preview)

It’s a good idea to change this so that you have to manually approve someone before they can join your session. This is to protect you in the case where you go to lunch and forget to disconnect your session. Your co-workers can’t log back in, change one letter in your database connection string and then laugh while you spend the next four hours trying to figure out how your life has gone so horribly wrong.

To enable this, add the following line to your User Settings file Ctrl/Cmd + ,.

"liveshare.guestApprovalRequired": true

Now you’ll be prompted when someone wants to join. If you block someone, they are blocked for the duration of the session. If they try to join again, you won’t be notified and they will be unceremoniously rejected by VS Live Share.

Go and enjoy your lunch. Your computer is safe.

Focus Followers

By default, anyone who joins your Live Share session is “following” you. That means that their editor will load up whatever file you are in and scroll whenever you scroll. Even if you switch files, participants will see exactly what you see.

The second that a person makes changes to a file, they are no longer following you. So if you are both working on a file together, and then you go to a different file, they won’t automatically go with you. That can lead to a lot of confusion with you talking about code in the file you’re in while the other person is looking at something entirely different.

Besides just telling each other where you are (which works, btw), there is a handy command called “Focus Participants” that is in the Command Palette Ctrl/Cmd + Shift + P.


vs code command palette showing live share focus command
Access the “focus” command from the VS Code Command Palette (Large preview)

You can also access it as an icon in the VS Live Share Explorer view.


vs code live share explorer focus icon
Send a follow request by clicking the follow icon in the VS Live Share Explorer viewlet (Large preview)

This will focus your participants on the next thing you click on or scroll to. By default, VS Live Share focus requests are accepted implicitly. If you don’t want people to be able to focus you, you can add the following line to your User Settings file.

"liveshare.focusBehavior": "prompt"

Also note that you can follow participants. If you click on their name in the VS Live Share Explorer view, you will begin to follow them.

Because following is turned off as soon as the other person begins editing code, it can be tough to know exactly when people are following you and when they aren’t. One place you can look is in the VS Live Share Explorer view. It will tell you the file that a person is in, but not whether or not they are following you.

A good practice is to just remember that focus is always changing so people may or may not see what you see at any given time.

Debug As A Team

Participants can share any debug sessions that you run. If you start a debug session, they will get the exact same experience that you do. If it breaks on your side, it breaks on theirs, and they get the full debug view into all of your code.

They can step in, out, over, add watches, evaluate in the Debug Console; any debugging that you can do, they can do too, and they can control it.

Debugging can also be launched by participants. Be default, though, VS Code does not allow your debugger to be started remotely. To enable this, add the following line to your User Settings file Ctrl/Cmd + ,:

"liveshare.allowGuestDebugControl": true

Share Your Terminal

A lot of the work we do as developers isn’t in our code; it’s in the terminal. Some days it seems like I spend about as much time on my terminal as I do in my editor. This means that if you have an error on your terminal or need to type some command, it would be nice if your participants in VS Live Share can see your terminal in addition to your code.

VS Code has an integrated terminal, and you can share it with VS Live Share.


vs code command palette with share terminal selected
Access the “Share Terminal” command from the VS Code Command Palette (Large preview)

When you do this, you have the opportunity to share your terminal as read-only, or as read-write.


vs code prompting to share terminal as read-only or read-write
Always share your terminal read-only unless you absolutely have to share it with write access (Large preview)

By default, you should be sharing your terminal as read-only. When you share your terminal read-write, the user can execute arbitrary commands directly on your terminal. Let that sink in for a moment. That’s heavy.

It goes without saying that having remote write access to someone’s terminal comes with a lot of trust and responsibility. You should only ever share your terminal read-write with people that you trust implicitly. Estranged ex’s are probably off the table.

Sharing your terminal read-only safely allows the person on the other end of the line to see what you are typing and your terminal output in real time, but restricts them from typing anything into that terminal.

Should you find yourself in a scenario where it would be quicker for the other person to just get at your terminal instead of trying to walk you through some wacky command with a ton of flags, you can share your terminal read-write. In this mode, the other person has full remote access to your terminal. Choose your friends wisely.

Share Your localhost

In the video above, the terminal command ends with a link to a site running on http://localhost:8080. With VS Live Share, you can share that localhost so that the other person can access it just like it was their own localhost.

If you are running a shared debug session, when the participant hits that localhost URL on their end, it will break for both of you if a breakpoint is hit. Even better, you can share any TCP process. That means that you can share something like a database or a Redis cache. For instance, you could share your local Mongo DB server. Seriously! This means no more changing config files or trying to get a shared database up. Just share the port for your local Mongo DB instance.

Share The Right Files The Right Way

Sometimes you don’t want collaborators to see certain files. There are likely private keys and passwords in your project that are not checked into source control and not suitable for public viewing. In this case, you would want to hide those files from anyone participating in your Live Share session.

By default, VS Live Share will hide any file that is specified in your .gitignore. If there is a file that you want to hide, just add it to your .gitignore. Note though, that this only hides the file in the project view. If you are in a shared debugging session and you step into a file that is in the .gitignore, it is still loaded up in the editor and your collaborators will be able to see it.

You can get more fine-grained control over how you share files by creating a .vsls.json file.

For instance, if you wanted to make sure that any files that are in the .gitignore are never visible, even during debugging, you can set the gitignore property to exclude.

{
    "$schema": "http://json.schemastore.org/vsls",
    "gitignore":"exclude"
}

Likewise, you could show everything in your .gitignore and control file visibilty directly from the .vsls.json file. To do that, set the gitignore to none and then use the excludeFiles and hideFiles properties. Remember — exclude means never visible, and hide means “not visible in the file explorer.”

{
    "$schema": "http://json.schemastore.org/vsls",
    "gitignore":"none",
    "excludeFiles":[
        "*.env"
    ],
    "hideFiles": [
        "dist"
    ]
}

Sharing And Extensions

Part of the appeal of VS Code to a lot of developers is the massive extensions marketplace. Most people will have more than a few installed. It’s important to understand how extensions will work, or not work, in the context of VS Live Share.

VS Live Share will synchronize anything that is specific to the context of the project you are sharing. For instance, if you have the Vetur extension installed because you are working with a Vue project, it will be shared across to any participants — regardless of whether or not they have it installed as well. The same is true for other context-specific things, like linters, formatters, debuggers, and language services.

VS Live Share does not synchronize extensions that are user specific. These would be things like themes, icons, keyboard bindings, and so on. As a general rule of thumb, VS Live Share shares your context, not your screen. You can consult the official docs article on this subject for a more in-depth explanation of what extensions you can expect to be shared.

Communicate While You Collaborate

One of the first things people do on their inaugural VS Live Share experience is to try to communicate by typing in code comments. This seems like the write (get it?) thing to do, but not really how VS Live Share was designed to be used.

VS Live Share is not meant to replace your chat client of choice. You likely already have a preferred chat mechanism, and VS Live Share assumes that you will continue to use that.

If you’re already using Slack, there is a VS Code extension called Slack Chat. This extension is still a tad early in its development, but it looks quite promising. It puts VS Code in split mode and embeds Slack on the right-hand side. Even better, you can start a Live Share session directly from the Slack chat.


vs code slack chat extension
The Slack Chat extension puts Slack inside of your editor (Large preview)

Another tool that looks quite interesting is called CodeStream.

CodeStream

While VS Live Share looks to improve collaboration from the editor, CodeStream is aiming to solve that same problem from a chat perspective.

The CodeStream extension allows you to chat directly within VS Code and those chats become part of your code history. You can highlight a chunk of code to discuss and it goes directly into the chat so there is context for your comments. These comments are then saved as part of your Git repo. They also show up in your code as little comment icons, and these comments will show up no matter which branch you are on.

When it comes to VS Live Share, CodeStream offers a complimentary set of features. You can start new sessions directly from the chat pane, as well as by clicking on an avatar. New sessions automatically create a corresponding chat channel that you can persist with the code, or dispose of when you are done.

If chatting isn’t enough to get the job done, and you need to collaborate like it’s 1999, help is just a phone call away.

VS Live Share Audio

While VS Live Share isn’t trying to reinvent chat, it does re-invent your telephone. Kind of.

With the VS Live Share Audio extension, you can call someone directly and do voice chat from within VS Code.


vs code command palette showing start audio call option
Make audio calls from VS Code using the VS Live Share Audio extension (Large preview)

The other person will then get a prompt to join your call.


vs code notification asking if you would like to join the audio call
VS Code will ask you if you want to join an audio call that is in process (Large preview)

You will see a speaker icon in the bottom status bar when you are connected to a call. You can click on that speaker to change your audio device, mute yourself, or disconnect from the call.


vs code options showing options like mute and disconnect for live share audio extension
You have full control over audio settings when in a VS Live Share Audio call (Large preview)

The last tip I’ll give you is probably the most important, and it’s not a fancy feature or obscure setting you didn’t know existed.

Change Your Muscle Memory

We’ve got years of learned behavior when it comes to getting help or sharing our code. The state of developer collaboration tools has been so bad for so long that we are conditioned to paste code into Slack, start an awkward Skype calls that consist mostly of “tell me when you can see my screen”, or crowd around a monitor and point excessively, i.e. stock photo style.


a group of people pointing at a computer screen
(Large preview)

The most important thing you can do to get the most out of VS Live Share is to actually use VS Live Share. And it will have to be a “conscious” effort.

Your brain is good at patterns. You are constantly recognizing and classifying the world around you based on patterns you have identified, and you are so good at it, you don’t even realize you are doing it. You then develop default responses to these patterns. You form instincts. This is why you will default to the old ways of collaboration without even thinking about what you are doing. Before you know it you will be on a Skype call with someone sharing your screen — even if you have Live Share installed.

I’ve written a lot about VS Code and people will ask me from time to time how they can get more productive with their editor. I always say the same thing: the next time you reach for the mouse to do something, stop. Can you do that something with the keyboard instead? You probably can. Look up the shortcut and then make yourself use it. At first it’s going to be slower, but if you are willing to deliberately adopt a different behavior, you will be astonished at how fast your brain will default to the more productive way of doing something.

The same goes for Live Share. You will be on a call sharing your screen when it occurs to you that you could be using Live Share. At that moment, stop; click that “Share” button in the bottom of VS Code.

Yes, the person on the other end may not have the extension installed. Yes, it may take a moment to set it up. But if you work on establishing this behavior now, the next time you go to do this, it will “just work” and it won’t be long before you don’t even have to think about it, and at that point, you will finally have achieved that “Anonymous Hippo” level of collaboration.

More Resources

Smashing Editorial
(rb, ra, il)


Source: Smashing Magazine

3 App and Website Prototyping Tools You Should Check out Today

This article was created in partnership with BAWMedia. Thank you for supporting the partners who make SitePoint possible. Prototyping tools are one of the best means of design communication. They are popular among interactive software system designers, developers, and project managers. Prototyping tools have proved to be key to successful design and development. Same goes […]

The post 3 App and Website Prototyping Tools You Should Check out Today appeared first on SitePoint.


Source: Sitepoint

Fixed Elements And Overlays In XD: Incredibly Easy And Fun Methods For Your Prototypes

Fixed Elements And Overlays In XD: Incredibly Easy And Fun Methods For Your Prototypes

Fixed Elements And Overlays In XD: Incredibly Easy And Fun Methods For Your Prototypes

Manuela Langella

2018-09-18T12:30:32+02:00
2018-09-18T14:30:48+00:00

(This article is kindly sponsored by Adobe.) A fixed element is an object you set to a fixed position on the artboard, allowing other items to scroll underneath. This way, you get a realistic simulation of scrolling on desktop and mobile. With the new overlay feature, you can simulate interactions such as lightbox effects and submenus.

How do famous brands use fixed elements and overlays? Well, let’s take a look at some examples to get some inspiration first.


Examples of brands using fixed elements and overlays
From left to right: 1) McDonald’s mobile home 2) A submenu slides up when you click on the hamburger menu. This is an example of an overlay. 3) Netflix’s Italian mobile website home screen. 4) Netflix sets its call to action as a fixed element. When you scroll down, the button stays fixed to the bottom of the screen. 5) Adobe mobile home 6) By clicking on the menu symbol, a submenu comes out as an overlay. (Large preview)

In this tutorial, we will learn how to set a menu bar as a fixed element and how to apply an overlay transition in a prototype, to simulate a menu opening from the click of a button. Both examples will be done in a mobile template, so that we can see our simulation in action directly on our mobile device. I’ve also included an Illustrator file with icons, which you can use to set up your examples quickly.

Let’s get started.

Preparing The Mobile Template

Open Adobe Xd, and choose the “iPhone 6/7/8 Plus” template. Then, go to File → Save As and choose a name to save your file (mine is mobile.xd).



(Large preview)

Let’s create a restaurant app in which people can select what to order from a list of food.

We will create two home layouts. The first one will be a long page, which we will use to see how fixed navigation works. The second will have a full-screen image, and the user will be able to click and open a menu bar that overlays the home screen.

To get started, click on the artboard icon on the left side, and click to the right of your current artboard. This will create a second identical artboard, near the first one.



(Large preview)

Let’s begin to design our elements, starting with the navigation bar. Click on the Rectangle tool (R) and draw a shape 414 pixels wide and 48 pixels tall. Set its color as #DE4F4F.



(Large preview)

I’ve prepared some icons in Illustrator to use in our layout. Just open the Illustrator file I’ve provided, and drag and drop the icons in your library, as shown below:

Large preview

In doing so, your icons will be automatically uploaded to your Adobe XD library, too.

To learn more about how to use libraries in different apps, read my earlier article, in which I go over some examples of how to add icons and elements to a library (in Illustrator, for instance) and then access them by opening that library in other apps (XD, in this case).

Once you have added the icons, open your XD library. You should see the icons in place:



(Large preview)

Drag and drop the icons on your artboard, as shown below. Position them, and make sure they are all about 25 pixels wide.



(Large preview)

Because we need our icons to be white, we have to modify these. We can directly modify them in the library, as demonstrated in my previous tutorial. With that done, we’ll see them updated in XD directly, without having to drag them from the library again.



(Large preview)

Now that the icons we want are in place, let’s create a logo. Let’s call this app “Gusto”. We’ll simply use the Text tool to add it. (I’m using the Leckerli One font here, but feel free to use whichever you like.) Align the logo to the middle of the navigation bar by clicking “Align center (horizontally)” in the right sidebar.



(Large preview)

Group all of the navigation elements together, and call the group “Menu”. To do this, select all elements in the left panel, right-click and choose “Group”.



(Large preview)


(Large preview)

Let’s add a beautiful hero image. I selected one from Pexels. Drag it on your artboard, and resize its height to 380 pixels.



(Large preview)

Now, click on Rectangle tool (R), and draw a rectangle the same size as the hero image, and place it on the image. Set a gradient for the rectangle’s color, using the values shown in the image below.



(Large preview)

(If you’d like more information about gradients, feel free to see my previous tutorial on how to apply them in XD.)

Insert some white text on the hero image and a circle for a button. Place a little circle with a number on the cart icon as well; we will need it later.



(Large preview)

Next, let’s increase the artboard’s height. We have to do that in order to insert new elements and to create the scrolling simulation.

After double-clicking on the artboard, set its height to 1265 pixels. Be sure that “Scrolling” is set to “Vertical” and that the “Viewport Height” is set to 736 pixels. A little blue marker will allow you to set the scrolling boundary towards the bottom of the artboard, as seen below:



(Large preview)

Let’s add in our content: Gusto’s mouthwatering menu. Click on the Rectangle tool (R) to create a rectangle for the picture that we will add.



(Large preview)

Drag and drop a picture directly into the box we just created; the image will automatically fit in it. Click on it once, and drag the little white circle from an angle inwards, in order to round all of the angles. Their values should be around 25, as shown in the picture below. Get rid of the border by unchecking the border value in the right sidebar.

Large preview

Click on the Text tool (T), and write a title on the right side of the image. I chose Lato as the font, at 14 pixels. Feel free to use another font, but maintain the 14-pixel size.



(Large preview)

Grab the Text tool (T) again, and write some lines for the description (Lato, 10 pixels) and for the price (Lato, 16 pixels).



(Large preview)

Take the Rectangle tool (R) and draw a rectangle of 100 by 30 pixels. Color it with the same orange we used on the button for the hero image; add the text “Add to Cart” with the Text tool (T); and add the cart icon from the library. All of these steps are covered in the short video below:

Finally, click on “Repeat Grid” to create a grid for this section. Once that’s done, we can change images and text easily, as shown in the video below:

If you want to learn more about how to create grids, follow my tutorial.

I used the following pictures from Pexels:

  • https://www.pexels.com/photo/close-up-of-food-247685/
  • https://www.pexels.com/photo/food-dinner-pasta-spaghetti-8500/
  • https://www.pexels.com/photo/selective-focus-photography-of-beef-steak-with-sauce-675951/
  • https://www.pexels.com/photo/food-plate-chocolate-dessert-132694/
  • https://www.pexels.com/photo/bread-food-sandwich-wood-62097/

Add some titles, descriptions and buttons.



(Large preview)

Finally, let’s add a rectangle for the footer, with the text “Gusto” in the center. Set the rectangle’s fill color to #211919.



(Large preview)

Yes! We’ve completed the first template design. Let’s set up our second template before we begin prototyping.

For our second mobile layout, just copy and paste the navigation and hero section from the first layout, and size the hero image to be full screen. Then, add a “Try Now” button to it.

In the short video below, I show you how to copy and paste elements into the second artboard, create a new button with the Rectangle tool (R) and write text on it with the Text tool (T).



(Large preview)

Excellent! Let’s move on and create our prototypes.

Setting Fixed Elements

We want to make the top navigation of our layout fixed, making it stick to its position as we scroll the artboard.

Click on your “Menu” group to select it, and select “Fixed Position” in the right sidebar.



(Large preview)

Important: In order for all elements to scroll under the menu, the menu should be on top of all other elements. Simply place the menu folder at the top, in the left sidebar.



(Large preview)

Now, to see your fixed navigation in action, simply click on the “Desktop Preview” button and try scrolling. You should see this:

Large preview

Tremendously simple, isn’t it?

Setting Overlay Elements

To see how overlays work in XD, we first need to create the elements that will be overlaid. When you click an item in the menu, what would you expect to happen? Exactly: A submenu should appear.

Let’s create three different submenus, like the ones in the image below, using the Rectangle tool (R). I chose a rectangle because the menu will overlay the screen, so it will cover not the whole artboard but just a part of it.

Follow the video below to see how I created the three overlay menus. You will see that I used the Rectangle tool (R), Line tool (L) and Text tool (T). We’re using rectangles to create the menu backgrounds because we need an object to overlay the screen. I’ve included the icons in the Adobe Illustrator file.

Below, you’ll see how I use “Repeat Grid” and how I modify elements inside of it.

Here is the final result:



(Large preview)

We will work on the second home layout at this point.

Set the visual mode to “Prototype”, selecting it from the top left of the screen.



(Large preview)

Next, double-click on the little hamburger menu icon, and drag and drop the little blue arrow onto the “Overlay 1” artboard. When the popup window appears, choose “Overlay” and “Slide right”. Then, click the “Desktop Preview” button to see it in action.

Large preview

Let’s do the same thing with the user icon and cart icon. Double-click on the user icon in Prototype mode, and drag and drop the little blue arrow onto the “Overlay 2” artboard. When the popup window appears, choose “Overlay” and “Slide left”. Then, click the “Desktop Preview” button to see it in action.

Large preview

Now, double-click on the cart icon in Prototype mode, and drag and drop the little blue arrow onto the “Overlay 3” artboard. When the popup windows appears, choose “Overlay” and “Slide left”. Click the “Desktop Preview” button again to see it work.

Large preview

We’re done! These great new features are super-easy to learn, and they’ll add a new level of interactivity simulation to your prototypes.

Quick tip: Want to preview the layout on your phone? Just upload your XD file to Creative Cloud, download the XD app for mobile, and open your document.

Here’s what we have learned in this tutorial:

  • set and create mobile layouts and elements,
  • set fixed elements,
  • use overlays to simulate a click-to-open submenu.

Where would you use fixed elements or overlays? Feel free to share your examples in the comments below!

Smashing Editorial
(il, yk)


Source: Smashing Magazine

20 Best WordPress Calendar Plugins and Widgets

Whether you need an event calendar plugin, a booking system with payments, or a Google calendar widget, this list of plugins will have something to improve your app or site. Take a look at these 20 plugins available for download on Envato Market to see what WordPress is capable of.

WordPress calendar plugins encompass plugins for events, bookings, and appointments. Some transform WordPress into its own private workplace app, while others let you set up a fully functioning scheduling and payment gateway.

Take a look at these 20 WordPress calendar plugins available on Envato Market and you’ll see what I mean.

1. EventOn

The EventOn WordPress event calendar plugin is an excellent turnkey solution that doesn’t skimp on features.

It has a clean, minimal design, and you’ll be up and running quickly and easily.

EventOn - WordPress Event Calendar Plugin

Fully optimized for mobile use, this tiny calendar is big on features:

  • use featured images
  • add your own data fields
  • Google Maps integration
  • calendar widgets and shortcode generator
  • event categories with custom color assignments
  • and much more

Not only can you customize each event with images, maps, icons, colors, and more, but you can also configure your calendar to search and sort in several different ways.

EventOn is a really nice, easy-to-use event calendar plugin that also offers a unique slider addon.

2. SUMO WooCommerce Bookings

SUMO WooCommerce Bookings will transform your WordPress WooCommerce site into a bookings powerhouse.

This is more than just a calendar plugin—it’s a full-fledged WooCommerce booking plugin.

SUMO WooCommerce Bookings

Features include:

  • Google Calendar integration
  • assign users to manage booking availabilities
  • configure reservations and bookings
  • booking detail notifications
  • and much, much more

Appointments, reservations, or events—SUMO WooCommerce Bookings can handle them all.

3. Bookly

You can book and schedule just about anything with this WordPress plugin.

Bookly is an incredible appointment booking system that blurs the line between a WordPress website and a web application.

Bookly - Book Appointments Book Services Book Anything Easy and Fast Booking for Your Clients

This is well designed, fully responsive, and even supports gestures.

You’ll also find:

  • a form builder
  • Google Calendar sync
  • WooCommerce integration
  • SMS and email notifications
  • several online payment gateways
  • and a whole lot more

Customers can book their own appointments, include personal information, and send payment. They can also cancel their own appointments via their confirmation email.

There’s also the ability to create schedules for each staff member—you can even block out holidays.

Bookly‘s customization options and useful features make it more than just a way to serve customers well—it also helps the website owner keep track of staff and appointments at the same time.

4. Calendarize it!

Even though this WordPress calendar plugin is built to work in conjunction with WPBakery Page Builder, it can be used just as easily on its own.

Calendarize it! for WordPress is full of features that can be configured just how you like.

Calendarize it for WordPress

With a very simple design, this calendar plugin can fit in to just about any design scheme or style.

You’ll find many useful features, including, but not limited to:

  • events by user role
  • sidebar widgets and shortcodes
  • Custom Post Types support
  • advanced filtering with custom taxonomies
  • single events, recurring events, arbitrary recurring events, and recurring events with exceptions

You can set up detailed venue pages, leverage Google Maps integration, and use it internationally with multiple languages and date formats.

Calendarize it! is one of the most agile, customizable WordPress calendar plugins.

5. WordPress Pro Event Calendar

There are certain features that you expect with a WordPress calendar plugin; however, there are a few features that really set a plugin apart. Take a look at WordPress Pro Event Calendar and you’ll see a number of advanced features that really make it stand out from the pack.

WordPress Pro Event Calendar

Well designed and fully responsive, this plugin has some really great features:

  • WPML support
  • flexible event settings
  • Google Maps integration
  • subscribe to a calendar
  • custom fields and date range support
  • and more

But what really sets it apart is the ability to import events from ICS feeds and Facebook.

Best of all, WordPress Pro Event Calendar accepts events submitted by front-end users, making it easy for users to add events.

6. Event Booking Pro

Here’s another great option for setting up a fully functional event booking system.

Event Booking Pro is very pro as it boasts over 500 settings!

Event Booking Pro - WP Plugin Paypal or Offline

There are a lot of features with this WordPress calendar plugin, and they are always adding more. Here are a few:

  • unlimited events
  • AJAX control panel
  • offline and multiple booking
  • PayPal, coupon, and CSV integration
  • customize email sent to booker and admin
  • and many, many more

There’s no shortage of shortcodes, it supports CSV, and everything can be customized and styled as you like, making it fit into your WordPress theme design perfectly.

Event Booking Pro is an impressive WordPress calendar plugin.

7. Timetable Responsive Schedule For WordPress

The Timetable Responsive Schedule For WordPress plugin offers a whole different look and approach to WordPress calendar plugins.

With it, you can create a timetable of events easily!

Timetable Responsive Schedule For WordPress

Use the Timetable shortcode generator to create timetable views for classes, medical departments, nightclubs, tutoring, and so on.

Quickly create a timetable by:

  • adding a new event with day, time, category, and more
  • adjust and configure the design and appearance
  • generate your shortcode and place it into a post or page

And that’s it!

There are plenty of event options and many different shortcode options—color picker and font configuration included.

Timetable Responsive Schedule For WordPress also includes a great widget lineup, rounding out one of the best WordPress calendar plugins you’ll find.

8. Booked: Appointment Booking for WordPress

Booked Appointment Booking for WordPress is another solid appointment booking option.

If you’re looking for appointment booking, think about booking Booked.

Booked - Appointment Booking for WordPress

Mobile friendly and with a clean design, this plugin has some nice features:

  • guest booking
  • customer profile pages
  • custom time slots and custom fields
  • customizable customer and admin emails
  • display your calendar with a shortcode or widget
  • and more

I really like the customer profile pages, but being able to display multiple booking agents with assigned calendars is where this WordPress calendar plugin really shines.

If you are considering Booked: Appointment Booking for WordPress, be sure to also look at the Booked add-ons such as Front-End AgentsPayments with WooCommerce, and Calendar Feeds.

9. WordPress Events Calendar Registration & Booking

The WordPress Events Calendar Registration & Booking plugin is feature rich, offering some options you’ll only find in plugin addons.

Everything you need (and maybe more) for successfully setting up a fully functional registration and booking system is right here.

WordPress Events Calendar Registration  Booking

This “out of the box” solution includes:

  • shortcodes
  • color picker
  • multilingual support
  • Google Maps integration
  • recurring events, tickets, and coupons
  • and more

One of the best features, for this plugin and others, is the countdown timer for all your events.

Beautifully designed and leveraging Bootstrap 3.0, the WordPress Events Calendar Registration & Booking should not be overlooked.

10. Booki

Like several of the aforementioned WordPress calendar plugins, Booki offers a full booking system using WordPress.

There are so many great applications for these type of plugins, with each plugin offering a unique perspective on the appointment management process.

Booki - Booking Calendar plugin - A WordPress booking system for online reservation and appointments

You can set up unlimited booking projects and service providers. Options include:

  • add optional extras for bookings
  • online payments via PayPal Express
  • offline payments—book now, pay later
  • admin stats page with summary information
  • sync bookings to a provider’s Google Calendar
  • and more

As for the calendar itself, it displays your booking and appointment calendar with a popup, inline, and more.

Booki is an excellent solution for booking appointments with multiple projects and service providers.

11. Team Booking: WordPress Booking System

This calendar plugin doesn’t try to reinvent the wheel.

Team Booking ties directly into something you’re already probably using: Google Calendar.

Team Booking - WordPress Booking System

Team Booking’s mission is to:

Use Google Calendar to schedule availability.

Additional features include:

  • team booking
  • keep and export your data
  • supports Stripe and PayPal
  • appointment approval system
  • customized forms for each booking type
  • and more

There are also a lot of nice customer features, like displaying reservations and the option to cancel their own appointments.

Team Booking is a fresh take on appointment booking calendars and leverages Google Calendar to the fullest. 

12. WP Booking Calendar

A lot of the WordPress booking calendar plugins include a rich feature set, offering a solid all-in-one solution.

WP Booking Calendar takes a much-needed, refreshingly straightforward approach.

WP Booking Calendar

With minimal configuration, you can set up available time slots, unlimited calendars, confirmations, and more.

Features include:

  • CSV export
  • PayPal integration
  • confirmation emails
  • make multiple reservations
  • unlimited number of time slots and duration
  • and more

You can also set the number of days before a user can make a booking.

WP Booking Calendar is simple without forfeiting great features.

13. Goo Calendar

Goo Calendar is an excellent calendar option.

Build calendars with static and dynamic ranges for your WordPress pages. Once the calendar is set up, publish it, and run it via shortcode on page, post or widget area.

Simple and straightforward, this is a great way to display a full calendar on your website.

Goo Calendar

Features include:

  • both static and dynamic calendars
  • fully customizable to match your look and feel
  • display posts, post meta, Advanced Custom Fields, and custom post types
  • and more

Goo Calendar is a solid solution that provides the basic tools to modify it to your own use.

14. Timetable

A timetable calendar is a great option for situations in which there are several events going on the same day.

Timetable is a plugin with a nice TV guide styled UI and presentation.

Timetable for WordPress

Built on jQuery and CSS3, this plugin lets you add events and modify your timetable from within its modern admin screens.

One of the most powerful features of Timetable is the ability to import and export timetables via CSV. Now you can edit and make changes in Excel or another spreadsheet app and import your changes and added events.

You can also select which program to print, for users who prefer their schedules on paper.

15. Chronosly Event Calendar

Most WordPress calendar plugins focus on the back end and leave most of the design to the designers.

But the Chronosly Event Calendar makes customization as easy as drag and drop.

Chronosly Event Calendar WordPress Plugin

This plugin is fully editable and can be used in one of two ways: basic and advanced.

The advanced features include a whole set of customization tools:

  • custom CSS
  • customize views
  • custom front-end events

Other features include:

  • shortcodes
  • addons marketplace
  • detailed single pages
  • templates marketplace
  • multi-language and Google Maps integration
  • and more

Chronosly Event Calendar can be configured and customized from the comfort of your WordPress admin.

16. Business Calendar

Most of the WordPress calendar plugins we’ve covered focus on the website user.

However, the Business Calendar shifts that focus, as it creates a full-featured internal calendar for each user.

Business Calendar - WordPress Internal Calendar

With the Business Calendar plugin, you can turn a WordPress install into a working platform for business.

Features include:

  • smart invitation system
  • settings are user specific
  • Google Maps localization
  • enable email notifications and reminders
  • creates private page for each event for notes, comments, and file uploads
  • and more

The Business Calendar is a creative approach to using WordPress like an app or full-fledged working platform.

17. HBook: Hotel Booking System

You can use a one-size-fits-all booking plugin for hotels and B&Bs, or you can use a solution built specifically for them.

The HBook hotel booking system is perfect for anyone in the hospitality business.

17 HBook - Hotel Booking System - WordPress Plugin

This snappy plugin includes:

  • seasons
  • rates tables
  • PayPal payment
  • availability calendars
  • booking forms and rules
  • and more

HBook has a clean design and can be configured specifically for hotels, B&Bs, and more!

18. Responsive Event Scheduler

The Responsive Event Scheduler is one of the most beautiful options for publishing event schedules on your website.

It is suitable for music festivals, conferences, conventions, meetings, training, exhibitions etc.

Responsive Event Scheduler

Features include:

  • built with HTML5 and CSS3 — SVG icons enabled
  • one-click color customization
  • event image options
  • fully responsive
  • WPML ready
  • and more

Responsive Event Scheduler is not only impressive from a feature standpoint, but it’s one of the best-looking options you’re going to find.

19. Facebook Events Calendar

Facebook is where everyone is at, but how do you integrate it with your website?

The Facebook Events Calendar is a great way to display your Facebook events online in a super easy way.

Facebook Events Calendar

Features include:

  • displays all events from your Facebook page on the calendar
  • two layouts versions—full and compact
  • using a widget or shortcode, placing this in the page is super easy
  • and more

Facebook Events Calendar is a great way to connect your Facebook with your website.

20. gAppointments: Appointment Booking Addon for Gravity Forms

gAppointments is a great appointment booking addon for Gravity Forms.

If you’re already using Gravity Forms and need to integrate some appointment booking, this solution is certainly worth a look.

gAppointments - Appointment booking addon for Gravity Forms

Features include:

  • supports paid and non-paid booking
  • accepts any payment gateway
  • many options for service intervals and slots
  • and more

Combined with Gravity Forms, gAppointments is a powerful plugin for booking appointments.

Conclusion

WordPress has come a long way since that first default calendar widget. You can see by this list that WordPress has evolved into a web-based tool that can be used day in and day out for all kinds of organizations.

You can dig through Envato Market for more WordPress calendar plugins—and of course, if you can’t find exactly what you’re looking for, you could always code your own!


Source: Nettuts Web Development

Flexbox: How Big Is That Flexible Box?

Flexbox: How Big Is That Flexible Box?

Flexbox: How Big Is That Flexible Box?

Rachel Andrew

2018-09-17T13:30:30+02:00
2018-09-17T11:38:35+00:00

This is the third part of my series on Flexbox. In the past two articles, we have looked at what happens when you create a flex container and explored alignment as it works in Flexbox. This time we are going to take a look at sizing. How do we control the size of our flex items, and what choices is the browser making when it controls the size?

Initial Display Of Flex Items

If I have a set of items, which have variable lengths of content inside, and set their parent to display: flex, the items will display as a row and line up at the start of that axis. In the example below my three items have a small amount of content and are able to display the content of each item as an unbroken line. There is space at the end of the flex container which the items do not grow into because the initial value of flex-grow is 0, do not grow.


Three items with space at the end
The flex items have room to each be displayed on one line (Large preview)

If I add more text to these items, they eventually fill the container, and the text begins to wrap. The boxes are assigned a portion of the space in the container which corresponds to how much text is in each box — an item with a longer string of text is assigned more space. This means that we don’t end up with a tall skinny column with a lot of text when the next door item only contains a single word.


Three items, the final item has longer text and the text wraps
The space is distributed to give more space to a longer item (Large preview)

This behavior is likely to be familiar to you if you have ever used Flexbox, but perhaps you have wondered how the browser is working that sizing out, as if you look in multiple modern browsers you will see that they all do the same thing. This is down to the fact that detail such as this is worked out in the specification, making sure that anyone implementing Flexbox in a new browser or other user agent is aware of how this calculation is supposed to work. We can use the spec to find this information out for ourselves.

The CSS Intrinsic And Extrinsic Sizing Specification

You fairly quickly discover when looking at anything about sizing in the Flexbox specification, that a lot of the information you need is in another spec — CSS Intrisnic and Extrinsic Sizing. This is because the sizing concepts we are using aren’t unique to Flexbox, in the same way that alignment properties aren’t unique to Flexbox. However, for how these sizing constructs are used in Flexbox, you need to look in the Flexbox spec. It can feel a little like you are jumping back and forth, so I’ll round up a few key definitions here, which I’ll be using in the rest of the article.

Preferred Size

The preferred size of a box is the size defined by a width or a height, or the logical aliases for these properties of inline-size and block-size. By using:

.box {
    width: 500px;
}

Or the logical alias inline-size:

.box {
    inline-size: 500px;
}

You are stating that you want your box to be 500 pixels wide, or 500 pixels in the inline direction.

min-content Size

The min-content size is the smallest size that a box can be without causing overflow. If your box contains text then all possible soft-wrapping opportunities will be taken.

max-content Size

The max-content size is the largest size the box can be to contain the contents. If the box contains text with no formatting to break it up, then it will display as one long unbroken string.

Flex Item Main Size

The main size of a flex item is the size it has in the main dimension. If you are working in a row — in English — then the main size is the width. In a column in English, the main size is the height.

Items also have a minimum and maximum main size as defined by their min-width or min-height on the main dimension.

Working Out The Size Of A Flex Item

Now that we have some terms defined, we can have a look at how our flex items are sized. The initial value of the flex properties are as follows:

  • flex-grow: 0
  • flex-shrink: 1
  • flex-basis: auto

The flex-basis is the thing that sizing is calculated from. If we set flex-basis to 0 and flex-grow to 1 then all of our boxes have no starting width, so the space in the flex container is shared out evenly, assigning the same amount of space to each item.

See the Pen Smashing Flexbox Series 3: flex: 1 1 0; by Rachel Andrew (@rachelandrew) on CodePen.

Whereas if flex-basis is auto and flex-grow: 1, only the spare space is distributed, taking the size of the content into account.

See the Pen Smashing Flexbox Series 3: flex: 1 1 auto short text by Rachel Andrew (@rachelandrew) on CodePen.

In situations where there is no spare space, for example when we have more content than can fit in a single line, then there is no space to distribute.

See the Pen Smashing Flexbox Series 3: flex: 1 1 auto long text by Rachel Andrew (@rachelandrew) on CodePen.

This shows us that figuring out what auto means is pretty important if we want to know how Flexbox works out the size of our boxes. The value of auto is going to be our starting point.

Defining Auto

When auto is defined as a value for something in CSS, it will have a very specific meaning in that context, one that is worth taking a look at. The CSS Working Group spend a lot of time figuring out what auto means in any context, as this talk for spec editor Fantasai explains.

We can find the information about what auto means when used as a flex-basis in the specification. The terms defined above should help us dissect this statement.

“When specified on a flex item, the auto keyword retrieves the value of the main size property as the used `flex-basis`. If that value is itself auto, then the used value is `content`.”

So if our flex-basis is auto, Flexbox has a look at the defined main size property. We would have a main size if we had given any of our flex items a width. In the below example, the items all have a width of 110px, so this is being used as the main size as the initial value for flex-basis is auto.

See the Pen Smashing Flexbox Series 3: flex items with a width by Rachel Andrew (@rachelandrew) on CodePen.

However, our initial example has items which have no width, this means that their main size is auto and so we need to move onto the next sentence, “If that value is itself auto, then the used value is content.”

We now need to look at what the spec says about the content keyword. This is another value that you can use (in supporting browsers) for your flex-basis, for example:

.item {
    flex: 1 1 content;
}

The specification defines content as follows:

“Indicates an automatic size based on the flex item’s content. (It is typically equivalent to the max-content size, but with adjustments to handle aspect ratios, intrinsic sizing constraints, and orthogonal flows”

In our example, with flex items that contain text, then we can ignore some of the more complicated adjustments and treat content as being the max-content size.

So this explains why, when we have a small amount of text in each item, the text doesn’t wrap. The flex items are auto-sized, so Flexbox is looking at their max-content size, the items fit in their container at that size, and the job is done!

The story doesn’t end here, as when we add more content the boxes don’t stay at max-content size. If they did they would break out of the flex container and cause overflow. Once they fill the container, the content begins to wrap and the items become different sizes based on the content inside them.

Resolving Flexible Lengths

It’s at this point where the specification becomes reasonably complex looking, however, the steps that need to happen are as follows:

First, add up the main size of all the items and see if it is bigger or smaller than the available space in the container.

If the container size is bigger than the total, we are going to care about the flex-grow factor, as we have space to grow.


flex items with spare space at the end
In the first case our items have available space to grow into. (Large preview)

If the container size is smaller than the total then we are going to care about the flex-shrink factor as we need to shrink.


flex items overflowing the container
In the second case our items are too large and need to shrink to fit into the container. (Large preview)

Freeze any inflexible items, which means that we can decide on a size for certain items already. If we are using flex-grow this would include any items which have flex-grow: 0. This is the scenario we have when our flex items have space left in the container. The initial value of flex-grow is 0, so they get as big as their max-width and then they don’t grow any more from their main size.

If we are using flex-shrink then this would include any items with flex-shrink: 0. We can see what happens in this step if we give our set of flex items a flex-shrink factor of 0. The items become frozen in their max-content state and so do not flex and arrange themselves to fit in the container.

See the Pen Smashing Flexbox Series 3: flex: 0 0 auto by Rachel Andrew (@rachelandrew) on CodePen.

In our case — with the initial values of flex items — our items can shrink. So the steps continue and the algorithm enters a loop in which it works out how much space to assign or take away. In our case we are using flex-shrink as the total size of our items is bigger than the container, so we need to take away space.

The flex-shrink factor is multiplied by the items inner base size, in our case that is the max-content size. This gives a value with which to reduce space. If items removed space only according to the flex-shrink factor then small items could essentially vanish, having had all of their space removed, while the larger item still has space to shrink.

There is an additional step in this loop to check for items which would become smaller or larger than their target main size, in which case the item stops growing or shrinking. Again, this is to avoid certain items becoming tiny, or massive in comparison to the rest of the items.

All that was simplified in terms of the spec as I’ve not looked at some of the more edge-casey scenarios, and you can generally simply further in your mind, assuming you are happy to let Flexbox do its thing and are not after pixel perfection. Remembering the following two facts will work in most cases.

If you are growing from auto then the flex-basis will either be treated as any width or height on the item or the max-content size. Space will then be assigned according to the flex-grow factor using that size as a starting point.

If you are shrinking from auto then the flex-basis will either be treated as any width or height on the item or the max-content size. Space will then be removed according to the flex-basis size multiplied by the flex-shrink factor, and therefore removed in proportion to the max-content size of the items.

Controlling Growing And Shrinking

I’ve spent most of this article describing what Flexbox does when left to its own devices. You can, of course, exercise greater control over your flex items by using the flex properties. They will hopefully seem more predictable with an understanding of what is happening behind the scenes.

By setting your own flex-basis, or given the item itself a size which is then used as the flex-basis you take back control from the algorithm, telling Flexbox that you want to grow or shrink from this particular size. You can turn off growing or shrinking altogether by setting flex-grow or flex-shrink to 0. On this point, however, it is worth using a desire to control flex items as a time to check whether you are using the right layout method. If you find yourself trying to line up flex items in two dimensions then you might be better choosing Grid Layout.

If your flex items are ending up an unexpected size, then this is usually because your flex-basis is auto and there is something giving that item a width, which is then being used as the flex-basis. Inspecting the item in DevTools may help identify where the size is coming from. You can also try setting a flex-basis of 0 which will force Flexbox to treat the item as having zero width. Even if this isn’t the outcome that you want, it will help to identify the flex-basis value in use as being the culprit for your sizing issues.

Flex Gaps

A much-requested feature of Flexbox is the ability to specify gaps or gutters between flex items in the same way that we can specify gaps in grid layout and multi-column layout. This feature is specified for Flexbox as part of Box Alignment, and the first browser implementation is on the way. Firefox expects to ship the gap properties for Flexbox in Firefox 63. The following example can be viewed in Firefox Nightly.

See the Pen Smashing Flexbox Series 3: flex-gaps by Rachel Andrew (@rachelandrew) on CodePen.


Three rows of items with gutter spacing between them
The image as seen in Firefox 63 (Large preview)

As with grid layout, the length of the gap is taken into account before space is distributed to flex items.

Wrapping Up

In this article, I’ve tried to explain some of the finer points of how Flexbox works out how big the flex items are. It can seem a little academic, however, taking some time to understand the way this works can save you huge amounts of time when using Flexbox in your layouts. I find it really helpful to come back to the fact that, by default, Flexbox is trying to give you the most sensible layout of a bunch of items with varying sizes. If an item has more content, it is given more space. If you and your design don’t agree with what Flexbox thinks is best then you can take control back by setting your own flex-basis.

Smashing Editorial
(il)


Source: Smashing Magazine

Monthly Web Development Update 9/2018: Native Lazy Loading And Imaginary Work

Monthly Web Development Update 9/2018: Native Lazy Loading And Imaginary Work

Monthly Web Development Update 9/2018: Native Lazy Loading And Imaginary Work

Anselm Hannemann

2018-09-14T14:50:19+02:00
2018-09-14T13:06:51+00:00

It’s an interesting concept to compare JavaScript with CO2 and yet a very valid one. Alex Russel who works for the Chrome team and has a lot of insights into the current state of the web says that using too much JavaScript or using it exclusively (without progressive enhancement/graceful degradation) will have the same effect as too much CO2 for the ecosystem on planet Earth — the ecosystem will fall apart. And just like we need a certain amount of CO2 to live, we need JavaScript on the web. It’s that fine line that makes the difference — the line between not too much and none at all.

I feel that with the native browser APIs that we have these days we have a fantastic opportunity to build great web services without bloating them too much and without relying only on JavaScript. We can enhance native elements with the Custom Elements API easily via ES6 Classes, with so little code that it seems ridiculous to build all that on your own in a third-party framework. Coincidentally, the Github engineering team published an article about how they dropped jQuery entirely and what they now use instead: native JavaScript and small, lean code that is progressively enhancing their platform. Less code, better maintainability, and more stability.

News

  • Chrome 70 is now in beta, bringing shape detection as an origin trial that allows us to perform QR code reading, face detection, and text recognition in images. The Web Authentication API got some updates, too, and referrerpolicy support was added to <script> elements. This version will also deprecate Custom Elements v0, HTML Imports, and Shadow DOM v0.
  • Finally, with Firefox 62, Mozilla ships ::selection instead of :-moz-selection. They also implemented flat(), and flatMap() for JavaScript arrays and developers get a new Shape Path Editor.
  • Chrome 69 is out and brings us CSS Scroll Snap Points, the CSS viewport-fit property for cutout-displays like the one of iPhone X, and the Web Locks API which allows scripts running in one tab or worker to asynchronously acquire a lock, hold it while work is performed, and then release it. The update also comes with CSS conic gradient support, toggleAttribute() (which is similar to the classList.toggle() method but for attributes), and flat() and flatMap() for arrays. Unfortunately, this release changed how the browser displays the URL, and it seems that people consider it a security bug. Let’s see how that will evolve.
  • With Firefox 62 supporting variable web fonts, we finally have support in all major browsers and can use it widely now to improve performance, be more creative with typography, and reduce data traffic drastically.
  • Manuel Rego Casasnovas wrote about recent changes on CSS Grid Layout in percentages and indefinite height in the Chrome browser.
  • Anyone who isn’t an expert would be hard-pressed to explain how tracking on the internet actually works. That’s why Firefox now changes their default settings and enforces tracking blocking in their browser by default.
  • PHP7.3 is coming soon with new Heredoc and Nowdoc syntax, trailing commas in function calls, is_countable(), array_key_first(), array_key_last(), and Argon2 password hash enhancements.

General

  • Alex Russell’s “The ‘Developer Experience’ Bait-and-Switch” is a great piece that explains the toxic environments we currently build for the web and why JavaScript can be compared to CO2 — both are needed in small portions, but if there’s too much of it, it’ll put the entire ecosystem (the web) at risk. A thoughtful article that I recommend everyone here to read, share, and remember.
  • As Alexa, Cortana, Siri, and even customer support chat bots become the norm we have to start considering not only how our content looks but how it could sound. We can — and should — use HTML and ARIA to make our content structured, sensible, and most importantly, meaningful.

Web Performance

Security

  • Nightwatch Cybersecurity published a security vulnerability in Android that exposes information about the user’s device to all applications running on it. This seems to include the WiFi network name, BSSID, local IP addresses, DNS server information, and the MAC address — all in all quite a lot of private information that allows people to track individual Android devices. Unfortunately, all Android OS versions including forks (except for Android P/9 where a fix was provided) seem to be affected with no plan to fix older versions.

CSS

  • Chen Hui Jing explains how to customize radio buttons without compromising their accessibility.
  • CSS Shapes have quite some history already. Brought to the web early by an initiative of the Adobe Web team, browser vendors removed the implementations soon again, and are now slowly coming back with iterated, improved specifications and implementations. Rachel Andrew shares how to implement CSS Shapes.
  • Sara Soueidan wrote down the reasons she switched from defining CSS colors as HEX or RGB to HSL and what the benefits are.
  • With the web’s growth come new features to better accommodate its new form factors and use cases. One feature I’m excited about is the color-adjust property, proposed in CSS Color Module Level 4. It is an acknowledgment that the web will continue to show up on devices that have less-than-stellar displays.
Color harmonies
Creating color harmonies becomes a piece of cake with HSL. (Image credit)

HTML & SVG

JavaScript

Accessibility

  • Ethan Marcotte reflects on what accessibility means and realizes that it’s not about making a website compatible with some assistive technology or software but about making it usable for everyone who wants to access it, regardless of the technology. This is a huge difference because his approach includes people who have difficulties reading a website even though they use the same browser and the same laptop as you. Maybe they are in bright sunlight, have difficulties with small text, or get distracted by bright colors or animated elements.
  • Eric Bailey emphasizes how important it is to manually test for accessibility.
  • Scott O’Hara shares a breadcrumb navigation using aria-label to provide an accessible name and aria-current to indicate the currently active link.

Work & Life

Real Work vs. Imaginary Work
We all have been there before: Imagining a solution in your head and implementing it are two entirely different things. (Image credit)

Going Beyond…

  • I love the concept of doodling, and even though I don’t do it regularly, it always fascinates me. Doodle Addicts is a platform that collects doodles from people all around the world. A nice gallery to get inspiration from.
  • Jonny Brooks-Bartlett wrote an interesting article on why so many data scientists are leaving their jobs. The job might sound quite interesting and like a good bet these days, but often expectations don’t match reality and politics and ethical decisions are extremely difficult.
  • Marco Lambertini explains how technology can help us save the planet, but more than anything we need to learn to value nature and its resources.
  • An interesting discussion was raised this week by a very well-known Open Source contributor who tried to change the license of one of their projects in order to prevent companies who support the U.S. ICE institution from using their software. The change was quickly reverted after it was revealed that it wasn’t legally enforceable. However, the entire topic (which comes up way more often lately) shows that more and more people think about the impact of their work. They don’t want it to be used for bad, but for good. And while the idea of open, non-restricted source is desirable, it’s only if people use it to support human rights and for improving lives. I’m curious about new solutions that could ensure this; maybe we’ll see more terms of service for open-source projects soon (which would then be legally binding but may prevent free open-source projects from using them).
Smashing Editorial
(cm)


Source: Smashing Magazine

How to Deploy Your Secure Vue.js App to AWS

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.

Writing a Vue app is intuitive, straightforward, and fast. With low barriers to entry, a component-based approach, and built-in features like hot reloading and webpack, Vue allows you to focus on developing your application rather than worrying about your dev environment and build processes. But, what happens when you are ready to deploy your app into production? The choices can be endless and sometimes unintuitive.

As an AWS Certified Solutions Architect, I am frequently asked how to deploy Vue apps to AWS. In this tutorial, I will walk you through building a small, secure Vue app and deploying it to Amazon Web Services (AWS). If you’ve never used AWS, don’t worry! I’ll walk you through each step of the way starting with creating an AWS account.

About AWS

Amazon Web Services (AWS) is a cloud platform that provides numerous on-demand cloud services. These services include cloud computing, file storage, relational databases, a content distribution network, and many, many more. AWS came into existence not as a retail offering, but rather Amazon’s internal answer to the growing complexity of the infrastructure that was responsible for powering Amazon.com and their e-commerce operations. Amazon quickly realized their cloud-based infrastructure was a compelling, cost-effective solution and opened it to the public in 2006.

At the time of writing this article, AWS is worth an estimated $250B (yes, that’s a B for BILLION) and used by thousands of companies and developers worldwide.

AWS Products

What You Will Build

I feel the best way to learn is by doing. I’ll walk you through building a small, Vue app with an Express REST server. You will secure your app using Okta’s OpenID Connect (OIDC) which enables user authentication and authorization with just a few lines of code.

You will begin by building the Vue frontend and deploy it to Amazon S3. Then you will leverage Amazon CloudFront to distribute your Vue frontend to edge servers all around the world. Lastly, you will create an Express API server and deploy it with Serverless. This API server will contain a method to fetch “secure data” (just some dummy data) which requires a valid access token from the client to retrieve.

The goal of this article is to show you how to leverage multiple AWS services rather than just spinning up a single EC2 instance to serve your app. With this services-based approach, you have a limitless scale, zero maintenance, and a cost-effective way to deploy apps in the cloud.

What is Okta?

Okta is a cloud service that allows developers to manage user authentication and connect them with one or multiple applications. The Okta API enables you to:

Register for a free developer account, and when you’re done, come on back so we can learn more deploying a Vue app to AWS.

Bootstrap Frontend

You are going to build the Vue frontend to your secure app first and deploy it to Amazon S3 and Amazon CloudFront. Amazon S3 (Simple Storage Service) is a highly redundant, object-based file store that is both powerful and featureful. In the scope of this article, we will focus on one of the best features S3 provides: Static website hosting.

To get started quickly, you can use the scaffolding functionality from vue-cli to get your app up and running quickly. For this article, you can use the webpack template that includes hot reloading, CSS extraction, linting, and integrated build tools.

To install vue-cli run:

npm install -g vue-cli@2.9.6

Next up is to initialize your project. When you run the following vue init command, accept all the default values.

vue init webpack secure-app-client
cd ./secure-app-client
npm run dev

The init method should also install your app’s dependencies. If for some reason it doesn’t, you can install them via npm install. Finally, open your favorite browser and navigate to http://localhost:8080. You should see the frontend come alive!

Welcome to Your Vue.js App

About Single Page Applications

When you create an application with Vue, you are developing a Single Page Application (or “SPA”). SPAs have numerous advantages over traditional multi-page, server-rendered apps. It’s important to understand the difference between SPAs and multi-page web applications — especially when it comes to deploying.

A SPA app is often referred as a “static app” or “static website.” Static, in this context, means that your application compiles all its code to static assets (HTML, JS, and CSS). With these static assets, there is no specialized web server required to serve the application to your users.

Traditional web applications require a specialized web server to render every request to a client. For each of these requests, the entire payload of a page (including static assets) is transferred.

Conversely, within an SPA there is only an initial request for the static files, and then JavaScript dynamically rewrites the current page. As your users are navigating your app, requests to subsequent pages are resolved locally and don’t require an HTTP call to a server.

SPA versus Traditional Web Server

Vue-router and Creating Additional Routes

The component of an SPA that is required to rewrite the current page dynamically is commonly referred to as a “router”. The router programmatically calculates which parts of the page should mutate based off the path in the URL.

Vue has an official router that is aptly named vue-router. Since you used the vue-cli bootstrap, your app has this dependency and a router file defined (./src/router/index.js). Before we can define additional routes, we need to create the pages (or components) that you want the router to render. Create the following files in your project:

Homepage: ./src/components/home.vue

<template>
  <div>
    <h1>Home</h1>
    <div>
      <router-link to="/secure">Go to secure page</router-link>
    </div>
  </div>
</template>

Secure Page (not secured… yet!) ./src/components/secure.vue

<template>
  <div>
    <h1>Secure Page</h1>
    <div>
      <router-link to="/">Go back</router-link>
    </div>
  </div>
</template>

Using vue-router, you can inform the application to render each page based on the path.

Modify ./src/router/index.js to match the following code snippet:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/home'
import Secure from '@/components/secure'

Vue.use(Router)

let router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/secure',
      name: 'Secure',
      component: Secure
    }
  ]
})

export default router

Try it out! Tab back to your browser, and you should see the new home screen. If you click on the “Go to secure page” link you will notice the page (and URL) change, but no request was sent to a server!

Understand Hash History

As you navigated between the two pages above, you might have seen that the URL looks different than expected (do you noticed the “#/” at the beginning of the path?)

http://localhost:8080/#/ and http://localhost:8080/#/secure

The reason the URL looks like is because vue-router’s default mode is hash mode. Hash mode simulates a new URL change without instructing the browser to reload the page. This behavior is what allows SPA’s to navigate pages without forcing your browser to make any additional HTTP requests. Vue-router listens for changes in the hash portion of the URL (everything after the “#”) and responds accordingly based on the routes configured.

You can change the mode of vue-router to leverage history mode which will give your app “pretty URLs” like:

http://localhost:8080/secure

But, this comes with a significant drawback — especially when you are deploying. Since your SPA compiles to a static assets, there is just one single entry point index.html. If you try to access a page direction that is not index.html page (i.e.; http://localhost:8080/secure) the web server will return a 404 error. Why? The browser is sending a GET /secure request to the server and trying to resolve to the filesystem “/secure” (and the file doesn’t exist). It does work when you navigate to /secure from the homepage because vue-router prevents the default behavior of the browsers and instructs the router instance to fire in any mode.

By using history mode, you have to take additional steps to make sure page refreshes work correctly. You can read more about HTML5 History Mode. To keep things easy, I will show you a simple trick to ensure your refreshing works with AWS CloudFront.

Enable history mode by modifying ./router/index.js with the following setting.

let router = new Router({
  mode: 'history',
})

Note: The dev server (npm run dev) automatically rewrites the URL to index.html for you. So the behavior you see locally is how it should work in production.

Building Your Single Page Application

Now that you have a simple, two-page frontend working locally, it’s time to build your app and get it deployed to AWS!

Because you used vue-cli scaffolding, a single call to the included build script is all you need. From your project root, run npm run build and webpack will build your application into the target ./dist directory. If the dev server is still running in your console, you can press CTRL+C.

If you open the ./dist folder and you should see the results of the build process:

  • ./index.html – This is the entry point of your SPA. It’s a minified HTML document with links to the apps CSS and JS.
  • ./static – This folder contains all your compiled static assets (JS and CSS)

During the build, you might have noticed the following notification: Tip: built files are meant to be served over an HTTP server. Opening index.html over file:// won’t work. If you want to test your newly compiled application locally, you can use serve (install via npm install -g serve). Run serve ./dist and it will output a URL for you to load into your browser.

This also gives you to have a hands-on experience with the major caveat of history mode with vue-router. After running serve ./dist, click on the “Go to secure page”. You should see a 404 error.

404 Error

Getting Started with AWS

You will need an AWS account to continue beyond this point. If you already have an AWS account, you can skip ahead. If you don’t, it’s a simple process that only takes a few minutes.

  • Navigate to the Amazon Web Services home page
  • Click Sign Up (or if you have signed into AWS recently choose Sign In to the Console)
  • If prompted, you can select “Personal” for account type
  • Complete the required information, add a payment method, and verify your phone number
  • After your account is created, you should receive a confirmation email
  • Log in!

Note: Amazon requires you to enter a payment method before you can create your account. All the services discussed in this article are covered under AWS Free Tier which gives you 12 months FREE.

Host Your App on Amazon S3

Since your SPA is comprised of only static assets, we can leverage Amazon S3 (Simple Storage Service) to store and serve your files.

To get started, you will need to create a bucket. Buckets are a logical unit of storage within S3, and you can have up to 100 buckets per AWS account by default (if you are studying for the AWS Certified Solutions Architect exam, you should know this!). Each bucket can have its own configuration and contain unlimited files and nested folders.

After you log in to your AWS Console, navigate to the S3 console (you can do this under AWS services search for “S3”).

  • Click “Create Bucket” and enter a Bucket name. Important: Bucket names are unique across the entire AWS platform. I chose bparise-secure-app-client for this article, but you might need to be creative with your naming!
  • Click “Create” in the bottom left.

Create S3 Bucket

You should now see your bucket listed. Next, let’s configure it for static website hosting.

  • Click your Bucket name and then choose the “Properties” tab.
  • Click on “Static website hosting” box
  • Choose “Use this bucket to host a website” and add “index.html” as the index document. Click “Save”.

Static website hosting

At the top of the Static website hosting box, you should see a URL for “Endpoint”. This is the publicly accessible URL to view your static website. Open the link into a new browser window, and you should see this:

403 Forbidden

Access Denied and S3 Bucket Policies

Yes, you should see a 403 Forbidden error! By default, S3 bucket permissions are deny all. To access your bucket’s contents, you must explicitly define who can access your bucket. These bucket permissions are called a Bucket Policy.

To add a Bucket Policy, click on the “Permissions” tab and click “Bucket Policy” button at the top. The following policy allows anyone to read any file in your bucket. Make sure to replace “YOUR-BUCKET-NAME” with your actual bucket name.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadAccess",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*"
        }
    ]
}

Bucket Policies can be quite complex and powerful. But, the main parts of the policy that you should be aware of are:

  • "Effect": "Allow"
  • "Principal": "*" – Who the policy covers (“*” implies everyone)
  • "Action": "s3:GetObject" – The action allowed (s3:GetObject allows read-only access to all objects in your bucket)
  • "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*" – Which bucket and objects the policy is about.

Click “Save” on the Bucket Policy editor. You should notice a new error is displayed if you set up the policy correctly:

This bucket has public access

This warning is good advice and a rule of thumb for all S3 buckets. But, since our bucket is exclusively used to host a static website, we don’t have to worry about anyone accessing a file within the bucket they shouldn’t.

Tab back to your browser and refresh the endpoint. You should now see a 404 Not Found error. This error is much easier to resolve because you don’t have any files in your bucket yet.

404 index.html not found

Deploy to AWS with aws-cli

Now that you have a bucket created and permissions correctly set, it’s time to upload your static assets. Although you can do this manually through the interface by using the “Upload” button, I feel using the aws-cli is more efficient.

Installing asw-cli is different based on your OS. Choose one:

The post How to Deploy Your Secure Vue.js App to AWS appeared first on SitePoint.


Source: Sitepoint