Mozilla

Found 372 results for “html5”

Sort by:

View:

  1. Phones for Apps for Firefox OS

    Update: Today, Monday, May 13 at 11:00am PDT, we closed the submission form for the Phones for Apps program. Thanks so much to all of you for your interest and enthusiasm. Your response has been overwhelming! We’ve received thousands of applications, more than we’re equipped to review in a timely fashion.

    We’ve started reviewing your proposals, and in the next few weeks we plan to notify application builders and porters who’ve been selected. We regret we can’t respond to the thousands of you with great ideas for apps for Firefox OS. There will be other opportunities to get access to the the Developer Preview device. Please keep working on your apps. We can’t wait to see them in Firefox Marketplace.

    Hello HTML5 app developers, the open mobile web is calling.

    We know you’re out there, chomping at the bit, coding, testing, reading documentation, downloading and running the Firefox Simulator. And you’re ready to ‘Send to Device.’ You just need to get your hands on a device.

    Today we’re announcing a new program with you in mind. We call it: Phones for Apps for Firefox OS.

    Firefox Marketplace on the Geeksphone

    Firefox Marketplace on the Geeksphone Keon

    Maybe you’ve built apps in the past for Chrome, webOS, Blackberry WebWorks, or the PhoneGap store. Maybe you’ve created beautiful web apps for a desktop environment and now you want to port them to mobile. Maybe you’re a student about to start a summer break. We know you may not live anywhere near Bogota, Colombia or Warsaw, Poland, locations of upcoming App Workshops.

    Wherever you are

    Wherever you are, if you can show you’ve got a great app idea and the skill to build it, we’d love to see your apps in the Marketplace when the Firefox OS launch begins later this summer. And to sweeten the deal, we’ll send a Firefox OS Developer Preview device for you to work with now.

    When Firefox OS phones become available to consumers in select locales this summer, you’ll have an opportunity that only comes around once—a first-mover advantage in Firefox Marketplace. End users in Latin America, Eastern Europe and other launch locations will be on the lookout for playful and practical apps to install: games, tools, and utilities as well as locally relevant news, sports, travel, entertainment, review apps, and social sharing experiences. And you can build and submit them now!

    Apply now

    Tell us about the Firefox App you’d like to build or port. If your proposal is accepted, we’ll send you a Geeksphone Keon. Our device inventory is limited and our launch dates are approaching fast, so act now. This program will close at the end of May or when our limited supply of Geeksphones runs out. There’s a limit of one phone per app proposal. We can’t wait to see what you’re working on. There’s never been a better time to get started.

    Apply here.

  2. How to Spread The Word About Your Code

    You spent an entire weekend building a library, jQuery plugin, build tool, or other great piece of code you wanted to share far and wide, but after some tweets and a failed attempt to make the front page of Hacker News, your creation languished, unloved, in a GitHub repo. A common situation for many developers nowadays, but one you can avoid.

    As the editor of several programming newsletters, I frequently get two types of e-mails from developers. Those reaching out to ask if I can mention their projects, and those expressing surprise and excitement that their work has been featured. If you’re a developer doing good work but feel more like you’d be in that second group, the three steps in this article are for you.

    Before we get started, there’s a stumbling block we need to kick away. Terms like ‘marketing’ and ‘advertising’ are dirty words for many developers and it’s not uncommon for developers to be reluctant to do much promotion. ‘Build it and they will come’ used to work when exciting open source projects were few and far between but now everyone seems to be working on something and making a noise about it. Few of the successes you see come through pure luck but because developers are actively promoting their work or, at least, making it discoverable. It’s time to join them!

    Step 1: Get your project ready

    Before you can promote your project, you need to make it attractive to potential users and evangelists (including general wellwishers, the media, and other developers).

    A good name

    Ensure your project has a palatable name. It doesn’t need to be clever or even descriptive, but it’s worth avoiding innuendos that may present a problem down the line. For example, the popular Testacular and Authgasm projects, are now named Karma and Authlogic respectively after users raised a fuss.

    You should perform a search for the name you choose to be sure you’re not clashing with anything else that’s popular or trademarked (did you know Firefox was called Phoenix and Firebird prior to Firefox?). The US Patent and Trademark Office has an online trademark search facility.

    A benefit of having a relatively unique or uncommon name is so you can search for it over time (or even set up a Google Alerts notification for the name) and find mentions of your project without many irrelevant results popping up. If you want to have something descriptive but unique, consider joining two words together. For example, when I created a Ruby library to do natural language detection, I called it WhatLanguage and it’s easy to search for.

    An official homepage or project URL

    The term ‘homepage’ is a bit outdated but you ideally need a single ‘home’ URL that you can promote and point people to in relation to your project. You don’t need to splash out on a fancy template or even a domain name, but your project needs a focal point. That could be an entire site with its own domain, such as those for Yeoman or HTML5 Boilerplate, a simple single page on an existing domain, such as that for RoughDraft.js, or even a regular GitHub repo, such as for vague.js.

    If you have the freedom to do so, make sure your site looks good on the major browsers (including mobile), hook up some analytics to your page and ensure the <title> tag is well written. Use a title like “MyProject – A JavaScript Library to X, Y and Z” instead of just “MyProject – About” or a blank title. With social bookmarking, this matters as you can’t guarantee your evangelists will write a good title of their own.

    If you’re not a Web designer, don’t have the time to spend making a complete design, but still want a complete site rather than just a GitHub repo and README, consider using a framework like Bootstrap as it’ll provide a clean layout out of the box and you can forget about many cross browser and device issues.

    Documentation and copywriting

    It’s only just a cliché that developers don’t like to write documentation, but you need something for potential users to fall back on, and time invested in producing useful documentation up front will pay dividends later.

    At a cynically bare minimum, you need to write enough documentation that someone will be confident about sharing your link or promoting your project and not feel like they’re sending their own followers into a black hole of misunderstanding. This means your homepage or README needs to cover a few angles. You’ll need to:

    • Prominently feature a “[noun] is” paragraph. An alarming number of project homepages don’t explain, in simple terms, what the project is actually for or does. If you’ve built a JavaScript library that does language detection, say, you have to say so. For example: “LanguageDetect is a JavaScript library for detecting the natural language of text.”

      An excellent example of this in action is on libcinder.org where it states right up front: “Cinder is a community-developed, free and open source library for professional-quality creative coding in C++.” Perfect!

    • Write clear titles, subheadings, and support copy. At a bare minimum, ensure titles, subtitles, and any sort of writing on your homepage are straightforward and clear. Write for the lowest common denominator on your homepage. You can get more advanced elsewhere.

    • Write a beginner’s tutorial and link to it from your home page. Unless everything’s simple enough to explain on a single page, quickly write a tutorial that covers basic installation and usage and either include it in your README file or put it on the Web and link to it from your README and/or homepage.

    • State dependencies and requirements clearly. Does your library only work on a specific version of Node? Is it a browser extension for Firefox? Does your code require PostgreSQL, Redis, or another specific database? Be sure to include a bulletpoint list of dependencies and requirements for your project to be usable so as not to disappoint potential users.

    • Specify the license for your code. While you could get away with keeping your licensing information tucked away in a LICENSE file in your GitHub repo, specifying what license your code is released under up front and center will help put many developers at ease. Likewise, if your project is commercial is nature and costs money, don’t hide that detail away and mislead visitors.

    • If your project is a library or API, feature some example code on the homepage. Unless your library is particularly complex, let visitors see an example of its usage on the project homepage. If your API is good, this could be a great way to get an ‘easy sale.’ I’m not a huge fan of the code example chosen but the homepage for Ruby shows off this technique.

    Extra materials

    A blog post is a great way to introduce a project that might need more background or have more of a story than it’s practical to tell on a homepage or within documentation. If there’s any sort of story behind your project, a blog post is a great way to tell it. Be sure to link to the post from your project’s homepage and consider promoting the blog post separately to relevant sites within your niche.

    If you have the ability, recording a screencast or other sort of video can help. Could you put together a simple 5 minute screencast of how to install and use your library? Or have you built a game that could be demonstrated in a few minutes of gameplay? Record a simple video, put it on YouTube, and embed it on your homepage. Your accent doesn’t have to be as crisp as a newsreader’s and you don’t even have to appear within the video. All that matters is you get to the point quickly and your audio is tolerable (not muffled, clipping, or drowned in background music).

    As the editor of several programming newsletters, I look at thousands of projects each year, and it’s still uncommon to see simple screencasts, yet they certainly help a project stand out and, as a consequence, make it more likely for me to talk about it. You can see a perfect example on Punch’s homepage. The early popularity of Ruby on Rails also depended upon a popular ‘build a blog engine in 15 minutes’ video, back when the concept of using video to promote an open source project was very novel.

    If you’re sticking to the straight up, GitHub README approach (and it’s certainly not a bad idea for a simple library), a bonus tip is to create a tiny screencast of your code in action and convert it to an animated GIF for inclusion in your README. Richard Schneeman outlines this technique in Use GIFs in your Pull Request for Good, not Evil. The result is striking and could help your README stand out.

    For further ideas on how to make your project stand out before you begin promoting it, check out the great How to Make Your Open Source Project Really Awesome by Michael Klishin. It digs into more detail about versioning, announcements, having a changelog and writing good documentation.

    Step 2: Get the word out

    You’ve polished your project, got a URL to promote, and you’re ready to get the news out.

    A word of caution, however. Don’t use every technique on day one. You could overload your site with traffic or, worse, be subjected to a barrage of online criticism if your work or site is broken. With something like a library or tool, a gentler approach will work well and building up small streams of visitors and users over time will give you a much better time.

    Social networking

    Your own social networking profiles are always a good place to start if you have them. You’ll get more immediate feedback from people who actually know you and if your project is particularly interesting, it could go viral even from a single mention.

    A great example of a simple project going viral was YouTube Instant by Feross Aboukhadijeh. Feross built YouTube Instant quickly, mentioned it on Facebook before going to bed, and woke up to a flood of traffic and press mentions.

    If you like to experiment and have several bucks going spare, you could also consider paying for a promoted post on Facebook. This will give your post more visibility in your news feed, but is best reserved for if your Facebook friends are mostly developers or people likely to be interested in your project. If not, and you’d still like to spend some money, consider an ad on Reddit or a relevant programming blog instead.

    Influencers, bloggers, and niche media

    Whether you’re working on a JavaScript library, Firefox extension, backend app in Rails, or a theme for Bootstrap, your code will fit into one or more niches and every technical niche has a variety of ‘influencers’, people and publications who are popular and well known for the topic at hand.

    Getting a tweet, retweet, or even an entire blog post from an influencer could have a significant impact on your project, as could being invited to blog elsewhere (Mozilla Hacks, for example!). If Brendan Eich tweeted about your JavaScript library, Lea Verou wrote a blog post about a CSS trick you discovered, or Paul Irish mentioned a Web development tool you built in a talk, you would attract a lot of interest quickly. It is key, however, to realize there are many great influencers in every space and you’ll achieve nothing by hounding any one person so be prepared to move on.

    Spend some time working out who the influencers and key publications are in your niche. For Twitter, Followerwonk is a handy tool that searches Twitter biographies for certain words. If you search for “javascript” the first page includes several users who would be useful to reach out to if you had a particularly interesting JavaScript-related release to promote. Reaching out on Twitter can be as simple as a single tweet and many busy folks prefer Twitter as it takes less time to reply than an e-mail. A single tweet from @smashingmag could drive thousands of visitors your way, so consider tweeting them, and other similar accounts, when you have something relevant.

    I’d also advise looking for blogs and e-mail newsletters in your niche. Start with something as simple as Googling for “javascript blog”, “javascript newsletter”, “css blog” or whatever’s relevant to your project. Most bloggers or e-mail newsletter publishers will not be offended by you sending them a quick note (emphasis on quick) letting them know about your work. Indeed, some weeks there can be a shortage of interesting things to write about and you might be doing them a huge favor.

    If you choose to e-mail people (and your project will probably be more substantial than a few hours’ work to justify this), take care not to make demands or to even expect a reply. Many bloggers and influential people have overflowing inboxes and struggle to reply to everything they receive. Make your e-mail as easy to process as possible by including a single URL (to your now superb homepage or README) and include your “[noun] is” paragraph. Don’t take a non-response as an insult but keep moving on to the next most relevant person. You might even consider taking a “Here’s my project that does X, Y and Z. No reply needed, I just thought you might like it” approach. Softly, softly works here, as long as you get to the point quickly.

    How to get attention from internet celebrities by Jason Cohen and How to Write the Perfect Outreach Email by Gregory Ciotti go into more detail about e-mail etiquette when promoting your work to influencers. While you might not need to contact any ‘celebrities’ in your niche, the principles of keeping it short, including a call to action, and ensuring your work is appropriate to the person are really true for anyone you’re sending unsolicited messages to.

    Podcasters are an often forgotten source of promotion opportunities too. While some podcasts don’t cover news or new releases at all, many do, and being on the radar of their hosts could help you get a mention on a show. Smashing Magazine has put together a list of tech podcasts covering the areas of design, user experience, and Web development in general. Again, keep your e-mails short and sweet with no sense of expectation to get the best results.

    User curated social news sites

    As well as reaching influencers and niche media, sometimes reaching the public ‘firehose’ of news can work too, and there are few better examples of these in the modern world of development than Hacker News or Reddit.

    Hacker News in particular is notoriously hard to reach the front page on and ‘gaming’ it by getting other people to vote up your post can backfire. (Indeed, it will backfire if you link people to your post on Hacker News and encourage them to upvote. They have ways of detecting this behavior. Get people to manually find your post instead.) If you do reach the front page of Hacker News, of course, you can certainly expect an audience of many thousands of developers to be exposed to your work, so be sure to try.

    With Reddit, the key isn’t to dive straight into a huge sub-Reddit like /r/programming but to look for sub-Reddits more directly related to your project. For a JavaScript library, I’d post to /r/javascript or possibly /r/webdev. Reddit ads can also perform well if you’re OK with spending some money and these can be targeted to specific sub-Reddits too.

    There are many similar sites that are less well known but which are respected in their niches and can drive a lot of interested visitors, including Designer News (mobile and Web design), DZone (general developer stuff), EchoJS (JavaScript), RubyFlow (Ruby and Rails), and Lobste.rs (general hacker and developer stuff). Finding the right site like this and taking time to make an on-topic, well written post will help a lot.

    The mass media / press

    This article is primarily focused on the promotion of open source and front-end projects and these are typically not frequently covered in print or on the TV or radio. If, however, you think the mass media would be relevant for your project, here are some other articles packed with handy tips:

    Step 3: Maintain momentum

    You’ve built up some interest, your GitHub stars, Reddit votes, and pageviews are all rocketing up, but now you want to capitalize on the attention and maintain some momentum.

    User support

    Whether you’ve built an open source project or a cool tool, you’re going to end up with users or fellow developers who want to provide feedback, get help, or point out issues with your work. On GitHub, the common way to do this is through the built-in ‘issues’ tracker, but you might also find people start to e-mail you too.

    Be sure to define a policy, whatever it is. Users won’t feel good about opening issues on your GitHub repo if there are already many unresolved issues there and your project could stagnate. Ensure you respond to your audience or at least make your policy clear within your README or on your site. If you don’t want issues raised or code contributions, make this clear up front.

    Extending your reach

    For many projects, create a dedicated Twitter account, blog, Facebook page, or Google+ page in advance is overkill, but if your project starts to take off, consider these things. They’ll provide an extra way not only for users to remain in touch with your project but also a way for them to help promote it by retweeting things you post or by directing potential new users your way.

    You can also extend your reach in person by going to user groups and conferences and, if you’re really lucky, you can speak about your work too. This is a great way to get new users as people are much more likely to look into your work if they’ve met you in person.

    Avoid being defensive

    If your project does well on sites like Hacker News or Reddit, you’ll be tempted to read all of the comments your peers leave, but be careful. Comments about your work will, naturally, seem magnified in their intensity and critical comments that might not actually be mean spirited may seem as if they are to you.

    It’s hard, but the best policy is to not let any overtly mean comments get to you, duly correct any observations that are wrong, and to thank anyone who goes out of their way to compliment your work. Even if you’re in the right, with the lack of body language and verbal cues, being too defensive can look bad online and result in the post becoming a lightning rod for drama. Engage as best you can, but if it feels wrong to reply to something, listen to your gut.

    Be careful if you go into a new community to promote your work and get negative feedback. Most communities have rules or expectations and merely entering a community to promote your work is frequently considered a faux pas. Be sensitive to people’s environments and try to abide by a community’s rules at all times.

    The long term

    If your project does particularly well, you could be presented with the opportunity of turning it into a business in its own right. Many simple open source projects, often started by a single developer, have turned into long term work or even entire companies for their creators.

    Back in 2010, Mitchell Hashimoto released Vagrant, a Ruby-based tool for building a deploying VirtualBox-based virtualized development environments. In late 2012, Mitchell launched Hashicorp, a company providing Vagrant consulting services to enterprise customers. An even higher profile example is Puppet Labs, a company built around the Puppet open-source configuration management tool and which has taken total funding of $45.5 million so far.

    If your project becomes respected and heavily used within its field, you might also be approached to write a book or article about it or even speak at a conference. This is a good sign that your project has ‘made it’ to some extent as publishers and event organizers are in the business of working out what it makes business sense to present.

    Putting it all together: A checklist

    This has only been a basic introduction to promoting your work and with practice you’ll come up with tons of tips of your own (it’d be excellent if you could share some in the comments here). Based on all of the ideas above, here’s a basic checklist to run through next time you release a new project and want to get some added exposure:

    • Focus most of your efforts on your project’s homepage or README.
    • Check your project’s name doesn’t clash with anything else and is unique enough to find references to your work later.
    • Promote your work to your closest social group first to unbury any problems with your work.
    • Record a screencast or write a blog post about your project if some extra background would be useful for others.
    • Work out a perfect *”[project name] is”* sentence to describe what your project is or does.
    • Use your *”[project name] is”* sentence to give your page a descriptive title.
    • Find influential people, blogs, podcasts, and e-mail newsletters in your niche and send them a short, pleasant note.
    • Post to social news and bookmarking sites. Ensure your title is descriptive.
    • Use your *”[project name] is”* sentence in e-mails and contacts with influencers.
    • Take a positive, “look on the good side” approach to responding to comments about your work.

    Good luck!

  3. Web Payments with PaySwarm: Purchasing (part 3 of 3)

    The Promise of Web Payments

    The first and second articles in this series outlined how PaySwarm is designed to transmit and receive funds with the same ease as sending and receiving an email. The articles went on to explain how making the tools that have been traditionally only available to banks, Wall Street, and large corporations available to everyone can help reform our financial systems. The goal is not just one-click payments, but also to enable crowdfunding innovation, help Web developers earn a living through the Web, boost funding rounds for start-ups, and to advance initiatives that will lead to a more egalitarian society.

    This is the final article in a three part series on sending and receiving funds using the PaySwarm specification. This article will review some of the concepts in the first two articles and introduce the concepts of a purchase request, digital contract, and digital receipt. A tutorial will go on to explain how to perform a purchase via PaySwarm as well as how to download the digital receipt of sale. Code examples and video of the process are provided.

    Review: Identity

    As explained in the first article, the Web Keys specification provides a simple, decentralized identity solution for the Web based on public key cryptography. It enables Web applications to send messages that are encrypted and verifiable.

    The messages are marked up using the JavaScript Object Notation for Linking Data (JSON-LD). As the name suggests, JSON-LD is a way of expressing Linked Data in JSON. Both HTML documents and JSON-LD documents describe things and have links to other documents on the Web. The primary benefit of a JSON-LD document is that a machine can easily extract and perform basic reasoning over the information it contains without placing a large burden on its author.

    Web Keys coupled with JSON-LD provide the underlying identity and messaging mechanism used by PaySwarm to perform Web Payments.

    Review: Assets and Listings

    As explained in the second article, PaySwarm enables products and services to be listed for sale on the Web in a decentralized way. The specification allows content creators and developers to be in control of their own product descriptions and prices in addition to giving them the option to delegate this responsibility to an App Store or large retail website. The second article elaborated on the two basic concepts that are used to describe products and services for sale on the Web: assets and listings.

    An asset is a description of a product or service. Examples of assets include web pages, ebooks, groceries, concert tickets, dog walking services, donations, rights to transmit on a particular radio frequency band, and invoices for work performed. In general, anything of value can be modeled as an asset.

    A listing is a description of the specific terms under which an asset is offered for sale. These terms include: the asset being sold, the license that will be associated with the purchase, the list of people or organizations to be paid for the asset, and the validity period for the listing.

    Purchase Requests, Contracts, and Receipts

    So far this series has introduced a decentralized identity mechanism, a secure and verifiable messaging mechanism, and a decentralized mechanism for publishing products and services for sale. This article introduces the purchase request, the contract, and the receipt.

    A purchase request is sent to a PaySwarm Authority when a purchase is requested by the customer. It contains details about the asset and listing that the buyer would like to purchase. There are two ways a purchase request can be authorized:

    The first way is for the vendor to provide a customer with a purchase request to give to their PaySwarm Authority. Once the customer submits the purchase request, they can then use an interface provided by their PaySwarm Authority to view the potential contract and decide whether they agree to its terms.

    The second way a purchase request can be authorized by a customer is by digitally signing it using software running on a device like a personal computer or a cell phone. The purchase request can then be transmitted by this software to their PaySwarm Authority for processing. This approach allows the customer to use innovative third party applications that need to perform purchases on their behalf.

    A contract is an electronic document that expresses an agreement between all parties involved in a transaction. It contains the asset, digitally signed by the asset provider, and the listing, digitally signed by the vendor. A contract can be finalized in one of two ways:

    The first way a contract is completed is when an authorized purchase request is submitted to a PaySwarm Authority. If payment processing can occur without issue, then a contract for that purchase is completed and kept on record by the PaySwarm Authority.

    The second way to complete a contract requires a customer to digitally sign the contract before submitting it to a PaySwarm Authority. This approach allows a customer to fully review the terms of the contract using an interface that is not hosted by the PaySwarm Authority. If the customer agrees to the contract, their software digitally signs it. The digitally-signed contract can then be transmitted to their PaySwarm Authority using a variety of different mechanisms. This is particularly useful when the customer does not have access to the Internet, but the vendor from which they are purchasing does. An example of this is when a customer makes an in-store retail purchase with a PaySwarm-enabled mobile phone with no data plan. The phone could receive a contract from the vendor over NFC, digitally sign the contract on the phone, and transmit the signed contract back to the vendor over NFC. The contract would then be delivered to the customer’s PaySwarm Authority by the vendor and payment processing would be performed.

    A receipt is the result of a successful purchase. Typically, receipts are provided to a vendor by a PaySwarm Authority with the minimum amount of information necessary to prove that the sale of an asset to a particular customer was completed successfully. For a more comprehensive review of a purchase, a vendor or customer can request a full contract from their PaySwarm Authority. A contract is provided to buyers as a proof-of-purchase and for offline storage. It will contain all of the details proving the purchase occurred, even if the PaySwarm Authority that processed the purchase and/or the vendor go out of business or shut down for any reason.

    The video below shows a browser-based mechanism used to process a purchase request, contract, and receipt:

    The rest of this tutorial will demonstrate how to perform a console-based purchase where the customer constructs, signs, and transmits the purchase request to a PaySwarm Authority for processing. Code from the payswarm.js node module will be used throughout this tutorial. Specifically, it references the asset purchasing example. The payment processor will be the PaySwarm Developer Sandbox and the asset hosting service will be the PaySwarm Developer Listing Service.

    Performing the Purchase

    This tutorial assumes that you have already read the first and second articles in this series. In those articles, an identity was created via a PaySwarm Authority and a Web Key was associated with the identity for the purpose of creating digital signatures. The registered Web Key will be used to digitally sign the purchase request seen in this tutorial. An asset and listing were also published to the PaySwarm Developer Listing Service.

    The first step in performing a purchase is to retrieve the listing that indicates which asset is for sale. The getJsonLd() function in the payswarm.js library can be used to retrieve the listing data given a URL:

    var url = 
      'http://listings.dev.payswarm.com/mozhacks/html5-me-song#listing';
    payswarm.getJsonLd(url, {cache: true}, function(listing) {
      // do something with the listing
    });

    The code above simply fetches the listing from the given URL in JSON-LD format. The data could be expressed on the page as HTML+RDFa, which is then translated to JSON-LD and returned to the application. The listing data can then be used to construct a purchase request, digitally sign it, and deliver it to a PaySwarm Authority for processing. All of this is done below by calling the purchase() function in the payswarm.js library:

    // purchase the asset under the terms of the listing by 
    // digitally signing a purchase request and sending it 
    // to the PaySwarm Authority
    payswarm.purchase(listing, {
      // the Web Service that will process the purchase request
      transactionService: 'https://dev.payswarm.com/transactions',
      // the identity that is performing the purchase
      customer: 'https://dev.payswarm.com/i/IDENTITY',
      // this financial account will be the source for 
      // the payment funds
      source: 'https://dev.payswarm.com/i/IDENTITY/accounts/ACCOUNT',
      // the private key information used to digitally sign 
      // the purchase request
      privateKeyPem: publicKey.privateKeyPem,
      // the public key ID that will be associated with the 
      // digitally signed purchase request
      publicKey: publicKey.id,
      // log details of the transaction to the console
      verbose: true
    }, function(err, receipt) {
      // if err is null, the purchase was successful
      // do something with the receipt
      console.log('Receipt:', receipt);
      // the transaction ID can be used to download 
      // the complete contract
      console.log('Transaction ID:', receipt.contract.id);
    });

    The code above builds a purchase request using the listing data retrieved in the previous step. The purchase request also includes the financial account which will provide the funds for the purchase. It is then digitally signed using the buyer’s public key. The signed purchase request is then HTTP POSTed to the transaction processing web service on the PaySwarm Authority. If the asset, listing, license, and payment details in the contract are all valid, the PaySwarm Authority will process the payment and return a digitally signed receipt. The receipt will contain the transaction ID for the sale, which can then be used to retrieve the full contract for the sale.

    Downloading the Contract

    The contract for the sale can be downloaded and stored to be used as a proof-of-purchase. A utility provided with the payswarm.js library can be used to download the transaction by issuing a simple command:

    ./bin/payswarm url https://dev.payswarm.com/transactions/1.24.f3d
    

    The video below demonstrates what a console-based purchase looks like using the payswarm.js library:

    Conclusion

    This was the final article in this three part series on building PaySwarm-enabled websites and web applications. One of the primary goals of PaySwarm is to make transmitting and receiving funds on the Web as easy as sending and receiving an email. This is not just about one-click payments; it is also about using open standards to bring new and powerful tools to the general public that will breed competition and innovation.

    If you would like to keep up-to-date with the latest in Web Payments, join the Web Payments Community mailing list.

  4. HiDPI support, HTML5 notifications, Parallel JS, asm.js and more – Firefox Development Highlights

    Time for another look at the latest developments with Firefox. This is part of our Bleeding Edge and Firefox Development Highlights series, and most examples only work in Firefox Nightly (and could be subject to change).

    HiDPI support

    We’re happy to say that ico/icns with multiple images are now supported: the highest resolution icon is now used on HiDPI/Retina displays.

    Favicon implementation is described in bug 828508 and ico/icns is described in bug 419588.

    Performance improvements/Snappy:

    Numerous performance improvements have been made, such as faster startup, better scrolling on touchpads and smoother animations.

    The most important improvement, however, is probably multithreaded image decoder. The result should be faster page loads and tab switching. All the nitty-gritty detalis are described in bug 716140.

    HTML5

    When it comes to the world of HTML5 & friends, we have some good additional support:

    <input type=”range”>

    We now support the <input type="range"> element in forms. To style it, you can use the ::-moz-range-progress:

    ::-moz-range-progress {
        background: #f00;
    }
     
    <input type="range">

    You can see this <input type=”range”> demo in action on jsFiddle.

    HTML5 notifications

    HTML5 notifications have now been implemented. Basically, you ask for permission and then you can create a notification:

    function authorizeNotification() {
        Notification.requestPermission(function(perm) {
            alert(perm);
        });
    }
     
    function showNotification() {
        var notification = new Notification("This is a title", {
            dir: "auto",
            lang: "",
            body: "This is a notification body",
            tag: "sometag",
        });
    }

    See the HTML5 notification demo in action on jsFiddle.

    WebAudio API activated by default

    WebAudio API has been activated by default in Firefox Nightly. Testers welcome, though there are still work to be done before it can be released.

    JavaScript

    Parallel JS

    The first version of Parallel JS has landed for Firefox. A lot more details in the Parallel JS Lands article.

    asm.js

    We’re happy to say that asm.js is now in Firefox, scheduled to be released in Firefox 22! Luke Wagner has written more about it in asm.js in Firefox Nightly.

    ES6 Arrow function syntax

    We now support the ES6 Arrow function syntax

    let square = x => x*x;
    console.log(square(3));

    CSS

    @supports activated by default

    We plan on releasing this with Firefox 22. More about @supports on MDN.

    min-width and min-height ‘auto’ keyword

    min-width and min-height 'auto' keyword is no more supported. It has been removed from CSS3 Flexbox. More about that in bug 848539.

    CSS Flexbox has been re-enabled

    Happy to let you know that CSS Flexbox has been re-enabled by default in Firefox 22, which is currently in Firefox Aurora!

  5. Web Payments with PaySwarm: Assets and Listings (part 2 of 3)

    The Promise of Web Payments

    The first article in this series on PaySwarm outlined how the technology is designed to transmit and receive funds with the same ease as sending and receiving an email. It went on to explain how taking the tools that have been traditionally only available to banks, Wall Street, and large corporations and making them available to everyone can reshape financial systems in a very positive way. The goal is not just one-click payments, but also to enable crowdfunding innovation, help Web developers earn a living through the Web, boost funding rounds for start-ups, and more.

    This article is the second in a three part series on buying and selling content using the PaySwarm specification. It will review some basic concepts covered in the first article and then explain how to list things for sale using PaySwarm.

    Review: Web Keys and JSON-LD

    As explained in part one, the Web Keys specification provides a simple, decentralized identity solution for the Web based on public key cryptography. It enables Web applications to send messages that are both protected from snooping and verifiable via digital signatures.

    The messages are marked up using the JavaScript Object Notation for Linking Data (JSON-LD). As the name suggests, JSON-LD is a way of expressing Linked Data in JSON. Both HTML documents and JSON-LD documents describe things and have links to other documents on the Web. The primary benefit with JSON-LD is that the entire document is understandable by a machine to the point that it can extract and perform basic reasoning without placing a huge burden on the developer writing the JSON markup.

    Web Keys coupled with JSON-LD provide the underlying messaging and product markup mechanism used by PaySwarm to perform Web Payments.

    Decentralized Products and Services

    One design requirement of a Web Payments system is that the identity mechanism (Web Keys) must be decentralized. Another requirement is that the data markup mechanism (JSON-LD) must be capable of expressing decentralized resources like people, places, events, goods/services, and a variety of other data that will likely exist on 3rd party websites.

    Similarly, PaySwarm does not require that products and services be listed in a central location on the Web. Instead, it allows content creators and developers to be in control of their own product descriptions and prices in addition to giving them the option to delegate this responsibility to an App Store or large retail website. PaySwarm has the following requirements when it comes to listing products and services for sale:

    • The listings must be able to be decentralized, which reduces the possibility of monopolistic behavior among retailers.
    • The product being sold must be separable from the terms under which the sale occurs, enabling different prices to be associated with different licenses, affiliate sales, and business models like daily deals.
    • The creator of the product must be able to specify restrictions on pricing, resellers, validity periods, and a variety of other properties associated with the sale of the product. This ensures that the product creator is in control of her product at all times.
    • It must support decentralized extensibility, which enables applications to add application-specific data to the product description and terms of sale.
    • It must be secure, such that the risk of tampering with product descriptions and prices is mitigated.
    • It must be non-repudiable, such that the creator of the listing cannot dispute the fact that they created it.

    Assets and Listings

    There are two concepts that are core to understanding how products and services are listed for sale via PaySwarm.

    The first is the asset. An asset is a description of a product or service. Examples of assets include web pages, ebooks, groceries, concert tickets, dog walking services, donations, rights to transmit on a particular radio frequency band, and invoices for work performed. In general, anything of value can be modeled as an asset.

    An asset typically describes something to be sold, who created it, a set of restrictions on selling it, and a validity period. Since the asset is expressed using JSON-LD, a number of other application-specific properties can be associated with it. For example, a 3D printing store could include the dimensions of the asset when physically printed, the materials to be used to print the asset, and a set of assembly instructions. Upon purchase of the asset, a digital receipt with a description of the asset is generated. This receipt can be given to a printer to produce a physical representation of the asset.

    The second concept that is key to understanding how products and services are sold in PaySwarm is the listing. A listing is a description of the specific terms under which an asset is offered for sale. These terms include: the exact asset being sold, the license that will be associated with the purchase, the list of people or organizations to be paid for the asset, and the validity period for the listing. Like an asset, a listing may include other application-specific properties.

    This tutorial elaborates on creating an asset and listing and publishing them to a website, as shown briefly in the video below:

    Code from the payswarm.js node module will be used throughout this tutorial. Specifically, it utilizes the asset publishing example. The payment processor will be the PaySwarm Developer Sandbox and asset hosting service will be the PaySwarm Developer Listing Service.

    Creating an Asset

    As mentioned previously, an asset is described using JSON-LD. An asset is built in a programming language the same way one would build data to be published as a JSON document. Typically, this involves using an object (in JavaScript), a dictionary (in Python), an associative array (in PHP), or a hash (in Ruby). Here is the code to create an asset in JavaScript. Pay particular attention to the comments as they will explain what each key-value pair means. Let’s try a simple example first:

    // create a PaySwarm asset
    var asset = {
      // the @context is a hint to a JSON-LD processor on how to interpret the 
      // key-value pairs in the document
      '@context': 'https://w3id.org/payswarm/v1',
      // this is the global identifier for the asset
      id: 'http://listings.dev.payswarm.com/mozhacks/demo#asset',
      type: ['Asset'],
      // this is the person who created the asset
      creator: { fullName: 'Developer Joe' },
      title: 'Mozilla Hacks Demo Asset',
      // this is typically the link to the paid content
      assetContent: 'http://listings.dev.payswarm.com/mozhacks/demo#asset',
      // this is the entity that has rights to the asset (or owns it)
      assetProvider: 'https://dev.payswarm.com/i/YOUR_IDENTITY_HERE'
    };

    The code above is a working example of an asset description in about seven lines of code (without comments). It describes an asset called Mozilla Hacks Demo Asset, which can be sold by anyone. The idea is that you would express this data on a website, either as a separate JSON-LD document or directly in an HTML5 page using RDFa markup. Any PaySwarm-compatible payment processor could then get your document and know exactly what you have created and what the sale restrictions are.

    Let’s take a look at a more complex example. The asset below specifies a song with a twist on how it can be sold. It can be resold by anyone, with 80% of the proceeds, or a minimum of $0.50, going to the band that created the song.

    // create a PaySwarm asset
    var asset = {
      // the @context is a hint to a JSON-LD processor on how to interpret the 
      // key-value pairs in the document
      '@context': 'https://w3id.org/payswarm/v1',
      // this is the global identifier for the asset
      id: 'http://listings.dev.payswarm.com/mozhacks/html5-me-song#asset',
      type: ['Asset', 'schema:MusicRecording'],
      // this is the person who created the asset
      creator: { fullName: 'The Webdevs' },
      title: 'HTML5 Me, Baby',
      // this is the link to the paid content
      assetContent: 'http://listings.dev.payswarm.com/mozhacks/paid/html5-me-song',
      // this is the entity that has rights to the asset (the artist in this case)
      assetProvider: 'https://dev.payswarm.com/i/the-webdevs',
      // these are restrictions under which the asset can be sold
      listingRestrictions: {
        // validity dates so that the price information below doesn't
        // last forever (you may want to change your price)
        validFrom: payswarm.w3cDate(validFrom),
        validUntil: payswarm.w3cDate(validUntil),
        payee: [{
          // this is an entity that should be paid when the asset is sold
          type: 'Payee',
          // when the asset is sold, put the money for the asset provider here
          destination: 'https://dev.payswarm.com/i/the-webdevs/accounts/royalties',
          // the name of the group determines how this particular payee's rate comes 
          // out of the total price of the sale
          payeeGroup: ['assetProvider'],
          // next 6 lines: the greater of 80% of the vendor's price or $0.50 should go
          // to the content creator
          payeeRate: '80',
          payeeRateType: 'Percentage',
          payeeApplyType: 'ApplyInclusively',
          payeeApplyGroup: ['vendor'],
          minimumAmount: '0.50',
          currency: 'USD',
          // show this to the buyer as one of the line items in the digital receipt
          comment: 'Payment to The Webdevs for creating the HTML5 Me, Baby song'
        }],
        payeeRule: [{
          // next 2 lines: allow the payment processor (the PaySwarm Authority) to add 
          // a fee for processing the transaction
          type: 'PayeeRule',
          payeeGroupPrefix: ['authority']
        }, {
          // next 4 lines: vendors can only specify a flat fee for reselling the song
          // from their website
          type: 'PayeeRule',
          payeeGroup: ['vendor'],
          payeeRateType: 'FlatAmount',
          payeeApplyType: 'ApplyExclusively'
        }]
      }
    };

    The code above is a more comprehensive example of an asset description in approximately 30 lines of code (without comments). It describes an asset, which is a song, called HTML5 Me, Baby that can be sold by anyone who complies with the other restrictions set forth. A content creator who describes an asset this way on the web creates an incentive for their fan base to blog about and resell the content on their personal blogs. Imagine a WordPress plugin that allows you to review and resell your favorite bands songs directly from your blog. The artist is always guaranteed to get paid, regardless of which blog sells it or which PaySwarm Authority processes the payment. In this particular example, the asset provider has enabled their fans to take a 20% cut of the sale.

    When a sale of the song above occurs, 80% of the sale price, or a minimum of $0.50 USD, is transferred to the asset provider. The PaySwarm Authority may add a fee for processing payment for the asset. A vendor may set a flat price for the song. For example, if the song is sold for $1.00, then $0.80 goes to The Webdevs (80% of final price restriction kicks in). If the song is sold for $0.60 USD, then $0.50 goes to The WebDevs ($0.50 USD minimum restriction kicks in). As you can see, the listing restrictions provide a great deal of power to the asset provider to specify exactly how their product should be sold.

    Once the asset has been created, the developer can then use her private key to digitally sign the asset:

    payswarm.sign(asset, {
      publicKeyId: publicKey.id,
      privateKeyPem: privateKey.privateKeyPem
    }, function(err, signedAsset) {
      // do something with the signed asset
    });

    Digitally signing the asset ensures that no one can change any of the information associated with it. This is important because, at a minimum, a content creator wouldn’t want to be removed from the list of people who should be paid when the asset is sold. The digital signature also guarantees, to a buyer, that the content creator did in fact describe the asset and its sale restrictions as seen.

    The next step in preparing the asset for sale is to create a special identifier for the asset so that it can be accurately referenced by the listing. This identifier is called a cryptographic hash and is generated using the payswarm.js library’s hash() function:

    // generate a hash for the signed asset
    payswarm.hash(signedAsset, function(err, assetHash) {
      // do something with the signed asset hash
    });

    Once we have the signed asset and the signed asset hash, we can create the listing that will be used to purchase the asset.

    Creating a Listing

    As mentioned earlier in this article, a listing is a description of the terms under which an asset is offered for sale. A listing, like an asset, is expressed in JSON-LD. The listing below specifies which license to associate with the asset being sold as well as who should get paid for the sale of the asset. It also specifies restrictions on certain payees, such as how much a PaySwarm Authority can charge for processing a payment. Pay particular attention to the comments above each line as they explain what the line does:

    // create the listing
    var listing = {
      // the @context is a hint to a JSON-LD processor on how to interpret the 
      // key-value pairs in the document
      '@context': 'https://w3id.org/payswarm/v1',
      // this is the identifier for the listing
      id: 'http://listings.dev.payswarm.com/mozhacks/html5-me-song#listing',
      type: ['Listing'],
      // the identity offering the item for sale is The WebDevs
      vendor: 'https://dev.payswarm.com/i/the-webdevs',
      payee: [{
        type: 'Payee',
        // payment should be deposited into this financial account
        destination: 'https://dev.payswarm.com/i/the-webdevs/accounts/royalties',
        // this is used to determine how fees are applied to the final price
        payeeGroup: ['vendor'],
        // the next 4 lines: Sell the song for $1.00
        payeeRateType: 'FlatAmount',
        payeeRate: '1.00',
        currency: 'USD',
        payeeApplyType: 'ApplyExclusively',
        // this should be displayed for the line item in the digital receipt
        comment: 'Payment to The Webdevs for creating the HTML5 Me, Baby song'
      }],
      // the next 6 lines: The payment processor cannot take more than 5% of
      // the total sale price.
      payeeRule : [{
        type: 'PayeeRule',
        payeeGroupPrefix: ['authority'],
        payeeRateType: 'Percentage',
        maximumPayeeRate: '5',
        payeeApplyType: 'ApplyInclusively'
      }],
      // this is the ID of the asset being sold
      asset: 'http://listings.dev.payswarm.com/mozhacks/html5-me-song#asset',
      assetHash: assetHash,
      // this is the license that should be associated with the asset upon sale
      license: 'https://w3id.org/payswarm/licenses/personal-use',
      licenseHash: 'urn:sha256:' +
        'd9dcfb7b3ba057df52b99f777747e8fe0fc598a3bb364e3d3eb529f90d58e1b9',
      // the offer of sale is only valid between these two times
      validFrom: payswarm.w3cDate(validFrom),
      validUntil: payswarm.w3cDate(validUntil)
    };

    The code above states that the song HTML5 Me, Baby is for sale for $1.00 and a payment processor can’t charge more than 5% of the total sale price in transaction processing fees. The song is licensed for personal use, with the full text of the license available at the provided URL. Once the listing has been created, it must be digitally signed:

    payswarm.sign(listing, {
      publicKeyId: cfg.publicKey.id,
      privateKeyPem: cfg.publicKey.privateKeyPem
    }, function(err, signedListing) {
      // do something with the signed listing
    });

    The listing is digitally signed for the same reason that the asset is: to prevent tampering and for non-repudiation. Once both the asset and the listing are signed, they are ready to be published. This could be done by publishing them as two different documents or as a single document. The easiest way to publish them as a single document in JSON-LD is to use the ‘@graph’ keyword, which essentially states that you want to combine two independent objects into the same JSON-LD document.

    var assetAndListing = {
      '@context': 'https://w3id.org/payswarm/v1',
      '@graph': [signedAsset, signedListing]
    };

    Publishing an Asset and Listing

    The final step in the publication process is to take the signed asset and listing document and publish it to the Web. Since PaySwarm is decentralized, we can publish our signed asset and listing to any website. Since the assets are digitally signed, the website doesn’t have to be protected by Transport Layer Security (TLS), more commonly known as HTTPS. The digital signature guarantees that no one can modify the data without invalidating the signature on the asset and listing. In the following example, we use the payswarm.js library’s postJsonLd() function to upload the asset and listing to a public PaySwarm listing service.

    var url = 'http://listings.dev.payswarm.com/mozhacks/html5-me-song';
    payswarm.postJsonLd(url, assetAndListing, function(err, result) {
      // if result is a 200, then your listing has been published
    });

    After the asset and listing have been uploaded, the asset can be purchased by any PaySwarm client. Note that while the asset and listing information was expressed as JSON-LD, it could have just as easily been published as HTML5+RDFa. PaySwarm Authorities are capable of interpreting both JSON-LD and RDFa. While we won’t go into the details in this blog post, a future blog post will address how to take the asset and listing Linked Data expressed above and publish it as HTML5+RDFa.

    Next: Purchasing an Asset

    This is the second article in a three part series on developing PaySwarm-aware Web applications to engage in commerce. The next article will explain how to purchase the asset that was created in this tutorial and retrieve the digital receipt of the sale.

  6. Geeksphone to start selling Firefox OS Developer Preview phones on April 23

    Mozilla, Geeksphone and Telefonica have been working together to create a Firefox OS developer preview phone, and we’re excited to say they will go on sale April 23rd. With early access to hardware, developers can test the capabilities of Firefox OS in a real environment with a mobile network and true hardware characteristics like the accelerometer and camera that are not easily tested on the Firefox OS Simulator. Plus, new hardware is fun to play with!

    Firefox OS Phones Up

    Firefox OS Phones Up! Photo by Mark Coggins

    The Firefox OS Developer Preview Geeksphone devices have development versions of Firefox OS and are are unlocked so that developers can use them wherever they are in the world and they are updated regularly with the latest Firefox OS build. This will enable developers to explore the potential of the open Web and to bring the power of the Web to mobile for billions of users worldwide.

    Two developer devices

    Geeksphone has two Firefox OS developer devices for sale, the Keon and the Peak. Both phones can be bought online and shipped to just about anywhere in the world. The Keon has similar specifications as the actual target hardware that operators will ship in the phones they roll out to consumers later this year. The Peak offers a slightly more high-end device for developers wanting to experiment with apps for devices that might be commercially available in the future.

    The Keon is an orange (like Firefox!) phone with a 3.5″ screen Qualcomm 1Ghz processor and 512 MB of RAM. It’s available for €91 plus taxes, shipping and handling.

    The Peak has a slightly larger screen (4.3″) and a Qualcomm DualCore 1.2Ghz processor. It costs €149 plus taxes, shipping and handling.

    Both phones can be purchased directly from Geeksphone. Support and updates will also be provided directly by Geeksphone. Of course you can visit the Mozilla Developer Network for more information about Firefox OS and the Firefox Marketplace Developer Hub for information on how to build, publish and submit your open web app to Firefox Marketplace.

    Existing web apps

    Developers have already built and published awesome mobile web apps that you can check out today on the Developer Preview phone. We expect that these developer devices will inspire and enable even more. For some examples, you can check out the Marketplace for apps by indie developers that solve cool problems like:

    Or try these indie games or challenge yourself to write your own game:

    You can create an app for Firefox OS by making some small changes to your existing website. As Alexander Saladrigas said last weekend, “It was exciting to see Firefox OS in action on hardware that will be representative of the final commercial devices. I remember several devs pushing their web apps made for browsers or other platforms with the only addition of a tiny JSON manifest… and it worked flawlessly on the first try. I thought ‘Wow, that easy? Just as any web page?”

    Although, it’s great to have the actual hardware to test your apps, if you’re not in a position to purchase a Geeksphone at the moment, you can still try out Firefox OS and your app in several other ways:

    • Install Marketplace for Android on your Android phone. (Your friends and family can also do this – it’s as easy as installing an app, so they can try out your app too.)
    • Use the browser-based Firefox OS Simulator to view and test your mobile app on the desktop.
    • Install Firefox OS on your own hardware.

    Why develop an app for Firefox OS?

    • Keep the web open. Support the open web and help make sure the power of the web is available to everyone – even on mobile devices.
    • Simplicity. Develop on a single technology stack (HTML5/CSS/JavaScript/new WebAPIs) and deliver across the web and devices.
    • Freedom. You’re not locked in to a vendor-controlled ecosystem. You can distribute your app through the Firefox Marketplace, your own website, or any other store based on Mozilla’s open app store technology.

    If you have any more questions, please read the Firefox OS Developer Preview. Below is also a helpful FAQ on Geeksphone.

    We look forward to seeing what awesome apps developers make for the mobile open web. Happy hacking!

    Geeksphone FAQ:

    Q. What are you announcing today?

    A. We’re announcing the availability of two Firefox OS developer preview devices manufactured by Geeksphone and available for purchase at www.geeksphone.com. These devices allow developers to test the capabilities of Firefox OS in a real environment, testing characteristics such as real performance and interaction with the mobile network.

    Q. What are the device specs and how much will each cost?

    A. The Keon is equipped with a Cortex-A5 1Ghz processor, 3.5 inch multi-touch screen, tri-band UMTS/HSPA, 4GB ROM, 512 MB RAM and a long-lasting 1580 mAh battery. It will cost 91 € without VAT or shipping.

    The Peak is equipped with a 1.2 GHz dual-core Qualcomm 8225 chipset, 4.3-inch qHD IPS screen, 8 Mpx back camera and 2 Mpx front camera, as well as tri-band UMTS/HSPA and 1800 mAh battery. It will cost 149 € without VAT or shipping.

    Q. Why are there two devices?

    A. The Keon has similar specifications to the actual target hardware that operators will ship in the phones they roll out to consumers later this year. The Peak offers a slightly more high-end device for developers wanting to experiment with apps for devices that might be commercially available in the future.

    Q. Will Geeksphone ship to any country?

    A. Yes.

    Q. Who is Geeksphone?

    A. Geeksphone is a Spanish company dedicated to designing and manufacturing latest generation smartphones. It was formed in 2009 and was the first European company to develop a smartphone featuring Android OS.

    Q. What is Telefónica and Mozilla’s involvement?

    A. Telefónica and Mozilla worked closely with Geeksphone to make it possible to manufacture these developer test units.

    Q. Why do you need these devices?

    A. Making preview developer devices available is crucial to ensure a rich ecosystem is ready when handsets launch for the mass market. The Geeksphone devices will allow developers to test the capabilities of Firefox OS in a real environment beyond the facilities provided by current emulators. It will be possible to test some characteristics like real performance and interaction with the mobile network.

    Q. Are these the first ever Firefox OS devices?

    A. Through the development of the project Firefox OS has been ported onto a number of different devices from different OEMs in order to test and demonstrate. This is the first time that developer handsets have been made available for developers working outside of the project to take away and test their applications. Today’s announcement does not represent a commercial launch for Firefox OS. These will take place later this year.

    Q. Can consumers get the Geeksphone handsets?

    A. These devices have not been designed for consumers and include pre-release development versions of Firefox OS. Although we know many people are excited to get their hands on Firefox OS, we would urge them to wait until commercial devices are ready and they will be able to get the full experience.

    Q: What version of Firefox OS is this?

    A: v1.0.1

    Q: How often does it update?

    A: The software will update every couple of weeks as new builds become available.

    Q: Is this feature complete or will anything be added before launch?

    A: This is a developer device with a developer build. New features, performance/stability enhancements will continue to be added on a regular basis. The software here is not necessarily 100% representative of what will ship into customer’s hands.

    Q: How can I test v2/1.1/what’s next?

    A: New releases will be automatically made available OTA (over the air) and developers who have a Geeksphone will be able to update to their build in order to test their apps.

  7. Detecting touch: it’s the ‘why’, not the ‘how’

    One common aspect of making a website or application “mobile friendly” is the inclusion of tweaks, additional functionality or interface elements that are particularly aimed at touchscreens. A very common question from developers is now “How can I detect a touch-capable device?”

    Feature detection for touch

    Although there used to be a few incompatibilities and proprietary solutions in the past (such as Mozilla’s experimental, vendor-prefixed event model), almost all browsers now implement the same Touch Events model (based on a solution first introduced by Apple for iOS Safari, which subsequently was adopted by other browsers and retrospectively turned into a W3C draft specification).

    As a result, being able to programmatically detect whether or not a particular browser supports touch interactions involves a very simple feature detection:

    if ('ontouchstart' in window) {
      /* browser with Touch Events
         running on touch-capable device */
    }

    This snippet works reliably in modern browser, but older versions notoriously had a few quirks and inconsistencies which required jumping through various different detection strategy hoops. If your application is targetting these older browsers, I’d recommend having a look at Modernizr – and in particular its various touch test approaches – which smooths over most of these issues.

    I noted above that “almost all browsers” support this touch event model. The big exception here is Internet Explorer. While up to IE9 there was no support for any low-level touch interaction, IE10 introduced support for Microsoft’s own Pointer Events. This event model – which has since been submitted for W3C standardisation – unifies “pointer” devices (mouse, stylus, touch, etc) under a single new class of events. As this model does not, by design, include any separate ‘touch’, the feature detection for ontouchstart will naturally not work. The suggested method of detecting if a browser using Pointer Events is running on a touch-enabled device instead involves checking for the existence and return value of navigator.maxTouchPoints (note that Microsoft’s Pointer Events are currently still vendor-prefixed, so in practice we’ll be looking for navigator.msMaxTouchPoints). If the property exists and returns a value greater than 0, we have touch support.

    if (navigator.msMaxTouchPoints > 0) {
      /* IE with pointer events running
         on touch-capable device */
    }

    Adding this to our previous feature detect – and also including the non-vendor-prefixed version of the Pointer Events one for future compatibility – we get a still reasonably compact code snippet:

    if (('ontouchstart' in window) ||
         (navigator.maxTouchPoints > 0) ||
         (navigator.msMaxTouchPoints > 0)) {
          /* browser with either Touch Events of Pointer Events
             running on touch-capable device */
    }

    How touch detection is used

    Now, there are already quite a few commonly-used techniques for “touch optimisation” which take advantage of these sorts of feature detects. The most common use cases for detecting touch is to increase the responsiveness of an interface for touch users.

    When using a touchscreen interface, browsers introduce an artificial delay (in the range of about 300ms) between a touch action – such as tapping a link or a button – and the time the actual click event is being fired.

    More specifically, in browsers that support Touch Events the delay happens between touchend and the simulated mouse events that these browser also fire for compatibility with mouse-centric scripts:

    touchstart > [touchmove]+ > touchend > delay > mousemove > mousedown > mouseup > click

    See the event listener test page to see the order in which events are being fired, code available on GitHub.

    This delay has been introduced to allow users to double-tap (for instance, to zoom in/out of a page) without accidentally activating any page elements.

    It’s interesting to note that Firefox and Chrome on Android have removed this delay for pages with a fixed, non-zoomable viewport.

    <meta name="viewport" value="... user-scalable = no ...">

    See the event listener with user-scalable=no test page, code available on GitHub.

    There is some discussion of tweaking Chrome’s behavior further for other situations – see issue 169642 in the Chromium bug tracker.

    Although this affordance is clearly necessary, it can make a web app feel slightly laggy and unresponsive. One common trick has been to check for touch support and, if present, react directly to a touch event (either touchstart – as soon as the user touches the screen – or touchend – after the user has lifted their finger) instead of the traditional click:

    /* if touch supported, listen to 'touchend', otherwise 'click' */
    var clickEvent = ('ontouchstart' in window ? 'touchend' : 'click');
    blah.addEventListener(clickEvent, function() { ... });

    Although this type of optimisation is now widely used, it is based on a logical fallacy which is now starting to become more apparent.

    The artificial delay is also present in browsers that use Pointer Events.

    pointerover > mouseover > pointerdown > mousedown > pointermove > mousemove > pointerup > mouseup > pointerout > mouseout > delay > click

    Although it’s possible to extend the above optimisation approach to check navigator.maxTouchPoints and to then hook up our listener to pointerup rather than click, there is a much simpler way: setting the touch-action CSS property of our element to none eliminates the delay.

    /* suppress default touch action like double-tap zoom */
    a, button {
      -ms-touch-action: none;
          touch-action: none;
    }

    See the event listener with touch-action:none test page, code available on GitHub.

    False assumptions

    It’s important to note that these types of optimisations based on the availability of touch have a fundamental flaw: they make assumptions about user behavior based on device capabilities. More explicitly, the example above assumes that because a device is capable of touch input, a user will in fact use touch as the only way to interact with it.

    This assumption probably held some truth a few years back, when the only devices that featured touch input were the classic “mobile” and “tablet”. Here, touchscreens were the only input method available. In recent months, though, we’ve seen a whole new class of devices which feature both a traditional laptop/desktop form factor (including a mouse, trackpad, keyboard) and a touchscreen, such as the various Windows 8 machines or Google’s Chromebook Pixel.

    As an aside, even in the case of mobile phones or tablets, it was already possible – on some platforms – for users to add further input devices. While iOS only caters for pairing an additional bluetooth keyboard to an iPhone/iPad purely for text input, Android and Blackberry OS also let users add a mouse.

    On Android, this mouse will act exactly like a “touch”, even firing the same sequence of touch events and simulated mouse events, including the dreaded delay in between – so optimisations like our example above will still work fine. Blackberry OS, however, purely fires mouse events, leading to the same sort of problem outlined below.

    The implications of this change are slowly beginning to dawn on developers: that touch support does not necessarily mean “mobile” anymore, and more importantly that even if touch is available, it may not be the primary or exclusive input method that a user chooses. In fact, a user may even transition between any of their available input methods in the course of their interaction.

    The innocent code snippets above can have quite annoying consequences on this new class of devices. In browsers that use Touch Events:

    var clickEvent = ('ontouchstart' in window ? 'touchend' : 'click');

    is basically saying “if the device support touch, only listen to touchend and not click” – which, on a multi-input device, immediately shuts out any interaction via mouse, trackpad or keyboard.

    Touch or mouse?

    So what’s the solution to this new conundrum of touch-capable devices that may also have other input methods? While some developers have started to look at complementing a touch feature detection with additional user agent sniffing, I believe that the answer – as in so many other cases in web development – is to accept that we can’t fully detect or control how our users will interact with our web sites and applications, and to be input-agnostic. Instead of making assumptions, our code should cater for all eventualities. Specifically, instead of making the decision about whether to react to click or touchend/touchstart mutually exclusive, these should all be taken into consideration as complementary.

    Certainly, this may involve a bit more code, but the end result will be that our application will work for the largest number of users. One approach, already familiar to developers who’ve strived to make their mouse-specific interfaces also work for keyboard users, would be to simply “double up” your event listeners (while taking care to prevent the functionality from firing twice by stopping the simulated mouse events that are fired following the touch events):

    blah.addEventListener('touchend', function(e) {
      /* prevent delay and simulated mouse events */
      e.preventDefault();
      someFunction()
    });
    blah.addEventListener('click', someFunction);

    If this isn’t DRY enough for you, there are of course fancier approaches, such as only defining your functions for click and then bypassing the dreaded delay by explicitly firing that handler:

    blah.addEventListener('touchend', function(e) {
      /* prevent delay and simulated mouse events */
      e.preventDefault();
      /* trigger the actual behavior we bound to the 'click' event */
      e.target.click();
    })
    blah.addEventListener('click', function() {
      /* actual functionality */
    });

    That last snippet does not cover all possible scenarios though. For a more robust implementation of the same principle, see the FastClick script from FT labs.

    Being input-agnostic

    Of course, battling with delay on touch devices is not the only reason why developers want to check for touch capabilities. Current discussions – such as this issue in Modernizr about detecting a mouse user – now revolve around offering completely different interfaces to touch users, compared to mouse or keyboard, and whether or not a particular browser/device supports things like hovering. And even beyond JavaScript, similar concepts (pointer and hover media features) are being proposed for Media Queries Level 4. But the principle is still the same: as there are now common multi-input devices, it’s not straightforward (and in many cases, impossible) anymore to determine if a user is on a device that exclusively supports touch.

    The more generic approach taken in Microsoft’s Pointer Events specification – which is already being scheduled for implementation in other browser such as Chrome – is a step in the right direction (though it still requires extra handling for keyboard users). In the meantime, developers should be careful not to draw the wrong conclusions from touch support detection and avoid unwittingly locking out a growing number of potential multi-input users.

    Further links

  8. A Social-aware Dashboard Experience with Gecko in Walls

    This article covers a Web project that rethinks how TV appliances can be used in public spaces for real-time content and interaction with social networks. Tela Social is a powered by Mozilla system application that runs in Linux appliances and creates a visual experience that presents custom and interactive content with real time data using the Web. It’s different of a standard kiosk and far from the personal browser experience because it’s not tailored for an individual. Instead, it explores how online data can be used to provide impact to users in common areas. In the following sections, you will read about the general system’s architecture; a special focus is given to how CSS3 and JavaScript is used to support the user experience with engaging animated effects.

    First, boot to the Web

    The application starts following the Linux system’s reboot. A monitor process is launched and starts to check whether the Gecko-based client is running or not. If not running, it starts the main process: a Gecko-based single window browsing engine with no toolbars in full screen.

    The following image shows an overview of the web stack infrastructure that is launched. The web application sits above the engine in a similar way to applications such as Firefox or other Powered by Mozilla apps using Gecko.

    Gecko architecture overview

    Online and Offline

    Instead of loading a remote web page, most of the resources are loaded from a local web server written in JavaScript using NodeJS — TelaSocial Mediator. This system is also monitored in order to reduce problems in the case of script execution failures.

    Once the web app comes from a local web server, a main HTML layout may bring inner HTML components that are loaded within iframes. This degree of separation exists to help developers to create isolated components in a standard test environment: all the components are made of plain pages. As part of this project, an experimental project script was created to help developers to quickly deploy new grid layouts — Gridtype.JS can take strings as arguments and can generate a grid layout that is tableless. The following example shows how to generate a grid of DIVs:

    grid('abcdabee',4);

    The above “string” specification will generate the following layout:

    Layout design

    Free of pop-ups or unwanted desktop interfaces

    There are many systems using online data to display information in TV appliances. Some of these systems are applications launched on top of the operating system graphic user interface. The following photos were taken from airports in 2012 in Brazil. These are a few of many examples of problems with unwanted user interface elements that are displayed on top of systems using operating system desktops. For this reason, and also the principle of simplicity and cost reduction, the designed approach was to launch Gecko from the basic X Window infra structure. Such approach ensures that no other visual applications are running at the same time, thus creating an improved quality experience without those unwanted pop-ups.

    Picture shows an Operating System update pop up which is common in airports in Brazil

    Picture shows an Operating System update pop up which is common in airports in Brazil

    Routing Gecko pop-ups into frames

    While OS desktop pop-ups are out of the scene, yet there are some conditions where Gecko used to display pop-ups to alert the user. The solution to this problem was to use Gecko’s preferences API and ask Gecko to display network error messages inline. With this, all errors are displayed in the iframe which is great because it is possible to track the errors and signal application logic outside the Gecko process. As an example, we can monitor the output console and change the layout depending on network error conditions. So, for example, if a weather channel frames brings a network error, the system should be able to launch an alternate layout.

    Animation library with zoom and pan

    The above elements are essential to keep the level of quality that is expected in enterprise environments. With this functional base, it’s when things can be creative and the web developer mindset rules. HTML5 and modern effects, provided by CSS3, can be used to help understand and improve the user experience in this scenario that is not the same of a desktop or a mobile.

    To help the creation of content, a small JavaScript library was also produced as part of this project. The main goal of this library is to help the creation of visual narratives out of HTML pages. The TagVisor library reads a list of <li> elements which tells how CSS3 and other transformation effects are applied with time-referenced data:

    <ul id="animation" style="display: none;">
       <li data-target="slidea" data-time="1s"
          data-effect="scalefit" data-duration="3s">
       </li>
       <li data-target="slideb" data-time="6s" 
          data-effect="scalefit" data-duration="3s">
       </li>
       <li data-target="slidec" data-time="12s"
          data-effect="scalefit" data-duration="3s">
       </li>
    </ul>

    The above script dispatches transformation functions that can modify the document using JavaScript for DOM transformations and DOM style changes that will take care of the visual effects. These effects are common in many systems, including well known JS-based solutions such as Impress.JS. However TagVisor comes with tailored functions that are very important for the scenarios in digital signage. One difference is that the script allows modifications to be performed within iframes which is good for cases where many separated HTML resources are loaded in a grid arrangement.

    The zoom and animation metaphor does a lot of the heavy work to ensure a level of smoothness in animation which is expected by users in front of a TV panel. Some effects can also be combined in time in order to produce engaging visual narratives as shown in the TagVisor video demonstration.

    Web-driven, for adaptation

    User experience is of major importance and a main reason for the use of a web-based infrastructure. Such model brings a level of dynamism supporting organisations who can tailor the system with custom data-sources using web services formats such as JSON or RSS. This approach has allowed us to test the screens with a variety of online sources; and to learn how the stream of web events can impact users in local organisations.

    The following videos are examples of systems with Tela Social. The first video refers to the system at a major science park in Brazil (Press release in Portuguese). It’s an example with a variety of content areas that are tied to a variety of sources: from journalists to editors plus open channels using social networks. The second video shows an example where the TV appliance is set in vertical position.

    People recognise that using data from events plus local interest content can build local participation. For most people, TV content is something far away and not tailored to their local community interests. To make things different, we have even used TVs in the vertical position to make a point that the whole experience was flipped and that content and interaction is bottom up.

    The objective of the project is to develop web-based solutions that can be useful in spaces and bring social-aware experiences that are positive to local communities . While social features can be used in the mobile and on desktop, we believe that our approach can help communities because it extends the physical environment — it creates a social reflection to the environment. It’s a chance for custom web experiences that build awareness about contributions made by local communities and real-time data of interest. This approach also explores challenges in user interfaces since it engages people to interact in new ways: it’s not a direct touch like standard kiosks. It’s the web in the first place and opportunities for interaction are explored based on live data.

  9. Serving Backbone for Robots & Legacy Browsers

    I like the Single Page Application model and Backbone.js, because I get it. As a former Java developer, I am used to object oriented coding and events for messaging. Within our HTML5 consultancy, SC5, Backbone has become almost a synonym for single page applications, and it is easy to move between projects because everybody gets the same basic development model.

    We hate the fact that we need to have server side workarounds for robots. Making applications crawlable is very reasonable business-wise, but ill-suited for the SPA model. Data-driven single page applications typically get only served a HTML page skeleton, and the actual construction of all the visual elements is done in browser. Any other way would easily lead into double code paths (one on a browser, one on a server). Some have even concerned on giving up the SPA model and moving the logic and representation back to the server.

    Still, we should not let the tail wag the dog. Why sacrifice the user experience of 99,9% of the users for the sake of the significant 0.1%? Instead, for such low traffic, a better suited solution would be to create a server side workaround.

    Solving the Crawling Problem with an App Proxy

    The obvious solution for the problem is running the same application code at the both ends. Like in the digital television transformation, a set-top box would fill in the gap of legacy televisions by crunching the digital signal into analog form. Correspondingly, a proxy would run the application server side and serve the resulting HTML back to the crawlers. Smart browsers would get all the interactive candy, whereas crawlers and legacy browsers would just get the pre-processed HTML document.

    Proxy pattern explained through a TV set metaphor

    Thanks to node.js, JavaScript developers have been able to use their favourite language on the both ends for some time already, and proxy-like solutions have become a plausible option.

    Implementing DOM and Browser APIs on the Server

    Single page applications typically heavily depend on DOM manipulation. Typical server applications combine several view templates into a page through concatenation, whereas Backbone applications append the views into DOM as new elements. Developer would either need to emulate DOM on the server side, or build an abstraction layer that would permit using DOM on the browser and template concatenation on the server. DOM can either be serialized into a HTML document or vice versa, but these techniques cannot be easily mixed runtime.

    A typical Backbone application talks with the browser APIs through several different layers – either by using Backbone or jQuery APIs, or accessing the APIs directly. Backbone itself has only minor dependencies to layers below – jQuery is used in DOM manipulation and AJAX requests, and application state handling is done using pushState.

    Sample Backbone layers

    Node.js has ready-made modules for each level of abstraction: JSDOM offers a full DOM implementation on the server-side, whereas Cheerio provides a jQuery API on top of a fake DOM with a better performance. Some of the other server-side Backbone implementations, like AirBnB Rendr and Backbone.LayoutManager, set the abstraction level to the level of Backbone APIs (only), and hide the actual DOM manipulation under a set of conventions. Actually, Backbone.LayoutManager does offer the jQuery API through Cheerio, but the main purpose of the library itself is to ease the juggling between Backbone layouts, and hence promote a higher level of abstraction.

    Introducing backbone-serverside

    Still, we went for our own solution. Our team is a pack of old dogs that do not learn new tricks easily. We believe there is no easy way of fully abstracting out the DOM without changing what Backbone applications essentially are. We like our Backbone applications without extra layers, and jQuery has always served us as a good compatibility layer to defend ourselves against browser differences in DOM manipulation. Like Backbone.LayoutManager, we choose Cheerio as our jQuery abstraction. We solved the Backbone browser API dependencies by overriding Backbone.history and Backbone.ajax with API compatible replacements. Actually, in the first draft version, these implementations remain bare minimum stubs.

    We are quite happy about the solution we have in the works. If you study the backbone-serverside example, it looks quite close to what a typical Backbone application might be. We do not enforce working on any particular level of abstraction; you can use either Backbone APIs or the subset of APIs that jQuery offers. If you want to go deeper, nothing stops from implementing server-side version of a browser API. Insuch cases, the actual server side implementation may be a stub. For example, needs touch event handling on the server?

    The current solution assumes a node.js server, but it does not necessarily mean drastic changes to an existing server stack. An existing servers for API and static assets can remain as-is, but there should be a proxy to forward the requests of dumb clients to our server. The sample application serves static files, API and the proxy from the same server, but they all could be decoupled with small modifications.

    backbone-serverside as a proxy

    Writing Apps That Work on backbone-serverside

    Currently the backbone-serverside core is a bare minimum set of adapters to make Backbone run on node.js. Porting your application to run on server may require further modifications.

    If the application does not already utilise a module loader, such as RequireJS or Browserify, you need to figure out on how to load the same modules on the server. In our example below, we use RequireJS and need a bit JavaScript to use Cheerio instead of vanilla jQuery on the server. Otherwise we are pretty able to use the same stack we typically use (jQuery, Underscore/Lo-Dash, Backbone and Handlebars.When choosing the modules, you may need to limit to the ones that do not play with Browser APIs directly, or be prepared to write a few stubs by yourself.

    // Compose RequireJS configuration run-time by determining the execution
    // context first. We may pass different values to browser and server.
    var isBrowser = typeof(window) !== 'undefined';
     
    // Execute this for RequireJS (client or server-side, no matter which)
    requirejs.config({
     
        paths: {
            text: 'components/requirejs-text/text',
            underscore: 'components/lodash/dist/lodash.underscore',
            backbone: 'components/backbone/backbone',
            handlebars: 'components/handlebars/handlebars',
            jquery: isBrowser ? 'components/jquery/jquery' : 'emptyHack'
        },
     
        shim: {
            'jquery': {
                deps: ['module'],
                exports: 'jQuery',
                init: function (module) {
                    // Fetch the jQuery adapter parameters for server case
                    if (module && module.config) {
                        return module.config().jquery;
                    }
     
                    // Fallback to browser specific thingy
                    return this.jQuery.noConflict();
                }
            },
            'underscore': {
                exports: '_',
                init: function () {
                    return this._.noConflict();
                }
            },
            'backbone': {
                deps: ['underscore', 'jquery'],
                exports: 'Backbone',
                init: function (_, $) {
                    // Inject adapters when in server
                    if (!isBrowser) {
                        var adapters = require('../..');
                        // Add the adapters we're going to be using
                        _.extend(this.Backbone.history,
                            adapters.backbone.history);
                        this.Backbone.ajax = adapters.backbone.ajax;
                        Backbone.$ = $;
                    }
     
                    return this.Backbone.noConflict();
                }
            },
            'handlebars': {
                exports: 'Handlebars',
                init: function() {
                    return this.Handlebars;
                }
            }
        },
     
        config: {
            // The API endpoints can be passed via URLs
            'collections/items': {
                // TODO Use full path due to our XHR adapter limitations
                url: 'http://localhost:8080/api/items'
            }
        }
    });

    Once the configuration works alright, the application can be bootstrapped normally. In the example, we use Node.js express server stack and pass specific request paths to Backbone Router implementation for handling. When done, we will serialize the DOM into text and send that to the client. Some extra code needs to be added to deal with Backbone asynchronous event model. We will discuss that more thoroughly below.

    // URL Endpoint for the 'web pages'
    server.get(/\/(items\/\d+)?$/, function(req, res) {
        // Remove preceeding '/'
        var path = req.path.substr(1, req.path.length);
        console.log('Routing to \'%s\'', path);
     
        // Initialize a blank document and a handle to its content
        //app.router.initialize();
     
        // If we're already on the current path, just serve the 'cached' HTML
        if (path === Backbone.history.path) {
            console.log('Serving response from cache');
            res.send($html.html());
        }
     
        // Listen to state change once - then send the response
        app.router.once('done', function(router, status) {
            // Just a simple workaround in case we timeouted or such
            if (res.headersSent) {
                console.warn('Could not respond to request in time.');
            }
     
            if (status === 'error') {
                res.send(500, 'Our framework blew it. Sorry.');
            }
            if (status === 'ready') {
                // Set the bootstrapped attribute to communicate we're done
                var $root = $html('#main');
                $root.attr('data-bootstrapped', true);
     
                // Send the changed DOM to the client
                console.log('Serving response');
                res.send($html.html());
            }
        });
     
        // Then do the trick that would cause the state change
        Backbone.history.navigate(path, { trigger: true });
    });

    Dealing with Application Events and States

    Backbone uses an asynchronous, event-driven model for communicating between the models views and other objects. For an object oriented developer, the model is fine, but it causes a few headaches on node.js. After all, Backbone applications are data driven; pulling data from a remote API endpoint may take seconds, and once it eventually arrives, the models will notify views to repaint themselves. There is no easy way to know when all the application DOM manipulation is finished, so we needed to invent our own mechanism.

    In our example we utilise simple state machines to solve the problem. Since the simplified example does not have a separate application singleton class, we use a router object as the single point of control. Router listens for changes in states of each view, and only notifies the express server about readiness to render when all the views are ready. In the beginning of the request, router resets the view states to pending and does not notify the browser or server until it knows all the views are done. Correspondingly, the views do not claim to be done until they know they are fed with valid data from their corresponding model/collection. The state machine is simple and can be consistently applied throughout the different Backbone objects.

    Activity diagram of a Backbone app event flow

    Beyond the Experimental Hack

    The current version is still experimental work, but it proves Backbone applications can happily live on the server without breaking Backbone APIs or introducing too many new conventions. Currently in SC5 we have a few projects starting that could utilise the this implementation, so we will
    continue the effort.

    We believe the web stack community benefits from this effort, thus we have published the work in GitHub. It is far from being finished and we would appreciate all community continueributions in the forms of ideas and code. Share the love, criticism and all in between: @sc5io #backboneserverside.

    Particularly,we plan to change and hope to get contributions for the following:

    • The current example will likely misbehave on concurrent requests. It shares a single DOM representation for all the ongoing requests, which can easily mess up each other.
    • The state machine implementation is just one idea on how to determine when to serialize the DOM back to the client. It likely can be drastically simplified for most use cases, and it is quite possible to find a better generic solution.
    • The server-side route handling is naive. To emphasize that only the crawlers and legacy browsers might need server-side rendering, the sample could use projects like express-device to detect if we are serving a legacy browser or a server.
    • The sample application is a very rudimentary master-details view application and will not likely cause any wow effect. It needs a little bit of love.

    We encourage you to fork the repository and start from modifying the example for your needs. Happy Hacking!

  10. Gameleon and the map editor – a WebFWD project

    More than 9 months ago, we were working on a web game, having all the nice HTML5 stuff like Canvas, WebSocket, CSS3. We were playing a lot with experimental code in NodeJS and Redis. We had all the nice scripts and plugins and quite a good architecture to make the game possible.

    We lacked one thing though: a powerful editor. Since we had 8 years of nothing but web development experience, we were keen on making this web too. We didn’t like Flash though or anything which isn’t a web standard or open technology, because it was restricting us from using what we made on all the devices we had through the office, in the same way (tablets, phones, laptops, desktops).

    Creating an editor

    So, we’ve started making Gameleon for Shay, our game architect. He did quite a lot of Dungeons and Dragons and played with many of the RPG editors out there. We thought that he was good just like that, without any programming knowledge, and we wanted to give him the means to make anything in our game, without coming to us.

    The first thing we made was the map editor. One thing was sure about this: we didn’t want to have any kind of limitations, such as tiles. What we love doing is drawing the maps ourselves, in any way we see fit. The one thing you can never know about a random picture is where the obstacles are. For that, we made a polygon editing tool, which can define just that. It is like a mesh applied on top of the map, giving it the logic for collision detection later.

    Probably this video demonstrating how a map is built will be of more help:

    Processing a map

    In this article i’ll try to discuss a bit about how the map is processed and turned into a walkable, obstacle friendly surface.

    When it comes to making a friendly way to define areas, using vectors is the way to go, as you probably saw in the above video.

    A map is defined by vertices and points. They are sent to the server via WebSocket, in JSON format.

    The struggle when having a good map is to have that good mixture between freedom to create as much content as you want, yet be able to determine what surface is an obstacle and have a very fast collision detection system and path finding.

    image

    The best mix of these two we’ve found to be in a grid. Using A* and QuadTree to determine the shortest route and the collisions between objects, no matter what size, became a lot simpler. By the way, all objects defined on a map, are treated as circles. When we determine if an object collides with another (in a combat situation for instance), we can make one of the objects move to the nearest empty area, while still being in range of the target.

    So, this is why we are going to transform the vector map we’ve just received, into a grid, having a square of the size of 8 x 8 points. Experimentally, we’ve determined it is a small enough square to have a small number of collisions, and yet be effective when searching across long distances (for instance, searching for the shortest path between two points A and B on a map of 3200 x 2000 points).

    Determining the squares

    To determine the squares a polygon is going to cover, we use a brute force technique. Yes, it may sound crude, but it is quite effective. First, we determine the rectangle covered by the polygon.

    enhance.prototype._determineRectangle = function( points, poly )
    {
        var minX = null, minY = null, maxX = null, maxY = null;
     
        for(var j=0;j<poly.coords.length;j++)
        {
            var currentPoint = points[ poly.coords[j] ];
     
            if( minX == null || currentPoint[ 0 ] < minX )
            {
                minX = currentPoint[0];
            }
     
            if( maxX == null || currentPoint[ 0 ] > maxX )
            {
                maxX = currentPoint[0];
            }
     
            if( minY == null || currentPoint[ 1 ] < minY )
            {
                minY = currentPoint[1];
            }
     
            if( maxY == null || currentPoint[ 1 ] > maxY )
            {
                maxY = currentPoint[1];
            }
        }
     
        return { minX: minX, minY: minY, maxX: maxX, maxY: maxY };
    }

    image

    Checking point positions

    Once we have that, we start going through each point of that rectangle and check if the point is inside or outside the polygon. The theory behind this is to draw a horizontal line passing through that point and check the number of intersections with the polygon’s vertices. If the number of intersections is odd, then the point is outside. If the number is even, then it is inside.

    enhance.prototype._pointInPolygon = function( x, y, poly, points )
    {
        var j = poly.coords.length - 1, oddNodes = false;
     
        for(var i = 0;i < poly.coords.length; i++)
        {
            var pointI = poly.coords[i],
                pointJ = poly.coords[j],
                _pointIY = points[ pointI ][1],
                _pointJY = points[ pointJ ][1],
                _pointIX = points[ pointI ][0],
                _pointJX = points[ pointJ ][0];
     
            if(
                _pointIX == x &&
                _pointIY == y
            )
            {
                return true;
            }
     
            if(
                ( _pointIY < y && _pointJY >= y ) ||
                ( _pointJY < y && _pointIY >= y )
            )
            {   
                if(
                    _pointIX + ( y - _pointIY ) / ( _pointJY - _pointIY ) * ( _pointJX - _pointIX ) < x
                )
                {
                    oddNodes = !oddNodes;
                }
            }
     
            j = i;
        }
     
        return oddNodes;
    }

    This way, we mark the walkable and non-walkable areas of the map. However, there are those special situations when you want to mark an area as walkable or non-walkable dynamically.

    image

    Say you have some debris and you don’t want that area to be walkable, but once the debris are destroyed, that area has to be changed. So, we keep in a separate vector, the actual points covered by each polygon.

    Setting names

    In the map editor, you are being given the ability to name polygons, both for esthetic purposes – to notify the player that he is entering “The Killing Fields” for instance, and to lookup via scripting.

    The scripting names are automatically given – ZP01, ZP02, etc. – to ensure their unique name.

    In the script editor, you can use an action named setWalkableArea, and send as parameter the polygon name. When the action is executed, the server will broadcast to every member on the map, the points which are suppose to change their state, thus updating the map grid with ease. No additional processing will be done.

    image

    Say you attach this to the event of an object being destroyed, which was right on top of that area. This would create the illusion that the object itself was an obstacle and that it is now removed.

    Neat, isn’t it?

    Part of Gameleon

    The code above is part of the editor and this coding standard can be found throughout the entire Gameleon code.

    Hope you enjoyed this short intro into how we see maps and games being created. If you want to know more, have a look at Gameleon and follow us on twitter: @gameleonMain.

    The complete source code is available on GitHub.