Creating Asha Web Apps with Brunch and Jade

Asha web apps?

Asha web apps are a lightweight application development framework for creating apps for low end Nokia devices (Asha series and earlier). While JME is the most popular technology for creating apps for Asha, web apps are a reasonably quick and convenient way to expose content on the web – basically, your garden variety front ends for restful services, spiced by some simple navigation.

Since Asha devices don’t have local javascript execution, javascript is executed on proxy server. “Normal” web pages execute all javascript on the proxy, but Asha web apps provide some “shortcuts” for doing simple DOM manipulation (add/remove css classes, set values in input fields) without the proxy roundtrip. Check out “MWL” library for details.

Standard workflow

Normally, you use Eclipse to develop and test Asha web apps. Nokia provides the “Nokia Web Tools” IDE for this; it’s a rather mainstream Eclipse based IDE, spiced with webkit based “local” simulator (that runs javascript locally), and the “cloud” simulator that runs Javacript on the real Nokia proxy servers (but still renders the DOM on the webkit based simulator).

While this is fine for most web developers, there are lots of us relentlessly looking to optimize our workflows, to make it little more efficient, little more fun (or more tolerable, depending how bad an aversion you have for Javascript and HTML) and little more readable and maintainable.

For this kind of developer, there are tools like CoffeeScript, Brunch, Jade, SASS, LESS, HAML. In this exposition we’ll use CoffeeScript, Brunch and Jade.

CoffeeScript is a language that compiles to idiomatic and readable/debuggable JavaScript. It makes producing JavaScript more tolerable for people used to modern languages without semicolons, `function` keywords
and a selection of other nastiness that plagues JavaScript.

JADE is a language that compiles to HTML.

This Jade:

        doctype 5
	html(lang="en")
	  head
	    title= pageTitle
	  body
	    h1 Jade - node template engine
	    #container
	      if youAreUsingJade
	        p You are amazing
	      else
	        p Get on it!

Compiles to this html:

<h1>Jade - node template engine</h1>
<div id="container">
 
You are amazing
 
</div>

As you can see, this makes it easier to “see forest from the trees”, as the eye is not misdirected by stream of redundant characters and endless <div>’s.

Brunch is an “assembler” for HTML5 applications. It picks up all the pieces you have (CoffeeScript files, JADE templates, etc.) and produces a runnable web application out of that. It can watch the files on the background, compiling CoffeeScript files to JavaScript the second you save them, running unit tests immediately, refreshing the browser in real time etc.

We use Brunch as the “skeleton” of our Asha web application.

Getting started

Prerequisites: This flow has been tested on Linux and Windows. Have to install Node.js, git, the usual stuff every self respecting web developer has set up on day one. Anecdotal evidence suggests it’s a good idea to compile Node.js from source instead of using the packaged versions, if you are lucky enough to be on Linux.

We clone the basic scaffolding from github and install the dependencies:

 

$ git clone git@github.com:vivainio/awa-brunch.git awa-helloworld
$ cd awa-helloworld/
$ npm install
npm http GET https://registry.npmjs.org/javascript-brunch
npm http GET https://registry.npmjs.org/css-brunch
npm http GET https://registry.npmjs.org/uglify-js-brunch
npm http GET https://registry.npmjs.org/clean-css-brunc
.. etc ..
This install Brunch, CoffeeScript compile and lots of other packages with npm.

Let’s take a look at the project structure:


ville@ville-tp:~/p/awa-helloworld$ tree app
app
├── assets
│   ├── config.xml
│   ├── icon.png
│   ├── index.html
│   └── s40-theme
│   ├── css
│   │   ├── s40-theme.css
│   │   ├── single_landscape.css
│   │   └── single_portrait.css
│   ├── images
│   │   ├── arrow-close.png
│   │   ├── arrow-open.png
│   │   ├── back_40x40.png
│   │   ├── button-bg_40x40.png
│   │   ├── close_40x40.png
│   │   ├── grid_40x40.png
│   │   ├── option-menu_titlebar.png
│   │   ├── refresh_40x40.png
│   │   ├── search_40x40.png
│   │   ├── tab_bg.png
│   │   └── title-bar.png
│   └── js
│   ├── s40-theme.js
│   └── screensize.js
├── index.jade
├── README.md
├── templates
│   └── mainlist.jade
├── testCs.coffee
└── testJs.js

 

Now, we start “brunch watch” that compiles the application in real time as we edit the files, and for added convenience launches a webserver serving on :3333:


ville@ville-tp:~/p/awa-helloworld$ brunch watch --server
26 Apr 22:03:48 - info: application started on http://localhost:3333/
26 Apr 22:03:48 - info: compiled in 115ms
26 Apr 22:03:49 - info: compiled in 206ms

 

The resulting application that we can deploy, or preview in browser, gets generated in awa-helloworld/public directory:

 

ville@ville-tp:~/p/awa-helloworld$ tree public
public
├── config.xml
├── icon.png
├── index.html
├── javascripts
│   ├── app.js
│   ├── templates.js
│   └── vendor.js
├── js
│   └── templates.js
└── s40-theme
├── css
│   ├── s40-theme.css
│   ├── single_landscape.css
│   └── single_portrait.css
├── images
│   ├── arrow-close.png
│   ├── arrow-open.png
│   ├── back_40x40.png
│   ├── button-bg_40x40.png
│   ├── close_40x40.png
│   ├── grid_40x40.png
│   ├── option-menu_titlebar.png
│   ├── refresh_40x40.png
│   ├── search_40x40.png
│   ├── tab_bg.png
│   └── title-bar.png
└── js
├── s40-theme.js
└── screensize.js

 

“Sources” under app/ directory were processed to produce these files; .coffee files were compiled and concatenated to “app.js”, index.jade was converted to index.html, and so on.

There is one extra directory we didn’t show yet, the “vendor” directory:


ville@ville-tp:~/p/awa-helloworld$ tree vendor/
vendor/
├── jade_runtime.js
└── README.md

If you are using JavaScript libraries like jQuery, you would just copy it under vendor/ and all of them get automatically concatenated to vendor.js. This makes the app fast to load as it reduces the amount of separate files to download. For production, Brunch can also minify the Javascript files to further reduce page weight. jade_runtime.js is here to support *precompiled Jade templates*

Shut up and show it running

In the interest of making things as “familiar” and frictionless as possible, we will preview the application in standard Chrome browser instead of Nokia Web Tools. So we launch Chromium and disable web security to prevent CORS from cramping our style and killing our Ajax requests:

	$ chromium-browser --disable-web-security http://localhost:3333

This doesn’t look at all what you would expect on the phone screen, because we haven’t specified a viewport size:

Chromium inspector has a handy feature of overriding the viewport size (Settings -> Overrides -> Device Metrics), so we use it to set the resolution to match Asha Full Touch devices (240 x 400):

Now, we have a low-fidelity representation of the phone experience! While this certainly wouldn’t satisfy an UI designer, it’s sufficient for a busy software developer that mostly needs to focus on the “logic” side of the web app.

Launching in NWT

Now is the time to get this running with “real” IDE, i.e. Nokia Web Tools. Launch NWT, do File -> New -> Import web app, select public/config.xml and launch the application in local preview:

Is this it?

There is more to show: how to utilize precompiled templates, how to inject the MWL library, and how Jade can help you create MWL UI “components” with reusable, encapsulated logic. These, and other things to smoothen the development flow will be covered in another blog post, as this already got way too long.

Touchy-Feely with DOM Events: Rethinking Cross-Device User Interaction

There have been numerous ways for users to interact with web pages on mobile phones. Historically, users navigated the mobile web by pressing physical buttons (arrow keys, soft keys, etc.), while some devices required a stylus.

In the last several years, devices with touch-enabled screens have been adopted at such a rapid rate that touch interaction has become ubiquitous. Now we have tablets that take input not only from touch, but from keyboards and mousepads using optional peripherals.

So what does it mean to you as a web developer? It means you need to detect the correct user input method, and design the correct user experience into your web apps.

Continue reading

Make a Map Mashup

To go along with this article on the Nokia Conversations Blog, today, we’re going to look at a simple example of a HERE map mashup. This is aimed at people familiar with at least the basics of HTML and JavaScript.

The map mashup (a.k.a. Location Application/Mapplication/MapHack…) we’re going to build combines the HERE JavaScript API with the Flickr API to display a heatmap of the most popular locations for photographs in an area. You could also use this when planning a trip to a new city to find the ‘must-see’ photo ops. We’ll get into the code in a moment but here’s what we’re going to build:

Flickr Heatmap

Before getting started, you’ll need to register with the Developer Portal and get your own App ID and Authentication Token. It should just take a couple of seconds. Less than a minute, definitely. We’ll wait.

Boilerplate

As with all good projects, it’s useful to have a jumping off point that gets all the boilerplate code out of the way so we can dive straight in as quickly as possible.

This file contains all the things you need to get started using the HERE API

HERE JavaScript API Boilerplate

Download it, open it in your browser and you’ll see the map.

Once we’ve created a map, we try and determine the user’s location. This functionality isn’t supported by older versions of Internet Explorer but recent versions of all the browsers allow the user to decide whether or not to share their location with the web page. If we don’t manage, we’ll just display the map in a default location (the HERE office in Berlin).

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(foundLocation, notFoundLocation);
} else {
    notFoundLocation();
}

If we get the location, set the map center to that

map.setCenter(location.coords);

Give me all you’ve got

Now we have a map and it’s centered on the user, it’s time to ask Flickr for images. You’ll need to sign up with Flickr to get your authentication token with them, too.

We can make a request to Flickr that returns the 500 most recent photos around a certain point. To do this we make an AJAX call to:

http://www.flickr.com/services/api/explore/flickr.photos.search

With our API key and the map centre latitude/longitude. In this request, we also need to specify the parameters &extras=geo to ensure that Flickr will return the location tags for the image.

We’re using jQuery in this demo so the code to make the request to Flickr looks like this:

var apiCall = $.get('http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={YOUR_API_KEY}&min_upload_date=1356886856&lat='+map.center.latitude+'&lon='+map.center.longitude+'&extras=geo&format=json&per_page=500&nojsoncallback=1')
    .done(function(data) {
        // Other stuff
    });

Note: if this doesn’t return anything or you get an error in your JavaScript console about cross-origin problems, you’ll need to view the demo via a local server. To avoid this check out our previous article “Quick Tip: Simple Servers

Heatmaps

When the data comes back from Flickr, we need to format it in a way the Heatmap Overlay can process. There are two types of heatmap visualisation available using the API – ‘density’ and ‘value’. By default, a density heatmap will highlight areas where there are more items closely together while a value heatmap will highlight areas where the values are higher. For example, if there are a lot of cheap houses for sale in the north of a city and one expensive house for sale in the south, a density heatmap would highlight the north while a value heatmap would highlight the south. The difference is between “How much?” (value) and “How many?” (density).

We loop over the photos returned by Flickr:

var heatMapData = [];
if(data.photos && data.photos.photo) {
    for(var i = 0; i < data.photos.photo.length;i++){
        heatMapData.push({
            "latitude": data.photos.photo[i].latitude,
            "longitude": data.photos.photo[i].longitude
        });
    }
}

We’re going to use density here to show where most people take photos so the heatMapData array only contains objects with latitude and longitude.

With the Heatmap Overlay object, we could modify the colours any way we like so that the popular areas show green while the unpopular ones are pale yellow or have them range between neon blue and pink but we’ll stick with the default rainbow colour scheme.

function addHeatMap(heatMapData) {
    // First, delete any previous heatmaps
    map.overlays.clear();
 
    var heatmap;
    // Create the Heatmap
    heatmap = new nokia.maps.heatmap.Overlay({
        // This is the greatest zoom level for which the overlay will provide tiles
        max: 20,
        // This is the overall opacity applied to this overlay
        opacity: 0.8,
        // Defines if our heatmap is value or density based
        type: "density",
        // Coarseness defines the resolution with which the heat map is created.
        coarseness: 2
        });
 
    heatmap.addData(heatMapData);
 
    // Rendering the heat map onto the map
    map.overlays.add(heatmap);
}

Once we’ve added the data to the heatmap, we add the heatmap to the actual map (the map.overlays.add(heatmap) line above). Areas where lots of photos have been taken show in orange and red while areas with fewer photos are pale yellow. We can now see at a glance where the most popular places for photos are.

Check out the finished map

The full source for the FlickrHeat demo is available on GitHub along with our other examples.

Other maps

We can easily do the same mashup using other APIs.

Instagram Heatmap

This is exactly the same as the Flickr example but with the Instagram API instead. This would be handy to highlight areas where people are hanging out.

Neighbourhood Hangouts

Use the Foursquare API and heatmaps to visualize on the map the areas where your neighbors like to hang out and the spots that people like the most in your neighborhood.

SoundScape

Note: this requires a modern browser that supports the Web Audio API

This little application uses the Web Audio API together with the concert information available from the Last FM API to create an immersive, directional soundscape of a city. Fly around and discover the sounds of upcoming gigs. Best with headphones.

This video gives some technical insight into the Soundscape demo

Dynamic backgrounds with background-size: cover

This is a two-part article. The second part will be covered in a future post.

There are some fantastic styles available now in CSS3. Apart from anything else, border-radius and box-shadow alone are the greatest tools to be added to the web developer’s toolbox since float:left. Alongside these highly important and commonly used attributes, there are also some new values for existing rules like background-size:cover.

Continue reading

Measuring the speed of resource loading with JavaScript and HTML5

This is a follow up article to Measuring site performance with JavaScript on mobile, I suggest you read it before you continue. In the previous article I talked about the Navigation Timing spec, here I will talk about the Performance Timeline and Resource Timing specs and how they work in IE10, the first browser to implement them. I created a page that shows some of the data available and a library that generates a HAR that you can later analyse.

Continue reading

Creating A Custom HTML5 Form Validation

In his blog post on HTML5 forms and IE10 Mobile, Andrea explained HTML5 forms and what is new in Internet Exporer 10 Mobile, so you should now have some understanding of HTML5 form validation. To summarize, HTML5 eases the pain of writing extra logic to validate users’ form inputs, letting you create usable forms with a little or no scripting.

In this tutorial, I will show you a practical example of creating a custom validated form  with CSS3, web fonts, and a bit of JavaScript (or not).
Continue reading

Measuring site performance with JavaScript on mobile

There is a lot of talk around responsive Web design being too slow or too resource intensive and that other methodologies can achieve better performance. I don’t want to go into the details of which approach is better because I think different scenarios require different solutions. What is certainly true in all cases is that a Web site or app that loads faster is better than one that is slow. Companies like Google, Gomez and Akamai have all published papers and survey results showing how speed affects user perception of a service from your desktop computer and even more on a mobile device (KISSmetrics has also drawn a nice infographic for the lazy ones). This is the first article and another one will follow shortly. Continue reading

HTML5 forms (and IE10 (Mobile))

One of the many improvements introduced by HTML5 is around forms, users hate filling forms and developers hate validating the data submitted. HTML5 makes these tasks a lot simpler.
In this article I will not talk about what HTML5 added, but I will rather focus on what is new in IE10 mobile, i.e. the browser that comes with Windows Phone 8. At the end of the article I have collected a few useful links that cover HTML5 forms at large and provide more examples and complete support tables. All the code examples are meant to be cross-browser, unless specified. Continue reading

Cross Platform NFC Geo Tags

Nfc Geo Tag on the Nokia N9.Imagine the following: you’re playing a treasure hunt game in your home town. At one station, you touch an NFC tag with your Nokia phone; this opens Nokia Maps to reveal the location of the final place where to collect the treasure. Similar scenarios are possible if you’d like to use Nokia Maps to navigate to the point of interest that you just read about; for example, the St. Stephen’s Cathedral in Vienna, after reading about it in a tourist brochure.

Alternatives

To implement this, you need to store the longitude and latitude of the landmark on the NFC tag (you could also call them "GPS coordinates"). But how to store them? This use case hasn’t been set by the current NDEF URI RTD specification of the NFC Forum, so there isn’t necessarily a solution that works across all NFC enabled phones.

One approach is using the geo: URI scheme (RFC 5870). In the most simple and short form (important due to the limited space on a tag), the URI to write to the tag could look like the following: "geo:60.17,24.829". This encodes the decimal coordinates with latitude of 60.17 and longitude 24.829 in WSG-84 (the location of the Nokia House in Finland, by the way). This works fine with the N9 and directly opens the Nokia Maps client showing the correct location, given that you have PR 1.1+, which is required for default NFC tag handling by the phone. However, Symbian currently can’t understand Geo URIs.

An alternative is to write the URL to Nokia Maps to the tag, according to the Nokia Maps Rendering API. For example: http://m.ovi.me/?c=60.17,24.829. When opening this URL on a Symbian phone, it automatically opens the Nokia Maps client at the correct location. On other devices like the PC, it redirects to the full Nokia Maps web client or the HTML5 version of it. However, MeeGo Harmattan just shows the static map image and doesn’t start the Nokia Maps client.

Cross Platform Geo Tags

So, those two approaches don’t work across the Nokia portfolio. However, there is a simple solution: store the URI of a small script on a server, which then redirects a MeeGo (or Android) phone to the Geo URI, and every other device to the Nokia Maps URI. You can retrieve the operating system by checking the user agent of the browser.

On MeeGo, you can directly send out an HTML header to redirect the browser to the Geo URI (causing it to open Nokia Maps), without loading and rendering the actual web page. On Symbian, a JavaScript redirect can put the browser on the right track and trigger it to open the Nokia Maps client.

Creating Nfc Geo Tags

To make this easier for you, the new Nfc Interactor app (available for Symbian and the Nokia N9) lets you conveniently write geo tags by just entering the coordinates. In the tag compose view, you can also choose which of the three variants you want to write to the Nfc tag. The app will take care of formatting the actual NDEF message for the tag.

For your experiments, the maps redirection PHP script explained above is hosted on http://nfcinteractor.com/m.php and can be used with a URI on the NFC tag like this:

http://nfcinteractor.com/m?c=60.17,24.829

Note that there is no service or uptime guarantee for the hosted script at nfcinteractor.com – it’s intended for testing purposes only and could be removed at any point. You should host the script on your own server for real-world deployment. See the web services information page for more details.

Additionally, hosting the service on your own web server allows you
to add custom-named places to the script, so that the link on the tag
doesn’t need to contain the coordinates, but you can link to a custom
place-name instead. See the source code of the script for details on how
you can add your own places. Example:

http://nfcinteractor.com/m?l=nokia

The source code of the Geo Tags redirection script is now also available under the open source BSD license, so that you can adapt it to your needs, add custom locations (instead of specifying the coordinates as parameters) and upload the script to your own web server.