• // Comments

    An inescapable symptom of widespread web design bad-assery is an abundance of vocabulary words that web designers need to be familiar with. For every job, there is the right tool (or, at least, the “righter” tool), but in order to use that tool, we have to first know its name.

    Today, I’d like to take a moment to describe some common JavaScript vocabulary that many of us have heard, though we may have only the vaguest sense of their meaning. With an expanded vocabulary, the application of the right tool becomes easier.

    CommonJS

    CommonJS is an API aimed at creating a standards library for JavaScript beyond the browser. It is created, promoted, and refined by the CommonJS Group. Its mission statement defines it as an organization primarily focused on API design for server side adoption, but the influence of CommonJS can be felt in the larger community. For instance, AMD is informed by CommonJS Module Identifiers.

    RequireJS

    RequireJS is a JavaSript module loader. It’s tight. From its docs:

    RequireJS is a JavaScript file and module loader. It is optimized for in-browser use,
    but it can be used in other JavaScript environments, like Rhino and Node. Using a
    modular script loader like RequireJS will improve the speed and quality of your code.

    I recently wrote a post detailing how Require.js might be able to fit in with Drupal.

    Backbone.js

    Backbone.js is a JavaScript framework that upholds an MV* approach to application design. If that acronym throws you, read this awesome post by Addy Osmani. With Backbone.js, one can more sanely create JavaScript rich applications. It provides the foundations for creating models, relating them to views, routing requests to other views, etc. From its docs:

    Backbone.js gives structure to web applications by providing models with key-value
    binding and custom events, collections with a rich API of enumerable functions,views
    with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

    Underscore.js

    Underscore.js is a small JavaScript utility library. It gives JavaScript developers some of the fancy stuff that programmers of other languages take for granted. From its docs:

    Underscore is a utility-belt library for JavaScript that provides a lot of the functional
    programming support that you would expect in Prototype.js (or Ruby), but without
    extending any of the built-in JavaScript objects.

    Underscore.js is a dependency of Backbone.js, so if you’re considering Backbone.js, you’re considering Underscore.js. Not a terrible thing, as Underscore.js is teeny tiny, and gives us some great JavaScript methods.

    Zepto.js

    Zepto is a jQuery-like library with pretty specific design goals. It aims to almost completely replicate the jQuery API while staying light as a feather, a feat Zepto achieves mostly by removing cross-browser compatibility cruft from jQuery. From its docs:

    Zepto is a minimalist JavaScript library for modern browsers with a largely
    jQuery-compatible API. If you use jQuery, you already know how to use Zepto.

    Now, cross-browser compatibility cruft is why a lot of us use and love jQuery; so as to have predictable JavaScript across many browsers. But if your primary concern is modern browsers and lightweight pages, Zepto is worth a hard look.

    Ember.js

    Ember.js states simply that it is a “framework for creating ambitious web applications.” It’s a JavaScript framework similar to Backbone.js, but diverges from Backbone.js in that Ember.js favors convention over configuration (ala RoR). Where Backbone.js leaves one with the freedom and sometimes curse of figuring out how all the parts of an application fit together, Ember.js seems to say “I already thought about this, jerk.”

    Handlebars

    Handlebars is a JavaScript library for HTML templating, a paradigm that is very useful when building complex applications: Rather than dropping strings of markup directly into JS code, we can define templates with dynamic content for use in our applications. From its docs:

    Handlebars provides the power necessary to let you build semantic templates
    effectively with no frustration.

    Modernizr

    Modernizr is a sweet library that tests browsers for feature support. If we can detect what features a user’s browser is capable of, then we can progressively enhance their experience accordingly. From its docs:

    Modernizr is a JavaScript library that detects HTML5 and CSS3 features in the
    user’s browser.

    Modernizr allows for this progressive enhancement by adding CSS classes to the html element on page load. These classes reflect functionality we might want to leverage, for instance, CSS gradients. If a user doesn’t have that capability in their browser, we wind up with a class called “no-cssgradients”, and can either polyfill this discrepancy or write CSS that progressively reflects this.

    Express

    Express is a little framework for creating web apps with node.js. It looks a lot like Sinatra, in that it can be a dead simple mechanism for defining routes that resources are available at. From its docs:

    Express is a minimal and flexible node.js web application framework, providing a
    robust set of features for building single and multi-page, and hybrid web applications.

    You can probably already imagine creating a simple RESTful service with Express that could spoon feed data to a Backbone.js application.

    Of course, the moment this distilled glossary is published, there will be a new framework, library, or utility that will be worth consideration; that is the nature of the ever shifting landscape of web design.

    Originally published on the Aten blog

  • // Comments

    Working with JavaScript in Drupal can be a sometimes inconsistent experience, making the already important pursuit of organized code a bit more acute. This post chronicles a bit of exploration I’ve been doing on this topic. It waxes tangential, but that’s alright, as tangents are the space we sometimes discover larger problems and better solutions. It begins like this.

    I’ve been trying to become a better JavaScript developer. As a front-end developer, JavaScript is a topic that cultivates programming skills in a language often used to craft spectacular interaction design, something any good front-end developer should be very interested in. In conjunction with the obvious deepening of my JavaScript knowledge, one of my areas of focus is the organization of JavaScript code, specifically within Drupal.

    Organization is something we give a lot of thought to at Aten Design Group. We are fairly collaborative, and within this context, the merits of thoughtfully organized code are self-evident. We strive for clarity in the arrangement of our Drupal modules, the naming conventions used for our SASS components and the verbosity of our GIT commit messages and branches. Another such space is in the organization of JavaScript within our Drupal themes and modules.

    Enter the JavaScript Module Pattern (not to be confused with a Drupal module, though the idea of reusable code persists). Rather than lumping code into a gargantuan main.js, something one frequently sees in theme development, we can create thoughtfully named and reusable JavaScript modules. It gives us a way to write and encapsulate JavaScript functions in a manner that denotes their specific usage, leading to a more easily maintained project.

    For instance, we can write a JavaScript module that loads content into a modal popup box, independent of what content will actually be loaded. We can then use the module in, say, js/main.js where we’ve noted that on such and such page, such and such form should be loaded and displayed to the user, while on such and such other page, such and such other form should instead be displayed. When done right, debugging problems with the aforementioned interaction can be minimized, something intrinsic to better code organization.

    // This is js/modules/myJavaScriptModule.js
    var myJavaScriptModule = (function(){
      var myJS = {};
      myJS.moduleMethod = function () {
        // Do something terribly useful, right here.
      };
    
      return myJS;
    }());
    
    // This is js/main.js
    Drupal.behaviors.myModule =  {
      attach: function (context, settings) {
    
        // Use the terribly useful JavaScript Module.
        myJavaScriptModule.moduleMethod();
      }
    };

    Note, this assumes that these files have been loaded in the right order.

    Now, JavaScript modules can be somewhat sticky, in that they still don’t solve some of the larger issues inherent to JavaScript. A much espoused creed in JavaScript is “Don’t Pollute The Global Namespace! Exclamation!”. JavaScript modules generally export their value into the global namespace, and while this isn’t always disastrous, it can lead to strange bugs or code implosions. This is particularly true when working with code you didn’t necessarily write, or when you expect your code to be reused by strangers. Another issue that persists is the handling of dependencies. If your JS module needs another JS module to function, you better make sure they are loading in the correct order. Now imagine this problem snowballing as one breaks more and more code out into JS modules.

    These issues, amongst others, are addressed if one takes JS modules a step further, with Asynchronous Module Definitions. Dependency management is handled, as the function won’t execute until all of its dependencies have loaded. Additionally, JS modules are loaded asynchronously, which means a more performant JavaScript experience.

    define(['aDependency'], function (aDependency) {
    
        // Define the module value by returning a value.
        return function () {};
    });

    We’re getting warmer, but this is where things begin to get a bit sticky when working with Drupal, as once we have an AMD specified piece of code, we need a means by which to load it. A likely candidate for AMD module loading is RequireJS, but using RequireJS within Drupal is not simply a matter of dropping it into your theme or module. And thus, the ramble. It begins like this.

    JavaScript Architecture in Drupal - Moving Forward

    In Drupal, JavaScript lives all over the place. It exists in Drupal core, contributed and custom modules, and in Drupal themes. This makes for an interesting problem, in that JavaScript is not the sole problem domain of front-end developers, as it is often described. We have a PHP function for interacting with this, in the form of drupal_add_js(). This aggregates all JS into an array, where JavaScripts are loaded based on their respective weight in the array. Controlling these weights can be very cumbersome, particularly for the front-end developer.

    Essentially, Drupal’s JavaScript architecture has a completely unique and sometimes eccentric API for interacting with a larger problem domain. This brings to mind a term I’ve come across in the time I’ve been a Drupal developer. The term is Drupalism. A Drupalism is something that is needlessly unique to Drupal, in that it is a weird way we Drupal developers do things. Now, I’m not saying outright that drupal_add_js() is a Drupalism, but the JavaScript architecture of Drupal is not something one can instantly acclimate to. JavaScript in Drupal is not as malleable as it ought to be. Derivative of this is the fact that, as a front-end developer, I cannot easily update jQuery or use RequireJS for loading AMD modules.

    As Drupal 8 continues to take shape, Drupal developers should more loudly discuss the management of JavaScript in Drupal. There are a few threads on drupal.org that discuss AMD in Drupal. And though it may be too late this go-around, we should consider creating a more pluggable JavaScript architecture, perhaps leveraging RequireJS for module loading. It occurs to me that implementing a widely used system like RequireJS might attract new front-end talent to Drupal. This would be analogous to a noted benefit in the decision to add Symfony2 to Drupal core, in that “The use of widely used libraries and techniques makes Drupal more approachable to new developers.”

    Onward, to RequireJS

    Though we cannot immediately reap all the benefits of AMD JavaScript modules and RequireJS in Drupal, we can still use these tools in a meaningful way. There is overlap between Drupal’s JavaScript architecture and RequireJS, but they aren’t mutually exclusive. If our corner of Drupal (theme or module) can benefit from better JS organization, we can arrange and load AMD modules, and then funnel this conglomerate to the extant JavaScript API with drupal_add_js().

    There are a great many tutorials on using RequireJS, and in an effort to keep the scope of this already rambling post a bit more concise, I’ll leave it to the reader to look to those. Of particular note is r.js, which will optimize AMD performance. Here, I’d like to describe special considerations in implementing RequireJS from within a Drupal theme.

    Once we’ve arranged our JavaScript using the AMD pattern, we need only add the RequireJS script tag to our theme in order to load these modules. This can be done from template.php, as follows:

    /**
     * Implements hook_preprocess_html().
     */
    function mytheme_preprocess_html(&$vars) {
    
      drupal_add_js(drupal_get_path('theme', 'prototype') . '/js/require.js', array('every_page' => TRUE, 'external' => TRUE));
    }
    
    /**
     * Implements hook_preprocess_html_tag().
     */
    function mytheme_preprocess_html_tag(&$vars) {
      if (isset($vars['element']['#attributes']['src'])
          && $vars['element']['#attributes']['src'] == '/' . drupal_get_path('theme', 'mytheme') . '/js/require.js') {
              $vars['element']['#attributes']['data-main'] = '/' . drupal_get_path('theme', 'mytheme') . '/js/main';
      }
    }

    This approach, though not perfect, is still relevant if one plans on implementing more complex JS in displaying or manipulating Drupal data. There are decisions to be made about what kind of interactions should occur with the larger architecture, but one tangent is enough for today. For now, it’s nice to know that RequireJS and drupal_add_js() can get along as we pursue a clean JavaScript architecture in Drupal.

    Originally published on the Aten blog

  • // Comments

    Call me Garrett. I’m a front-end developer, and I’ve just recently joined team Aten. What an opportunity, to work with this exceptional design and development shop, and with such gifted and positive people.

    I’ve been a web creator for the past four or five years. Like many people in my field, I began my career as a web designer almost accidentally; by following a meandering path of inquiry that eventually led me to a desire to build the web, but started with a simple wish to communicate.

    I’m an artist, and have always felt that my art, and really, all art, is motivated by the need to be understood. To speak with other people. Nothing man-made is created for the vacuum, but rather, is inspired by this desire to bring people together, and most crucially, to connect ideas with people and their reality.

    Exploring this idea is how I found myself pursuing web creation. As communication moves increasingly to a completely new medium, what better way to explore that medium than to build it.

    Along this path, I’ve learned many things. I’ve worked with many people, all motivated by different philosophies and ideas. Given my own personal philosophies, it’s no accident that I now find myself in the employ of Aten Design Group. Aten is a shop that prioritizes working with organizations that promote good in the world. Organizations that seem to understand the web as a powerful conduit for positive ideas, rather than the means to a more overwhelming and inescapable marketing system.

    I am very enthusiastic about having the opportunity to work with Aten Design Group. Time spent with Aten will be time spent building meaningful works, in a medium that is often characterized as the avenue to a loss of meaning. I’m glad to be here.

    Originally published on the Aten blog

    * Photo used under Creative Commons license from Nick Bramhall.

  • // Comments

    Page Manager and Panels are enormously capable modules for Drupal, but getting started with them can be pretty tricky. Here, I'll describe how I used Page Manager, Panels and Views Content Panes to build a Taxonomy driven content structure. I'll also describe some of the fundamental Page Manager concepts that I'm still digesting.

    The quote I borrowed for the title of this post is from Johan Falk, who will be sorely missed by the Drupal community, as the screencast series he produced for Node One on Page Manager is exceptionally informative, and often hilarious. If you haven’t seen the series, check it out.

    Ahem, Okay. First, let’s understand what Page Manager actually is; Page Manager is a sort of responder to HTTP requests that overrides Drupal’s natural behavior. Drupal generally establishes a URI structure that dictates where a piece of Drupal content lives. With Page Manager, we can begin overriding Drupal’s behavior, injecting content that is architected with something like Views where Drupal content would normally be. I guess that means that Page Manager is really a content manager, at least in application. If this is a poorly formed assumption, please leave a comment.

    Used is conjuction with Panels, which is a layout manager, we suddenly have enormous potential for controlling the typical content that appears at, say, node/ or taxonomy/term/. We can more easily control the content flow. This is just the thing I need to manipulate what typically appears at Drupal’s often used, but pretty lame, term pages.

    Here is my use case. I’ve built a navigation using Taxonomy Menu, which is rad, as I have a large dynamic Taxonomy that needs to control the flow of how a user winds up on a node page. By default, each menu item links to the term page used to build it.

    At a term page, I want to see any node that have been tagged with the term, and any child terms that the term has, so that I can build a pretty looking catalog. Like this:

    Parent term (i want to see a list of all children)
    - Child term (i want to see a list of all grandchildren)
    -- Grandchild term (this is where I want nodes to appear)

    This can be halfway done with Views, or maybe even completely done with Views, but attempting a pure Views approach was like pulling out my own teeth. So, this is where I turned to Page Manager, as I can begin overriding what appears at a term page.

    Because of Drupal’s kindness, we have an argument available at a term page that dictates what term appears. This means Page Manager can know that argument, and we can then pass that argument to whatever appears on the page. In our case, thats Views Content Panes. So, enable Page Manager and Panels, and then enable the term page manager that it comes with stock.

    enabling page manager's term page

    Okay. If you’ve watched Johan’s screencast, you should have a sense of what is going on here. We’ve enabled the page override, and now we need to tell it what to do. So, we’ll create a variant that responds to a request for a term with a panel display. Using Page Manager’s selection rules, we can also instruct Page Manager to only respond if the request is for a term that belongs to a particular category. In my case, this is my navigation taxonomy.

    Now, we can use the Panels layout interface to determine what kind of panels system we want. I’/m not looking for anything fancy, so I used a single column layout.

    Now, lets hop over to Views, where we’ll build some content to feed to Page Manager. In my case, I want two distinct views; One that returns nodes, and one that returns child terms. With page manager, we can get these to co-exist on a single page if the Views display is a Views Content Pane. This is a new display option that one has after enabling Page Manager.

    It’s worth noting that, by default, Page Manager can display child terms of a term, but this is better done with a view so that we can include fields attached to the terms, just like with any view.

    Now for the tricky part. For each of these views, we essentially want to contextually filter them with an argument that is being passed to the view by Page Manager. Johan Falk suggests using “context” as the argument input for each view, but I couldn’t get this working. Instead, I’ve used Panel arguments.

    So, build and configure the master display for each view as normal. This means creating a contextual filter based on a term id.

    For the node view, we get this via a relationship called “Content: Taxonomy terms on node”, and a contextual filter of “(term) Taxonomy term: Term ID”.

    For the term view, we’ll add a relationship called “Taxonomy term: Parent term”, so that we can use the parent term’s tid to filter. Again, we’ll add a contextual filter called “(Parent) Taxonomy term: Term ID”.

    Now, for magic. As we have two views that can be contextually filtered by a term id, we can configure where that contextual filter comes from. To do so, create a new display for each view, selecting “Views Content Pane” as the display type. Once that is done, we can configure where that contextual filter is fetched from, using the “Argument Input” setting.

    Argument Input

    Configure each view to get it’s contextual filter argument from “Panel Argument 1”.

    Now we’ve got some views to plug into Page Manager. Navigate back to Page Manager, and add some content to our term view override. At the content tab, hit the little gear and select “Add Content”. In the list of options under “Views Panes”, we can see both of the content panes we just built. Add both, and arrange them however you like.

    Now, on a term page, we’ll see a list of Child terms, and any nodes tagged with that term. The views content panes are responding to the argument that typically exists on the page, which is being passed to the view as a panel argument.