Mozilla

Featured Articles

Sort by:

View:

  1. Firefox OS, Animations & the Dark Cubic-Bezier of the Soul

    I’ve been using Firefox OS daily for a couple of years now (wow, time flies!). While performance has steadily improved with efforts like Project Silk, I’ve often noticed delays in the user interface. I assumed the delays were because the hardware was well below the “flagship” hardware I’ve become accustomed to with Android and iOS devices.

    Last year, I built Firefox OS for a Nexus 4 and started using that as my daily phone. Quickly I realized that even with better hardware, I sometimes had to wait on Firefox OS for basic interactions, even when the task wasn’t computationally intensive. I moved on to a Nexus 5 and then a Sony Z3 Compact, both with better specs than the Nexus 4, and experienced the same thing.

    Time passed. Frustration grew. Whispers of a nameless fear…

    Running the numbers

    While reading Ralph Thomas’s post about creating animations based on physical models, I wondered about the implementation of animations in Firefox OS, and how that might be involved in this problem. I performed an audit of the number of instances of different animations, grouped by their duration. I removed progress indicators and things like the boot shutdown animation. Here are the animation and transition durations in Firefox OS, grouped by duration, for transitional interactions like scaling, opening, closing and sliding:

    • 0.1s: 15
    • 0.2s: 57
    • 0.3s: 79
    • 0.4s: 40
    • 0.5s: 78
    • 0.6s: 8

    A couple of things stand out. First, we have a pretty wide distribution of animation durations. Second, the vast majority of the animations are more than 300ms long!

    In fact, in more than 80 animations we are making the user wait more than half a second. These slow animations are dragging us down, resulting in a poorer overall experience of Firefox OS.

    How did we get here?

    The Firefox OS UX and interaction designers didn’t huddle in a room and design each interaction to be intentionally slow. The engineers who implemented these animations didn’t ever think to themselves “this feels really responsive… let’s make it slower!”

    My theory is that interactions like these don’t feel slow while you’re designing and implementing them, because you’re working with a single interaction at a time. When designing and developing an animation, I look for fluidity of motion, the aesthetics of that single action and how the visual impact enhances the task at hand, and then I iterate on duration and effects until it feels right.

    We do have guidelines for responsiveness and user-perceived performance in Firefox OS, written up by Gordon Brander, which you can see in the screenshot below. (Click the image for a larger, more readable version.) However, those guidelines don’t cover the sub-second period between the initial perception of cause and effect and the next actionable state of the user interface.

    Screenshot 2015-04-18 09.38.10

    Users have an entirely different experience than we do as developers and designers. Users make their way through our animations while hurriedly sending a text message, trying to capture that perfect moment on camera, entering their username and password, or arduously uploading a bunch of images one at a time. People are trying to get from point A to point B. They want to complete a task… well, actually not just one: Smartphone users are trying to complete 221 tasks every day, according to a study in the UK last October by Tecmark. All those animations add up! I assert that the aggregate of those 203 animations in Gaia that are 300ms and longer contributes to the frustrating feeling of slowness I was experiencing before digging into this.

    Making it feel fast

    So I tested this theory, by changing all animation durations in Gaia to 200ms, as a starting point. The result? Firefox OS feels far more responsive. Moving through tasks and navigating around the OS felt quick but not abrupt. The camera snaps to readiness. Texting feels so much more fluid and snappy. Apps pop up, instead of slowly hauling their creaky bones out of bed. The Rocketbar gets closer to living up to its name (though I still think the keyboard should animate up while the bar becomes active).

    Here’s a demo of some of our animations side by side, before and after this patch:

    There are a couple of things we can do about this in Gaia:

    1. I filed a bug to get this change landed in Gaia. The 200ms duration is a first stab at this until we can do further testing. Better to err on the snappy side instead of the sluggish side. We’ve got the thumbs-up from most of the 16 developers who had to review the changes, and are now working with the UX team to sign off before it can land. Kevin Grandon helped by adding a CSS variable that we can use across all of Gaia, which will make it easier to implement these types of changes OS-wide in the future as we learn more.
    2. I’m working with the Firefox OS UX team to define global and consistent best-practices for animations. These guidelines will not be correct 100% of the time, but can be a starting point when implementing new animations, ensuring that the defaults are based on research and experience.
    If you are a Firefox OS user, report bugs if you experience anything that feels slow. By reporting a bug, you can make change happen and help improve the user experience for everyone on Firefox OS.

    If you are a developer or designer, what are your animation best-practices? What user feedback have you received on the animations in your Web projects? Let us know in the comments below!

  2. ES6 In Depth: An Introduction

    Welcome to ES6 In Depth! In this new weekly series, we’ll be exploring ECMAScript 6, the upcoming new edition of the JavaScript language. ES6 contains many new language features that will make JS more powerful and expressive, and we’ll visit them one by one in weeks to come. But before we start in on the details, maybe it’s worth taking a minute to talk about what ES6 is and what you can expect.

    What falls under the scope of ECMAScript?

    The JavaScript programming language is standardized by ECMA (a standards body like W3C) under the name ECMAScript. Among other things, ECMAScript defines:

    What it doesn’t define is anything to do with HTML or CSS, or the Web APIs, such as the DOM (Document Object Model). Those are defined in separate standards. ECMAScript covers the aspects of JS that are present not only in the browser, but also in non-browser environments such as node.js.

    The new standard

    Last week, the final draft of the ECMAScript Language Specification, Edition 6, was submitted to the Ecma General Assembly for review. What does that mean?

    It means that this summer, we’ll have a new standard for the core JavaScript programming language.

    This is big news. A new JS language standard doesn’t drop every day. The last one, ES5, happened back in 2009. The ES standards committee has been working on ES6 ever since.

    ES6 is a major upgrade to the language. At the same time, your JS code will continue to work. ES6 was designed for maximum compatibility with existing code. In fact, many browsers already support various ES6 features, and implementation efforts are ongoing. This means all your JS code has already been running in browsers that implement some ES6 features! If you haven’t seen any compatibility issues by now, you probably never will.

    Counting to 6

    The previous editions of the ECMAScript standard were numbered 1, 2, 3, and 5.

    What happened to Edition 4? An ECMAScript Edition 4 was once planned—and in fact a ton of work was done on it—but it was eventually scrapped as too ambitious. (It had, for example, a sophisticated opt-in static type system with generics and type inference.)

    ES4 was contentious. When the standards committee finally stopped work on it, the committee members agreed to publish a relatively modest ES5 and then proceed to work on more substantial new features. This explicit, negotiated agreement was called “Harmony,” and it’s why the ES5 spec contains these two sentences:

    ECMAScript is a vibrant language and the evolution of the language is not complete. Significant technical enhancement will continue with future editions of this specification.

    This statement could be seen as something of a promise.

    Promises resolved

    ES5, the 2009 update to the language, introduced Object.create(), Object.defineProperty(), getters and setters, strict mode, and the JSON object. I’ve used all these features, and I like what ES5 did for the language. But it would be too much to say any of these features had a dramatic impact on the way I write JS code. The most important innovation, for me, was probably the new Array methods: .map(), .filter(), and so on.

    Well, ES6 is different. It’s the product of years of harmonious work. And it’s a treasure trove of new language and library features, the most substantial upgrade for JS ever. The new features range from welcome conveniences, like arrow functions and simple string interpolation, to brain-melting new concepts like proxies and generators.

    ES6 will change the way you write JS code.

    This series aims to show you how, by examining the new features ES6 offers to JavaScript programmers.

    We’ll start with a classic “missing feature” that I’ve been eager to see in JavaScript for the better part of a decade. So join us next week for a look at ES6 iterators and the new for-of loop.

  3. Easier in-app payments with fxpay

    For developers building web applications on Firefox OS or Firefox Desktop, supporting payments is easy with Mozilla’s fxpay library. In addition to accepting credit cards, Mozilla’s payment system lets users charge purchases directly to their phone bill in many countries—making it ideal for mobile commerce.

    Since our first introduction to fxpay the library has received a lot of bug fixes and new features. Based on developer feedback, we also decided to offer a new interface supporting native promises (shimmed on older browsers) for flexibility and better error handling. This article explains how to retrieve products, process payments, and restore products from receipts.

    If you’ve already set up in-app payments using the mozPay API directly, consider porting to fxpay for the convenience of Mozilla-hosted products and additional features such as desktop payments. At the very least, please make sure your JWT libraries are patched for the latest security vulnerabilities.

    Let’s get started! After installing the fxpay library, you can begin testing it out with some fake products.

    fxpay.configure({fakeProducts: true});
    fxpay.getProducts()
      .then(function(products) {
        products.forEach(function(product) {
          addBuyButtonForProduct(product);
        });
      })
      .catch(function(error) {
        console.error('error getting products: ' + error);
      });
    

    This retrieves some pre-configured fake products that you can play around with. Once you’ve configured real products on the Firefox Marketplace Developer Hub, you can remove this configuration value to work with real products.

    In the example function called above, you could display a buy button per product like this:

    function addBuyButtonForProduct(product) {
      var button = document.createElement('button');
      button.textContent = 'Buy ' + product.name;
      button.addEventListener('click', function () {
     
        fxpay.purchase(product.productId)
          .then(function(purchasedProduct) {
            console.log('product purchased! ', 
                        purchasedProduct);
          })
          .catch(function(error) {
            console.error('error purchasing: ' + error);
          });
     
      });
      document.body.appendChild(button);
    }
    

    The fxpay library does all the payment processing behind the scenes using Mozilla’s web services so when the promise resolves, it’s safe to deliver the product. At this time, fxpay also installs a receipt on the user’s device. When the user returns to your app later on, you’ll want to check for any receipts so you can restore their purchases.

    Here’s a rewrite of the product fetching code to restore purchased products:

    fxpay.getProducts()
      .then(function(products) {
        products.forEach(function(product) {
        
          if (product.hasReceipt()) {
            product.validateReceipt()
              .then(function(restoredProduct) {
                console.log('restored product from receipt:', 
                            restoredProduct);
              })
              .catch(function(error) {
                console.error('error validating receipt: ' + 
                              error);
              });
          } else {
            addBuyButtonForProduct(product);
          }
        
        });
      });
    

    We’re hoping this new interface makes experimenting with in-app payments even easier than before. You never know what kind of business model will work in your app so why not try out some ideas?

    The complete usage guide to fxpay is here on MDN.

  4. Drag Elements, Console History, and more – Firefox Developer Edition 39

    Quite a few big new features, improvements, and bug fixes made their way into Firefox Developer Edition 39. Update your Firefox Developer Edition, or Nightly builds to try them out!

    Inspector

    The Inspector now allows you to move elements around via drag and drop. Click and hold on an element and then drag it to where you want it to go. This feature was added by contributor Mahdi Dibaiee.

    Back in Firefox 33, a tooltip was added to the rule view to allow editing curves for cubic bezier CSS animations. In Developer Edition 39, we’ve greatly enhanced the tooltip’s UX by adding various standard curves you can try right away, as well as cleaning up the overall appearance. This enhancement was added by new contributor John Giannakos.

    cubic

    The CSS animations panel we debuted in Developer Edition 37 now includes a time machine. You can rewind, fast forward, and set the current time of your animations.

    Console

    Previously, when the DevTools console closed, your past Console history was lost. Now, Console history is persisted across sessions. The recent commands you’ve entered will remain accessible in the next toolbox you open, whether it’s in another tab or after restarting Firefox. Additionally, we’ve added a clearHistory console command to reset the stored list of commands.

    The shorthand $_ has been added as an alias for the last result evaluated in the Console. If you evaluated an expression without storing the result to a variable (for example), you can use this as a quick way to grab the last result.

    We now format pseudo-array-like objects as if they were arrays in the Console output. This makes a pseudo-array-like object easier to reason about and inspect, just like a real array. This feature was added by contributor Johan K. Jensen.

    pseudo-array

    WebIDE and Mobile

    WiFi debugging for Firefox OS has landed. WiFi debugging allows WebIDE to connect to your Firefox OS device via your local WiFi network instead of a USB cable. We’ll discuss this feature in more detail in a future post.

    WebIDE gained support for Cordova-based projects. If you’re working on a mobile app project using Cordova, WebIDE now knows how to build the project for devices it supports without any extra configuration.

    Other Changes

    • Attribute changes only flash the changed attribute in the Markup View, instead of the whole element.
    • Canvas Debugger now supports setTimeout for animations.
    • Inline box model highlighting.
    • Browser Toolbox can now be opened from a shortcut: Cmd-Opt-Shift-I / Ctrl-Alt-Shift-I.
    • Network Monitor now shows the remote server’s IP address and port.
    • When an element’s highlighted in the Inspector, you can now use the arrow keys to highlight the current element’s parent (left key), or its first child, or its next sibling if it has no children, or the next node in the tree if it has no siblings (right key). This is especially useful when an element and its parent occupy the same space on the screen, making it difficult to select one of them using only the mouse.

    For an even more complete list, check out all 200 bugs resolved during the Firefox 39 development cycle.

    Thanks to all the new developers who made their first DevTools contribution this release:

    • Anush
    • Brandon Max
    • Geoffroy Planquart
    • Johan K. Jensen
    • John Giannakos
    • Mahdi Dibaiee
    • Nounours Heureux
    • Wickie Lee
    • Willian Gustavo Veiga

    Do you have feedback, bug reports, feature requests, or questions? As always, you can comment here, add/vote for ideas on UserVoice, or get in touch with the team at @FirefoxDevTools on Twitter.

  5. Mobile game development with the Device Orientation and Vibration APIs

    The market for casual mobile gaming is keeping pace with the growing market for smartphones. There are Web tools that can help web developers like you build games that compete with native games. You’ll need great execution to stand out from the crowd – using the JavaScript APIs correctly can help. For game development, you’ll want to understand the Device Orientation API and the Vibration API.

    Continued…

  6. Trainspotting: Firefox 37, Developer Edition and More

    Welcome to Trainspotting, a new series on Mozilla Hacks designed to help the busy Web developer keep up with what’s new, what’s changed and what is coming soon in all of the Firefoxes, the Web platform, and the tools for building the Web!

    Mozilla develops Gecko and Firefox on a “train model” – we branch the code and ship a release on a time-based schedule (every six weeks). If a feature is not finished, it’s reverted or disabled and has to, as we say, ride the next train. This means we ship new features, performance improvements, and bug fixes to users every six weeks, instead of having to wait up to 18 months.

    Trainspotting will publish every six weeks when we branch the code – and we’ll point out any changes that might require action or cause compatibility issues, as well as new features that Web developers would want to take advantage of.

    Firefox 37

    For a detailed list of all noted changes in the release, check out the official release notes for Firefox 37. Below is a list of notable features, links to documentation, and anything that requires action by developers or site operators.

    Desktop Features

    • A subset of the Media Source Extensions (MSE) API has been implemented and is enabled to allow native playback of HTML5 video on websites such as YouTube. You can read about the various MSE APIs and their usage on MDN.
    • Bing search now uses HTTPS. Hurray for private and secure searching!
    • Heartbeat is a new feedback feature in Firefox desktop: Each day a random subset of Firefox users will be shown a notification bar with an opportunity to provide feedback on their experience. You can see screenshots and read more about how it works on the Heartbeat project page.

    Firefox for Android

    This time around, Firefox for Android is getting a security and stability release. The biggest user-facing changes—improved performance of file downloads, and the addition of some new locales: Albanian, Burmese, Lower Sorbian, Songhai, Upper Sorbian, Uzbek. Read the full list of security fixes for Firefox Android 37 and the full release notes.

    HTML5 & Web Platform

    There are a bunch of new Web platform features that you can now use in production content in Firefox 37, and here are a few examples:

    Keep reading the Firefox 37 for Developers article on MDN for a detailed look at all the rest.

    Developer Tools

    If you’re using Firefox Developer Edition these additions won’t be news, but if you’ve been doing your development in the release build, there are a few new features to note:

    Security

    Firefox 37 has a bunch of security changes. Most of these do not require any action, however if you are a site operator you should definitely look to see if any of these changes impact you. Big thanks to David Keeler, security engineer for Firefox, for his help deciphering this section of the release notes.

    • We removed support for DSA in certificates and TLS, because we found that almost nobody was using these. If you’re a site operator and your certificate was signed with a DSA algorithm, contact your CA and get a new certificate. You can check with `openssl x509 -in {certificate file} -text -noout` and search for “Signature Algorithm.” If you do have one of these certificates and do not change it, users will see an override-able error.
    • HTTP/2 AltSvc is temporarily disabled due to a bug. We implemented HTTP/2 AltSvc support for opportunistic encryption. This feature allows encryption over TLS for unauthenticated connections that would otherwise be clear text. Configuration is very simple, and Patrick McManus has written instructions for how to set it up on your server.
    • We have disabled insecure TLS version fallback. If a secure site isn’t working, you can try setting the “security.tls.version.fallback-limit” preference in about:config to 1 and see if it works then. If you see this anywhere, please file a Tech Evangelism bug, noting the URL of the site, so we can work with the operators to update it. Site operators should make sure their servers aren’t TLS-intolerant, which you can do with the SSL Labs tool.
    • Users can now report SSL connection problems for a variety of non-certificate-related errors. For example, if a user encounters a non-override-able TLS error, they can now send a report to Mozilla directly from the error page. The information in the report consists of the domain you were trying to reach, the certificates the server sent, the time, which error was encountered, and some user agent information. We use this information to work with site operators to fix their configurations, and to improve our software that detects these issues, so please do send reports. Check out a screenshot of what this looks like.
    • TLS False Start optimization now requires a cipher suite using AEAD construction. If you’re running a server and false start isn’t working as expected, try using an AEAD cipher suite. Learn more about AEAD at Wikipedia and in RFC 5288. The only AEAD cipher suite that Firefox supports at this time is AES-GCM.
    • We now log usage of weak ciphers to the web console. For example, if you visit a site with a SHA-1 certificate with the web console open you’ll now see a message like, “This site makes use of a SHA-1 Certificate; it’s recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1. Learn more…” If you run a site and your certificate was signed with SHA-1, get a new certificate from your CA.

    Firefox Beta

    In six short weeks Beta will be available for general release, becoming Firefox 38. Here’s some of what’s coming your way:

    • All Firefox preferences are now in a new tab-based UI.
    • Improved page-load times with speculative connection warmup.
    • MSE support on Mac OS X.
    • EME support for encrypted media playback.
    • Web platform features: WebSockets in Web Workers, KeyboardEvent.code, and the BroadcastChannel API.

    Read the Firefox 38 Beta release notes for the full list.

    Firefox Developer Edition

    This release of Firefox Developer edition (which will be Firefox 39) is frankly kind of ridiculous. The developer tools are getting precariously close to something indistinguishable from magic. Huge props to the developer tools team for what you’re about to see.

    • Developer Tools: Wi-Fi debugging of Firefox OS devices from WebIDE, drag and drop of nodes in the Inspector’s markup view, Web Console input history persistence, localhost works with WebSocket connections when you’re offline, and the cubic bezier tooltip now shows a gallery of pre-sets you can choose from to make your CSS animations super slick.
    • Web platform features include the “switch” role in Aria 1.1, CSS scroll snap points, Cache API, Fetch API, <link rel=”preconnect”> and more.

    Read the full release notes for this release of Firefox Developer Edition.

    Nightly

    The nightly branch of Firefox is where a lot of features are in active development. It’s a place where you can test experimental Web APIs and see user-facing browser features that are not yet ready for hundreds of millions of users. You might see a crash or two, you might lose you session data, but you also might experience the vision and wonder of what the future holds. It’s the Mos Eisley of browsers – a dangerous place, but we stick around for the action.

    There are a number of features that have landed and are shipping nightly builds either enabled by default or by pref:

    • E10s – Web content runs in a separate process from the browser UI.
    • Partial implementation of Service Workers.
    • Shumway – Flash implemented in JavaScript is enabled for some sites.

    Thus concludes the first edition of Trainspotting. Let us know what you think in the comments, and what you’d like to see more of!

  7. Peering Through the WebRTC Fog with SocketPeer

    WebRTC allows browsers to do things they never could before, but a soup of unfamiliar terminology and the complexity of the API makes for a steep learning curve. After spending several weeks neck-deep in example code and cargo-culting several libraries, I have emerged with a workable understanding and a nifty library that helps hide some of the complexity of WebRTC for its simplest use case of two way peer-to-peer communication.

    But before I start talking about the library, it helps to understand a bit of what it abstracts away.

    Alice and Bob (and ICE and NAT and STUN and SDP)

    When two devices want to speak to each other, we need a way for them to exchange contact information such as their IP addresses. In the same way DNS servers help browsers locate remote machines, we can set up a mutually known server to help potential peers locate each other. In WebRTC this is known as a signalling server.

    In our simple case, each peer contacts the signalling server. The server provides the peers with each other’s addresses, and then the peers can begin exchanging data.

    The plot thickens

    Today’s Internet doesn’t quite work that way. Most computers online don’t have unique IP addresses; they share a public address with all the other devices on their local network. Most local networks also have firewalls that protect machines from unwanted inbound traffic. Swapping IP addresses isn’t enough.

    ICE the wound

    The telecommunications industry has been dealing with this problem for a while now*. There are a number of different ways a connection can pass back through a firewall and router to an internal network. ICE is a kitchen-sink protocol that uses the tried-and-true technique “Try Everything and See What Works™.” A server, called a STUN server, uses the ICE protocol to find out and inform a peer of all the possible ways it can be reached from the public Internet. These potential connection methods are called ICE candidates.

    When a machine receives a candidate, it needs to communicate that to its peer. Here the signalling server comes to the rescue again — relaying each peer’s candidates to the other.

    Call and response

    When a device wants to establish a connection, it generates a message called an offer and sends it to a peer using the signalling server. The offer, encoded in the SDP format, consists of information about the device — such as which protocols it knows how to speak and which communication methods it has. When the remote peer receives the offer, it responds with its own SDP message called an answer. Then, the two potential peers send each other possible ICE candidates. Once the peers find a connection method that works for both of them, the connection is established!

    Let’s take it from the top

    Let’s review the connection process, incorporating all the techniques from above:

    1. A device uses a signalling server to relay an SDP offer to a potential peer. In the meantime, it asks an ICE server to find out how it can be reached from the public Internet.
    2. The potential peer replies with its own connection offer, and also gathers ICE candidates.
    3. The peers use the signalling server to exchange ICE candidates, attempting to use them to open a connection.
    4. Once each peer finds a working candidate, the connection is established.

    Let’s give them something to talk about with

    Once a PeerConnection is established, it can be used to carry audio and video MediaStreams as well as a more general DataChannel. People are excited about browser-to-browser video conferencing (with good reason!), but WebRTC isn’t just about voice and video. RTCDataChannel provides a general data pipeline that works similarly to a WebSocket. It’s immensely powerful and useful, but under-promoted.

    Boilerplate the ocean

    WebRTC is a low level, nuts-and-bolts API. It’s made of multiple small, composable APIs that offer a large amount of flexibility and extensibility. The downside of this is that accomplishing even a basic task can require significant boilerplate code. The notion is that JS libraries and frameworks will step in to abstract away this complexity, and indeed, there are a large number of WebRTC libraries out there already.

    Many of these libraries fall short due to a lack of signalling server and fallback support for browsers with no WebRTC support. To address this, Chris Van and I built SocketPeer.

    Using SocketPeer

    SocketPeer is, as its name suggests, a combination of WebSockets and RTCPeerConnection. This node.js library abstracts away the common pattern of using WebSockets as a signalling server to instantiate a DataChannel over WebRTC. The WebSocket server will also serve as a fallback message relay if the peers cannot establish a peer-to-peer connection.

    Server code

    // In your server module alongside existing application code.
    var SocketPeer = require('socketpeer');
    new SocketPeer();

    I’ll admit that’s a bit facile, but SocketPeer is designed to simplify the process of running a signalling server — at its simplest, it does everything for you. The server is fairly configurable, but by default it takes care of itself, by:

    • Creating an http.Server if one is not supplied.
    • Attaching logic to serve the client-side socketpeer.js library.
    • Starting a WebSocket server if one is not supplied.
    • Starting to listen on a default port.

    If all you need is a basic signalling server, then this is all the code you need. But let’s say you want to integrate SocketPeer with an existing Express app:

    // `app` is an existing Express Application
    var server = http.createServer(app);
    new SocketPeer({
      httpServer: server
    });
    server.listen(/* port */);

    Client code

    As described above, when SocketPeer is running on a server it will serve the client library at a known URL. By default, this can be found at /socketpeer/socketpeer.js. The client library exposes an event interface and a series of events to keep you informed of the state of the connection. The three most important events are:

    • connect – Fires when peers are paired. Data can be exchanged using WebSockets at this point.
    • upgrade – Fires when an RTCPeerConnection is established. Data can now be exchanged peer-to-peer.
    • data – Fires when data arrives from the remote peer.

    The last important piece of information is called pairCode. This is an arbitrary string used by the two ends of a peer-to-peer connection to identify each other. It can be any mutually agreed-upon value.

    var peer = new SocketPeer({
      pairCode: 'foobar'
    });
     
    peer.on('connect', function () {
      // connected via WebSockets
      peer.send('Hello via WebSockets.');
    });
     
    peer.on('upgrade', function () {
      // now using RTCPeerConnection
      peer.send('Hello via WebRTC!');
    });
     
    peer.on('data', function (data) {
      // do something awesome
    });

    Chat is the new todo

    What’s sample code without a working demo? I built a super simple example of peer-to-peer chat using SocketPeer. Try it out, and check out the code on GitHub to see how it works.

    Depiction of the SocketPeer demo chat app.

    The library is still a work in progress, but all the core functionality is in place and tested. Please try it out and let us know of any issues or feedback on the API.

    * The author of this post is not a telecommunications engineer. He read a lot of Wikipedia and skimmed a few RFCs so you don’t have to.

  8. What do you want from your DevTools?

    Every tool starts with an idea: “if I had this, then I could do that faster, better, or more easily.” The Firefox Developer Tools are built atop hundreds of those ideas, and many of them come from people in the web development community just like you.

    We collect those ideas in our UserVoice forum, and use your votes to help prioritize our work.

    Last April, @hopefulcyborg requested the ability to “Connect Firefox Developer Tools to [Insert Browser Here].” The following November, we launched Firefox Developer Edition which includes a preliminary version of just that: the ability to debug Chrome and Safari, even on mobile, from Firefox on your desktop. We called it Valence.

    Good ideas don’t have to be big or even particularly innovative as long as they help you accomplish your goals more effectively. For instance, all of the following features also came directly from feedback on our UserVoice forum:

    The color picker introduced in Firefox 31

    The color picker introduced in Firefox 31

    Though somewhat small in scope, each of those ideas made the DevTools more efficient, more helpful, and more usable. And that’s our mission: we make Firefox for you, and we want you to know that we’re listening. If you have ideas for the Firefox Developer Tools, submit them on UserVoice. If you don’t have ideas, vote on the ones that are already there. The right people will see it, and it will help us build the best tools for you.

    If you want to go a step further and contribute to the tools yourself, we’re always happy to help people get involved. After all, Mozilla was founded on the open source ideal of empowering communities to collaborate and improve the Internet for all of us.

    These are your tools. How could they be better?

  9. Understanding the CSS box model for inline elements

    In a web page, every element is rendered as a rectangular box. The box model describes how the element’s content, padding, border, and margin determine the space occupied by the element and its relation to other elements in the page.

    Depending on the element’s display property, its box may be one of two types: a block box or an inline box. The box model is applied differently to these two types. In this article we’ll see how the box model is applied to inline boxes, and how a new feature in the Firefox Developer Tools can help you visualize the box model for inline elements.

    Inline boxes and line boxes

    Inline boxes are laid out horizontally in a box called a line box:

    2-inline-boxes

    If there isn’t enough horizontal space to fit all elements into a single line, another line box is created under the first one. A single inline element may then be split across lines:

    line-boxes

    The box model for inline boxes

    When an inline box is split across more than one line, it’s still logically a single box. This means that any horizontal padding, border, or margin is only applied to the start of the first line occupied by the box, and the end of the last line.

    For example, in the screenshot below, the highlighted span is split across 2 lines. Its horizontal padding doesn’t apply to the end of the first line or the beginning of the second line:

    horizontal-padding

    Also, any vertical padding, border, or margin applied to an element will not push away elements above or below it:

    vertical-padding

    However, note that vertical padding and border are still applied, and the padding still pushes out the border:

    vertical-border-padding

    If you need to adjust the height between lines, use line-height instead.

    Inspecting inline elements with devtools

    When debugging layout issues, it’s important to have tools that give you the complete picture. One of these tools is the highlighter, which all browsers include in their devtools. You can use it to select elements for closer inspection, but it also gives you information about layout.

    layout-info

    In the example above, the highlighter in Firefox 39 is used to highlight an inline element split across several lines.

    The highlighter displays guides to help you align elements, gives the complete dimensions of the node, and displays an overlay showing the box model.

    From Firefox 39 onwards, the box model overlay for split inline elements shows each individual line occupied by the element. In this example the content region is displayed in light blue and is split over four lines. A right padding is also defined for the node, and the highlighter shows the padding region in purple.

    Highlighting each individual line box is important for understanding how the box model is applied to inline elements, and also helps you check the space between lines and the vertical alignment of inline boxes.