Why Choose SharePoint Framework (SPFx) for a Teams Application?

We can build Teams Apps with Power Platform and SharePoint Framework. Which to choose for any particular customer requirement? To answer, we need to examine both. This post will discuss the SPFx option. A future post will look at the Power Platform option.

Not Just SharePoint

SharePoint Framework (SPFx) has evolved from customizing SharePoint to providing coding templates for Word and Outlook customizations and Teams. In time we may see the name change to reflect its broader mission. The Teams templating path differs from the familiar SharePoint webpart and application customizer templates. First, let’s look at Teams Toolkit.

Yeoman Generator or Teams Toolkit?

It is possible to create a Teams app using Yeoman generator when building SPFx webpart or extensions projects. However, current Microsoft documentation demonstrates the process using Teams Toolkit, their own scaffolding tool that becomes available in Visual Studio Code as an icon in the left toolbar once installed. It can also be used via CLI.

Teams Toolkit Installation

Overview of Building a Teams App

To begin, click the Teams Toolkit icon and then “Create New Project”. Then choose “Create a new Teams app” on the center dropdown. Note: We are accustomed to creating an SPFx project within an existing folder but Teams Toolkit lets us set the folder later.

Create New Teams App

In the Capabilities dialog, the Tab box is automatically selected. Click OK.

Select Tab Box

For the Frontend hosting type, choose SharePoint Framework (SPFx). SharePoint Framework will afford us the standard Workbench mode to allow local development before deployment and a generally more SharePoint-connected approach. (Azure mode requires logging into Azure and leverages Azure resources such as Azure Functions.)

Front End Hosting Type

The Framework selection for this demo is React; click the checkmark. Then in the “Web Part Name” dialog enter “infotab”.

Choosing an InfoTab

After you enter the description, the following dialog requires you to select Typescript. On enter, select the folder you want to use for the project. Next, you will enter a project name.

Enter Project Name

This will create a folder with this name within the folder you selected earlier. The toolkit will scaffold your project now, and you can view its structure.

Folder Structure

Press F5 to run the project. You will see commands scroll through the terminal window that is reminiscent of running an SPFx project generated from Yeoman. You may have to click yes to accept the certificate in a Security Warning. Then the SharePoint Web Part Workbench will appear. Open the plus to select your project.

Identify commands

A familiar sight: the SPFx webpart layout appears, previewing what will show in the Teams tab after deployment.

SharePoint webpart layout

Let’s change what it looks like, first. Open the .tsx file found in the src->webparts\infotab->components folder. Throw in a table to simulate data.

Simulating Data

Give the table a style name.

Give Tab a Style Name

Now add that style name in your .module.scss file.

Add Style Name to Module

I also changed the background color to purple.

Purple Background Color

As you save the file, the workbench updates automatically to show you your edits with each change. This is convenient!

Deploy

To deploy we will generate and add a .sppkg file to the App Catalog in a SharePoint Online tenant, exactly as deployment works for SharePoint webparts built-in SPFx. But instead of building the files from the command line, we will use Teams Toolkit in VS Code. Click the “Provision in the Cloud” item in the Toolkit Project menu.

Use Teams Toolkit in VS Code

The lower right corner of VS Code will show a success message. After it appears (and then disappears; keep watching for it), you will click the Deploy to the Cloud option. Of course, no such deployment is available; but the dialog that appears to say also includes the button you need to build the project.

VS Code Success Message

Click that Build SharePoint Package button. Watch the lower right corner of VS Code for progress. This will take a couple of minutes. When complete, return to files view in VS Code. In the SPFx->sharepoint\solution folder, you will find a file with the extension .sppkg. This is the file we will deploy to the SharePoint App Catalog. If you need to create your App Catalog, follow these steps. Open your App Catalog and add the .sppkg file by choosing Upload Document and browsing to it.

Upload Document to SharePoint Catalog

Infotab appears in your App Catalog.

InfoTab in Catalog

Sync to Teams: first select the project in the App Catalog and then click the icon in the ribbon for “Sync to Teams”.

Sync the App Catalog to TeamsWhat does this do? Configuration is (apparently) applied behind the Office Online scenes to make this webpart available to your Teams application. A dialog will appear requiring you to choose to deploy as trusted. Check the “Make this solution available to all sites…” box and then click Deploy.

Trust and Deploy

When you navigate to Apps in your tenant Teams (online Teams shown), your new app will appear in the top section “Built for your org.” Click the new app!

Build for your Org Tab

A dialog will appear; click the Add button.

InfoTab

A new tab will appear on the left nav of Teams with your app.

Sample Company Teams Schedule

Congratulations! You’ve built a Teams Application with SPFx.

Building a Teams app with SPFx is not low code and so forgoes the convenience of Power Apps. You have to set up a development environment with an IDE, the correct version of Node, supporting packages-also the accurate versions, React, or another framework. Data connection is significant work. These take effort to decide upon, maintain and use. When would this be potentially preferable?

  • Design control: Building with actual code permits a fantastic ability to fine-tune every aspect of the app’s behavior, design, and appearance.
  • Access control: Building with actual code permits administrators at the App Catalog level to control who the app is available to and ensure it is available to everyone to install.
  • Source control: SPFx projects built-in VS Code or Visual Studio can be stored in source control, allowing all the power of versions, branches, and multi-developer-team development.

When is Power Apps the better way to build Teams apps? Stay tuned for the next in this blog series: Build A Teams App Using Power Platform. This will contrast building a Teams app using SharePoint Framework and Teams Toolkit.

The landscape for Power BI licensing is complex and evolving. To begin to grasp the structure and detail, let’s break it down. Today I am asking: what are the capabilities of using a free license?

Really, It’s Free

More than one path exists to obtain a free account. For our exploration in this article, I will use two:

  • Individual Free Account
  • Office 365 (Dev Tenant) Member Free Account

Let’s frame this in a story with two fictional characters. Cary Small started a small one-person business during the pandemic and wants to send a graph of her sales data to her small business Meetup group friends. Max Rockatansky is her friend. As an employee for a small company that subscribes to Microsoft 365, he was assigned a free account by the M365 tenant admin.

Fictional Characters

Free Account User Source of Free Account Different Experience in Power BI
Cary Small Individual Free Account Cannot publish to public
Max Rockatansky Assigned account by M365 tenant admin* Publish to public if admin has allowed it

*admin name Imperator Furiosa 😀

Let’s See This in Action

Cary created her Individual Free account from a personal domain name email address to try out Power BI, let’s say carys@mysweetstartup.biz. A link to create this type of account is in the Links section at the end of this article. Email addresses from free email companies such as Gmail, Hotmail, or Outlook.com are not accepted. This account type is interesting because it is the free-est of the free; no Office 365 membership is needed.

Create Free Individual Account form

Power BI Desktop

With her new account, the starting point for Cary is to install the Power BI Desktop application. This application is free to download, install and use, even without ever logging in to any account. A link to the download is included at the end of this article. Power BI Desktop is the starting point to generate and shape reports and visualizations.

Install Power BI Application

Here Cary imports her spreadsheet of sales data. She can transform it and create a visualization or report all before logging in. Within an hour, Cary has completed her graph of sales data:

Cary's Sales Chart

Now she wants to share it with her Small Business Meetup friends. The report must be published to the Power BI Service. Navigate to Home -> Publish in the menu. Cary will then see a prompt to log in to her Free Account.

To Publish and Share a Login is required

A dialog wants to know a destination. The only option for the free account is My Workspace. My Workspace is accessible to only the account owner. It does not allow for collaboration with publishing to Workspaces or App Workspaces as these are features available from paid subscriptions. Cary then selects My Workspace and clicks Next.

Publish workspace with Power BI

Success! Her report was published to My Workspace in the Power BI Service. A dialog appeared with the link to open the Power BI website.
Publishing to PowerBI

Profile and Account Status

Once on the Power BI site, click on your profile in the upper right corner. The dropdown detail will show your status: Free account, with a prompt to purchase a Pro upgrade.

Profile Info shows free account

Sharing the Report

Now that Cary’s report is published, she can explore her options for sharing the chart. Under the Export menu item are options to export to PowerPoint, a PDF, or to Analyze in Excel and be emailed as file attachments.

Export to file options

For a free account, this functionality feature is nice, but there is more to be offered.

Functionality features

Under the Share menu, she finds three options (Figure 9). The first option will email a link. When she clicks it, a Pro license requirement pops up. The last option is a QR code that requires the device to be logged into Power BI. Neither of those is helpful. But the middle one, Embed report, offers a selection to Publish to the web (public) so, she tries it.

Publish to the Public Web

Hitting a Roadblock

We hit another impediment:

Roadblock

Recently, an admin setting added to Power BI requires an admin to permit sharing publicly explicitly. As an Individual Free Account, Cary has no admin to approach. Her account is not in a tenant that she can access. At this point, Cary can share only by exporting a file. She thinks this is pretty good for free! But she would also like to embed the report in her free GitHub Pages website.

Max comes for help

Cary calls her friend Max for help. Unfortunately, Max does have the capability to publish a public Power BI report. To do this, he must gain access to Cary’s computer, so they start a Zoom meeting and steps below:

  1. Close the browser window to apps.powerbi.com.
  2. Return to Power BI Desktop – Cary signs out.
  3. Max will sign in.
  4. Publish again, choose My Workspace.
  5. On the Power BI Service website, sign out as Cary and sign in Max.
  6. Choose Embed -> Publish to Web.
  7. Now they see a better dialog (Figure 12):

Publish sharing is now possible

Click Create Embed Code. A dialog will caution you to be careful! “Public” means completely public so that any sensitive data will be compromised. But in our case, this is all for the sake of IT and is not real! Let’s go! Click Publish.

Embed in a public website

Success! You now have both an iframe tag and a link that you can email. Cary tested by emailing the link to her phone and clicked the link. The report opened directly to the chart with no impediment, no login. She then embeds the link on her startup website, opens Max’s LinkedIn page, and writes him a glowing compliment.

Getting started with PowerBI

A startup business might not be ready to invest in Premium Space or Pro licenses. With an Office 365 account, the option to use the free license also offers report sharing. The sharing is limited, and there is no collaboration option, but the business can still convey data visualizations. This is a great place to get started with Power BI.

Links

Do your users want reports in SharePoint? Yes! They crave reports and charts. Regardless of which version of SharePoint they are using, getting started now to build their data visualizations in Power BI will position the reports for seamless migration to future SharePoint versions. These are the necessary steps to take to add a simple report in a SharePoint modern page.

Important note: To embed Power BI reports in SharePoint Online, a Power BI Pro license is required.

The Process Flow

This is the flow:

The Process Flow Figure 1

Figure 1: The Process Flow

  1. Create your data in SharePoint; say a list or library.
  2. Start Power BI Desktop to connect to SharePoint to read the data and transform it and create visualizations.
  3. Publish to Power BI Online, where a link becomes available to paste into the Power BI webpart available in SharePoint Modern pages.

We’ve gone full circle! Let’s look at the steps.

SharePoint Online Data

For this example, we will read data from a simple custom list. I added the list to my SPO Dev Tenant site named Vacation Planner. Since all our “vacay” are now “staycay,” I decided to make a board game list. Along with the default Title column that you get with any new list, I added three more. Each is a number column. Then I added games to the list; I listed every game I could think of. For each one, I entered somewhat random numbers for Difficulty and Minimum age and Popularity, although I am pretty sure Candy Land is for 4-year-olds.

SharePoint Online Data Figure 2

Figure 2: Board games list

To create the list, I was logged into SPO as a fictitious test user I named Gwen Lim.

Build the Report

Install the Power BI Desktop application to build the report. It’s free: download it here.

On first use, you will be prompted to sign in. If the login type option appears, choose “Organizational” and log in with a Windows account. I logged in with fictional Gwen Lim’s account. The app, either from the startup splash screen or the menu, chooses “Get Data.”

Select Data Source Figure 4

Figure 3: Select a data source

From the Common data sources dropdown, select “More…” at the bottom. Then click the “Online Services” option, and you should see “SharePoint Online List” on the right. Select that and then click “Connect” at the bottom.

Choose SharePoint online Figure 5

Figure 4: We will choose SharePoint online list

In the SharePoint Online Lists dialog, paste the address URL of the SharePoint site that contains your list. You can check the 2.0 (Beta) radio button (see figure 6) to enable the app to open the default view of your list or leave it 1.0 if you prefer.

SharePoint Site URL Figure 6

Figure 5: Enter the SharePoint site URL

A Navigator window appears with all of the lists available in the SharePoint site in the left columns with checkboxes. Then, check BoardGames to see a view of the data in the right side of the pane. Click the Load button.

Select the List Figure 7

Figure 6: Select the List

You can start building the report. The fields of the data display on the right side. Having chosen a specific, limited column view as default for the list, along with selecting the 2.0 radio button, you will see only a few fields (aka columns) on the right, which is easy to work with.

BoardGames List App

Figure 7: The BoardGames list fields appear

Ignore the fields for a moment while you chose a Visualization. Select the doughnut. Now, it’s time to apply fields to the doughnut. Drag Title into the Legend box under Visualizations. A legend appears beside the doughnut chart. Drag Popularity into the Values box, and your doughnut comes to life with color.

Pick a visualization Figure 9

Figure 8: Pick a visualization chart and add fields

When you hover the chart, tooltips appear with data for each game. Age level, Difficulty, and Popularity values have been imported as decimal values, which would be more readable as whole numbers. To alter this, and to edit column heading text, click on the ribbon’s Transform Data button.

Modify the Data Figure 10

Figure 9: Modify the data

To change the column value from a decimal to a whole number, click the column title to select it and then click on the ribbon’s Data Type button. Select Whole Number as in figure. Double click the column heading to rename the column.

Changing field titles and data types

Figure 10: Changing field titles and data types

Click the Close & Apply button on the left in the ribbon to cause the visualization to appear with the changes applied. Now when you hover your cursor over a section, Minimum Age will appear with a space and both values as whole numbers.

Ready to Publish Figure 11

Figure 11: Improved tooltips

Display in SharePoint

To display the report in SharePoint, click the Publish button in the ribbon on the right side. You will be prompted to save your report in .pbix format.

Ready to publish report figure

Figure 12: Ready to publish!

Save anywhere you want to keep it, and then the Publish to Power BI dialog appears. Varied workspaces can be configured, but initially, you only have “My Workspace” as an option, which is fine. Select it and then click “Select.”

Publishing to Power BI

Figure 13: Successful publish to Power BI Online

When you see the Success! dialog, click on the link to open the .pbix in Power BI online to view your report. In the Share menu above the report, drop down the menu options, and hover over Embed report. Here you want to see an option for SharePoint online.

Link to use in SharePoint page Figure 14

Figure 14: Get a link to use in a SharePoint page

This will be missing until you upgrade to a Power BI Pro license. This is not free, but the trial is for 60 days. Once you have that option in the menu and select it, you are rewarded with the Embed link to use in SharePoint.

Embed link for SharePoint

Figure 15: Click to highlight and then copy

Click that link to highlight it and copy. Now head over to your SharePoint site and create a page.

Locate built-in Power BI

Figure 16: Locate the built-in Power BI webpart

Click the webpart plus sign, and in the search box, type “power” to filter the results. The Power BI webpart will appear. Click on it, and the webpart will be inserted into your page. You will see a green button for Add report; click it to open the properties panel on the right. Paste in the embed link you got from Power BI online.

Apply the embed link

Figure 17: Apply the embed link

Click away from that textbox and your report will appear on the left.

Report Displayed Correctly

Figure 18: Report successfully displayed in SharePoint Online

Conclusion

This is a no-code solution and a simple demo. However, the depth of tooling provided by Power BI to enable developers and business data experts to transform and visualize organizational data is immense. The speed and ease with which we can integrate data reporting into SharePoint modern pages will be welcome to customers as they migrate to current SharePoint versions.

Links

Embed a report web part in SharePoint Online – Power BI | Microsoft Docs

We live in fractious times! Let’s escape for a few minutes to consider how Microsoft is moving us toward calm and synchrony. Together with a consistent, organized design aesthetic, the Fluent Design System delivers a User Experience bridge across apps, platforms, and devices.

Fluent UI is a package of tools we can use to build for our customers faster and with a consistent UX.

Across Platforms

5 Platforms - Fluent Design System
Five Platforms of tools offered by the Fluent Design System

The Fluent Design System applies to five platforms: Web, Windows, iOS, Android, macOS (recently added). Fluent UI is the set of design tools within the overall System. We can use these toolsets to implement coherent, consistent design elements.

Many Names

Note that for Windows development, the design and toolset are being allowed to keep the existing name of WinUI. The Fluent naming changes are a moving target! Fluent Design System is a design language developed in 2017 as the successor to Metro at the introduction of Windows 10.  Microsoft gave the name Fluent UI to the merge of two repositories, UI Fabric and another Microsoft UI library that was named Stardust. Browsing the Fluent Design website you will encounter places where Fluent UI is still named UI Fabric. We will see these become Fluent UI gradually. Having the names organized helps to deliver the Design System concept.

Native

Achieving a consistent look and UX appears a straightforward goal. But the challenge is more than meets the eye. Working Fluent Design smoothly into the native behaviors, elements, and controls of the many devices will require a balancing effort. The challenge is to respect each platform’s native elements and behavior while adding a uniquely Fluent feeling. Consider that Android devices are built using Google’s Material Design. Displaying Office on an Android device requires considering how the Fluent experience will work with the Material Design of the OS. It is worth the effort. Familiar user patterns across devices increase productivity for end-users. To help build natively, Fluent UI React Native was announced at Build, to allow easier cross-platform development.

A Coherent User Experience

Users are evolving and expecting a different experience. Today people use multiple devices and sometimes all at the same time. We want to let a user start work on one device and finish on another. Our cloud-powered, multi-device, cross-platform world has created a need and expectation of a consistent and coherent experience from one to the other.

“Fluent has taken Microsoft back to the basics of design, with a much bigger focus on simplicity. Instead of bold typography and edge-to-edge content, Fluent focuses on subtle elements like light, depth, motion, and material. We’ve seen it appear in Windows with hints of motion and blur effects. It’s also appeared in Office and on the web across services like OneDrive, Office Online, and Outlook. Microsoft is gradually making Fluent the centerpiece for how the company thinks about design.” –The Verge

Fluent UI React

Used by Microsoft 365 apps such as Outlook and SharePoint, Fluent UI React is also incorporated in the generators for SharePoint Framework, Office Add-ins.

 Fluent Design used by many Microsoft products
Microsoft products built using Fluent Design

Developing for Microsoft 365 apps using SharePoint Framework and Add-Ins is supported by having Fluent UI already included from the generator, to keep the design of webparts and add-ins consistent with the hosting product.

Design-to-Code

The Design-to-Code concept separates design from development to ease building on multiple platforms. Using a design tool such as Figma, Sketch, or Adobe XD, the designer sets UI elements once and can export the tokens to many development environments. It exports style tokens into machine-readable formats: XAML for Windows, compiled CSS for Web, and Swift for iOS.

“Most designers at Microsoft use Figma” – Medium

Getting Started

The deceptively simple Fluent site opens the way to a sizeable body of documentation and quickstarts. Choose your platform and jump in. From the Build presentation: “Our opportunity in the cloud-powered, multi-device and cross-platform world is for us to design seamless experiences that close the technology gaps and allow people to organize, manage, create and communicate wherever they are in ways they’ve never imagined before.”

Recap

  • Fluent Design System helps build natural and productive experiences on each device
  • Resources are available to build UX on Windows, Web, Mobile, and Cross-Platform
  • Further improvements to come to improve design to code

Links

Building data and formatting features into MS Office applications using Office Add-Ins can be a crucial productivity boost to an organization. Now Microsoft has given us the ability to build Add-Ins faster and easier using the SharePoint Framework (SPFx).

What are Office Add-ins?

You will find them in the ribbon of Office apps. Below is the Add-ins pane found in the ribbon in Word. The default installation of Word includes the Wikipedia Add-in, a great example of an add-in, that you can see in your client installed Word:

Add-ins pane
ADD-INS: Add-ins can be accessed, installed, and managed from this tab in the Office application ribbon.

The history of building extensions to Office apps is long, extending back to leveraging Visual Studio Tools for Office: the venerable VSTO. With VSTO the only option has been to build and deploy server-side code with its attendant risk and longer deployment lead times. Also, it works only on Windows. The great advantage of building Add-Ins in the newer JavaScript and HTML model is that the Add-Ins work on all platforms and Office Online. Deployment is a fraction of the effort it once was.

Initially building MS Word Add-Ins using the Yeoman generator and the modern toolchain was not a part of the SharePoint Framework, but to any developer who has looked at both, they bear a striking resemblance to each other in many ways. To merge these dev workflows seems natural, efficient, and pleasing. 

Already Integrated to SharePoint

What do Add-Ins gain from being integrated into the SharePoint Framework? Mainly, the data connection to SharePoint. If your Add-In does not need a SharePoint connection, you can stick with using the standard Office generator in the Yeoman generator. But the connection to data in SharePoint is valuable. But wait, there’s more! SharePoint is a hosting platform as well with authentication built-in, so you can host your Add-In from SharePoint. With the introduction of building Add-Ins in SPFx, the step of hosting, and connection to SharePoint are now built into the Yeoman Generator!

Walk Through

Let’s build one. It is still a work in progress, a beta version. The Yeoman Generator will currently only build an Add-In for Outlook, and it is only available in the preview version of the generator, so we will invoke the beta version using “- – plusbeta” after the yo @microsoft/sharepoint command be sure to add –plusbeta as in the image below.

Yeoman Generator
Scaffold the application with Yeoman Generator

For the following generator steps, provide these answers:

  • SharePoint Online only (does not work on on-prem)
  • “Yes” to Do you want the allow the tenant admin to be able to deploy to all sites.
  • “No” to Will the components in the solution require permissions.
  • “WebPart” as the type. It is not strictly a SharePoint webpart, and likely another word will become available. For now, this is the option to choose.
  • No JavaScript framework, for the demo
Generator Image
Answer the generator’s questions.

When the project is finished scaffolding, open in VS Code, in the project, files will be a folder named “officeAddin” that usually doesn’t appear in an SPFx WebPart project. This is inserted when “—plusbeta” is added to the initial generator command. In this folder will be the manifest .xml file that is recognized as crucial in “yo office” scaffolded projects. This manifest is the pivotal point of configuration that connects your add-in to the internal operation of Word or Excel or PowerPoint or Outlook.

Manifest Window
The generated project as viewed in VS Code, when the –plusbeta parameter is added. Note the officeAddin folder and manifest inside.

Add type definitions by running the following:
npm install @types/office-js –save-dev
The webpart render code is still that which is generated for the default SharePoint webpart, so we will add some code to check for the Office context. Edit the webpart .ts file in the webparts folder. Add the following after the public render(): line:

Context Window
Add conditional code to determine the existence of the Office context.

Edit the title, subtitle and description lines to have placeholders for the output so that an Outlook message will display if our Add-in displays successfully in Outlook:

Span Classes

Deployment

At this point, deploying to SharePoint is a significant departure from the current Office Add-in deployment model. It is as easy as bundling and uploading to the app catalog in the same manner as deploying an SPFx webpart. Run gulp bundle –ship and gulp package-solution –ship, and then locate the .sppkg file in the SharePoint folder of your project.

Deploy the .sppkg file to the App Catalog in SharePoint. In the “Do you trust” dialog that appears, check the box to “make this solution available to all sites in the organization” to enable access to the Add-In from Office online applications (in this case, Outlook).

Manifest

The manifest file, whether generated in this SPFx workflow or from using the Office scaffolded project, is the critical piece that tells the Office application about your Add-In; where to find the code to render and what permissions it will have within your Office application. It can also be modified for what name will appear for your Add-in and what icon to display. For the client installed Office apps, the manifest must be given special Trust status within the application. The SPFx-to-Office-online version of this is more accessible: you upload the manifest file.

Add-Ins Goal

The vision for add-ins is to achieve:

  • Speed repetitive document tasks and creation
  • Have a native and intuitive feel
  • Use the same UI as Office (Fluent UI)

Researching for this post, I hoped that the story for Word add-ins was as far along as it is for Outlook and that SPFx would also provide for building Add-Ins for on-premises SharePoint. See the first video link below to see a demo of a Word add-in built with SPFx over a year ago; I think this capability is imminent. Stay tuned!

Links

Progressive Web Apps (PWAs)

As an introduction to PWAs, let’s build a mobile app the fastest, easiest way, using the Progressive Web App model. A PWA is both a mobile app and a website. Built with HTML, CSS, and javascript, the website can be viewed as either a website on your laptop or a mobile app on your phone or tablet. No need to develop a separate native app for every platform!

Creating Website with Addition of JavaScript files app will behave "app-like"

What does “App-like” mean? PWAs can work on your phone or tablet so much like a native app, it is hard to see the difference. Twitter produces both, a native app you can find in your app store, and a PWA you can “install” from browsing to twitter.com. Check out images of each:

Natie iPhone App vs. PWA - Twitter.com

A PWA can even access device hardware like the camera or microphone! They can produce push notifications and work offline. How does it do these things? It’s all in the site javascript and structure. It is the best way to build a mobile app. Let’s see how this works.

PWA Goals

To work like a native app, the PWA website has to:

  • Work offline
  • Perform fast
  • A display like a native app, responsive, with no browser UI visible
  • Startup from an icon on your home screen

Advantages

Why and when would we want to create a PWA?

  • Fast deployment: Avoids submission to the app stores for review and approval
  • Quicker updates are published immediately because it is served on the web and so no need to wait for the user to download to their device
  • More discoverable: Users can find and link to it via search engines
  • Secure: They use the browser security model, so providing the security of operating within the web browser context
  • Connectivity independent: PWAs can function on very low bandwidth or no connection at all.
  • Installable: Like a mobile app, this is opened from an icon on the home screen.
  • Notifications: Can send push notifications to the device like a native app
  • Hardware access: Can use the mobile device camera, microphone, etc.

Progressive?

“Progressive” in the name refers to that it will work and display in all browsers to a varying degree. Because it is browser dependent, it is affected by the capability of which browser the user has, and what version. PWAs have a goal to display and function at least minimally in all browsers, regardless of version. As such they become progressively more feature-rich in newer versions.

History

The Progressive Web App concept was created by Google in 2015. Its roots go even further back though, to Steve Jobs’ introduction of the iPhone in 2007. He declared back then that development for the iPhone would be done in html5 and have no SDK. His vision was undermined by iPhone jailbreaking which forced Apple to retreat to having an SDK and app store. But the concept lived on and is seeing increasing life in the PWA model.

Let’s Build One

We will look at how to use a manifest and service worker to create a very simple application that provides the features of a PWA. This is exciting to see on your phone, in action!
In your development environment, create a folder in your local for your project, name it anything, and add subfolders for js and images, and an index.html file:

Application Providing Features of a PWA

This demo was edited VS Code and the site was served on IIS in Windows but any favorite editor and dev web server will be fine. Node.js http-server is another easily available web server you could use. The file index.html should look like this, to start. We’ll add more later:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Hello My Phone</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class="fullscreen">
  <div class="container">
    <h1 class="title">Hello My Phone!</h1>
  </div>
</body>
</html>

Run the app now in your webserver to see how it is shaping up. So far this is just a web app. Push it to your GitHub Pages repo to see it run on the web. To add mobile app functionality, we need to add two files, a Service Worker and a manifest.

Service Worker and Manifest

These change the app from a simple web app to one that can behave like a mobile app, a Progressive Web App. The Service Worker is the middleman between the web page and content. It contains the code to determine whether to deliver static, cached content or dynamic data based on whatever criteria you want, typically whether it finds a connection to the internet or not. The manifest is a json file that provides properties to the browser such as which page to load when the app is first opened, or what is the title of the app. Both the manifest and the service worker live on the root directory for access.

Create a file named manifest.json in the root of the site, and add the following:

{
  "name": "My Phone App",
  "short_name": "My App",
  "icons": [{
    "src": "images/phoneapp-icon-128.png",
      "sizes": "128x128",
      "type": "image/png"
    }, {
      "src": "images/phoneapp-icon-144.png",
      "sizes": "144x144",
      "type": "image/png"
    }, {
      "src": "images/phoneapp-icon-152.png",
      "sizes": "152x152",
      "type": "image/png"
    }, {
      "src": "images/phoneapp-icon-192.png",
      "sizes": "192x192",
      "type": "image/png"
    }, {
      "src": "images/phoneapp-icon-256.png",
      "sizes": "256x256",
      "type": "image/png"
    }, {
      "src": "images/phoneapp-icon-512.png",
      "sizes": "512x512",
      "type": "image/png"
    }],
  "description": "Sample Progressive Web App",
  "lang": "en-US",
  "start_url": "index.html",
  "display": "standalone",
  "background_color": "white",
  "orientation": "any",
  "theme_color": "white"
}

Link the manifest file in your index.html file, in the head section:

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

Service Worker

To add the service worker, create a file in the root folder named sw.js. Add the following to it:

var cacheName = 'phoneApp';
var filesToCache = [
  './',
  './index.html',
  './css/style.css',
  './js/main.js'
];

/* Start the service worker and cache files in filesToCache */
self.addEventListener('install', function(e) {
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return cache.addAll(filesToCache); 
    })
  );
});

/* Serve cached content when offline */
self.addEventListener('fetch', function(e) {
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request);
    })
  );
});

Adding a service worker is the first step towards enabling the following progressive web app features:

  • Offline performance
  • Push notifications
  • Add icon to the home screen

Our service worker file caches specifically named pages to be able to serve them from the cache when the device is offline. The file must be placed in the app root to allow it access to all of the app’s files. Service workers only have permission to access files in their same-level directory and subfolder. In the first function of the sw.js, the first item in the variable filesToCache is “./” because that allows caching of our index.html. The cacheName variable adds the content to the browser cache to be available to be called from the javascript. The following function fetches the cached content. This file works for our demo but to properly fortify the app with error handling and to see what else the service worker can do, check out PWABuilder. It is a handy file generator for your PWA, but even if you don’t use the generator, just looking at this site sums nicely what you can define in the manifest and service worker and what they can do. For now, we’ll keep our service worker simple.

Register the Service Worker

We need one more file to call, or “register”, the service worker. Create a javascript file in your js folder named main.js. This tells the browser where to find your service worker JavaScript file. Add the following:

window.onload = () => {
‘use strict’;

if (‘serviceWorker’ in navigator) {
navigator.serviceWorker
.register(‘./sw.js’);
}
}

Link to main.js at the bottom of index.html by adding a script link before the closing body tag:

<script src="js/main.js"></script>

App Icons

We need to provide icons that various displays can use, to support the mobile app experience of having an app icon on the device. Images of varying sizes are defined in the manifest above. We will put these images in the Images folder to be available to display the home screen icon when users “install” your app. Sample images for these and for favicon.ico are included in the downloadable files (link below). The file structure looks like this now:

Production of App Icons

Add Responsive HTML

To see the best effect of your sites’ web vs mobile view, add some responsive elements and styles to index.html. This example uses the free W3 Schools templates. It links to their online w3.css stylesheet for responsive styles. A link to the W3 Schools templates is included in the links at the end of this post along with a link to download the project files.

With the addition of the html below, our site now has navigation and layout that changes based on the viewport. The HTML now looks like this:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>PWA Sample</title>
  <link rel="manifest" href="manifest.json">
  <link rel="stylesheet" href="css/style.css"> <!-- optional -->
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="theme-color" content="white"/>
  <link rel="icon" href="favicon.ico" type="image/x-icon" />  
<link rel="apple-touch-icon" href="images/pwa-icon-152.jpg">   
<meta name="theme-color" content="white"/>  
<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="Hello World"> 
<meta name="msapplication-TileImage" content="images/pwa-icon-144.jpg">  
<meta name="msapplication-TileColor" content="#FFFFFF">
</head>
<body class="fullscreen">
<!-- Sidebar/menu -->
<nav class="w3-sidebar w3-collapse w3-top w3-large w3-padding" style="z-index:3;width:300px;font-weight:bold; background-color:#ddd;" id="mySidebar">
  <a href="javascript:void(0)" onclick="w3_close()" class="w3-button w3-hide-large w3-display-topleft" style="width:100%;font-size:22px">Close Menu</a>
<div class="w3-container">
<div style="width: 120px; height:119px; background-color: #fff;">
  <img src="images/logo.jpg"</div>
</div>
<div class="w3-bar-block">
    <a href="#" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Home</a> 
    <a href="#sectionOne" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Section One</a> 
    <a href="#sectionTwo" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Section Two</a> 
    <a href="#simpleForm" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Contact</a>
  </div>
</nav>
<!-- Top menu on small screens -->
<header class="w3-container w3-top w3-hide-large w3-grey w3-xlarge w3-padding">
  <a href="javascript:void(0)" class="w3-button w3-grey w3-margin-right" onclick="w3_open()">☰</a>
  <span>My Mobile App</span>
</header>

<!-- Overlay effect when opening sidebar on small screens -->
<div class="w3-overlay w3-hide-large" onclick="w3_close()" style="cursor:pointer" title="close side menu" id="myOverlay"></div>
<!-- !PAGE CONTENT! -->
<div class="w3-main" style="margin-left:340px;margin-right:40px">
<!-- Header -->
  <div class="w3-container" id="showcase">
   <h1 class="w3-xxlarge">My Mobile App</h1>
   <h1 class="w3-large w3-text-gray"><b>Lorem dolor etc!</b></h1>
  </div>
<!-- Photo grid (modal) -->
<div class="w3-row-padding">
<div class="w3-half">
      <img src="images/circle1.jpg" style="width:100%" onclick="onClick(this)" alt="It's a photo">
      <img src="images/circle4.jpg" style="width:100%" onclick="onClick(this)" alt="It's a photo">
  </div>
<div class="w3-half">
      <img src="images/circle3.jpg" style="width:100%" onclick="onClick(this)" alt="It's a photo">
      <img src="images/circle2.jpg" style="width:100%" onclick="onClick(this)" alt="It's a photo">
  </div>
</div>
  <!-- Top Section -->
<div class="w3-container" id="sectionOne">
<h1 class="w3-large w3-text-gray"><b>Section One</b></h1>
  Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
</div>
<!-- Section of Text -->
<div class="w3-container" id="sectionTwo">
<h1 class="w3-large w3-text-grey"><b>Section Two</b></h1>
 Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
<b>All The Things:</b>
  </div>
  <!-- Images in Boxes -->
<div class="w3-row-padding w3-grayscale">  
  <div class="w3-col m4 w3-margin-bottom"> 
   <div class="w3-light-grey">     
     <div class="w3-container">
        <h3>Thing 1</h3>Thing 1 Phasellus eget enim eu lectus faucibus vestibulum. Suspendisse sodales pellentesque elementum.
     </div>
   </div>
</div>
<div class="w3-col m4 w3-margin-bottom">
  <div class="w3-light-grey">
    <div class="w3-container">
       <h3>Thing 2</h3>Thing 2 Phasellus eget enim eu lectus faucibus vestibulum. Suspendisse sodales pellentesque elementum.
    </div>
  </div>
</div>
<div class="w3-col m4 w3-margin-bottom">
   <div class="w3-light-grey">
     <div class="w3-container">
       <h3>Thing 3</h3>Thing 3 Phasellus eget enim eu lectus faucibus vestibulum. Suspendisse sodales pellentesque elementum.
     </div>
    </div>
  </div>
</div>
<div class="w3-container" id="simpleForm" style="margin-top:75px">
My Form   
   <form action="/myformaction.js" target="_blank">
     <div class="w3-section">
      <label>Name</label>
      <input class="w3-input w3-border" type="text" name="Name" required>
     </div>
     <div class="w3-section">
       <label>Email</label>
       <input class="w3-input w3-border" type="text" name="Email" required>
     </div>
     <div class="w3-section">
       <label>Message</label>
       <input class="w3-input w3-border" type="text" name="Message" required>
     </div>
     <button type="submit" class="w3-button w3-block w3-padding-large w3-grey w3-margin-bottom">Send Message</button>
   </form>
</div>
<!-- End page content -->
</div>
<script>
// Script to open and close sidebar
function w3_open() {
  document.getElementById("mySidebar").style.display = "block";
  document.getElementById("myOverlay").style.display = "block";
}

function w3_close() {
  document.getElementById("mySidebar").style.display = "none";
  document.getElementById("myOverlay").style.display = "none";
}
</script>
<script src="js/main.js"></script>
</body>
</html>

Install On Your Phone

Upload the files to a WebHost or browse to the localhost IP address in your wifi network, to try it on your phone. On the iPhone, browse to the URL and then choose the share button.

iOS Share button

From the context menu, choose “Add to home screen”. Android devices make this even easier by displaying a default button. See links at the end of this post for options to install on Android and other devices.

Summary

Progressive Web Apps offer the best of native mobile apps combined with the advantages of web development. Over time, the increasing embrace of PWA techniques by developers could bring Steve Jobs’ vision for smartphone applications to reality: no need for phone SDKs or and native app deployments or app store constraints, and a world in which web technology can be used to create mobile apps that are faster to build with every bit of functionality equal to their native counterparts.

Links

More about installation of a PWA on other OSs: