Friday, July 11, 2008

Transparent List



I often run into situations where I want to use a List but I want to have the rollOver and selection highlights disabled. This often occurs when I want a completely transparent list. There is a style which controls whether the rollOver highlight is displayed, called useRollOver, but it doesn't disable the selection highlight. In addition, even though Tree extends List, the useRollOver style has no effect for the Tree component. Fortunately, due to a good api design, there is a simple solution. You just create a new component class which extends List:

package
{
import mx.controls.List;
import mx.controls.listClasses.IListItemRenderer;

public class TransparentList extends List
{
override protected function createChildren():void
{
super.createChildren();

setStyle( "backgroundAlpha", "0" );
setStyle( "borderStyle", "none" );
}

override protected function drawItem( item:IListItemRenderer,
selected:Boolean=false,
highlighted:Boolean=false,
caret:Boolean=false,
transition:Boolean=false):void
{
super.drawItem(item, false, false, caret, transition);
}
}
}

In createChildren() set the border and background alpha styles. Then override the protected drawItem() function and always pass false to the selected and highlighted parameters of the parent function. You can do the same thing for the Tree component.

Wednesday, June 18, 2008

A Reusable Flex Hover Details Window



Update: The source code for this is now hosted on googlecode.


An increasingly common feature in rich web interfaces is when hovering over some piece of information, a window pops up providing more details about that item. An example of this is in the Gmail interface. If you hover over a name in your chat list, you get a popup which displays more details about the person, such as their name, photo and email address. In this short tutorial, I will go over how to do something similar in Flex in a reusable way.

First we start with our simple demo Application.
<?xml version="1.0" encoding="utf-8"?>
  <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="init()">
  <mx:Script>
  <![CDATA[
    import mx.collections.ArrayCollection;
    [Bindable] 
    private var dataProvider:ArrayCollection = 
                  new ArrayCollection( [ { name: "Leonard Nimoy", image: "nimoy.jpg" }, 
                                         { name: "William Shatner", image: "shatner.jpg" }, 
                                         { name: "Deforest Kelley", image: "kelley.jpg" },] );
  ]]>
  </mx:Script>
  <mx:Panel title="Famous Actors: Hover Over For More Details">
    <mx:List dataProvider="{dataProvider}" 
                labelField="name" 
                itemRenderer="PersonRenderer" 
                width="100%"/>
  </mx:Panel>
  </mx:Application>

In this case we are just displaying a set of names in a List component. We create a dataProvider for the list which is a set of persons where each person has a name and image property. We specify the labelField for the List as the name property of a person. Next we create a simple ItemRenderer called PersonRenderer which is used by the List component to display the items.
<mx:Label xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Script>
  <![CDATA[
    import mx.binding.utils.BindingUtils;

    override protected function createChildren():void
    {
      super.createChildren();

      //Instance the ImageHover object and attach it to
      //the item renderer
      var imageHover:ImageHover = new ImageHover();
      imageHover.parentComponent = this;

      //Create a binding between the image property of the data object
      //and the source property of the ImageHover so it knows which image to display
      BindingUtils.bindProperty( imageHover, "source", this, ["data","image"] );

      //Create a binding between the name property of the data object
      //and the title property of the ImageHover so it knows which title to display
      BindingUtils.bindProperty( imageHover, "title", this, ["data","name"] );        
    }
  ]]>
  </mx:Script>
  </mx:Label>



This renderer is based on the Label component. Since it implements IDataRenderer we can use it almost 'as is' in the List. We override createChildren() where we attach our ImageHover component to the renderer. This component is what actually displays the details window when we hover over the renderer. There are only three properties we set on this component, the title and the source, which we bind to the name and image properties of our person, and the parentComponent which is the component that we want the hover detail window to appear over. Let's look at the ImageHover component to see how it works:
<HoverComponent xmlns="*" xmlns:mx="http://www.adobe.com/2006/mxml">
  <!-- Simple extension of the HoverComponent to display
    an image specified by the source property with a title -->

  <mx:Script>
  <![CDATA[
    [Bindable] public var source:String;
    [Bindable] public var title:String;
  ]]>
  </mx:Script>

  <mx:Panel paddingBottom="5"
               paddingLeft="5"
               paddingTop="5"
               paddingRight="5"
               backgroundAlpha="1"
               title="{title}">
    <mx:Image id="image" source="{source}"/>
  </mx:Panel>
  </HoverComponent>

This component is very simple and only consists of a Panel with a title and an Image component inside the Panel. The key thing is that it extends HoverComponent, which provides the hover capabilities. You can modify the ImageHover to do just about anything as long as it extends the HoverComponent. So, finally let's look at the HoverComponent class:
package
  {
    import flash.events.MouseEvent;
    import flash.events.TimerEvent;
    import flash.geom.Point;
    import flash.utils.Timer;

    import mx.containers.Canvas;
    import mx.core.UIComponent;
    import mx.managers.PopUpManager;

    public class HoverComponent extends Canvas
    {
      public var delay:Number = 1000;
      private var _parentComponent:UIComponent;

      private var timer:Timer;
      private var popped:Boolean = false;

      public function set parentComponent( parentComponent:UIComponent ):void
      {
        _parentComponent = parentComponent;
        if ( _parentComponent != null )
        {
          var thisComponent:UIComponent = this;

          //Detects mouse overs and starts a timer to display the hover
          parentComponent.addEventListener( MouseEvent.MOUSE_OVER, function( evt:MouseEvent ):void
          {
            //Initialize the timer to trigger one time after delay millis
            timer = new Timer( delay, 1 );

            //Wait for the timer to complete
            timer.addEventListener(TimerEvent.TIMER_COMPLETE, function( tevt:TimerEvent ):void
            {
              //move to a position relative to the mouse cursor
              thisComponent.move( evt.stageX + 20, evt.stageY + 20 );

              //Popup the hover component
              PopUpManager.addPopUp( thisComponent, parentComponent );

              //Set a flag so we know that a popup actually occurred
              popped = true;
            });

            //start the timer
            timer.start();
          });

          parentComponent.addEventListener( MouseEvent.MOUSE_OUT, function( evt:MouseEvent ):void
          {
            //If the timer exists we stop it
            if ( timer )
            {
              timer.stop();
              timer = null;
            }

            //If we popped up, remove the popup
            if ( popped )
            {
              PopUpManager.removePopUp( thisComponent );
              popped = false;
            }
          });
        }
      }

      public function get parentComponent():UIComponent
      {
        return _parentComponent;
      }  
    }
  }

The HoverComponent class extends the Canvas component. It adds a delay property, which is the amount of time in milliseconds that you need to hover over an item before the window displays. It also adds the parentComponent property which is the item that you want the hover to appear over. The default delay is 1 second. When you set the parentComponent, a mouseOver and mouseOut listener get added to the parentComponent. When you mouseOver, a timer gets started. When the timer completes, the hover component gets positioned and uses PopUpManager to display itself. When you mouseOut, the timer will get cancelled if it is not completed, and the hover window is removed, if it was displayed.



So with the HoverComponent class we have a simple and re-usable way to create custom hover detail windows. Just create your window by extending the HoverComponent and attach it to the component you want it to appear over like we did in the PersonRenderer.

Here is a demo and the source code.


Demo:
Unable to initialize flash content

Friday, March 21, 2008

Object Leaks & The Dangers of ArrayCollection.removeItemAt



I have been using the new Profiler in Flex Builder 3 to fix some performance issues in my flex apps and discovered a bit of an anti-pattern in several places in my code. I like to use object pools to re-use my custom renderer objects. To do this I first have my renderers implement the IFactory interface. Which is basically just adding this function:
public function newInstance():*
In the class that I will be using the renderers, I create some code to manage the pool of renderers, which is basically just two methods:
protected function getRenderer():MyRenderer
protected function freeRenderers():void
Calling getRenderer() will check the pool of "free" renderers and return one if available, or if not, create a new one and add it tool the pool of renderers currently in use. The freeRenderers() method just takes all of the in-use renderers and moves them to the free pool. The discovered my anti-pattern here in the freeRenderers() method:
for ( var I:int i = 0; i < usedRenderers.length; i++ )
{
freeRenderers.addItem( usedRenderers.removeItemAt(i) );
}
This code will fail to copy all of the used renderers from the in-use pool to the free pool. The reason is that as we remove items, we are changing the length of the collection that we are indexing across. The proper way to do this is:
while ( usedRenderers.length > 0 )
{
freeRenderers.addItem( usedRenderers.removeItemAt( 0 ) );
}
There is another variation of this issue which needs to be handled differently. If you are only wanting to transfer some of the items out of the collection, you might do something like this:
var key:String = "foo";
for ( var i:int i = 0; i < collection.length; i++ )
{
if ( MyObject(collection.getItemAt( i )).id == key )
collection.removeItemAt( i );
}
Doing this will cause problems similar to the first example. This is basically like a ConcurrentModificationException that you might get in Java. The problem is that in Flex's ArrayCollection you don't get any exception when you do this, so it is real easy to think you are doing the right thing when you are not. Here is one possible fix for this:
var key:String = "foo";
var removes:ArrayCollection = new ArrayCollection();
for ( var i:int = 0; i < collection.length; i++ )
{
if ( MyObject(collection.getItemAt( i )).id == key )
removes.addItem( collection.getItemAt( i ) );
}

for ( i = 0; i < removes.length; i++ )
{
collection.removeItemAt( collection.getItemIndex( removes.getItemAt( i ) ) );
}
This is pretty simple but it is definitely something worth remembering

Thursday, February 28, 2008

What's Missing In Flex Builder 3



I have been using a beta version of the new Flex Builder 3 for a while now. I am pretty happy with the new features added to it, but there is something missing that I would really expect to be there. There is no code formatting functionality for the ActionScript 3 or MXML editors. For a $249 IDE plugin, I am amazed by this.

Reformatting your code by hand is an extremely tedious and error prone task. It also seems that with FB I am especially prone to writing badly formatted code. I did a google search for ActionScript code formatter and basically came up with very little. There is a PHP cut and paste formatter hosted on Senocular, but it isn't really usable for reformatting code in the IDE. I did learn today that IntelliJ IDEA has just added Flex functionality, including code formatting and a nice set of refactorings (Copy, Move, Safe delete, Introduce variable, Migrate). I think I will have to check it out.