Brick

Custom Elements for Custom Applications – Web Components with Mozilla’s Brick and X-Tag

In this article, we will explore the use of Mozilla’s Brick and X-Tag libraries. First we’ll use Brick to rapidly prototype a simple application. Then, we’ll build a custom web component using X-Tag.

The Technology

Brick: Curated Web Components

Brick is a set of modular, reusable UI components. The components are designed for adaptive, responsive applications and are a great choice for going mobile first, which is by and large how web-based applications should be developed. This philosophy and its design patterns accomodate a wide range of devices. Brick components aren’t just for mobile apps, they are for modern apps.

Brick is kind of like a library, but really you should think of it as a curated collection of web components.

Brick’s collection of components are used declaratively in your HTML <like-this> and can be styled with CSS like regular non-custom elements. Brick components have their own micro-APIs for interacting with them. These components are building blocks. Do you like Lego? Good. You will like Brick.

Brick web components are made using the X-Tag custom elements polyfill.

What is X-Tag?

X-Tag is a library that polyfills several (and soon all) features that enable web components in the browser. In particular, X-Tag is focused on polyfilling the creation of Custom Elements so that you can extend the DOM using your own declarative syntax and element-specific API.

When you are using components from Brick, you are using web components made using the X-Tag library. Brick includes X-Tag core, so if you include Brick and then decide to make your own custom elements — you do not need to include X-Tag to do so, all the features of X-Tag are already available for you.

Download Demo Project Files

Download the demo project files. First we’ll use the material in the simple-app-with-bricks folder.

Using Bricks in an app

Here we will build a simple skeleton app using <x-appbar>, <x-deck>, and <x-card>. x-appbar provides a tidy header bar for our application, and x-cards placed as children of an x-deck give us multiple views with transitions.

First, we start with a barebones HTML document and then include Brick’s CSS and JS, along with our own application-specific code (app.css and app.js respectively in the example to follow).

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" type="text/css" href="css/brick.min.css">
    <link rel="stylesheet" type="text/css" href="css/app.css">
    <title>Simple - Brick Demo</title> 
  </head> 
  <body> 
    <!--- Some Brick components will go here -->
    <script type="text/javascript" src="js/brick.min.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
  </body>
  </html>

Now we add some Brick elements:

<x-appbar id="bar">
  <header>Simple Brick App</header>
  <button id="view-prev">Previous View</button>
  <button id="view-next">Next View</button>
</x-appbar>

Below your x-appbar, create an x-deck with some x-cards as children. You can give the x-cards any content you like.

<!-- Place your x-deck directly after your x-appbar -->
<x-deck id="views">
  <x-card>
    <h1>View 1</h1>
    <p>Hello, world!</p>
  </x-card>
  <x-card>
    <h1>Pick a Date</h1>
    <p>&lt;x-datepicker&gt;s are a polyfill for &lt;input type="date"&gt;</p>
    <x-datepicker></x-datepicker>
    <p>Just here to show you another tag in action!</p>
  </x-card>
  <x-card>
    <h1>A Random Cat To Spice Things Up</h1>
    <!-- Fetches from the Lorem Pixel placeholder content service -->
    <img src="http://lorempixel.com/300/300/cats">
  </x-card>
</x-deck>

We have already almost completed the structure for a simple application. All we need now is a little bit of CSS and Javascript to tie it together.

document.addEventListener('DOMComponentsLoaded', function() { 
  // Run any code here that depends on Brick components being loaded first 
  // Very similar to jQuery's document.ready() 
 
  // Grab the x-deck and the two buttons found in our x-appbar and assign to local vars
  var deck = document.getElementById("views"),
  nextButton = document.getElementById("view-next"),
  prevButton = document.getElementById("view-prev"); 
 
  // Add event listeners so that when we click the buttons, our views transition between one another
  prevButton.addEventListener("click", function(){ deck.previousCard(); }); 
  nextButton.addEventListener("click", function(){ deck.nextCard(); });
});

<x-calendar> example in our demo application

Some simple CSS to style our fledgling application:

html, body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  height: 100%;
}
 
h1 {
  font-size: 100%;
}
 
x-deck > x-card {
  background: #eee;
  padding: 0.6em
}

Ka-bam! With a little bit of declarative markup and a few tweaks, we have a skeleton that anyone can use to make a multi-view app within a single HTML document. If you check out the markup in the developer tools, you’ll see the Brick custom elements living happily alongside vanilla HTML elements – you can use the developer tools to inspect and manipulate them in the same way as regular old HTML.

Custom elements alongside HTML elements in the Firefox Developer Tools

Now let’s learn how to make our own custom element using X-Tag.

Creating Custom Elements (Your Own ‘Bricks’) Using X-Tag

Let’s say we have a mobile application in which the user takes an action that results in a blocking task. Maybe the application is waiting for an external service. The program’s next instruction to complete the user-initiated task depends on the data from the server, so unfortunately we have to wait. For the sake of our purposes here, let’s pretend we can’t modify our program too much and assume an entrenched architecture – maybe we can’t do much else other than communicate to the user until we find a way to deal with the blocking better. We have to do the best with what we have.

We will create a custom modal spinner that will tell the user to wait. It’s important to give your users feedback on what’s happening in your app when they don’t get to complete their task in a timely manner. A frustrated or confused user might give up on using your app.

You will want to switch to the x-status-hud folder inside of the demo materials now.

1. Registering Your Custom Element

X-Tag relies on several different events to detect and upgrade elements to custom elements. X-Tag will work whether the element was present in the original source document, added by setting the innerHTML property, or created dynamically via document.createElement. You should take a look at the Helpers section of the X-Tag documentation as it covers various functions that will allow you to work with your custom elements just like vanilla ones.

The first thing that we need to do is register our custom element with X-Tag so that X-Tag knows what to do if and when it encounters our custom element. We do that by calling xtag.register.

xtag.register('x-status-hud', {
  // We will give our tag custom behavior here for our status indicating spinner
});

!IMPORTANT: All custom element names must contain a hyphen. Why is this? The idea here is that there are no standard HTML elements with a hyphen in them, so we don’t trample existing namespaces and have collisions. You do not have to prefix with ‘x-’, this is just a convention used for components create with X-Tag in the Brick ecosystem. Once upon a time in the early days of the W3C specification for custom elements, it was speculated that all custom elements would have an x- prefix; this restriction was relaxed in later versions of the specification. If you were to name an element ‘bacon-eggs’ or ‘adorable-kitten’, both of these would be perfectly valid names. Choose a name that describes what your element is or does.

If we wanted to, we could choose to set what HTML element is being used as our base element before upgrading. We can also set a specific prototype for our element if we want to involve functionality from a different element. You can declare these as follows:

xtag.register('x-superinput', {
  extends: 'input',
  prototype: Object.create(HTMLInputElement.prototype)
});

The element we are building doesn’t require these properties to be set explicitly. They are worth mentioning because they will be useful to you when you write more advanced components and want a specific level of control over them.

2. The Element Lifecycle

Custom elements have events that fire at certain times during their lifetime. Events are fired when an element is created, inserted into the DOM, removed from the DOM, and when attributes are set. You can take advantage of none or all of these events.

lifecycle:{
  created: function(){
    // fired once at the time a component
    // is initially created or parsed
  },
  inserted: function(){
    // fired each time a component
    // is inserted into the DOM
  },
  removed: function(){
    // fired each time an element
    // is removed from DOM
  },
  attributeChanged: function(){
    // fired when attributes are set
  }

Our element is going to use the created event. When this event fires, our code will add some child elements.

xtag.register('x-status-hud', {
  lifecycle: {
    created: function(){
        this.xtag.textEl = document.createElement('strong');
 
        this.xtag.spinnerContainer = document.createElement('div');
        this.xtag.spinner = document.createElement('div');
 
        this.xtag.spinnerContainer.className = 'spinner';
 
        this.xtag.spinnerContainer.appendChild(this.xtag.spinner);
        this.appendChild(this.xtag.spinnerContainer);
        this.appendChild(this.xtag.textEl);
    }
  }
  // More configuration of our element will follow here
});

3. Adding Custom Methods

We need to have control over when we show or hide our status HUD. To do that, we need to add some methods to our component. Let’s add some functions to do that. A simple toggle() may suffice for some use cases, but let’s throw in individual hide() and show() functions too.

 
xtag.register('x-status-hud', {
  lifecycle: {
    created: function(){
      this.xtag.textEl = document.createElement('strong');
 
      this.xtag.spinnerContainer = document.createElement('div');
      this.xtag.spinner = document.createElement('div');
 
      this.xtag.spinnerContainer.className = 'spinner';
 
      this.xtag.spinnerContainer.appendChild(this.xtag.spinner);
      this.appendChild(this.xtag.spinnerContainer);
      this.appendChild(this.xtag.textEl);
    }
  },
 
  methods: {
    toggle: function(){
      this.visible = this.visible ? false : true;
    },
 
    show: function (){
      this.visible = true;
    },
 
    hide: function (){
      this.visible = false;
    }
  }

4. Adding Custom Accessors

Something important to note about properties on custom elements: they do not have to map to an attribute. This is by design because some setters could be very complex and not have a sensible attribute equivalent.

If you would like an attribute and property to be linked, pass in an empty object literal to the attribute. You’ll see below where this has been done for the label attribute.

xtag.register('x-status-hud', {
  lifecycle: {
    created: function(){
      this.xtag.textEl = document.createElement('strong');
 
      this.xtag.spinnerContainer = document.createElement('div');
      this.xtag.spinner = document.createElement('div');
 
      this.xtag.spinnerContainer.className = 'spinner';
 
      this.xtag.spinnerContainer.appendChild(this.xtag.spinner);
      this.appendChild(this.xtag.spinnerContainer);
      this.appendChild(this.xtag.textEl);
    }
  },
 
  methods: {
    toggle: function(){
      this.visible = this.visible ? false : true;
    },
 
    show: function (){
      this.visible = true;
    },
 
    hide: function (){
      this.visible = false;
    }
  },
 
  accessors: {
    visible: {
      attribute: { boolean: true }
    },
 
    label: {
      attribute: {},
 
      set: function(text) {
        this.xtag.textEl.innerHTML = text;
      }
    }
  }
}); // End tag declaration

If the difference between attributes and properties is unclear to you, take a look at the top answer to this Stack Overflow question. Although the question being asked is about something else entirely (jQuery), the top answer has a great explanation that will help you understand the relationship between attributes and properties.

The Finished Component

When we write code that depends on custom elements having been loaded already, we add an event listener that fires when the components have finished loading. This is sort of like jQuery’s document.ready.

<script type="text/javascript">
document.addEventListener('DOMComponentsLoaded', function(){
  // Any HUD customizations should be done here.
  // We just pop up the HUD here to show you it works!
  var testHUD = document.getElementById("test");
  testHUD.label = "Please Wait...";
  testHUD.show();
}, false);
</script>

X-Tag Status HUD Demo

There you have it. We’ve created a simple modular, reusable widget for our client-side code. It’s a good starting point. But is it really finished?

Some ways we may improve this element:

  • Have the element recalculate it’s size when the attributeChanged event is fired and have the component resize to fit the label as it is updated rather than truncate the label with an ellipsis
  • Let the developer set an image, such as an animated GIF, in place of the CSS spinner to customize the user experience further
  • Have a progress bar instead of a spinner to give the user some additional information about task progress

Use your creativity to come up with a small set of practical features and improvements beyond these as an exercise on your own.

After following this tutorial you should understand how to extend the DOM with your own custom elements. If you’re stuck, leave a comment and we’ll do our best to get you back on track. If you’re not stuck, post your GitHub repo and show us what you’ve made with Brick and X-Tag. Happy hacking!

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Firefox OS Development: Web Components and Mozilla Brick

In this edition of “Firefox OS: The platform HTML5 deserves” (the previous six videos are published here), Mozilla’s Principal Evangelist Chris Heilmann (@codepo8) grilled Mozilla’s “Senior HTML5 Engineer Angle Bracket Coordinator” Matthew Claypotch (@potch) about the exciting new possibilities of Web Components for Web App developers and how Mozilla’s Brick library, a collection of custom elements to build applications with, can help with the transition. You can watch the interview on YouTube.

The Why of Web components

There is a problem with the Web as a platform for applications: HTML, the language that makes it easy to mark up documents and give them meaning doesn’t have enough elements to build applications. There are quite a few new elements in the HTML5 spec, but their support is sketchy across browsers and there are still a lot of widgets missing that other platforms like Flex or iOS give developers out-of-the-box. As a result, developers build their own “widgets” like menu bars, slider controls and calendars using non-semantic HTML (mostly DIV elements) and make them interactive using JavaScript and theme-able using CSS.

This is a great workaround but the issue is that we add on top of the functionality of browsers instead of extending the way they already function. In other words, a browser needs to display HTML and does a great job doing that at least 60 frames per second. We then add our own widget functionality on top of that and animate and change the display without notifying the browser. We constantly juggle the performance of the browser and our own code on top of it. This leads to laggy interfaces, battery drain and flickering.

To work around that problem a few companies and standards body members are working on the Web Components specification which allows developers to extend the browser’s understanding of markup with own elements. Instead of writing a slider control and make it work after the browser already displayed the document, you define a slider element and become part of the normal display flow. This means our widgets get more responsive, don’t work against the browser’s rendering flow and all in all perform better. Especially on low spec mobile devices this is a massive win. The whole thing already happens: if you for example add a video element to the document you see a video controller with a timed slider bar, a play button and volume controls. All of these are HTML, CSS and JavaScript and you can even see them in the debugging tools:

Anatomy of a video element

Firefox OS, being targeted at low end devices can benefit a lot from widgets that are part of the rendering flow, which is why Mozilla created Mozilla Brick, a collection of custom elements to build applications with. Earlier we introduced the concept using a library called XTags, which powers Brick. Using Brick, it is very simple to create for example a deck based application layout using the following markup:

<x-deck selected-index="0">
  <x-card>
    0<span>I'm the first card!</span>
  </x-card>
  <x-card>
    1
    <span>
      These cards can contain any markup!<br>
      <img src="../../site/img/grounds_keeping_it_real_s3.gif">
      <img src="../../site/img/grounds_keeping_it_real_s1.gif">
      <img src="../../site/img/grounds_keeping_it_real_s2.gif">
    </span>
  </x-card>
  <x-card>
    2 <img src="../../site/img/thumbs_up.gif">
  </x-card>
</x-deck>

The resulting app consists of three decks that can be animated into another without having to do anything but call a deck.shuffleNext(); function.

Web Components are a huge topic right now and many libraries and frameworks appear each week. We hope that by using Brick we can enable developers to build very responsive apps for Firefox OS quickly and cleanly and leave the pain of making your app perform really well up to the OS.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Introducing Brick: Minimal-markup Web Components for Faster App Development

Those of you on the cutting HTML5 edge may have already heard of the exciting Web Components specification. If you haven’t, you’ll probably want to read up on what makes this so exciting, but long story short, Web Components promise to open up a new realm of development by letting web developers write custom, reusable HTML tags. Think of them as JavaScript plugins without the need for additional code initialization or boilerplate markup/styling.

Unfortunately, it will be a while before we see native browser support for the spec, but that doesn’t mean developers can’t start taking advantage of the component concept now, thanks to Google’s Polymer framework and Mozilla’s x-tags polyfill library (both X-Tag and Polymer share the same low-level, Web Component polyfills).

We’re proud to announce the beta release of Brick, a cross-browser library that provides new custom HTML tags to abstract away common user interface patterns into easy-to-use, flexible, and semantic Web Components. Built on Mozilla’s x-tags library, Brick allows you to plug simple HTML tags into your markup to implement widgets like sliders or datepickers, speeding up development by saving you from having to initially think about the under-the-hood HTML/CSS/JavaScript.

Putting Brick into Action

Say that you wanted to implement a cross-browser, mobile-friendly calendar widget in your application. With current JavaScript plug-ins, such as jQuery UI, this would require putting boilerplate, non-semantic markup into your HTML, as well as explicitly initializing and managing it through JavaScript. However, with Brick, you can implement such a component simply by adding a custom HTML tag that you can treat as a normal native tag.

For our calendar example, this means just including the library’s CSS and Javascript file in your application, then adding the following tag to your markup:

<x-calendar></x-calendar>

which creates a DOM element that looks like this:

Want to edit how the component behaves, such as by adding navigational controls or pre-selecting a date? Like any other native tag, you can change how a component behaves just by changing the attributes of the tag!

<x-calendar controls chosen='2012-05-17'></x-calendar>

Available Bricks

At the time of writing, Brick consists of thirteen different tags, most of which are completely independent of one another, and can even be downloaded separately instead of a single bundle.

Some tags abstract away complex widgets into simple HTML tags, such as:

Others are cross-browser polyfill implementations of existing native not-yet-globally-supported elements, such as:

which polyfill <input type="range"> and <input type="date">, respectively. Still others are structural components simplifying the styling and markup of certain components, such as <x-layout>, which ensures that content, headers, and footers can fill a container element without explicit styling markup.

Each tag comes with a flexible attribute/JavaScript API and can be fully styled to match your application.

Start Building with Bricks

Want to start using components in your own applications? Head to mozilla.github.io/brick to download a release bundles, view demos, and read the documentation for the available tags. Alternatively, visit the Brick Github page to view the source code and contribute to the effort!

The library is still in a beta release, so we appreciate all user feedback! Brick is already starting to crop up in the wild, so we’d love to hear about how you’re using it!

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Brick Marketing Forms Strategic Web Design Partnership with Neal Advertising

For the first time in its six year history, Boston SEO firm, Brick Marketing has formed an official partnership for web design services. Brick Marketing will now refer all its SEO and search engine marketing clients to Neal Advertising for web design, web development, graphic design, and interactive and advertising services. (PRWeb April 19, 2011) Read the full story at http://www …

View full post on web development – Yahoo! News Search Results

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)