HTML5 Portfolio Project – Part 5

When I start a project, I like to tackle the parts that are new to me first. Obviously, I enjoy the dopamine hit from exploring something unfamiliar, but also, I've found that this is a great way to catch "gotchas" early, rather than waiting until the end when work-arounds might require substancial changes to parts of the code that would otherwise be more pedestrian.

With that approach in mind, I've spent a ridiculous amount of the last couple weeks hacking on a circular mask transition effect. I'd gotten this to work fine in the past for image content, but I wanted to be sure it would support other types of content too—a video player for instance. Ideally, I'd end up with a jQuery effect that could handle an arbitrary <div>. It should work on the latest version of any browser (and degrade gracefully in IE7/8).

This has proved itself a challenge several orders of magnitude larger than I'd expected.

The Big Deal

Perhaps the HTML spec isn't as clear as it ought to be: if you specify overflow: hidden, the clipping region should take border-radius into account. Firefox and IE9 do. That leaves a whole lot of everything else. As long as your content is an image, you can apply a border-radius to that, and the clipping looks OK as long as the image is square (IE7/8 notwithstanding). But you can't properly offset the image in its container (we'll get to why we need that eventually) unless you apply the image as a background.

In the interest of moving forward, I'm going to use the background-image technique, but that isn't going to help for videos etc. I also evaluated webkit-mask-image (webkit-only obviously) and using a canvas buffer (doesn't seem to work in Safari). Now, if you're paying attention, a combination of all-of-the-above would let us support all browsers, but I'm calling "scope creep" and deferring this to version 1.1. In the meantime, I'll probably use a lightbox for videos.

It hasn't been a complete waste. On the contrary, I learned quite a bit about CSS PIE and ExplorerCanvas.


Speaking of which, multiple commercial projects are conflicting with my original release schedule. June 1 is going to come and go, so I'm setting a new goal of July 1.

I'm not doing so well keeping to the hourly budget either. I burned through the original estimate just trying to get this effect working (everywhere). I'd originally estimated 3 hours and spent closer to 30. Ouch!

Like I said, warts and all.

Stay Tuned

Next time I'll show the sunburst background (a canvas-based effect) and the aforementioned circular mask (of doom) with compound borders. I already have this working, but I want to clean up the code before doing a write-up.


HTML5 Portfolio Project – Part 4

I'm structuring the project folder like this:




If your information architecture is tight, you'll likely see echoes of your file hierarchy in your data hierarchy and echoes from both in your code's object hierarchy. Guess that means we're going to need some code then.

Stay Tuned:

In the next installment, we're going to spend a little time playing with jQuery-based animation so that we're comfortable with it before trying to integrate the effect into the site itself.

HTML5 Portfolio Project – Part 3

Don Your Project Manager Hat

A week with no updates?! ... And things are about to get more busy, not less.

Plus, upon reviewing the project plan, I noticed an omission: there's no specific line item for the mask transition. It seemed so obvious, I neglected to capture it in the schedule. I'm adding 3 hours to account for it (new total: 44 hrs).

Ok, To Work Then

Last time, I talked a bit about the data model. Since then, I've thought of some improvements. Just because the Flash version worked a certain way doesn't mean I shouldn't re-evaluate my assumptions.

First, the home screen ought to be treated as a node. It has a url and graphical content, just like the portfolio pieces. It's button-ness behaves a little differently, and it's sized larger, but we should be able to abstract away the differences. In theory, it would be nice to allow unlimited node nesting. This would allow projects to have sub-projects (for example) and enable a lot more organizational flexibility, extending the useful lifetime of the site. We'll see if we can squeeze it in. (Google: YAGNI)

    "url"         : "/",
    "title"       : "shovemedia portfolio 2012",
    "content"     : "homepage.html",
    "sections"     : [
            "url"         : "contact",
            "client"      : "Email:<br />",
            "title"       : "contact info",
            "date"        : "01/01/2011",
            "role"        : "developer",
            "link"        : " Business",
            "thumbnail"   : "thumbnails/email.jpg",
            "content"     : "contact.html"
            "url"         : "3D",
            "client"      : "Photobiz",
            "title"       : "3D Templates",
            "date"        : "01/01/2011",
            "role"        : "developer",
            "link"        : "",
            "thumbnail"   : "thumbnails/3d-templates.jpg",
            "sections"        : [
                      "url"     : "video",
                      "title"   : "watch!",
                      "icon"    : "video",
                      "content" : "papervision/videoPlayer.html"
                      "url"     : "image1",
                      "title"   : "Image 1",
                      "icon"    : "pic",
                      "content" : "papervision/image1.jpg"
                      "url"     : "description",
                      "icon"    : "description",
                      "content" : "papervision/description.html",

Don't get lost in the braces. Deeper nesting is a necessary evil, I think. Otherwise, I'm going to end up with redundant references to "link" all the flattened elements.

I've also changed some of my naming conventions. Each nodes stores its child nodes in an Array called "sections".

Automatic Value-Object Mediation with JS Signals

Just a little something I cooked up tonight after a few beers with Lee:

ModelMediator = function (model) {
  this.__onChanged__ = new Dictionary();

  for (var key in model)
    this.__defineSetter__(key, function (arg) { this.set(model, key, arg) });
    this.__defineGetter__(key, function () { this.get(model, key) });
    this.__onChanged__.set(key, new signals.Signal());

ModelMediator.prototype.get = function (model, key)
  return model[key]

ModelMediator.prototype.set = function (model, key, value)
  model[key] = value;
  this.__onChanged__.get(key).dispatch({model:model, key:key, value:value});

Dictionary class here

Downloading and understanding JS Signals is left as an exercise for the reader.

Dictionary Class (JavaScript / JS)

I sorely miss the Dictionary class from AS3, but wasn't excited by what my Googles led to and figured I'd learn more by rolling my own.

JavaScript Arrays can be used as a hash, but only with String or Numeric keys. This class lets you use any Object. A function, an Array, a class ... anything. It could be faster, among other possible improvements, but this implementation has been coming in handy all over.

Dictionary = function ()
  this.keys = [];
  this.values = [];

Dictionary.prototype.get = function (key)
  var index = this.keys.indexOf(key);
  if (index != -1)
    return this.values[index];

Dictionary.prototype.set = function (key, value)
  var index = this.keys.indexOf(key);
  if (index == -1)
    index = this.keys.length - 1;

  this.values[index] = value;

Dictionary.prototype.remove = function (key)
  var index = this.keys.indexOf(key);
  if (index == -1)
      return undefined;

  var value = this.values[index];


  return value;

Removing Trace and Logging Statements for Production

I'm saving these recipes here so I can bookmark, and I'm sure someone else will find them useful.

I decided to convert calls to trace or my logging framework to use conditional compilation so that they won't be included when I do a production build, but are included when I do a debug build.

The Flex compiler supports this by allowing you to set a variable at compile-time, eg:


In your code, simply wrap the code to be conditionally compiled in curly braces, prepended with this variable, eg:

	trace( 'Debug' );

I spent some time writing a regular expression that finds trace statements, and wraps them in this block. In plain English, start at the beginning of the line, match zero or more whitespace, the word "trace", zero or more whitespace, an open parenthesis, the rest of the line.

Search for: ^([ \t]*)(trace[ \t]*\(.*)$
Replace with: $1CONFIG::debug { $2 }

FDT's internal parser doesn't like the conditional compilation syntax, so we need to change our replacement text slightly to wrap that part in markers instructing it to ignore them.

Search for: ^([ \t]*)(trace[ \t]*\(.*)$
Replace with: $1/*FDT_IGNORE*/ CONFIG::debug /*FDT_IGNORE*/ { $2 }

The same recipe for any call to logger, eg: logger.debug,, logger.warn, etc.

Search for: ^([ \t]*)(logger\..*)$
Replace with: $1/*FDT_IGNORE*/ CONFIG::debug /*FDT_IGNORE*/ { $2 }

Masking TLF (Text Layout Framework)

Just a quick note to point out a bug (?) I found today while working with the ActionScript 3 Text Layout Framework.

I wanted to add a mask to the Sprite container I'd passed to my TLF ContainerController. Whatever it is that happened wasn't correct: there was masking occurring, but the shape I was using as a mask was (incorrectly) visible on the stage. Rolling over my buttons caused redraw of stage regions, and my TLF text in those areas would go from invisible to incorrectly masked.

After trying several things, I pulled an old-school trick out of my bag: nest the Sprite I was passing as a container to the ContainerController in another holder Sprite, and apply the mask to the holder instead. From there, everything worked as expected.

Note: I further tracked this down to be caused by the ContainerController being created smaller than the text stuffed inside. Only then do I have problems with masking. YMMV.

(See the original post)

I messed around with this quite a bit but was never able to get things to work exactly as I'd hoped. I even got as far as using the XmlTask Ant extensions to modify the launch file on the fly. Unfortunately, I couldn't figure out how to get Eclipse to reload the modified configuration without completely restarting, so that path resulted more or less in a dead end.

What I did figure out is how to make your launch configurations shareable via SVN, so that only one team member (yours truly) has to deal with builds and launch configurations. Everyone else can update from SVN and run ANT tasks without being familiar with all these grisly details.

The last post mentioned (with no small amount of grumbling) that you have to change the JRE setting to "Same JRE as Workspace" on every single build target you create (or rename). This is incredibly annoying. If you go to the same dialog: Run >> External Tools >> External Tools Configurations...

Check out the Common Tab. Here you can pull the launch file configuration into the project and out of the workspace by selecting "Shared file" instead of "Local file". This lets you share launch configurations with the rest of the team.

If you wish, you can create a template for new build targets. If you get the file naming convention right, you should be able to get away with defining new build targets without ever needing to visit the External Tools Configurations dialog. I've got a mixed OS X / Windows Team, so I made some modifications to Eclipse's default launch file output. In short, I removed explicit references to my OS X default JVM.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ant.ui.DEFAULT_VM_INSTALL" value="false"/>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
<listEntry value="/PROJECT_NAME/build.xml"/>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
<listEntry value="1"/>
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="PROJECT_NAME"/>
<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_ANT_TARGETS" value="BUILD_TARGET_NAME"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/PROJECT_NAME/build.xml}"/>
<stringAttribute key="process_factory_id" value="org.eclipse.ant.ui.remoteAntProcessFactory"/>

Note the spots where you should substitute your own PROJECT_NAME and BUILD_TARGET_NAME.

I tried setting the DEFAULT_VM_INSTALL to true, and it worked, but Eclipse insisted on mucking with it as soon as I visited the External Tools Configurations dialog again.

I'm storing my launch files in .settings and setting the filename to:

Your mileage will almost certainly vary.

Use FDT Folder Path Variables in ANT

My latest FDT project has a lot of sub-projects. We've got a small team of mixed Mac and Windows users, so we don't want to assume any particular project directory structure if we can help it. The original thinking was to export SWC files for each sub-project, copy them to the appropriate projects for which they are dependencies, wash-rinse-repeat. I'd assumed I'd be able to use FDTs pre/post-build ANT tasks for this, but unfortunately you only get that tab when building to SWF, not for SWCs.

This brought about the idea of putting the entire build routine in ANT, but I hit another roadblock: I want the team members to be able to define folder path variables using the FDT Eclipse Linked Libraries mechanism. To access these:

  • Right-click the FDT project folder >> Properties
  • Choose FDT Build Path
  • Click "Add Linked Libraries..."
  • Click "Add..."

This window lets you manage folder and SWC paths in an abstract way so that build files and classpaths can use the variable instead of a hardcoded path. As long as each team member uses the same variable name, you can share build scripts and complicated classpath settings. All you have to do is tell SVN to ignore the .project file, and everything should be golden.

Ok, so how do you get access to those variables within your ANT scripts? Like this:

<project name="SampleProject" default="compileAll" basedir=".">
    <!-- Import FDT path variables for use as ANT properties -->
    <property file="${basedir}/../.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.resources.prefs"/>

    <!-- etc -->

(I know the wordpress template makes that impossible to read. Cut paste it.) There are some fairly radical assumptions at work here, and I'm not enough of an Eclipse expert to know if it will work in all environments (plus, there are a LOT of variations in environments out there). The idea, however, is that all projects are direct children of the workspace. Therefore, backing up one level from the basedir should put you in the root of the workspace. From there, the path to the aforementioned FDT path variable property file should be as listed. That, of course, assumes that your Eclipse projects are using the default path. If they aren't, you're on your own. I wasn't able to find a workspace variable that gets passed to ANT automatically, but you should be able to set one yourself by going to the menu Run >> External Tools >> External Tools Configurations... In the Arguments textbox, put:


That would let you use the workspace location directly:

    <!-- Import FDT path variables for use as ANT properties -->
    <property file="${workspace_loc}/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.resources.prefs"/>

You'll need to become at least passingly familiar with the External Tools dialog because you'll be visiting it more often than you'd like in order to bypass a minor oversight by the FDT team (IMHO). Go to the JRE tab and switch your Runtime JRE to "Run in the same JRE as the workspace". If I recall correctly, you'll have to do this every time you create a new build target (sigh). If you know a better way, by all means leave a comment.

This configuration also assumes that the build.xml file is a direct child of the project folder, ie basedir="." If this isn't the case you should now have enough info to pass the project folder as well. (Hint: try project_loc or project_path)

Once you've done this, your FDT path variables can be accessed by prefixing with "pathvariable". For example:

<echo message="${pathvariable.AS3SWF_SRC}" />

It took a little Googling on my part to find how to properly export a SWC under ANT without resorting to a complete re-configuration of the classpath. FDT includes an ANT task specifically meant for this purpose. An example looks like:

<target name="generateSwc2">

Getting all the variables set up is left as an exercise for the reader. For some help, try Boostworthy's seminal article.

You should now have all the pieces required to compile and copy SWCs without having paths to specific projects or tools littering your ANT build files. Good luck!

In Defense of Dependency Injection

I've been rolling the RobotLegs framework into a new project, but not all the team members are sold on the idea, mostly because it represents third-party code that's complex and difficult (impossible?) to understand just by reading over the source.

I realized I was having a difficult time articulating the advantages to the approach, and specifically, the fact that the closest alternatives are every bit as complex and headache-inducing once you get down into the details.

So, what follows is a bit of a thought experiment using a very simple case. Hopefully, by the end, you'll see that what's true for a single, simple case is also true for multiple, complex cases, and in the end, it actually makes good sense to have a framework handle these things.

Imagine first, a Main class. There's only one Main across the entire codebase. Now imagine classes A, B, C, etc (there are a lot of them) that all use a ColorManager class. A, B, C are separate SWFs, so it makes sense for ColorManager to be compiled into Main, and somehow linked into the A, B, and C modules, but not compiled into them. This in itself can be a bit tricky, and there are a few different approaches, with assorted pros and cons.

Our first thought is to compile against a linked SWC containing the concrete ColorManager class. That will keep the actual implementation out of our modules, but any change to ColorManager will require re-compiling every SWF that uses it. Less than ideal.

We could say:

public class A
  private var colorManagerClass:Class = getDefinitionByName("ColorManager");
  private var colorManager:IColorManager = new colorManagerClass();

It gets the job done, and it's easy to understand. As long as the interface stays in synch, it's not too hard to make changes to the concrete ColorManager class without recompiling the module (and all the others). That synched interface is a pretty big caveat, but we'll find that most (all?) approaches share it. We could forego the interface completely, but at the expense of loosing very valuable strong-typing and code completion.

The downside would be that the concrete class absolutely must be "ColorManager" -- even though we've gone to the trouble of creating an interface (which would/should/could allow other implementations) were stuck with the one-and-only ColorManager returned by getDefinitionByName. The simplest way to make this dynamic? Pass in the String representing the class name. You know what that's called? Dependency Injection. If you're willing to pass in a String, you might as well pass in the class itself.

Another quibble with this technique is that it relies on something known as a "magic string." The compiler doesn't have a way of warning you that this class does or doesn't exist, or that it correctly implements the IColorManager interface. You'll need to rely on runtime warnings for that. It's very easy to misspell or miscapitalize the package/classname breaking everything.

Ok, my (completely competent) team member suggests, we can provide a setter for the class. That might look like:

public class A
  private var colorManager:IColorManager

  public function setColorManagerClass (colorManagerClass:IColorManager)
    this.colorManager = new colorManagerClass();

Again, this is merely another way of doing Dependency Injection. The real question is whether you'll be using a framework to provide dependencies automatically. We'll come back to address this separately.

What about having our class request the class at runtime, rather than relying on the fact that it will be injected. Something like this:

public class A
  private var classLocatorServiceInstance:ClassLocatorService;
  private var colorManager:IColorManager;

  public function initColorManager()
    var colorManagerClass:Class = classLocatorServiceInstance.getConcreteClass(IColorManager);
    this.colorManager = new colorManagerClass();

This implementation, while quite valid, raises more questions than it answers. Who calls initColorManager? How can it be sure the ClassLocatorService is ready to provide ColorManager? And just where does this ClassLocatorService come from any way? It's a singleton? How is that enforced? Did you notice how we're requesting the concrete class? Via its interface. We've got the same problem with allowing only one implementation of IColorManager. In order to allow multiple implementations, we're back to using a magic String.