Categories
Programming

An HTML5 desktop app with electron4 min read

Electron let’s you build cross platform desktop apps using HTML5 and javascript. Let’s make a  demo desktop app with electron.

If you haven’t  heard of electron from GitHub, you should go through this Build cross platform desktop apps with JavaScript, HTML, and CSS before continuing.

Without wasting our time let’s get started with the app.

Prerequisites

The app

We shall call our app Dapp – Demo App.

Let’s also create a project folder named dapp and open command window inside the folder.

All the commands have to be run inside this folder.

The first command would be

npm init

Input the required information and our package.json file would be created.

Now we have to install electron which is available as an npm package.

npm install electron-prebuilt --save-dev

We are installing it as developer dependency.

The package.json file has to be modified to run electron at start

{
    "name": "dapp",
    "version": "1.0.0",
    "description": "A demo app made with electron.",
    "main": "index.js",
    "scripts": {
        "start": "electron ."
    },
    "keywords": [
        "electron",
        "demo"
    ],
    "build": {
        "appId": "in.jijnasu.dapp"
    },
    "author": "Hrishikesh M K <hrishikesh.mk1@gmail.com> (https://jijnasu.in)",
    "license": "ISC",
    "devDependencies": {
        "electron-prebuilt": "^1.4.10"
    }
}

Add a start script as shown above.

We have to create a file called index.js, as we have provided it in the package file with the key main.

Let’s just copy the index.js file provided in the electron website.

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

The index.js file would load an HTML file called index.html in our main window.

So let’s create one and save it in the same directory.

<!doctype html>
<html>

<head>
    <title>Dapp</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            position: relative;
            margin: 0;
            padding: 0;
            font-family: Avant Garde, Avantgarde, Century Gothic, CenturyGothic, AppleGothic, sans-serif;
            background-color: #2c3e50;
            color: #ffffff;
        }
        
        #cont {
            text-align: center;
            font-size: 30px;
            height: 300px;
            position: absolute;
            width: 300px;
            left: 50%;
            top: 50%;
            margin-left: -150px;
            margin-top: -150px;
            border: dashed;
        }
    </style>
</head>

<body>
    <div id="cont">
        <h1>Dapp</h1>
        <p id="time">...</p>
        <p id="date">...</p>
    </div>
    <script>
        var time_elem = document.getElementById('time');
        var date_elem = document.getElementById('date');
        window.setInterval(function() {
            var date = new Date();
            date_elem.innerHTML = date.toDateString();
            time_elem.innerHTML = make_valid(date.getHours()) + ':' + make_valid(date.getMinutes()) + ':' + make_valid(date.getSeconds());
        }, 200);

        function make_valid(num) {
            num = parseInt(num);
            if (num < 10) {
                return '0' + num;
            }
            return num;
        }
    </script>
</body>

</html>

Now our app is ready to run. Try it out with this command

npm start

Please note that the command window should be open inside the project folder throughout this tutorial.

Now that our app is ready, the only thing left is to package it.

Packaging electron applications

For packaging we use electron-builder.

First install electron-builder through npm.

npm install electron-builder --save-dev

The documentation for electron-builder tells us to modify the package.json file to add the pack and dist scripts.

A unique app id is also required for the build.

So let’s the modify the file.

{
    "name": "dapp",
    "version": "1.0.0",
    "description": "A demo app made with electron.",
    "main": "index.js",
    "scripts": {
        "start": "electron .",
        "pack": "build --dir",
        "dist": "build",
        "postinstall": "install-app-deps"
    },
    "keywords": [
        "electron",
        "demo"
    ],
    "build": {
        "appId": "in.jijnasu.dapp"
    },
    "author": "Hrishikesh M K <hrishikesh.mk1@gmail.com> (https://jijnasu.in)",
    "license": "ISC",
    "devDependencies": {
        "electron-builder": "^10.4.1",
        "electron-prebuilt": "^1.4.10"
    }
}

And finally run

npm run dist

Comment below if something went wrong.

✌️

Categories
Programming

Random color generator in javascript2 min read

If you ever tried to create HTML or SVG graphs, it is most likely that you have asked google the question How to generate random colors in javascript? , because I for sure did ???? .

Maybe you have searched it for some other reason. To create some cool UI or something, or maybe to irritate the user with stupid colors ???? .

If you have never searched it or thought about it, well why don’t you go ahead and try it now, it’s free after all.

There are plenty of resources in the internet that would help you get the job done. But here is my little experiment.

Where to start?

I want a function that would take the number of colors to generate, as input and outputs the generated colors.

Something like this –

//generate colors
function gen_colors(no_of_colors_to_generate) {
  //magic

  //return an array of colors
  return colors;
}

So I decided to start with one color and tweak and shuffle the RGB values to generate random colors.

function color_gen(len) {
  //array in which generated
  //colors are stored
  colors = [];

  function gen_colors(colrs, len) {
    //generate the colors
  }

  //start with rgb(180, 54, 54)
  return gen_colors([180, 54, 54], len);
}
 The full function
function color_gen(len) {
  //array in which generated
  //colors are stored
  colors = [];

  function gen_colors(colrs, len) {
    //loop and create all combinations
    //of the given color
    for (var i = 0; i < 3; i++) {
      for (var j = 0; j < 3; j++) {
        for (var k = 0; k < 3; k++) {
          var color_arr = [colrs[i], colrs[j], colrs[k]];
          //exclude if combination already exists
          //or have the same values ex rgb(180, 180, 180)
          if ((colors.indexOf(rgbize_arr(color_arr)) == -1) && !(colrs[i] == colrs[j] && colrs[i] == colrs[k])) {
            colors.push(rgbize_arr(color_arr));
          }
          //if required colors
          //grater than 25 repeat the 
          //colors generated
          if (colors.length >= 25) {
            colors = colors.concat(colors);
          }
          //if required no. of colors
          //are generated return
          if (colors.length == len) {
            return colors;
          }
          //if generated > required
          //return only required
          else if (colors.length > len) {
            //console.log(colors.slice(0, len));
            return colors.slice(0, len);
          }
          //if combinations are over
          //generate a new first color
          else {
            if (i == 2 && i == j && i == k) {
              var max_colr = Math.max.apply(Math, colrs);
              var min_colr = Math.min.apply(Math, colrs);
              var colr1 = Math.floor((max_colr + min_colr) / 4);
              var colr2 = Math.floor((max_colr + min_colr) / 2);
              var colr3 = Math.floor((max_colr + min_colr) / 3);
              return gen_colors([colr1, colr2, colr3], len);
            }
          }
        }
      }
    }
  }
  //convert array into rgb string
  function rgbize_arr(colr_arr) {
    return 'rgb(' + colr_arr.join() + ')';
  }
  return gen_colors([180, 54, 54], len);
}

Usage

var new_colors = color_gen(25);

Gotta better technique (highly likely), comment below  ???? .

See the color generator in action-

See the Pen Javascript random color generation by hrishikesh mk (@avastava) on CodePen.0

Categories
Programming wordpress

Writing a wordpress plugin – Google Analytics7 min read

This would be an answer to two of the most searched queries on the internet about wordpress.

  1. How to add google analytics to wordpress?
  2. How to write a wordpress plugin?

There are many plugins plugins that would help you enable google analytics on your wordpress site, including the ones that would give you analytics dashboard inside the admin panel.

But you know…. ????

Writing the plugin

What should it do?

  1. Add google analytics code on all pages, except the admin pages.
  2. Add a settings page for the plugin, which would have the options to input
    • GA tracking ID
    • A checkbox to know whether tracking has to be done when logged in.

Where to start?

First we would give our plugin a unique name. And I name it –

Jijnasu Google Analytics ?

For adding the GA tracking code to every page that we want to track, we just have to add and action

//add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
add_action( 'wp_footer', 'jijnasu_google_analytics_add_script');

We use the jijnasu_google_analytics_add_script function to add the required code.

The jijnasu_google_analytics_add_script function
	

function jijnasu_google_analytics_add_script() {
  if(is_admin() || (trim((esc_attr( get_option('jijnasu_google_analytics_hide_if_logged_in'))))=='1' && is_user_logged_in() )){
    return;
  }
?>
<script type="text/javascript">

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', <?php
echo "'" . esc_attr(get_option('jijnasu_google_analytics_ga_code')) . "'"; ?>, 'auto');
ga('send', 'pageview');

</script>
<?php
}
Refer

We should take the tracking ID from the from the user as input in the settings page. The value are saved with a key.

The key jijnasu_google_analytics_ga_code was used here to save the GA ID. 

Now to get this value from the database we use the get_option($key) method as shown above.

With another key jijnasu_google_analytics_hide_if_logged_in , we store the information on whether to disable the tracking when a user is logged in.

If the value of this option is ‘1 , the tracking won’t be active when a user is logged in.

Time to register these settings using the WordPress settings api

Registering plugin settings

Add an action on admin_int hook like this.

if (is_admin())
{
  add_action('admin_init', 'jijnasu_google_analytics_register_settings');
}
Refer

Now use the jijnasu_google_analytics_register_settings function to register the settings.

function jijnasu_google_analytics_register_settings()
{

  // register settings
  // add_settings_section( $id, $title, $callback, $page )

  add_settings_section('jijnasu_google_analytics_section1', 'General', 'jijnasu_google_analytics_section_callback_function', 'jijnasu_google_analytics_options');

  // add_settings_field( $id, $title, $callback, $page, $section, $args )

  add_settings_field('jijnasu_google_analytics_ga_code', 'Google analytics tracking code', 'jijnasu_google_analytics_ga_code_cf', 'jijnasu_google_analytics_options', 'jijnasu_google_analytics_section1');
  add_settings_field('jijnasu_google_analytics_hide_if_logged_in', 'Disable when logged in', 'jijnasu_google_analytics_hide_if_logged_in_cf', 'jijnasu_google_analytics_options', 'jijnasu_google_analytics_section1');
  register_setting('jijnasu_google_analytics_options', 'jijnasu_google_analytics_ga_code');
  register_setting('jijnasu_google_analytics_options', 'jijnasu_google_analytics_hide_if_logged_in');
}
Refer

With add_settings_section we can add an input section, and with add_settings_field,  inputs inside the section can be addded.

Input parameters for add_settings_section

  1. $id -> Unique ID for the settings section
  2. $title -> The title for the section. Ex- General or Advanced
  3. $callback -> A function that echoes text/HTML desription for the section.
  4. $page -> url-slug of the settings page.

Input parameters for add_settings_field

  1. $id -> Unique ID for the setting
  2. $title -> Label for the input field
  3. $callback -> Function that prints out the input element. Ex – echo ‘<input />’
  4. $section -> id of the section given in add_settings_section

Use register_setting when using add_settings_field so that WordPress could take care of your form submission and validation.

Creating the callback functions
// callbacks
// callback for add_settings_section

function jijnasu_google_analytics_section_callback_function()
{
  echo '<p>Jijnasu GA general settings</p>';
}

// for add_settings_field
// for GA code input

function jijnasu_google_analytics_ga_code_cf()
{
  echo '<input name="jijnasu_google_analytics_ga_code" id="jijnasu_google_analytics_ga_code" type="text" value="' . esc_attr(get_option('jijnasu_google_analytics_ga_code')) . '" />';
}

// for checkbox

function jijnasu_google_analytics_hide_if_logged_in_cf()
{
  echo '<input name="jijnasu_google_analytics_hide_if_logged_in" id="jijnasu_google_analytics_hide_if_logged_in" type="checkbox" value="1" class="code" ' . checked(1, get_option('jijnasu_google_analytics_hide_if_logged_in') , false) . ' />';
}

Values for the input fields are set by fetching it from the database using the get_option function.

Now that we have registered our settings, let’s add our plugin settings page.

Adding plugin settings page

Add one more action.

if (is_admin())
{
  add_action('admin_menu', 'jijnasu_google_analytics_settings_page');
  add_action('admin_init', 'jijnasu_google_analytics_register_settings');
}

We have added admin_init tag earlier, and now we add the admin_menu one for adding menu options.

The jijnasu_google_analytics_settings_page function

Second parameter to the add_action on admin_menu hook added above.

function jijnasu_google_analytics_settings_page()
{

  // add_options_page( $page_title, $menu_title, $capability, $menu_slug, $function);

  add_options_page('Jijnasu Google Analytics', 'Jijnasu GA', 'manage_options', 'jijnasu-google-analytics', 'jijnasu_google_analytics_options_page');
}
Refer

Now let’s add the contents of the settings page using the jijnasu_google_analytics_options_page function.

<?php

function jijnasu_google_analytics_options_page()
{
?>
    <div class="wrap">
      <h1>Jijnasu Google Analytics</h1>
      <form method="post" action="options.php">
        <?php
  settings_fields('jijnasu_google_analytics_options');
  do_settings_sections('jijnasu_google_analytics_options');
  submit_button();
?>
      </form>
    </div>
<?php
}
Refer

The do_settings_section would do the magic, well almost and print out all the input fields that we have added earlier.

Leave your queries below if you are not able to follow or something is wrong.

Good day ???? .

Download the plugin – Jijnasu Google Analytics

Other WordPress plugins – WordPress read time plugin