Angular

Case Study: Stone Fest 21 – PWA

Living in San Diego, we are surrounded by over 140 craft breweries. Once a year, Stone Brewing hosts an annual celebration, where they invite a bunch of their brewery friends to town and showcase their brews. I have been attending for a number of years, and one of the challenges in attending was having to find the beer on Untappd and check-in. So this year I thought I would whip up a quick Progressive Web App (PWA), that would allow me to quickly locate my beer and check in. Here is a link to the working Stone Fest 21 app.

After assembling the data set of the breweries, the beers, their logos (thanks, Untappd!), I generated the actual Ionic application. Since my buddies were on both iOS and Android, I knew the web was my only publishing option. But before I uploaded the code from Ionic to my server, there were some additional steps required to improve the performance of the PWA. Here is a list of the changes I made to project:

Enable gzip

By default, my Dreamhost account that I hosted Stone Fest 21 on did not have this enabled. So, I had to create a .htaccess file and enable it on the server.

# BEGIN GZIP
< ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
< /ifmodule>
# END GZIP

Improving iOS support

Since PWA support on iOS is not on par with Android was to include some Apple specific meta tags in the head of the index.html file:

< meta name="apple-mobile-web-app-capable" content="yes">
< meta name="apple-mobile-web-app-status-bar-style" content="black">
< meta name="apple-mobile-web-app-title" content="Stone Fest 21">

For more on these tags, see the Apple documentation.

App Icons

Although the manifest.json defines our app icon, not all platform understand this. So as a backup, I add this snippet in the index.html file to assist with that issue:

< link rel="apple-touch-icon" sizes="57x57" href="apple-icon-57x57.png">
< link rel="apple-touch-icon" sizes="60x60" href="apple-icon-60x60.png">
< link rel="apple-touch-icon" sizes="72x72" href="apple-icon-72x72.png">
< link rel="apple-touch-icon" sizes="76x76" href="apple-icon-76x76.png">
< link rel="apple-touch-icon" sizes="114x114" href="apple-icon-114x114.png">
< link rel="apple-touch-icon" sizes="120x120" href="apple-icon-120x120.png">
< link rel="apple-touch-icon" sizes="144x144" href="apple-icon-144x144.png">
< link rel="apple-touch-icon" sizes="152x152" href="apple-icon-152x152.png">
< link rel="apple-touch-icon" sizes="180x180" href="apple-icon-180x180.png">

I used the $ ionic cordova resources command to generate them, then renamed the manually. Since the $ ionic build command will wipe out the www directory, I added them directly to the server.

Updating the BODY tag

One of the items that the Lighthouse test measures is “First Meaningful Paint”. For those who don’t know this term, First Meaningful Paint is the time when page’s primary content appeared on the screen. I added inline CSS to the body tag, so that the browser would render something while the app was starting.

< body style="background-color: #1c1b17; background-image: url('assets/imgs/logo.jpg'); background-position: center; background-repeat: no-repeat;">

Handling the no JavaScript case

Lighthouse also checks what you do if JavaScript was disabled by the user. Remember, this is a Progressive web app. In my case, there was not a lot you can do without JavaScript, but I included this tag to meet the requirement:

< noscript>
< h1>Stone Fest 21 requires JavaScript< /h1>
< /noscript>

Removing Cordova

When you generate an Ionic application, Cordova plugins are automatically integrated, specifically the Splash Screen and Status Bar plugins. Since we are deploying to the web, we can remove Cordova and these plugins from our project. Using $ npm uninstall @ionic-native/splash-screen and $ npm uninstall @ionic-native/status-bar

Edit the app.module.ts to remove the import statements for these two plugins and remove them from the providers array.

In the app.component.ts file also remove the imports. Also, you will remove the injected imports from the arguments in the constructor, as well as the two references to the plugins in the platform.ready check.

If you generated your Ionic application with Cordova integration, there are other plugins and modules that you should remove as well. If you open your package.json file you will several references to cordova-* items. Go ahead and use npm to uninstall them:

  • cordova-plugin-console
  • cordova-plugin-device
  • cordova-plugin-splashscreen
  • cordova-plugin-statusbar
  • cordova-plugin-whitelist
  • and ionic-plugin-keyboard

Depending on what platforms you may have installed, you might also have these modules:

  • cordova-ios
  • cordova-android

Remove them as well.

Finally, we can also remove @ionic-native/core, as we have now scrubbed our Ionic application of any Ionic Native code.

Image Paths

As I checked my Lighthouse score, I noticed that it was flagging how my brewery logos were being called, as well as an accessibility issue around them. To quickly solve this, I adjusted the img tag to reference the full path to the logo and added the alt attribute

< img src="https://aj-software.com/apps/stone/assets/breweries/{{brewery.logo}}" alt="Company Logo">

Enabling the Serviceworker.js code

By default, this code block is commented out in the index.html. Uncomment this block of code and you have a nicely configured service worker ready to go.

if ('serviceWorker' in navigator) {
 navigator.serviceWorker.register('service-worker.js')
 .then(() => console.log('service worker installed'))
 .catch(err => console.error('Error', err));
}

Updating the manifest.json file

The last tweak is updating some of the items in the default manifest.json file.

  1. Update the name and short name. Note: the short name should not be more than 12 characters in length.
  2. Ensure there is an icon available in the proper directory and of the proper size.
  3. Update the theme and background colors to something that matched our app.
  4. Add an orientation value of portrait
{
 "name": "Stone Fest 21",
 "short_name": "Stone Fest",
 "start_url": "index.html",
 "display": "standalone",
 "icons": [{
 "src": "assets/imgs/logo.jpg",
 "sizes": "512x512",
 "type": "image/jpg"
 }],
 "background_color": "#1c1b17",
 "theme_color": "#1c1b17",
 "orientation": "portrait"
}

Summary

After implementing these steps, the Stone Fest 21 app received  the following Lighthouse score:

pwa_score

Hopefully, these guidelines can help you create better PWA using Ionic. Until stencil.js is ready, this is about a good as I can make an Ionic-Angular’s performance. I will be porting this application to stencil shortly and will update this post with the results. The source code is available on my GitHub account.

Advertisements

What is the Ionic Framework?

I had the good pleasure of presenting to a full room at the recent SoCal Code Camp on the Ionic Framework. Here are my slides from the talk.

ionic-slide

The Ionic Framework combines Google’s Angular with Apache’s Cordova to create fast and beautiful cross-platform mobile apps for iOS and Android (and Electron or Progressive Web Apps). Built atop the web technologies you know and love, this solution can help take your web skills beyond the browser.

AngularFire 2 Updates

As I warned in the book about “everything in beta” (a phrase my friend Leif Wells loves to quote), some recent updates to AngularFire 2 impact the To Do application in my book.The reason behind these changes is by breaking AngularFire into smaller modules, your app will load and run faster (always a good thing). For example, if you don’t need the user auth module in AngularFire, no need to load it.

There are just a few minor changes, so let get started…

First, make sure you have installed the latest versions of AngularFire2 and Firebase. Check your package.json and check the version numbers:

"angularfire2": "^4.0.0-rc.0",
"firebase": "^3.9.0"
If you are referencing an older version, update the version numbers and update your node modules.
Next, in the app.module.ts file you need to now import this additional module:
import { AngularFireDatabaseModule } from 'angularfire2/database';

and then include it within the imports array:

imports: [
  BrowserModule,
  HttpModule,
  IonicModule.forRoot(MyApp),
  AngularFireModule.initializeApp(firebaseConfig),
  AngularFireDatabaseModule
]
The tasklist.ts file will also need two changes. The first is to change
import { AngularFire, FirebaseListObservable } from 'angularfire2';

to

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

The AngularFire variable will need to be typed to AngularFireDatabase.

constructor(public navCtrl: NavController, public af: AngularFireDatabase, public dialogs: Dialogs) {...}

Finally, our reference to the data is now just:

this.tasks = af.list('/tasks');

And with that, your Ionic2Do app will run with the latest AngularFire.

Mobile App Development with Ionic is Released!

My Ionic book has just been published by O’Reilly!

Mobile App Development with Ionic 2 Cross-Platform Apps with Ionic, Angular, and Cordova

Mobile App Development with Ionic 2 Cross-Platform Apps with Ionic, Angular, and Cordova

Learn how to build app store-ready hybrid apps with the Ionic 2/3, the framework built on top of Apache Cordova (formerly PhoneGap) and Angular. This practical guide shows you how to use Ionic’s tools and services to develop apps with HTML, CSS, and TypeScript, rather than rely on platform-specific solutions found in Android, iOS, and Windows Phone.

The book takes you step-by-step through Ionic’s powerful collection of UI component and then helps you use it to build three cross-platform mobile apps. Whether you’re new to this framework or have been working with Ionic 1, this book is ideal for beginning, intermediate, and advanced web developers.

  • Understand what a hybrid mobile app is, and what comprises a basic Ionic application
  • Learn how Ionic leverages Apache Cordova, Angular, and TypeScript to create native mobile applications
  • Create a Firebase-enabled to-do application that stores data across multiple clients
  • Build a tab-based National Park explorer app with Google Map integration
  • Develop a weather app with the Darksky weather API and Google’s GeoCode API
  • Debug and test your app to resolve issues that arise during development
  • Walk through steps for deploying your app to native app stores
  • Learn how Ionic can be used to create Progressive Web Apps

The digital version is available now, and the print edition will be out soon. Amazon, Barnes & Noble, or O’Reilly.

Hiking Guide: Joshua Tree released!

We have released our second paid app, Hiking Guide: Joshua Tree! It is available for both iOS and Android for $0.99. The app contains over 20 hikes in the Joshua Tree National Park. You can find a wide range of hikes; from easy to hard, from short to long, the perfect hike is a few taps away.

The app contains USGS topographic maps that outline each trail’s route, as well as providing descriptions of the trail and directions to the trail head.

We hope you enjoy the app and use it explore the many hikes in Joshua Tree National Park.

 

Hybrid Mobile Apps with Ionic 2

rc_cat
I am excited to announce the early access release of my new book, Hybrid Mobile Apps with Ionic 2! For anyone looking to learn about this powerful mobile framework, this book aims to get you up and running. Here is overview:

The book itself provides a solid overview of hybrid mobile development before diving in and walking you through building 3 different applications. In it, I also cover Angular 2, TypeScript and Apache Cordova.

The core of the book focuses on building three applications, each that showcase different aspects of the Ionic Framework; the Ionic CLI, their starter templates, its component library and more.

Now, this is an early release version of the book, meaning there might be an error or two. Plus, Ionic 2 is not quite done yet, so something might break. I will keep a careful eye on its progress and flag anything that might arise. In the meantime, I will be pushing forward on the rest of the book as its technical dependencies allow.

You can pick up your digital copy from O’Reilly’s website now! I hope you enjoy reading it.

Angular 2 CSS Validator

I am working on a new Angular 2 application and one of the inputs allows you to define a CSS color. This is an interesting input to validate.

Valid input includes the standard hex code value (#ff2112), but named colors (rebeccapurple) are also valid.

For the hex code, we can use a standard regular expression to validate directly in-line, but that won’t let us also validate against the CSS names.

RegEx for CSS colors:
/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i

To validate both the hex code and the name we need to use a custom validator.

The basic flow of a validator is to take the input, perform the test(s), and then return the validity.

Create a new file named cssColor.validator.ts and save it within a directory named validators. I like to keep all my custom validators in a validators directory.

We need to import the FormControl module from @angular/forms

import { FormControl } from '@angular/forms';

Next, we need to declare the export function that we can call to validate our input

export function validateCSSColor(c: FormControl) {

Into this function, we will pass in the reference to the form. Now it is a simple matter of performing the tests. We will define the COLOR_REGEXP, then see if the input matches:

let COLOR_REGEXP = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i;
if (COLOR_REGEXP.test(c.value)) {
  return null;
 }

If the input is valid, the validator should just return a null value. Since this is the more probably input type by the user, I opted to test it first.

Next, if the input does not match this regex, we can see if is one of the custom CSS names. The full list of these names can be found here.

let validColors: Array<string> = ["black", "silver", "gray", "white", ...

With our array defined (and properly typed), we test if the input:

if ( validColors.indexOf(c.value.toLowerCase() ) == -1) {
  return { validateCSSColor: { valid: false } };
 } else {
  return null;
 }

Here is where we handle the case where the input matches neither a valid hex code nor a valid CSS name. In this case, we need to return a custom object. This object has one property, which is the name of the validation function (in our case validateCSSColor), and its value also, an object: { valid: false }.

Now our standard Angular validation directives will function, just like the built-in validators. The full code of the validator can be seen here.

With the validator written, we can now reference it within our code. In your component’s .ts file, import the validator:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder, ReactiveFormsModule } from'@angular/forms';
import { validateCSSColor } from'./validators/cssColor.validator';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})

export class AppComponent {
 pwaForm: FormGroup;
 themeColorCtrl: FormControl;
 title = 'Angular 2 Custom Validator Demo';

 constructor(private fb: FormBuilder) {
 this.themeColorCtrl = this.fb.control('', [Validators.required, validateCSSColor]);
 this.pwaForm = this.fb.group({
 themeColor: this.themeColorCtrl,
 });
 }
}

The key addition to this simple component is passing in our custom validator as part of the validator array when we declare the themeColorCtrl.

Let’s set up of HTML file for a simple input for the CSS color, and some feedback. Here is the snippet:

<input type="text" label="Theme Color" formControlName="themeColor" />
<div *ngIf="pwaForm.controls.themeColor.errors">Invalid CSS Color</div>

Now, we have linked our <input> to our component’s FormControl through the formControlName attribute. Then we can test if there is an error by querying ‘pwaForm.controls.themeColor.errors’ and display some feedback to the user.

For a complete example, see the GitHub repo.