Saturnboy
 12.14

It’s time to revisit drag-and-drop in Flex 4. For a long time now, my previous Drag-and-Drop in Flex 4 post has been the most popular post on this blog. I get something like 1,200 pageview/month on that one post. This time around, I’ll try to expand on the thinking that goes on before I write the code to add drag-and-drop functionality to an app.

UX 101

It is impossible to develop an RIA without some basic understanding of interaction design. As they say in one of my favorite movies, "Many men have tried. They tried and failed? They tried and died." So a short UX primer on drag-and-drop goes like this…

Users are typically familiar with drag-and-drop for two basic actions: moving-stuff-around and putting-stuff-into. For example, we move windows around the desktop or move songs around in a playlist or move icons around in a folder. Also, we put stuff into the trash or put a picture into an album or put an attachment into an email. At a fundmental level, users have an understanding of these actions because they mimic the physical world. Performing these actions via a touch interface (rather than a mouse) is even better, but that’s a story for another day.

Given these two basic actions, I’m going to design a sample app that exercises them both. This is what I came up with:

diagram 1

Our sample app has three drag actions. In #1, you can drag to put items from the palette into the list. In #2a and #2b, you can drag items from the list into a target box (that preforms some action). In #3, you can drag items around inside the list to reorder them. I’ll break them down one by one.

#1 — Drag List Item to Another List

Dragging from one list and dropping on another is super easy in Flex 4. Here’s a snippet:

<s:List id="sourceList" dragEnabled="true">
    <s:ArrayList source="['A','B','C','D']" />
</s:List>
 
<s:List id="targetList" dropEnabled="true">
    <s:ArrayList></s:ArrayList>
</s:List>

We set dragEnable=true on the source list and dropEnable=true on the target list. For bi-directional drag-and-drop, just set both attributes true for both lists. In a feat of awesomeness, Flex 4 does everything else for you. You don’t need to listen for any events or write any handlers. And you even get some nice eye candy for free, because the target list glows when you drag an item over it.

Trick 1 — When the drop target is an empty list, you must given it an empty dataProvider. In the above example, I just use an empty ArrayList pair of tags in MXML, but I could just as easily say dataProvider="{new ArrayList()}", or even do everything in Actionscript.

Trick 2 — The source list accepts a drop—if and only if—the item being dropped is compatible with the items in the target dataProvider. For example, you can not drop a Foo object on a list of Bar objects. Setting the target list to have an empty dataProvider (à la Trick 1), accepts anything.

#2 — Drag List Item to UIComponent Target

Again, to use a list as the drag source, we just set dragEnable=true. But this time the target is some non-List UIComponent, so we need to do what we always do to enable drop functionality on a component—namely, attach handlers to the dragEnter and dragDrop events. Here’s a snippet:

<s:List id="sourceList" dragEnabled="true">
    <s:ArrayList source="['A','B','C','D']" />
</s:List>
 
<s:Panel id="targetA" 
         dragEnter="dragEnterHandler(event)"
         dragDrop="dragDropHandler(event)">
</s:Panel>

And here are the handlers:

private function dragEnterHandler(e:DragEvent):void {
    DragManager.acceptDragDrop(e.currentTarget as IUIComponent);
}
private function dragDropHandler(e:DragEvent):void {
    //do something with dropped item here
}

As always, we accept the drop in the dragEnter handler via the static acceptDragDrop() method on the DragManager. And once the object is dropped, we can do whatever we want with it in the dragDrop handler.

#3 — Drag List Item to Reorder Items

Finally, we want to be able to reorder the items in a list. Again, the spark List does all the work for us. We just set both dragEnable=true and dropEnable=true on the list we want to reorder. We must also set the magical dragMoveEnabled=true, which has numerous ramifications. Here is the snippet:

<s:List id="reorderList"
        dragEnabled="true"
        dropEnabled="true"
        dragMoveEnabled="true">
    <s:ArrayList source="['A','B','C','D']" />
</s:List>

The code is trivial, but what’s going on with dragMoveEnabled=true? Well, dragMoveEnable, which defaults to false, controls whether or not an object is moved (aka removed from the source and added to the target) or copied (aka added to the target leaving the source untouched). So to reorder the items in a list, we need the move behavior, thus we set dragMoveEnabled=true.

Trick 3 — If the source list is dragMoveEnabled=true and the target is a non-List UIComponent, you will see some seemingly odd behavior. Every time to drop an object on your component, it will be deleted from the source list. This is because you are only seeing the first half of the move (the item is removed from the source), and not the second half (the item is added to the target) because the target is not a List.

Trick 4 — As an alternative to dragMoveEnabled=true, you can make a call to DragManager.showFeedback(DragManager.MOVE) in the dragEnter handler to control whether or not an object is moved or copied. Do NOT use both showFeedback and dragMoveEnabled at the same time.

Eye candy

What’s a Flex app without eye candy? But with drag-and-drop, I’d say most of the eye candy is more of a UX necessity than anything else. It’s used to indicate potential drop targets, or highlight a target that is ready to receive a drop, etc.

Glow On Enter

With list to list drag-and-drop, we get a glow on the target list for free, which tells the user that the target list is ready to receive the drop. But when dragging to a non-List UIComponent, we need to add the glow ourselves:

private function dragEnterHandler(e:DragEvent):void {
    myGlow.alpha = 1;
    DragManager.acceptDragDrop(e.currentTarget as IUIComponent);
}
private function dragExitHandler(e:DragEvent):void {
    myGlow.alpha = 0;
}
private function dragDropHandler(e:DragEvent):void {
    myGlow.alpha = 0;
    //do something with dropped item here
}

In the dragEnter handler, we turn the glow on, and we turn the glow off on either a dragExit or dragDrop event. And we need to add a simple GlowFilter to the target component:

<s:Panel id="targetA" 
         dragEnter="dragEnterHandler(event)"
         dragDrop="dragDropHandler(event)">
    <s:filters>
        <s:GlowFilter id="myGlow" blurX="16" blurY="16"
                color="#3399ff" alpha="0" />
    </s:filters>
</s:Panel>

No magic, just use MXML to add a GlowFilter to the target component, which in this snippet is a spark Panel component.

Custom Drag Proxy

Customizing the drag proxy (what an item looks like while dragging) is fun, but I covered that previously, so there’s no need to revisit it here. On the other hand, I haven’t discussed how to customizing an item dragged from a spark List yet. It is not only fun, but also quite a bit easier.

Flex 4 makes is super easy to create a custom drag proxy by simply adding a magic dragging state to the List‘s itemRenderer. For this snippet, imagine I have a trivial ItemRenderer that just shows a centered label with black text, but when it’s being dragged I want to turn the text red:

<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer ...>
    <s:states>
        <s:State name="normal" />
        <s:State name="hovered" />
        <s:State name="selected" />
        <s:State name="dragging"/>
    </s:states>
 
    <s:Label left="0" right="0" top="0" bottom="0"
            text="{data.label}" textAlign="center" verticalAlign="middle"
            color="#000000"
            color.hovered="#0000ff"
            color.dragging="#ff0000" />
</s:ItemRenderer>

As you can see from the above code, customizing the drag indicator is a huge nothing. Just add the magic dragging state to the list of states, and use Flex 4′s inline state syntax to do whatever you want. In this snippet, we set color.dragging="#ff0000" to turn the text red when its being dragged. The sample app below does quite a few more things to customize the dragged item, so check out that code too.

Custom Drop Indicator

When a user drags an item over a target spark List, a line appears to show the user where the item will be inserted. This line is known as the drop indicator. To change things up, we will make a custom drop indicator that is a dashed line.

Trick 5 — Alas, Flex 4 does not have direct support for dashed strokes, so we need to fake it. The easy way to make a dashed line in Flex 4 is to use BitmapFill. First, we create an image that is a tileable pattern of squares. Then, we make a Rect and set its fill to BitmapFill and fillMode="repeat".

The dropIndicator component is found in the fx:Declarations block of the default spark ListSkin, so we must create a custom List skin with our custom dropIndicator component. Here’s a snippet from our custom skin’s fx:Declarations block:

<fx:Declarations>
    <fx:Component id="dropIndicator">
        <s:Group minWidth="1" minHeight="1" maxWidth="1" maxHeight="1">
            <s:Rect left="0" right="0" top="0" bottom="0">
                <s:fill>
                    <s:BitmapFill source="@Embed('dash.png')"
                            fillMode="repeat" />
                </s:fill>
            </s:Rect>
        </s:Group>
    </fx:Component>
</fx:Declarations>

As described above, we have a Rect with a BitmapFill, and an image dash.png that is a tileable pattern of squares. But the real magic is in the Group wrapper, by setting all of minWidth, maxWidth, minHeight, maxHeight to 1px we ensure we get a one pixel line as our drop indicator independent of the layout applied to our List. This is because HorizontalLayout ignore min and max height, and VerticalLayout ignore min and max width. So if we take a 1px view of our pattern of squares, we see dashes.

Conclusion

Here’s the complete drag-and-drop sample (view source enabled):

Flash is required. Get it here!

Hopefully, I covered the full spectrum of drag-and-drop functionality that the average Flex app (or even above average) is ever likely to need. If you want more, check out the links below, or just leave me a comment.

Useful Links
  • My first post on drag-and-drop in Flex 4 covered a lot of drag proxy stuff.
  • Flex After Dark has a solid drag-and-drop tutorial that is definitely worth reading if you are implementing drag-and-drop functionality in your app.
  • Evtim, aka The Godfather, as I like to call him, has a cool post on customizing both the drag indicator and the drop indicator of the spark List component.
Files

 8.5

UPDATE: I have another Drag-and-Drop Revisited post that covers even more drag-and-drop functionality available in Flex 4.

The Flex 4 gods were kind to us developers when they made the great decision to leave the custom drag-and-drop support unchanged. We just do what we’ve always done: detect the user is trying to drag something via mouseDown or mouseMove and then add both dragEnter and dragDrop event handlers to the drop target. So there is nothing in this post that’s not basically identical to Flex 3, except the coolness of FXG (which you can easily mimic with Degrafa in Flex 3).

Simple Drag-and-Drop

I’ll begin with a basic Flex 4 application. We have two draggable graphics (a Rect and an Ellipse) in the left panel, and a target panel on the right:

<?xml version="1.0" encoding="utf-8"?>
<s:Application
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark">
 
    <fx:Script>
        <![CDATA[
            imports...
 
            private function mouseDownHandler(e:MouseEvent):void {
                DragManager.doDrag(e.currentTarget as IUIComponent, null, e);
            }
 
            private function dragEnterHandler(e:DragEvent):void {
                DragManager.acceptDragDrop(e.currentTarget as IUIComponent);
            }
 
            private function dragDropHandler(e:DragEvent):void {
                e.currentTarget.addElement(e.dragInitiator);
            }
        ]]>
    </fx:Script>
 
    <s:Panel title="src" width="100" minHeight="133" x="10" y="10">
        <s:Graphic width="80" height="80"
                mouseDown="mouseDownHandler(event)">
            <s:Rect ... </s:Rect>
        </s:Graphic>
 
        <s:Graphic width="80" height="80"
                mouseDown="mouseDownHandler(event)">
            <s:Ellipse ... </s:Ellipse>
        </s:Graphic>
        ...
    </s:Panel>
 
    <s:Panel title="target" width="100" minHeight="133" x="120" y="10"
            dragEnter="dragEnterHandler(event);"
            dragDrop="dragDropHandler(event);">
        ...
    </s:Panel>
</s:Application>

Reading the code above, each draggable Graphic has a mouseDown handler that calls DragManager.doDrag() to initiate dragging. And the target Panel calls DragManager.acceptDragDrop() on dragEnter and addElement() on dragDrop. Note that since Panel is a Spark container we must use addElement() to re-parent the dropped graphic (the familiar addChild() is still used for Halo containers).

Our simple drag-and-drop app (view source enabled):

Flash is required. Get it here!
Using a FXG Drag Proxy

In the example above, the moment you start dragging a component the drag proxy is displayed. By default, the proxy is just a bounding rectangle with an alpha value of 0.5. This is particularly noticeable and lame when you try to drag the pink circle. Thankfully, we can use any display object for the drag proxy (more specifically any component that implements IFlexDisplayObject which includes UIComponent and any of its descendants). Why not use a FXG graphic? It is, after all, a major piece of the new hotness that is Flex 4.

First, we need to modify the mouseDownHandler to instantiate our FXG graphic. Then we just add it as the forth parameter to the DragManager.doDrag() call.

private function mouseDownHandler(e:MouseEvent):void {
    var star:Star = new Star();
    DragManager.doDrag(e.currentTarget as IUIComponent, null, e, star);
}

And here is Star.mxml:

<?xml version="1.0" encoding="utf-8"?>
<s:Graphic
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        width="80" height="80">
 
    <s:Path data="M 119,0 L 148,86 238,86 166,140 192,226 119,175 46,226 72,140 0,86 90,86 Z"
            y="2" scaleX="0.3361345" scaleY="0.3361345">
        <s:fill>
            <mx:SolidColor color="#FFCC00" />
        </s:fill>
    </s:Path>
</s:Graphic>

Bang! We have a gold star as our drag proxy. Try it out for yourself (view source enabled):

Flash is required. Get it here!
Dynamic Drag Proxy

Dragging a gold star is pretty cool, but how can we make the drag proxy look exactly like the drag source? For that we need a dynamic drag proxy.

First, for reasons which will become clear in a moment, we need to revise our app to make each of the drag source graphics into a separate component. So the left Panel changes to contain these custom components:

<s:Panel title="src" width="100" minHeight="133" x="10" y="10">
    <graphics:Square fillColor="#6666FF"
            mouseDown="mouseDownHandler(event)" />
 
    <graphics:Circle fillColor="#FF66FF"
            mouseDown="mouseDownHandler(event)" />
 
    <graphics:Star fillColor="#FFCC00"
            mouseDown="mouseDownHandler(event)" />
 
    <graphics:Square fillColor="#66FF99"
            mouseDown="mouseDownHandler(event)" />
 
    <s:layout>
        <s:VerticalLayout gap="10" horizontalAlign="center" paddingTop="10" paddingBottom="10" />
    </s:layout>
</s:Panel>

Next, we again modify the mouseDownHandler, this time we instantiate our drag proxy dynamically. We use reflection on the incoming drag source to get its name, instantiate it, adjust a few properties, and pass it to the DragManager.doDrag() call.

private function mouseDownHandler(e:MouseEvent):void {
    var dragSrc:Graphic = e.currentTarget as Graphic;
 
    //create a proxy by creating a new "copy" of the drag src
    var className:String = getQualifiedClassName(dragSrc);
    var klass:Class = getDefinitionByName(className) as Class;
    var proxy:* = new klass();
 
    //set the proxy's properties to match the src + sexy drop shadow
    proxy.width = dragSrc.width;
    proxy.height = dragSrc.height;
    proxy.fillColor = (dragSrc as IDraggableGraphic).fillColor;
    proxy.filters = [new DropShadowFilter()];
 
    DragManager.doDrag(dragSrc, null, e, proxy);
}

The real reason for the reflection gymnastics, plus the need to package each drag source as a custom component, is the lack of a deep copy operation on UIComponent. If we could just clone the drag source, we’d be golden. Alas, for many reasons, the most obvious of which is that it is a huge pain in the ass, there is no such thing as deep copy. In our case, my work around was to package all the visual stuff of each draggable item into a single custom component with a known API (all the custom graphics implement IDraggableGraphic). Then I reflect, instantiate, configure, and pass to doDrag().

Our dynamic drag proxy now matches the drag source, plus the sexy drop shadow. Check it out (view source enabled):

Flash is required. Get it here!
Files

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




© 2017 saturnboy.com