Mozilla

JavaScript Articles

Sort by:

View:

  1. Browserify and Gulp with React

    The JS world moves quickly, and nowadays, there’re some new kids around the block. Today, we’ll explore Browserify, Gulp, and React and see whether they’d sound suitable for our projects. You might have heard of them but not have had the time to check them out. So we’ll look at the advantages and disadvantages of using Browserify, using Gulp, using React. Because it certainly doesn’t hurt to know our options.

    Browserify: Bundling Node Modules for the Browser

    Browserify is a development tool lets us write Node-style modules in the browser or include actual Node modules from npm. Modules are written in separate files, things can be exported, and modules pull in other modules through require. Browserify can then parse our main JS module, building a dependency tree, to bundle everything together.

    One great thing is that the tens of thousands of modules on NPM are now available for our projects. Dependencies are defined in package.json, and if our project requires them, Browserify will bundle these dependencies with our JS. Take this package.json for example:

    /* package.json */
    {
      "name": "hipApp",
      "description": "Showing off hip stuff",
      "dependencies": {
        "browserify": "~3.44.x",
        "react": "0.11.x",
        "underscore": "*",
      }
    }

    Once we run npm install, we’ll have modules like React and Underscore available to use in our project. Now we just require them in our project:

    /* app.js */
    var React = require('react');
    var myModule = require('./myModule');
    // ...

    Then we invoke Browserify:

    browserify --debug app.js > bundle.js
    

    And Browserify will include React from npm for us. Notice that it will even figure out which local modules to include. We included ./myModule which is another module in the same folder as app.js.

    Let’s compare this style of dependency loading with technologies such as AMD ,which is prominently implemented by RequireJS. They are both JS module definition APIs but with different implementations. Browserify falls in line with CommonJS which is suited for the server, and RequireJS falls in line with AMD which is suited for the browser. However, either can be used in either environment.

    What’s awesome about Browserify is that all NPM modules are available for our project, 86K and counting. Its modules also do not need to be wrapped in a define call.

    Though Browserify requires all the modules up front, which means needing a build step. AMD is asynchronous so modules can be lazily-loaded, and all that is needed is a page refresh. Though we can automate the Browserify build step with Gulp.

    Gulp: The Streaming Build System

    Gulp is a JS build system, like Grunt, that makes use of “streams”, or pipelining, and focuses on code-over-configuration. Build systems are usually set up to watch for changes to projects, and then automatically handling common build steps such as bundling, pre-compilation, or minification. Both Gulp and Grunt have tons of plugins to help with these things. Browserify is one such plugin.

    Let’s take a look at an example Gulpfile. It includes some facilities for React JSX files which we haven’t looked at yet, but it’ll come in handy later. Read the comments in the Gulpfile to follow along:

    /* gulpfile.js */
     
    // Load some modules which are installed through NPM.
    var gulp = require('gulp');
    var browserify = require('browserify');  // Bundles JS.
    var del = require('del');  // Deletes files.
    var reactify = require('reactify');  // Transforms React JSX to JS.
    var source = require('vinyl-source-stream');
    var stylus = require('gulp-stylus');  // To compile Stylus CSS.
     
    // Define some paths.
    var paths = {
      css: ['src/css/**/*.styl'],
      app_js: ['./src/js/app.jsx'],
      js: ['src/js/*.js'],
    };
     
    // An example of a dependency task, it will be run before the css/js tasks.
    // Dependency tasks should call the callback to tell the parent task that
    // they're done.
    gulp.task('clean', function(done) {
      del(['build'], done);
    });
     
    // Our CSS task. It finds all our Stylus files and compiles them.
    gulp.task('css', ['clean'], function() {
      return gulp.src(paths.css)
        .pipe(stylus())
        .pipe(gulp.dest('./src/css'));
    });
     
    // Our JS task. It will Browserify our code and compile React JSX files.
    gulp.task('js', ['clean'], function() {
      // Browserify/bundle the JS.
      browserify(paths.app_js)
        .transform(reactify)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./src/'));
    });
     
    // Rerun tasks whenever a file changes.
    gulp.task('watch', function() {
      gulp.watch(paths.css, ['css']);
      gulp.watch(paths.js, ['js']);
    });
     
    // The default task (called when we run `gulp` from cli)
    gulp.task('default', ['watch', 'css', 'js']);

    Just install the NPM dependencies, run ./node_modules/.bin/gulp, and it handles everything for us in the background. Our files are watched with gulp.watch, tasks are automatically run, and things are cleanly accomplished in streams and pipelines. Whenever we modify any JS/CSS, we can can refresh in the browser just as if we were using AMD.

    Whether to use Grunt or Gulp is a matter of preference. Both have tons of modules available, though Gulp is a bit newer. Grunt is done more through configuration whereas Gulp is done more through code and streams. Though Gulp can be a bit faster as it does not require intermediary files to accomplish its tasks. So with our build system in place, let’s head to the big show: React.

    React: Declarative and Reactive Components

    React is a JS library from Facebook for building reusuable web components. It’s not a full MVC framework like AngularJS; React focuses on view rendering of components making no assumptions about framework, and it can plug in to most projects smoothly.

    Facebook says React was made to build large applications with data that changes over time. Facebook wanted something that didn’t take over the whole application. They could mix in components that could be integrated with legacy components. If you’d like some convincing, Pete Hunt, one of the authors of React, wrote some arguments for React on Quora.

    Rather than imperative one-way data binding as in traditional applications or two-way data binding as in Angular, React implements a one-way reactive data flow. Rather than manually registering listeners and handlers to update the DOM, or having to set up linking functions and data bindings, React’s components are declaratively defined and automatically re-render when its data changes. Like a function, data goes in, components come out.

    For convenience, let’s take a look at an example based off of React’s homepage, which simply displays a name:

    /** @jsx React.DOM */
    var React = require('react');  // Browserify!
     
    var HelloMessage = React.createClass({  // Create a component, HelloMessage.
      render: function() {
        return <div>Hello {this.props.name}</div>;  // Display a property.
      }
    });
    React.renderComponent(  // Render HelloMessage component at #name.
      <HelloMessage name="John" />,
      document.getElementById('name'));

    You may have noticed, there’s some mark-up in our Javascript. React features syntatical sugar called JSX. It needs to be compiled into JS, which’ll automatically be done with our Gulpfile from earlier through the Reactify plugin. Though React also has a JSX compiler if we wanted it. Note that JSX is not required; React has normal JS APIs, but where’s the fun in that?

    Components are created with createClass. Like functions, components can take in arguments during rendering in the form of props. In the above example name="John" is passed into the component and is then referenced by {this.props.name}. Note that components can be made up of only one Node. If we wish to have multiple DOM nodes, they must all be wrapped under a single root node.

    Along with taking input data through props, a component can have an internal and mutable state as accessed through this.state. Here’s another example, this time of a timer, based off of React’s homepage:

    /** @jsx React.DOM */
    var React = require('react');
     
    var Timer = React.createClass({
      getInitialState: function() {  // Like an initial constructor.
        return {
            seconds: 0
        };
      },
      incrementTimer: function() {  // A helper method for our Timer.
        this.setState({  // Use setState to modify state.
            seconds: this.state.seconds + 1  // Never modify state directly!
        });
      },
      componentDidMount: function() {  // A method run on initial rendering.
        setInterval(this.incrementTimer, 1000);
      },
      render: function() {
        return (
          <div>Seconds Elapsed: {this.state.seconds}</div>
        );
      }
    });
     
    React.renderComponent(<Timer />, document.getElementById('timer'));

    We have a setInterval modifying our component’s state which triggers a refresh every 1000ms. Though in more practical applications, the state more likely be modified through user input or through data coming in via XHR rather than through a simple interval.

    And those are some of the basics of React. If reusuable declarative components and reactive rendering hits you as something that would sound perfect in your project, you can head to Getting Started with React. Best of luck to your development. Whether you decide to use these tools or not, it is always advantageous to know your options.

  2. Time to get hacking – Introducing Rec Room

    It’s no secret that the best frameworks and tools are extracted, not created out of thin air. Since launching Firefox OS, Mozilla has been approached by countless app developers and web developers with a simple question: “How do I make apps for Firefox OS?” The answer: “It’s the web; use existing web technologies.” was—and still is—a good answer.

    But if you don’t already have an existing toolchain as a web developer, I’ve been working on extracting something out of the way I’ve been creating web apps at Mozilla that you can use to write your next web app. From project creation to templating to deployment, Mozilla’s Rec Room will help you create awesome web apps in less time with more ease.

    Rec Room is a Node.js utility belt you can wear to build client side web apps. It includes:

    • Brick to add components like appbars and buttons to your UI.
    • Ember for your app’s controllers, models, and views.
    • Handlebars to write your app’s templates.
    • Grunt to run the tasks for your app, including building for production.
    • I18n.js to localize your app.
    • Mocha to test your app.
    • Stylus to write your CSS.
    • Yeoman to scaffold new code for your app’s models and templates.

    In this post I’ll walk through how to create a simple world clock web app with Rec Room, how to deploy it, and how you can try out Rec Room for yourself.

    Where Does Rec Room Come From?

    Much of Rec Room came from a recent rewrite of the HTML5 podcast app. I started working on this app well over a year ago, but its original version wasn’t as easy to work on; it had a lot of global state and a lot of by-hand data-binding. I liked the look of Ember for app development, but back when I started it didn’t quite feel mature enough. These days it’s much better, and I’ve tweaked it in Rec Room to work perfectly without a server.

    I tried to take the best from that system and extract it into a set of tools and documentation that anyone can use.

    Create your own Rec Room app

    Rec Room has just recently been extracted from my experiences with Podcasts; it hasn’t been tested by more than a handful of developers. That said: we’d love your help trying to build your own app for Firefox OS using these tools. They integrate well with tools you probably already know and use–like Node.js and Firefox’s own Web IDE.

    To get started, install Rec Room using Node.js:

    npm install -g recroom

    Clock App

    We’ll create a simple clock app with (minimal) time zone support for our example. The app will let you have a clock and compare it with a few time zones.

    The recroom binary is your entry point to all of the cool things Rec Room can do for you. First, create your app using recroom new world-clock. This creates the basic app structure. To see the basic app skeleton that Rec Room creates we can now enter that directory and run our app: cd world-clock and then type recroom run. The app will open in your default browser.

    First, we’ll add the current time to the main tab. Rec Room supports Ember’s MVC app structure, but also offers simple “pages” for a controller without a 1:1 relationship to a model. We’ll generate a new page that will show our actual clock:

    recroom generate page Clock

    We can edit its template by opening app/templates/clock.hbs. Let’s change clock.hbs to include the variable that will output our local time:

    <h2>Local Time: {{localTime}}</h2>

    That won’t do much yet, so let’s add that variable to our ClockController, in app/scripts/controllers/clock_controller.js:

    WorldClock.ClockController = Ember.ObjectController.extend({
        localTime: new Date().toLocaleTimeString()
    });

    You can see that any property inside the controller is accessible inside that controller’s template. We define the 1ocalTime property and it gets carried into our template context.

    Now our clock app will show the current local time when we navigate to http://localhost:9000/#clock. Of course, it just shows the time it was when the controller was initialized; there is no live updating of the time. We should update the time every second inside the controller:

    WorldClock.ClockController = Ember.ObjectController.extend({
        init: function() {
            // Update the time.
            this.updateTime();
     
        // Run other controller setup.
            this._super();
        },
     
        updateTime: function() {
            var _this = this;
     
            // Update the time every second.
            Ember.run.later(function() {
                _this.set('localTime', new Date().toLocaleTimeString());
                _this.updateTime();
            }, 1000);
        },
     
        localTime: new Date().toLocaleTimeString()
    });

    Now we can go to our clock URL and see our clock automatically updates every second. This is thanks to Ember’s data-binding between controllers and templates; if we change a value in a controller, model, or view that’s wired up to a template, the template will automatically change that data for us.

    Adding Timezones

    Next, we want to add a few timezones that the user can add to their own collection of timezones to compare against local time. This will help them schedule their meetings with friends in San Francisco, Buenos Aires, and London.

    We can create a timezone model (and accompanying controllers/routes/templates) with the same generate command, but this time we’ll generate a model:

    recroom generate model Timezone

    We want each timezone we’re to include in our app to have a name and an offset value, so we should add them as model attributes. We use Ember Data for this, inside app/scripts/models/timezone_model.js:

    WorldClock.Timezone = DS.Model.extend({
        name: DS.attr('string'),
        offset: DS.attr('number')
    });

    Next we’ll want a list of all timezones to offer the user. For this we’ll grab a copy of Moment Timezone. It’s an awesome JavaScript library for dealing with dates and times in JavaScript. We’ll install it with bower:

    bower install moment-timezone --save

    And then add it to our app inside app/index.html:

    <!-- build:js(app) scripts/components.js -->
    <!-- [Other script tags] -->
    <script src="bower_components/moment/moment.js"></script>
    <script src="bower_components/moment-timezone/builds/moment-timezone-with-data-2010-2020.js"></script>
    <!-- endbuild -->

    Adding that tag will automatically add moment-timezone-with-data-2010-2020.js to our built app. We’ll add a tab to the page that lets us edit our timezones, on a different screen than the clocks. To add a tab, we just need to open app/templates/application.hbs and add a tab. While we’re there, we’ll change the main tab from the useless {{#linkTo 'index'}} and point it to {{#linkTo 'clock'}}. The new application.hbs should look like this:

    <x-layout>
      <header>
        <x-appbar>
          <h1>{{t app.title}}</h1>
        </x-appbar>
      </header>
      <section>
        {{outlet}}
      </section>
      <footer>
        <x-tabbar>
          <x-tabbar-tab>
            {{#link-to 'clock'}}Clock{{/link-to}}
          </x-tabbar-tab>
          <x-tabbar-tab>
            {{#link-to 'timezones'}}Timezones{{/link-to}}
          </x-tabbar-tab>
        </x-tabbar>
      </footer>
    </x-layout>

    Side note: notice the root URL points to a useless welcome page? We probably want the default route to be our ClockController, so we can set the index route to redirect to it. Let’s do that now, in app/scripts/routes/application_route.js:

    WorldClock.ApplicationRoute = Ember.Route.extend({
        redirect: function() {
            this.transitionTo('clock');
        }
    });

    Interacting with Timezone models

    We’ll keep things simple for our example and allow users to select a timezone from a <select> tag and add it with a button. It will show up in their list of timezones, and they can delete it if they want from there. The clock tab will show all times. First, we’ll add our timezone data from Moment.js into our TimezonesController in app/scripts/controllers/timezones_controller.js. We’re also going to implement two actions: “add” and “remove”. These will be used in our template:

    WorldClock.TimezonesController = Ember.ObjectController.extend({
        init: function() {
            var timezones = [];
     
            for (var i in moment.tz._zones) {
              timezones.push({
                  name: moment.tz._zones[i].name,
                  offset: moment.tz._zones[i].offset[0]
              });
          }
     
          this.set('timezones', timezones);
     
          this._super();
      },
     
      selectedTimezone: null,
     
      actions: {
          add: function() {
              var timezone = this.store.createRecord('timezone', {
                  name: this.get('selectedTimezone').name,
                  offset: this.get('selectedTimezone').offset
              });
     
              timezone.save();
          },
     
          remove: function(timezone) {
              timezone.destroyRecord();
          }
      }
    });

    So we create a list of all available timezones with offsets. Then we add methods that allow us to add or remove timezones from our offline data store. Next we modify the timezones template in app/templates/timezones.hbs to use the actions and variables we created. All we need to utilize these variables is the Ember SelectView and the {{action}} helper to call our add and remove methods:

    <h2>Add Timezone</h2>
     
    <p>{{view Ember.Select content=timezones selection=selectedTimezone
           optionValuePath='content.offset' optionLabelPath='content.name'}}</p>
     
    <p><button {{action add}}>Add Timezone</button></p>
     
    <h2>My Timezones</h2>
     
    <ul>
      {{#each model}}
        <li>{{name}} <button {{action remove this}}>Delete</button></li>
      {{/each}}
    </ul>

    Now we have a Timezones tab that allows us to add and remove Timezones we want to track. This data persists between app refreshes. The last thing we need to do is show these times relative to our local time in our clock tab. To do this we need to load all the Timezone models in the ClockRoute. They’re automatically loaded in the TimezonesRoute, but it’s easy to add them in the ClockRoute (in app/scripts/routes/clock_route.js):

    WorldClock.ClockRoute = Ember.Route.extend({
        model: function() {
            return this.get('store').find('timezone');
        }
    });

    Because of the way our Ember app is wired up, we load all our models in the route and they are sent to the controller once the data store has asynchonously loaded all of the models. The request to find('timezone') actually returns a Promise object, but Ember’s router handles the Promise resolving for us automatically so we don’t have to manage callbacks or Promises ourselves.

    Now we have access to all the user’s Timezones in the ClockController, so we can make times in each timezone the user has requested and show them in a list. First we’ll add each Timezone’s current time to our ClockController in app/scripts/controllers/clock_controller.js using Moment.js:

    WorldClock.ClockController = Ember.ObjectController.extend({
        updateTime: function() {
            var _this = this;
     
            // Update the time every second.
            Ember.run.later(function() {
                _this.set('localTime', moment().format('h:mm:ss a'));
     
                _this.get('model').forEach(function(model) {
                    model.set('time',
                              moment().tz(model.get('name')).format('h:mm:ss a'));
                });
     
                _this.updateTime();
            }, 1000);
        }.on('init'),
     
        localTime: moment().format('h:mm:ss a')
    });

    Our final app/templates/clock.hbs should look like this:

    <h2>Local Time: {{localTime}}</h2>
     
    <p>
      {{#each model}}
        <h3>{{name}}: {{time}}</h3>
      {{/each}}
    </p>

    And that’s it! Now we have an offline app that shows us time zones in various places, saves the data offline, and updates every second without us having to do much work!

    Command Line Tools

    The old Podcasts app used a (rather awful) Makefile. It wasn’t very useful, and I don’t think it ran on Windows without some serious effort. The new build system uses Node so it runs comfortably on Windows, Mac, and Linux. Commands are proxied via the recroom binary, also written in Node, so you don’t have to worry about the underlying system if you don’t need to modify build steps. recroom new my-app creates a new app; recroom serve serves up your new app, and recroom generate model Podcast creates a new model for you.

    To build your app, you just need to run recroom build and a version with minified CSS, JS, and even HTML will be created for you in the dist/ folder. This version is ready to be packaged into a packaged app or uploaded to a server as a hosted app. You can even run recroom deploy to deploy directory to your git repository’s GitHub pages branch, if applicable.

    See the app in action!

    This entire sample app is available at worldclock.tofumatt.com and the source code is available on GitHub.

    Try Using Rec Room for Your Next Web App

    You can try out Rec Room on Github. Right now some docs and tools are still being abstracted and built, but you can start building apps today using it and filing bugs for missing features. We’d really love it if you could give it a try and let us know what’s missing. Together we can build a cohesive and polished solution to the all-too-common question: “How do I build a web app?”

  3. JavaScript Error- and XHR Log Recording With Every Bug Report

    Let’s start with a story. A user story:

    A friend of mine called me in the middle of the day with a very strange request. He told me

    “Could you come over and help me to fill-in a form”.

    I was surprised as filling forms is the easiest thing to do online, isn’t it? Even for not so-tech-savvy people.

    So I went to my friend’s home and surprise, it wasn’t so easy! It took me 25 min to debug what was wrong with this website (a government one, in Bulgaria). The problem was missing validation (via XMLHttpRequest).

    Of course, I called the agency, expecting everything to go to /dev/null/, but surprisingly they were interested in the problem, so I spent another 25 min explaining the problem and sending them all data they needed. These included:

    1. Screen Size
    2. Browser and OS version
    3. Where exactly the problem occurs
    4. Javascript errors and XHR Logs (pasted in an email)
    5. Plugins installed on my friend’s browser

    etc, etc, etc … you know what I am talking about.

    It was exhausting.

    The perfect bug report

    Let’ step aside from the story and think more like developers. What a developer will need to fix the problem quickly, WITHOUT asking the user difficult questions:

    • Screen size, plugins, installed on your browser, URL where the problem happened, OS and Browser version
    • A visual and annotated screenshot showing where exactly is the problem and how it looks like through the user’s eyes with all steps on how to reproduce the bug.

    Right?

    Wait, something is missing.

    The worst thing about most error reports from users is that they happen on the client-side, in front-end javascript, a cruel, cruel place, far away from the developer trying to fix them.

    Agreed? That’s why a perfect bug report should contain something else – a browsable JavaScript error- and XHR-logs recorder.

    See

    Let’s Talk Code: Recorded JavaScript Errors

    The Usersnap Console Recorder saves every kind of JavaScript error. You can browse through the web developer console in the Usersnap dashboard, as if you would sit right on your user’s browser!

    Every error / log contains a NTP synced timestamp, a full stack including JavaScript source files and line numbers and formatting like the developer console you already know from Firebug

    Every debug log issued by console.log, console.info, console.warn or console.error gets properly formatted (including recursive object/array formatting and browsing).

    Guaranteed no [object Object] hell during debugging!

    Accessing Properties of Undefined/Null Objects

    First example which happens quite often in the wild: a fixed element should be aligned by another element by using the top property during scrolling.

    However, due to a markup rework, the element #inexistent does no longer exist. This leads to offset() returning null and the property top can no longer be accessed:

    function clicky() {
        console.info("Accessing a property of an undefined object");
        console.log("calculating scroll top %d", $('#inexistent').offset().top);
    };

    Calling Methods of Undefined Objects

    Another rework case here: One tries to call a method on an undefined object.

    function clicky2() {
        console.info("Calling a method of an undefined object");
        adjust.ScrollBottom();
    };

    Plain Exceptions

    Sometimes you even know during development that something can break – wouldn’t it be great to know it when it actually breaks?

    function clicky3() {
        console.info("Throwing an exception");
        throw "Version Mismatch!";
    };

    XHR Errors

    Sometimes, XHRs deliver errors (like 404 Not Found or 500 Internal Server Error). Most of the time, such errors lead to bugs which are very hard to reproduce.

    function clicky4() {
        console.info("404 on XHR");
        $.ajax({
            "url": "non_existing.php"
        });
    };

    Cross-Origin XHRs are troublesome. Image someone changes the CORS header and your cross origin XHR does no longer work from one day to another.

    function clicky5() {
        console.info("Cross-Origin on XHR");
        $.ajax({
            "url": "http://facebook.com/cross-origin"
        });
    };

    XHR and Time Tracking

    Recording the Steps During a Checkout

    Conversion rates are key in most businesses. Any obstacle for the user can lower your rates – e.g. it takes too long to load a page or you even have an error during checkout.

    This short example shows a standard click handler which calls getcheckout.php via XHR. Unfortunately, the second XHR (confirm.php) fails and throws a JavaScript exception. That’s nice, but: the user does not get any feedback. The page just stalls.

    function checkout() {
        console.log("check out clicked!");
        $.ajax({
            url: "getcheckout.php",
            dataType: "json"
        }).done(function(data) {
            console.log("Checked out: %o", data);
            confirm();
        });
    };
    function confirm() {
        confirmService.checkConfirm();
        $.ajax({
            url: "confirm.php"
        }).error(function() {
            throw "internal server error on confirm!";
        });
    };

    Additionally, you will get a full synced time frame of your user’s action (regardless if the time on the user’s browser is correct or not!). The full formatting support for objects (console.log(“Checked out: %o”, data);) is super convenient for debugging.

    Conclusion

    Now every developer can have the superpower of understanding what the problem is even on the client-side and stop worrying about “It does not work. Fix it ASAP!” type of communication.

    And now every user will be able to report the issues better, because he/she needs just to press one button to report and issue, using the tools he/she knows well, and the magic will happen in the background.

    Free licenses for FOSS projects

    We at Usersnap support and believe in the FOSS (Free/Libre and Open Source) movement and that’s why Usersnap is free (as in free beer) for any FOSS project to use.

    We utilize a number of open source components like nginx, python, rabbitmq, angular and giving back to the community + improving the quality of your projects is a way to say “Thanks”

    Your project must meet all of the following criteria to be approved:

    • The project is licensed under a license approved by the Open Source Initiative.
    • The project source code is available for download.
    • Your open source project has a publicly accessible website.

    Apply here.

  4. What’s new in Cordova 3.5.0 for Firefox OS

    The Cordova community recently released version 3.5.0 of the tools. This version includes some exciting improvements to the Firefox OS development workflow. Before we dive into the new features, make sure you have the latest version by running:

    $ sudo npm install -g cordova
    $ sudo npm install -g plugman

    Now that we’re all set up, let’s dive into the new features.

    Improved manifest management

    In previous versions of Cordova, developers had to manually edit the manifest.webapp file to add permissions and other app information. This file has crucial information that Firefox OS needs to interact with your app.

    Cordova has a configuration file called config.xml that already contains the same information needed for the manifest file. Cordova will create and update the manifest based on your config.xml file. In the new version, plugins can add configuration specifying which permissions are necessary. Whenever you run a cordova prepare, the manifest is updated based on your configuration. Now you can have all your app’s information in one place.

    Building packages with Cordova

    Firefox OS uses web technologies that do not require a compilation step to generate binaries. The related Cordova commands build and compile were left unimplemented and would throw an exception when called. That behavior was confusing and left some people wondering what went wrong.

    Now cordova build or Cordova compile will create a zip of your packaged app in the build folder inside the platform/firefoxos folder. A big thank you to the contributor Gert-Jan Braas for implementing this!

    Plugins

    A fresh batch of core plugins were released too. We added Firefox OS support to a few more plugins:

    To update to the latest version of the plugins, you need to remove and add them again. For example, to use the latest version of the file plugin run:

    $ cordova plugin rm org.apache.cordova.file
    $ cordova plugin add org.apache.cordova.file

    Replace the plugin name for the plugin you want to update. The geolocation and contacts plugins have been updated to support auto managing permissions, make sure you update them too.

    Check our status page for updated information on plugin status.

    What’s next

    A highly requested feature is support for emulate and run Cordova commands. We are working with the Dev Tools team to create an awesome experience for debugging Cordova applications using Firefox’s App Manager. Here is a sneak preview of what’s coming!

    Meanwhile you can debug your app by adding the platforms/firefoxos/www folder to the app manager in Firefox. For more information, check out Cordova for Firefox OS on MDN.

    We are working on creating default icons for a newly created app. They will serve as placeholders that can be easily replaced with your app’s brand.

    We also have a development status page where you can see up to the minute information on what is being worked on.

    We’d love to hear your feedback and feature requests. You can reach us in the #cordova channel on IRC, or through email at mozilla-cordova@mozilla.org or log your issues and requests on the Apache Cordova issue site. Also if you are interested in helping out with the project let us know.

  5. Stack Overflow Dashboard – check engagement, metrics and more

    Recently I put together a little Mozilla tags on Stack Overflow dashboard to check the engagement and numbers for the tags we sponsor. I liked the idea and wanted to create a general purpose dashboard for Stack Overflow, and share the feature, code and thinking with you.

    Features

    Numbers and developer behavior are always interesting areas, especially to spot trends, common questions, related areas and more. As Stack Overflow is one of the de facto channels where developers ask questions to solve problems I find it very interesting to look at those numbers and see possible correlations.

    You can filter the data based on dates and time periods (different data is available through one or the other option), and the areas the dashboard offers information for are:

    • Questions:
      • # with activity
      • # of unanswered
      • Percentage of unanswered questions (Note that a question must have at least one upvoted answer to be considered answered)
      • List of unanswered questions
      • Frequently asked questions
    • Top answerers
    • Top askers
    • Related tags

    The approach

    My thinking was to use the Stack Exchange API and do simple requests for various tags end the engagement around them. I also wanted to make it easy for the user and autocomplete values for the tag criteria field. Given how many tags there are on Stack Overflow, though, to avoid massive overload I only get the 100 most popular tags and put them in a <datalist> element, connected to the <input> element where the user enters the tag to look for data for. This is being done directly on page load.

    General mindset

    The general mindset when building up the dashboard:

    1. Create a simple HTML form with tag, date period input
    2. Use a simple XMLHttpRequest to get the most popular tags for the <datalist> element
    3. For any request, use the basic XHR to get the data directly in JSON
    4. Depending on the requested data – multiple requests are needed to fill the dashboard – parse the returned JSON and present the results

    API methods being used

    The other API methods that are being called are:

    Request throttling

    Note that the limit for each IP number is 300 requests per 24 hours (unless you have an access_token, then the limit is 10,000).

    Code

    The code is available on GitHub and the idea has been to keep it as simple and free of dependencies as possible. It doesn’t use any JavaScript libraries as I see the use cases here, and where we are right now with HTML5, competent enough not to need that.

    Pre-populating the <datalist> element

    As an example, this is (trimmed-down) version of the code to get the most popular tags as JSON through the Stack Exchange API and polulate the <datalist>:

    function getPopularTags () {
        getItems("popularTags", "http://api.stackexchange.com/2.2/tags?pagesize=100&amp;order=desc&amp;sort=popular&amp;site=stackoverflow");
    }
     
    // Run automatically at page load to pre-populate the &lt;datalist&gt; element
    getPopularTags();
     
    function getItems(type, url) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                var response = xhr.response;
     
                if (response.error_message) {
                    // Show errors
                }
                else {
                    addResults(type);
                }
            }
        };
     
        xhr.open("GET", url, true);
        xhr.responseType = "json";
        xhr.send(null);
    };
     
    function addResults (type) {
        // Popular tags, for filling the &lt;datalist&gt; element
        if (type === "popularTags") {
            var popularTagsList = document.querySelector("#popular-tags"),
                popularTags = questions.popularTags.items,
                popularTagsResults = "";
            for (var i=0,l=popularTags.length, tag; i&lt;l; i++) {
                tag = popularTags[i];
                popularTagsResults += '&lt;option value="' + tag["name"] + '"&gt;';
            }
            popularTagsList.innerHTML = popularTagsResults;
        }
    }

    Give feedback & hack it

    I hope you find this interesting, and a good point to evaluate which areas to focus on and learn more! Also feel more than welcome to use the dashboard, check out the code and issue pull requests, suggest features and more!

  6. Easy audio capture with the MediaRecorder API

    The MediaRecorder API is a simple construct, used inside Navigator.getUserMedia(), which provides an easy way of recording media streams from the user’s input devices and instantly using them in web apps. This article provides a basic guide on how to use MediaRecorder, which is supported in Firefox Desktop/Mobile 25, and Firefox OS 2.0.

    What other options are available?

    Capturing media isn’t quite as simple as you’d think on Firefox OS. Using getUserMedia() alone yields raw PCM data, which is fine for a stream, but then if you want to capture some of the audio or video you start having to perform manual encoding operations on the PCM data, which can get complex very quickly.

    Then you’ve got the Camera API on Firefox OS, which until recently was a certified API, but has been downgraded to privileged recently.

    Web activities are also available to allow you to grab media via other applications (such as Camera).

    the only trouble with these last two options is that they would capture only video with an audio track, and you would still have separate the audio if you just wanted an audio track. MediaRecorder provides an easy way to capture just audio (with video coming later — it is _just_ audio for now.)

    A sample application: Web Dictaphone

    An image of the Web dictaphone sample app - a sine wave sound visualization, then record and stop buttons, then an audio jukebox of recorded tracks that can be played back.

    To demonstrate basic usage of the MediaRecorder API, we have built a web-based dictaphone. It allows you to record snippets of audio and then play them back. It even gives you a visualization of your device’s sound input, using the Web Audio API. We’ll concentrate on the recording and playback functionality for this article.

    You can see this demo running live, or grab the source code on Github (direct zip file download.)

    CSS goodies

    The HTML is pretty simple in this app, so we won’t go through it here; there are a couple of slightly more interesting bits of CSS worth mentioning, however, so we’ll discuss them below. If you are not interested in CSS and want to get straight to the JavaScript, skip to the “Basic app setup” section.

    Keeping the interface constrained to the viewport, regardless of device height, with calc()

    The calc function is one of those useful little utility features that’s cropped up in CSS that doesn’t look like much initially, but soon starts to make you think “Wow, why didn’t we have this before? Why was CSS2 layout so awkward?” It allows you do a calculation to determine the computed value of a CSS unit, mixing different units in the process.

    For example, in Web Dictaphone we have theee main UI areas, stacked vertically. We wanted to give the first two (the header and the controls) fixed heights:

    header {
      height: 70px;
    }
     
    .main-controls {
      padding-bottom: 0.7rem;
      height: 170px;
    }

    However, we wanted to make the third area (which contains the recorded samples you can play back) take up whatever space is left, regardless of the device height. Flexbox could be the answer here, but it’s a bit overkill for such a simple layout. Instead, the problem was solved by making the third container’s height equal to 100% of the parent height, minus the heights and padding of the other two:

    .sound-clips {
      box-shadow: inset 0 3px 4px rgba(0,0,0,0.7);
      background-color: rgba(0,0,0,0.1);
      height: calc(100% - 240px - 0.7rem);
      overflow: scroll;
    }

    Note: calc() has good support across modern browsers too, even going back to Internet Explorer 9.

    Checkbox hack for showing/hiding

    This is fairly well documented already, but we thought we’d give a mention to the checkbox hack, which abuses the fact that you can click on the <label> of a checkbox to toggle it checked/unchecked. In Web Dictaphone this powers the Information screen, which is shown/hidden by clicking the question mark icon in the top right hand corner. First of all, we style the <label> how we want it, making sure that it has enough z-index to always sit above the other elements and therefore be focusable/clickable:

    label {
        font-family: 'NotoColorEmoji';
        font-size: 3rem;
        position: absolute;
        top: 2px;
        right: 3px;
        z-index: 5;
        cursor: pointer;
    }

    Then we hide the actual checkbox, because we don’t want it cluttering up our UI:

    input[type=checkbox] {
       position: absolute;
       top: -100px;
    }

    Next, we style the Information screen (wrapped in an <aside> element) how we want it, give it fixed position so that it doesn’t appear in the layout flow and affect the main UI, transform it to the position we want it to sit in by default, and give it a transition for smooth showing/hiding:

    aside {
       position: fixed;
       top: 0;
       left: 0;
       text-shadow: 1px 1px 1px black;  
       width: 100%;
       height: 100%;
       transform: translateX(100%);
       transition: 0.6s all;
       background-color: #999;
        background-image: linear-gradient(to top right, rgba(0,0,0,0), rgba(0,0,0,0.5));
    }

    Last, we write a rule to say that when the checkbox is checked (when we click/focus the label), the adjacent <aside> element will have it’s horizontal translation value changed and transition smoothly into view:

    input[type=checkbox]:checked ~ aside {
      transform: translateX(0);
    }

    Basic app setup

    To grab the media stream we want to capture, we use getUserMedia() (gUM for short). We then use the MediaRecorder API to record the stream, and output each recorded snippet into the source of a generated <audio> element so it can be played back.

    First, we’ll add in a forking mechanism to make gUM work, regardless of browser prefixes, and so that getting the app working on other browsers once they start supporting MediaRecorder will be easier in the future.

    navigator.getUserMedia = ( navigator.getUserMedia ||
                           navigator.webkitGetUserMedia ||
                           navigator.mozGetUserMedia ||
                           navigator.msGetUserMedia);

    Then we’ll declare some variables for the record and stop buttons, and the <article> that will contain the generated audio players:

    var record = document.querySelector('.record');
    var stop = document.querySelector('.stop');
    var soundClips = document.querySelector('.sound-clips');

    Finally for this section, we set up the basic gUM structure:

    if (navigator.getUserMedia) {
       console.log('getUserMedia supported.');
       navigator.getUserMedia (
          // constraints - only audio needed for this app
          {
             audio: true
          },
     
          // Success callback
          function(stream) {
     
     
          },
     
          // Error callback
          function(err) {
             console.log('The following gUM error occured: ' + err);
          }
       );
    } else {
       console.log('getUserMedia not supported on your browser!');
    }

    The whole thing is wrapped in a test that checks whether gUM is supported before running anything else. Next, we call getUserMedia() and inside it define:

    • The constraints: Only audio is to be captured; MediaRecorder only supports audio currently anyway.
    • The success callback: This code is run once the gUM call has been completed successfully.
    • The error/failure callback: The code is run if the gUM call fails for whatever reason.

    Note: All of the code below is placed inside the gUM success callback.

    Capturing the media stream

    Once gUM has grabbed a media stream successfully, you create a new Media Recorder instance with the MediaRecorder() constructor and pass it the stream directly. This is your entry point into using the MediaRecorder API — the stream is now ready to be captured straight into a Blob, in the default encoding format of your browser.

    var mediaRecorder = new MediaRecorder(stream);

    There are a series of methods available in the MediaRecorder interface that allow you to control recording of the media stream; in Web Dictaphone we just make use of two. First of all, MediaRecorder.start() is used to start recording the stream into a Blob once the record button is pressed:

    record.onclick = function() {
      mediaRecorder.start();
      console.log(mediaRecorder.state);
      console.log("recorder started");
      record.style.background = "red";
      record.style.color = "black";
    }

    When the MediaRecorder is recording, the MediaRecorder.state property will return a value of “recording”.

    Second, we use the MediaRecorder.stop() method to stop the recording when the stop button is pressed, and finalize the Blob ready for use somewhere else in our application.

    stop.onclick = function() {
      mediaRecorder.stop();
      console.log(mediaRecorder.state);
      console.log("recorder stopped");
      record.style.background = "";
      record.style.color = "";
    }

    When recording has been stopped, the state property returns a value of “inactive”.

    Note that there are other ways that a Blob can be finalized and ready for use:

    • If the media stream runs out (e.g. if you were grabbing a song track and the track ended), the Blob is finalized.
    • If the MediaRecorder.requestData() method is invoked, the Blob is finalized, but recording then continues in a new Blob.
    • If you include a timeslice property when invoking the start() method — for example start(10000) — then a new Blob will be finalized (and a new recording started) each time that number of milliseconds has passed.

    Grabbing and using the blob

    When the blob is finalized and ready for use as described above, a dataavailable event is fired, which can be handled using a mediaRecorder.ondataavailable handler:

    mediaRecorder.ondataavailable = function(e) {
      console.log("data available");
     
      var clipName = prompt('Enter a name for your sound clip');
     
      var clipContainer = document.createElement('article');
      var clipLabel = document.createElement('p');
      var audio = document.createElement('audio');
      var deleteButton = document.createElement('button');
     
      clipContainer.classList.add('clip');
      audio.setAttribute('controls', '');
      deleteButton.innerHTML = "Delete";
      clipLabel.innerHTML = clipName;
     
      clipContainer.appendChild(audio);
      clipContainer.appendChild(clipLabel);
      clipContainer.appendChild(deleteButton);
      soundClips.appendChild(clipContainer);
     
      var audioURL = window.URL.createObjectURL(e.data);
      audio.src = audioURL;
     
      deleteButton.onclick = function(e) {
        evtTgt = e.target;
        evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
      }
    }

    Let’s go through the above code and look at what’s happening.

    First, we display a prompt asking the user to name their clip.

    Next, we create an HTML structure like the following, inserting it into our clip container, which is a <section> element.

    <article class="clip">
      <audio controls></audio>
      <p><em>your clip name</em></p>
      <button>Delete</button>
    </article>

    After that, we create an object URL pointing to the event’s data attribute, using window.URL.createObjectURL(e.data): this attribute contains the Blob of the recorded audio. We then set the value of the <audio> element’s src attribute to the object URL, so that when the play button is pressed on the audio player, it will play the Blob.

    Finally, we set an onclick handler on the delete button to be a function that deletes the whole clip HTML structure.

    Conclusion

    And there you have it; MediaRecorder should serve to make your app media recording needs easier. Have a play around with it and let us know what you think: we are looking forward to seeing what you’ll build!

  7. PlayCanvas Goes Open Source

    This is a guest post by Will Eastcott of the PlayCanvas engine. As outlined in What Mozilla Hacks is, we constantly cover interesting information about open source and the Open Web, both from external as well as Mozilla authors, so feel free to share with us!

    On March 22nd 2011, Mozilla released Firefox 4.0 which enabled WebGL by default. A month later, we formed PlayCanvas and started building a game engine unlike anything that had gone before. Fast forward three years, and WebGL is everywhere. Only this week, Apple announced support for WebGL in both OS X and iOS 8. So what better time pass on some more exciting news for you:

    The PlayCanvas Engine has been open sourced!

    MozBlog500

    Introducing the PlayCanvas Engine

    The PlayCanvas Engine is a JavaScript library engineered specifically for building video games. It implements all of the major components that you need to write high quality games:

    • Graphics: model loading, per-pixel lighting, shadow mapping, post effects
    • Physics: rigid body simulation, ray casting, joints, trigger volumes, vehicles
    • Animation: keyframing, skeletal blending, skinning
    • Audio engine: 2D and 3D audio sources
    • Input devices: mouse, keyboard, touch and gamepad support
    • Entity-component system: high level game object management

    We had a couple of goals in mind when we originally designed the engine.

    1. It had to be easy to work with.
    2. It had to be blazingly fast.

    Simple Yet Powerful

    As a developer, you want well documented and well architected APIs. But you also want to be able to understand what’s going on under the hood and to debug when things go wrong. For this, there’s no substitute for a carefully hand-crafted, unminified, open source codebase.

    Additionally, you need great graphics, physics and audio engines. But the PlayCanvas Engine takes things a step further. It exposes a game framework that implements an entity-component system, allowing you to build the objects in your games as if they were made of Lego-like blocks of functionality. So what does this look like? Let’s check out a simple example on CodePen: a cannonball smashing a wall:

    playcanvas_codepen

    As you can see from the Pen’s JS panel, in just over 100 lines of code, you can create, light, simulate and view interesting 3D scenes. Try forking the CodePen and change some values for yourself.

    Need For Speed

    To ensure we get great performance, we’ve built PlayCanvas as a hybrid of hand-written JavaScript and machine generated asm.js. The most performance critical portion of the codebase is the physics engine. This is implemented as a thin, hand-written layer that wraps Ammo.js, the Emscripten-generated JavaScript port of the open source physics engine Bullet. If you haven’t heard of Bullet before, it powers amazing AAA games like Red Dead Redemption and GTAV. So thanks to Mozilla’s pioneering work on Emscripten and asm.js, all of this power is also exposed via the PlayCanvas engine. Ammo.js executes at approximately 1.5x native code speed in recent builds of Firefox so if you think that complex physics simulation is just not practical with JavaScript, think again.

    But what about the non-asm.js parts of the codebase? Performance is clearly still super-important, especially for the graphics engine. The renderer is highly optimized to sort draw calls by material and eliminate redundant WebGL calls. It has also been carefully written to avoid making dynamic allocations to head off potential stalls due to garbage collection. So the code performs brilliantly but is also lightweight and human readable.

    Powering Awesome Projects

    The PlayCanvas Engine is already powering some great projects. By far and away, the biggest is the PlayCanvas web site: the world’s first cloud-hosted game development platform.

    For years, we’ve been frustrated with the limitations of current generation game engines. So shortly after starting work on the PlayCanvas Engine, we began designing a new breed of game development environment that would be:

    Accessible
    using any device with a web browser, plug in a URL and instantly access simple, intuitive yet powerful tools.
    Collaborative
    See what you teammates are working on in real-time or just sit back and watch a game as it’s built live before your eyes.
    Social
    Making games is easier with the help of others. Be part of an online community of developers like you.

    PlayCanvas ticks all of these boxes beautifully. But don’t take our word for it – head to https://playcanvas.com and discover a better way to make games.

    In fact, here’s a game we have built using these very tools. It’s called SWOOOP:

    PLAY NOW!

    It’s a great demonstration of what you can achieve with HTML5 and WebGL today. The game runs great in both mobile and desktop browsers, and you are free to deploy your PlayCanvas games to app stores as well. For Google Play and the iOS App Store, there are wrapping technologies available that can generate a native app of your game. Examples of these are Ludei’s CocoonJS and the open source Ejecta project. For Firefox OS, the process is a breeze since the OS treats HTML5 apps as first class citizens. PlayCanvas games will run out of the box.

    Want!

    So if you think this is sounding tasty, where should you go to get started? The entire engine sourcebase is now live on GitHub:

    https://github.com/playcanvas/engine

    Get cloning, starring and forking while it’s fresh!

    Stay in the Loop

    Lastly, I want to give you some useful links that should help you stay informed and find help whenever you need it.

    We’re super excited to see what the open source community will do with the PlayCanvas Engine. So get creative and be sure to let us know about your projects.

    Toodle pip!

  8. App Framework and Firefox OS

    Intel’s App Framework is an open source, MIT licensed, cross platform HTML5 framework for building mobile applications. It is hosted on GitHub where you can contribute to the project, especially the Firefox OS theme.

    App Framework is comprised of three main areas.

    1. Query selector library
    2. UI/UX library
    3. Plugins

    The query selector library implements a subset of jQuery* API’s, with additional API’s targeted for mobile development. The UI/UX library offers top notch performance on a broad range of devices, including responsive design for phones and tablets. Plugins, the heart of App Framework UI, allow developers to write and share code for App Framework applications.

    Firefox OS support

    With the 2.1 launch of App Framework, Firefox OS is now officially supported. This was easy to accomplish, due to Firefox supporting vendor neutral prefixes on many CSS features, like CSS transforms. We will be adding an official Firefox OS theme soon.

    Getting the code

    To see everything that is offered in the framework, take a look at the App Framework website. You can find the quickstart guide, API documentation, and the UI component preview. You can clone the source code at GitHub

    Download the zip from GitHub and extract the zip file. View the index.html file to see a sample of the kitchen sink and example API’s. You can test drive App Framework UI and see a demonstration of the provided plugins.

    Building your first app

    Here we will build a sample Hello World app with App Framework UI. Create a new folder and copy over the following files from the kitchen sink into your project

    1. build/ui/appframework.ui.min.js
    2. build/css/af.ui.base.css
    3. build/css/icons.css

    Next create an index.html file, manifest.webapp, and app.js. You can find documentation for the manifest.webapp on MDN. See below for the folder structure for this project.

    __folder__
        index.html
        manifest.webapp
        js
            appframework.ui.min.js
            app.js
        css
            af.ui.base.css
            icons.min.css

    Open up your index.html file in your favorite editor and copy in the following code for the basic ‘Hello World’ app

    <!DOCTYPE html>
    <!--HTML5 doctype-->
    <html>
     
        <head>
            <title>FF OS sample</title>
            <meta http-equiv="Content-type" content="text/html; charset=utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
            <link rel="stylesheet" type="text/css" href="css/icons.css" />
            <link rel="stylesheet" type="text/css" href="css/af.ui.base.css" />
            <script type="text/javascript" charset="utf-8" src="ui/appframework.ui.min.js"></script>
            </head>
     
        <body>
            <div id="afui">
                <!-- this is the main container div.  This way, you can have only part of your app use UI -->
                <!-- this is the header div at the top -->
                <div id="header">
                </div>
                <!-- content is where your panels live/scrollable area -->
                <div id="content">
                    <!-- here is where you can add your panels -->
                    <div data-title='Firefox OS' id="main" class="panel" selected="true">
                        Hello World
                    </div>
                </div>
                <!-- bottom navbar. Add additional tabs here -->
                <div id="navbar">
                    <a href="#main" id='navbar_home' class='icon home'>home</a>
                </div>
            </div>
        </body>
     
    </html>

    Test

    Now you can test your sample app on the Firefox OS simulator or a device. You should see the header with the title “Firefox OS”, “Hello World” in the content area, and a footer with a single icon at the bottom. Since we did not add any additional panels, there isn’t much you can do. Let’s update our code and add more. Open up index.html in your editor and change it to the following.

    <!DOCTYPE html>
    <!--HTML5 doctype-->
    <html>
     
        <head>
            <title>FF OS sample</title>
            <meta http-equiv="Content-type" content="text/html; charset=utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
            <link rel="stylesheet" type="text/css" href="css/icons.css" />
            <link rel="stylesheet" type="text/css" href="css/af.ui.base.css" />
            <script type="text/javascript" charset="utf-8" src="ui/appframework.ui.min.js"></script>
            </head>
     
        <body>
            <div id="afui">
                <div id="header">
                </div>
                <div id="content">
                    <div data-title='Firefox OS' id="main" class="panel" selected="true">
                        Hello World
                    </div>
                    <div data-title='Page 2' id="page2" class="panel">
                        <ul class='list'>
                            <li>
                                <a href='#page2'>Item 1</a>
                            </li>
                            <li>
                                <a href='#page2'>Item 2</a>
                            </li>
                            <li>
                                <a href='#page2'>Item 3</a>
                            </li>
                            <li>
                                <a href='#page2'>Item 4</a>
                            </li>
                            <li class='divider'>
                                Divider
                            </li>
                            <li>
                                <a href='#page2'>Item 5</a>
                            </li>
                            <li>
                                <a href='#page2'>Item 6</a>
                            </li>
                            <li>
                                <a href='#page2'>Item 7</a>
                            </li>                                       
                        </ul>
                    </div>
     
                </div>
                <!-- bottom navbar. Add additional tabs here -->
                <div id="navbar">
                    <a href="#main" id='navbar_home' class='icon home'>home</a>
                    <a href="#page2" id='navbar_home' class='icon gear'>home</a>
                </div>
            </div>
        </body>
     
    </html>

    View the new code

    Run your updated code again in the simulator or device. You will see two items in the bottom tab bar, and a link to “Page 2″. Navigate to Page 2 and you will see the slide up transition, along with a stylized list. You can scroll the list using the built in JavaScript scroller. Hit the back button at the top to go back in the history stack.

    What’s next?

    Get a starter template and start building your application! Check out the App Framework website for more documentation and tips.

    We are working on a Firefox OS theme and you can check our work out. We love feedback and are happy to fix any bugs found. Just head on over to GitHub and report the issues. If you want to extend your app more, build plugins and share them with other developers

    Screenshots

    Below are some screen shots from the Intel® XDK App Preview application, powered by App Framework. This is a cross platform application that runs on phones and tablets.

    login

    list

    demo

    *Other names and brands may be claimed as the property of others.

  9. Treat Open Source Like a Startup

    What am I getting myself into?

    I was never an open source contributor. I had never even filed a GitHub issue. I considered myself an entrepreneur who simply happened to be technical.

    But when the startup I wanted to build needed something that didn’t exist, I followed an unprecedented whim and paused everything I was working on. I pulled a hard left, and I wound up spending three months working full-time on a project that I needed ASAP. Equally as motivating, I knew that other developers needed it too.

    So, I switched hats. I became an insanely focused, sleeping-isn’t-allowed developer.

    The outcome was an animation engine that drastically improved UI performance and workflow across all devices. See it at VelocityJS.org. It’s a powerful JavaScript tool that rivals the performance of CSS transitions. The trick? Simple: In contrast to jQuery (which was initially released in 2006), I was building an engine that incorporated 2014’s performance best practices from the ground-up. No legacy layers; no bloat. Not a Swiss Army knife; a scalpel.

    But, throughout my solitary confinement, I was genuinely concerned that I was building something for a customer base of one — myself.

    I eventually came to realize that switching hats was actually the wrong approach. I was never supposed to take my startup hat off. (Since normal people don’t wear two hats at once, this is where my metaphor breaks down.)

    This is the story of that realization.

    Success

    Let’s momentarily jump ahead three months — to the time of Velocity’s release. Pardon me for a moment while I gloat:

    • Within three days, Velocity reached the top of Hacker News and programming subreddits a total of four times.
    • Within nine days, Velocity amassed 2400 GitHub stars.
    • Within two weeks, Velocity topped the CodePen charts with multiple demos reaching 10,000 views each (codepen.io/rachsmith/pen/Fxuiacodepen.io/okor/pen/fJIEF, and codepen.io/sol0mka/full/kzyjJ).
    • Countless business, front-end platforms, and web agencies migrated to Velocity (examples: everlane.com, discover.typography.com, apartmentlist.com).

    How was this possible? Because I treated Velocity like I treated my businesses: First, there’s development. That’s 10%. Then, there’s marketing. That’s 90%.

    The perspective shift I underwent midway through development was to commit to the following mantra: However much time I wound up spending on development, I would spend even more time on marketing.

    After all, that was the time-split I experienced with my startups. I didn’t see a single reason why it should be different for this project. User acquisition is user acquisition.

    Ultimately, if you develop a startup or an open source project intended for public use, and nobody uses it… you failed. It doesn’t matter how clever it was. It doesn’t matter what technical challenges you overcame.

    Unfortunately, however, the peculiar reality of OSS growth hacking is that there’s a stigma attached to it: The act of marketing invokes pitching, rubbing shoulders, begging, and bribing. It’s stereotypically personified as an overeager, two-bit hustler wearing a cheap shirt and an even cheaper tie. This clashes with our ideals of open source — which itself is stereotypically personified as a headstrong and idealistic code warrior wearing a cheap shirt and an even cheaper haircut.

    I’ll quote GitHub’s Zach Holman to get to the root of the dichotomy, “We like to think that open source is pure; that it’s unadulterated. That marketing an open source project is silly. That’s just silly.” - ZachHolman.com

    To put it bluntly, if you want your open source project to have an impact, you need to step out of your coder bubble. After all, if you build something amazing — and you market it effectively — you’re doing everyone a favor. Not just yourself.

    The best part is, the more people that know about your work, the more people there are to contribute: Bugs get discovered sooner. Useful features get pitched more often.

    And don’t worry — being seen publicly marketing your project doesn’t frame you as an egotistical developer. It frames you as someone who’s passionate. If you take the time to appreciate the fact that more people benefiting from your hard work is a major motivation in your pursuit of open source, then you’ll realize that hustling on behalf of your project fits exactly within your pre-existing ideals.

    Open source growth hacking

    If you look closely at the current open source landscape, those who most often reach the top of GitHub’s charts are developer figureheads with pre-existing followings, and major companies sharing components of their internal stack.

    Looking at this month’s GitHub’s trending chart, the top ranking projects that aren’t educational resources (link collections, tutorials, etc.) include: Pop (Facebook), Atom (GitHub), Quill (Salesforce), Velocity (Me!), Mail-in-a-Box (individual), Famous (Famous), syncthing (individual), betty (individual), Isomer (individual), Bootstrap (Twitter), Angular (Google), PourOver (NY Times).

    There’s a fair representation of individuals in there, but it’s typically corporations that dominate open source marketing. The reality, however, is that these corporations employ developers that are no better than you or I. There’s no inherent natural selection driving the popularity of their projects versus yours

    Fight to get your project out there. Or sit back and watch the marketing teams of huge companies drown your voice out.

    Velocity.js CodePen Demo

    That’s enough with waxing poetic and analyzing the current landscape. Let’s dive into the meaty details: How exactly did I market Velocity?

    • I pre-wrote advanced drafts for major web development blogs to consider publishing. By presenting the editors with the full goods upfront — not a pitch, not an outline — I minimized their workload, making it very easy for them to say “yes.” I also made sure to wait until I had enough GitHub stars (from Hacker News coverage, etc.) before pitching. And, most importantly, I had a strong thematic focus for each article: One article was exclusively about performance, and the other was exclusively about UI workflow. In both cases, I minimized the amount of attention spent pitching Velocity, and focused instead on educating readers about the respective topic. Blogs don’t want to publish a giant ad on your project’s behalf; they want content that their readers will thank them for.
    • I found out where my power-users were. This advice is common in the startup world: Find your core 1,000 early adopters. It’s no different with open source. Who were the users that craved for a performant animation engine — that would do amazing things with it then show off their exploits to the world without me prompting them to? Web animation demo-sceners — that’s who; the passionate, hard-core devs who explore the intersection of technology and design. And, where do they hang out? CodePen.io. I reached out to the demoers whose work I greatly admired, and I gave them access to a pre-release version of Velocity. Sure enough, they eventually pumped out something amazing for me to share.
    • To ensure that new developers always stumble into Velocity.js — even far past the point that I’m still proactively marketing the project — I embedded Velocity into every popular web developer resource that I could find. I pull-requested BentoBox.io and the popular GitHub repo for front end bookmarks. I pitched the Treehouse video blog guys. That was all just the start. I also have upcoming codecasts on Velocity’s workflow that code schools will be presenting to their students. Simply put, I made sure that every developer trying to master web animation would at some point hear about Velocity.
    • Most importantly, I wrote great documentation. To quote GitHub’s Zach Holman once again, “Documentation is marketing. The best part is that documentation is linkable. It’s indexable. It’s tweetable. Particularly if you have a nice, coherent one-page overview of your project that lets people jump in and immediately ‘get’ it.” To expand on Zach’s thoughts, I would frame an open source project’s documentation as what a landing page is to a startup. And make no mistake, you do have to pitch; you can’t merely document your API and call it a day. The developers reading your documentation are no different than anyone else; they have limited time, and they need to be convinced that your project is worth considering.

    When you have great documentation, posting to Reddit and Hacker News will take care of itself. Developers recognize their peers’ hard work, and they’re happy to spread the word.

    On this topic, do you know what the best-kept secret about open source marketing is? That it’s 100x times easier than startup marketing. It’s less work, and you’ll see success with a much greater degree of certainty. Why? Because developers — as compared to the average web user — are more willing to listen, are more willing to retweet, and are generally less skeptical of your marketing claims. Whereas most web users are tired of being pitched with trite social media products, developers are always on the hunt for better tools. Similarly, the web development press is much easier to get a response from than the mainstream tech news press is. The former is scrounging for good content to share with their users whereas the latter is drowning in a sea of half-backed startup pitches.

    Because of the marketing efforts I put into Velocity, and because of the project’s ensuing success, I have become highly motivated to continue working on open source projects.

    I am only just getting started: Velocity is the first in a trilogy of libraries that aim to change the way we visually interact with software. If you’re interested in staying on top of my UI exploits, say hello on Twitter: @Shapiro.

  10. Creating a Multiplayer Game with TogetherJS and CreateJS

    Bubble Hell Duel is a multiplayer HTML5 dogfighting game. The object of the game is to dodge bubbles launched from your opponent while returning fire. This game was written mainly as a prototype for learning and the source code is available on GitHub. You can try the game out in single or multiplayer here. Currently the game does not contain any sound effects but uses CreateJS and TogetherJS.

    screenshot

    In this post I would like to share some of my experiences when developing the game. Please share your thoughts in the comments if you agree or have other suggestions.

    Game Engines

    When developing a 2d game you can write you own engine or make use of some fantastic libraries that are available. After spending a few days looking at the various options available I decided to use CreateJS. As I have some experience with Flash, CreateJS made sense for my needs as there was not much of a learning curve. I also wanted to make use of some Flash animations and CreateJS supported this feature. I will elaborate a bit more on animations later in the article.

    As I am a C++ developer I believe emscripten is also a good choice. It allows C/C++ code to be compiled to JavaScript, which can be executed in the browser. I am of the opinion that the static type checking and compile-time optimizations are great assets when developing large code bases. I have used emscripten before and it works very well, but for this project I wanted the fast and convenient prototyping capabilities of JavaScript. I also wanted to expand my JavaScript knowledge.

    I’d like to mention a few other libraries that seem very interesting: Cocos2d-x is making an emscripten port and they already support HTML5 binding. I also like pixi.js as it provides a webGL renderer but also supports Canvas fallback when the browser does not support webGL.

    C++ vs JavaScript

    At first I was a little bit worried about the performance of JavaScript, and that was the reason my decision between using CreateJS or emscripten was difficult. Fortunately a simple benchmark showed that a naive collision detection algorithm with about 400 balls on screen could still reach 40+ fps, which was enough for my simple experiment.

    As someone who has coded more in C++ than JavaScript I loved how quickly I could translate my thoughts into code and test them out on multiple browsers. On the other hand it was not very comfortable debugging my JavaScript. C++ compilers are quite good at pointing out misspellings and other mistakes that cause runtime issues. While the “use strict” directive and other mechanisms like closure compilers have their purpose they were not very helpful to me especially when variables became undefined. Rooting for the cause of errors can be somewhat difficult comparatively.

    As an example of difficult debugging, I encountered the following issue. I was using float numbers for coordinates and other geometric values like angles. These values were passed to the other player using the TogetherJS.send method for synchronization:

    var player = { x: 10.0, y: 10.0 };
    TogetherJS.send({type:'sync',x:player.x,y:player.y});
    TogetherJS.hub.on('sync', function(msg){
        enemy.x = msg.x;
        enemy.y = msg.y;
    });

    This worked, but lots of decimals were sent in this way, so I decided to relax the accuracy:

    TogetherJS.send({type:'sync', x:Math.round(player.x), y:Math.round(player.y) });

    Then I thought integers might not be accurate enough for collision detection, so I added more digits to the messages:

    TogetherJS.send({type:'sync', x:player.x.toFixed(2), y:player.y.toFixed(2) });

    While this seemed a reasonable solution, it actually induced a bug that was very hard to find and I did not notice it until I tested the game after implementing some more features. I noticed while playing the game the opponent would never move.

    It took me hours in debugging before I could locate the cause. I do not think I would have made this mistake using C++.

    If you would like to see this bug in action take a look at this jsFiddle project. Look at the three canvas tag outputs and you will notice the third canvas contains the bug. This issue occurs because toFixed returns a string representation.

    I am not sure using a closure compiler would have avoided this issue, but I did find in another project that it definitely helps with optimizations.

    Animation with Flash

    As with most games I wanted to use a good deal of animation. I was very familiar with creating animations in Flash and found that CreateJS supported several ways of consuming the Flash animations and presenting them in HTML5. CreateJS is a set of libraries and tools used to create interactive HTML5 content. So by using CreateJS I could consume my animations as well as use the other libraries available for loop handling, resource management and in the future, sound manipulation. For a quick introduction to CreateJS take a look at this video.

    CreateJS, which Mozilla now sponsors, offers great support for Flash animations.

    There are two ways of using Flash animations in HTML5 with CreateJS. The first option is to directly export the Flash animation in a way that you can access all the elements in their original form, including paths, transformations and tweens. The advantage to this approach is that it produces smaller files, and CreateJS allows you to transfer them into a sprite sheet on the client side, for faster rendering. Adobe Flash CS6 offers the CreateJS Toolkit plugin that allows the designer to export all the content of an animation to HTML5 files. This generally results in a JavaScript file with all the graphics and tweens, an HTML file, and a set of image files. You can open up the HTML document in your browser and see the animation.

    Another option is to export the animation into a sprite sheet, that is an image containing all the frames with a JavaScript file describing the position and size of each frame. These files can be easily integrated into HTML based games or applications via the SpriteSheet class in CreateJS. This is the approach I used for this game. To see the code where I use the SpriteSheet have a look at this link. If you want some more detail on this approach take a look at this video.

    I should also note that you can use a tool called Zoë to export directly to a sprite sheet or a JSON file from a Flash Animation as well.

    marisa

    The above image is an example of a sprite sheet that I use in the game and was generated as described above. The original image came from the game Touhou Hisouten ~ Scarlet Weather Rhapsody, which is availabe at http://www.spriters-resource.com.

    Multiplayer with TogetherJS

    On my first iteration of the code the game was not multiplayer. Originally it was a single-player bullet hell game, with a boss foe randomly moving across the screen. I could not last more than 30 seconds before succumbing to withering fire. It was interesting enough that I thought multiplayer would be exciting.

    I had heard of Together.js not long after it was released. The jsFiddle project is powered by Together.js and offers an impressive collaboration mode. This led me to using Together.js in my game. It is also very nice that Mozilla offers a default hub server simplifying the process of creating a multiplayer web based game. To learn more about Together.js be sure to check out this article.

    It was easy and comfortable integrating Together.js into my game, as it works like other event dispatcher/listeners frameworks.

    With Together.js, I was able to implement random match and invitation only multiplayer modes in the game. I did face a few design challenges that I had to overcome when designing the communication protocol.

    First off, I did not put code in to prevent cheating with two-party communications and assumed a certain level of trust between players. In the game design currently all collision detection of a player is done locally. Theoretically if you block corresponding messages you can mask that you have taken damage.

    Another area that I hacked a bit is that the bubbles of the enemy avatar are generated locally and randomly. This means that the bubbles seen from your character avatar are not necessarily the same as your opponent is seeing.

    In practice neither of these shortcuts should ruin the fun of the game.
    I did encounter a couple of issues or caveats with Together.JS.

    • I did not find a way to disable the cursor updating in Together.js. While this is useful in collaborative tools I did not need it in my game.
    • I am using Together.js in an asymmetric way, where both players see themselves as the red skirted Avatar (Reimu). This allows for easier placement of the player at the bottom of the screen and the opponent at the top. This also means that when you move the main player from an opponent’s view of the game your move is seen as the opponents move and vice versa.

    The Fun of Making Mistakes

    There are two visual effects in the game that came as unexpected surprises:

    • When a round finishes and the message ‘You Win’ or ‘You Lose’ appears, the time is frozen for a few seconds. This acts like a dramatic pause.
    • When a charge attack is released, the bullets are fixed and then gradually blown away toward the enemy.

    Neither of these effects was designed in this way. I didn’t want the pause and I wanted the bullets to continue rotating around the player upon releasing. However I made mistakes, and the result seemed to be much better than I had planned, so they made the final cut.

    Conclusion and Future Plans

    It is always fun learning new things. I like the fact that I could prototype and visualize pretty quickly. In the future I might add more patterns for the bullet curtains, and a few sound effects. In addition I will probably also draw more background images or possibly animate them.

    While developing the game I did realize in order to get a natural and intuitive feel required more effort than I expected. This is something I have always taken for granted while playing game.

    The code is open source, so feel free to fork and play. Be sure to comment if you have any suggestions for improving the game or the existing code.