Category Archives: JavaScript

Loading an image from the iOS Library in PhoneGap

23 Aug 2016

While working through one of my personal projects I’ve figured out how to load an image from an iOS device’s Library. There are two steps – first use the Camera plugin to provide a UI for the user to select a file. The next is to take the file path the Camera plugin provides and use the File plugin to load it.

Requirements

This was tested via PhoneGap Build using the following setup:

  • CLI 6.3.0
  • iOS deploy target: 9.0.0
  • Camera plugin version 2.2.0
  • File plugin version 3.0.0

If you’re using PhoneGap Build this is what should be added to your config.xml





Using the Camera Plugin to Access the Library

It might seem counter intuitive to use the Camera plugin since it seems logical to first look at the File API to look for files… unlike the File API where you would need to write your own file browser and UI, the Camera Plugin uses native functionality and so makes it trivial to pick an image from a user’s Library. The Camera plugin will present a native UI to the end-user so that they can navigate their Library’s folder structure to locate the image they want to use and in the end provide a path to that image on the device.

This code will do what is described above:

   navigator.camera.getPicture(
      function (fileURI){
         console.log(fileURI);
         /* remove the comment below to use with
          * the rest of the code on this page
          */
         //convertPath(fileURI);
      },
      function (err){
         // fail
         console.log('fail',err);
      },
      {
         allowEdit: true,
         correctOrientation: true,
         destinationType: Camera.DestinationType.FILE_URI,
         sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
         targetHeight: window.innerHeight,
         targetWidth: window.innerWidth
      }
   );

Literally copy and paste the above, here are the things to note about the configuration object:

  • allowEdit – this is a flag that tells the native Library picker UI to allow scaling/positioning of the resource that the user selects.
  • correctOrientation – as it implies, use the image in the correct orientation relevant to how the device is being held
  • destinationType – this is the part that tells the plugin to return the path to the image
  • sourceType – tells the plugin to display UI to allow the user to select the image from the library
  • targetHeight – the desired height of the image – iOS creates a temporary image and passes that path back to you based on any edits and the Height and Width settings. Here I just assume that you would want an image that is the size of the viewport.
  • targetWidth – see above

That’s it. Dead simple. Now we need to load up the file using the path that the Camera plugin returns which requires the use of the File plugin.

Using the File plugin to Load an Image

This part is trickier and the source of much frustration among developers – during my search for documentation there was no single source that explained how this should work. I was left to putting the parts together from various sources as the “official” documentation didn’t directly explain how to do it. Anyway, I’ll do the explaining here within the code comments.

In short, these are the steps that result in a Base64 serialization of the image from which you can do whatever you like:

  1. Convert the image path to a file Entry Object
  2. Pass the FileEntry Object to a function that converts it to a File Object
  3. Pass the File Object to a FileReader to read the file
  4. Handle the response containing the image data

Here is all of the code:

   /**
    * This takes a file:// URI and creates a file entry object. The operation is asynch,
    * so the resulting fileEntry object is passed to the success callback.
    * @type {Function}
    * @name convertPath
    * @param {String} fileURI - the file:// path to the resource
    * @return {} Returns nothing
    */
    function convertPath(fileURI){
        window.resolveLocalFileSystemURL(
            fileURI,
            function(fileEntry){
                getFileSuccess(fileEntry);
            }
        );
    }

   /**
    * This starts the read process via the file entry object. This is asynch, so the file is passed to the success callback
    * @type {Function}
    * @name getFileSuccess
    * @param {Object} fileEntry - the file entry object
    * @return {} Returns nothing
    */
    function getFileSuccess(fileEntry){
        fileEntry.file(
            readFile, // success
            function(err){ // failure
                console.log('Failed to get file.',err);
            }
        );
    }

   /**
    * This creates a file reader using the file object that is passed to it.
    * Note how similar this is to programatically creating an image and loading data into it.
    * @type {Function}
    * @name readFile
    * @param {Object} file - file object
    * @return {} Returns nothing
    */
    function readFile(file){
    	console.log('got file...',file);
        var reader = new window.FileReader();
        reader.oneerror = function(e){
            console.log('FileReader Error: ',e.target.result);
        };
        reader.onloadend = function(fileObject) {
            console.log('we have the file:',fileObject);
            console.log('the image data is in fileObject.target._result');
        };
        reader.readAsDataURL(file);
    }

You can use the fileObject.target._result to populate the background of a div, for example:

$('#myDiv').css('background-image','url:(' + fileObject.target._result + ')');

Or insert it into a canvas:

   var image = new Image();
   var canvas = document.getElementById('canvas');
   var context = canvas.getContext('2d'); //retrieve context
   
   image.onload = function(){
      context.drawImage(this, 0, 0,_canvas.width, _canvas.height);
   }
   image.src = fileObject.target._result; // load the image data

It’s worth noting that of course you’ll need the appropriate styling for your DIVs if using the resulting image data as a background image. Also, if loading the data into a canvas your aspect ratio may be off – you’ll need to figure out how to scale the data to fit the canvas without distortion.

CanvasPainter

27 Jul 2016

One of the ways a developer shows the passion he or she has for their work is how they spend their free time. I do my best to spend my time learning more about what I like to do. Being a fellow who has a degree in Graphic Design that means that I have spent a lot of time over the years slaving over self-assigned projects in an effort to learn the things that I never learned in college.

A few years ago I wrote a canvas signature widget for a PhoneGap’d Sencha Touch-based mobile app. That tiny canvas signature pad was the genesis for the thing that I today call CanvasPainter. While it grew slowly over the ensuing years via bursts of productive energy it mostly languished in the dusty corners of hard-drives and USB memory sticks. That has changed and a lot of time is now being applied to CanvasPainter.

The collage at the top of this page illustrate portions of the CanvasPainter UI – portions of a fully functional web app. A group of beta testers are currently running it through its paces.

You will be able to experience CanvasPainter online. If you are inclined, you will eventually be able to buy it from the App Store. The hybrid app version will do things that the web app version does not. What those features will be I’ll share at a later date as I get closer to launch.

Anyway, this page serves as my way of sharing my excitement at the approaching V1.0 milestone (huzzah!! applause!!!).

[edit 7/27/2016]

Below is a sample image that I made with CanvasPainter… as a result of having painted this I realized I needed a color picker and that the swatches needed to be modified a little, which lead to a new thing in the settings panel…

made with CanvasPainter

Made with CanvasPainter

[edit 10/26/2016]

CanvasPainter is now available for purchase at the App Store. Took less than 48hrs for it to be accepted – apparently they didn’t find any issue with it. Visit the app’s website at www.canvaspainter.io to learn more about what it does.

I will also do a breakdown here at my website running through how the app was made as time allows.

If/Else One-liners with Short Circuit Evaluation

08 Jun 2016

Here is a one-liner I came up with today that uses short circuit evaluation via logical OR and logical AND operators. I’m attempting to do two things here:

  • Hide two HTML elements
  • Show two HTML elements

To accomplish the above I decided to write a function that expects an argument to indicate whether the elements should be hidden (false) or visible (true).

This would be the typical approach:

function toggle(bool){
   if (bool){
      $('#sectionHeader').show();
      $('#homeIcon').show();
   } else {
      $('#sectionHeader').hide();
      $('#homeIcon').hide();
   }
}

Here is the same function but using a one-liner to do all the logic:

function toggle(bool){
   (bool && !!$('#sectionHeader').show() && !!$('#homeIcon').show()) || !$('#sectionHeader').hide() || $('#homeIcon').hide();
}

The logical AND && operator requires that each operand be true in order for the operand that follows to be evaluated. If any of the operands fail then the value of that operand is returned.

Lets dissect the initial parenthesized expression:

  1. bool
    • This is the flag passed to the function that drives if we are going to show or hide our HTML elements. Lets assume that bool is “true”. Since we assume “true” we know that the next operand will be evaluated. If it were false then the ***value*** of the entire parenthesized expression would be “false” and none of the operands within the parenthesized expression would be evaluated.

     

  2. !!$(‘#sectionHeader’).show()
    • The logical NOT operator is used twice !! to coerce the value of the operand to true or false. To determine the boolean nature of the operand the jQuery expression must first be evaluated. jQuery returns an object. The object gets coerced to “true” and so the next operand will be evaluated.

     

  3. !!$(‘#homeIcon’).show()
    • This is the last operand within the parenthesized expression. Once evaluated jQuery returns an object and the two logical NOT operators coerce it to boolean “true”. As it is the last operator in the parenthesized expression its value is returned as the value of the expression. In this case the parenthesized expression is boolean “true”.

     

  4. ||
    • The logical OR || operator behaves differently than the logical AND (&&) operator. Where logical AND executes its operands if the preceding operand returned “true”, logical OR only evaluates its operands if the preceding expression was false. Here we know that because all of the operands of the parenthesized “logical AND expression” were evaluated and that the last operand returned true that the entire value of the expression is boolean “true”. Because of this all evaluation stops (short circuits) at that point. Nothing else is evaluated and the two HTML elements are shown.

     

This diagram illustrates the above:

short-circuit-onoe-liner_01
 

Next lets assume that bool is false. We’ll then start over from the beginning to see what happens.

  1. bool
    • Since bool is false none of the other operators grouped by the parenthesis are evaluated (another short circuit) and the returned value for the entire parenthesized expression is now boolean “false”

     

  2. ||
    • The logical OR operator now comes into play. It will only evaluate the operands to the right if the operand to the left was false. Since that is the case here the operand to the right of the logical OR operator is evaluated next…

     

  3. !$(‘#sectionHeader’).hide()
    • Note the single logical NOT operator (!). It is coercing the object returned by jQuery as boolean “false”. This means that the logical OR operator that follows hasn’t been satisfied and the next operand will be evaluated.

     

  4. $(‘#homeIcon’).hide()
    • This is a simple expression, just a bit of jQuery. If we get to this point we don’t really care what the value is here since we know it will be evaluated and our HTML element will be hidden. So then, there is no need to coerce the object that jQuery returns.

     

 
This next image illustrates the preceding bullet points:

short-circuit-onoe-liner_02

Image Caching

17 May 2016

I’ve been putting together a demo the past couple of days for a sales pitch that our sales guys will be going on in a couple of weeks. The demo will be wrapped in Cordova and shown on an iPad Pro and will have lots of full-screen (or at minimum near-full-screen) background images. As you might imagine, those images can be quite large in file size. I’ve compressed them to a reasonable amount but fearing that my view rendering might be less than perfect I’ve decided to write a caching mechanism for them.
_cache
First I’ve set up the following variables; one that lists all the images that I want to cache, the next is a counter that will be incremented with each image load.

// add all images to be cached in this array
var _imagesToCache = ['home_bg.jpg','interstate_bg.jpg'];

// incremented by onload events. when this equals (_imagesToChache.length -1) we know all large assets have been loaded
var _cachedImages = 0; 

Here’s the class I wrote that will do the heavy lifting:

/**
 * This will cache an image
 * @private
 * @param {string} path the path to the image to be cached
 */
function CacheImage(){
   var img = new Image();
   img.onload = function(){
       _cachedImages++;
   };
   this.cache = function(path){
      img.src = 'css/images/' + path;
   };
}

Next I iterate through the image array and start the caching process:

/**
 * loads large assets, (i.e., images) in an attempt to cache them and speed up view render time
 * @method
 * @type {Function}
 * @name airstream.model.loadLargeAssets
 */
ns.loadLargeAssets = function(){
   var i, len = _imagesToCache.length;
   for (i=0;i

When the app clears the DOM Ready and Device Ready events I then start caching my templates and images. I poll the status of both with a setTimeout within the following function:

/**
 * Recursive function that checks for the successful caching of templates and images.
 * @method
 * @type {Function}
 * @name airstream.model.loadTemplates()
 * @param {}
 * @return {} Returns nothing
 */
ns.checkForCompleteLoad = function(){
   // this is for my template caching, not related to image caching stuff
   var loaded = true;
   for (var p in _templates){
      if (!_templates[p]){
         loaded = false;
      }
   }
   // This next line deals with looking to see if the images have been loaded 
   if (!loaded || _cachedImages !== _imagesToCache.length){ // check the image cache counter
      window.setTimeout(airstream.model.checkForCompleteLoad,100); // try again in 100ms
   } else {
      console.log('Images Cached: ' + _cachedImages);
      airstream.view.renderHomeView();
   }
};

In reviewing this I could easily remove the polling and instead do the "complete load check" in each template or image-caching instance where once they have completed their tasks they check the counters vs the length of the template and image arrays. At that point they could decided if they were the last ones to load and then fire the rendering of the initial view if true.

Anyway, the above does the job for now. I'll find time to refine things when there's time to be had.

Ternary Operators and Ternary-esque Expressions

02 May 2016

You’re likely already familiar with the ternary operator, how it takes three operands and is often used to create one-liners that would otherwise take multiple lines to write. There are other constructs that cleverly emulate the ternary operator. I’ll show the few that I know of here, but first lets start with an example that we’ll reduce to a ternary and then to the aforementioned ternary-esque patterns.

Each example below can be copied/pasted into your browser’s console so you can see the expected results.

Classic Ternary Example

Take this normal if/else block:

var foo = 'bar', str; // declare variables
if (foo === 'bar'){
   str = 'foobar';
} else {
   str = 'foo';
}
console.log(str); // foobar

The if block takes quite a few lines of code. By using the ternary operator we can shorten it to a single line. The ternary operator takes the following form:

condition ? expr1 : expr2

… which is to say, if the condition evaluates to “true” then return expr1 else return expr2.

Using the above we can turn our if example into this:

var foo = 'bar', str; // declare variables
str = foo === 'bar' ? 'foobar' : 'foo'; // use a ternary operator
console.log(str); // foobar

Simple enough, lets look at two examples that emulate the ternary operator, the first one is below…

Ternary-esque Short Circuit Expression

condition && (expr1) || (expr2)

This is not a ternary but rather an expression that takes advantage of operator precedence which first evaluates the expression to the left of the logical AND operator &&. If the left side is true then the right side of the logical AND will be evaluated next. The parenthesis forces the interpreter to first evaluate the contained expression for truthiness which is how we trick it to execute our code (see this example) – but of course in this case we just have a string. If the first expression is false (incidentally an error in exp1 will be falsey) then the expression to the right of the logical OR operator || is evaluated instead.

This is how our initial if statement looks using this pattern:

var foo = 'bar', str; // declare variables
str = foo === 'bar' && ('foobar') || ('foo');
console.log(str); // foobar

Ternary-esque Object Literal Using a Boolean Key

Here’s another ternary-esque example – this is an object literal treated as an associative array constructed in such a way that it behaves much like a ternary. It first constructs said object so that it has two properties, true and false and assigns string values to them. Next, via the array literal short-hand (brackets) it attempts to access either one of the properties via an expression that must return “true” or “false”. Either one of those values will function as the key to one the object’s properties (‘true’ or ‘false’) and return its value:

{false: expr2, true: expr1}[condition]

var foo = 'bar', str; // declare variables
str = {false:'foo',true: 'foobar'}[foo === 'bar'];
console.log(str); // foobar

Ternary-esque Array Literal with a Boolean-Converted Integer Index

This example makes use of the unary operator  +  to convert boolean true/false to the integers 1 or 0. For example:

console.log(+true); // returns 1
console.log(+false);// returns 0

We can replace the boolean with an expression:

console.log(+('cat' === 'cat')); // returns 1

The conversion of a boolean to an integer allows us to use the evaluated expression as an array index:

var foo = 'bar', str; // declare variables
str = ['foo','foobar'][+(foo === 'bar')];
console.log(str); // foobar

Another way to convert the boolean to a number (or any number in string form for that matter) is to use the double NOT bitwise operator:

console.log(~~true); // returns 1
console.log(~~false);// returns 0

Nesting Ternary Operators

What discussion about ternary operators would be complete without talking about nesting them? Its true you can do this and yes some people find it hard to read and in fact almost everybody rails against the practice. Lets review an example:

var countrycode = 'eu';
var audience = (countrycode == 'eu')?'audienceEU':(countrycode == 'jp')?'audienceJP':(countrycode == 'cn')?'audienceCN':'audienceUS';
console.log(audience); // audienceEU

What we see here is that if the first expression is evaluated as being “false” then the first nested ternary operator is evaluated. If its expression is false, then we go to the next ternary and so on until we reach the end. If the last nested ternary operator is reached and its expression is also false then audience must be ‘audienceUS’. Of course, it doesn’t get that far because in the above code sample the first expression proves to be true.

IMO its not all **that** confusing to read, but its certainly could be challenging for others to make sense of especially if one attempts to nest something more complicated than what is shown here.

However, if we add some whitespace the result is much easier to understand (portions of this code sample has been lifted from StackOverflow and I noticed that John Resig formatted a nested ternary the same in a 2012 forum post):

var countrycode = 'eu';
var audience = (countrycode == 'eu') ? 'audienceEU' :
               (countrycode == 'jp') ? 'audienceJP' :
               (countrycode == 'cn') ? 'audienceCN' :
               'audienceUS';
console.log(audience); // audienceEU

To my eyes the above is very readable. If we were to write it like this would there still be objections as to its use? I honestly don’t think so.

Looking at the above sample I think its quite clear that if the condition on the left is true, then the expression on the right is assigned. If the condition is false then we move to the next line and so on.

Emulating Nested Ternary Operators with Switch Statements

FWIW I think the added whitespace formatting makes the previous example look very similar to the following switch statement:

var countrycode = 'eu';
var audience;
switch(countrycode ) {
     case 'eu': audience = 'audienceEU'; break;
     case 'jp': audience = 'audienceJP'; break;
     case 'cn': audience = 'audienceCN'; break;
     default  : audience = 'audienceUS';
}
console.log(audience); // audienceEU

It may be a stretch to call the above switch statement a nested ternary-esque construct but if you’ll permit me to say so, I think it certainly **resembles** a series of nested ternary operators what with its waterfall of conditional expressions and then the final “default” value. (Yes, I did put the break statement on the same line to more closely resemble the nested ternary example 😉 )

If you use switch statements in your work you can see that you can save a little bit of code by using the whitespace-formatted nested ternary approach. Of course, it all depends on what you’re doing as these examples are simple enough to lend themselves to the discussion.

Emulating Nested Ternary Operators with Short Circuit Evaluation

As we get further away from the ternary pattern and closer to the constructs that mimic or resemble it (however vaguely) we would be remiss not to revisit in more detail the topic of short circuit evaluation via the use of the logical OR || and logical AND && operators.

First, as you may have surmised from the previous short circuit example, the logical OR operator takes this form:

expr1 || expr2

We can use logical OR to create expressions that have a fallback, for example, if the expression on the left of the operator is truthy then evaluation of the entire expression stops there. If it happens to be falsey, then what is to the right of the operator is evaluated instead. Its use essentially allows us to set a default value such as in the next example.

var audience = audience || ”;

Basically, if audience doesn’t exist then assign the empty string else assign audience to itself. Lets see this in its ternary form:

var audience = audience ? audience : ”;

Next, the logical AND operator && takes this form:

expr1 && expr2

Unlike the logical OR where if the left side is falsey then the right side is evaluated, the logical AND can be used to evaluate both sides of the operator. In the application of it in these final examples – the left side must be true in order for the right side to be evaluated. You will see here that we are grouping expressions to be evaluated for truthiness and that we are using a little trick to assign the right side of the operator if the left side happens to be true. Note how we can take advantage of it to do something like this:

var countrycode = 'eu';
var audience = (countrycode == 'eu') && ('audienceEU');
console.log(audience); // audienceEU

Its important to note that if the expression on the left evaluates to false then audience would be boolean “false”;

Can we represent this as a ternary operator? Yep:

var countrycode = 'eu';
var audience = countrycode == 'eu' ? 'audienceEU' : false;
console.log(audience); // audienceEU

Finally lets apply the idea of short circuit evaluation to the nested ternary example:

var countrycode = 'eu';
var audience = (countrycode == 'eu') && ('audienceEU') ||
               (countrycode == 'jp') && ('audienceJP') ||
               (countrycode == 'cn') && ('audienceCN') ||
               ('audienceUS');
console.log(audience); // audienceEU

Nesting Review

I think its useful to review the original nested ternary against the constructs that serve to accomplish the same thing, so here they are:

Nested Ternary Operators

var countrycode = 'eu';
var audience = (countrycode == 'eu') ? 'audienceEU' :
               (countrycode == 'jp') ? 'audienceJP' :
               (countrycode == 'cn') ? 'audienceCN' :
               'audienceUS';
console.log(audience); // audienceEU

Emulating Nested Ternary Operators with a Switch Statement

var countrycode = 'eu';
var audience;
switch(countrycode ) {
     case 'eu': audience = 'audienceEU'; break;
     case 'jp': audience = 'audienceJP'; break;
     case 'cn': audience = 'audienceCN'; break;
     default  : audience = 'audienceUS';
}
console.log(audience); // audienceEU

Emulating Nested Ternary Operators with Short Circuit Evaluation

var countrycode = 'eu';
var audience = (countrycode == 'eu') && ('audienceEU') ||
               (countrycode == 'jp') && ('audienceJP') ||
               (countrycode == 'cn') && ('audienceCN') ||
               ('audienceUS');
console.log(audience); // audienceEU

Emulating Nested Ternary Operators with a Ternary-esque Object Literal Using a Boolean Key

You might ask yourself why I mentioned a “Ternary-esque Object Literal Using a Boolean Key” but didn’t attempt to use that pattern in a “nested” fashion. I didn’t bother because I knew it would be too complex for everyday use. However, if you really want to see what that would look like then here it is, formatted to be as close to the above three examples as possible – I’m not advocating this approach – its just here for illustrative purposes!!!

// Don't do this unless your intent is to confuse people 😉
var countrycode = 'eu';
var audience =  {
   true: 'audienceEU', false:{
      true: 'audienceJP', false:{
         true: 'audienceCN', false:{
            true: 'audienceJP', false:'audienceUS'
            }[countrycode === 'jp']
         }[countrycode === 'cn']
      }[countrycode === 'jp']
   }[countrycode === 'eu'];
console.log(audience); // audienceEU

Emulating Nested Ternary Operators using an Array Literal with a Boolean-Converted Integer Index

The same nesting approach applied to the idea of using the unary operator to convert booleans to integer 1 or 0 to display the corresponding array index – not as confusing as I thought it would be but still not a pattern worth using.

// another confusing pattern....
var countrycode = 'eu'
var audience = [[['audienceUS',
                  'audienceCN'][+(countrycode == 'cn')],
                  'audienceJP'][+(countrycode == 'jp')],
                  'audienceEU'][+(countrycode == 'eu')]
console.log(audience); // audienceEU

// lets try different country codes
var countrycode = 'xyz'; // bad code
var audience = [[['audienceUS',
                  'audienceCN'][+(countrycode == 'cn')],
                  'audienceJP'][+(countrycode == 'jp')],
                  'audienceEU'][+(countrycode == 'eu')]
console.log(audience); // audienceUS << this is the fallback value

// try another countrycode
var countrycode = 'cn'
var audience = [[['audienceUS',
                  'audienceCN'][+(countrycode == 'cn')],
                  'audienceJP'][+(countrycode == 'jp')],
                  'audienceEU'][+(countrycode == 'eu')]
console.log(audience); // audienceCN