Saturnboy
 7.22

I’ve been building a lot of Flex 4 custom components lately, including a sliding drawer, a multiple content area container, and now SuperTextInput. Nor will this be that last, because I think I have a few more in me. I thought it would be useful to spend some time in the details, explaining The Flex 4 Way and how I try to walk the path.

SuperTextInput is a prompting, clearable TextInput extension in Flex 4. It’s just an enhanced version of the default TextInput control, and as such, it follows a fairly standard pattern of custom component creation.

Enhanced Component Pattern

It’s almost too stupid to call this a pattern, but it’s so common in custom component creation that I’ll run with it. Also, I’ve found it to be worthwhile to distinguish between adding new functionality to a component already present in the framework (aka an enhanced component) versus creating a truly custom component.

The enhanced component pattern is just two simple steps:

  1. Extend – extend some default component and add some new functionality
  2. Skin – make it look good

In my version of reality, these steps carry equal weight, because almost all worthwhile functionality in Flex touches the UI in some fashion, so the design and UX (the look-and-feel, it’s usability, the integration into the rest of the app, etc.) are critical. Don’t forget or skimp on step #2 because it’s all the client, team, customer ever sees.

A Prompting TextInput

Since SuperTextInput has two new pieces of functionality (the prompt and the clear button), I’ll split them apart, and consider each part separately. First, the prompt is merely the text you see when the TextInput is empty. It often becomes a space saving label, because it can be used to tell the user what goes into the TextInput without costing the UI any screen real estate.

Thinking more about the prompt, we want the prompt text to be visible initially, but it should disappear when the user clicks (or tabs) to the control, and only returns when the control loses focus and is still empty. So this tells us that we need to communicate both the prompt text and it’s visibility to our skin. The prompt text can just be a simple Label SkinPart, but it’s visibility is complicated enough that it makes sense to add a new prompting SkinState.

Here’s a functioning PromptingTextInput custom component (which is simply the prompting code lifted from SuperTextInput.as):

package components {
    import flash.events.FocusEvent;
    import mx.events.FlexEvent;
    import spark.components.Label;
    import spark.components.TextInput;
    import spark.events.TextOperationEvent;
 
    [SkinState("prompting")]
    public class PromptingTextInput extends TextInput {
 
        [SkinPart(required="false")]
        public var promptDisplay:Label;
 
        private var _prompt:String = '';
        private var _focused:Boolean = false;
 
        public function PromptingTextInput() {
            super();
 
            //watch for programmatic changes to text property
            this.addEventListener(FlexEvent.VALUE_COMMIT, textChangedHandler, false, 0, true);
 
            //watch for user changes (aka typing) to text property
            this.addEventListener(TextOperationEvent.CHANGE, textChangedHandler, false, 0, true);
        }
 
        [Bindable]
        public function get prompt():String {
            return _prompt;
        }
        public function set prompt(value:String):void {
            if (_prompt != value) {
                _prompt = value;
                if (promptDisplay != null) {
                    promptDisplay.text = value;
                }
            }
        }
 
        private function textChangedHandler(e:Event):void {
            invalidateSkinState();
        }
 
        override protected function focusInHandler(event:FocusEvent):void {
            super.focusInHandler(event);
            _focused = true;
            invalidateSkinState();
        }
        override protected function focusOutHandler(event:FocusEvent):void {
            super.focusOutHandler(event);
            _focused = false;
            invalidateSkinState();
        }
 
        override protected function partAdded(partName:String, instance:Object):void {
            super.partAdded(partName, instance);
 
            if (instance == promptDisplay) {
                promptDisplay.text = prompt;
            }
        }
 
        override protected function getCurrentSkinState():String {
            if (prompt.length > 0 && text.length == 0 && !_focused) {
                return 'prompting';
            }
            return super.getCurrentSkinState();
        }
    }
}

In addition to the promptDisplay SkinPart and the new prompting SkinState, there is a lot of other stuff going on in the above code. First, as is typical with data-driven SkinParts, we back the promptDisplay with a good old prompt property. The net is the fairly common pattern of: check if the SkinPart is not null, then do something to it. So in the prompt setter, we assign the incoming value to the private _prompt variable, then check if promptDisplay is available and if yes, set it’s text property. The setter does the job of updating the prompt, but only once everything is happily running. In order to get the data to the skin initially, we must use the partAdded() override to pass the local prompt to the promptDisplay‘s text property. And that’s it for the prompt text.

The prompt visibility part requires lots of event watching, and also SkinState stuff because we made the choice to push visibility via the prompting SkinState. First, we wire up both the programmatic text change events and the user text change events to a handler, textChangedHandler(), that does nothing more than invalidate the state. TextInput change events are a little wacky, but the code works fine. Next, instead of wiring the focus events to another handler (as seen in this prompting TextInput component by Andy McIntosh), we simply override the protected handlers in the parent and add our focus-tracking logic directly. Finally, we override getCurrentSkinState() to do the work of figuring out whether or not the prompt should be displayed.

A skin for PromptingTextInput is now trivial because our component does the work of pushing the important information to the skin. If we ignore all the pretty stuff, the skin is very simple:

<?xml version="1.0" encoding="utf-8"?>
<s:SparkSkin ...>
    ...
    <s:states>
        <s:State name="normal"/>
        <s:State name="prompting"/>
        <s:State name="disabled"/>
    </s:states>
 
    <s:RichEditableText id="textDisplay" ... />
    <s:Label id="promptDisplay" includeIn="prompting" ... />
</s:SparkSkin>

We add the prompting State to the list of states and also add the promptDisplay Label component. By using the standard inline state syntax, includeIn="prompting" our Label is shown only in the prompting state.

A Clearable TextInput

The second piece of SuperTextInput functionality is the clear button. The clear button appears when the TextInput has a value, and when clicked, it clears that value (which re-displays the prompt). Again, there are two pieces of information the need to be communicated to the skin to create the clear button functionality: the button itself and it’s visibility. In this case, since the visibility is so simple (on if TextInput has a value, otherwise off), we’ll just punt and manage it directly in the component. Therefore, the only a Button SkinPart for the clear button will be pushed to the skin.

Here’s a functioning ClearableTextInput custom component (which is simply the clear button code lifted from SuperTextInput.as):

package components {
    import flash.events.Event;
    import flash.events.MouseEvent;
    import mx.events.FlexEvent;
    import spark.components.Button;
    import spark.components.TextInput;
    import spark.events.TextOperationEvent;
 
    public class ClearableTextInput extends TextInput {
 
        [SkinPart(required="false")]
        public var clearButton:Button;
 
        public function ClearableTextInput() {
            super();
 
            //watch for programmatic changes to text property
            this.addEventListener(FlexEvent.VALUE_COMMIT, textChangedHandler, false, 0, true);
 
            //watch for user changes (aka typing) to text property
            this.addEventListener(TextOperationEvent.CHANGE, textChangedHandler, false, 0, true);
        }
 
        private function textChangedHandler(e:Event):void {
            if (clearButton) {
                clearButton.visible = (text.length > 0);
            }
        }
 
        private function clearClick(e:MouseEvent):void {
            text = '';
        }
 
        override protected function partAdded(partName:String, instance:Object):void {
            super.partAdded(partName, instance);
 
            if (instance == clearButton) {
                clearButton.addEventListener(MouseEvent.CLICK, clearClick);
                clearButton.visible = (text != null && text.length > 0);
            }
        }
 
        override protected function partRemoved(partName:String, instance:Object):void {
            super.partRemoved(partName, instance);
 
            if (instance == clearButton) {
                clearButton.removeEventListener(MouseEvent.CLICK, clearClick);
            }
        }
    }
}

After the PromptingTextInput, the ClearableTextInput is a little more straightforward. First, we have the clearButton SkinPart and it’s clearClick() event handler. Wiring the handler function to the button is done in the partAdded() override, and un-wiring in the partRemoved() override. Next, button visibility is managed by watching for both programmatic text change events and user text change events. The handler, textChangedHandler(), sets the button as visible when the control has text in it.

As I mentioned above, I decided against pushing the clearButton‘s visibility down to the skin via a SkinState, and instead chose to manage it inside the component by setting clearButton.visible directly. I tend to favor the SkinState method when more than one thing needs to change in the skin or if I need advanced visuals (like transitions). If I need to do just one thing and I don’t care about visuals, I’ll do it inside the component. The two examples here aren’t the best to illustrate the two options, but that’s my general thought process when building a custom component and custom skin.

A skin for ClearingTextInput is super trivial. Again, ignoring all the pretty stuff, the skin is:

<?xml version="1.0" encoding="utf-8"?>
<s:SparkSkin ...>
    ...
    <s:states>
        <s:State name="normal"/>
        <s:State name="disabled"/>
    </s:states>
 
    <s:RichEditableText id="textDisplay" ... />
    <s:Button id="clearButton" ... />
</s:SparkSkin>

Just add the clearButton Button and position it.

Fusion, Glorious Fusion

The fusion process of creating SuperTextInput from PromptingTextInput and ClearableTextInput is nothing more than copy and paste. SuperTextInput has lots of uses, but my favorite is to use it to capture text input to filter a list. It also works great as a search box, or in any smart form UI. Enjoy.

Here’s the finished product showing all three custom components skinned and ready for action (view source enabled):

Flash is required. Get it here!
Files

 7.15

Back in the days of Flex 3, if you wanted multiple content areas in your main application, you’d need to arrange some set of containers (Canvas, HBox, VBox) in the app and fill them with content. It was just your basic Flex 3 development process. The danger, of course, is that you are mixing content with presentation, aka bad separation of concerns. Today, with the power of Flex 4 skins, we can avoid this issue by moving the presentation layer into a skin (or set of skins). And thus, we can do a much better job achieving a happy level of separation of concerns.

The Flex 3 Way

To give a concrete example, I’ll build a blog layout (yes, another blog layout) with a header, footer, sidebar, and main content areas. But before we get started, let’s review the old Flex 3 way:

<mx:HBox id="header">
    <mx:Image source="@Embed('assets/logo.png')" />
</mx:HBox>
 
<mx:Canvas id="body" width="800">
    <mx:Text text="main content" width="600" />
 
    <mx:VBox id="sidebar" x="600" width="200">
        <mx:Text text="Sidebar" />
        <mx:Text text="sidebar content" width="100%" />
    </mx:VBox>
</mx:Canvas>
 
<mx:VBox id="footer">
    <mx:Text text="2010 saturnboy" styleName="footer" />
</mx:VBox>

The above code comes from a previous post, Designing in Flex 3, but has been modified to make sense here. You’ve got you basic blog design: a box for the header, footer, and body, where body is subsequently is divided into a main content area and a sidebar.

The 3-in-4 Way, aka The Wrong Way

The unfortunate next step in a Flex developer’s evolution is what I like to call the Flex 3-in-4 way. This is a the way of neanderthals, which is to say, it is an evolutionary dead end. If you ever have the bad luck to see 3-in-4 code, you can be sure you are dealing with a novice Flex 4 developer. In general, the 3-in-4 way consists of making the simple transcription: CanvasGroup, HBoxHGroup, VBoxVGroup. But the most damning tipoff of a 3-in-4 developer is the assertion that one is now a Flex 4 developer and the learning curve wasn’t all that bad. While I do think Flex 4 is more of an evolutionary release than a revolutionary release, it’s different enough. And it is particularly different on the design side of the framework, how it handles skins, layout, etc.

If we just transcribe the above example, we get some classic 3-in-4 code:

<s:HGroup id="header">
    <s:Label text="Multi Content Area Example" styleName="header" />
</s:HGroup>
 
<s:Group id="body" width="800">
    <s:Label text="main content" width="600" />
 
    <s:VGroup x="600" width="200" styleName="sidebarBox">
        <s:Label text="Sidebar" styleName="title" />
        <s:Label text="sidebar content" styleName="sidebar" />
    </s:VGroup>
</s:Group>
 
<s:VGroup id="footer">
    <s:Label text="2010 saturnboy" styleName="footer" />
</s:VGroup>

*Barf*, please not do this. This code has all the same issues as the Flex 3 code in the first example, and moreover it is a slap in the face of The Flex 4 Way and all of its improvements.

The Flex 4 Way

Yes, there is a Flex 4 Way and it looks like this.

First, we rewrite the main app using a custom container. Ignoring the specifics of the custom container for a moment, here is the re-written main app (minus some clutter):

<containers:headerContent>
    <s:Label text="Multi Content Area Example" styleName="header" />
</containers:headerContent>
 
<containers:sidebarContent>
    <s:RichText left="0" right="0" styleName="sidebar">
        <s:content>
            <s:p fontSize="20">Sidebar</s:p>
            <s:p>sidebar content</s:p>
        </s:content>
    </s:RichText>
</containers:sidebarContent>
 
<containers:footerContent>
    <s:Label text="2010 saturnboy" styleName="footer" />
</containers:footerContent>
 
<s:RichText left="0" right="0">
    <s:content>
        <s:p fontSize="30">Content</s:p>
        <s:p>main content</s:p>
    </s:content>
</s:RichText>

As you can see, the main app is now a nice set of semantic buckets, one for each of the content areas. Header stuff goes in the headerContent bucket, footer stuff goes in the footerContent bucket, etc.

Building a Multi Content Area Container

Second, we need to create a custom container with the nice set of semantic buckets used in the above code. This is achieved by following a straightforward formula:

  1. Extend SkinnableContainer – Extend SkinnableContainer or some child class. In our sample app, our custom container extends Application (which extends SkinnableContainer).
  2. Add Buckets – add some content buckets (in the form of xxxContent) as Arrays. These become the MXML tags used to bucket components together. Each content bucket has a public getter, but most importantly a public setter that accepts an incoming Array of IVisualElements and uses the magical mxmlContent property to assign it to the associated SkinPart.
  3. Add SkinParts – add some matching SkinParts (in the form of xxxGroup) as spark Groups. There are used in the custom skin to display the content. Also, I usually set required="false" to make everything optional.
  4. Add partAdded() & partRemoved() – override the new Flex 4 skinning lifecycle methods to wire the incoming content to the outgoing SkinPart.

The custom component code is actually easier to follow then the description. Here is a custom container with only one additional content bucket, sidebarContent, and its matching SkinPart, sidebarGroup:

package containers {
    import spark.components.Group;
    import spark.components.Application;
 
    public class MainApp extends Application {
        [SkinPart(required="false")]
        public var sidebarGroup:Group;
 
        private var _sidebarContent:Array = [];
 
        public function MainApp() {
            super();
        }
 
        [ArrayElementType("mx.core.IVisualElement")]
        public function get sidebarContent():Array {
            return _sidebarContent;
        }
        public function set sidebarContent(value:Array):void {
            _sidebarContent = value;
            if (sidebarGroup) {
                sidebarGroup.mxmlContent = value;
            }
        }
 
        override protected function partAdded(partName:String, instance:Object):void {
            super.partAdded(partName, instance);
 
            if (instance == sidebarGroup) {
                sidebarGroup.mxmlContent = _sidebarContent;
            }
        }
 
        override protected function partRemoved(partName:String, instance:Object):void {
            super.partRemoved(partName, instance);
 
            if (instance == sidebarGroup) {
                sidebarGroup.mxmlContent = null;
            }
        }
    }
}

Following the four steps: we extend Application, have a sidebarContent bucket and its associated sidebarGroup SkinPart, and override partAdded() and partRemoved() to wire everything together.

Skinning a Multi Content Area Container

Skinning in Flex 4 is awesome, and like everyone says, it’s easily one of the best new features in the framework. While I find the skinning process fairly straightforward, I would never call it trivial, mostly due to the depth and flexibility of the skinning system.

We need a custom skin for our custom multi content area component. This is probably the 10% case for skinning, but it’s also the coolest. In my experience, an average Flex 4 app has many Button skins (like 10 or even 20), a few default component skins (skins for List, DropDownList, TextInput, etc.), and maybe only two or three skins for custom components.

The skin itself is nothing special. To display our custom component’s SkinParts, we simply include a Group with the matching id attribute. For example, our skin will include a <s:Group id="sidebarGroup" /> to display the sidebarGroup SkinPart. Just rinse, wash, repeat, to add all of our custom content areas in the container to the skin.

Here is a trivial skin:

<s:Skin ... >
    <fx:Metadata>
        [HostComponent("containers.MainApp")]
    </fx:Metadata> 
 
    <s:states>
        <s:State name="normal" />
        <s:State name="disabled" />
    </s:states>
 
    <s:VGroup left="40" right="40" top="40" bottom="40" gap="20">
        <s:Group id="headerGroup" width="100%" />
        <s:Group id="contentGroup" width="100%" />
        <s:Group id="sidebarGroup" width="100%" />
        <s:Group id="footerGroup" width="100%" />
    </s:VGroup>
</s:Skin>

In this trivial skin, we just shove all the content groups (including SkinnableContainer‘s default Group, contentGroup) into a VGroup. Also note, we correctly set HostComponent to our custom container. If you are thinking, "Hey, this skin looks similar to the Flex 3 and 3-in-4 example code, just minus the content" that’s exactly the point.

Lastly, we wire out skin to our custom component via CSS:

containers|MainApp {
    skinClass:ClassReference('skins.TrivialAppSkin');
}

Using skinClass to wire a skin to a component is so 2009. The sample app has its CSS inline, but in any real app I’ll always put this in an external file.

Conclusion

After this, there’s really not much more to say. You can certainly create a more complicated arrangement of the multiple content areas by making a more complicated skin. I’ve done exactly this in the final sample, which includes three different skins and a skin switcher (click 1, 2, or 3 to switch skins).

» view MultiConentArea sample (view source enabled)

Files

 6.1

I needed a good way to have a large settings panel with a minimal visual impact. The obvious answer is to hide or minimize or collapse the settings panel when not in use. I thought about using Flexlib‘s WindowShade component (which I’ve dicussed in detail in Styling Flexlib’s WindowShade), but why reuse something when you can reinvent the wheel? Plus, it always helps to hone my Flex 4 custom component kung-fu. So, I chose to implement a simple sliding drawer component from scratch as a Flex 4 component.

The Drawer component is a vanilla container (it actually extends SkinnableContainer), so it will happily take any spark component for its children. Before I dive into my implementation, let’s check out the finished drawer component in action (view source enabled):

Flash is required. Get it here!

Just click on the handle to open and close the drawer.

Extending SkinnableContainer

The Drawer component itself, is just pure AS3, but the demo above uses a few MXML skins to achieve the desired look-and-feel. This is a pretty standard pattern that I see during Flex 4 development, so expect it when you write your own custom components.

We’ll review the component implementation in two steps. First, we focus on the skin state management aspect of the drawer. Here’s the relevant code (taken from Drawer.as):

[SkinState("opened")]
public class Drawer extends SkinnableContainer {
    private var _opened:Boolean = false;
 
    public function get opened():Boolean {
        return _opened;
    }
 
    public function set opened(value:Boolean):void {
        if (_opened != value) {
            _opened = value;
            invalidateSkinState();
        }
    }
 
    override protected function getCurrentSkinState():String {
        return (opened ? 'opened' : super.getCurrentSkinState());
    }
    ...
}

The Drawer component can either be closed (the default) or opened. To model theses states, we use the normal state from the superclass to represent the closed drawer, and add a new opened SkinState to represent the opened drawer. We just expose a simple opened boolean property with a custom getter and setter, and then override the getCurrentSkinState() method. It’s important to remember the states we are talking about are skin states, and not component states (see Flex 4 Component States vs. Skin States for the difference).

Second, we focus on the action of opening and closing the drawer. Here’s the relevant code (taken from Drawer.as):

public class Drawer extends SkinnableContainer {
    ...
    [SkinPart(required="false")]
    public var openButton:Button;
 
    private function clickHandler(event:MouseEvent):void {
        opened = !opened;
    }
 
    override protected function partAdded(partName:String, instance:Object):void {
        super.partAdded(partName, instance);
        if (instance == openButton) {
            openButton.addEventListener(MouseEvent.CLICK, clickHandler);
        }
    }
 
    override protected function partRemoved(partName:String, instance:Object):void {
        super.partRemoved(partName, instance);
        if (instance == openButton) {
            openButton.removeEventListener(MouseEvent.CLICK, clickHandler);
        }
    }
}

The Drawer component includes a simple spark button, as an optional SkinPart, that is used to initiate the state change. The partAdded() and partRemoved() methods are overridden to manage and adding and removing of the button’s click event handler. And lastly, the clickHandler() method flips between skin states by toggling the opened boolean property.

Usage

Using the Drawer is the same as any container. In MXML, just put any child components you want between the container’s open and close tags:

<containers:Drawer ... skinClass="skins.DrawerSkin">
    <!-- components go here -->
</containers:Drawer>

Here we also apply the DrawerSkin to our container.

Skins

The DrawerSkin is responsible for creating the desired look-and-feel and generally making the Drawer component look cool. Here are the interesting parts of the skin:

<s:Skin ...>
 
    <fx:Metadata>
        [HostComponent("containers.Drawer")]
    </fx:Metadata>
 
    <s:states>
        <s:State name="normal" />
        <s:State name="opened" />
        <s:State name="disabled" />
    </s:states>
 
   ...
 
    <s:Button id="openButton" ...
            skinClass="skins.DrawerOpenButtonSkin"
            skinClass.opened="skins.DrawerCloseButtonSkin" />
 
    <s:Group id="contentGroup" ... includeIn="opened" />
</s:Skin>

The DrawerSkin has three skin states, normal and disabled are inherited from SkinnableContainer, but opened is our custom skin state. The skin also includes the optional openButton SkinPart, which itself uses two custom buttons skins, one for the open drawer and one for the closed drawer. Lastly, note that the container’s content is only displayed when the skin is in the opened state via the newfangled inline state syntax: includeIn="opened".

Files

 9.20

Flex 4 introduced an awesome new skinning architecture. Among other things, the new architecture provides significantly better separation between a component and its skin. Flex 4 also promotes the use of states to the point where they are virtually mandatory in any non-trivial app. And that brings us to the question of the day:

How do you communicate state information from the host component down to its skin?

As always, we’ll dive into some examples to explore how things work. In our first example, we just want our skin to mirror the states of its host component. So, we begin with a simple component based on SkinnableComponent. And then we add three states: base, happy, sad. The code:

<?xml version="1.0" encoding="utf-8"?>
<s:SkinnableComponent
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        skinClass="skins.SmileySkin">
 
    <s:states>
        <s:State name="base" />
        <s:State name="happy" />
        <s:State name="sad" />
    </s:states>
</s:SkinnableComponent>

Right now our component is just a bag of states. But going forward, we know we want to skin it with skin that has same three states. So we force the skin state to mirror the host state with three simple steps:

  1. SkinState – Add SkinState metadata to the host component.
  2. getCurrentSkinState() – Override the getCurrentSkinState() method to return the host’s currentState. (This is the mirror!)
  3. invalidateSkinState() – Force the skin state to update by calling invalidateSkinState() every time the host’s state changes.

Implementing these changes, we arrive at:

<?xml version="1.0" encoding="utf-8"?>
<s:SkinnableComponent
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        skinClass="skins.SmileySkin">
 
    <fx:Metadata>
        [SkinState("base")]
        [SkinState("happy")]
        [SkinState("sad")]
    </fx:Metadata>
 
    <fx:Script>
        <![CDATA[
            override protected function getCurrentSkinState():String {
                return currentState;
            }
        ]]>
    </fx:Script>
 
    <s:states>
        <s:State name="base" enterState="invalidateSkinState()" />
        <s:State name="happy" enterState="invalidateSkinState()" />
        <s:State name="sad" enterState="invalidateSkinState()" />
    </s:states>
</s:SkinnableComponent>

Step 1 is straightforward. In Step 2, we override and return currentState. And Step 3 is achieved by calling invalidateSkinState() directly in each state’s enterState event handler. So to answer our original question: skin state is literally communicated from the host component down to the skin via the getCurrentSkinState() method. If we pass in currentState then we get a perfect state mirror (aka skin state = host component state).

We finish off our example app by adding a silly yellow smiley face skin and a simple main app to hold our component. Here it is (view source enabled):

Flash is required. Get it here!

Use the ButtonBar to change the component’s state. Check the source to see the trivial FXG used to draw the smiley face.

ItemRenderer States

All of this has been leading up to my typical case. I have a nice custom component with a nice skin (maybe I built my component and skin in Flash Catalyst or maybe I built them by hand). Then I suddenly realize, Damn!, I need to use my component in an ItemRenderer. So how do I go about hooking up the standard ItemRenderer states (normal, hovered, selected) to my custom component?

Before I get to the answer, let’s rewind a little bit to set the scene. Imagine I have a component that displays a grade, and I want to display a different graphical treatment depending on the grade. The Flex implementation is the standard stateless custom component with a multi-state skin (Button is a good example). A little different that our first example, but our component still need to communicate skin state information down to its skin.

Our grade component:

<?xml version="1.0" encoding="utf-8"?>
<s:SkinnableComponent
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        skinClass="skins.GradeSkin">
 
    <fx:Metadata>
        [SkinState("A")]
        [SkinState("B")]
        [SkinState("C")]
    </fx:Metadata>
 
    <fx:Script>
        <![CDATA[
            private var _grade:int = 0;
 
            [Bindable]
            public function get grade():int {
                return _grade;
            }
            public function set grade(value:int):void {
                _grade = (value > 100 ? 100 : value < 0 ? 0 : value);
                invalidateSkinState();
            }
 
            override protected function getCurrentSkinState():String {
                return (grade >= 90 ? 'A' : grade >= 80 ? 'B' : 'C');
            }
        ]]>
    </fx:Script>
</s:SkinnableComponent>

We followed a similar set of three steps to create this component. Step 1 is still “add SkinState metadata”. Step 2 is still “override getCurrentSkinState()” but this time we return a state based on the value of grade. Step 3 is still “force the skin state to change by calling invalidateSkinState()” but this time we call it in the setter method for grade. These three steps give us exactly what we want: a host component without any states that changes its skin state depending on the value of grade.

The code for our three state skin is here:

<?xml version="1.0" encoding="utf-8"?>
<s:Skin ...>
 
    <fx:Metadata>
        [HostComponent("components.Grade")]
    </fx:Metadata>
 
    <s:states>
        <s:State name="A" />
        <s:State name="B" />
        <s:State name="C" />
    </s:states>
 
    <!-- gold star -->
    <s:Path scaleX="0.2655" scaleY="0.2655" includeIn="A">
        ...
    </s:Path>
 
    <!-- pink circle -->
    <s:Ellipse left="0" right="0" top="0" bottom="0" includeIn="B">
        ...
    </s:Ellipse>
 
    <!-- blue square -->
    <s:Rect left="0" right="0" top="0" bottom="0" includeIn="C">
        ...
    </s:Rect>
 
    <s:SimpleText text="{hostComponent.grade}" ... />
</s:Skin>

We define our three states and then use a different FXG shape for each state. A is a gold star, B is a pink circle, and C is a blue square. We also display the number grade via simple binding to hostComponent.grade. Alternately, we could have used a SkinPart to pass the grade information down to the skin (here is a good example), but it costs us complexity so I went with the simple binding instead.

Where I Say, Damn!, ItemRenderer

So, I need to use my nice component in an ItemRenderer. Damn!, I say. As a first attempt, we just dump our custom component inside an inline ItemRenderer, like this:

<?xml version="1.0" encoding="utf-8"?>
<s:Application ... >
 
    <s:List left="10" top="10" width="400" height="95">
        <mx:ArrayCollection source="[95,85,75,5,101,90,80,-1]" />
 
        <s:itemRenderer>
            <fx:Component>
                <s:ItemRenderer>
                    <s:states>
                        <s:State name="normal" />
                        <s:State name="hovered" />
                        <s:State name="selected" />
                    </s:states>
 
                    <comps:Grade grade="{data}" />
                </s:ItemRenderer>
            </fx:Component>
        </s:itemRenderer>
 
        <s:layout>
            <s:HorizontalLayout ... />
        </s:layout>
    </s:List>
</s:Application>

We get a nice app, but it obviously doesn’t respond to any of the ItemRenderer‘s states. Here is attempt #1 (view source enabled):

Flash is required. Get it here!

For attempt #2, we can respond to the states directly by adding some code inside the inline ItemRenderer. What code? Well, filters are the prefect fit in this case. They provide a nice visual effect (not easily mimicked by JavaScript), and they are very easy to wrap around a component in a non-invasive manner. Here is the code:

<s:ItemRenderer>
    <s:states>
        <s:State name="normal" />
        <s:State name="hovered" />
        <s:State name="selected" />
    </s:states>
 
    <comps:Grade grade="{data}">
        <comps:filters>
            <s:GlowFilter color="#000000" includeIn="hovered"
                     alpha="0.5" blurX="8" blurY="8" />
            <s:DropShadowFilter includeIn="selected"
                     alpha="0.5" blurX="8" blurY="8" />
        </comps:filters>
    </comps:Grade>
</s:ItemRenderer>

I love filters, and using them can often save the day and avoid some implementation pain. But sometimes, it’s just not enough. Sometimes, you absolutely must have your custom component (and it’s skin) respond to the ItermRenderer‘s states. In those cases, you just need get a little dirty…

For attempt #3 (our final attempt), we need to communicate the ItemRenderer‘s state down to our custom component. The easiest thing to do is bind our custom component’s state to the ItemRenderer‘s state. A simple currentState = "{this.currentState}" does the trick. Here is the refactored inline ItemRenderer code:

<s:ItemRenderer>
    <s:states>
        <s:State name="normal" />
        <s:State name="hovered" />
        <s:State name="selected" />
    </s:states>
 
    <comps:Grade grade="{data}" currentState="{this.currentState}" />
</s:ItemRenderer>

Now we must add three new states to our custom component, and communicate those states down to our skin. Again, we revisit our favorite three steps and refactor our custom component like this:

<?xml version="1.0" encoding="utf-8"?>
<s:SkinnableComponent
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        skinClass="skins.GradeSkin">
 
    <fx:Metadata>
        [SkinState("Anormal")]
        [SkinState("Ahovered")]
        [SkinState("Aselected")]
        [SkinState("Bnormal")]
        [SkinState("Bhovered")]
        [SkinState("Bselected")]
        [SkinState("Cnormal")]
        [SkinState("Chovered")]
        [SkinState("Cselected")]
    </fx:Metadata>
 
    <fx:Script>
        <![CDATA[
            ... getter and setter for grade, same as before ...
 
            override protected function getCurrentSkinState():String {
                return (grade >= 90 ? 'A' : grade >= 80 ? 'B' : 'C') + currentState;
            }
        ]]>
    </fx:Script>
 
    <s:states>
        <s:State name="normal" enterState="invalidateSkinState()" />
        <s:State name="hovered" enterState="invalidateSkinState()" />
        <s:State name="selected" enterState="invalidateSkinState()" />
    </s:states>
</s:SkinnableComponent>

In Step 1, we added a bunch more SkinState metadata directives. In Step 2, we simply appended currentState to the string returned by the overridden getCurrentSkinState() method. The result is 3×3 = 9 skin states (added in Step 1). In Step 3, we added three new states (mirroring the ItemRenderer‘s states) to our component. And in each enterState event handler, we call invalidateSkinState(). There are, of course, other ways to do it. But to me it makes the most conceptual sense to add the new states to our custom component, and then pass them down to the skin.

Lastly, we refactor our skin to include all 9 states and respond to them graphically:

<?xml version="1.0" encoding="utf-8"?>
<s:Skin ...>
 
    <fx:Metadata>
        [HostComponent("components.Grade")]
    </fx:Metadata>
 
    <s:states>
        <s:State name="Anormal" stateGroups="A, normal" />
        <s:State name="Ahovered" stateGroups="A, hovered" />
        <s:State name="Aselected" stateGroups="A, selected" />
        <s:State name="Bnormal" stateGroups="B, normal" />
        <s:State name="Bhovered" stateGroups="B, hovered" />
        <s:State name="Bselected" stateGroups="B, selected" />
        <s:State name="Cnormal" stateGroups="C, normal" />
        <s:State name="Chovered" stateGroups="C, hovered" />
        <s:State name="Cselected" stateGroups="C, selected" />
    </s:states>
 
    <s:Path scaleX="0.2655" scaleY="0.2655" includeIn="A">
        <s:data>...</s:data>
        <s:stroke>
            <s:SolidColorStroke color="#000000" />
        </s:stroke>
        <s:fill>
            <s:RadialGradient>
                <s:GradientEntry color="#FFCC00" ratio="0" />
                <s:GradientEntry ratio="1"
                    color="#FFCC00"
                    color.Ahovered="#CC0066"
                    color.Aselected="#660033" />
            </s:RadialGradient>
        </s:fill>
    </s:Path>
 
    ...
</s:Skin>

The first thing to note is the use of stateGroups. And all this time you thought they were useless? Here they enable us to split our combined states into their component parts, giving a simpler and more understandable set of states: A, B, C, normal, hovered, selected. In the code, we preserve the original grade to shape mapping (A is still a gold star, etc.), but we’ve added code to respond to the ItemRenderer states via a color change.

It is more interesting to see the result. So, here is attempt #3 (view source enabled):

Flash is required. Get it here!
Conclusion

Remember the three steps to achieve host component to skin state communication and you will live forever in skinning nirvana:

  1. SkinState
  2. getCurrentSkinState()
  3. invalidateSkinState()
Files

NOTE: All code was built with Flash Builder 4 Beta 1.




 6.1

The plan is simple, take the nice Degrafa-skinned components from Part 1 and assemble them into a video player powered by the OvpNetStream class from the Open Video Player project.

Design

I knew right away that the design was not going to have any right angles, but I also didn’t want to go with rounded rectangles everywhere. Modern TVs tend to have a lot of soft rounded edges, so I decided to go with a more vintage look. So I fired up Inkscape and got to work:

tv

Implementing the video player design above in Degrafa, the cabinet mapped to a RoundedRectangle, and the screen & antenna became Paths. You can read more about about translating SVG to Degrafa in my Inkscape SVG to Degrafa Path article. But for now, let’s focus on the resulting Degrafa code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
        xmlns:mx="http://www.adobe.com/2006/mxml"
        xmlns:Degrafa="http://www.degrafa.com/2007"
        layout="absolute">
 
    <Degrafa:GeometryComposition graphicsTarget="{[box]}">
        <!-- Antenna -->
        <Degrafa:Path data="...path data...">
            <Degrafa:transform>
                <Degrafa:TranslateTransform x="15" />
            </Degrafa:transform>
        </Degrafa:Path>
 
        <!-- TV cabinet -->
        <Degrafa:RoundedRectangle y="144" width="350" height="300"
                cornerRadius="20" />
 
        <Degrafa:fill>
            <Degrafa:SolidFill color="#333333" />
        </Degrafa:fill>
        <Degrafa:stroke>
            <Degrafa:SolidStroke color="#FF00FF" weight="4" alpha="0.4" />
        </Degrafa:stroke>
    </Degrafa:GeometryComposition>
 
    <!-- TV Screen -->
    <Degrafa:GeometryComposition graphicsTarget="{[tvscreen]}">
        <Degrafa:Path data="...path data...">
            <Degrafa:fill>
                <Degrafa:SolidFill color="#FF99FF" />
            </Degrafa:fill>
            <Degrafa:stroke>
                <Degrafa:SolidStroke color="#FF00FF" weight="2" alpha="0.4" />
            </Degrafa:stroke>
            <Degrafa:filters>
                <mx:GlowFilter color="#EEEEEE" alpha="0.2" blurX="16" blurY="16" />
            </Degrafa:filters>
        </Degrafa:Path>
    </Degrafa:GeometryComposition>
 
    <mx:Canvas width="350" height="444"
            horizontalCenter="0" verticalCenter="0">
        <mx:Canvas id="box" />
        <mx:Canvas x="50" y="174" id="tvscreen" />
    </mx:Canvas>
</mx:Application>

I ended up using a pair of GeometryCompositions to wrap my three shapes to help keep my fills, strokes, and filters organized. It made sense to do it this way, but I won’t claim it’s the best way. Throw the control bar on below the TV screen, and the design is done.

Backend

The backend is build on the OvpNetStream class provided by the Open Video Player project. OvpNetStream extends NetStream and smooths out some of the rough edges as I discussed previously. Basically, it provides a sane interface (no need to construct a dynamic object with function callbacks) and useful events (like metadata and progress events).

For this demo, we simply instantiate OvpNetStream on creationComplete and wire up all the event handlers:

private function complete():void {
    nc = new OvpConnection();
    nc.addEventListener(OvpEvent.ERROR, errorHandler);
    nc.addEventListener(NetStatusEvent.NET_STATUS, connStatusHandler);
    nc.connect(null);
 
    ns = new OvpNetStream(nc);
    ns.addEventListener(OvpEvent.ERROR, errorHandler);
    ns.addEventListener(NetStatusEvent.NET_STATUS, streamStatusHandler);
    ns.addEventListener(OvpEvent.NETSTREAM_METADATA, streamMetadataHandler);
    ns.addEventListener(OvpEvent.PROGRESS, streamProgressHandler);
    ns.addEventListener(OvpEvent.COMPLETE, streamCompleteHandler);
 
    vid = new Video();
    vid.attachNetStream(ns);
    vidContainer.addChild(vid);
}

The most interesting events are the metadata and progress events. The metadata event delivers the duration of the video and its size. The progress event arrives periodically (theoretically every 100ms by default, but in reality I see them come in just a couple of times per second) and delivers the current video time.

Control Bar

The control bar consists of three components: a play-pause button, a scrubber, and a volume slider. They were skinned using Degrafa in Part 1. In order to control video playback, we need to wire the control bar components to the instance of OvpNetStream created above.

Here are the event handlers for the three control bar components:

// PlayPause event handler
private function playPauseClick():void {
    if (first) {
        first = false;
        ns.play(filename);
    } else {
        ns.togglePause();
     }
}
 
// Scrub event handlers
private function scrubPress():void {
    ns.pause();
    playPause.selected = false;
}
private function scrubDrag():void {
    ns.seek(scrub.value);
}
private function scrubRelease():void {
    ns.togglePause();
    playPause.selected = true;
}
 
// Volume event handler
private function volumeChange():void {
    ns.volume = volume.value;
}

In the playPauseHandler(), the initial click calls play() which actually loads the video (and then starts playback), all subsequent clicks just toggle between play or pause. For the scrubber handlers, I chose to break them up into three separate steps: on mouse down pause the video, on mouse up restart playback, and on drag attempt to seek to the to the new time.

That’s it. Here is the resulting Degrafa-skinned video player (view source enabled):

Flash is required. Get it here!

Click Play to start playing Elephants Dream (which is the “world’s first open movie,” and pretty cool too). Right away you’ll notice some visual issues because the dimensions of the video are unknown until the metadata arrives. Also, scrubbing has some problems which I believe are related to cue points in progressive downloads. Lastly, I didn’t implement any indicators for buffering or download progress, so you’ll need to be patient. Since this is just a demo, I’ll have to leave fixing those bugs as an exercise for the reader.

Files

© 2010 saturnboy.com