Monday, December 28, 2020

How to create WhatsApp and Telegram contact link in our website.

This is a short tutorial on how we can add some social media links to communicate.

If you provide the services and allow the client to communicate then this might be helpful.

1. Adding WhatsApp link to chat.

For WhatsApp, if you want to add the link that helps to send the message, it will be a good option. This feature will allow beginning to chat with someone whose phone number is not saved on your contact list. But they need to have an active WhatsApp account.

Once the link is clicked a chat will automatically open to start. It's suitable for both web and mobile. You can simply create the link as below:
<a href="https://wa.me/977XXXXXXX" target="_blank"><img
        src="whatsApp.png"
        alt=""> </a>
Make sure to have your phone number in the link above. The general format is:
https://wa.me/<number>
where, the number is a full phone number in international format without any zeroes, brackets, or dashes. 

Use: https://wa.me/1XXXXXXXXXX

Don't use: https://wa.me/+001-(XXX)XXXXXXX

2. Adding Telegram link to chat:

Similar to WhatsApp, you can add a telegram link.

First, create the telegram account and create a username. You can create a username from the web as well as mobile

Go the Setting >> Username >> 

Now, add the following link to your website.
<a href="https://t.me/yourusername" target="_blank"><img src="telegram.png" alt=""></a>
Add your username to the link.
Share:

Sunday, December 20, 2020

VueJs PWA: Notify User about the App Update | skipWaiting

Once the application is updated and deployed then, the new version of the application will be available. But how we can notify the user that a newer version is available while they are interacting with the application. How to give the user control over app updates.

Please check out my previous articles on PWA:


1. Understanding how the UI get an update when new content is available:

When you change the app content and deploy it then, you can see in the browser what the service worker is trying to do.




Here, you can see, as soon as the new content is available new service worker trying to install it and is in waiting state.

Although, the old service worker is registered and serving with the old content. The new service worker will be still in a skip waiting state i.e waiting.

Here, once we notify the user about the new update and if they allow us to update the app we can simply do skip waiting and reload the page for new content. After that, a new service worker will be activated and will serve with a new update available.

2. Register the custom event to notify the user about the app update:

We know that service worker can't access the web DOM element directly. As they will run in the background in a separate thread. So we have to notify users from our application. In order to do so, we need to register the custom event which can be listened to in the application.

You can see the file registerServiceWorker.js which is generated by Vue CLI.

/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n' +
        'For more details, visit https://goo.gl/AFskqB'
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

There are multiple events that will be triggered. Here, we need to use the updated hook to notify the user. Let's register for the custom event.
updated (registration) {
      console.log('New content is available; please refresh.')
      document.dispatchEvent(
          new CustomEvent('serviceWorkerUpdateEvent', { detail: registration })
      );
    },
Now let's add this event listener serviceWorkerUpdateEvent in our application. Inside App.vue
created() {
    document.addEventListener(
        'serviceWorkerUpdateEvent', this.appUpdateUI, { once: true }
    );
  },





Let's add some data used and appUpdateUI function.
data: () => ({
    registration:null,
    isRefresh: false,
    refreshing: false,
  }),
  methods:{
    appUpdateUI:function (e){
      this.registration = e.detail;
      this.isRefresh = true;
    }
  }

When the updated event inside registerServiceWorker.js triggered then serviceWorkerUpdateEvent will be triggered which calls the appUpdateUI to show the button to update. Let's add a simple button inside the template as a user interface to update the app. You can use a nicer snack bar instead.
<button v-if="isRefresh" @click="update">Update</button>
Let's add update() inside methods.
update(){
     this.isRefresh = false;
     if (this.registration || this.registration.waiting) {
       this.registration.waiting.postMessage({type:'SKIP_WAITING'});
     }
   },
Now when the user clicks the update button then it will send the post message of type 'SKIP_WAITING' to communicate with the service worker.

If you are using GenerateSW mode then make sure this post message matches the message listener inside the service worker. You can verify it by building your app. Once the app is built then under dist/ folder you can find the service-worker.js to verify.

If you are using injectManifest mode then, use the message listener as below inside service-worker.js:
self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});
Now, this listener will be triggered and it will do skip waiting. The last thing is we need to reload the application to reflect the content change.



For this, we can use 'controllerchange' listener in our application. Under App.vue inside created use the following listener.
created() {
    navigator.serviceWorker.addEventListener(
        'controllerchange', () => {
          if (this.refreshing) return;
          this.refreshing = true;
          window.location.reload();
        }
    );
  },
This is the idea to notify the user of the App update.
Share:

VueJs: How to Get the App Version from package.json

This is a quick tutorial on how we can access the app version.

While building applications, there may be a different phase of development. We need to have a clear vision that which version of the application is on the server.

In the VueJs application under package.json file, you can see the one property called version. We can use this version while deploying to indicate the different versions of the application.


So, what we can do is simply increase the value for a different version of development.

The version can be accessed in our application by simply importing this file as below:

import {version} from '../../package'
Make sure it's accessible. Here, e.g '../../' will give the access for the package which is used under /src/somefolder/component.vue. As the package.json file is under the app root directory. If you want it inside App.vue you can use '../' instead.
data: () => ({
    appVersion:version
  }),
Now access in your template or can set in the store and access it.

<h1>{{appVersion}}</h1>

If you want the package version inside npm script:

const version = process.env.npm_package_version
Share:

How to Use and Customize Service Worker in VueJs Progressive Web Apps(PWA)

 1. Introduction:

What exactly a service worker? What is the need of service worker in our web application?

The service worker is the script that runs in the browser in the background. This means the service worker will run in a separate thread and is independent of our web pages. Service worker can't access the DOM directly.

The service worker is very handy for the caching strategy, push notification, background sync. This means we can manage which files need to be cache and which are not.

Also particularly for mobile app, when it is not opened and needs to send the push notification As well as if the app is not opened and needs to send the request to the server.

Please visit our previous articles on PWA:


2. Default Implementation of Service Worker in VueJs PWA:

VueJs application with Vue CLI uses the default configuration to set up and use the service worker.



If you build your application then, you can see the service worker file generated.
yarn build
 

There are two webpack plugin mode, one is GenerateSW mode which will generate the complete service worker. Vue CLI uses this as a default mode.

Another is InjectManifest mode, which allows us to customize and organize as our requirement and we do have full control over service worker.

If you want to know when to use and when not to use these modes please visit Workbox webpack Plugins

You can see the default service worker generated after building the application as shown in the figure above.

We are going to use the InjectManifest mode so that we can have control over the service worker.

3. Register the Service Worker:

The service worker registration is done by Vue CLI by default. You can see the registerServiceWorker.js under /src folder, the file looks as below:
/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n' +
        'For more details, visit https://goo.gl/AFskqB'
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}
Note: make sure to change the service worker name if you use a different name for it.





Here, the service worker is enabled only for production, enabling service worker in development mode is not encouraged, as it will not reflect the current changes in development, instead it will use cached resources. All the events will be triggered in different cases. 

4. Customize Service Worker with InjectManifest Mode:


Let's copy the service worker service-worker.js file from the dist/ folder or create a new  service-worker.js file under the src/ directory.


Now, let's configure the config to notice that we are using the InjectManifiest mode and provide the newly created service worker path to use that service worker.

For this, create a vue.config.js file under the app root directory. Make sure to have the same name mentioned so this config file will be used by Vue CLI. The file looks as below.


Now, lets set up the config:
 pwa:{
        workboxPluginMode: "InjectManifest",
        workboxOptions:{
            swSrc:"./src/service-worker.js",
        }
    }



Add the above PWA configuration inside the vue.config.js file. Here, we are using plugin mode as InjectManifest and give the path of the newly created service-worker.js file.

The custom service worker file needs to be as shown below:

workbox.core.setCacheNameDetails({prefix: "vue-pwa"});

self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

self.addEventListener('message', (event) => {
    if (event.data && event.data.type === 'SKIP_WAITING') {
        self.skipWaiting();
    }
});

Let's change the cache name from "vue-pwa" to "vue-pwa-test" and build the application. If you look into the service-worker.js under the dist/ folder and if you see the changes there, you are good to go.

Also, you can see some import scripts added at the beginning of the file by Vue CLI which looks something like below.
importScripts("/precache-manifest.7b241a43a2278739512d45eb32884cc1.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
The precache-manifest has a different json config for different files to cache. Note, the file name to be cache will be different in each build. Now, build and deploy the application.

Note: each change in the application will be reflected in the browser after new content is updated and the app is reloaded or refreshed.



Now, click on "skipWaiting" and reload the page which will reload our application with new changes. We will do this skipWaiting from the application in the next tutorial by giving the user control of the app update. Or if you do it right away especially for testing you can add the following inside service-worker.js.
workbox.core.skipWaiting();

You can see the caching files under the cache storage tab.



The life cycle of the service worker is implemented by default. You can handle each event/hooks inside registerServiceWorker.js file as mentioned in step 3.

Now, you can especially handle different push notifications, background sync, using indexdb inside this custom service worker created.

5. Service Worker Life Cycle Event:

If you want to implement the lifecycle event on your own you can use them inside the service-worker.js file itself. Make sure to unregister the service worker from the registerServiceWorker.js file and register your service worker. It can be done in the main.js file.  Some of the life cycle events are below: 
self.addEventListener('install', (event) => {
  console.log("Installing ....................");
});
self.addEventListener('activate', (event) => {
  console.log("activateing ....................");
});
self.addEventListener('fetch', (event) => {
  console.log("fetching ....................");
});
self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});
If you want to know more about these events please look Service Workers: an Introduction.

Share:

Wednesday, December 16, 2020

VueJs Progressive Web Apps(PWA): How to Change the App Name, Icon, Color, Display for Mobile Devices.

In this tutorial, I will show you how to create and change the Manifest file. The manifest file will allow the way of displaying our application, especially on mobile devices i.e showing app name, app icon for different size mobile screen, the color of the app, etc.

Please visit our previous articles on PWA:

Create a Simple VueJs Progressive Web Apps (PWA) and Deploy to Firebase


Create a Manifest file.

The default manifest file will be created when you build your application with Vue CLI. Let's build our application.

yarn build
Now you can see the manifest.json file under the dist/ folder. This is the file that we are going to modified according to our requirements.



To change this file first copy the file inside the public/ folder. On each build, all the files under the public folder will be copied to the dist/ folder so we have our changes in production.


 The manifest.json file looks like below:
{
  "name": "vue-pwa",
  "short_name": "vue-pwa",
  "theme_color": "#4DBA87",
  "icons": [
    {
      "src": "./img/icons/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "./img/icons/android-chrome-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    },
    {
      "src": "./img/icons/android-chrome-maskable-192x192.png",
      "sizes": "192x192",
      "type": "image/png",
      "purpose": "maskable"
    },
    {
      "src": "./img/icons/android-chrome-maskable-512x512.png",
      "sizes": "512x512",
      "type": "image/png",
      "purpose": "maskable"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "background_color": "#000000"
}

We will discuss each property used here. If you have difficulties generating this file make sure to create one with this structure.

If you deploy with this default configuration and open it into your mobile then you can see the below display.

Note: we are using the default vue CLI application for testing.


name :

This will be the name displayed on the screen(splash screen) before the application load the CSS. Please change the name you want for your application. When you click the icon then you will see this name and icon as a first screen.

short_name:

This is similar to the name property but displayed under the launcher icon as shown above.

theme_color:

The default theme color of the application.

icons:

Different icons used for different screen mobile devices. For e.g the different launcher icon size for the different screen for the android device looks as below:


Make sure to put different size image icon for your app under public/img/icons folders or if you want to use in a different folder inside public/ then use the same path on manifest.json file.

By providing different size icons, the icon will be used according to the different screen size devices.

start_url:

This will be the URL for the entry point when you add the app to the home screen.

display:

"that determines the developers’ preferred display mode for the website. The display mode changes how much of browser UI is shown to the user and can range from the browser (when the full browser window is shown) to fullscreen (when the app is full-screened)."

background_color:

This defines the background color of the splash screen before the application CSS is loaded. When you click the app on your device, initially it will load the background color with icons before the app is loaded.

For other properties and more descriptions please visit Web App Manifest. 

Finally, make changes to the properties under manifest.json and build the application and deploy. You can see the desired changes in your mobile devices.



Share:

Monday, December 14, 2020

How to Test Our VueJs Progressive Web Apps(PWA) Locally over HTTPs.

In this tutorial, I will show you how we can test our PWA application locally. The PWA needs an HTTPS connection to work properly. So, it's better to test the application over HTTPs locally.

Make sure you have a sample running PWA locally. I am using vuejs sample PWA application for testing purposes.

1. Build our application:


yarn build
This will create the dist folder which is deployment-ready.



2. Install an http-server package:

First, install http-server package globally, which helps to run the dist folder. For this, open a terminal or command prompt to run the following command.

For npm package manager:
npm install http-server -g

For yarn package manager:
yarn global add http-server

Make sure to refresh your terminal or command prompt after installing the package.

Now, run the application using this package.
http-server dist/
Where dist/ is the folder created while building the application. This will run the application. If you open the application, you will see that our application is not working properly as no service worker is registered.



3. Install and setup Ngrok to run the application.

Here, we are using the third-party service called Ngrok which is free for testing.

What it will do is it will simply tunnel our local server with a specific port over HTTPS which is what we want to test locally. 

Download it from Ngrok download.

Go to the downloaded folder and extract it. You can see the executable binary file. In order to run the file please follow as below.

For Windows:

Simply double click that .exe file. Which will open in the command prompt.

Now, you are ready to tunnel your local server. Use the following command to tunnel your server.
ngrok.exe http 8080
Make sure your application is running in port 8080 otherwise, use your own port instead.


You can see similar to the above. Now you can open the HTTPS tunneled URL.

If you are getting an Invalid Host header issue then you can simply run the below command instead which resolves the issue.
ngrok.exe http 8080 -host-header="localhost:8080"
For Linux: Go to the extracted Ngrok file directory and use the following command.
./ngrok http 8080




If you get the issue with an Invalid Host header then use the following command instead:
./ngrok http 8080 -host-header="localhost:8080"
Once, you open the URL, you can see the service worker for PWA will be working as below.





Share:

Sunday, December 13, 2020

How to Deploy VueJs Application to Firebase for Different Environment

In this tutorial, we are going to deploy our Vue application to the firebase server for different environments.

Before putting any project into production it needs to develop, QA first.

So, for different cases, we may need different configurations and need to use different server resources.

According to this requirement, we need to set up different configuration files for different environments. So while deploying, it can take a specific config for the corresponding environment.

Generally, what we are going to do is:

  1. Create different projects for different env in firebase
  2. Set up firebase hosting in our application
  3. Configuring test config file for different environment
  4. Deploy the application for different environment

1. Create projects in firebase for different environment

Go to the "https://console.firebase.google.com/" and create a project.

Here we are creating two sample projects for develop and qa environment.

- Give the name of the project, we are giving "develop-vue-test" to develop and "qa-vue-test" to qa environment








Note: Create two different projects for two different environments.

2. Set up a firebase hosting in our application.

Here, we are considering you already have your vuejs application. Go to the project directory and initialize the firebase.

- Install Firebase CLI:

For npm package manager:
npm install -g firebase-tools
For yarn package manager:
yarn global add firebase-tools

- Initialize your project:

firebase login
This will redirect you to login with a Google account. Use the same account to login which is used to create for the different firebase projects previously.


Now, initialize the firebase project using the following command:

firebase init




The above process will create the following two different files in your project directory:

- .firebaserc:

{
  "projects": {
    "default": "develop-vue-test"
  }
}
As we use default firebase project as "develop-vue-test" while doing firebase init.

- firebase.json
{
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}
This is the firebase config file where you can see the setup we did previously. For e.g "public": "dist" as we choose dist as public.

3. Configuring test config file for the different environment:

Now let's create some config files in the project directory for different env.

For production:

.env.production

For develop:

.env.develop
VUE_APP_ENDPOINT=https://develop.com
You can create whatever config key-value pair here with the respective environment. We are using VUE_APP_ENDPOINT test sample.

For qa:

.env.qa
VUE_APP_ENDPOINT=https://qa.com
You can access that config file property anywhere by using:
process.env.VUE_APP_ENDPOINT



Now let's add a qa-vue-test firebase project inside firebase.json
{
  "projects": {
    "default": "develop-vue-test",
    "qa": "qa-vue-test"
  }
}
Let's go to the package.json file and add and change the build script to use this config file.

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "develop": "vue-cli-service build --mode develop",
    "qa": "vue-cli-service build --mode qa"
  },
Here, we added two more scripts for develop and qa environment.

"develop": "vue-cli-service build --mode develop",
"qa": "vue-cli-service build --mode qa"

4. Deploy the application:

For develop:
yarn develop
Which will build the application for develop env.
firebase deploy


as inside the firebase.json file, the default project is selected as develop-vue-test so it will simply deploy to develop.


For qa:
yarn qa
firebase deploy -P qa
Make sure the name "qa" needs to same as the name of the project defined in firebase.json. This will simply deploy the build folder to "qa-vue-test" firebase project.

Finally, we have successfully deployed our vuejs application to firebase for different environments.

If you want to track the hosting inside the firebase console then you can go to the Hosting tab in the console.




Share:

Saturday, December 12, 2020

Create a Simple VueJs Progressive Web Apps (PWA) and Deploy to Firebase

In this tutorial, we are going to create a simple VueJs PWA application and also show you how to deploy it to firebase. As we know that PWA is being more famous these days due to its very fast performance and can be used for different platforms with a single code base as well as the offline functionality and caching support.

1. Install Vue CLI

If you haven't installed the Vue CLI, open the command prompt or terminal and run the following command to install it globally. 

- For npm package manager:

npm install -g @vue/cli
- For yarn package manager:

yarn global add @vue/cli



2. create a VueJs PWA project:

vue create vue-pwa
Now, select the manual option

Select Progressive Web App (PWA) Support option from the list. As you need to go to that option using the down arrow on the keyboard and hit the spacebar to select that option. Also select the other option if you are going to use them like Router, Vuex, etc.



Now, go to the project directory and run the application.
cd vue-pwa
yarn serve
Vue CLI created a sample demo application for us so, we are using the same for this tutorial. If you look into the Application tab by doing the inspect element of the above running project, there you can see the Service Workers. The main heart of the PWA is this service worker. As if we run the PWA application locally the service worker will not work, as it required an HTTPS secure connection.

 

The service worker is the script that will run in the background separately from the application which helps to install, activate, caching of our application. There are more thing about service worker, will discuss in the future article.

So how we can test the PWA application. As we can use some third-party services as well as we can simply deploy to firebase.

3. How to test our PWA application locally:

- Build the application in production mode:

yarn build
This will create the deployment-ready dist folder.

First, run this locally using http-server package. In order to do the show first install it globally.
npm install http-server -g
Now, run the dist folder:
http-server dist/
Which will run the application. Now what we need to do is tunnel our local server with HTTPS. Please follow this Tunnel local server to the public internet with HTTPS using Ngrok. This will tunnel our local server over HTTPS. Now open the tunneled URL. You can see the service worker as follows.



Also, you can see the + icon to install your PWA app in the browser.


If you run the same tunneled URL on the mobile then you will get the following screen to install your PWA application.

Add vue-pwa to Home screen if you click this, it will add the application to the home screen so that you can later open it by simply clicking it.

4. Deploy to firebase.

Now, let's deploy the build dist folder in the firebase server.

- Go to the firebase console "https://console.firebase.google.com/"

- Create a project by giving the project name.

- Installing firebase in our system.

 Open the command prompt or terminal and install firebase globally.
npm install -g firebase-tools
Initialize the project: Make sure to go to the project directory.
firebase login
This will ask for a google login. You can authenticate the google account where your firebase console project is created. If you want to logout use the following command.
firebase logout
Now, initialize the project:
firebase init
This will ask a couple of question make sure you insert the right as below:
We are simply using it for hosting our application so chose the same option.


Make sure the above setting. The public directory will be dist in our case, as we are deploying the dist folder.

This will create two files in our project:

- .firebaserc

where you can find the project's configuration. Make sure you have the same project name in the "default" section to that create on the firebase console. While deploying it, will use the same firebase console project created. In my case, it is "vue-pwa-7ed80". The config file looks like below.

{
  "projects": {
    "default": "vue-pwa-7ed80"
  }
}

- firebase.json

where all the hosting configuration is done. The config file looks like below.

{
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

Deploy our application.

First, build the application:
yarn build

Now, deploy the build dist folder

 
firebase deploy

This will deploy our application to the firebase server. You can see the deployment history and track from the console under the Hosting section inside the firebase console.

Firebase gives the live HTTPS URL which you can see in the firebase console. If you run that URL you will see the service worker will register and can be run the application as a PWA application.

Finally, we created a simple VueJs application with PWA support and successfully deployed it to the firebase.



Share:

Friday, December 11, 2020

How to Implement Webcam in VueJs Application

In this tutorial, we are going to implement a webcam in the Vuejs application.


Generally, what it does is:

  1. Stream the video from the webcam
  2. Capture photo from the streaming video
  3. Preview the captured photo
  4. Convert it into the file to send to the server
The overall implementation looks as below:




1. Create a sample Vuejs application.

Open the terminal or command prompt and create the application.

vue create vue-camera
  

Select the default option or can select manually, where you can have a choice to set up.
cd vue-camera
yarn serve

2. Create a Vuejs webcam component



Now, let's create a component called Camera.vue.  
<div class="camera-box">
    <div style="display: flex; justify-content: center;">
        <img style="height: 25px;" v-if="isCameraOpen"
             src="https://img.icons8.com/material-outlined/50/000000/camera--v2.png"
             class="button-img camera-shoot" @click="capture"/>
        <div class="camera-button">
            <button type="button" class="button is-rounded cam-button"
                    style="margin-left: 40%; background-color: white; border: 0px;"
                    @click="toggleCamera"
            >
        <span v-if="!isCameraOpen"><img style="height: 25px;" class="button-img"
                                        src="https://img.icons8.com/material-outlined/50/000000/camera--v2.png"></span>
                <span v-else><img style="height: 25px;" class="button-img"
                                  src="https://img.icons8.com/material-outlined/50/000000/cancel.png"></span>
            </button>
        </div>
    </div>
    <div style="height: 200px">
        <div v-if="isCameraOpen" class="camera-canvas">
            <video ref="camera" :width="canvasWidth" :height="canvasHeight" autoplay></video>
            <canvas v-show="false" id="photoTaken" ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
        </div>
    </div>
</div>
Let's set the data used.
export default {
  name: "Camera",
  components: {
  },
  data() {
    return {
      isCameraOpen: false,
      canvasHeight:200,
      canvasWidth:190,
      items: [],
    }
  },
  }
<style scoped>
.camera-box {
  border: 1px dashed #d6d6d6;
  border-radius: 4px;
  padding: 2px;
  width: 80%;
  min-height: 300px;
}

</style>





The HTML file used will show the camera image button to capture the photo. Here, we are using canvas height and width for the photo size. You can always adjust the different size photo by adjusting canvas height and width.

Let's use the different functions used in HTML.
toggleCamera() {
      if (this.isCameraOpen) {
        this.isCameraOpen = false;
        this.stopCameraStream();
      } else {
        this.isCameraOpen = true;
        this.startCameraStream();
      }
    },
This function simply toggles the camera to capture the photo. And start streaming the video. Let's implement the function used inside this toggleCamer().
startCameraStream() {
      const constraints = (window.constraints = {
        audio: false,
        video: true
      });
      navigator.mediaDevices
          .getUserMedia(constraints)
          .then(stream => {
            this.$refs.camera.srcObject = stream;
          }).catch(error => {
        alert("Browser doesn't support or there is some errors." + error);
      });
    },
The above function will start the camera by using the navigator mediaDevices interface which will access to the connected media input device, in our case its camera. And asign the streaming to canvas dom element to show the video. Here we are setting the constraints as audio is false because we don't need the audio to capture the photo.
stopCameraStream() {
      let tracks = this.$refs.camera.srcObject.getTracks();
      tracks.forEach(track => {
        track.stop();
      });
    },
The above function will simply stop the camera by stopping the sequence of track in streaming.
capture() {
      const FLASH_TIMEOUT = 50;
      let self = this;
      setTimeout(() => {
        const context = self.$refs.canvas.getContext('2d');
        context.drawImage(self.$refs.camera, 0, 0, self.canvasWidth, self.canvasHeight);
        const dataUrl = self.$refs.canvas.toDataURL("image/jpeg")
            .replace("image/jpeg", "image/octet-stream");
        self.addToPhotoGallery(dataUrl);
        self.uploadPhoto(dataUrl);
        self.isCameraOpen = false;
        self.stopCameraStream();
      }, FLASH_TIMEOUT);
    },
When a user clicks the camera button, then it will take the video streaming dom context and captured the 2d photo with the given width and height. We are using the setTimeout because video streaming will take some time to stream.




Let's implement the self.addToPhotoGallery() used in the above function. This is to preview the captured photo. For this, we are using the "vue-picture-swipe" library. So first let's add this to our application.

For yarn package manager:

yarn add vue-picture-swipe

For npm package manager:

npm install --save vue-picture-swipe

Import the library in our application:

import VuePictureSwipe from 'vue-picture-swipe';
Register the component:

components: {
    VuePictureSwipe
  },
Use in the template:

<vue-picture-swipe :items="items"></vue-picture-swipe>

addToPhotoGallery(dataURI) {
      this.items.push(
          {
            src: dataURI,
            thumbnail: dataURI,
            w: this.canvasWidth,
            h: this.canvasHeight,
            alt: '' // optional alt attribute for thumbnail image
          }
      )
    },
This will preview the captured pictures.

Finally, using self.uploadPhoto() we can upload the captured picture to the server.

uploadPhoto(dataURL){
      let uniquePictureName = this.generateCapturePhotoName();
      let capturedPhotoFile = this.dataURLtoFile(dataURL, uniquePictureName+'.jpg')
      let formData = new FormData()
      formData.append('file', capturedPhotoFile)
      // Upload api
      // axios.post('http://your-url-upload', formData).then(response => {
      //   console.log(response)
      // })
    },
    generateCapturePhotoName(){
      return  Math.random().toString(36).substring(2, 15)
    },
    dataURLtoFile(dataURL, filename) {
      let arr = dataURL.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type: mime});
    },




generateCapturePhotoName() will generate the unique name for each captured picture, and to send to the server, first we are converting the dataUrl value to file using dataURLtoFile()

The overall implementation of the component Camera.vue looks like as below:

<template>
    <div class="camera-box">
        <div style="display: flex; justify-content: center;">
            <img style="height: 25px;" v-if="isCameraOpen"
                 src="https://img.icons8.com/material-outlined/50/000000/camera--v2.png"
                 class="button-img camera-shoot" @click="capture"/>
            <div class="camera-button">
                <button type="button" class="button is-rounded cam-button"
                        style="margin-left: 40%; background-color: white; border: 0px;"
                        @click="toggleCamera"
                >
        <span v-if="!isCameraOpen"><img style="height: 25px;" class="button-img"
                                        src="https://img.icons8.com/material-outlined/50/000000/camera--v2.png"></span>
                    <span v-else><img style="height: 25px;" class="button-img"
                                      src="https://img.icons8.com/material-outlined/50/000000/cancel.png"></span>
                </button>
            </div>
        </div>
        <div style="height: 200px">
            <div v-if="isCameraOpen" class="camera-canvas">
                <video ref="camera" :width="canvasWidth" :height="canvasHeight" autoplay></video>
                <canvas v-show="false" id="photoTaken" ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
            </div>
        </div>
        <vue-picture-swipe :items="items"></vue-picture-swipe>
    </div>
</template>

<script>
    import VuePictureSwipe from 'vue-picture-swipe';

    export default {
        name: "Camera",
        components: {
            VuePictureSwipe
        },
        data() {
            return {
                isCameraOpen: false,
                canvasHeight:200,
                canvasWidth:190,
                items: [],
            }
        },
        methods: {
            toggleCamera() {
                if (this.isCameraOpen) {
                    this.isCameraOpen = false;
                    this.stopCameraStream();
                } else {
                    this.isCameraOpen = true;
                    this.startCameraStream();
                }
            },
            startCameraStream() {
                const constraints = (window.constraints = {
                    audio: false,
                    video: true
                });
                navigator.mediaDevices
                    .getUserMedia(constraints)
                    .then(stream => {
                        this.$refs.camera.srcObject = stream;
                    }).catch(error => {
                    alert("Browser doesn't support or there is some errors." + error);
                });
            },

            stopCameraStream() {
                let tracks = this.$refs.camera.srcObject.getTracks();
                tracks.forEach(track => {
                    track.stop();
                });
            },

            capture() {
                const FLASH_TIMEOUT = 50;
                let self = this;
                setTimeout(() => {
                    const context = self.$refs.canvas.getContext('2d');
                    context.drawImage(self.$refs.camera, 0, 0, self.canvasWidth, self.canvasHeight);
                    const dataUrl = self.$refs.canvas.toDataURL("image/jpeg")
                        .replace("image/jpeg", "image/octet-stream");
                    self.addToPhotoGallery(dataUrl);
                    self.uploadPhoto(dataUrl);
                    self.isCameraOpen = false;
                    self.stopCameraStream();
                }, FLASH_TIMEOUT);
            },

            addToPhotoGallery(dataURI) {
                this.items.push(
                    {
                        src: dataURI,
                        thumbnail: dataURI,
                        w: this.canvasWidth,
                        h: this.canvasHeight,
                        alt: 'some numbers on a grey background' // optional alt attribute for thumbnail image
                    }
                )
            },
            uploadPhoto(dataURL){
                let uniquePictureName = this.generateCapturePhotoName();
                let capturedPhotoFile = this.dataURLtoFile(dataURL, uniquePictureName+'.jpg')
                let formData = new FormData()
                formData.append('file', capturedPhotoFile)
                // Upload image api
                // axios.post('http://your-url-upload', formData).then(response => {
                //   console.log(response)
                // })
            },

            generateCapturePhotoName(){
                return  Math.random().toString(36).substring(2, 15)
            },

            dataURLtoFile(dataURL, filename) {
                let arr = dataURL.split(','),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n);

                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, {type: mime});
            },
        }
    }
</script>

<style scoped>
    .camera-box {
        border: 1px dashed #d6d6d6;
        border-radius: 4px;
        padding: 2px;
        width: 80%;
        min-height: 300px;
    }

</style>



Share:

Monday, December 7, 2020

How to Build the Vuejs Application as a Library and Web Component

In this tutorial, we are going to learn how to create a library and a web component of the Vuejs application, so that we can reuse them as a library in a different application and a custom HTML element in different webpages.

Using VueCli 3.x it's very easy to build our application. It gives some command to create them.

1. Create a sample Vuejs application:

Open the command prompt or terminal and use the following command:

vue create vue-build-target-app
  

You can either select the Default option so that you don't manually setup. This will default use the yarn package manager so, make sure to have package manager installed. Also, you can manually select features option.

Now, go to the project directory and run the application using the command:
cd vue-build-target-app
yarn serve
  
If you open the project, you can see the default component called HelloWorld.vue. We are using the same component to test.

2. Build as a Library:

Note: In lib mode, Vue is externalized. This means the bundle will not bundle Vue even if your code imports Vue

While building as a library even if we are importing the Vue in the component it will not use that in the bundle.

Building a single component as a library:

vue-cli-service build --target lib --name myLib [entry]
  
This is the command that we use where myLib is the name of the output bundle file and [entry] is the entity that we use.

For e.g:

vue-cli-service build --target lib --name HelloWorld src/components/HelloWorld.vue
  
This will build the single component HelloWorld.vue as the library. So, what you need to do is place the above command inside the package.json file under scripts.

"build-lib": "vue-cli-service build --target lib --name HelloWorld src/components/HelloWorld.vue",
  

Now, run the script from the command prompt:

yarn build-lib
  
This command will build the target files inside dis folder.


dist\HelloWorld.umd.js is the UMD bundle that can be served in the normal HTML file. As you can see the sample use case inside the dist folder contain the following demo.html file:

<meta charset="utf-8"></meta>
<title>HelloWorld demo</title>
<script src="https://unpkg.com/vue"></script>
<script src="./HelloWorld.umd.js"></script>

 <link href="./HelloWorld.css" rel="stylesheet"> </link>


<div id="app">
  <demo>  </demo>
</div>

<script>
new Vue({
  components: {
    demo: HelloWorld
  }
}).$mount('#app')
</script>
  
If you run this HTML file then you can see the desire output for that page.

dist\HelloWorld.umd.min.js   is the minified version of the UMD bundle 

dist\HelloWorld.common.js  is used in a module-based application

dist\HelloWorld.css is the CSS file that is associated with that component.

You can use those desired files on your web pages.

3. Build as a Web Component:

You can build a single entry as:

vue-cli-service build --target wc --name my-element [entry]
Here wc will build as a web component. For e.g:

vue-cli-service build --target wc -name HelloWorld src/components/HelloWorld.vue



Use this inside script and run the command:

"build-wc":vue-cli-service build --target wc -name HelloWorld src/components/HelloWorld.vue
Here you can give any name instead of  "build-wc" but you need to run the build command with this name

yarn build-wc
Which will create the following files under the dist folder:

dist\hello-world.js 
dist\hello-world.min.js

This is the web pack bundle that can be used in web pages. Sample example is created under the same folder i.e demo.html.

This doesn't require component registration, as the component is already registered while creating it. So it looks like a normal plain HTML element.

If you want to build the multiple components file then use the following command instead:

//package.json
    "build-wc": "vue-cli-service build --target wc --name demo src/components/*.vue",





Share: