Hi, I'm Ben. This used to be my blog.
It is now an archive, so comments are disabled.

Smooth Scrolling Flex List

Smooth scrolling is a pretty common request for the List component in Flex. Flex Team engineer Alex Harui provided a working, albeit unofficial, example a while back. Michael Ritchie recently ported that example to HorizontalList. I’ve been sitting on some code for a while now and Michael’s tweet on the topic convinced me to finally post my take on the subject.

While in San Francisco for Adobe MAX last November, I volunteered to help out another team from Universal Mind on a project. The task I was assigned was to make a smooth scrolling List. The List had to support variable row heights, which meant Alex’s implementation wasn’t an option. The List also had to support drag and drop, which meant writing my own list component from scratch wasn’t feasible either. I was basically left with only one option: cheat. What I ended up doing was to create a List that would ensure that it was always tall enough to create and show all of its renderers. Wrapping that in a Canvas would then simulate smooth scrolling by utilizing the Canvas’s scroll mechanism instead of the List’s.

Check out the demo (view source enabled) or go straight to the source.

It would obviously be a bad idea to use this if your dataProvider had a ton of items in it, but for most use cases it should work pretty well. The code is pretty straightforward and heavily commented so I won’t rehash everything here. If you have questions feel free to post a comment.

Enjoy!

What the Flex? – HierarchicalCollectionView

If you’ve ever used an AdvancedDataGrid, chances are you’ve encountered HierarchicalCollectionView. If you’ve ever used an AdvancedDataGrid for anything remotely complex, chances are you’ve cursed and shaken your metaphorical fists at HierarchicalCollectionView.

There are likely myriad reasons to despise this class but the one that burned me was this gem: any filterFunction applied to your HierarchicalCollectionView is also applied directly to your underlying child collections. In case the ramifications of that are not immediately clear, what it means is that you cannot simultaneously have two distinct views of a single data set that you have wrapped into a HierarchicalCollectionView. In fact, once applied you will have to manually clear the filter from underlying collections in order to get them back to normal. Because of this, the class is of extremely limited utility, and I would submit that its name is highly misleading. The ‘View’ at the end of the name implies that it will be creating a “virtual” view of the underlying data, leaving the source intact. This is how the immensely useful ListCollectionView class works. Apparently, other languages/frameworks also have “collection view” classes that do not modify the underlying data, so this is quite a departure from convention, not to mention common sense.

If you happen to look at the docs for HierarchicalCollectionView you will notice that filterFunction isn’t even listed as a supported property. Maybe the thinking was if they don’t tell anyone about it, we’ll overlook how poorly implemented it is?

Custom IList implementation to flatten hierarchical data

I recently needed to show a set of hierarchical data in a Flex List component. By default, the List component displays a one dimensional, or flat, set of data. In my case the hierarchy was to be shown by displaying the top level objects as dividers with a different visual appearance than their child items. The wrong way to do that would be to create a whole new list that is flat, with some artificial property to differentiate top level objects from children.

I remembered hearing Deepa talk about some sort of virtual lists at MAX 2007, so I started Google-ing. Turns out she was talking about IList implementations. Unfortunately, her examples and every other example I found demonstrated using IList to virtually merge two separate, but related lists of objects. This wasn't what I needed, but it put me on the right track.

As it turns out, the only parts of IList you have to implement are the length getter and the getItemAt() method. I realized that by having control over getItemAt(), you could essentially hide what your list actually contains and return whatever you want. The result is FlattenedList (source). For the lazy and impatient (that includes me) I have included the two most important pieces here:

public function FlattenedList( items:Array, subCollectionFieldName:String )
{
    // store master list
    this.items = items;
    this.subCollectionFieldName = subCollectionFieldName;

    // the first grouping will obviously start at zero
    topLevelObjectIndexes.push( 0 );

    for each( var obj:Object in items )
    {
        // create internal length var to hold total number of items, regardless of level
        _length += obj[ subCollectionFieldName ].length + 1;

        // the next grouping will begin at the index equal to the total number of items already counted
        topLevelObjectIndexes.push( _length );
    }

    // remove last entry since its for next grouping, which doesn't exist
    topLevelObjectIndexes.pop();
}

public function getItemAt( index:int, prefetch:int = 0 ):Object
{
    // iterate over our list of index dividing points
    for( var i:int = 0; i <topLevelObjectIndexes.length; i++ )
    {
        // if the requested index is between the current and next stored index
        // or we've reached the last stored index, use this top level object
        if( index>= topLevelObjectIndexes[ i ] && ( index <topLevelObjectIndexes[ i + 1 ] ||  i == topLevelObjectIndexes.length - 1 ) )
        {
            // get a ref to the top level object
            var topLevelObject:Object = items[ i ];
            // get the "local index" that will be applied to selected top level object
            var indexDelta:int = index - topLevelObjectIndexes[ i ];

            // if requested index is equal to stored start index we return the top level object itself
            if( indexDelta == 0 )
            {
                return topLevelObject;
            }
            else // otherwise we return one of its child objects
            {
                return topLevelObject[ subCollectionFieldName ][ indexDelta - 1 ];
            }
        }
    }

    return {};
}

The code is heavily commented and fairly straightforward so I won't try to explain it here, but take a look and see what you think. I will provide some disclaimers that I only implemented as much as I needed, so there are several unimplemented IList methods in the class. I did implement toArray() because its required to support sorting and filtering. I suppose a better approach might be to subclass an existing IList implementation and just override what you need. As it turns out, ListCollectionView is the only IList implementation in the Flex framework and its a great class that will probably be the subject of a future blog post here.

Lastly, it probably wouldn't take much tweaking to allow FlattenedList to support an infinite/variable level of nesting versus the single level it supports right now. Anyone out there up for a challenge?

Flash Player on OS X bug in need of votes

I submitted a bug a while back titled KeyboardEvent.keyCode value is decremented by 64 when Control key is down on Mac and it seems to be languishing in the purgatory that is Community status. While the title is pretty self explanatory, what it boils down to is that adding keyboard shortcuts to your Flex application can become quite tricky if you plan on supporting Mac users.

Particularly troublesome is the Q key, whose keyCode is normally 81. Thanks to this bug, Ctrl + Q returns a keyCode of 17. Problem is, 17 is also the keyCode for Ctrl by itself, and for Command by itself. Discerning between the two is more or less impossible, which sucks.

Can I get some vote love from the community?

Simple monkey patch to fix ToolTipManager.toolTipClass

ToolTipManager.toolTipClass doesn't work in Flex 3.0 out of the box. While its intent of allowing you to specify a custom IToolTip implementation is great, ToolTipManagerImpl simply acts as if the property doesn't exist and instantiates an instance of ToolTip. Luckily, the fix is quite easy if you are willing to do a bit of monkey patching. You just have to make a slight modification to the createToolTip() method, making it look like the following:

public function createToolTip(text:String, x:Number, y:Number,
                                     errorTipBorderStyle:String = null,
                                     context:IUIComponent = null):IToolTip
{
    // ***** USE THE PROPERTY! *****
    var toolTip:IToolTip = new ToolTipManager.toolTipClass();

    var sm:ISystemManager = context ?
                            context.systemManager :
                            ApplicationGlobals.application.systemManager;
    sm.toolTipChildren.addChild(UIComponent(toolTip));

    if (errorTipBorderStyle)
    {
        UIComponent(toolTip).setStyle("styleName", "errorTip");
        UIComponent(toolTip).setStyle("borderStyle", errorTipBorderStyle);
    }

    toolTip.text = text;

    sizeTip(toolTip);

    toolTip.move(x, y);
    // Ensure that tip is on screen?
    // Should x and y for error tip be tip of pointy border?

    // show effect?

    return toolTip;
}

Here is a diff of the base and updated classes.

As an aside, an easier fix is said to exist here, but it doesn't seem to work when calling ToolTipManager.createToolTip() directly, which is what I needed to do. If you are using toolTips normally by just setting the toolTip property I would recommend trying Peter's fix first.

I would also like to go on record that I hate the *Impl naming convention. Despite what Theo says, I like my interfaces with I's. *Impl just seems kludgy and redundant, and it reminds me of AS2.

flexmdi sans MXML

Update: I have slightly modified the code below to correct a mistake in the original post. Thanks to Brindy for pointing it out.

Every now and then I come across a request of how to use FlexMDI using only ActionScript. Its completely straightforward but I have finally gotten around to getting an example up. The first code snippet shows how to do this while still utilizing MDICanvas for some of the convenience it provides.

import flexmdi.containers.MDICanvas;
import flexmdi.containers.MDIWindow;
import flexmdi.effects.effectsLib.MDIVistaEffects;

private function init():void
{
    var mdic:MDICanvas = new MDICanvas();
    mdic.percentWidth = mdic.percentHeight = 100;
    mdic.effects = new MDIVistaEffects();

    var win1:MDIWindow = new MDIWindow();
    win1.title = "First Window";
    win1.width = 300;
    win1.height = 200;
    mdic.windowManager.add( win1 );

    var win2:MDIWindow = new MDIWindow();
    win2.title = "Second Window";
    win2.width = 300;
    win2.height = 200;
    win2.x = 325;
    win2.y = 50;
    mdic.windowManager.add( win2 );

    var btn:Button = new Button();
    btn.label = "Awesome Button";
    win2.addChild( btn );

    addChild( mdic );
}

This next example shows how to turn a basic Canvas component into the container for an MDI implementation.

import flexmdi.containers.MDICanvas;
import flexmdi.containers.MDIWindow;
import flexmdi.effects.effectsLib.MDIVistaEffects;
import flexmdi.managers.MDIManager;

import mx.containers.Canvas;

private function init():void
{
    var canvas:Canvas = new Canvas()
    canvas.percentWidth = canvas.percentHeight = 100;

    var mgr:MDIManager = new MDIManager( canvas, new MDIVistaEffects() );

    var win1:MDIWindow = new MDIWindow();
    mgr.add( win1 );
    win1.title = "First Window";
    win1.width = 300;
    win1.height = 200;
    win1.x = win1.y = 10;

    var win2:MDIWindow = new MDIWindow();
    mgr.add( win2 );
    win2.title = "Second Window";
    win2.width = 300;
    win2.height = 200;
    win2.x = 350;
    win2.y = 100;

    var btn:Button = new Button();
    btn.label = "Awesome Button";
    win2.addChild( btn );

    addChild( canvas );
}

Hopefully this clears up some of the uncertainty around how to use FlexMDI without our good friend MXML but feel free to ask questions in the comments.

Creating bindable, calculated read-only properties in Flex

Binding to read-only properties in Flex takes a bit more work than one might think at first glance. There are two basic types of read-only properties in Flex: "variable backed" and "calculated". Can you guess which one we're going to discuss here?

Lets start by clarifying exactly what we mean by read-only property. The most basic description is when you have a getter but no setter:

public function get someValue():Number {...}

The variable backed version is when the getter is just a gatekeeper for a private variable:

private var _someValue:Number;

public function get someValue():Number
{
   return _someValue;
}

The calculated version is a bit more complex and is generally either a combination of values like first name and last name or a value that requires calculation. The example we'll use here is a totalTime property of a Playlist. The totalTime is calculated by adding together the duration of all songs in the playlist at any given time.

OK, how?

By default you will get a warning telling you that the binding on a read-only property will be ignored (and whatever you've bound to it will indeed not receive any updates). The first part of enabling the bindings involves using metadata. Everybody knows [Bindable], but what we're looking for is [Bindable(event="eventName")]. That will essentially tell the compiler to dispatch a PropertyChangeEvent for the property (which is how binding works) any time an event of type "eventName" is fired. That brings us to the next step of firing the event. In our scenario of a calculated read-only property this needs to happen when one/any of our inputs changes.

Going back to the playlist example, a good time to let everyone know totalTime has changed is when a song is added. For the sake of simplicity that is the only scenario this example covers. I won't bother talking through the code in the example because it is very straightforward.

View the example and view the source and you'll see this is all very simple. I have included the classes generated by the compiler as well in case anyone wants to dig around. The magic seems to be injected from _CalculatedBindableReadOnlyWatcherSetupUtil.as but I won't claim to have a very solid understanding of how that all works.

I hope this will shed some light for somebody out there and maybe even come in handy if you're stuck. Binding to variable backed read-only properties has been covered by numerous other people and I would recommend learning about that as well. Enjoy!

Hidden gem of the Flex framework: LayoutContainer

Every now and then I stumble across something in the Flex framework that I am both surprised and sorry I didn't know about sooner. Like the fact that CheckBox has a built-in clickHandler method. Duh. LayoutContainer just may be one of the most useful classes around, especially if you're creating components you want to be reusable and flexible. First, a little background.

Its fairly common knowledge that VBox and HBox both extend Box and do nothing more than set a direction property. What may be a bit less obvious is the fact that the direction property is actually applied to an internal layoutObject property. In the case of Box (and by extension VBox and HBox), layoutObject is of type BoxLayout. As it turns out, Canvas uses an internal layoutObject as well, but in that case its an instance of CanvasLayout. Now notice that my references to both BoxLayout and CanvasLayout are not linked to the corresponding documentation. This is because Adobe has specifically excluded them from the documentation because, for whatever reason, Joe Developer isn't supposed to directly use them.

When I first discovered this I set about using them anyways because I had been struggling to find an optimal solution to a problem for a couple of days. Sure they always say things "may not be supported in future versions" but when was the last time they actually pulled something out and besides, where's your sense of adventure? I was on my way to creating a base class that could act like a Canvas, VBox or HBox using some intelligent switching between what type of layoutObject (and direction) it used. I was happy. Well, I didn't get far before I started hitting errors due to not implementing some deeply nested interface or some other nonsense. I was no longer happy. Thankfully, while digging through source and documentation I stumbled onto LayoutContainer. Lo and behold it does exactly what I was trying to accomplish! By changing the layout property between "absolute", "vertical" and "horizontal" (defined as constants on ContainerLayout), you can have your container lay its children out like a Canvas would (direction = ContainerLayout.ABSOLUTE) or like a Box would (direction = ContainerLayout.VERTICAL | ContainerLayout.HORIZONTAL). I suppose this is only exciting if you have a need for this kind of functionality, which, who knows how common that is but it was an absolute life saver on my recent task.

Stay tuned for where this technique is getting applied but I will leave you with the chunk of code from LayoutContainer that does the magic referenced in this post.

public function set layout(value:String):void
{
    if (_layout != value)
    {
        _layout = value;

        if (layoutObject)
            // Set target to null for cleanup.
            layoutObject.target = null;

        if (_layout == ContainerLayout.ABSOLUTE)
            layoutObject = new canvasLayoutClass();
        else
        {
            layoutObject = new boxLayoutClass();

            if (_layout == ContainerLayout.VERTICAL)
            {
                BoxLayout(layoutObject).direction =
                    BoxDirection.VERTICAL;
            }
            else
            {
                BoxLayout(layoutObject).direction =
                    BoxDirection.HORIZONTAL;
            }
        }

        if (layoutObject)
            layoutObject.target = this;

        invalidateSize();
        invalidateDisplayList();

        dispatchEvent(new Event("layoutChanged"));
    }
}

While the implementation may not be rocket surgery it is extremely useful at times. In fact, you may have even used one of LayoutContainer's subclasses before, its a little class called Application.

Efficient, reusable (and centered) CheckBox renderers for DataGrids

As it turns out, truly reusable CheckBox renderers are much simpler to create than I previously reported. This post will provide and discuss what I think are the last CheckBox renderers you will ever need.

Did you know that CheckBox has a built-in click handler? I didn't until recently, despite its not-so-sneaky name of clickHandler. It is a protected function, so its only accessible if you subclass CheckBox, but that's OK since our renderers will do just that. clickHandler is key to creating these reusable renderers and keeping them super simple.

Before I start in on my inevitably wordy and detailed description lets take a look at our end result. CheckBoxRenderers in action and the source.

Edit: I initially forgot to mention that these renderers are heavily based on and influenced by the information provided by Flex Jedi Alex Harui on his blog. Thanks to Alex for illustrating "the right way" to do things.

This time around we will start with the item renderer since it is the simpler of the two. (Both of these classes center the CheckBox as that is the most common request, but if you don't need them centered simply remove the updateDisplayList() functions.)

CenteredCheckBoxItemRenderer.as:

package com.returnundefined.view.renderers
{
    import flash.display.DisplayObject;
    import flash.events.MouseEvent;
    import flash.text.TextField;

    import mx.controls.CheckBox;
    import mx.controls.dataGridClasses.DataGridListData;

    public class CenteredCheckBoxItemRenderer extends CheckBox
    {
        // update data item on click
        override protected function clickHandler(event:MouseEvent):void
        {
            super.clickHandler(event);
            data[DataGridListData(listData).dataField] = selected;
        }

        // center the checkbox icon
        override protected function updateDisplayList(w:Number, h:Number):void
        {
            super.updateDisplayList(w, h);

            var n:int = numChildren;
            for (var i:int = 0; i <n; i++)
            {
                var c:DisplayObject = getChildAt(i);
                // CheckBox component is made up of box skin and label TextField
                if (!(c is TextField))
                {
                    c.x = (w - c.width) / 2;
                    c.y = (h - c.height) / 2;
                }
            }
        }
    }
}

There are 2 major differences between this class and our previous version. First, it doesn't implement ClassFactory, which means we can simply type its fully qualified class name into the itemRenderer attribute of a DataGrid and it will work (just like with mx.controls.CheckBox), requiring one less bindable variable in our file. The reason we can do this is that CheckBox, and by extension CenteredCheckBoxItemRenderer implement IDropInListItemRenderer. I won't go into the full details (if anyone would like me to dedicate a post to describing this more fully let me know) but in the case of CheckBox, that basically means that it knows how to set its selected state based on a piece of data that is passed to it. The second major difference is closely related to this fact, which is that we no longer have to override the data setter- we get that functionality for free.

The most important line in the item renderer class is essentially the other half of the equation. Whereas we get data retrieval and rendering for free, we have to provide the data setting functionality. That is really the only thing that separates it from a regular CheckBox other than the centering code, and its accomplished with this single line of code:

data[DataGridListData(listData).dataField] = selected;

This line uses the listData property (defined by IDropInListItemRenderer) to locate and update the specific piece of data this CheckBox is rendering in our DataGrid.

The CenteredCheckBoxHeaderRender class is pretty similar to my previous version in that it still implements IFactory and has to be implemented as a ClassFactory instance. For details on using ClassFactory see the previous post referenced above. The main differences this time around are that the class is defined in ActionScript rather than MXML and streamlines things by using the built-in clickHandler function. Below is the portion of the class we will discuss further.

// these vars are used to reference the external property that stores our selected state
public var stateHost:Object;
public var stateProperty:String;

// set selected state based on external property
override public function set data(value:Object):void
{
    selected = stateHost[stateProperty];
}

// toggle external property on click
override protected function clickHandler(event:MouseEvent):void
{
    super.clickHandler(event);
    stateHost[stateProperty] = selected;
}

As discussed in the previous post, headerRenderers get initialized repeatedly during their existence. This means that we are unable to store any kind of state for them inside themselves because it will get reset over and over again. To work around this we define the stateHost and stateProperty variables which will be assigned via the properties property of ClassFactory. (Again, see previous post for a more thorough explanation of ClassFactory.) In our example application we point these to a selectAllFlag variable (the stateProperty) defined in the main application (the stateHost property). The overridden data setter shown above then uses this external value to set the selected state of our component. Correspondingly, clickHandler sets this value when our CheckBox is clicked, saving our state out to a safe, external location.

Two minor things to mention about our application are a couple of attributes set on the DataGridColumn that our renderers live in. First, notice that we set a dataField attribute like usual. This is required for our new itemRenderer class to work properly, whereas it was not needed when using ClassFactory for both the headerRenderer and itemRenderer. The second important point is that we have set the column's sortable attribute to false. This is necessary in order to ensure clicks in the header are processed as CheckBox clicks and not sorting actions. Also note that we process the header click and set the item values in the main file. While it would be possible to do this inside the header renderer class leaving it outside makes the renderer that much more flexible.

Hopefully this all makes sense, is not too long winded and provides renderers that others can and will use in future projects. Please post questions, complaints and comments in the... well... comments.

CellularDataGrid for Flex 2

A DataGrid that supports highlighting and selection on a cellular level (as opposed to row level like the default) is a fairly common request/topic. While I realize people have done this before and this is supported out of the box by Flex 3 (sort of, see first comment below) I decided to give it a shot during some down time yesterday. I was pretty amazed at how easy it was. Even in my newline-happy code format the component is only 55 lines. The results of about 2 hours of fiddling can been seen and downloaded by following the link below.

View CellularDataGrid (Right click for source)

Hopefully someone finds this useful and/or interesting. If nothing else it should serve as an example of why diving into the framework and getting your tweak on is a worthwhile activity.

Update: Thanks to Tom's suggestion, the problem with the selection indicator not disappearing correctly when selecting a cell in the same row is now fixed. The example and source have been updated.