Mozilla

Apps Articles

Sort by:

View:

  1. Building applications for Firefox OS using AngularJS

    When you start developing for Firefox OS you might be underwhelmed by the tools that are provided. There is no standard UI toolkit, or a JavaScript framework that all apps build on. This is not a situation that’s inherently bad because in essence Firefox OS is the web; and thus gives you complete freedom in the toolchain you use. This gives us the advantage to use any new technology that pops up also on Firefox OS. The downside is that you’ll miss out on things you might be used to on Android or iOS, like built-in templates; view transitions and UI components.

    In Telenor Digital we decided to build a ready-to-go application framework that deals with these shortcomings, built on top of AngularJS, the MVW framework by Google. The template is the result of iterating over our internal applications that we built for Firefox OS, and addresses the following things:

    1. Built on top of AngularJS, that has provides data binding; templating; routes; and code structure
    2. Built in set of UI components
      and transitions, in the style of Firefox OS
    3. Ability to publish apps as a mobile web page (hosted app),
      or as a packaged app for the Firefox OS marketplace
    4. Offline first approach. Every app built on top of the template works offline,
      also when hosted on your own web server.
    5. A build system to create release builds with one command,
      that does minification and template caching for optimal performance

    Let’s look at how the demo application looks like. It’s a standard CRUD app that shows a list-detail pattern: http://janjongboom.com/ffos-list-detail/. You can click on items to go to the detail view, you can edit items, or add new items. The ‘+’ button is an install button (only visible in Firefox) and allows you to add the app to your phone (Android / FxOS).

    Getting the code

    To start building, do this:

    • git clone git@github.com:comoyo/ffos-list-detail.git
    • npm install
    • ./node_modules/bower/bin/bower install
    • Now you can open www/index.html in any browser, or use the app manager and add the
      www folder as a packaged app.

    Structure

    The application lives in the www/ folder, and is made up of the following subfolders:

    • components/, third party libraries, loaded through bower
    • css/, style sheets. List all styles used by your app in
      css/main.css.
      They will be combined into one big stylesheet, for optimal performance.
    • img/, holds the icons for the app in three formats.
    • js/, our code
      • controllers/, the code that binds data to our UI
      • lib/, external libraries that are not in bower
      • services/, data providers, or code that is not bound to UI
      • app.js, starting point of the application, contains global configuration like routes
      • main.js, bootstrap file based on RequireJS.
        Lists all the JavaScript files we use. When you create a new JS file, add it here.
    • views/, view templates
    • index.html, bootstrap file where we load the application. You probably never will touch this.
    • manifest.appcache, AppCache file.
      You’ll need to list all the images & other resources (other than CSS/JS) that your app needs here,
      to enable offline for hosted applications.
    • manifest.webapp, Firefox OS App manifest file.

    You don’t need any build chain set up during development, you can just edit files in www, and refresh index.html at will. That’s the power of the web :-) Of course if you’re developing in the app manager, press UPDATE to refresh the app.

    Now let’s add some new functionality to this application, so we can see how developing new features works in practice.

    Adding a new button

    Let’s say that we want to add a credits screen that shows who built the application. First thing we need to do is add a button somewhere. In our case let’s put it on the home screen of the app. The code of the view is in www/views/list.html

    The components that you see come from the Firefox OS Building Blocks, which are the same blocks that are used to build Firefox OS itself. Let’s add a new button at the bottom of the screen (below the </ul> and the </section>:

    <a class="recommend" role="button" ng-tap="go('/credits', 'popup')">Credits</a>

    Important here is the ng-tap attribute. When we tap this item we go to /credits URL, with animation popup. There are four built in animations: forward, backward, popup and popdown; but you can create your own using simple CSS.

    Now when we look at this it doesn’t look like a button yet, because we didn’t tell that we needed the button building block. Go to css/main.css and add the following line to make it look nice:

    @import url("../components/building-blocks/style/buttons.css");

    All this is always documented on the page on the Building Blocks website.

    Hooking it up

    When we click on the button nothing happens though (well, we get redirected back to the list view), and that’s because we don’t listen on the /credits URL yet. To fix that we need to create a route handler (like in any MV* server side framework as well). Open the list of routes in js/app.js, and add a handler for the credits URL (before the otherwise handler):

    .when('/credits', {
      templateUrl: 'views/credits.html',
      controller: 'CreditsCtrl'
    })

    Here we tell which controller we want to consult (with JS code), and which view (with HTML) belongs to that. Let’s create the view first. Add a new file called credits.html in the views folder.

    <section role="region">
      <!-- Header building block http://buildingfirefoxos.com/building-blocks/headers.html -->
      <header>
        <!-- here we handle the back click and we do a popdown animation -->
        <a ng-tap="go('/', 'popdown')"><span class="icon icon-back">back</span></a>
        <h1>Credits</h1>
      </header>
    </section>
    <!-- The content of the view should have a 'view' class, and add the name of
         the view to easily style the view later -->
    <section class="view credits">
      This application is made by {{ name }}. <!-- AngularJS does data binding for us -->
    </section>

    To style this view we can add some content in css/app.css, f.e. add some padding and make the text bigger:

    .view.credits {
      padding: 1.5rem;
      font-size: 2rem;
    }

    Now write a simple controller to fill the content of {{ name }}, using standard AngularJS data binding. Add a new file called credits.js in www/js/controllers:

    /* We use RequireJS AMD style modules to get a reference to the app object */
    define(['app'], function(app) {
      /* Tell that we're defining a controller with name
        CreditsCtrl, and with dependencies on $scope, we specify this as string
        to not break when minifying
      */
      app.controller('CreditsCtrl', ['$scope',
        /* Implementation. AngularJS does dependency injection to fill the $scope var */
        function CreditsCtrl($scope) {
          /* Data binding to the view */
          $scope.name = 'Your name';
        }
      ]);
    });

    Last thing is to tell RequireJS that we have a new JS file that needs to be included in our builds, by editing js/main.js and adding a line above 'js/controllers/edit.js':

    'js/controllers/credits.js',

    When we now click the button in the app, everything works as expected. The view pops in, we have data, and we can dismiss by clicking the back button. What’s also great is that when you send the URL to someone else (f.e. http://your/url/index.html#/credits) they will go to the same view by default. That’s because we do proper state management through URLs by default.

    Talking to a third party data source

    The app currently only talks static data, so we want to hook it up to a real data source. In our case the project list should come from GitHub’s page with projects by mozilla-b2g. They have an API at: https://api.github.com/users/mozilla-b2g/repos.

    AngularJS has an idea of services, that abstract data away from your controller. For this app we have a database service that currently returns in-mem data. We can modify the service to talk to a web service instead. Clear out www/js/services/database.js and replace the content with:

    /*global define */
    "use strict";
    define(['app'], function(app) {
      /* Add a new factory called database, with a dependency on http */
      app.factory('database', ['http', function(http) {
        var getItems = function() {
          /* getItems makes a HTTP get call to github */
          return http.get('https://api.github.com/users/mozilla-b2g/repos', {
            // this is the cache configuration, we want to always cache requests
            // because it gives better UX. Plus when there is no internet, we can
            // get the data from cache and not break for the user...
            idbCache: {
              cacheKey: 'api.index',
              // expiration time in ms. from now (this is 5 minutes)
              // This is only obeyed if there is an internet connection!
              expiresInMs: 5 * 60 * 1000
            }
          }).then(function(res) {
            // Format it, sort it and map it to have the same format as our previous in mem dataset
            return res.data.sort(function(a, b) {
              return a.stargazers_count < b.stargazers_count;
            }).map(function(item) {
              return {
                title: item.name,
                description: item.description,
                id: item.name
              };
            });
          });
        };
     
        // Similar story but now for just one item
        var getItemById = function(id) {
          return http.get('https://api.github.com/repos/mozilla-b2g/device-flatfish', {
            idbCache: {
              cacheKey: 'api.detail.' + id,
              expiresInMs: 10 * 60 * 1000
            }
          }).then(function(res) {
            var repo = res.data;
            return {
              title: repo.name,
              description: repo.description,
              id: repo.name,
              date: new Date((repo.pushed_at || "").replace(/-/g,"/").replace(/[TZ]/g," "))
            };
          });
        };
     
        return {
          getItems: getItems,
          getItemById: getItemById
        };
      }]);
    });

    This API is now asynchronous though, but that doesn’t matter for Angular. If you data-bind to a promise, Angular will wait until the promise resolves until data binding happens.

    The beauty here is now that even when there is no Internet connection, the data will still load (as long as it was loaded at least once), and the data is auto-cached. No need for the controller to worry about that.

    Publishing the app

    These were two ways we quickly added some functionality to this application. First, adding a new button and a new view; and second, showing data binding and offline caching of server data. Please note that this application template can be used for much more than just list->detail applications, you’ve got the whole power of AngularJS at your hands!

    Now when we want to share this application with the rest of the world, we can go two ways:

    • Create a hosted application. This is an app that lives on your own server, like any mobile website. Hosted apps can still be published on the marketplace, and will work offline, but cannot use all the APIs in Firefox OS due to security limitations.
    • Create a packaged application. This is a ZIP file, similar to APK files on Android, that contain all the assets of your app, and are distributed through the marketplace.

    Both of these applications can be generated using our build script. The script will create a new folder dist/ that lists all the files the app needs. If you want to publish the app to your own server, just copy over the contents of the folder. If you want to publish the app as a packaged app, ZIP up the content and publish to the marketplace.

    To build, run:

    • Packaged: node build.js
    • Hosted: node build.js appcache

    Happy coding!

  2. Firefox OS Apps run on Android

    At Mozilla we believe that apps and browsing are best viewed as cooperative and symbiotic, each better when working together. We are working to strengthen that relationship by building an apps ecosystem that is built using the Web technologies that so many developers are already familiar with.

    We built Firefox OS as a mobile OS that puts the Web and Open Web Apps at the centre of the mobile experience. The efforts to reduce the performance gaps between the Web and native are paying rich dividends and our work on exposing device capabilities to the Web via WebAPIs, have made web first app development a viable alternative to native platforms.

    Build Open Web Apps, run out-of-the-box on Android

    Now, with Firefox for Android 29, Mozilla is extending this open Open Web Apps ecosystem to Android. Over the past few months, we have been working on providing a “native experience” for Open Web Apps. What this means is that as a user, you can now manage your web app just like you would a native app. You can install/update/uninstall the app and the app will also show up in the App Drawer as well as the Recent Apps list.

    As a developer, you can now build your Open Web App for Firefox OS devices and have that app reach millions of existing Firefox for Android users without having to change a single line of code!

    Check out the video to see an Open Web App in action on an Android device,

    Better yet, if you have installed Firefox for Android try one or build an app and submit it to the Marketplace.

    We also recommend reading Testing Your Native Android App.

  3. Testing Your Native Android App

    It’s an interesting time to be a web developer!

    For years Apps have been eating the web and now we are seeing the Web eat the OS. Mozilla is pushing for a world where you can write standards-based, Open Web Apps. These apps should install as native apps and just work, regardless of the platform.

    Packaged App on Firefox OS

    With the new Firefox for Android, we will now automatically convert your Open Web App into a native Android app.

    Packaged App on Android

    But how can you test you app on Android, before you submit it to the Marketplace?

    We have a new tool to add to your lineup!

    Introducing mozilla-apk-cli

    If you have NodeJS as well as zip/unzip installed, then you can use our new command line tool to build testable .apk installers.

    mozilla-apk-cli is a command-line application, so the commands below would be run from a terminal application.

    Getting setup is easy:

    npm install mozilla-apk-cli

    This will give you a new program mozilla-apk-cli available in ./node_modules/.bin/

    You can also globally install with

    npm install -g mozilla-apk-cli

    I’ll assume you put ./node_modules/.bin in your path or installed globally.

    Open Web Apps come in three flavors and the CLI can build them all:

    • hosted app
    • packaged app zip file
    • packaged app from a directory of source code

    Let’s assume you have a packaged app you are working on.
    You have a directory layout like this:

    www/
       index.html
       manifest.webapp
       css/
           style.css
       i/
         icon-256.png
         icon-128.png
         icon-60.png
       js/
          main.js

    You can build a testable Android app with the following:

    mozilla-apk-cli ./www my_test_app.apk

    This will produce my_test_app.apk which can be side-loaded to your phone in either of the following ways:

    • Put in on the web and download/install form a browser on your Android device
    • Use adb to install the app
    adb install my_test_app.apk

    Setting up adb is out of scope for this blog post, but the Android SDK site has some good resources on adb.

    adb using USB

    Distribution

    Do not distribute this test .apk file!!!

    If you change your app, rebuild and send the APK to your users, the update will fail to install. With each new version of your app, using Android’s app manager, you have to remove the test app before installing the 2nd version.

    mozilla-apk-cli is only for testing and debugging your new Android app locally. When you are happy with your app, you should distribute the Open Web App through the Marketplace or from your website via an install page.

    You don’t need to manage an .apk file directly. Just like you don’t need to manage Mac OS X, Windows or Linux builds for your Open Web App.

    We’ve baked native Android support deeply into the Firefox for Android runtime. When a user chooses to install an Open Web App, the native app is synthesized on demand using the production APK Factory Service. This works regardless of the website or Marketplace you are installing the Open Web App from.

    How does the CLI work?

    Back to our new test tool. This tool is a frontend client to the APK Factory Service. It takes your code and sends it to a reviewer instance of the service. Reviewer as opposed to the production release environment.

    This service synthesizes an native Android app, builds it with the Android SDK and lastly signs it with a development cert. As mentioned, this synthesized APK is debuggable and should not be distributed.

    The nice thing about the service is that you do not have to have Java, ant, the Android SDK and other Android development tools installed on your local computer. You can focus on the web and test on whatever devices you have handy.

    Hosted and Packaged Zip files

    We just looked at how to test a packaged app which is a directory of source code. Now lets look at the other two modes. If you already have built your packaged app into a .zip file, use:

    mozilla-apk-cli ./my_app.zip my_test_app.apk

    If you are building a hosted app, use:

    mozilla-apk-cli http://localhost:8080/ my_test_app.apk

    No Android Devices? No stress

    Perhaps you are saying "Sounds cool, but I don’t have any Android devices… How am I supposed to test?"

    Good point. We’re enabling this automatically.

    On the one hand, don’t worry. One thing mobile first development has taught us, is that there are way more devices and platforms that you will ever have testing resources for. The web is about open standards and progressive enhancement.

    Your web app is just going to be a little bit nicer as a native android app, fitting into the OS as the user expects.

    It doesn’t use native UI widgets or anything like that, so extensive testing is not required. The rendering engine is gecko from the already installed Firefox for Android.

    On the other hand… open standards and compatibility is a nice story, but as web developers, we know things tend to have platform specific bugs. I’d recommend the traditional grading of supported platforms and if Android is a high priority, definitely get a device, Firefox for Android and test your app.

    As we make native experiences automatic across platforms (Android, Mac OS X, etc) we are all ears for feedback. What do you think?

    mozilla-apk-cli Resources

    The source code for the CLI tool is on GitHub. If you need a sample packaged app, here is a demo version. The source code for the APK Factory Service is also on GitHub.

    Join us in with ideas, feedback and questions and please file bugs in Marketplace Integration.

    Thanks to Wil Clouser for the illustrations.

  4. Build Your Next App With a Flame

    Earlier this week, we introduced Flame, the Firefox OS reference device for developers, testers and reviewers from T2Mobile, and announced the opening of the everbuying.com pre-order page. The Flame retails at $170 (USD), global shipping included.

    Wanted: Engaging apps for Firefox OS

    Flame2If you are an experienced HTML5 app developer with a published, well-rated app that you’d like to port to Firefox OS, we’d love to hear from you! It’s always exciting to discover topnotch apps (such as PhoneGap app Find the Movie, pictured to the right running on a Flame) and see them ported from native platforms to Firefox OS. We currently have a small inventory of Flame phones for qualified HTML5 app developers with published, well-rated apps.

    How to qualify

    Through our ongoing Phones for Apps program, there’s an opportunity now for a limited number of invited app developers to receive Flame devices in exchange for a commitment to port their qualifying HTML5 apps within a month of receiving the device. Please apply here.

    There are only three ways to qualify:

    1. You’ve built a successful, well-rated HTML5 app on another platform (such as Amazon Web Apps, Blackberry WebWorks, Chrome Web Store, WebOS, Windows Phone or the PhoneGap store) and are ready to port it now to Firefox OS.
    2. You’ve built a successful, well-rated native app for iOS or Android using a cross-platform wrapper like Cordova or PhoneGap and are ready to port it to Firefox OS. Be sure to indicate the cross-platform tool you used.
    3. You’ve already published a well-rated app in Firefox Marketplace, and you have a second app in progress or already built, and are ready to port it now to Firefox OS.

    Resources

    • Learn more about the Flame (Mozilla Developer Network)
    • Get started with Open Web Apps (Mozilla Developer Network)
    • Mark your calendars for Marketplace Day, June 26 – it’s all about Apps and how you can contribute – as app developers, testers, reviewers and localizers. Hope you can join us!
  5. Introducing TranslationTester and localization support for Open Web Apps

    When building Open Web Apps, one important factor is to make your content available to as many possible, and one way to do that is to make it available in more than one language. Therefore we want to make it as easy as possible for you, both with a complete code repository to get started and updated documentation and possibilities to get translations for your apps.

    We are now also offering a way to have your app set up and to get connected to localizers directly!

    Presenting TranslationTester

    Based on the great work and content by Jason in Localizing Firefox OS Apps and Christie in Localizing the Firefox OS Boilerplate App, I’ve been working on simplifying the set-up for localization.

    Above articles describe many facets and possibilities available, and to complement that, I wanted to be able to offer the most basic code and structure for most use cases: basically, just add translations and you’re good to go!

    This lead to the creation of the TranslationTester code repository, available on GitHub.

    From no translation to localized app in less than 4 minutes!

    Based on the TranslationTester, Will Bamberg has put together a nice and short screencast showing the exact process of going from no translations to having support in just a few minutes!

    In the app-l10n-example repository you have versions of the before and after stages in this screencast, and all of the localization process is described on MDN.

    How to localize an app

    These are the things needed to localize an app. All of them are included in the TranslationTester repository, but included here to show easy it is to get started, or continue to build on the TranslationTester platform for your app.

    Mark up the HTML

    For any element that you want to have its text localized, add a data-l10n-id attribute to the desired element. For example:

    <p data-l10n-id="winter-for-real">Winter for real</p>

    Create translations

    In the locales directory, you have a directory for each language, and can just add new ones for new languages. In each language directoy you create an app.properties file which will contain all your translations for that language (optionally you can also create a manifest.properties file for the name and description of the app, unless you edit it in the main manifest.webapp for your app).

    Include l10n.js

    By including the l10n.js file, the translations for respective language’s app.properties file will be applied to element with the corresponding data-l10n-id attribute.

    Add “name” and “description” translations

    The translations for the name and description for your app could be added to the main manifest.webapp file, or in an optional manifest.properties under each locale’s directory.

    How to view different locales

    To view your app with a different locale, change the language in Firefox/App Manager:

    All platforms
    Set the desired locale to test in JavaScript, e.g:

    document.webL10n.setLanguage("es");
    App Manager/Firefox OS
    Language setting in the Settings app
    Firefox
    Choose language under Preferences > Content > Languages. More information in Set content language in Firefox

    Get help with translations

    We have a Mozilla localization app pilot offered through the Transifex service. As part of that, we’re offering you to add your apps as part of this pilot, to be connected to localizers and quickly offer your app in more languages, to more people.

    Please apply in the Localize My Firefox App form to get started!

  6. Firefox OS App Workshop Prague

    Update:This event will be rescheduled for Autumn 2014. We are designing the workshop with a new regional focus and aim to re-open the invitation request form with a confirmed date and venue before the summer starts. Please stay tuned here on the Hacks blog.

    Back in March, Mozilla tech evangelist Frédéric Harper visited Prague in the Czech Republic and gave a talk at the local Prague JavaScript meetup. His presentation, Empower Mobile Web Developers With JavaScript and WebAPI introduced a roomful of Czech JavaScripters to Firefox OS, Open Web Apps, and our recent integration with Apache Cordova and Adobe PhoneGap. PhoneGap/Cordova developers who’ve built native apps for other platforms and stores can now port PhoneGap-built apps to Firefox OS.

    Just as sure as the coming of summer, Firefox OS is coming to the Czech Republic in 2014, and Fred and friends are heading back to Prague to host a full-day, invitation-only Firefox OS App Workshop on Saturday, June 28. There will be phones! All participants will receive a developer device to test and demo their apps, and to keep for future app development. For free.

    Requirements: Show us your app

    REQUIRED: To qualify for this free hands-on, technical workshop, you must be able to show us a published HTML5 app that you’re porting to Firefox OS or a working Firefox OS app in progress. Show us a link to your existing app or to working code for the app you’re building.

    Apply now for the Prague App Workshop, June 28, 2014.

    FoxSay500


    NOTE: If you do not provide relevant links to working app code we will not be able to consider your application. Firefox Marketplace currently offers plenty of tic-tac-toe games, sliding puzzles, calculators, and to-do list apps. We love to be impressed by new, original, and locally relevant apps, for work and play.

    In the Czech Republic, we need apps that are in Czech. And if you want to extend the reach of your app by translating it to other languages, we have a pilot localization program to help you.

    What to expect

    This workshop is open to individual developers and teams of up to 4 people. The workshop begins with a technical introduction in English in the morning; the rest of the time is for coding and testing your app using the App Manager that’s built in Firefox Developer Tools. Bring laptops and devices.

    At the close of the day, there will be demos of all the apps in progress. After demos, we’ll all go to dinner. Mozilla will provide food and drink throughout the day of the workshop, but travel and lodging arrangements are up to you. And after the workshop, we will stay in touch while you complete your apps and submit them to Firefox Marketplace.

    Resources

    If you don’t have a Firefox OS app in progress, here are some resources to help you get started. There’s never been a better time:

  7. HTML out of the Browser

    Amongst my friends, I’m known as something of a Star Wars nerd. My longtime nick has been cfjedimaster (a combination of two passions, the other being ColdFusion), I work in a room packed to the gills with Star Wars toys, and I’ve actually gotten inked up twice now with Star Wars tats. That being said, it was another movie that had the most influence on my current career – Tron.

    Tron_poster

    I had already discovered an interest in computers before then, but it was Tron that really crystallized the idea for me. All of sudden I imagined myself being the programmer – creating intelligent programs and dominating the grid. Yeah, I know, I was a nerd back then too.

    My dreams, though, ran into reality rather quickly during my time as a Comp Sci major in college. First – I discovered that “Hey, I’m good at math!” means crap all when you hit Calculus 3, and secondly, I discovered that I really wasn’t that interested in the performance of one sort versus another. I switched to English as a major (always a good choice) but kept messing around with computers. It was during this time that I was exposed to Mosaic and the early web.

    I quickly jumped into the web as – well – I’ll put it bluntly – easier programming than what I had been exposed to before. I can remember LiveScript. I can remember my first Perl CGI scripts. This wasn’t exactly light cycle coding but it was simpler, fun, and actually cutting edge. I’ve spent a good chunk of my adult life now as a web developer, and while I certainly have delusions of the web being a pristine environment, it has been good to me (and millions of others) and I’m loving to see how much it evolves over time.

    One of the most fascinating ways that web technologies have grown is outside of the web itself. In this article I’m going to look at all the various ways we can reuse our web-based technologies (HTML, JavaScript, and CSS) in non-web based environments. While it would be ludicrous to say that one shouldn’t learn other technologies, or that web standards work everywhere and in every situation, I feel strongly that the skills behind the web are ones open to a large variety of people in different disciplines – whether or not you got that PhD in computer science!

    Mobile

    This is typically the point where I’d discuss how important mobile is, but it’s 2014 and I think we’re past that now. Mobile development has typically involved either Java (Android) or Objective-C (iOS). Developers can also use web standards to build native applications. One solution is Apache Cordova (AKA PhoneGap).

    Cordova uses a web view wrapped in a native application to allow web developers to build what are typically referred to as hybrid applications. Along with providing an easy way to get your HTML into an app, Cordova provides a series of different plugins that let you do more than what a typical web page can do on a device. So for example, you have easy access to the camera:

    navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
        destinationType: Camera.DestinationType.DATA_URL
    });
     
    function onSuccess(imageData) {
        var image = document.getElementById('myImage');
        image.src = "data:image/jpeg;base64," + imageData;
    }
     
    function onFail(message) {
        alert('Failed because: ' + message);
    }

    You can also work with the accelerometer, GPS, contacts, the file system, and more. Cordova provides a JavaScript API that handles the communication to native code in the back end. Best of all, the same code can be used to build native applications for multiple different platforms (including Firefox OS, now supported in Cordova & PhoneGap).

    To be clear, this isn’t a case of being able to take an existing web site and just package it up. Mobile applications are – by definition – completely different from a simple web site. But the fact that you can use your existing knowledge gives the developer a huge head start.

    Another example of this (and one that is hopefully well known to readers of this site) is Firefox OS. Unlike Cordova, developers don’t have to wrap their HTML inside a web view wrapper. The entire operating system is web standards based. What makes Firefox OS even more intriguing is support for hosted applications. Firefox OS is a new platform, and the chance that your visitors are using a device with it is probably pretty slim. But with a hosted application I can easily provide support for installation on the device while still running my application off a traditional URL.

    Consider a simple demo I built called INeedIt. If you visit this application in Chrome, it just plain works. If you visit it in a mobile browser on Android or iOS – it just works. But visit it with Firefox and code will trigger to ask if you want to install the application. Here is the block that handles this.

    if(!$rootScope.checkedInstall &amp;&amp; ("mozApps" in window.navigator)) {
     
        var appUrl = 'http://'+document.location.host+'/manifest.webapp';
        console.log('havent checked and can check');
        var request = window.navigator.mozApps.checkInstalled(appUrl);
     
        //silently ignore
        request.onerror = function(e) {
            console.log('Error checking install '+request.error.name);
        };
     
        request.onsuccess = function(e) {
            if (request.result) {
                console.log("App is installed!");
            }
            else {
                console.log("App is not installed!");
                if(confirm('Would you like to install this as an app?')) {
                    console.log('ok, lets try to install'); 
                    var installRequest = window.navigator.mozApps.install(appUrl);
     
                    installRequest.onerror = function() {
                        console.log('install failure: '+this.error.name);
                        alert('Sorry, install failed.');    
                    };
     
                    installRequest.onsuccess = function() {
                        console.log('did it');
                        alert('Thanks, app installed!');    
                    };
                }
                $rootScope.checkedInstall=true;
            }
        };
     
    } else {
        console.log('either checked or non compat');                
    }

    Pretty simple, right? What I love about this is that the code is 100% ignored outside of Firefox OS but automatically enhanced for folks using that operating system. I risk nothing – but I get the benefit of providing them a way to download and have my application on their device screen.

    FF OS prompting you to install the app

    Desktop

    Of course, there are still a few people who sit in front of a gray box (or laptop) for their day to day work. Many desktop applications have been replaced by web pages, but there are still things that outside the scope of web apps. There are still times when a desktop app makes sense. And fortunately – there’s multiple ways of building them with web standards as well.

    So you know the code example I just showed you? The one where Firefox OS users would be given a chance to install the application from the web page? That exact same code works on the desktop as well. While still in development (in fact, the application I built doesn’t work due to a bug with Geolocation), it will eventually allow you to push your web based application both to a mobile Firefox OS user as well as the other billion or so desktop users. Here’s the application installed in my own Applications folder.

    INeedIt as a desktop app

    As I said though – this is still relatively new and needs to bake a bit longer before you can make active use of it. Something you can use right now is Node Webkit. This open source project allows you to wrap Node.js applications in a desktop shell. Executables can than be created for Windows, Mac, and Linux. You get all the power of a “real” desktop application with the ease of use of web standards as your platform. There’s already a growing list of real applications out there making use of the framework – some I had even used before what realizing they used Node Webkit behind the scenes.

    As an example, check out A Wizard’s Lizard, a RGP with random dungeons and great gameplay.

    Screen shot - Wizard's Lizard

    Native App Extensions

    In the previous section we covered applications built with web standards. There are also multiple applications out there today, built natively, that can be extended with web standards. As a web developer you are probably already familiar with Firefox Add-Ons and Chrome extensions. There is an incredibly rich ecosystem of browser extensions for just about any need you can think of. What interests me however is the move to use web standards to open other products as well.

    Did you know Photoshop, yes, Photoshop, now has the ability to extended with Node.js? Dubbed “Adobe Generator”, this extensibility layer allows for a script-based interface to the product. One example of this is the ability to generate web assets from layers based on a simple naming scheme. If you’ve ever had to manually create web assets, and update them, from a PSD, you will appreciate this. The entire feature though is driven by JavaScript and all makes use of a public API you can build upon. The code, and samples, are all available via GitHub.

    Generator running within Photoshop

    What Next?

    Coming from the perspective of someone who has been in this industry for way too long, I can say that I feel incredibly lucky that web standards have become such a driving force of innovation and creativity. But it is not luck that has driven this improvement. It is the hard work of many people, companies, and organizations (like Mozilla) that have created the fertile landscape we have before us today. To continue this drive requires all of us to become involved, evangelize to others, and become proponents of a web created by everyone – for everyone.

  8. Powerful tools for developing Web Apps

    In the recent years, web development changed drastically. The emergence of the mobile web and the new form factor of smart phones created the demand for different solutions than the former desktop-only web.

    Since then a lot of frameworks and tools have been created, with new ones being added almost weekly. Now, we web developers are faced with a different problem: for every development concern, there are multiple options to consider, without clear pros or cons. It is easy to feel intimidated not only by the choices available, but also by how similar those choices are.

    Every day, web developers have to successfully overcome this issue and turn this diversity from a daunting proposition into an empowering one.

    But why reinvent the wheel all the time?

    A set of solid recommendations for app developers

    Mozilla is putting together a core set of tools and recommendations that we believe are the most useful for making Web apps.

    The key considerations for what we might recommend are:

    • Sufficiently well-documented and straightforward to use for an average developer (we will concisely document the required knowledge one needs in order to engage with the technology).
    • Loosely coupled and as modular as possible (so you can follow one recommendation but not another if you are so inclined).
    • Tested on Mozilla products (i.e. the UI components will perform well on Firefox OS, etc), but with cross-platform apps in mind

    The upcoming, initial set of recommendations involves a toolchain that’s core to any modern web app, like a JavaScript framework, templating interface, UI framework and task runner. We will employ existing solutions wherever possible and write libraries or utilities to fill in the gaps.

    On an ongoing basis, we’ll expand this systematically across the different parts of the development experience, such as offline handling or the use of various Web APIs.

    All of this will be delivered in one central spot: The App Center on the Mozilla Developer Network (MDN), our established, renowned resource for web app development.

    But I already have it all figured out!

    We encourage you to share your success story with us. Heck, share your failures too. We need all the feedback we can get from everyday web developers. If you have a tool chain of your own, with your favorite JavaScript framework, etc., we’re not interested in converting you to something else. We’re trying to help developers who aren’t sure how to go about making these kinds of decisions.

    Come join us!

    In the Mozilla tradition, this is a community-driven process. This means your input is encouraged and appreciated, and we would like your help to make this a successful initiative!

    The main discussions around this will happen in the following places:

    For the initial tool chain recommendations, I started a thread on the mailing list already, go ahead and weigh in.

    If you have ideas for topics worth exploring in future iterations, don’t be shy and open a new thread to get the discussion started.

    What’s next?

    If this whets your appetite, then great! 2014 is an exciting year to be a web app developer. We’ll keep you updated here on Hacks, as well as the MDN App Center over the coming months.

  9. Rormix – Discover Emerging Music Videos with Firefox OS

    Rormix is a platform for discovering emerging music videos. Music videos are tagged by genre and similar commercial artists, making it easy to discover new music videos.

    The Rormix app was made using PhoneGap and released on iOS and Android. Development took just over a month from the first line of code, to the app submissions in the app stores. The Firefox OS port took one developer just one day!

    Listed below are a few things we learnt along the way:

    What screen sizes am I developing for?

    When you develop an open web app you can install it in the actual desktop browser, the Android Firefox browser or Firefox OS devices.

    If you want to support all of them in one app, responsive designs are a must (you can also select just the platform you want to support). The current crop of Firefox OS phones have a resolution of 320×480. They have a pixel density of 1 so no special graphics need to be produced.

    Back Button?

    iOS devices don’t have a back button, Android devices have a hardware back button, so where does Firefox OS stand? It has a software back button that you can optionally hide or show when building the manifest for the app. The back button can be hidden at the bottom of the screen however it can be hard to press.

    I recommend that you build a back button into your app and hide the default one to make the app easier to navigate.

    //jQuery example
    $('.backbutton').click(function(){
        history.go(-1);
    });

    Stateful design

    As a back button has a presence in Firefox OS you need to build a stateful application in order to go back in state when the user presses the back button.
    A simple way to implement this is using one of the various JS frameworks that use fragment identifiers to load different states (e.g. Sammy JS).

    //jQuery example
     
    //Sammy app
    var app;
     
    $(function(){
     
        app = Sammy(function() {
            this.get('#/', function() {
                //Load default content
            });
            this.get('#/trending', function() {
                //Get trending content
            });
            this.get('#/fresh', function() {
                //Get fresh content
            });
        });
    });
     
    //Load the default content on app load
    app.run('#/');
     
     
    //Go to fresh content
    $('.freshbutton').click(function(){
        app.setLocation('#/fresh');
    });

    Creating a menu

    The trick with making menus for Firefox OS is to use CSS3 transforms for speed, but also making them simple enough to limit the redraw cycle when the menu comes into play. Firefox OS phones have the same width in reference pixels as all iPhones (at the time of writing), and the same pixel height as iPhones previous to the iPhone 5, so if you have a design that works for iOS then you’re all set.

    Adding some Firefox OS flavour

    There are a set of design guidelines that give you an idea of the colour scheme etc of the Firefox OS platform. They also detail how to make the icon for your app, the fonts used etc.

    Submitting your app

    When you have finished building your app you have a choice of how to submit it. You can package it up in a zip file:

    zip -r package.zip *

    You can send this zip to the Marketplace or you can host it yourself.

    The other option is to simply host the code as a web page (rather than zip it), and with a little extra JS prompt the user to download the app to their phone.

    Aside: Using PhoneGap / Cordova and HTML5

    Building web apps allows you to quickly and easily build cross platform apps. Even better, with responsive designs it can all be in one project. Advancing tools and workflows (Sass and Yeoman for example) makes developing apps even easier.

    PhoneGap / Cordova supports Firefox OS from version 3.4 (more information in Building Cordova apps for Firefox OS). The biggest advantage of using PhoneGap is that you only need to support a single codebase for all your apps. We all know some browsers have niggles, and PhoneGap has a built in merge mechanism that allows you to put platform specific code aside from the main code and it will merge them when building the app.

    PhoneGap also has a bunch of libraries for accessing native properties of the phone (native dialogue boxes for example) and this code is the same across all platforms, minimising duplicate code.

    The best thing about PhoneGap is the ability for you to create your own plugins, harnessing the power of mobile devices in a really easy way, effortlessly switching between JS and native mobile code.

    Contact:
    @pixelcodeUK

  10. Building a persistent Notes app for Firefox OS

    In this tutorial we will be building a notes app (like Evernote) from scratch and deploy it to Firefox OS! See a live demo.

    A persistent notes app needs a place to store all the notes for a user (so no one else can read it). For this we will use my own backend solution called Sproute. Sproute is a hosted web framework for quickly building dynamic webapps.

    First create an account with a unique subdomain then access the Dashboard through http://<mysubdomain>.sproute.io/admin. You must login with the same details used to signup to Sprotue.

    Models

    In Sproute there is a concept called Models. A model defines the dynamic data in our app with properties for data integrity. Create a new model called notes with the following fields and properties:

    • body: Text, Required, Min: 1
    • sharing: Text, Allowed Values: public, private, Default Value: private
    The model form filled out for notes

    The model form filled out for notes

    The body field will store the contents of the note. The sharing field will specify whether the note can be viewed by others (with a direct link) or just the owner. This is all the data we need to define, everything else is covered by built-in fields.

    List notes

    We need a way to list the available notes for a user. This can be done with Pages. A page is HTML with embedded template tags for retrieving and processing data.

    Open the index page. This is the home page when people view your space. We will list the notes here. Add the following:

    {{ get /data/notes?sort=_lastUpdated,desc as notes }}

    All data is retrieved through an HTTP interface so the {{ get }} tag must take a URL. The request above is retrieving all notes for the logged in user and stores the results in a variable called notes. We use a query parameter to sort the results by last modified first (An underscore denotes a built-in field).

    Let’s display each note in a list:

    <ul>
        {{ each notes as note }}
            <li><a href="/view/{{note._id}}">
            {{ word note.body 0 5 }}
            </a></li>
        {{ / }}
    </ul>

    The {{ word }} template tag will extract the first 5 words from the body content. We link to a not-yet-made page with the URL /view/<id>. note._id is a built-in unique identifier.

    Add the above code in the 'index' page

    Add the above code in the ‘index’ page

    Create a note

    Before creating the view page for a note, let’s make a new page for creating a note. Create a new page called create. Add the following HTML:

    <form action="/data/notes?goto=/" method="post">
        <div><textarea name="body"></textarea></div>
        <div><select name="sharing">
            <option value="private">Private</option>
            <option value="public">Public</option>
        </select></div>
        <button type="submit">Create Note</button>
    </form>

    Simple! As mentioned above, all data is retrieved and modified through an HTTP interface. This means we can use a simple HTML form to create a new note. The goto query parameter will redirect the user to that URL.

    Because this is a new page we need to create a new route so the page is accessible. A route is a pattern for a requested URL that will render a page if matched. There will already be a route for the index page. Click Routes and create a new one with the following:

    • Route: /create, Page: create.
    New route to 'create' page

    New route to ‘create’ page

    User login and registration

    User accounts are built into Sproute but we still need to create a Register and Login page. Thankfully this is also a simple HTML form so create a new page called users and add the following:

    <h2>Login</h2>
    <form action="/api/login?goto=/" method="post">
        <label>
            <div>Username:</div>
            <input type="text" name="name" />
        </label>
        <label>
            <div>Password:</div>
            <input type="password" name="pass" />
        </label>
        <button type="submit">Login</button>
    </form>

    You may add the Register form on the same page by copying the login form and replace the action attribute to /api/register. Create two new routes with the following:

    • Route: /login, Page: users
    • Route: /register, Page: users

    View and update a note

    Previously we created a link to view a note. This will also be where we let users modify the note. Create a new page called view and add the following:

    {{ get /data/notes/_id/:params.id?single=true admin as note }}
     
    {{ if note.sharing eq private }}
        {{ if note._creator neq :session.user._id }}
            {{ error This note is private }}
        {{ / }}
    {{ / }}
     
    <form action="/data/notes/_id/{{params.id}}?goto=/" method="post">
        <div><textarea name="body">{{note.body}}</textarea></div>
        <div><select name="sharing">
           <option value="private" selected>Private</option>
           <option value="public">Public</option>
        </select></div>
        <button type="submit">Update Note</button>
    </form>

    We make a request to get the note data for the note that was passed into the URL (through the params object). The query parameter single=true will return just the object instead of a one item collection. admin will run the request with the specified user-type. Next we check whether the note is private. If so throw an error if the user is not the creator.

    The update form is very similar to the create form. We only need to change the action to update notes where the _id matches the one in the URL.

    This page requires a slightly complex route. We need to use a placeholder in the route so that /view/anything will still match the view page and store anything in a variable.

    Create a route with the following:

    • Route: /view/:id, Page: view

    Now you can see where params.id comes from. params is an object for all placeholders in the route and the matched values.

    Permissions

    The last important concept of Sproute is permissions. Permissions are just like routes where a requested URL matches a pattern but instead of pointing to a page, it validates against a required user type.

    Click Permissions and add the following:

    • Method: GET, Route: /data/notes, User: Owner
    • Method: GET, Route: /data/notes/*, User: Owner

    This will make sure the only notes listed will be ones the user has created (i.e. the owner). Because of the second permission, we needed to run the {{ get }} request as admin otherwise it would fail for everyone (except for admins and the creator) even if the note is public.

    Adding a permission to retrieving notes

    Adding a permission to retrieving notes

    Firefox OS support

    Sproute can very easily support hosted apps on Firefox OS by creating a page with the manifest JSON data and the route: /manifest.webapp.

    Create a new page called manifest with the following:

    {
        "name": "{{self.name}}",
        "description": "A persistent notes app",
        "launch_path": "/",
        "icons": {
            "128": "/absolute/path/to/icon"
        }
    }

    Create a Route with the pattern /manifest.webapp pointing to the manifest page.

    We’re done! Test this in the app manager by using the link to the manifest (http://notes.sproute.io/manifest.webapp). Sproute is open-source and on GitHub under the Mozilla Public License v2 so you may clone the repo for private hosting.

    Notes app at mobile width

    Notes app at mobile width