YUI 3.x Home -

YUI Library Examples: Overlay: Animation Plugin

Overlay: Animation Plugin

This example shows how you can use Widget's plugin infrastructure to customize the existing behavior of a widget.

We create an Animation plugin class for Overlay called AnimPlugin which changes the way Overlay instances are shown/hidden, by fading them in and out. The Overlay is initially constructed with the AnimPlugin plugged in (with the duration set to 2 seconds). Clicking the "Unplug AnimPlugin" button, will restore the original non-Animated Overlay show/hide behavior. Clicking on the "Plug AnimPlugin" button will plug in the AnimPlugin again, but with a shorter duration.

Overlay Header
Overlay Body
Overlay Footer

Creating an Animation Plugin For Overlay

Setting Up The YUI Instance

For this example, we'll pull in the overlay module, along with the anim and plugin modules. The anim module provides the animation utility, and plugin will provide the Plugin base class which we'll extend to create our AnimPlugin. The code to set up our sandbox instance is shown below:

  1. YUI({...}).use("overlay", "anim", "plugin", function(Y) {
  2. // We'll write our code here, after pulling in the default
  3. // Overlay widget, the Animation utility and the
  4. // Plugin base class
  5. });
YUI({...}).use("overlay", "anim", "plugin", function(Y) {
    // We'll write our code here, after pulling in the default 
    // Overlay widget, the Animation utility and the 
    // Plugin base class
});

Using the overlay module will also pull down the default CSS required for overlay, on top of which we only need to add our required look/feel CSS for the example.

AnimPlugin Class Structure

The AnimPlugin class will extend the Plugin base class. Since Plugin derives from Base, we follow the same pattern we use for widgets and other utilities which extend Base to setup our new class.

Namely:

  • Setting up the constructor to invoke the superclass constructor
  • Setting up a NAME property, to identify the class
  • Setting up the default attributes, using the ATTRS property
  • Providing prototype implementations for anything we want executed during initialization and destruction using the initializer and destructor lifecycle methods

Additionally, since this is a plugin, we provide a NS property for the class, which defines the property which will refer to the AnimPlugin instance on the host class (e.g. overlay.fx will be an instance of AnimPlugin)

.

This basic structure is shown below:

  1. /* Animation Plugin Constructor */
  2. function AnimPlugin(config) {
  3. AnimPlugin.superclass.constructor.apply(this, arguments);
  4. }
  5.  
  6. /*
  7.  * The namespace for the plugin. This will be the property on the widget, which will
  8.  * reference the plugin instance, when it's plugged in
  9.  */
  10. AnimPlugin.NS = "fx";
  11.  
  12. /*
  13.  * The NAME of the AnimPlugin class. Used to prefix events generated
  14.  * by the plugin class.
  15.  */
  16. AnimPlugin.NAME = "animPlugin";
  17.  
  18. /*
  19.  * The default set of attributes for the AnimPlugin class.
  20.  */
  21. AnimPlugin.ATTRS = {
  22.  
  23. /*
  24.   * Default duration. Used by the default animation implementations
  25.   */
  26. duration : {
  27. value: 0.2
  28. },
  29.  
  30. /*
  31.   * Default animation instance used for showing the widget (opacity fade-in)
  32.   */
  33. animVisible : {
  34. valueFn : function() {
  35. ...
  36. }
  37. },
  38.  
  39. /*
  40.   * Default animation instance used for hiding the widget (opacity fade-out)
  41.   */
  42. animHidden : {
  43. valueFn : function() {
  44. ...
  45. }
  46. }
  47. }
  48.  
  49. /*
  50.  * Extend the base plugin class
  51.  */
  52. Y.extend(AnimPlugin, Y.Plugin, {
  53.  
  54. // Lifecycle methods
  55. initializer : function(config) { ... },
  56. destructor : function() { ... },
  57.  
  58. // Other plugin specific methods
  59. _uiAnimSetVisible : function(val) { ... },
  60. _uiSetVisible : function(val) { ... },
  61. ...
  62. });
/* Animation Plugin Constructor */
function AnimPlugin(config) {
    AnimPlugin.superclass.constructor.apply(this, arguments);
}
 
/* 
 * The namespace for the plugin. This will be the property on the widget, which will 
 * reference the plugin instance, when it's plugged in
 */
AnimPlugin.NS = "fx";
 
/*
 * The NAME of the AnimPlugin class. Used to prefix events generated
 * by the plugin class.
 */
AnimPlugin.NAME = "animPlugin";
 
/*
 * The default set of attributes for the AnimPlugin class.
 */
AnimPlugin.ATTRS = {
 
    /*
     * Default duration. Used by the default animation implementations
     */
    duration : {
        value: 0.2
    },
 
    /*
     * Default animation instance used for showing the widget (opacity fade-in)
     */
    animVisible : {
        valueFn : function() {
            ...
        }
    },
 
    /*
     * Default animation instance used for hiding the widget (opacity fade-out)
     */
    animHidden : {
        valueFn : function() {
            ...
        }
    }
}
 
/*
 * Extend the base plugin class
 */
Y.extend(AnimPlugin, Y.Plugin, {
 
    // Lifecycle methods
    initializer : function(config) { ... },
    destructor : function() { ... },
 
    // Other plugin specific methods
    _uiAnimSetVisible : function(val) { ... },
    _uiSetVisible : function(val) { ... },
    ...
});

Attributes: animVisible, animHidden

The animVisible and animHidden attributes use Attribute's valueFn support to set up instance based default values for the attributes.

The animHidden attribute is pretty straight forward and simply returns the Animation instance bound to the bounding box of the Overlay to provide a fade-out animation:

  1. animHidden : {
  2. valueFn : function() {
  3. return new Y.Anim({
  4. node: this.get("host").get("boundingBox"),
  5. to: { opacity: 0 },
  6. duration: this.get("duration")
  7. });
  8. }
  9. }
animHidden : {
    valueFn : function() {
        return new Y.Anim({
            node: this.get("host").get("boundingBox"),
            to: { opacity: 0 },
            duration: this.get("duration")
        });
    }
}

The animVisible attribute is a little more interesting:

  1. animVisible : {
  2. valueFn : function() {
  3.  
  4. var host = this.get("host"),
  5. boundingBox = host.get("boundingBox");
  6.  
  7. var anim = new Y.Anim({
  8. node: boundingBox,
  9. to: { opacity: 1 },
  10. duration: this.get("duration")
  11. });
  12.  
  13. // Set initial opacity, to avoid initial flicker
  14. if (!host.get("visible")) {
  15. boundingBox.setStyle("opacity", 0);
  16. }
  17.  
  18. // Clean up, on destroy. Where supported, remove
  19. // opacity set using style. Else make 100% opaque
  20. anim.on("destroy", function() {
  21. if (Y.UA.ie) {
  22. this.get("node").setStyle("opacity", 1);
  23. } else {
  24. this.get("node").setStyle("opacity", "");
  25. }
  26. });
  27.  
  28. return anim;
  29. }
  30. }
animVisible : {
    valueFn : function() {
 
        var host = this.get("host"),
            boundingBox = host.get("boundingBox");
 
        var anim = new Y.Anim({
            node: boundingBox,
            to: { opacity: 1 },
            duration: this.get("duration")
        });
 
        // Set initial opacity, to avoid initial flicker
        if (!host.get("visible")) {
            boundingBox.setStyle("opacity", 0);
        }
 
        // Clean up, on destroy. Where supported, remove
        // opacity set using style. Else make 100% opaque
        anim.on("destroy", function() {
            if (Y.UA.ie) {
                this.get("node").setStyle("opacity", 1);
            } else {
                this.get("node").setStyle("opacity", "");
            }
        });
 
        return anim;
    }
}

It essentially does the same thing as animHidden; setting up an Animation instance to provide an opacity based fade-in. However it also sets up a listener which will attempt to cleanup the opacity state of the Overlay when the plugin is unplugged from the Overlay. When a plugin is unplugged, it is destroyed.

Lifecycle Methods: initializer, destructor

In the initializer, we set up listeners on the animation instances (using _bindAnimVisible, _bindAnimHidden), which invoke the original visibility handling to make the Overlay visible before starting the animVisible animation and hide it after the animHidden animation is complete.

  1. initializer : function(config) {
  2. this._bindAnimVisible();
  3. this._bindAnimHidden();
  4.  
  5. this.after("animVisibleChange", this._bindAnimVisible);
  6. this.after("animHiddenChange", this._bindAnimHidden);
  7.  
  8. // Override default _uiSetVisible method, with custom animated method
  9. this.doBefore("_uiSetVisible", this._uiAnimSetVisible);
  10. }
  11.  
  12. ...
  13.  
  14. _bindAnimVisible : function() {
  15. var animVisible = this.get("animVisible");
  16.  
  17. animVisible.on("start", Y.bind(function() {
  18. // Setup original visibility handling (for show) before starting to animate
  19. this._uiSetVisible(true);
  20. }, this));
  21. },
  22.  
  23. _bindAnimHidden : function() {
  24. var animHidden = this.get("animHidden");
  25.  
  26. animHidden.after("end", Y.bind(function() {
  27. // Setup original visibility handling (for hide) after completing animation
  28. this._uiSetVisible(false);
  29. }, this));
  30. }
initializer : function(config) {
    this._bindAnimVisible();
    this._bindAnimHidden();
 
    this.after("animVisibleChange", this._bindAnimVisible);
    this.after("animHiddenChange", this._bindAnimHidden);
 
    // Override default _uiSetVisible method, with custom animated method
    this.doBefore("_uiSetVisible", this._uiAnimSetVisible);
}
 
...
 
_bindAnimVisible : function() {
    var animVisible = this.get("animVisible");
 
    animVisible.on("start", Y.bind(function() {
        // Setup original visibility handling (for show) before starting to animate
        this._uiSetVisible(true);
    }, this));
},
 
_bindAnimHidden : function() {
    var animHidden = this.get("animHidden");
 
    animHidden.after("end", Y.bind(function() {
        // Setup original visibility handling (for hide) after completing animation
        this._uiSetVisible(false);
    }, this));
}

However the key part of the initializer method is the call to this.doBefore("_uiSetVisible", this._uiAnimSetVisible) (line 9). Plugin's doBefore and doAfter methods, will let you set up both before/after event listeners, as well as inject code to be executed before or after a given method on the host object (in this case the Overlay) is invoked.

For the animation plugin, we want to change how the Overlay updates its UI in response to changes to the visible attribute. Instead of simply flipping visibility (through the application of the yui-overlay-hidden class), we want to fade the Overlay in and out. Therefore, we inject our custom animation method, _uiSetAnimVisible, before the Overlay's _uiSetVisible.

Using Plugin's doBefore/doAfter methods to setup any event listeners and method injection code on the host object (Overlay), ensures that the custom behavior is removed when the plugin is unplugged from the host, restoring it's original behavior.

The destructor simply calls destroy on the animation instances used, and lets them perform their own cleanup (as defined in the discussion on attributes):

  1. destructor : function() {
  2. this.get("animVisible").destroy();
  3. this.get("animHidden").destroy();
  4. },
destructor : function() {
    this.get("animVisible").destroy();
    this.get("animHidden").destroy();
},

The Animated Visibility Method

The _uiAnimSetVisible method is the method we use to over-ride the default visibility handling for the Overlay. Instead of simply adding or removing the yui-overlay-hidden class, it starts the appropriate animation depending on whether or not visible is being set to true or false:

  1. _uiAnimSetVisible : function(val) {
  2. if (this.get("host").get("rendered")) {
  3. if (val) {
  4. this.get("animHidden").stop();
  5. this.get("animVisible").run();
  6. } else {
  7. this.get("animVisible").stop();
  8. this.get("animHidden").run();
  9. }
  10. return new Y.Do.Halt();
  11. }
  12. }
_uiAnimSetVisible : function(val) {
    if (this.get("host").get("rendered")) {
        if (val) {
            this.get("animHidden").stop();
            this.get("animVisible").run();
        } else {
            this.get("animVisible").stop();
            this.get("animHidden").run();
        }
        return new Y.Do.Halt();
    }
}

Since this method is injected before the default method which handles visibility changes for Overlay (_uiSetVisibility), we invoke Y.Do.Halt() to prevent the original method from being invoked, since we'd like to invoke it in response to the animation starting or completing. Y.Do is YUI's aop infrastructure and is used under the hood by Plugin's doBefore and doAfter methods when injecting code

.

The Original Visibility Method

The original visiblity handling for Overlay is replicated in the AnimPlugin's _uiSetVisible method and is invoked before starting the animVisible animation and after completing the animHidden animation as described above.

  1. _uiSetVisible : function(val) {
  2. var host = this.get("host");
  3. if (!val) {
  4. host.get("boundingBox").addClass(host.getClassName("hidden"));
  5. } else {
  6. host.get("boundingBox").removeClass(host.getClassName("hidden"));
  7. }
  8. }
_uiSetVisible : function(val) {
    var host = this.get("host");
    if (!val) {
        host.get("boundingBox").addClass(host.getClassName("hidden"));
    } else {
        host.get("boundingBox").removeClass(host.getClassName("hidden"));
    }
}

NOTE: We're evaluating whether or not Y.Do may provide access to the original method for a future release, which would make this replicated code unnecessary.

Using The Plugin

All objects which derive from Base are Plugin Hosts. They provide plug and unplug methods to allow users to add/remove plugins to/from existing instances. They also allow the user to specify the set of plugins to be applied to a new instance, along with their configurations, as part of the constructor arguments:

  1. var overlay = new Y.Overlay({
  2. contentBox: "#overlay",
  3. width:"10em",
  4. height:"10em",
  5. visible:false,
  6. shim:false,
  7. align: {
  8. node: "#show",
  9. points: ["tl", "bl"]
  10. },
  11. plugins : [{fn:AnimPlugin, cfg:{duration:2}}]
  12. });
  13. overlay.render();
var overlay = new Y.Overlay({
    contentBox: "#overlay",
    width:"10em",
    height:"10em",
    visible:false,
    shim:false,
    align: {
        node: "#show", 
        points: ["tl", "bl"]
    },
    plugins : [{fn:AnimPlugin, cfg:{duration:2}}]
});
overlay.render();

We use the constructor support to setup the AnimPlugin for the instance with a custom value for its duration attribute as shown on line 11 above.

NOTE: In the interests of keeping the example focused on the plugin infrastructure, we turn off shimming for the overlay. If we needed to enable shimming, In IE6, we'd need to remove the alpha opacity filter set on the shim while animating, to have IE animate the contents of the Overlay correctly.

The example also uses the plug and unplug methods, to add and remove the custom animation behavior after the instance is created:

  1. // Listener for the "Unplug AnimPlugin" button,
  2. // removes the AnimPlugin from the overlay instance
  3. Y.on("click", function() {
  4. overlay.unplug("fx");
  5. }, "#unplug");
  6.  
  7. // Listener for the "Plug AnimPlugin" button,
  8. // removes the AnimPlugin from the overlay instance,
  9. // and re-adds it with a new, shorter duration value.
  10. Y.on("click", function() {
  11. overlay.unplug("fx");
  12. overlay.plug(AnimPlugin, {duration:0.5});
  13. }, "#plug");
// Listener for the "Unplug AnimPlugin" button, 
// removes the AnimPlugin from the overlay instance
Y.on("click", function() {
    overlay.unplug("fx");
}, "#unplug");
 
// Listener for the "Plug AnimPlugin" button, 
// removes the AnimPlugin from the overlay instance, 
// and re-adds it with a new, shorter duration value.
Y.on("click", function() {
    overlay.unplug("fx");
    overlay.plug(AnimPlugin, {duration:0.5});
}, "#plug");

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings