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

Customizing Ionic Native Mocks

By design, the Ionic Native Mocks I wrote are very generic. They just return the bare minimum amount of data for them to function. But for them to be more useful in your project, you probably will want to customize them. In this blog post, I will show you how to do this. For this example, we will customize the BarcodeScanner mock, in part, as it is was the plugin that inspired the project.

In your existing Ionic project, first import the actual Ionic native module:

$ npm install --save @ionic-native/barcode-scanner

And the actual Cordova plugin as well,

$ ionic cordova plugin add phonegap-plugin-barcodescanner

Before we update the app.module.ts file, let’s install the mock first. Although the mocks are available via npm, we want to get the code directly from GitHub and the source typescript code (https://github.com/chrisgriffith/ionic-native-mocks/tree/master/src/%40ionic-native-mocks/plugins/barcode-scanner).

In your project, create a new directory named mocks, and create another directory named barcodescanner. Within that directory, download the index.ts file from Github into this directory.

Now let’s adjust out app.module.ts file. Like all Ionic Native modules, we need to import it.

import { BarcodeScanner } from '@ionic-native/barcode-scanner';

Also import our plugin mock as well.

import { BarcodeScannerMock } from '../mocks/barcodescanner';

Instead of including the Ionic Native plugin directly into the providers array, we instead tell Angular to provide a mapping to our mock. This allows us to keep the rest of application referencing the real Ionic Native module, yet use the code from the mock instead.

{ provide: BarcodeScanner, useClass: BarcodeScannerMock }

At this point we could build our app, making calls to the barcode scanner plugin without needing to install on an actual device. But, out of the box, the barcode scanner is going to return an empty string.

But, let’s have it return something that we might want our user to scan. For my original app, it was a QR code on our packaging. Open the index.ts file within our project and change the scan function to

scan(options?: BarcodeScannerOptions): Promise {

  let code='Your Custom Response Here';

  let theResult:BarcodeScanResult= {format:'QR_CODE', cancelled:false, text:code };

  return new Promise((resolve, reject) => {

    resolve(theResult);

  });

}

Save the file, and run the application. Now when you call the barcode scanner, it will return your custom data.

When you are ready to use the real plugin, change the provider and remove the import of the mock. And there you have a basic guide to customizing your Ionic Native Mocks.

Vertical Tabs in Ionic

Recently I started thinking about designing some Ionic applications specifically for larger physical screens (tablets and desktop). I wanted to have a layout much like Slack or Flickr for my iPad.

IMG_1364

The basics of this layout are to have a fixed series of icons (tabs) displayed vertically on the left side of the window, and the rest of the window displays that tab’s content. However, currently, the Ionic Tab component can only be positioned horizontally at the top or bottom of the window. To solve this I turned to the SplitPane component.

This component allows me to have two separate containers (a sidemenu container and the main content container) that I can adjust and populate with content. However, the sidemenu will typically respond to various screen widths. Since I want the element to always be visible regardless of the width, I just needed to include the ‘when’ attribute to the ion-split-pane component and set its value to ‘xs’. See the documentation for the other allowable values.

By default, the width of the sidemenu is between 270px and 28% of the window. Since I just wanted a single row of touchable icons, I need to override this. When I first began playing with this component, those values were not directly exposed, but after filing a GitHub issue, they are now available as Sass variables.

In the variables.scss file, is simply add the following variables:

$split-pane-ios-side-min-width: 70px;
$split-pane-ios-side-max-width: 70px;
$split-pane-md-side-min-width: 70px;
$split-pane-md-side-max-width: 70px;

Adding my Tabs

With the container ready, I could move on to the next step, creating the tabs themselves. Each tab was going to be a simple button component like this:
< button ion-button large block clear icon-only>
  < ion-icon name="md-list">
</ button>

I repeat this for the other tabs I wanted to display. Since I was not using the Tab component, the state management was going to become my responsibility. To handle the visual feedback, I add the following code to each button:

[color]="isList ? 'primary' : 'light'"

This code will set the color of the button based on the boolean state of the variable isList. If it is true, Ionic’s primary color will be used, otherwise, the light color will be applied. I added this to each of the remaining buttons, changing the variable for each button.

The final piece was to add a click handler to each button so I could switch the main content.

(click)="togglePage('List')"
In the app.component.ts file, I added that function. For this demo, it handles the state swapping and basic page navigation:
togglePage(whichPage: string): void {
  this.isList=false;
  this.isLocation=false;
  this.isSelf=false;
  this.isNotifications=false;
  this.isSearch=false;
  this.isCamera=false;

  letnewTab:string='';

  switch (whichPage) {
    case'List':
      this.isList=true;
      newTab='PhotosPage';
      break;
    case'Location':
      this.isLocation=true;
      newTab='LocationsPage';
      break;
    case'Self':
      this.isSelf=true;
      newTab='SelfPage';
      break;
    case'Notifications':
      this.isNotifications=true;
      newTab='NotificationsPage';
      break;
    case'Search':
      this.isSearch=true;
      newTab='SearchPage';
      break;
    case'Camera':
      this.isCamera=true;
      newTab='CameraPage';
      break;
   }

   this.nav.setRoot(newTab);
}
Note: You do need to include the @ViewChild into your component and the proper imports as well.
Now, I have a basic working tab system!

Centering the Tabs

I decided to challenge myself a little further and wanted to have the tabs be vertically centered. Since we can safely use Flexbox, this is actually straight forward.
Rather than adjusting an Ionic tag directly (and possibly some unknown cascade), I wrapped my buttons in a new div and gave it a class of ‘centervert’. The CSS is:
.centervert {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
The trick to making this work is to set the height of the div to be 100%. This tells the webview how to calculate the proper positioning.  Here is what the app looks like:
VertialTabsIonic

Vertical ‘Tabs’

I did add a Footer component to have App settings and Log Out button be anchored to the bottom of the column. The content pages are just Ionic generated stubs. I have posted the source for the shell of the application on my GitHub repo. Have fun!

Speaking on Adobe XD!

BigDesign_340

I am honored to be speaking on Adobe XD at this year’s Big Design Conference in Addison, Texas in September. With my long history of user experience prototyping, Adobe XD is a welcomed addition to my arsenal of tools. Here is the description of the talk:

Go from idea to prototype faster with Adobe Experience Design CC (Beta), the first all-in-one cross-platform tool for designing and prototyping websites and mobile apps. In this session, Chris Griffith will show you how to design and prototype a complete experience using the new Adobe XD app. Learn tips and tricks to immediately be more productive creating a great user experience. He will introduce you to the capabilities of this rapid prototyping tool from its repeat grid to the built-in UI kits. He then will go further and show you how to share your work, gain feedback and even view it on your mobile device.

For more information on the event, visit: http://bigdesignevents.com/

Announcing Ionic Native Mocks!

I am excited to announce the first initial release of my Ionic Native Mocks! Recently I was prototyping an Ionic app that required the use of the barcode scanner as part of the initial user flow. But by adding the Ionic Native module and the companion Cordova plugin, I would no longer be able easily to preview and debug the application locally within my browser. I often caution my students and workshop attendees to refrain from adding Cordova plugins until later in the development to avoid this slowdown.

To resolve this issue, I quickly created a mock provider for the barcode scanner, that would match the methods and properties of the actual Ionic Native wrapper. With this mock injected into my app, I could simulate interaction with the barcode scan plugin, and continue my local development.So, I then thought to myself, why create a library of mocks for the Ionic Natives that I could quickly inject into my app? This first release covers the Cordova plugins that included within the Ionic View app.

So, I then thought to myself, why create a library of mocks for the Ionic Natives that I could quickly inject into my app? This first release covers the Cordova plugins that included within the Ionic View app.

Ionic Native Mocks are designed to be used as placeholders during development for the actual Ionic Native modules. If you don’t know what Ionic Native is, here is the official summary:

Ionic Native is a curated set of wrappers for Apache Cordova plugins that make adding any native functionality you need to your Ionic mobile application easier.

Ionic Native wraps plugin callbacks in a Promise or Observable, providing a common interface for all plugins and making it easy to use plugins with Angular change detection.

Currently Available Mocks

  • actions-sheets
  • barcode-scanner
  • ble
  • bluetooth-serial
  • calendar
  • camera
  • contacts
  • date-picker
  • db-meter
  • device-motion
  • device-orientation
  • device
  • dialog
  • email-composer
  • geolocation
  • globalization
  • image-picker
  • keyboard
  • network
  • social-sharing
  • splash-screen
  • sqlite
  • status-bar
  • toast
  • touch-id
  • vibration

Installation

This project allows developers to use Ionic Native Mocks in place of the actual Ionic Native modules. They can be installed in via to methods.

  1. via npm: Installing these prebuilt mocks is easy but they are not easily customized.
  2. via GitHub and manually added to your Ionic project: Installing this way means the mocks can be customized to return specific data, like a specific parsing of a QR code.

Installation via npm

Run the following command to install an Ionic Native Mock into your project.

npm install @ionic-native-mocks/[plug-in] --save

For instance, to install the camera mock:

npm install @ionic-native-mocks/camera --save

You also need to install the Ionic Native package for each plugin you want to add. Please see the Ionic Native documentation for complete instructions on how to add and use the plugins.

Documentation

For the full Ionic Native documentation, please visit https://ionicframework.com/docs/native/.

Basic Usage

To use a plugin, import and add the plugin provider to your @NgModule, and then inject it where you wish to use it.

// app.module.ts
import { Camera } from '@ionic-native/camera';
import { CameraMock } from '@ionic-native-mocks/camera';
...

@NgModule({
  ...

  providers: [
    ...
    { provide: Camera, useClass: CameraMock }
    ...
  ]
  ...
})
export class AppModule { }
import { Platform } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';

@Component({ ... })
export class MyComponent {

  constructor(private camera: Camera, private platform: Platform) {

    platform.ready().then(() => {

      const options: CameraOptions = {
        quality: 100,
        destinationType: this.camera.DestinationType.DATA_URL,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE
      }

      this.camera.getPicture(options).then((imageData) => {
        // imageData is either a base64 encoded string or a file URI
        // If it's base64:
        console.log(imageData);
        let base64Image = 'data:image/jpeg;base64,' + imageData;
      }, (err) => {
        // Handle error
      });
    });
  }
}

Missing a mock? Found a problem?

Let us know or submit a PR! We will be working to add in the rest of the Ionic Native collection in the near future.

Credits

Chris Griffith – @chrisgriffith

Leif Wells – @leifwells

Live Online Training

banner
I am pleased to announce I will be giving another live online training on Ionic 3 through O’Reilly training. The online sessions will be held on September 5 & 6, 2017 from 10:00 am – 1:00 pm PDT.
By the end of this live, online course, you’ll understand:
  • How Ionic, Cordova, and Angular work together to create hybrid mobile apps
  • How to design and program Ionic apps
  • How to publish your applications to the app stores
And you’ll be able to:
  • Generate Ionic applications using the Ionic CLI
  • Use common Ionic UI components
  • Extend your Ionic applications with Ionic Native
  • Preview your applications on your devices
  • Compile your applications to ready them for submission to mobile app stores
Here is the course outline:
The timeframes are only estimates and may vary according to how the class is progressing

DAY 1

Introduction to Ionic (20 minutes)

  • Lecture: What’s new in Ionic 2; introduction to the Ionic CLI; Ionic file structure
  • Hands-on Exercise: Create an Ionic blank template

Introduction to Angular and TypeScript (30 minutes)

  • Lecture: Introduction to Angular and TypeScript
  • Hands-on exercise: Short quiz

Building your first app (30 minutes)

  • Lecture: Building your first app with Ionic2Do; using Ionic serve to preview your application
  • Hands-on Exercise: Compile and run your Ionic2Do app locally in the browser

Break (10 minutes)

Styling your Ionic app (30 minutes)

  • Lecture: How Ionic apps are themed; using Ionic View to quickly preview the app on your device
  • Hands-on Exercise: Preview your app on your mobile device (with data stored remotely)

Ionic Native (30 minutes)

  • Lecture: Adding native touches to your application using Cordova plugins via Ionic Native; publishing the application to the app stores
  • Hands-on exercise: Replace the JavaScript dialog with a native dialog

Debugging Ionic applications (20 minutes)

  • Lecture: How to debug your application
  • Hands-on Exercise: Use Chrome or Safari to remote debug your application

Wrap-up and Q&A (10 minutes)

DAY 2

Building your second app (30 minutes)

  • Lecture: Building an app with IonicParks; exploring Ionic Tabs; loading data; Ionic Lists
  • Hands-on exercise: Build an application using the local data file and rendering the park list

Ionic navigation (30 minutes)

  • Lecture: How navigation works in an Ionic application; using the Ionic generate command to improve your workflow; designing the park details screen
  • Hands-on Exercise: Generate and populate the park details screen of the app

Google Maps integration (30 minutes)

  • Lecture: Adding a map to your application; custom classes
  • Hands-on exercise: Add a live Google map to your application

Break (10 minutes)

Exploring other Ionic components (30 minutes)

  • Lecture: Common Ionic components (slides, popover, date and time, toast, grid, and gestures)
  • Hands-on exercise: Short quiz

Accelerate your application’s development and features (30 minutes)

  • Lecture: The larger elements of Ionic that can accelerate your application’s development and features (exploring Ionic.io, deploy, build, notification, and users)
  • Hands-on exercise: Short quiz

Next steps, wrap-up, and Q&A (20 minutes)

I hope to see you there.
To sign up for the course, visit Safari Online.

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.