4 ? Y.Array(arguments, 4, true) : null;
return Y.Event.onAvailable.call(Y.Event, id, fn, o, a);
}
};
/**
* Executes the callback as soon as the specified element
* is detected in the DOM with a nextSibling property
* (indicating that the element's children are available).
* This function expects a selector
* string for the element(s) to detect. If you already have
* an element reference, you don't need this event.
* @event contentready
* @param type {string} 'contentready'
* @param fn {function} the callback function to execute.
* @param el {string} an selector for the element(s) to attach.
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.Env.evt.plugins.contentready = {
on: function(type, fn, id, o) {
var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null;
return Y.Event.onContentReady.call(Y.Event, id, fn, o, a);
}
};
}, 'patched-v3.11.0', {"requires": ["event-custom-base"]});
YUI.add('event-custom-base', function (Y, NAME) {
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
*/
Y.Env.evt = {
handles: {},
plugins: {}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* Allows for the insertion of methods that are executed before or after
* a specified method
* @class Do
* @static
*/
var DO_BEFORE = 0,
DO_AFTER = 1,
DO = {
/**
* Cache of objects touched by the utility
* @property objs
* @static
* @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object
* replaces the role of this property, but is considered to be private, and
* is only mentioned to provide a migration path.
*
* If you have a use case which warrants migration to the _yuiaop property,
* please file a ticket to let us know what it's used for and we can see if
* we need to expose hooks for that functionality more formally.
*/
objs: null,
/**
* Execute the supplied method before the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:
*
* Y.Do.Halt(message, returnValue)
* Immediatly stop execution and return
* returnValue
. No other wrapping functions will be
* executed.
* Y.Do.AlterArgs(message, newArgArray)
* Replace the arguments that the original function will be
* called with.
* Y.Do.Prevent(message)
* Don't execute the wrapped function. Other before phase
* wrappers will be executed.
*
*
* @method before
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {string} handle for the subscription
* @static
*/
before: function(fn, obj, sFn, c) {
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_BEFORE, f, obj, sFn);
},
/**
* Execute the supplied method after the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:
*
* Y.Do.Halt(message, returnValue)
* Immediatly stop execution and return
* returnValue
. No other wrapping functions will be
* executed.
* Y.Do.AlterReturn(message, returnValue)
* Return returnValue
instead of the wrapped
* method's original return value. This can be further altered by
* other after phase wrappers.
*
*
* The static properties Y.Do.originalRetVal
and
* Y.Do.currentRetVal
will be populated for reference.
*
* @method after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return {string} handle for the subscription
* @static
*/
after: function(fn, obj, sFn, c) {
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_AFTER, f, obj, sFn);
},
/**
* Execute the supplied method before or after the specified function.
* Used by before
and after
.
*
* @method _inject
* @param when {string} before or after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @return {string} handle for the subscription
* @private
* @static
*/
_inject: function(when, fn, obj, sFn) {
// object id
var id = Y.stamp(obj), o, sid;
if (!obj._yuiaop) {
// create a map entry for the obj if it doesn't exist, to hold overridden methods
obj._yuiaop = {};
}
o = obj._yuiaop;
if (!o[sFn]) {
// create a map entry for the method if it doesn't exist
o[sFn] = new Y.Do.Method(obj, sFn);
// re-route the method to our wrapper
obj[sFn] = function() {
return o[sFn].exec.apply(o[sFn], arguments);
};
}
// subscriber id
sid = id + Y.stamp(fn) + sFn;
// register the callback
o[sFn].register(sid, fn, when);
return new Y.EventHandle(o[sFn], sid);
},
/**
* Detach a before or after subscription.
*
* @method detach
* @param handle {string} the subscription handle
* @static
*/
detach: function(handle) {
if (handle.detach) {
handle.detach();
}
}
};
Y.Do = DO;
//////////////////////////////////////////////////////////////////////////
/**
* Contains the return value from the wrapped method, accessible
* by 'after' event listeners.
*
* @property originalRetVal
* @static
* @since 3.2.0
*/
/**
* Contains the current state of the return value, consumable by
* 'after' event listeners, and updated if an after subscriber
* changes the return value generated by the wrapped function.
*
* @property currentRetVal
* @static
* @since 3.2.0
*/
//////////////////////////////////////////////////////////////////////////
/**
* Wrapper for a displaced method with aop enabled
* @class Do.Method
* @constructor
* @param obj The object to operate on
* @param sFn The name of the method to displace
*/
DO.Method = function(obj, sFn) {
this.obj = obj;
this.methodName = sFn;
this.method = obj[sFn];
this.before = {};
this.after = {};
};
/**
* Register a aop subscriber
* @method register
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype.register = function (sid, fn, when) {
if (when) {
this.after[sid] = fn;
} else {
this.before[sid] = fn;
}
};
/**
* Unregister a aop subscriber
* @method delete
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype._delete = function (sid) {
delete this.before[sid];
delete this.after[sid];
};
/**
* Execute the wrapped method. All arguments are passed into the wrapping
* functions. If any of the before wrappers return an instance of
* Y.Do.Halt
or Y.Do.Prevent
, neither the wrapped
* function nor any after phase subscribers will be executed.
*
* The return value will be the return value of the wrapped function or one
* provided by a wrapper function via an instance of Y.Do.Halt
or
* Y.Do.AlterReturn
.
*
* @method exec
* @param arg* {any} Arguments are passed to the wrapping and wrapped functions
* @return {any} Return value of wrapped function unless overwritten (see above)
*/
DO.Method.prototype.exec = function () {
var args = Y.Array(arguments, 0, true),
i, ret, newRet,
bf = this.before,
af = this.after,
prevented = false;
// execute before
for (i in bf) {
if (bf.hasOwnProperty(i)) {
ret = bf[i].apply(this.obj, args);
if (ret) {
switch (ret.constructor) {
case DO.Halt:
return ret.retVal;
case DO.AlterArgs:
args = ret.newArgs;
break;
case DO.Prevent:
prevented = true;
break;
default:
}
}
}
}
// execute method
if (!prevented) {
ret = this.method.apply(this.obj, args);
}
DO.originalRetVal = ret;
DO.currentRetVal = ret;
// execute after methods.
for (i in af) {
if (af.hasOwnProperty(i)) {
newRet = af[i].apply(this.obj, args);
// Stop processing if a Halt object is returned
if (newRet && newRet.constructor === DO.Halt) {
return newRet.retVal;
// Check for a new return value
} else if (newRet && newRet.constructor === DO.AlterReturn) {
ret = newRet.newRetVal;
// Update the static retval state
DO.currentRetVal = ret;
}
}
}
return ret;
};
//////////////////////////////////////////////////////////////////////////
/**
* Return an AlterArgs object when you want to change the arguments that
* were passed into the function. Useful for Do.before subscribers. An
* example would be a service that scrubs out illegal characters prior to
* executing the core business logic.
* @class Do.AlterArgs
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newArgs {Array} Call parameters to be used for the original method
* instead of the arguments originally passed in.
*/
DO.AlterArgs = function(msg, newArgs) {
this.msg = msg;
this.newArgs = newArgs;
};
/**
* Return an AlterReturn object when you want to change the result returned
* from the core method to the caller. Useful for Do.after subscribers.
* @class Do.AlterReturn
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newRetVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.AlterReturn = function(msg, newRetVal) {
this.msg = msg;
this.newRetVal = newRetVal;
};
/**
* Return a Halt object when you want to terminate the execution
* of all subsequent subscribers as well as the wrapped method
* if it has not exectued yet. Useful for Do.before subscribers.
* @class Do.Halt
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.Halt = function(msg, retVal) {
this.msg = msg;
this.retVal = retVal;
};
/**
* Return a Prevent object when you want to prevent the wrapped function
* from executing, but want the remaining listeners to execute. Useful
* for Do.before subscribers.
* @class Do.Prevent
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
*/
DO.Prevent = function(msg) {
this.msg = msg;
};
/**
* Return an Error object when you want to terminate the execution
* of all subsequent method calls.
* @class Do.Error
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
* @deprecated use Y.Do.Halt or Y.Do.Prevent
*/
DO.Error = DO.Halt;
//////////////////////////////////////////////////////////////////////////
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
// var onsubscribeType = "_event:onsub",
var YArray = Y.Array,
AFTER = 'after',
CONFIGS = [
'broadcast',
'monitored',
'bubbles',
'context',
'contextFn',
'currentTarget',
'defaultFn',
'defaultTargetOnly',
'details',
'emitFacade',
'fireOnce',
'async',
'host',
'preventable',
'preventedFn',
'queuable',
'silent',
'stoppedFn',
'target',
'type'
],
CONFIGS_HASH = YArray.hash(CONFIGS),
nativeSlice = Array.prototype.slice,
YUI3_SIGNATURE = 9,
YUI_LOG = 'yui:log',
mixConfigs = function(r, s, ov) {
var p;
for (p in s) {
if (CONFIGS_HASH[p] && (ov || !(p in r))) {
r[p] = s[p];
}
}
return r;
};
/**
* The CustomEvent class lets you define events for your application
* that can be subscribed to by one or more independent component.
*
* @param {String} type The type of event, which is passed to the callback
* when the event fires.
* @param {object} defaults configuration object.
* @class CustomEvent
* @constructor
*/
/**
* The type of event, returned to subscribers when the event fires
* @property type
* @type string
*/
/**
* By default all custom events are logged in the debug build, set silent
* to true to disable debug outpu for this event.
* @property silent
* @type boolean
*/
Y.CustomEvent = function(type, defaults) {
this._kds = Y.CustomEvent.keepDeprecatedSubs;
this.id = Y.guid();
this.type = type;
this.silent = this.logSystem = (type === YUI_LOG);
if (this._kds) {
/**
* The subscribers to this event
* @property subscribers
* @type Subscriber {}
* @deprecated
*/
/**
* 'After' subscribers
* @property afters
* @type Subscriber {}
* @deprecated
*/
this.subscribers = {};
this.afters = {};
}
if (defaults) {
mixConfigs(this, defaults, true);
}
};
/**
* Static flag to enable population of the `subscribers`
* and `afters` properties held on a `CustomEvent` instance.
*
* These properties were changed to private properties (`_subscribers` and `_afters`), and
* converted from objects to arrays for performance reasons.
*
* Setting this property to true will populate the deprecated `subscribers` and `afters`
* properties for people who may be using them (which is expected to be rare). There will
* be a performance hit, compared to the new array based implementation.
*
* If you are using these deprecated properties for a use case which the public API
* does not support, please file an enhancement request, and we can provide an alternate
* public implementation which doesn't have the performance cost required to maintiain the
* properties as objects.
*
* @property keepDeprecatedSubs
* @static
* @for CustomEvent
* @type boolean
* @default false
* @deprecated
*/
Y.CustomEvent.keepDeprecatedSubs = false;
Y.CustomEvent.mixConfigs = mixConfigs;
Y.CustomEvent.prototype = {
constructor: Y.CustomEvent,
/**
* Monitor when an event is attached or detached.
*
* @property monitored
* @type boolean
*/
/**
* If 0, this event does not broadcast. If 1, the YUI instance is notified
* every time this event fires. If 2, the YUI instance and the YUI global
* (if event is enabled on the global) are notified every time this event
* fires.
* @property broadcast
* @type int
*/
/**
* Specifies whether this event should be queued when the host is actively
* processing an event. This will effect exectution order of the callbacks
* for the various events.
* @property queuable
* @type boolean
* @default false
*/
/**
* This event has fired if true
*
* @property fired
* @type boolean
* @default false;
*/
/**
* An array containing the arguments the custom event
* was last fired with.
* @property firedWith
* @type Array
*/
/**
* This event should only fire one time if true, and if
* it has fired, any new subscribers should be notified
* immediately.
*
* @property fireOnce
* @type boolean
* @default false;
*/
/**
* fireOnce listeners will fire syncronously unless async
* is set to true
* @property async
* @type boolean
* @default false
*/
/**
* Flag for stopPropagation that is modified during fire()
* 1 means to stop propagation to bubble targets. 2 means
* to also stop additional subscribers on this target.
* @property stopped
* @type int
*/
/**
* Flag for preventDefault that is modified during fire().
* if it is not 0, the default behavior for this event
* @property prevented
* @type int
*/
/**
* Specifies the host for this custom event. This is used
* to enable event bubbling
* @property host
* @type EventTarget
*/
/**
* The default function to execute after event listeners
* have fire, but only if the default action was not
* prevented.
* @property defaultFn
* @type Function
*/
/**
* The function to execute if a subscriber calls
* stopPropagation or stopImmediatePropagation
* @property stoppedFn
* @type Function
*/
/**
* The function to execute if a subscriber calls
* preventDefault
* @property preventedFn
* @type Function
*/
/**
* The subscribers to this event
* @property _subscribers
* @type Subscriber []
* @private
*/
/**
* 'After' subscribers
* @property _afters
* @type Subscriber []
* @private
*/
/**
* If set to true, the custom event will deliver an EventFacade object
* that is similar to a DOM event object.
* @property emitFacade
* @type boolean
* @default false
*/
/**
* Supports multiple options for listener signatures in order to
* port YUI 2 apps.
* @property signature
* @type int
* @default 9
*/
signature : YUI3_SIGNATURE,
/**
* The context the the event will fire from by default. Defaults to the YUI
* instance.
* @property context
* @type object
*/
context : Y,
/**
* Specifies whether or not this event's default function
* can be cancelled by a subscriber by executing preventDefault()
* on the event facade
* @property preventable
* @type boolean
* @default true
*/
preventable : true,
/**
* Specifies whether or not a subscriber can stop the event propagation
* via stopPropagation(), stopImmediatePropagation(), or halt()
*
* Events can only bubble if emitFacade is true.
*
* @property bubbles
* @type boolean
* @default true
*/
bubbles : true,
/**
* Returns the number of subscribers for this event as the sum of the on()
* subscribers and after() subscribers.
*
* @method hasSubs
* @return Number
*/
hasSubs: function(when) {
var s = 0,
a = 0,
subs = this._subscribers,
afters = this._afters,
sib = this.sibling;
if (subs) {
s = subs.length;
}
if (afters) {
a = afters.length;
}
if (sib) {
subs = sib._subscribers;
afters = sib._afters;
if (subs) {
s += subs.length;
}
if (afters) {
a += afters.length;
}
}
if (when) {
return (when === 'after') ? a : s;
}
return (s + a);
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('detach', 'attach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
this.monitored = true;
var type = this.id + '|' + this.type + '_' + what,
args = nativeSlice.call(arguments, 0);
args[0] = type;
return this.host.on.apply(this.host, args);
},
/**
* Get all of the subscribers to this event and any sibling event
* @method getSubs
* @return {Array} first item is the on subscribers, second the after.
*/
getSubs: function() {
var sibling = this.sibling,
subs = this._subscribers,
afters = this._afters,
siblingSubs,
siblingAfters;
if (sibling) {
siblingSubs = sibling._subscribers;
siblingAfters = sibling._afters;
}
if (siblingSubs) {
if (subs) {
subs = subs.concat(siblingSubs);
} else {
subs = siblingSubs.concat();
}
} else {
if (subs) {
subs = subs.concat();
} else {
subs = [];
}
}
if (siblingAfters) {
if (afters) {
afters = afters.concat(siblingAfters);
} else {
afters = siblingAfters.concat();
}
} else {
if (afters) {
afters = afters.concat();
} else {
afters = [];
}
}
return [subs, afters];
},
/**
* Apply configuration properties. Only applies the CONFIG whitelist
* @method applyConfig
* @param o hash of properties to apply.
* @param force {boolean} if true, properties that exist on the event
* will be overwritten.
*/
applyConfig: function(o, force) {
mixConfigs(this, o, force);
},
/**
* Create the Subscription for subscribing function, context, and bound
* arguments. If this is a fireOnce event, the subscriber is immediately
* notified.
*
* @method _on
* @param fn {Function} Subscription callback
* @param [context] {Object} Override `this` in the callback
* @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()
* @param [when] {String} "after" to slot into after subscribers
* @return {EventHandle}
* @protected
*/
_on: function(fn, context, args, when) {
var s = new Y.Subscriber(fn, context, args, when),
firedWith;
if (this.fireOnce && this.fired) {
firedWith = this.firedWith;
// It's a little ugly for this to know about facades,
// but given the current breakup, not much choice without
// moving a whole lot of stuff around.
if (this.emitFacade && this._addFacadeToArgs) {
this._addFacadeToArgs(firedWith);
}
if (this.async) {
setTimeout(Y.bind(this._notify, this, s, firedWith), 0);
} else {
this._notify(s, firedWith);
}
}
if (when === AFTER) {
if (!this._afters) {
this._afters = [];
}
this._afters.push(s);
} else {
if (!this._subscribers) {
this._subscribers = [];
}
this._subscribers.push(s);
}
if (this._kds) {
if (when === AFTER) {
this.afters[s.id] = s;
} else {
this.subscribers[s.id] = s;
}
}
return new Y.EventHandle(this, s);
},
/**
* Listen for this event
* @method subscribe
* @param {Function} fn The function to execute.
* @return {EventHandle} Unsubscribe handle.
* @deprecated use on.
*/
subscribe: function(fn, context) {
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
return this._on(fn, context, a, true);
},
/**
* Listen for this event
* @method on
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} An object with a detach method to detch the handler(s).
*/
on: function(fn, context) {
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
if (this.monitored && this.host) {
this.host._monitor('attach', this, {
args: arguments
});
}
return this._on(fn, context, a, true);
},
/**
* Listen for this event after the normal subscribers have been notified and
* the default behavior has been applied. If a normal subscriber prevents the
* default behavior, it also prevents after listeners from firing.
* @method after
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} handle Unsubscribe handle.
*/
after: function(fn, context) {
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
return this._on(fn, context, a, AFTER);
},
/**
* Detach listeners.
* @method detach
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {int} returns the number of subscribers unsubscribed.
*/
detach: function(fn, context) {
// unsubscribe handle
if (fn && fn.detach) {
return fn.detach();
}
var i, s,
found = 0,
subs = this._subscribers,
afters = this._afters;
if (subs) {
for (i = subs.length; i >= 0; i--) {
s = subs[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s, subs, i);
found++;
}
}
}
if (afters) {
for (i = afters.length; i >= 0; i--) {
s = afters[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s, afters, i);
found++;
}
}
}
return found;
},
/**
* Detach listeners.
* @method unsubscribe
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {int|undefined} returns the number of subscribers unsubscribed.
* @deprecated use detach.
*/
unsubscribe: function() {
return this.detach.apply(this, arguments);
},
/**
* Notify a single subscriber
* @method _notify
* @param {Subscriber} s the subscriber.
* @param {Array} args the arguments array to apply to the listener.
* @protected
*/
_notify: function(s, args, ef) {
var ret;
ret = s.notify(args, this);
if (false === ret || this.stopped > 1) {
return false;
}
return true;
},
/**
* Logger abstraction to centralize the application of the silent flag
* @method log
* @param {string} msg message to log.
* @param {string} cat log category.
*/
log: function(msg, cat) {
},
/**
* Notifies the subscribers. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters:
*
* The type of event
* All of the arguments fire() was executed with as an array
* The custom object (if any) that was passed into the subscribe()
* method
*
* @method fire
* @param {Object*} arguments an arbitrary set of parameters to pass to
* the handler.
* @return {boolean} false if one of the subscribers returned false,
* true otherwise.
*
*/
fire: function() {
// push is the fastest way to go from arguments to arrays
// for most browsers currently
// http://jsperf.com/push-vs-concat-vs-slice/2
var args = [];
args.push.apply(args, arguments);
return this._fire(args);
},
/**
* Private internal implementation for `fire`, which is can be used directly by
* `EventTarget` and other event module classes which have already converted from
* an `arguments` list to an array, to avoid the repeated overhead.
*
* @method _fire
* @private
* @param {Array} args The array of arguments passed to be passed to handlers.
* @return {boolean} false if one of the subscribers returned false, true otherwise.
*/
_fire: function(args) {
if (this.fireOnce && this.fired) {
return true;
} else {
// this doesn't happen if the event isn't published
// this.host._monitor('fire', this.type, args);
this.fired = true;
if (this.fireOnce) {
this.firedWith = args;
}
if (this.emitFacade) {
return this.fireComplex(args);
} else {
return this.fireSimple(args);
}
}
},
/**
* Set up for notifying subscribers of non-emitFacade events.
*
* @method fireSimple
* @param args {Array} Arguments passed to fire()
* @return Boolean false if a subscriber returned false
* @protected
*/
fireSimple: function(args) {
this.stopped = 0;
this.prevented = 0;
if (this.hasSubs()) {
var subs = this.getSubs();
this._procSubs(subs[0], args);
this._procSubs(subs[1], args);
}
if (this.broadcast) {
this._broadcast(args);
}
return this.stopped ? false : true;
},
// Requires the event-custom-complex module for full funcitonality.
fireComplex: function(args) {
args[0] = args[0] || {};
return this.fireSimple(args);
},
/**
* Notifies a list of subscribers.
*
* @method _procSubs
* @param subs {Array} List of subscribers
* @param args {Array} Arguments passed to fire()
* @param ef {}
* @return Boolean false if a subscriber returns false or stops the event
* propagation via e.stopPropagation(),
* e.stopImmediatePropagation(), or e.halt()
* @private
*/
_procSubs: function(subs, args, ef) {
var s, i, l;
for (i = 0, l = subs.length; i < l; i++) {
s = subs[i];
if (s && s.fn) {
if (false === this._notify(s, args, ef)) {
this.stopped = 2;
}
if (this.stopped === 2) {
return false;
}
}
}
return true;
},
/**
* Notifies the YUI instance if the event is configured with broadcast = 1,
* and both the YUI instance and Y.Global if configured with broadcast = 2.
*
* @method _broadcast
* @param args {Array} Arguments sent to fire()
* @private
*/
_broadcast: function(args) {
if (!this.stopped && this.broadcast) {
var a = args.concat();
a.unshift(this.type);
if (this.host !== Y) {
Y.fire.apply(Y, a);
}
if (this.broadcast === 2) {
Y.Global.fire.apply(Y.Global, a);
}
}
},
/**
* Removes all listeners
* @method unsubscribeAll
* @return {int} The number of listeners unsubscribed.
* @deprecated use detachAll.
*/
unsubscribeAll: function() {
return this.detachAll.apply(this, arguments);
},
/**
* Removes all listeners
* @method detachAll
* @return {int} The number of listeners unsubscribed.
*/
detachAll: function() {
return this.detach();
},
/**
* Deletes the subscriber from the internal store of on() and after()
* subscribers.
*
* @method _delete
* @param s subscriber object.
* @param subs (optional) on or after subscriber array
* @param index (optional) The index found.
* @private
*/
_delete: function(s, subs, i) {
var when = s._when;
if (!subs) {
subs = (when === AFTER) ? this._afters : this._subscribers;
}
if (subs) {
i = YArray.indexOf(subs, s, 0);
if (s && subs[i] === s) {
subs.splice(i, 1);
}
}
if (this._kds) {
if (when === AFTER) {
delete this.afters[s.id];
} else {
delete this.subscribers[s.id];
}
}
if (this.monitored && this.host) {
this.host._monitor('detach', this, {
ce: this,
sub: s
});
}
if (s) {
s.deleted = true;
}
}
};
/**
* Stores the subscriber information to be used when the event fires.
* @param {Function} fn The wrapped function to execute.
* @param {Object} context The value of the keyword 'this' in the listener.
* @param {Array} args* 0..n additional arguments to supply the listener.
*
* @class Subscriber
* @constructor
*/
Y.Subscriber = function(fn, context, args, when) {
/**
* The callback that will be execute when the event fires
* This is wrapped by Y.rbind if obj was supplied.
* @property fn
* @type Function
*/
this.fn = fn;
/**
* Optional 'this' keyword for the listener
* @property context
* @type Object
*/
this.context = context;
/**
* Unique subscriber id
* @property id
* @type String
*/
this.id = Y.guid();
/**
* Additional arguments to propagate to the subscriber
* @property args
* @type Array
*/
this.args = args;
this._when = when;
/**
* Custom events for a given fire transaction.
* @property events
* @type {EventTarget}
*/
// this.events = null;
/**
* This listener only reacts to the event once
* @property once
*/
// this.once = false;
};
Y.Subscriber.prototype = {
constructor: Y.Subscriber,
_notify: function(c, args, ce) {
if (this.deleted && !this.postponed) {
if (this.postponed) {
delete this.fn;
delete this.context;
} else {
delete this.postponed;
return null;
}
}
var a = this.args, ret;
switch (ce.signature) {
case 0:
ret = this.fn.call(c, ce.type, args, c);
break;
case 1:
ret = this.fn.call(c, args[0] || null, c);
break;
default:
if (a || args) {
args = args || [];
a = (a) ? args.concat(a) : args;
ret = this.fn.apply(c, a);
} else {
ret = this.fn.call(c);
}
}
if (this.once) {
ce._delete(this);
}
return ret;
},
/**
* Executes the subscriber.
* @method notify
* @param args {Array} Arguments array for the subscriber.
* @param ce {CustomEvent} The custom event that sent the notification.
*/
notify: function(args, ce) {
var c = this.context,
ret = true;
if (!c) {
c = (ce.contextFn) ? ce.contextFn() : ce.context;
}
// only catch errors if we will not re-throw them.
if (Y.config && Y.config.throwFail) {
ret = this._notify(c, args, ce);
} else {
try {
ret = this._notify(c, args, ce);
} catch (e) {
Y.error(this + ' failed: ' + e.message, e);
}
}
return ret;
},
/**
* Returns true if the fn and obj match this objects properties.
* Used by the unsubscribe method to match the right subscriber.
*
* @method contains
* @param {Function} fn the function to execute.
* @param {Object} context optional 'this' keyword for the listener.
* @return {boolean} true if the supplied arguments match this
* subscriber's signature.
*/
contains: function(fn, context) {
if (context) {
return ((this.fn === fn) && this.context === context);
} else {
return (this.fn === fn);
}
},
valueOf : function() {
return this.id;
}
};
/**
* Return value from all subscribe operations
* @class EventHandle
* @constructor
* @param {CustomEvent} evt the custom event.
* @param {Subscriber} sub the subscriber.
*/
Y.EventHandle = function(evt, sub) {
/**
* The custom event
*
* @property evt
* @type CustomEvent
*/
this.evt = evt;
/**
* The subscriber object
*
* @property sub
* @type Subscriber
*/
this.sub = sub;
};
Y.EventHandle.prototype = {
batch: function(f, c) {
f.call(c || this, this);
if (Y.Lang.isArray(this.evt)) {
Y.Array.each(this.evt, function(h) {
h.batch.call(c || h, f);
});
}
},
/**
* Detaches this subscriber
* @method detach
* @return {int} the number of detached listeners
*/
detach: function() {
var evt = this.evt, detached = 0, i;
if (evt) {
if (Y.Lang.isArray(evt)) {
for (i = 0; i < evt.length; i++) {
detached += evt[i].detach();
}
} else {
evt._delete(this.sub);
detached = 1;
}
}
return detached;
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('attach', 'detach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
return this.evt.monitor.apply(this.evt, arguments);
}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* EventTarget provides the implementation for any object to
* publish, subscribe and fire to custom events, and also
* alows other EventTargets to target the object with events
* sourced from the other object.
* EventTarget is designed to be used with Y.augment to wrap
* EventCustom in an interface that allows events to be listened to
* and fired by name. This makes it possible for implementing code to
* subscribe to an event that either has not been created yet, or will
* not be created at all.
* @class EventTarget
* @param opts a configuration object
* @config emitFacade {boolean} if true, all events will emit event
* facade payloads by default (default false)
* @config prefix {String} the prefix to apply to non-prefixed event names
*/
var L = Y.Lang,
PREFIX_DELIMITER = ':',
CATEGORY_DELIMITER = '|',
AFTER_PREFIX = '~AFTER~',
WILD_TYPE_RE = /(.*?)(:)(.*?)/,
_wildType = Y.cached(function(type) {
return type.replace(WILD_TYPE_RE, "*$2$3");
}),
/**
* If the instance has a prefix attribute and the
* event type is not prefixed, the instance prefix is
* applied to the supplied type.
* @method _getType
* @private
*/
_getType = function(type, pre) {
if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) {
return type;
}
return pre + PREFIX_DELIMITER + type;
},
/**
* Returns an array with the detach key (if provided),
* and the prefixed event name from _getType
* Y.on('detachcategory| menu:click', fn)
* @method _parseType
* @private
*/
_parseType = Y.cached(function(type, pre) {
var t = type, detachcategory, after, i;
if (!L.isString(t)) {
return t;
}
i = t.indexOf(AFTER_PREFIX);
if (i > -1) {
after = true;
t = t.substr(AFTER_PREFIX.length);
}
i = t.indexOf(CATEGORY_DELIMITER);
if (i > -1) {
detachcategory = t.substr(0, (i));
t = t.substr(i+1);
if (t === '*') {
t = null;
}
}
// detach category, full type with instance prefix, is this an after listener, short type
return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];
}),
ET = function(opts) {
var etState = this._yuievt,
etConfig;
if (!etState) {
etState = this._yuievt = {
events: {}, // PERF: Not much point instantiating lazily. We're bound to have events
targets: null, // PERF: Instantiate lazily, if user actually adds target,
config: {
host: this,
context: this
},
chain: Y.config.chain
};
}
etConfig = etState.config;
if (opts) {
mixConfigs(etConfig, opts, true);
if (opts.chain !== undefined) {
etState.chain = opts.chain;
}
if (opts.prefix) {
etConfig.prefix = opts.prefix;
}
}
};
ET.prototype = {
constructor: ET,
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to on
except the
* listener is immediatelly detached when it is executed.
* @method once
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
once: function() {
var handle = this.on.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to after
except the
* listener is immediatelly detached when it is executed.
* @method onceAfter
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
onceAfter: function() {
var handle = this.after.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Takes the type parameter passed to 'on' and parses out the
* various pieces that could be included in the type. If the
* event type is passed without a prefix, it will be expanded
* to include the prefix one is supplied or the event target
* is configured with a default prefix.
* @method parseType
* @param {String} type the type
* @param {String} [pre=this._yuievt.config.prefix] the prefix
* @since 3.3.0
* @return {Array} an array containing:
* * the detach category, if supplied,
* * the prefixed event type,
* * whether or not this is an after listener,
* * the supplied event type
*/
parseType: function(type, pre) {
return _parseType(type, pre || this._yuievt.config.prefix);
},
/**
* Subscribe a callback function to a custom event fired by this object or
* from an object that bubbles its events to this object.
*
* Callback functions for events published with `emitFacade = true` will
* receive an `EventFacade` as the first argument (typically named "e").
* These callbacks can then call `e.preventDefault()` to disable the
* behavior published to that event's `defaultFn`. See the `EventFacade`
* API for all available properties and methods. Subscribers to
* non-`emitFacade` events will receive the arguments passed to `fire()`
* after the event name.
*
* To subscribe to multiple events at once, pass an object as the first
* argument, where the key:value pairs correspond to the eventName:callback,
* or pass an array of event names as the first argument to subscribe to
* all listed events with the same callback.
*
* Returning `false` from a callback is supported as an alternative to
* calling `e.preventDefault(); e.stopPropagation();`. However, it is
* recommended to use the event methods whenever possible.
*
* @method on
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
on: function(type, fn, context) {
var yuievt = this._yuievt,
parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce,
detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,
Node = Y.Node, n, domevent, isArr;
// full name, args, detachcategory, after
this._monitor('attach', parts[1], {
args: arguments,
category: parts[0],
after: parts[2]
});
if (L.isObject(type)) {
if (L.isFunction(type)) {
return Y.Do.before.apply(Y.Do, arguments);
}
f = fn;
c = context;
args = nativeSlice.call(arguments, 0);
ret = [];
if (L.isArray(type)) {
isArr = true;
}
after = type._after;
delete type._after;
Y.each(type, function(v, k) {
if (L.isObject(v)) {
f = v.fn || ((L.isFunction(v)) ? v : f);
c = v.context || c;
}
var nv = (after) ? AFTER_PREFIX : '';
args[0] = nv + ((isArr) ? v : k);
args[1] = f;
args[2] = c;
ret.push(this.on.apply(this, args));
}, this);
return (yuievt.chain) ? this : new Y.EventHandle(ret);
}
detachcategory = parts[0];
after = parts[2];
shorttype = parts[3];
// extra redirection so we catch adaptor events too. take a look at this.
if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {
args = nativeSlice.call(arguments, 0);
args.splice(2, 0, Node.getDOMNode(this));
return Y.on.apply(Y, args);
}
type = parts[1];
if (Y.instanceOf(this, YUI)) {
adapt = Y.Env.evt.plugins[type];
args = nativeSlice.call(arguments, 0);
args[0] = shorttype;
if (Node) {
n = args[2];
if (Y.instanceOf(n, Y.NodeList)) {
n = Y.NodeList.getDOMNodes(n);
} else if (Y.instanceOf(n, Node)) {
n = Node.getDOMNode(n);
}
domevent = (shorttype in Node.DOM_EVENTS);
// Captures both DOM events and event plugins.
if (domevent) {
args[2] = n;
}
}
// check for the existance of an event adaptor
if (adapt) {
handle = adapt.on.apply(Y, args);
} else if ((!type) || domevent) {
handle = Y.Event._attach(args);
}
}
if (!handle) {
ce = yuievt.events[type] || this.publish(type);
handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true);
// TODO: More robust regex, accounting for category
if (type.indexOf("*:") !== -1) {
this._hasSiblings = true;
}
}
if (detachcategory) {
store[detachcategory] = store[detachcategory] || {};
store[detachcategory][type] = store[detachcategory][type] || [];
store[detachcategory][type].push(handle);
}
return (yuievt.chain) ? this : handle;
},
/**
* subscribe to an event
* @method subscribe
* @deprecated use on
*/
subscribe: function() {
return this.on.apply(this, arguments);
},
/**
* Detach one or more listeners the from the specified event
* @method detach
* @param type {string|Object} Either the handle to the subscriber or the
* type of event. If the type
* is not specified, it will attempt to remove
* the listener from all hosted events.
* @param fn {Function} The subscribed function to unsubscribe, if not
* supplied, all subscribers will be removed.
* @param context {Object} The custom object passed to subscribe. This is
* optional, but if supplied will be used to
* disambiguate multiple listeners that are the same
* (e.g., you subscribe many object using a function
* that lives on the prototype)
* @return {EventTarget} the host
*/
detach: function(type, fn, context) {
var evts = this._yuievt.events,
i,
Node = Y.Node,
isNode = Node && (Y.instanceOf(this, Node));
// detachAll disabled on the Y instance.
if (!type && (this !== Y)) {
for (i in evts) {
if (evts.hasOwnProperty(i)) {
evts[i].detach(fn, context);
}
}
if (isNode) {
Y.Event.purgeElement(Node.getDOMNode(this));
}
return this;
}
var parts = _parseType(type, this._yuievt.config.prefix),
detachcategory = L.isArray(parts) ? parts[0] : null,
shorttype = (parts) ? parts[3] : null,
adapt, store = Y.Env.evt.handles, detachhost, cat, args,
ce,
keyDetacher = function(lcat, ltype, host) {
var handles = lcat[ltype], ce, i;
if (handles) {
for (i = handles.length - 1; i >= 0; --i) {
ce = handles[i].evt;
if (ce.host === host || ce.el === host) {
handles[i].detach();
}
}
}
};
if (detachcategory) {
cat = store[detachcategory];
type = parts[1];
detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;
if (cat) {
if (type) {
keyDetacher(cat, type, detachhost);
} else {
for (i in cat) {
if (cat.hasOwnProperty(i)) {
keyDetacher(cat, i, detachhost);
}
}
}
return this;
}
// If this is an event handle, use it to detach
} else if (L.isObject(type) && type.detach) {
type.detach();
return this;
// extra redirection so we catch adaptor events too. take a look at this.
} else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {
args = nativeSlice.call(arguments, 0);
args[2] = Node.getDOMNode(this);
Y.detach.apply(Y, args);
return this;
}
adapt = Y.Env.evt.plugins[shorttype];
// The YUI instance handles DOM events and adaptors
if (Y.instanceOf(this, YUI)) {
args = nativeSlice.call(arguments, 0);
// use the adaptor specific detach code if
if (adapt && adapt.detach) {
adapt.detach.apply(Y, args);
return this;
// DOM event fork
} else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {
args[0] = type;
Y.Event.detach.apply(Y.Event, args);
return this;
}
}
// ce = evts[type];
ce = evts[parts[1]];
if (ce) {
ce.detach(fn, context);
}
return this;
},
/**
* detach a listener
* @method unsubscribe
* @deprecated use detach
*/
unsubscribe: function() {
return this.detach.apply(this, arguments);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method detachAll
* @param type {String} The type, or name of the event
*/
detachAll: function(type) {
return this.detach(type);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method unsubscribeAll
* @param type {String} The type, or name of the event
* @deprecated use detachAll
*/
unsubscribeAll: function() {
return this.detachAll.apply(this, arguments);
},
/**
* Creates a new custom event of the specified type. If a custom event
* by that name already exists, it will not be re-created. In either
* case the custom event is returned.
*
* @method publish
*
* @param type {String} the type, or name of the event
* @param opts {object} optional config params. Valid properties are:
*
*
*
* 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)
*
*
* 'bubbles': whether or not this event bubbles (true)
* Events can only bubble if emitFacade is true.
*
*
* 'context': the default execution context for the listeners (this)
*
*
* 'defaultFn': the default function to execute when this event fires if preventDefault was not called
*
*
* 'emitFacade': whether or not this event emits a facade (false)
*
*
* 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'
*
*
* 'fireOnce': if an event is configured to fire once, new subscribers after
* the fire will be notified immediately.
*
*
* 'async': fireOnce event listeners will fire synchronously if the event has already
* fired unless async is true.
*
*
* 'preventable': whether or not preventDefault() has an effect (true)
*
*
* 'preventedFn': a function that is executed when preventDefault is called
*
*
* 'queuable': whether or not this event can be queued during bubbling (false)
*
*
* 'silent': if silent is true, debug messages are not provided for this event.
*
*
* 'stoppedFn': a function that is executed when stopPropagation is called
*
*
*
* 'monitored': specifies whether or not this event should send notifications about
* when the event has been attached, detached, or published.
*
*
* 'type': the event type (valid option if not provided as the first parameter to publish)
*
*
*
* @return {CustomEvent} the custom event
*
*/
publish: function(type, opts) {
var ret,
etState = this._yuievt,
etConfig = etState.config,
pre = etConfig.prefix;
if (typeof type === "string") {
if (pre) {
type = _getType(type, pre);
}
ret = this._publish(type, etConfig, opts);
} else {
ret = {};
Y.each(type, function(v, k) {
if (pre) {
k = _getType(k, pre);
}
ret[k] = this._publish(k, etConfig, v || opts);
}, this);
}
return ret;
},
/**
* Returns the fully qualified type, given a short type string.
* That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix.
*
* NOTE: This method, unlike _getType, does no checking of the value passed in, and
* is designed to be used with the low level _publish() method, for critical path
* implementations which need to fast-track publish for performance reasons.
*
* @method _getFullType
* @private
* @param {String} type The short type to prefix
* @return {String} The prefixed type, if a prefix is set, otherwise the type passed in
*/
_getFullType : function(type) {
var pre = this._yuievt.config.prefix;
if (pre) {
return pre + PREFIX_DELIMITER + type;
} else {
return type;
}
},
/**
* The low level event publish implementation. It expects all the massaging to have been done
* outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast
* path publish, which can be used by critical code paths to improve performance.
*
* @method _publish
* @private
* @param {String} fullType The prefixed type of the event to publish.
* @param {Object} etOpts The EventTarget specific configuration to mix into the published event.
* @param {Object} ceOpts The publish specific configuration to mix into the published event.
* @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will
* be the default `CustomEvent` instance, and can be configured independently.
*/
_publish : function(fullType, etOpts, ceOpts) {
var ce,
etState = this._yuievt,
etConfig = etState.config,
host = etConfig.host,
context = etConfig.context,
events = etState.events;
ce = events[fullType];
// PERF: Hate to pull the check out of monitor, but trying to keep critical path tight.
if ((etConfig.monitored && !ce) || (ce && ce.monitored)) {
this._monitor('publish', fullType, {
args: arguments
});
}
if (!ce) {
// Publish event
ce = events[fullType] = new Y.CustomEvent(fullType, etOpts);
if (!etOpts) {
ce.host = host;
ce.context = context;
}
}
if (ceOpts) {
mixConfigs(ce, ceOpts, true);
}
return ce;
},
/**
* This is the entry point for the event monitoring system.
* You can monitor 'attach', 'detach', 'fire', and 'publish'.
* When configured, these events generate an event. click ->
* click_attach, click_detach, click_publish -- these can
* be subscribed to like other events to monitor the event
* system. Inividual published events can have monitoring
* turned on or off (publish can't be turned off before it
* it published) by setting the events 'monitor' config.
*
* @method _monitor
* @param what {String} 'attach', 'detach', 'fire', or 'publish'
* @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object.
* @param o {Object} Information about the event interaction, such as
* fire() args, subscription category, publish config
* @private
*/
_monitor: function(what, eventType, o) {
var monitorevt, ce, type;
if (eventType) {
if (typeof eventType === "string") {
type = eventType;
ce = this.getEvent(eventType, true);
} else {
ce = eventType;
type = eventType.type;
}
if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
monitorevt = type + '_' + what;
o.monitored = what;
this.fire.call(this, monitorevt, o);
}
}
},
/**
* Fire a custom event by name. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters.
*
* The first argument is the event type, and any additional arguments are
* passed to the listeners as parameters. If the first of these is an
* object literal, and the event is configured to emit an event facade,
* that object is mixed into the event facade and the facade is provided
* in place of the original object.
*
* If the custom event object hasn't been created, then the event hasn't
* been published and it has no subscribers. For performance sake, we
* immediate exit in this case. This means the event won't bubble, so
* if the intention is that a bubble target be notified, the event must
* be published on this object first.
*
* @method fire
* @param type {String|Object} The type of the event, or an object that contains
* a 'type' property.
* @param arguments {Object*} an arbitrary set of parameters to pass to
* the handler. If the first of these is an object literal and the event is
* configured to emit an event facade, the event facade will replace that
* parameter after the properties the object literal contains are copied to
* the event facade.
* @return {Boolean} True if the whole lifecycle of the event went through,
* false if at any point the event propagation was halted.
*/
fire: function(type) {
var typeIncluded = (typeof type === "string"),
argCount = arguments.length,
t = type,
yuievt = this._yuievt,
etConfig = yuievt.config,
pre = etConfig.prefix,
ret,
ce,
ce2,
args;
if (typeIncluded && argCount <= 3) {
// PERF: Try to avoid slice/iteration for the common signatures
// Most common
if (argCount === 2) {
args = [arguments[1]]; // fire("foo", {})
} else if (argCount === 3) {
args = [arguments[1], arguments[2]]; // fire("foo", {}, opts)
} else {
args = []; // fire("foo")
}
} else {
args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0));
}
if (!typeIncluded) {
t = (type && type.type);
}
if (pre) {
t = _getType(t, pre);
}
ce = yuievt.events[t];
if (this._hasSiblings) {
ce2 = this.getSibling(t, ce);
if (ce2 && !ce) {
ce = this.publish(t);
}
}
// PERF: trying to avoid function call, since this is a critical path
if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
this._monitor('fire', (ce || t), {
args: args
});
}
// this event has not been published or subscribed to
if (!ce) {
if (yuievt.hasTargets) {
return this.bubble({ type: t }, args, this);
}
// otherwise there is nothing to be done
ret = true;
} else {
if (ce2) {
ce.sibling = ce2;
}
ret = ce._fire(args);
}
return (yuievt.chain) ? this : ret;
},
getSibling: function(type, ce) {
var ce2;
// delegate to *:type events if there are subscribers
if (type.indexOf(PREFIX_DELIMITER) > -1) {
type = _wildType(type);
ce2 = this.getEvent(type, true);
if (ce2) {
ce2.applyConfig(ce);
ce2.bubbles = false;
ce2.broadcast = 0;
}
}
return ce2;
},
/**
* Returns the custom event of the provided type has been created, a
* falsy value otherwise
* @method getEvent
* @param type {String} the type, or name of the event
* @param prefixed {String} if true, the type is prefixed already
* @return {CustomEvent} the custom event or null
*/
getEvent: function(type, prefixed) {
var pre, e;
if (!prefixed) {
pre = this._yuievt.config.prefix;
type = (pre) ? _getType(type, pre) : type;
}
e = this._yuievt.events;
return e[type] || null;
},
/**
* Subscribe to a custom event hosted by this object. The
* supplied callback will execute after any listeners add
* via the subscribe method, and after the default function,
* if configured for the event, has executed.
*
* @method after
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
after: function(type, fn) {
var a = nativeSlice.call(arguments, 0);
switch (L.type(type)) {
case 'function':
return Y.Do.after.apply(Y.Do, arguments);
case 'array':
// YArray.each(a[0], function(v) {
// v = AFTER_PREFIX + v;
// });
// break;
case 'object':
a[0]._after = true;
break;
default:
a[0] = AFTER_PREFIX + type;
}
return this.on.apply(this, a);
},
/**
* Executes the callback before a DOM event, custom event
* or method. If the first argument is a function, it
* is assumed the target is a method. For DOM and custom
* events, this is an alias for Y.on.
*
* For DOM and custom events:
* type, callback, context, 0-n arguments
*
* For methods:
* callback, object (method host), methodName, context, 0-n arguments
*
* @method before
* @return detach handle
*/
before: function() {
return this.on.apply(this, arguments);
}
};
Y.EventTarget = ET;
// make Y an event target
Y.mix(Y, ET.prototype);
ET.call(Y, { bubbles: false });
YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();
/**
* Hosts YUI page level events. This is where events bubble to
* when the broadcast config is set to 2. This property is
* only available if the custom event module is loaded.
* @property Global
* @type EventTarget
* @for YUI
*/
Y.Global = YUI.Env.globalEvents;
// @TODO implement a global namespace function on Y.Global?
/**
`Y.on()` can do many things:
Subscribe to custom events `publish`ed and `fire`d from Y
Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and
`fire`d from any object in the YUI instance sandbox
Subscribe to DOM events
Subscribe to the execution of a method on any object, effectively
treating that method as an event
For custom event subscriptions, pass the custom event name as the first argument
and callback as the second. The `this` object in the callback will be `Y` unless
an override is passed as the third argument.
Y.on('io:complete', function () {
Y.MyApp.updateStatus('Transaction complete');
});
To subscribe to DOM events, pass the name of a DOM event as the first argument
and a CSS selector string as the third argument after the callback function.
Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,
array, or simply omitted (the default is the `window` object).
Y.on('click', function (e) {
e.preventDefault();
// proceed with ajax form submission
var url = this.get('action');
...
}, '#my-form');
The `this` object in DOM event callbacks will be the `Node` targeted by the CSS
selector or other identifier.
`on()` subscribers for DOM events or custom events `publish`ed with a
`defaultFn` can prevent the default behavior with `e.preventDefault()` from the
event object passed as the first parameter to the subscription callback.
To subscribe to the execution of an object method, pass arguments corresponding to the call signature for
`Y.Do.before(...)` .
NOTE: The formal parameter list below is for events, not for function
injection. See `Y.Do.before` for that signature.
@method on
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@see Do.before
@for YUI
**/
/**
Listen for an event one time. Equivalent to `on()`, except that
the listener is immediately detached when executed.
See the `on()` method for additional subscription
options.
@see on
@method once
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Listen for an event one time. Equivalent to `once()`, except, like `after()`,
the subscription callback executes after all `on()` subscribers and the event's
`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase
subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`
subscribers will execute.
The listener is immediately detached when executed.
See the `on()` method for additional subscription
options.
@see once
@method onceAfter
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Like `on()`, this method creates a subscription to a custom event or to the
execution of a method on an object.
For events, `after()` subscribers are executed after the event's
`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.
See the `on()` method for additional subscription
options.
NOTE: The subscription signature shown is for events, not for function
injection. See `Y.Do.after`
for that signature.
@see on
@see Do.after
@method after
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [args*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
}, 'patched-v3.11.0', {"requires": ["oop"]});
YUI.add('event-custom-complex', function (Y, NAME) {
/**
* Adds event facades, preventable default behavior, and bubbling.
* events.
* @module event-custom
* @submodule event-custom-complex
*/
var FACADE,
FACADE_KEYS,
YObject = Y.Object,
key,
EMPTY = {},
CEProto = Y.CustomEvent.prototype,
ETProto = Y.EventTarget.prototype,
mixFacadeProps = function(facade, payload) {
var p;
for (p in payload) {
if (!(FACADE_KEYS.hasOwnProperty(p))) {
facade[p] = payload[p];
}
}
};
/**
* Wraps and protects a custom event for use when emitFacade is set to true.
* Requires the event-custom-complex module
* @class EventFacade
* @param e {Event} the custom event
* @param currentTarget {HTMLElement} the element the listener was attached to
*/
Y.EventFacade = function(e, currentTarget) {
if (!e) {
e = EMPTY;
}
this._event = e;
/**
* The arguments passed to fire
* @property details
* @type Array
*/
this.details = e.details;
/**
* The event type, this can be overridden by the fire() payload
* @property type
* @type string
*/
this.type = e.type;
/**
* The real event type
* @property _type
* @type string
* @private
*/
this._type = e.type;
//////////////////////////////////////////////////////
/**
* Node reference for the targeted eventtarget
* @property target
* @type Node
*/
this.target = e.target;
/**
* Node reference for the element that the listener was attached to.
* @property currentTarget
* @type Node
*/
this.currentTarget = currentTarget;
/**
* Node reference to the relatedTarget
* @property relatedTarget
* @type Node
*/
this.relatedTarget = e.relatedTarget;
};
Y.mix(Y.EventFacade.prototype, {
/**
* Stops the propagation to the next bubble target
* @method stopPropagation
*/
stopPropagation: function() {
this._event.stopPropagation();
this.stopped = 1;
},
/**
* Stops the propagation to the next bubble target and
* prevents any additional listeners from being exectued
* on the current target.
* @method stopImmediatePropagation
*/
stopImmediatePropagation: function() {
this._event.stopImmediatePropagation();
this.stopped = 2;
},
/**
* Prevents the event's default behavior
* @method preventDefault
*/
preventDefault: function() {
this._event.preventDefault();
this.prevented = 1;
},
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
halt: function(immediate) {
this._event.halt(immediate);
this.prevented = 1;
this.stopped = (immediate) ? 2 : 1;
}
});
CEProto.fireComplex = function(args) {
var es,
ef,
q,
queue,
ce,
ret = true,
events,
subs,
ons,
afters,
afterQueue,
postponed,
prevented,
preventedFn,
defaultFn,
self = this,
host = self.host || self,
next,
oldbubble,
stack = self.stack,
yuievt = host._yuievt,
hasPotentialSubscribers;
if (stack) {
// queue this event if the current item in the queue bubbles
if (self.queuable && self.type !== stack.next.type) {
if (!stack.queue) {
stack.queue = [];
}
stack.queue.push([self, args]);
return true;
}
}
hasPotentialSubscribers = self.hasSubs() || yuievt.hasTargets || self.broadcast;
self.target = self.target || host;
self.currentTarget = host;
self.details = args.concat();
if (hasPotentialSubscribers) {
es = stack || {
id: self.id, // id of the first event in the stack
next: self,
silent: self.silent,
stopped: 0,
prevented: 0,
bubbling: null,
type: self.type,
// defaultFnQueue: new Y.Queue(),
defaultTargetOnly: self.defaultTargetOnly
};
subs = self.getSubs();
ons = subs[0];
afters = subs[1];
self.stopped = (self.type !== es.type) ? 0 : es.stopped;
self.prevented = (self.type !== es.type) ? 0 : es.prevented;
if (self.stoppedFn) {
// PERF TODO: Can we replace with callback, like preventedFn. Look into history
events = new Y.EventTarget({
fireOnce: true,
context: host
});
self.events = events;
events.on('stopped', self.stoppedFn);
}
self._facade = null; // kill facade to eliminate stale properties
ef = self._createFacade(args);
if (ons) {
self._procSubs(ons, args, ef);
}
// bubble if this is hosted in an event target and propagation has not been stopped
if (self.bubbles && host.bubble && !self.stopped) {
oldbubble = es.bubbling;
es.bubbling = self.type;
if (es.type !== self.type) {
es.stopped = 0;
es.prevented = 0;
}
ret = host.bubble(self, args, null, es);
self.stopped = Math.max(self.stopped, es.stopped);
self.prevented = Math.max(self.prevented, es.prevented);
es.bubbling = oldbubble;
}
prevented = self.prevented;
if (prevented) {
preventedFn = self.preventedFn;
if (preventedFn) {
preventedFn.apply(host, args);
}
} else {
defaultFn = self.defaultFn;
if (defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) {
defaultFn.apply(host, args);
}
}
// broadcast listeners are fired as discreet events on the
// YUI instance and potentially the YUI global.
if (self.broadcast) {
self._broadcast(args);
}
if (afters && !self.prevented && self.stopped < 2) {
// Queue the after
afterQueue = es.afterQueue;
if (es.id === self.id || self.type !== yuievt.bubbling) {
self._procSubs(afters, args, ef);
if (afterQueue) {
while ((next = afterQueue.last())) {
next();
}
}
} else {
postponed = afters;
if (es.execDefaultCnt) {
postponed = Y.merge(postponed);
Y.each(postponed, function(s) {
s.postponed = true;
});
}
if (!afterQueue) {
es.afterQueue = new Y.Queue();
}
es.afterQueue.add(function() {
self._procSubs(postponed, args, ef);
});
}
}
self.target = null;
if (es.id === self.id) {
queue = es.queue;
if (queue) {
while (queue.length) {
q = queue.pop();
ce = q[0];
// set up stack to allow the next item to be processed
es.next = ce;
ce._fire(q[1]);
}
}
self.stack = null;
}
ret = !(self.stopped);
if (self.type !== yuievt.bubbling) {
es.stopped = 0;
es.prevented = 0;
self.stopped = 0;
self.prevented = 0;
}
} else {
defaultFn = self.defaultFn;
if(defaultFn) {
ef = self._createFacade(args);
if ((!self.defaultTargetOnly) || (host === ef.target)) {
defaultFn.apply(host, args);
}
}
}
// Kill the cached facade to free up memory.
// Otherwise we have the facade from the last fire, sitting around forever.
self._facade = null;
return ret;
};
/**
* @method _hasPotentialSubscribers
* @for CustomEvent
* @private
* @return {boolean} Whether the event has potential subscribers or not
*/
CEProto._hasPotentialSubscribers = function() {
return this.hasSubs() || this.host._yuievt.hasTargets || this.broadcast;
};
/**
* Internal utility method to create a new facade instance and
* insert it into the fire argument list, accounting for any payload
* merging which needs to happen.
*
* This used to be called `_getFacade`, but the name seemed inappropriate
* when it was used without a need for the return value.
*
* @method _createFacade
* @private
* @param fireArgs {Array} The arguments passed to "fire", which need to be
* shifted (and potentially merged) when the facade is added.
* @return {EventFacade} The event facade created.
*/
// TODO: Remove (private) _getFacade alias, once synthetic.js is updated.
CEProto._createFacade = CEProto._getFacade = function(fireArgs) {
var userArgs = this.details,
firstArg = userArgs && userArgs[0],
firstArgIsObj = (firstArg && (typeof firstArg === "object")),
ef = this._facade;
if (!ef) {
ef = new Y.EventFacade(this, this.currentTarget);
}
if (firstArgIsObj) {
// protect the event facade properties
mixFacadeProps(ef, firstArg);
// Allow the event type to be faked http://yuilibrary.com/projects/yui3/ticket/2528376
if (firstArg.type) {
ef.type = firstArg.type;
}
if (fireArgs) {
fireArgs[0] = ef;
}
} else {
if (fireArgs) {
fireArgs.unshift(ef);
}
}
// update the details field with the arguments
ef.details = this.details;
// use the original target when the event bubbled to this target
ef.target = this.originalTarget || this.target;
ef.currentTarget = this.currentTarget;
ef.stopped = 0;
ef.prevented = 0;
this._facade = ef;
return this._facade;
};
/**
* Utility method to manipulate the args array passed in, to add the event facade,
* if it's not already the first arg.
*
* @method _addFacadeToArgs
* @private
* @param {Array} The arguments to manipulate
*/
CEProto._addFacadeToArgs = function(args) {
var e = args[0];
// Trying not to use instanceof, just to avoid potential cross Y edge case issues.
if (!(e && e.halt && e.stopImmediatePropagation && e.stopPropagation && e._event)) {
this._createFacade(args);
}
};
/**
* Stop propagation to bubble targets
* @for CustomEvent
* @method stopPropagation
*/
CEProto.stopPropagation = function() {
this.stopped = 1;
if (this.stack) {
this.stack.stopped = 1;
}
if (this.events) {
this.events.fire('stopped', this);
}
};
/**
* Stops propagation to bubble targets, and prevents any remaining
* subscribers on the current target from executing.
* @method stopImmediatePropagation
*/
CEProto.stopImmediatePropagation = function() {
this.stopped = 2;
if (this.stack) {
this.stack.stopped = 2;
}
if (this.events) {
this.events.fire('stopped', this);
}
};
/**
* Prevents the execution of this event's defaultFn
* @method preventDefault
*/
CEProto.preventDefault = function() {
if (this.preventable) {
this.prevented = 1;
if (this.stack) {
this.stack.prevented = 1;
}
}
};
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
CEProto.halt = function(immediate) {
if (immediate) {
this.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this.preventDefault();
};
/**
* Registers another EventTarget as a bubble target. Bubble order
* is determined by the order registered. Multiple targets can
* be specified.
*
* Events can only bubble if emitFacade is true.
*
* Included in the event-custom-complex submodule.
*
* @method addTarget
* @param o {EventTarget} the target to add
* @for EventTarget
*/
ETProto.addTarget = function(o) {
var etState = this._yuievt;
if (!etState.targets) {
etState.targets = {};
}
etState.targets[Y.stamp(o)] = o;
etState.hasTargets = true;
};
/**
* Returns an array of bubble targets for this object.
* @method getTargets
* @return EventTarget[]
*/
ETProto.getTargets = function() {
var targets = this._yuievt.targets;
return targets ? YObject.values(targets) : [];
};
/**
* Removes a bubble target
* @method removeTarget
* @param o {EventTarget} the target to remove
* @for EventTarget
*/
ETProto.removeTarget = function(o) {
var targets = this._yuievt.targets;
if (targets) {
delete targets[Y.stamp(o, true)];
if (YObject.size(targets) === 0) {
this._yuievt.hasTargets = false;
}
}
};
/**
* Propagate an event. Requires the event-custom-complex module.
* @method bubble
* @param evt {CustomEvent} the custom event to propagate
* @return {boolean} the aggregated return value from Event.Custom.fire
* @for EventTarget
*/
ETProto.bubble = function(evt, args, target, es) {
var targs = this._yuievt.targets,
ret = true,
t,
ce,
i,
bc,
ce2,
type = evt && evt.type,
originalTarget = target || (evt && evt.target) || this,
oldbubble;
if (!evt || ((!evt.stopped) && targs)) {
for (i in targs) {
if (targs.hasOwnProperty(i)) {
t = targs[i];
ce = t._yuievt.events[type];
if (t._hasSiblings) {
ce2 = t.getSibling(type, ce);
}
if (ce2 && !ce) {
ce = t.publish(type);
}
oldbubble = t._yuievt.bubbling;
t._yuievt.bubbling = type;
// if this event was not published on the bubble target,
// continue propagating the event.
if (!ce) {
if (t._yuievt.hasTargets) {
t.bubble(evt, args, originalTarget, es);
}
} else {
if (ce2) {
ce.sibling = ce2;
}
// set the original target to that the target payload on the facade is correct.
ce.target = originalTarget;
ce.originalTarget = originalTarget;
ce.currentTarget = t;
bc = ce.broadcast;
ce.broadcast = false;
// default publish may not have emitFacade true -- that
// shouldn't be what the implementer meant to do
ce.emitFacade = true;
ce.stack = es;
// TODO: See what's getting in the way of changing this to use
// the more performant ce._fire(args || evt.details || []).
// Something in Widget Parent/Child tests is not happy if we
// change it - maybe evt.details related?
ret = ret && ce.fire.apply(ce, args || evt.details || []);
ce.broadcast = bc;
ce.originalTarget = null;
// stopPropagation() was called
if (ce.stopped) {
break;
}
}
t._yuievt.bubbling = oldbubble;
}
}
}
return ret;
};
/**
* @method _hasPotentialSubscribers
* @for EventTarget
* @private
* @param {String} fullType The fully prefixed type name
* @return {boolean} Whether the event has potential subscribers or not
*/
ETProto._hasPotentialSubscribers = function(fullType) {
var etState = this._yuievt,
e = etState.events[fullType];
if (e) {
return e.hasSubs() || etState.hasTargets || e.broadcast;
} else {
return false;
}
};
FACADE = new Y.EventFacade();
FACADE_KEYS = {};
// Flatten whitelist
for (key in FACADE) {
FACADE_KEYS[key] = true;
}
}, 'patched-v3.11.0', {"requires": ["event-custom-base"]});
YUI.add('event-delegate', function (Y, NAME) {
/**
* Adds event delegation support to the library.
*
* @module event
* @submodule event-delegate
*/
var toArray = Y.Array,
YLang = Y.Lang,
isString = YLang.isString,
isObject = YLang.isObject,
isArray = YLang.isArray,
selectorTest = Y.Selector.test,
detachCategories = Y.Env.evt.handles;
/**
* Sets up event delegation on a container element. The delegated event
* will use a supplied selector or filtering function to test if the event
* references at least one node that should trigger the subscription
* callback.
*
* Selector string filters will trigger the callback if the event originated
* from a node that matches it or is contained in a node that matches it.
* Function filters are called for each Node up the parent axis to the
* subscribing container node, and receive at each level the Node and the event
* object. The function should return true (or a truthy value) if that Node
* should trigger the subscription callback. Note, it is possible for filters
* to match multiple Nodes for a single event. In this case, the delegate
* callback will be executed for each matching Node.
*
* For each matching Node, the callback will be executed with its 'this'
* object set to the Node matched by the filter (unless a specific context was
* provided during subscription), and the provided event's
* currentTarget
will also be set to the matching Node. The
* containing Node from which the subscription was originally made can be
* referenced as e.container
.
*
* @method delegate
* @param type {String} the event type to delegate
* @param fn {Function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param el {String|node} the element that is the delegation container
* @param filter {string|Function} a selector that must match the target of the
* event or a function to test target and its parents for a match
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @static
* @for Event
*/
function delegate(type, fn, el, filter) {
var args = toArray(arguments, 0, true),
query = isString(el) ? el : null,
typeBits, synth, container, categories, cat, i, len, handles, handle;
// Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...);
// and Y.delegate(['click', 'key'], fn, el, filter, ...);
if (isObject(type)) {
handles = [];
if (isArray(type)) {
for (i = 0, len = type.length; i < len; ++i) {
args[0] = type[i];
handles.push(Y.delegate.apply(Y, args));
}
} else {
// Y.delegate({'click', fn}, el, filter) =>
// Y.delegate('click', fn, el, filter)
args.unshift(null); // one arg becomes two; need to make space
for (i in type) {
if (type.hasOwnProperty(i)) {
args[0] = i;
args[1] = type[i];
handles.push(Y.delegate.apply(Y, args));
}
}
}
return new Y.EventHandle(handles);
}
typeBits = type.split(/\|/);
if (typeBits.length > 1) {
cat = typeBits.shift();
args[0] = type = typeBits.shift();
}
synth = Y.Node.DOM_EVENTS[type];
if (isObject(synth) && synth.delegate) {
handle = synth.delegate.apply(synth, arguments);
}
if (!handle) {
if (!type || !fn || !el || !filter) {
return;
}
container = (query) ? Y.Selector.query(query, null, true) : el;
if (!container && isString(el)) {
handle = Y.on('available', function () {
Y.mix(handle, Y.delegate.apply(Y, args), true);
}, el);
}
if (!handle && container) {
args.splice(2, 2, container); // remove the filter
handle = Y.Event._attach(args, { facade: false });
handle.sub.filter = filter;
handle.sub._notify = delegate.notifySub;
}
}
if (handle && cat) {
categories = detachCategories[cat] || (detachCategories[cat] = {});
categories = categories[type] || (categories[type] = []);
categories.push(handle);
}
return handle;
}
/**
Overrides the _notify
method on the normal DOM subscription to
inject the filtering logic and only proceed in the case of a match.
This method is hosted as a private property of the `delegate` method
(e.g. `Y.delegate.notifySub`)
@method notifySub
@param thisObj {Object} default 'this' object for the callback
@param args {Array} arguments passed to the event's fire()
@param ce {CustomEvent} the custom event managing the DOM subscriptions for
the subscribed event on the subscribing node.
@return {Boolean} false if the event was stopped
@private
@static
@since 3.2.0
**/
delegate.notifySub = function (thisObj, args, ce) {
// Preserve args for other subscribers
args = args.slice();
if (this.args) {
args.push.apply(args, this.args);
}
// Only notify subs if the event occurred on a targeted element
var currentTarget = delegate._applyFilter(this.filter, args, ce),
//container = e.currentTarget,
e, i, len, ret;
if (currentTarget) {
// Support multiple matches up the the container subtree
currentTarget = toArray(currentTarget);
// The second arg is the currentTarget, but we'll be reusing this
// facade, replacing the currentTarget for each use, so it doesn't
// matter what element we seed it with.
e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce);
e.container = Y.one(ce.el);
for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) {
e.currentTarget = Y.one(currentTarget[i]);
ret = this.fn.apply(this.context || e.currentTarget, args);
if (ret === false) { // stop further notifications
break;
}
}
return ret;
}
};
/**
Compiles a selector string into a filter function to identify whether
Nodes along the parent axis of an event's target should trigger event
notification.
This function is memoized, so previously compiled filter functions are
returned if the same selector string is provided.
This function may be useful when defining synthetic events for delegate
handling.
Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`).
@method compileFilter
@param selector {String} the selector string to base the filtration on
@return {Function}
@since 3.2.0
@static
**/
delegate.compileFilter = Y.cached(function (selector) {
return function (target, e) {
return selectorTest(target._node, selector,
(e.currentTarget === e.target) ? null : e.currentTarget._node);
};
});
/**
Regex to test for disabled elements during filtering. This is only relevant to
IE to normalize behavior with other browsers, which swallow events that occur
to disabled elements. IE fires the event from the parent element instead of the
original target, though it does preserve `event.srcElement` as the disabled
element. IE also supports disabled on ``, but the event still bubbles, so it
acts more like `e.preventDefault()` plus styling. That issue is not handled here
because other browsers fire the event on the ` `, so delegate is supported in
both cases.
@property _disabledRE
@type {RegExp}
@protected
@since 3.8.1
**/
delegate._disabledRE = /^(?:button|input|select|textarea)$/i;
/**
Walks up the parent axis of an event's target, and tests each element
against a supplied filter function. If any Nodes, including the container,
satisfy the filter, the delegated callback will be triggered for each.
Hosted as a protected property of the `delegate` method (e.g.
`Y.delegate._applyFilter`).
@method _applyFilter
@param filter {Function} boolean function to test for inclusion in event
notification
@param args {Array} the arguments that would be passed to subscribers
@param ce {CustomEvent} the DOM event wrapper
@return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter
@protected
**/
delegate._applyFilter = function (filter, args, ce) {
var e = args[0],
container = ce.el, // facadeless events in IE, have no e.currentTarget
target = e.target || e.srcElement,
match = [],
isContainer = false;
// Resolve text nodes to their containing element
if (target.nodeType === 3) {
target = target.parentNode;
}
// For IE. IE propagates events from the parent element of disabled
// elements, where other browsers swallow the event entirely. To normalize
// this in IE, filtering for matching elements should abort if the target
// is a disabled form control.
if (target.disabled && delegate._disabledRE.test(target.nodeName)) {
return match;
}
// passing target as the first arg rather than leaving well enough alone
// making 'this' in the filter function refer to the target. This is to
// support bound filter functions.
args.unshift(target);
if (isString(filter)) {
while (target) {
isContainer = (target === container);
if (selectorTest(target, filter, (isContainer ? null: container))) {
match.push(target);
}
if (isContainer) {
break;
}
target = target.parentNode;
}
} else {
// filter functions are implementer code and should receive wrappers
args[0] = Y.one(target);
args[1] = new Y.DOMEventFacade(e, container, ce);
while (target) {
// filter(target, e, extra args...) - this === target
if (filter.apply(args[0], args)) {
match.push(target);
}
if (target === container) {
break;
}
target = target.parentNode;
args[0] = Y.one(target);
}
args[1] = e; // restore the raw DOM event
}
if (match.length <= 1) {
match = match[0]; // single match or undefined
}
// remove the target
args.shift();
return match;
};
/**
* Sets up event delegation on a container element. The delegated event
* will use a supplied filter to test if the callback should be executed.
* This filter can be either a selector string or a function that returns
* a Node to use as the currentTarget for the event.
*
* The event object for the delegated event is supplied to the callback
* function. It is modified slightly in order to support all properties
* that may be needed for event delegation. 'currentTarget' is set to
* the element that matched the selector string filter or the Node returned
* from the filter function. 'container' is set to the element that the
* listener is delegated from (this normally would be the 'currentTarget').
*
* Filter functions will be called with the arguments that would be passed to
* the callback function, including the event object as the first parameter.
* The function should return false (or a falsey value) if the success criteria
* aren't met, and the Node to use as the event's currentTarget and 'this'
* object if they are.
*
* @method delegate
* @param type {string} the event type to delegate
* @param fn {function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param el {string|node} the element that is the delegation container
* @param filter {string|function} a selector that must match the target of the
* event or a function that returns a Node or false.
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.delegate = Y.Event.delegate = delegate;
}, 'patched-v3.11.0', {"requires": ["node-base"]});
YUI.add('event-focus', function (Y, NAME) {
/**
* Adds bubbling and delegation support to DOM events focus and blur.
*
* @module event
* @submodule event-focus
*/
var Event = Y.Event,
YLang = Y.Lang,
isString = YLang.isString,
arrayIndex = Y.Array.indexOf,
useActivate = (function() {
// Changing the structure of this test, so that it doesn't use inline JS in HTML,
// which throws an exception in Win8 packaged apps, due to additional security restrictions:
// http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences
var supported = false,
doc = Y.config.doc,
p;
if (doc) {
p = doc.createElement("p");
p.setAttribute("onbeforeactivate", ";");
// onbeforeactivate is a function in IE8+.
// onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below).
// onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test).
// onbeforeactivate is undefined in Webkit/Gecko.
// onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick).
supported = (p.onbeforeactivate !== undefined);
}
return supported;
}());
function define(type, proxy, directEvent) {
var nodeDataKey = '_' + type + 'Notifiers';
Y.Event.define(type, {
_useActivate : useActivate,
_attach: function (el, notifier, delegate) {
if (Y.DOM.isWindow(el)) {
return Event._attach([type, function (e) {
notifier.fire(e);
}, el]);
} else {
return Event._attach(
[proxy, this._proxy, el, this, notifier, delegate],
{ capture: true });
}
},
_proxy: function (e, notifier, delegate) {
var target = e.target,
currentTarget = e.currentTarget,
notifiers = target.getData(nodeDataKey),
yuid = Y.stamp(currentTarget._node),
defer = (useActivate || target !== currentTarget),
directSub;
notifier.currentTarget = (delegate) ? target : currentTarget;
notifier.container = (delegate) ? currentTarget : null;
// Maintain a list to handle subscriptions from nested
// containers div#a>div#b>input #a.on(focus..) #b.on(focus..),
// use one focus or blur subscription that fires notifiers from
// #b then #a to emulate bubble sequence.
if (!notifiers) {
notifiers = {};
target.setData(nodeDataKey, notifiers);
// only subscribe to the element's focus if the target is
// not the current target (
if (defer) {
directSub = Event._attach(
[directEvent, this._notify, target._node]).sub;
directSub.once = true;
}
} else {
// In old IE, defer is always true. In capture-phase browsers,
// The delegate subscriptions will be encountered first, which
// will establish the notifiers data and direct subscription
// on the node. If there is also a direct subscription to the
// node's focus/blur, it should not call _notify because the
// direct subscription from the delegate sub(s) exists, which
// will call _notify. So this avoids _notify being called
// twice, unnecessarily.
defer = true;
}
if (!notifiers[yuid]) {
notifiers[yuid] = [];
}
notifiers[yuid].push(notifier);
if (!defer) {
this._notify(e);
}
},
_notify: function (e, container) {
var currentTarget = e.currentTarget,
notifierData = currentTarget.getData(nodeDataKey),
axisNodes = currentTarget.ancestors(),
doc = currentTarget.get('ownerDocument'),
delegates = [],
// Used to escape loops when there are no more
// notifiers to consider
count = notifierData ?
Y.Object.keys(notifierData).length :
0,
target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;
// clear the notifications list (mainly for delegation)
currentTarget.clearData(nodeDataKey);
// Order the delegate subs by their placement in the parent axis
axisNodes.push(currentTarget);
// document.get('ownerDocument') returns null
// which we'll use to prevent having duplicate Nodes in the list
if (doc) {
axisNodes.unshift(doc);
}
// ancestors() returns the Nodes from top to bottom
axisNodes._nodes.reverse();
if (count) {
// Store the count for step 2
tmp = count;
axisNodes.some(function (node) {
var yuid = Y.stamp(node),
notifiers = notifierData[yuid],
i, len;
if (notifiers) {
count--;
for (i = 0, len = notifiers.length; i < len; ++i) {
if (notifiers[i].handle.sub.filter) {
delegates.push(notifiers[i]);
}
}
}
return !count;
});
count = tmp;
}
// Walk up the parent axis, notifying direct subscriptions and
// testing delegate filters.
while (count && (target = axisNodes.shift())) {
yuid = Y.stamp(target);
notifiers = notifierData[yuid];
if (notifiers) {
for (i = 0, len = notifiers.length; i < len; ++i) {
notifier = notifiers[i];
sub = notifier.handle.sub;
match = true;
e.currentTarget = target;
if (sub.filter) {
match = sub.filter.apply(target,
[target, e].concat(sub.args || []));
// No longer necessary to test against this
// delegate subscription for the nodes along
// the parent axis.
delegates.splice(
arrayIndex(delegates, notifier), 1);
}
if (match) {
// undefined for direct subs
e.container = notifier.container;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
delete notifiers[yuid];
count--;
}
if (e.stopped !== 2) {
// delegates come after subs targeting this specific node
// because they would not normally report until they'd
// bubbled to the container node.
for (i = 0, len = delegates.length; i < len; ++i) {
notifier = delegates[i];
sub = notifier.handle.sub;
if (sub.filter.apply(target,
[target, e].concat(sub.args || []))) {
e.container = notifier.container;
e.currentTarget = target;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
}
if (e.stopped) {
break;
}
}
},
on: function (node, sub, notifier) {
sub.handle = this._attach(node._node, notifier);
},
detach: function (node, sub) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
if (isString(filter)) {
sub.filter = function (target) {
return Y.Selector.test(target._node, filter,
node === target ? null : node._node);
};
}
sub.handle = this._attach(node._node, notifier, true);
},
detachDelegate: function (node, sub) {
sub.handle.detach();
}
}, true);
}
// For IE, we need to defer to focusin rather than focus because
// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,
// el.onfocusin, doSomething, then el.onfocus. All others support capture
// phase focus, which executes before doSomething. To guarantee consistent
// behavior for this use case, IE's direct subscriptions are made against
// focusin so subscribers will be notified before js following el.focus() is
// executed.
if (useActivate) {
// name capture phase direct subscription
define("focus", "beforeactivate", "focusin");
define("blur", "beforedeactivate", "focusout");
} else {
define("focus", "focus", "focus");
define("blur", "blur", "blur");
}
}, 'patched-v3.11.0', {"requires": ["event-synthetic"]});
YUI.add('event-hover', function (Y, NAME) {
/**
* Adds support for a "hover" event. The event provides a convenience wrapper
* for subscribing separately to mouseenter and mouseleave. The signature for
* subscribing to the event is
*
* node.on("hover", overFn, outFn);
* node.delegate("hover", overFn, outFn, ".filterSelector");
* Y.on("hover", overFn, outFn, ".targetSelector");
* Y.delegate("hover", overFn, outFn, "#container", ".filterSelector");
*
*
* Additionally, for compatibility with a more typical subscription
* signature, the following are also supported:
*
* Y.on("hover", overFn, ".targetSelector", outFn);
* Y.delegate("hover", overFn, "#container", outFn, ".filterSelector");
*
*
* @module event
* @submodule event-hover
*/
var isFunction = Y.Lang.isFunction,
noop = function () {},
conf = {
processArgs: function (args) {
// Y.delegate('hover', over, out, '#container', '.filter')
// comes in as ['hover', over, out, '#container', '.filter'], but
// node.delegate('hover', over, out, '.filter')
// comes in as ['hover', over, containerEl, out, '.filter']
var i = isFunction(args[2]) ? 2 : 3;
return (isFunction(args[i])) ? args.splice(i,1)[0] : noop;
},
on: function (node, sub, notifier, filter) {
var args = (sub.args) ? sub.args.slice() : [];
args.unshift(null);
sub._detach = node[(filter) ? "delegate" : "on"]({
mouseenter: function (e) {
e.phase = 'over';
notifier.fire(e);
},
mouseleave: function (e) {
var thisObj = sub.context || this;
args[0] = e;
e.type = 'hover';
e.phase = 'out';
sub._extra.apply(thisObj, args);
}
}, filter);
},
detach: function (node, sub, notifier) {
sub._detach.detach();
}
};
conf.delegate = conf.on;
conf.detachDelegate = conf.detach;
Y.Event.define("hover", conf);
}, 'patched-v3.11.0', {"requires": ["event-mouseenter"]});
YUI.add('event-key', function (Y, NAME) {
/**
* Functionality to listen for one or more specific key combinations.
* @module event
* @submodule event-key
*/
var ALT = "+alt",
CTRL = "+ctrl",
META = "+meta",
SHIFT = "+shift",
trim = Y.Lang.trim,
eventDef = {
KEY_MAP: {
enter : 13,
esc : 27,
backspace: 8,
tab : 9,
pageup : 33,
pagedown : 34
},
_typeRE: /^(up|down|press):/,
_keysRE: /^(?:up|down|press):|\+(alt|ctrl|meta|shift)/g,
processArgs: function (args) {
var spec = args.splice(3,1)[0],
mods = Y.Array.hash(spec.match(/\+(?:alt|ctrl|meta|shift)\b/g) || []),
config = {
type: this._typeRE.test(spec) ? RegExp.$1 : null,
mods: mods,
keys: null
},
// strip type and modifiers from spec, leaving only keyCodes
bits = spec.replace(this._keysRE, ''),
chr, uc, lc, i;
if (bits) {
bits = bits.split(',');
config.keys = {};
// FIXME: need to support '65,esc' => keypress, keydown
for (i = bits.length - 1; i >= 0; --i) {
chr = trim(bits[i]);
// catch sloppy filters, trailing commas, etc 'a,,'
if (!chr) {
continue;
}
// non-numerics are single characters or key names
if (+chr == chr) {
config.keys[chr] = mods;
} else {
lc = chr.toLowerCase();
if (this.KEY_MAP[lc]) {
config.keys[this.KEY_MAP[lc]] = mods;
// FIXME: '65,enter' defaults keydown for both
if (!config.type) {
config.type = "down"; // safest
}
} else {
// FIXME: Character mapping only works for keypress
// events. Otherwise, it uses String.fromCharCode()
// from the keyCode, which is wrong.
chr = chr.charAt(0);
uc = chr.toUpperCase();
if (mods["+shift"]) {
chr = uc;
}
// FIXME: stupid assumption that
// the keycode of the lower case == the
// charCode of the upper case
// a (key:65,char:97), A (key:65,char:65)
config.keys[chr.charCodeAt(0)] =
(chr === uc) ?
// upper case chars get +shift free
Y.merge(mods, { "+shift": true }) :
mods;
}
}
}
}
if (!config.type) {
config.type = "press";
}
return config;
},
on: function (node, sub, notifier, filter) {
var spec = sub._extra,
type = "key" + spec.type,
keys = spec.keys,
method = (filter) ? "delegate" : "on";
// Note: without specifying any keyCodes, this becomes a
// horribly inefficient alias for 'keydown' (et al), but I
// can't abort this subscription for a simple
// Y.on('keypress', ...);
// Please use keyCodes or just subscribe directly to keydown,
// keyup, or keypress
sub._detach = node[method](type, function (e) {
var key = keys ? keys[e.which] : spec.mods;
if (key &&
(!key[ALT] || (key[ALT] && e.altKey)) &&
(!key[CTRL] || (key[CTRL] && e.ctrlKey)) &&
(!key[META] || (key[META] && e.metaKey)) &&
(!key[SHIFT] || (key[SHIFT] && e.shiftKey)))
{
notifier.fire(e);
}
}, filter);
},
detach: function (node, sub, notifier) {
sub._detach.detach();
}
};
eventDef.delegate = eventDef.on;
eventDef.detachDelegate = eventDef.detach;
/**
* Add a key listener. The listener will only be notified if the
* keystroke detected meets the supplied specification. The
* specification is a string that is defined as:
*
*
* spec
* [{type}:]{code}[,{code}]*
* type
* "down", "up", or "press"
* code
* {keyCode|character|keyName}[+{modifier}]*
* modifier
* "shift", "ctrl", "alt", or "meta"
* keyName
* "enter", "backspace", "esc", "tab", "pageup", or "pagedown"
*
*
* Examples:
*
* Y.on("key", callback, "press:12,65+shift+ctrl", "#my-input");
* Y.delegate("key", preventSubmit, "#forms", "enter", "input[type=text]");
* Y.one("doc").on("key", viNav, "j,k,l,;");
*
*
* @event key
* @for YUI
* @param type {string} 'key'
* @param fn {function} the function to execute
* @param id {string|HTMLElement|collection} the element(s) to bind
* @param spec {string} the keyCode and modifier specification
* @param o optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {Event.Handle} the detach handle
*/
Y.Event.define('key', eventDef, true);
}, 'patched-v3.11.0', {"requires": ["event-synthetic"]});
YUI.add('event-mouseenter', function (Y, NAME) {
/**
* Adds subscription and delegation support for mouseenter and mouseleave
* events. Unlike mouseover and mouseout, these events aren't fired from child
* elements of a subscribed node.
*
* This avoids receiving three mouseover notifications from a setup like
*
* div#container > p > a[href]
*
* where
*
* Y.one('#container').on('mouseover', callback)
*
* When the mouse moves over the link, one mouseover event is fired from
* #container, then when the mouse moves over the p, another mouseover event is
* fired and bubbles to #container, causing a second notification, and finally
* when the mouse moves over the link, a third mouseover event is fired and
* bubbles to #container for a third notification.
*
* By contrast, using mouseenter instead of mouseover, the callback would be
* executed only once when the mouse moves over #container.
*
* @module event
* @submodule event-mouseenter
*/
var domEventProxies = Y.Env.evt.dom_wrappers,
contains = Y.DOM.contains,
toArray = Y.Array,
noop = function () {},
config = {
proxyType: "mouseover",
relProperty: "fromElement",
_notify: function (e, property, notifier) {
var el = this._node,
related = e.relatedTarget || e[property];
if (el !== related && !contains(el, related)) {
notifier.fire(new Y.DOMEventFacade(e, el,
domEventProxies['event:' + Y.stamp(el) + e.type]));
}
},
on: function (node, sub, notifier) {
var el = Y.Node.getDOMNode(node),
args = [
this.proxyType,
this._notify,
el,
null,
this.relProperty,
notifier];
sub.handle = Y.Event._attach(args, { facade: false });
// node.on(this.proxyType, notify, null, notifier);
},
detach: function (node, sub) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
var el = Y.Node.getDOMNode(node),
args = [
this.proxyType,
noop,
el,
null,
notifier
];
sub.handle = Y.Event._attach(args, { facade: false });
sub.handle.sub.filter = filter;
sub.handle.sub.relProperty = this.relProperty;
sub.handle.sub._notify = this._filterNotify;
},
_filterNotify: function (thisObj, args, ce) {
args = args.slice();
if (this.args) {
args.push.apply(args, this.args);
}
var currentTarget = Y.delegate._applyFilter(this.filter, args, ce),
related = args[0].relatedTarget || args[0][this.relProperty],
e, i, len, ret, ct;
if (currentTarget) {
currentTarget = toArray(currentTarget);
for (i = 0, len = currentTarget.length && (!e || !e.stopped); i < len; ++i) {
ct = currentTarget[0];
if (!contains(ct, related)) {
if (!e) {
e = new Y.DOMEventFacade(args[0], ct, ce);
e.container = Y.one(ce.el);
}
e.currentTarget = Y.one(ct);
// TODO: where is notifier? args? this.notifier?
ret = args[1].fire(e);
if (ret === false) {
break;
}
}
}
}
return ret;
},
detachDelegate: function (node, sub) {
sub.handle.detach();
}
};
Y.Event.define("mouseenter", config, true);
Y.Event.define("mouseleave", Y.merge(config, {
proxyType: "mouseout",
relProperty: "toElement"
}), true);
}, 'patched-v3.11.0', {"requires": ["event-synthetic"]});
YUI.add('event-mousewheel', function (Y, NAME) {
/**
* Adds mousewheel event support
* @module event
* @submodule event-mousewheel
*/
var DOM_MOUSE_SCROLL = 'DOMMouseScroll',
fixArgs = function(args) {
var a = Y.Array(args, 0, true), target;
if (Y.UA.gecko) {
a[0] = DOM_MOUSE_SCROLL;
target = Y.config.win;
} else {
target = Y.config.doc;
}
if (a.length < 3) {
a[2] = target;
} else {
a.splice(2, 0, target);
}
return a;
};
/**
* Mousewheel event. This listener is automatically attached to the
* correct target, so one should not be supplied. Mouse wheel
* direction and velocity is stored in the 'wheelDelta' field.
* @event mousewheel
* @param type {string} 'mousewheel'
* @param fn {function} the callback to execute
* @param context optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.Env.evt.plugins.mousewheel = {
on: function() {
return Y.Event._attach(fixArgs(arguments));
},
detach: function() {
return Y.Event.detach.apply(Y.Event, fixArgs(arguments));
}
};
}, 'patched-v3.11.0', {"requires": ["node-base"]});
YUI.add('event-outside', function (Y, NAME) {
/**
* Outside events are synthetic DOM events that fire when a corresponding native
* or synthetic DOM event occurs outside a bound element.
*
* The following outside events are pre-defined by this module:
*
* blur
* change
* click
* dblclick
* focus
* keydown
* keypress
* keyup
* mousedown
* mousemove
* mouseout
* mouseover
* mouseup
* select
* submit
*
*
* Define new outside events with
* Y.Event.defineOutside(eventType);
.
* By default, the created synthetic event name will be the name of the event
* with "outside" appended (e.g. "click" becomes "clickoutside"). If you want
* a different name for the created Event, pass it as a second argument like so:
* Y.Event.defineOutside(eventType, "yonderclick")
.
*
* This module was contributed by Brett Stimmerman, promoted from his
* gallery-outside-events module at
* http://yuilibrary.com/gallery/show/outside-events
*
* @module event
* @submodule event-outside
* @author brettstimmerman
* @since 3.4.0
*/
// Outside events are pre-defined for each of these native DOM events
var nativeEvents = [
'blur', 'change', 'click', 'dblclick', 'focus', 'keydown', 'keypress',
'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup',
'select', 'submit'
];
/**
* Defines a new outside event to correspond with the given DOM event.
*
* By default, the created synthetic event name will be the name of the event
* with "outside" appended (e.g. "click" becomes "clickoutside"). If you want
* a different name for the created Event, pass it as a second argument like so:
* Y.Event.defineOutside(eventType, "yonderclick")
.
*
* @method defineOutside
* @param {String} event DOM event
* @param {String} name (optional) custom outside event name
* @static
* @for Event
*/
Y.Event.defineOutside = function (event, name) {
name = name || (event + 'outside');
var config = {
on: function (node, sub, notifier) {
sub.handle = Y.one('doc').on(event, function(e) {
if (this.isOutside(node, e.target)) {
e.currentTarget = node;
notifier.fire(e);
}
}, this);
},
detach: function (node, sub, notifier) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
sub.handle = Y.one('doc').delegate(event, function (e) {
if (this.isOutside(node, e.target)) {
notifier.fire(e);
}
}, filter, this);
},
isOutside: function (node, target) {
return target !== node && !target.ancestor(function (p) {
return p === node;
});
}
};
config.detachDelegate = config.detach;
Y.Event.define(name, config);
};
// Define outside events for some common native DOM events
Y.Array.each(nativeEvents, function (event) {
Y.Event.defineOutside(event);
});
}, 'patched-v3.11.0', {"requires": ["event-synthetic"]});
YUI.add('event-resize', function (Y, NAME) {
/**
* Adds a window resize event that has its behavior normalized to fire at the
* end of the resize rather than constantly during the resize.
* @module event
* @submodule event-resize
*/
/**
* Old firefox fires the window resize event once when the resize action
* finishes, other browsers fire the event periodically during the
* resize. This code uses timeout logic to simulate the Firefox
* behavior in other browsers.
* @event windowresize
* @for YUI
*/
Y.Event.define('windowresize', {
on: (Y.UA.gecko && Y.UA.gecko < 1.91) ?
function (node, sub, notifier) {
sub._handle = Y.Event.attach('resize', function (e) {
notifier.fire(e);
});
} :
function (node, sub, notifier) {
// interval bumped from 40 to 100ms as of 3.4.1
var delay = Y.config.windowResizeDelay || 100;
sub._handle = Y.Event.attach('resize', function (e) {
if (sub._timer) {
sub._timer.cancel();
}
sub._timer = Y.later(delay, Y, function () {
notifier.fire(e);
});
});
},
detach: function (node, sub) {
if (sub._timer) {
sub._timer.cancel();
}
sub._handle.detach();
}
// delegate methods not defined because this only works for window
// subscriptions, so...yeah.
});
}, 'patched-v3.11.0', {"requires": ["node-base", "event-synthetic"]});
YUI.add('event-simulate', function (Y, NAME) {
(function() {
/**
* Simulate user interaction by generating native DOM events.
*
* @module event-simulate
* @requires event
*/
//shortcuts
var L = Y.Lang,
win = Y.config.win,
isFunction = L.isFunction,
isString = L.isString,
isBoolean = L.isBoolean,
isObject = L.isObject,
isNumber = L.isNumber,
//mouse events supported
mouseEvents = {
click: 1,
dblclick: 1,
mouseover: 1,
mouseout: 1,
mousedown: 1,
mouseup: 1,
mousemove: 1,
contextmenu:1
},
pointerEvents = (win && win.PointerEvent) ? {
pointerover: 1,
pointerout: 1,
pointerdown: 1,
pointerup: 1,
pointermove: 1
} : {
MSPointerOver: 1,
MSPointerOut: 1,
MSPointerDown: 1,
MSPointerUp: 1,
MSPointerMove: 1
},
//key events supported
keyEvents = {
keydown: 1,
keyup: 1,
keypress: 1
},
//HTML events supported
uiEvents = {
submit: 1,
blur: 1,
change: 1,
focus: 1,
resize: 1,
scroll: 1,
select: 1
},
//events that bubble by default
bubbleEvents = {
scroll: 1,
resize: 1,
reset: 1,
submit: 1,
change: 1,
select: 1,
error: 1,
abort: 1
},
//touch events supported
touchEvents = {
touchstart: 1,
touchmove: 1,
touchend: 1,
touchcancel: 1
},
gestureEvents = {
gesturestart: 1,
gesturechange: 1,
gestureend: 1
};
//all key, mouse and touch events bubble
Y.mix(bubbleEvents, mouseEvents);
Y.mix(bubbleEvents, keyEvents);
Y.mix(bubbleEvents, touchEvents);
/*
* Note: Intentionally not for YUIDoc generation.
* Simulates a key event using the given event information to populate
* the generated event object. This method does browser-equalizing
* calculations to account for differences in the DOM and IE event models
* as well as different browser quirks. Note: keydown causes Safari 2.x to
* crash.
* @method simulateKeyEvent
* @private
* @static
* @param {HTMLElement} target The target of the given event.
* @param {String} type The type of event to fire. This can be any one of
* the following: keyup, keydown, and keypress.
* @param {Boolean} bubbles (Optional) Indicates if the event can be
* bubbled up. DOM Level 3 specifies that all key events bubble by
* default. The default is true.
* @param {Boolean} cancelable (Optional) Indicates if the event can be
* canceled using preventDefault(). DOM Level 3 specifies that all
* key events can be cancelled. The default
* is true.
* @param {Window} view (Optional) The view containing the target. This is
* typically the window object. The default is window.
* @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} altKey (Optional) Indicates if one of the ALT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} metaKey (Optional) Indicates if one of the META keys
* is pressed while the event is firing. The default is false.
* @param {int} keyCode (Optional) The code for the key that is in use.
* The default is 0.
* @param {int} charCode (Optional) The Unicode code for the character
* associated with the key being used. The default is 0.
*/
function simulateKeyEvent(target /*:HTMLElement*/, type /*:String*/,
bubbles /*:Boolean*/, cancelable /*:Boolean*/,
view /*:Window*/,
ctrlKey /*:Boolean*/, altKey /*:Boolean*/,
shiftKey /*:Boolean*/, metaKey /*:Boolean*/,
keyCode /*:int*/, charCode /*:int*/) /*:Void*/
{
//check target
if (!target){
Y.error("simulateKeyEvent(): Invalid target.");
}
//check event type
if (isString(type)){
type = type.toLowerCase();
switch(type){
case "textevent": //DOM Level 3
type = "keypress";
break;
case "keyup":
case "keydown":
case "keypress":
break;
default:
Y.error("simulateKeyEvent(): Event type '" + type + "' not supported.");
}
} else {
Y.error("simulateKeyEvent(): Event type must be a string.");
}
//setup default values
if (!isBoolean(bubbles)){
bubbles = true; //all key events bubble
}
if (!isBoolean(cancelable)){
cancelable = true; //all key events can be cancelled
}
if (!isObject(view)){
view = Y.config.win; //view is typically window
}
if (!isBoolean(ctrlKey)){
ctrlKey = false;
}
if (!isBoolean(altKey)){
altKey = false;
}
if (!isBoolean(shiftKey)){
shiftKey = false;
}
if (!isBoolean(metaKey)){
metaKey = false;
}
if (!isNumber(keyCode)){
keyCode = 0;
}
if (!isNumber(charCode)){
charCode = 0;
}
//try to create a mouse event
var customEvent /*:MouseEvent*/ = null;
//check for DOM-compliant browsers first
if (isFunction(Y.config.doc.createEvent)){
try {
//try to create key event
customEvent = Y.config.doc.createEvent("KeyEvents");
/*
* Interesting problem: Firefox implemented a non-standard
* version of initKeyEvent() based on DOM Level 2 specs.
* Key event was removed from DOM Level 2 and re-introduced
* in DOM Level 3 with a different interface. Firefox is the
* only browser with any implementation of Key Events, so for
* now, assume it's Firefox if the above line doesn't error.
*/
// @TODO: Decipher between Firefox's implementation and a correct one.
customEvent.initKeyEvent(type, bubbles, cancelable, view, ctrlKey,
altKey, shiftKey, metaKey, keyCode, charCode);
} catch (ex /*:Error*/){
/*
* If it got here, that means key events aren't officially supported.
* Safari/WebKit is a real problem now. WebKit 522 won't let you
* set keyCode, charCode, or other properties if you use a
* UIEvent, so we first must try to create a generic event. The
* fun part is that this will throw an error on Safari 2.x. The
* end result is that we need another try...catch statement just to
* deal with this mess.
*/
try {
//try to create generic event - will fail in Safari 2.x
customEvent = Y.config.doc.createEvent("Events");
} catch (uierror /*:Error*/){
//the above failed, so create a UIEvent for Safari 2.x
customEvent = Y.config.doc.createEvent("UIEvents");
} finally {
customEvent.initEvent(type, bubbles, cancelable);
//initialize
customEvent.view = view;
customEvent.altKey = altKey;
customEvent.ctrlKey = ctrlKey;
customEvent.shiftKey = shiftKey;
customEvent.metaKey = metaKey;
customEvent.keyCode = keyCode;
customEvent.charCode = charCode;
}
}
//fire the event
target.dispatchEvent(customEvent);
} else if (isObject(Y.config.doc.createEventObject)){ //IE
//create an IE event object
customEvent = Y.config.doc.createEventObject();
//assign available properties
customEvent.bubbles = bubbles;
customEvent.cancelable = cancelable;
customEvent.view = view;
customEvent.ctrlKey = ctrlKey;
customEvent.altKey = altKey;
customEvent.shiftKey = shiftKey;
customEvent.metaKey = metaKey;
/*
* IE doesn't support charCode explicitly. CharCode should
* take precedence over any keyCode value for accurate
* representation.
*/
customEvent.keyCode = (charCode > 0) ? charCode : keyCode;
//fire the event
target.fireEvent("on" + type, customEvent);
} else {
Y.error("simulateKeyEvent(): No event simulation framework present.");
}
}
/*
* Note: Intentionally not for YUIDoc generation.
* Simulates a mouse event using the given event information to populate
* the generated event object. This method does browser-equalizing
* calculations to account for differences in the DOM and IE event models
* as well as different browser quirks.
* @method simulateMouseEvent
* @private
* @static
* @param {HTMLElement} target The target of the given event.
* @param {String} type The type of event to fire. This can be any one of
* the following: click, dblclick, mousedown, mouseup, mouseout,
* mouseover, and mousemove.
* @param {Boolean} bubbles (Optional) Indicates if the event can be
* bubbled up. DOM Level 2 specifies that all mouse events bubble by
* default. The default is true.
* @param {Boolean} cancelable (Optional) Indicates if the event can be
* canceled using preventDefault(). DOM Level 2 specifies that all
* mouse events except mousemove can be cancelled. The default
* is true for all events except mousemove, for which the default
* is false.
* @param {Window} view (Optional) The view containing the target. This is
* typically the window object. The default is window.
* @param {int} detail (Optional) The number of times the mouse button has
* been used. The default value is 1.
* @param {int} screenX (Optional) The x-coordinate on the screen at which
* point the event occured. The default is 0.
* @param {int} screenY (Optional) The y-coordinate on the screen at which
* point the event occured. The default is 0.
* @param {int} clientX (Optional) The x-coordinate on the client at which
* point the event occured. The default is 0.
* @param {int} clientY (Optional) The y-coordinate on the client at which
* point the event occured. The default is 0.
* @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} altKey (Optional) Indicates if one of the ALT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} metaKey (Optional) Indicates if one of the META keys
* is pressed while the event is firing. The default is false.
* @param {int} button (Optional) The button being pressed while the event
* is executing. The value should be 0 for the primary mouse button
* (typically the left button), 1 for the terciary mouse button
* (typically the middle button), and 2 for the secondary mouse button
* (typically the right button). The default is 0.
* @param {HTMLElement} relatedTarget (Optional) For mouseout events,
* this is the element that the mouse has moved to. For mouseover
* events, this is the element that the mouse has moved from. This
* argument is ignored for all other events. The default is null.
*/
function simulateMouseEvent(target /*:HTMLElement*/, type /*:String*/,
bubbles /*:Boolean*/, cancelable /*:Boolean*/,
view /*:Window*/, detail /*:int*/,
screenX /*:int*/, screenY /*:int*/,
clientX /*:int*/, clientY /*:int*/,
ctrlKey /*:Boolean*/, altKey /*:Boolean*/,
shiftKey /*:Boolean*/, metaKey /*:Boolean*/,
button /*:int*/, relatedTarget /*:HTMLElement*/) /*:Void*/
{
//check target
if (!target){
Y.error("simulateMouseEvent(): Invalid target.");
}
if (isString(type)){
//make sure it's a supported mouse event or an msPointerEvent.
if (!mouseEvents[type.toLowerCase()] && !pointerEvents[type]){
Y.error("simulateMouseEvent(): Event type '" + type + "' not supported.");
}
}
else {
Y.error("simulateMouseEvent(): Event type must be a string.");
}
//setup default values
if (!isBoolean(bubbles)){
bubbles = true; //all mouse events bubble
}
if (!isBoolean(cancelable)){
cancelable = (type !== "mousemove"); //mousemove is the only one that can't be cancelled
}
if (!isObject(view)){
view = Y.config.win; //view is typically window
}
if (!isNumber(detail)){
detail = 1; //number of mouse clicks must be at least one
}
if (!isNumber(screenX)){
screenX = 0;
}
if (!isNumber(screenY)){
screenY = 0;
}
if (!isNumber(clientX)){
clientX = 0;
}
if (!isNumber(clientY)){
clientY = 0;
}
if (!isBoolean(ctrlKey)){
ctrlKey = false;
}
if (!isBoolean(altKey)){
altKey = false;
}
if (!isBoolean(shiftKey)){
shiftKey = false;
}
if (!isBoolean(metaKey)){
metaKey = false;
}
if (!isNumber(button)){
button = 0;
}
relatedTarget = relatedTarget || null;
//try to create a mouse event
var customEvent /*:MouseEvent*/ = null;
//check for DOM-compliant browsers first
if (isFunction(Y.config.doc.createEvent)){
customEvent = Y.config.doc.createEvent("MouseEvents");
//Safari 2.x (WebKit 418) still doesn't implement initMouseEvent()
if (customEvent.initMouseEvent){
customEvent.initMouseEvent(type, bubbles, cancelable, view, detail,
screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey,
button, relatedTarget);
} else { //Safari
//the closest thing available in Safari 2.x is UIEvents
customEvent = Y.config.doc.createEvent("UIEvents");
customEvent.initEvent(type, bubbles, cancelable);
customEvent.view = view;
customEvent.detail = detail;
customEvent.screenX = screenX;
customEvent.screenY = screenY;
customEvent.clientX = clientX;
customEvent.clientY = clientY;
customEvent.ctrlKey = ctrlKey;
customEvent.altKey = altKey;
customEvent.metaKey = metaKey;
customEvent.shiftKey = shiftKey;
customEvent.button = button;
customEvent.relatedTarget = relatedTarget;
}
/*
* Check to see if relatedTarget has been assigned. Firefox
* versions less than 2.0 don't allow it to be assigned via
* initMouseEvent() and the property is readonly after event
* creation, so in order to keep YAHOO.util.getRelatedTarget()
* working, assign to the IE proprietary toElement property
* for mouseout event and fromElement property for mouseover
* event.
*/
if (relatedTarget && !customEvent.relatedTarget){
if (type === "mouseout"){
customEvent.toElement = relatedTarget;
} else if (type === "mouseover"){
customEvent.fromElement = relatedTarget;
}
}
//fire the event
target.dispatchEvent(customEvent);
} else if (isObject(Y.config.doc.createEventObject)){ //IE
//create an IE event object
customEvent = Y.config.doc.createEventObject();
//assign available properties
customEvent.bubbles = bubbles;
customEvent.cancelable = cancelable;
customEvent.view = view;
customEvent.detail = detail;
customEvent.screenX = screenX;
customEvent.screenY = screenY;
customEvent.clientX = clientX;
customEvent.clientY = clientY;
customEvent.ctrlKey = ctrlKey;
customEvent.altKey = altKey;
customEvent.metaKey = metaKey;
customEvent.shiftKey = shiftKey;
//fix button property for IE's wacky implementation
switch(button){
case 0:
customEvent.button = 1;
break;
case 1:
customEvent.button = 4;
break;
case 2:
//leave as is
break;
default:
customEvent.button = 0;
}
/*
* Have to use relatedTarget because IE won't allow assignment
* to toElement or fromElement on generic events. This keeps
* YAHOO.util.customEvent.getRelatedTarget() functional.
*/
customEvent.relatedTarget = relatedTarget;
//fire the event
target.fireEvent("on" + type, customEvent);
} else {
Y.error("simulateMouseEvent(): No event simulation framework present.");
}
}
/*
* Note: Intentionally not for YUIDoc generation.
* Simulates a UI event using the given event information to populate
* the generated event object. This method does browser-equalizing
* calculations to account for differences in the DOM and IE event models
* as well as different browser quirks.
* @method simulateHTMLEvent
* @private
* @static
* @param {HTMLElement} target The target of the given event.
* @param {String} type The type of event to fire. This can be any one of
* the following: click, dblclick, mousedown, mouseup, mouseout,
* mouseover, and mousemove.
* @param {Boolean} bubbles (Optional) Indicates if the event can be
* bubbled up. DOM Level 2 specifies that all mouse events bubble by
* default. The default is true.
* @param {Boolean} cancelable (Optional) Indicates if the event can be
* canceled using preventDefault(). DOM Level 2 specifies that all
* mouse events except mousemove can be cancelled. The default
* is true for all events except mousemove, for which the default
* is false.
* @param {Window} view (Optional) The view containing the target. This is
* typically the window object. The default is window.
* @param {int} detail (Optional) The number of times the mouse button has
* been used. The default value is 1.
*/
function simulateUIEvent(target /*:HTMLElement*/, type /*:String*/,
bubbles /*:Boolean*/, cancelable /*:Boolean*/,
view /*:Window*/, detail /*:int*/) /*:Void*/
{
//check target
if (!target){
Y.error("simulateUIEvent(): Invalid target.");
}
//check event type
if (isString(type)){
type = type.toLowerCase();
//make sure it's a supported mouse event
if (!uiEvents[type]){
Y.error("simulateUIEvent(): Event type '" + type + "' not supported.");
}
} else {
Y.error("simulateUIEvent(): Event type must be a string.");
}
//try to create a mouse event
var customEvent = null;
//setup default values
if (!isBoolean(bubbles)){
bubbles = (type in bubbleEvents); //not all events bubble
}
if (!isBoolean(cancelable)){
cancelable = (type === "submit"); //submit is the only one that can be cancelled
}
if (!isObject(view)){
view = Y.config.win; //view is typically window
}
if (!isNumber(detail)){
detail = 1; //usually not used but defaulted to this
}
//check for DOM-compliant browsers first
if (isFunction(Y.config.doc.createEvent)){
//just a generic UI Event object is needed
customEvent = Y.config.doc.createEvent("UIEvents");
customEvent.initUIEvent(type, bubbles, cancelable, view, detail);
//fire the event
target.dispatchEvent(customEvent);
} else if (isObject(Y.config.doc.createEventObject)){ //IE
//create an IE event object
customEvent = Y.config.doc.createEventObject();
//assign available properties
customEvent.bubbles = bubbles;
customEvent.cancelable = cancelable;
customEvent.view = view;
customEvent.detail = detail;
//fire the event
target.fireEvent("on" + type, customEvent);
} else {
Y.error("simulateUIEvent(): No event simulation framework present.");
}
}
/*
* (iOS only) This is for creating native DOM gesture events which only iOS
* v2.0+ is supporting.
*
* @method simulateGestureEvent
* @private
* @param {HTMLElement} target The target of the given event.
* @param {String} type The type of event to fire. This can be any one of
* the following: touchstart, touchmove, touchend, touchcancel.
* @param {Boolean} bubbles (Optional) Indicates if the event can be
* bubbled up. DOM Level 2 specifies that all mouse events bubble by
* default. The default is true.
* @param {Boolean} cancelable (Optional) Indicates if the event can be
* canceled using preventDefault(). DOM Level 2 specifies that all
* touch events except touchcancel can be cancelled. The default
* is true for all events except touchcancel, for which the default
* is false.
* @param {Window} view (Optional) The view containing the target. This is
* typically the window object. The default is window.
* @param {int} detail (Optional) Specifies some detail information about
* the event depending on the type of event.
* @param {int} screenX (Optional) The x-coordinate on the screen at which
* point the event occured. The default is 0.
* @param {int} screenY (Optional) The y-coordinate on the screen at which
* point the event occured. The default is 0.
* @param {int} clientX (Optional) The x-coordinate on the client at which
* point the event occured. The default is 0.
* @param {int} clientY (Optional) The y-coordinate on the client at which
* point the event occured. The default is 0.
* @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} altKey (Optional) Indicates if one of the ALT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} metaKey (Optional) Indicates if one of the META keys
* is pressed while the event is firing. The default is false.
* @param {float} scale (iOS v2+ only) The distance between two fingers
* since the start of an event as a multiplier of the initial distance.
* The default value is 1.0.
* @param {float} rotation (iOS v2+ only) The delta rotation since the start
* of an event, in degrees, where clockwise is positive and
* counter-clockwise is negative. The default value is 0.0.
*/
function simulateGestureEvent(target, type,
bubbles, // boolean
cancelable, // boolean
view, // DOMWindow
detail, // long
screenX, screenY, // long
clientX, clientY, // long
ctrlKey, altKey, shiftKey, metaKey, // boolean
scale, // float
rotation // float
) {
var customEvent;
if(!Y.UA.ios || Y.UA.ios<2.0) {
Y.error("simulateGestureEvent(): Native gesture DOM eventframe is not available in this platform.");
}
// check taget
if (!target){
Y.error("simulateGestureEvent(): Invalid target.");
}
//check event type
if (Y.Lang.isString(type)) {
type = type.toLowerCase();
//make sure it's a supported touch event
if (!gestureEvents[type]){
Y.error("simulateTouchEvent(): Event type '" + type + "' not supported.");
}
} else {
Y.error("simulateGestureEvent(): Event type must be a string.");
}
// setup default values
if (!Y.Lang.isBoolean(bubbles)) { bubbles = true; } // bubble by default
if (!Y.Lang.isBoolean(cancelable)) { cancelable = true; }
if (!Y.Lang.isObject(view)) { view = Y.config.win; }
if (!Y.Lang.isNumber(detail)) { detail = 2; } // usually not used.
if (!Y.Lang.isNumber(screenX)) { screenX = 0; }
if (!Y.Lang.isNumber(screenY)) { screenY = 0; }
if (!Y.Lang.isNumber(clientX)) { clientX = 0; }
if (!Y.Lang.isNumber(clientY)) { clientY = 0; }
if (!Y.Lang.isBoolean(ctrlKey)) { ctrlKey = false; }
if (!Y.Lang.isBoolean(altKey)) { altKey = false; }
if (!Y.Lang.isBoolean(shiftKey)){ shiftKey = false; }
if (!Y.Lang.isBoolean(metaKey)) { metaKey = false; }
if (!Y.Lang.isNumber(scale)){ scale = 1.0; }
if (!Y.Lang.isNumber(rotation)){ rotation = 0.0; }
customEvent = Y.config.doc.createEvent("GestureEvent");
customEvent.initGestureEvent(type, bubbles, cancelable, view, detail,
screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey,
target, scale, rotation);
target.dispatchEvent(customEvent);
}
/*
* @method simulateTouchEvent
* @private
* @param {HTMLElement} target The target of the given event.
* @param {String} type The type of event to fire. This can be any one of
* the following: touchstart, touchmove, touchend, touchcancel.
* @param {Boolean} bubbles (Optional) Indicates if the event can be
* bubbled up. DOM Level 2 specifies that all mouse events bubble by
* default. The default is true.
* @param {Boolean} cancelable (Optional) Indicates if the event can be
* canceled using preventDefault(). DOM Level 2 specifies that all
* touch events except touchcancel can be cancelled. The default
* is true for all events except touchcancel, for which the default
* is false.
* @param {Window} view (Optional) The view containing the target. This is
* typically the window object. The default is window.
* @param {int} detail (Optional) Specifies some detail information about
* the event depending on the type of event.
* @param {int} screenX (Optional) The x-coordinate on the screen at which
* point the event occured. The default is 0.
* @param {int} screenY (Optional) The y-coordinate on the screen at which
* point the event occured. The default is 0.
* @param {int} clientX (Optional) The x-coordinate on the client at which
* point the event occured. The default is 0.
* @param {int} clientY (Optional) The y-coordinate on the client at which
* point the event occured. The default is 0.
* @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} altKey (Optional) Indicates if one of the ALT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} metaKey (Optional) Indicates if one of the META keys
* is pressed while the event is firing. The default is false.
* @param {TouchList} touches A collection of Touch objects representing
* all touches associated with this event.
* @param {TouchList} targetTouches A collection of Touch objects
* representing all touches associated with this target.
* @param {TouchList} changedTouches A collection of Touch objects
* representing all touches that changed in this event.
* @param {float} scale (iOS v2+ only) The distance between two fingers
* since the start of an event as a multiplier of the initial distance.
* The default value is 1.0.
* @param {float} rotation (iOS v2+ only) The delta rotation since the start
* of an event, in degrees, where clockwise is positive and
* counter-clockwise is negative. The default value is 0.0.
*/
function simulateTouchEvent(target, type,
bubbles, // boolean
cancelable, // boolean
view, // DOMWindow
detail, // long
screenX, screenY, // long
clientX, clientY, // long
ctrlKey, altKey, shiftKey, metaKey, // boolean
touches, // TouchList
targetTouches, // TouchList
changedTouches, // TouchList
scale, // float
rotation // float
) {
var customEvent;
// check taget
if (!target){
Y.error("simulateTouchEvent(): Invalid target.");
}
//check event type
if (Y.Lang.isString(type)) {
type = type.toLowerCase();
//make sure it's a supported touch event
if (!touchEvents[type]){
Y.error("simulateTouchEvent(): Event type '" + type + "' not supported.");
}
} else {
Y.error("simulateTouchEvent(): Event type must be a string.");
}
// note that the caller is responsible to pass appropriate touch objects.
// check touch objects
// Android(even 4.0) doesn't define TouchList yet
/*if(type === 'touchstart' || type === 'touchmove') {
if(!touches instanceof TouchList) {
Y.error('simulateTouchEvent(): Invalid touches. It must be a TouchList');
} else {
if(touches.length === 0) {
Y.error('simulateTouchEvent(): No touch object found.');
}
}
} else if(type === 'touchend') {
if(!changedTouches instanceof TouchList) {
Y.error('simulateTouchEvent(): Invalid touches. It must be a TouchList');
} else {
if(changedTouches.length === 0) {
Y.error('simulateTouchEvent(): No touch object found.');
}
}
}*/
if(type === 'touchstart' || type === 'touchmove') {
if(touches.length === 0) {
Y.error('simulateTouchEvent(): No touch object in touches');
}
} else if(type === 'touchend') {
if(changedTouches.length === 0) {
Y.error('simulateTouchEvent(): No touch object in changedTouches');
}
}
// setup default values
if (!Y.Lang.isBoolean(bubbles)) { bubbles = true; } // bubble by default.
if (!Y.Lang.isBoolean(cancelable)) {
cancelable = (type !== "touchcancel"); // touchcancel is not cancelled
}
if (!Y.Lang.isObject(view)) { view = Y.config.win; }
if (!Y.Lang.isNumber(detail)) { detail = 1; } // usually not used. defaulted to # of touch objects.
if (!Y.Lang.isNumber(screenX)) { screenX = 0; }
if (!Y.Lang.isNumber(screenY)) { screenY = 0; }
if (!Y.Lang.isNumber(clientX)) { clientX = 0; }
if (!Y.Lang.isNumber(clientY)) { clientY = 0; }
if (!Y.Lang.isBoolean(ctrlKey)) { ctrlKey = false; }
if (!Y.Lang.isBoolean(altKey)) { altKey = false; }
if (!Y.Lang.isBoolean(shiftKey)){ shiftKey = false; }
if (!Y.Lang.isBoolean(metaKey)) { metaKey = false; }
if (!Y.Lang.isNumber(scale)) { scale = 1.0; }
if (!Y.Lang.isNumber(rotation)) { rotation = 0.0; }
//check for DOM-compliant browsers first
if (Y.Lang.isFunction(Y.config.doc.createEvent)) {
if (Y.UA.android) {
/*
* Couldn't find android start version that supports touch event.
* Assumed supported(btw APIs broken till icecream sandwitch)
* from the beginning.
*/
if(Y.UA.android < 4.0) {
/*
* Touch APIs are broken in androids older than 4.0. We will use
* simulated touch apis for these versions.
* App developer still can listen for touch events. This events
* will be dispatched with touch event types.
*
* (Note) Used target for the relatedTarget. Need to verify if
* it has a side effect.
*/
customEvent = Y.config.doc.createEvent("MouseEvents");
customEvent.initMouseEvent(type, bubbles, cancelable, view, detail,
screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey,
0, target);
customEvent.touches = touches;
customEvent.targetTouches = targetTouches;
customEvent.changedTouches = changedTouches;
} else {
customEvent = Y.config.doc.createEvent("TouchEvent");
// Andoroid isn't compliant W3C initTouchEvent method signature.
customEvent.initTouchEvent(touches, targetTouches, changedTouches,
type, view,
screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey);
}
} else if (Y.UA.ios) {
if(Y.UA.ios >= 2.0) {
customEvent = Y.config.doc.createEvent("TouchEvent");
// Available iOS 2.0 and later
customEvent.initTouchEvent(type, bubbles, cancelable, view, detail,
screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey,
touches, targetTouches, changedTouches,
scale, rotation);
} else {
Y.error('simulateTouchEvent(): No touch event simulation framework present for iOS, '+Y.UA.ios+'.');
}
} else {
Y.error('simulateTouchEvent(): Not supported agent yet, '+Y.UA.userAgent);
}
//fire the event
target.dispatchEvent(customEvent);
//} else if (Y.Lang.isObject(doc.createEventObject)){ // Windows Mobile/IE, support later
} else {
Y.error('simulateTouchEvent(): No event simulation framework present.');
}
}
/**
* Simulates the event or gesture with the given name on a target.
* @param {HTMLElement} target The DOM element that's the target of the event.
* @param {String} type The type of event or name of the supported gesture to simulate
* (i.e., "click", "doubletap", "flick").
* @param {Object} options (Optional) Extra options to copy onto the event object.
* For gestures, options are used to refine the gesture behavior.
* @return {void}
* @for Event
* @method simulate
* @static
*/
Y.Event.simulate = function(target, type, options){
options = options || {};
if (mouseEvents[type] || pointerEvents[type]){
simulateMouseEvent(target, type, options.bubbles,
options.cancelable, options.view, options.detail, options.screenX,
options.screenY, options.clientX, options.clientY, options.ctrlKey,
options.altKey, options.shiftKey, options.metaKey, options.button,
options.relatedTarget);
} else if (keyEvents[type]){
simulateKeyEvent(target, type, options.bubbles,
options.cancelable, options.view, options.ctrlKey,
options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode);
} else if (uiEvents[type]){
simulateUIEvent(target, type, options.bubbles,
options.cancelable, options.view, options.detail);
// touch low-level event simulation
} else if (touchEvents[type]) {
if((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.phantomjs) && !(Y.UA.chrome && Y.UA.chrome < 6)) {
simulateTouchEvent(target, type,
options.bubbles, options.cancelable, options.view, options.detail,
options.screenX, options.screenY, options.clientX, options.clientY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.touches, options.targetTouches, options.changedTouches,
options.scale, options.rotation);
} else {
Y.error("simulate(): Event '" + type + "' can't be simulated. Use gesture-simulate module instead.");
}
// ios gesture low-level event simulation (iOS v2+ only)
} else if(Y.UA.ios && Y.UA.ios >= 2.0 && gestureEvents[type]) {
simulateGestureEvent(target, type,
options.bubbles, options.cancelable, options.view, options.detail,
options.screenX, options.screenY, options.clientX, options.clientY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.scale, options.rotation);
// anything else
} else {
Y.error("simulate(): Event '" + type + "' can't be simulated.");
}
};
})();
}, 'patched-v3.11.0', {"requires": ["event-base"]});
YUI.add('event-synthetic', function (Y, NAME) {
/**
* Define new DOM events that can be subscribed to from Nodes.
*
* @module event
* @submodule event-synthetic
*/
var CustomEvent = Y.CustomEvent,
DOMMap = Y.Env.evt.dom_map,
toArray = Y.Array,
YLang = Y.Lang,
isObject = YLang.isObject,
isString = YLang.isString,
isArray = YLang.isArray,
query = Y.Selector.query,
noop = function () {};
/**
* The triggering mechanism used by SyntheticEvents.
*
* Implementers should not instantiate these directly. Use the Notifier
* provided to the event's implemented on(node, sub, notifier)
or
* delegate(node, sub, notifier, filter)
methods.
*
* @class SyntheticEvent.Notifier
* @constructor
* @param handle {EventHandle} the detach handle for the subscription to an
* internal custom event used to execute the callback passed to
* on(..) or delegate(..)
* @param emitFacade {Boolean} take steps to ensure the first arg received by
* the subscription callback is an event facade
* @private
* @since 3.2.0
*/
function Notifier(handle, emitFacade) {
this.handle = handle;
this.emitFacade = emitFacade;
}
/**
* Executes the subscription callback, passing the firing arguments as the
* first parameters to that callback. For events that are configured with
* emitFacade=true, it is common practice to pass the triggering DOMEventFacade
* as the first parameter. Barring a proper DOMEventFacade or EventFacade
* (from a CustomEvent), a new EventFacade will be generated. In that case, if
* fire() is called with a simple object, it will be mixed into the facade.
* Otherwise, the facade will be prepended to the callback parameters.
*
* For notifiers provided to delegate logic, the first argument should be an
* object with a "currentTarget" property to identify what object to
* default as 'this' in the callback. Typically this is gleaned from the
* DOMEventFacade or EventFacade, but if configured with emitFacade=false, an
* object must be provided. In that case, the object will be removed from the
* callback parameters.
*
* Additional arguments passed during event subscription will be
* automatically added after those passed to fire().
*
* @method fire
* @param e {EventFacade|DOMEventFacade|Object|any} (see description)
* @param arg* {any} additional arguments received by all subscriptions
* @private
*/
Notifier.prototype.fire = function (e) {
// first arg to delegate notifier should be an object with currentTarget
var args = toArray(arguments, 0, true),
handle = this.handle,
ce = handle.evt,
sub = handle.sub,
thisObj = sub.context,
delegate = sub.filter,
event = e || {},
ret;
if (this.emitFacade) {
if (!e || !e.preventDefault) {
event = ce._getFacade();
if (isObject(e) && !e.preventDefault) {
Y.mix(event, e, true);
args[0] = event;
} else {
args.unshift(event);
}
}
event.type = ce.type;
event.details = args.slice();
if (delegate) {
event.container = ce.host;
}
} else if (delegate && isObject(e) && e.currentTarget) {
args.shift();
}
sub.context = thisObj || event.currentTarget || ce.host;
ret = ce.fire.apply(ce, args);
sub.context = thisObj; // reset for future firing
// to capture callbacks that return false to stopPropagation.
// Useful for delegate implementations
return ret;
};
/**
* Manager object for synthetic event subscriptions to aggregate multiple synths on the
* same node without colliding with actual DOM subscription entries in the global map of
* DOM subscriptions. Also facilitates proper cleanup on page unload.
*
* @class SynthRegistry
* @constructor
* @param el {HTMLElement} the DOM element
* @param yuid {String} the yuid stamp for the element
* @param key {String} the generated id token used to identify an event type +
* element in the global DOM subscription map.
* @private
*/
function SynthRegistry(el, yuid, key) {
this.handles = [];
this.el = el;
this.key = key;
this.domkey = yuid;
}
SynthRegistry.prototype = {
constructor: SynthRegistry,
// A few object properties to fake the CustomEvent interface for page
// unload cleanup. DON'T TOUCH!
type : '_synth',
fn : noop,
capture : false,
/**
* Adds a subscription from the Notifier registry.
*
* @method register
* @param handle {EventHandle} the subscription
* @since 3.4.0
*/
register: function (handle) {
handle.evt.registry = this;
this.handles.push(handle);
},
/**
* Removes the subscription from the Notifier registry.
*
* @method _unregisterSub
* @param sub {Subscription} the subscription
* @since 3.4.0
*/
unregister: function (sub) {
var handles = this.handles,
events = DOMMap[this.domkey],
i;
for (i = handles.length - 1; i >= 0; --i) {
if (handles[i].sub === sub) {
handles.splice(i, 1);
break;
}
}
// Clean up left over objects when there are no more subscribers.
if (!handles.length) {
delete events[this.key];
if (!Y.Object.size(events)) {
delete DOMMap[this.domkey];
}
}
},
/**
* Used by the event system's unload cleanup process. When navigating
* away from the page, the event system iterates the global map of element
* subscriptions and detaches everything using detachAll(). Normally,
* the map is populated with custom events, so this object needs to
* at least support the detachAll method to duck type its way to
* cleanliness.
*
* @method detachAll
* @private
* @since 3.4.0
*/
detachAll : function () {
var handles = this.handles,
i = handles.length;
while (--i >= 0) {
handles[i].detach();
}
}
};
/**
* Wrapper class for the integration of new events into the YUI event
* infrastructure. Don't instantiate this object directly, use
* Y.Event.define(type, config)
. See that method for details.
*
* Properties that MAY or SHOULD be specified in the configuration are noted
* below and in the description of Y.Event.define
.
*
* @class SyntheticEvent
* @constructor
* @param cfg {Object} Implementation pieces and configuration
* @since 3.1.0
* @in event-synthetic
*/
function SyntheticEvent() {
this._init.apply(this, arguments);
}
Y.mix(SyntheticEvent, {
Notifier: Notifier,
SynthRegistry: SynthRegistry,
/**
* Returns the array of subscription handles for a node for the given event
* type. Passing true as the third argument will create a registry entry
* in the event system's DOM map to host the array if one doesn't yet exist.
*
* @method getRegistry
* @param node {Node} the node
* @param type {String} the event
* @param create {Boolean} create a registration entry to host a new array
* if one doesn't exist.
* @return {Array}
* @static
* @protected
* @since 3.2.0
*/
getRegistry: function (node, type, create) {
var el = node._node,
yuid = Y.stamp(el),
key = 'event:' + yuid + type + '_synth',
events = DOMMap[yuid];
if (create) {
if (!events) {
events = DOMMap[yuid] = {};
}
if (!events[key]) {
events[key] = new SynthRegistry(el, yuid, key);
}
}
return (events && events[key]) || null;
},
/**
* Alternate _delete()
method for the CustomEvent object
* created to manage SyntheticEvent subscriptions.
*
* @method _deleteSub
* @param sub {Subscription} the subscription to clean up
* @private
* @since 3.2.0
*/
_deleteSub: function (sub) {
if (sub && sub.fn) {
var synth = this.eventDef,
method = (sub.filter) ? 'detachDelegate' : 'detach';
this._subscribers = [];
if (CustomEvent.keepDeprecatedSubs) {
this.subscribers = {};
}
synth[method](sub.node, sub, this.notifier, sub.filter);
this.registry.unregister(sub);
delete sub.fn;
delete sub.node;
delete sub.context;
}
},
prototype: {
constructor: SyntheticEvent,
/**
* Construction logic for the event.
*
* @method _init
* @protected
*/
_init: function () {
var config = this.publishConfig || (this.publishConfig = {});
// The notification mechanism handles facade creation
this.emitFacade = ('emitFacade' in config) ?
config.emitFacade :
true;
config.emitFacade = false;
},
/**
* Implementers MAY provide this method definition.
*
* Implement this function if the event supports a different
* subscription signature. This function is used by both
* on()
and delegate()
. The second parameter
* indicates that the event is being subscribed via
* delegate()
.
*
* Implementations must remove extra arguments from the args list
* before returning. The required args for on()
* subscriptions are
* [type, callback, target, context, argN...]
*
* The required args for delegate()
* subscriptions are
*
* [type, callback, target, filter, context, argN...]
*
* The return value from this function will be stored on the
* subscription in the '_extra' property for reference elsewhere.
*
* @method processArgs
* @param args {Array} parmeters passed to Y.on(..) or Y.delegate(..)
* @param delegate {Boolean} true if the subscription is from Y.delegate
* @return {any}
*/
processArgs: noop,
/**
* Implementers MAY override this property.
*
* Whether to prevent multiple subscriptions to this event that are
* classified as being the same. By default, this means the subscribed
* callback is the same function. See the subMatch
* method. Setting this to true will impact performance for high volume
* events.
*
* @property preventDups
* @type {Boolean}
* @default false
*/
//preventDups : false,
/**
* Implementers SHOULD provide this method definition.
*
* Implementation logic for subscriptions done via node.on(type,
* fn)
or Y.on(type, fn, target)
. This
* function should set up the monitor(s) that will eventually fire the
* event. Typically this involves subscribing to at least one DOM
* event. It is recommended to store detach handles from any DOM
* subscriptions to make for easy cleanup in the detach
* method. Typically these handles are added to the sub
* object. Also for SyntheticEvents that leverage a single DOM
* subscription under the hood, it is recommended to pass the DOM event
* object to notifier.fire(e)
. (The event name on the
* object will be updated).
*
* @method on
* @param node {Node} the node the subscription is being applied to
* @param sub {Subscription} the object to track this subscription
* @param notifier {SyntheticEvent.Notifier} call notifier.fire(..) to
* trigger the execution of the subscribers
*/
on: noop,
/**
* Implementers SHOULD provide this method definition.
*
* Implementation logic for detaching subscriptions done via
* node.on(type, fn)
. This function should clean up any
* subscriptions made in the on()
phase.
*
* @method detach
* @param node {Node} the node the subscription was applied to
* @param sub {Subscription} the object tracking this subscription
* @param notifier {SyntheticEvent.Notifier} the Notifier used to
* trigger the execution of the subscribers
*/
detach: noop,
/**
* Implementers SHOULD provide this method definition.
*
* Implementation logic for subscriptions done via
* node.delegate(type, fn, filter)
or
* Y.delegate(type, fn, container, filter)
. Like with
* on()
above, this function should monitor the environment
* for the event being fired, and trigger subscription execution by
* calling notifier.fire(e)
.
*
* This function receives a fourth argument, which is the filter
* used to identify which Node's are of interest to the subscription.
* The filter will be either a boolean function that accepts a target
* Node for each hierarchy level as the event bubbles, or a selector
* string. To translate selector strings into filter functions, use
* Y.delegate.compileFilter(filter)
.
*
* @method delegate
* @param node {Node} the node the subscription is being applied to
* @param sub {Subscription} the object to track this subscription
* @param notifier {SyntheticEvent.Notifier} call notifier.fire(..) to
* trigger the execution of the subscribers
* @param filter {String|Function} Selector string or function that
* accepts an event object and returns null, a Node, or an
* array of Nodes matching the criteria for processing.
* @since 3.2.0
*/
delegate : noop,
/**
* Implementers SHOULD provide this method definition.
*
* Implementation logic for detaching subscriptions done via
* node.delegate(type, fn, filter)
or
* Y.delegate(type, fn, container, filter)
. This function
* should clean up any subscriptions made in the
* delegate()
phase.
*
* @method detachDelegate
* @param node {Node} the node the subscription was applied to
* @param sub {Subscription} the object tracking this subscription
* @param notifier {SyntheticEvent.Notifier} the Notifier used to
* trigger the execution of the subscribers
* @param filter {String|Function} Selector string or function that
* accepts an event object and returns null, a Node, or an
* array of Nodes matching the criteria for processing.
* @since 3.2.0
*/
detachDelegate : noop,
/**
* Sets up the boilerplate for detaching the event and facilitating the
* execution of subscriber callbacks.
*
* @method _on
* @param args {Array} array of arguments passed to
* Y.on(...)
or Y.delegate(...)
* @param delegate {Boolean} true if called from
* Y.delegate(...)
* @return {EventHandle} the detach handle for this subscription
* @private
* since 3.2.0
*/
_on: function (args, delegate) {
var handles = [],
originalArgs = args.slice(),
extra = this.processArgs(args, delegate),
selector = args[2],
method = delegate ? 'delegate' : 'on',
nodes, handle;
// Can't just use Y.all because it doesn't support window (yet?)
nodes = (isString(selector)) ?
query(selector) :
toArray(selector || Y.one(Y.config.win));
if (!nodes.length && isString(selector)) {
handle = Y.on('available', function () {
Y.mix(handle, Y[method].apply(Y, originalArgs), true);
}, selector);
return handle;
}
Y.Array.each(nodes, function (node) {
var subArgs = args.slice(),
filter;
node = Y.one(node);
if (node) {
if (delegate) {
filter = subArgs.splice(3, 1)[0];
}
// (type, fn, el, thisObj, ...) => (fn, thisObj, ...)
subArgs.splice(0, 4, subArgs[1], subArgs[3]);
if (!this.preventDups ||
!this.getSubs(node, args, null, true))
{
handles.push(this._subscribe(node, method, subArgs, extra, filter));
}
}
}, this);
return (handles.length === 1) ?
handles[0] :
new Y.EventHandle(handles);
},
/**
* Creates a new Notifier object for use by this event's
* on(...)
or delegate(...)
implementation
* and register the custom event proxy in the DOM system for cleanup.
*
* @method _subscribe
* @param node {Node} the Node hosting the event
* @param method {String} "on" or "delegate"
* @param args {Array} the subscription arguments passed to either
* Y.on(...)
or Y.delegate(...)
* after running through processArgs(args)
to
* normalize the argument signature
* @param extra {any} Extra data parsed from
* processArgs(args)
* @param filter {String|Function} the selector string or function
* filter passed to Y.delegate(...)
(not
* present when called from Y.on(...)
)
* @return {EventHandle}
* @private
* @since 3.2.0
*/
_subscribe: function (node, method, args, extra, filter) {
var dispatcher = new Y.CustomEvent(this.type, this.publishConfig),
handle = dispatcher.on.apply(dispatcher, args),
notifier = new Notifier(handle, this.emitFacade),
registry = SyntheticEvent.getRegistry(node, this.type, true),
sub = handle.sub;
sub.node = node;
sub.filter = filter;
if (extra) {
this.applyArgExtras(extra, sub);
}
Y.mix(dispatcher, {
eventDef : this,
notifier : notifier,
host : node, // I forget what this is for
currentTarget: node, // for generating facades
target : node, // for generating facades
el : node._node, // For category detach
_delete : SyntheticEvent._deleteSub
}, true);
handle.notifier = notifier;
registry.register(handle);
// Call the implementation's "on" or "delegate" method
this[method](node, sub, notifier, filter);
return handle;
},
/**
* Implementers MAY provide this method definition.
*
* Implement this function if you want extra data extracted during
* processArgs to be propagated to subscriptions on a per-node basis.
* That is to say, if you call Y.on('xyz', fn, xtra, 'div')
* the data returned from processArgs will be shared
* across the subscription objects for all the divs. If you want each
* subscription to receive unique information, do that processing
* here.
*
* The default implementation adds the data extracted by processArgs
* to the subscription object as sub._extra
.
*
* @method applyArgExtras
* @param extra {any} Any extra data extracted from processArgs
* @param sub {Subscription} the individual subscription
*/
applyArgExtras: function (extra, sub) {
sub._extra = extra;
},
/**
* Removes the subscription(s) from the internal subscription dispatch
* mechanism. See SyntheticEvent._deleteSub
.
*
* @method _detach
* @param args {Array} The arguments passed to
* node.detach(...)
* @private
* @since 3.2.0
*/
_detach: function (args) {
// Can't use Y.all because it doesn't support window (yet?)
// TODO: Does Y.all support window now?
var target = args[2],
els = (isString(target)) ?
query(target) : toArray(target),
node, i, len, handles, j;
// (type, fn, el, context, filter?) => (type, fn, context, filter?)
args.splice(2, 1);
for (i = 0, len = els.length; i < len; ++i) {
node = Y.one(els[i]);
if (node) {
handles = this.getSubs(node, args);
if (handles) {
for (j = handles.length - 1; j >= 0; --j) {
handles[j].detach();
}
}
}
}
},
/**
* Returns the detach handles of subscriptions on a node that satisfy a
* search/filter function. By default, the filter used is the
* subMatch
method.
*
* @method getSubs
* @param node {Node} the node hosting the event
* @param args {Array} the array of original subscription args passed
* to Y.on(...)
(before
* processArgs
* @param filter {Function} function used to identify a subscription
* for inclusion in the returned array
* @param first {Boolean} stop after the first match (used to check for
* duplicate subscriptions)
* @return {EventHandle[]} detach handles for the matching subscriptions
*/
getSubs: function (node, args, filter, first) {
var registry = SyntheticEvent.getRegistry(node, this.type),
handles = [],
allHandles, i, len, handle;
if (registry) {
allHandles = registry.handles;
if (!filter) {
filter = this.subMatch;
}
for (i = 0, len = allHandles.length; i < len; ++i) {
handle = allHandles[i];
if (filter.call(this, handle.sub, args)) {
if (first) {
return handle;
} else {
handles.push(allHandles[i]);
}
}
}
}
return handles.length && handles;
},
/**
* Implementers MAY override this to define what constitutes a
* "same" subscription. Override implementations should
* consider the lack of a comparator as a match, so calling
* getSubs()
with no arguments will return all subs.
*
* Compares a set of subscription arguments against a Subscription
* object to determine if they match. The default implementation
* compares the callback function against the second argument passed to
* Y.on(...)
or node.detach(...)
etc.
*
* @method subMatch
* @param sub {Subscription} the existing subscription
* @param args {Array} the calling arguments passed to
* Y.on(...)
etc.
* @return {Boolean} true if the sub can be described by the args
* present
* @since 3.2.0
*/
subMatch: function (sub, args) {
// Default detach cares only about the callback matching
return !args[1] || sub.fn === args[1];
}
}
}, true);
Y.SyntheticEvent = SyntheticEvent;
/**
* Defines a new event in the DOM event system. Implementers are
* responsible for monitoring for a scenario whereby the event is fired. A
* notifier object is provided to the functions identified below. When the
* criteria defining the event are met, call notifier.fire( [args] ); to
* execute event subscribers.
*
* The first parameter is the name of the event. The second parameter is a
* configuration object which define the behavior of the event system when the
* new event is subscribed to or detached from. The methods that should be
* defined in this configuration object are on
,
* detach
, delegate
, and detachDelegate
.
* You are free to define any other methods or properties needed to define your
* event. Be aware, however, that since the object is used to subclass
* SyntheticEvent, you should avoid method names used by SyntheticEvent unless
* your intention is to override the default behavior.
*
* This is a list of properties and methods that you can or should specify
* in the configuration object:
*
*
* on
* function (node, subscription, notifier)
The
* implementation logic for subscription. Any special setup you need to
* do to create the environment for the event being fired--E.g. native
* DOM event subscriptions. Store subscription related objects and
* state on the subscription
object. When the
* criteria have been met to fire the synthetic event, call
* notifier.fire(e)
. See Notifier's fire()
* method for details about what to pass as parameters.
*
* detach
* function (node, subscription, notifier)
The
* implementation logic for cleaning up a detached subscription. E.g.
* detach any DOM subscriptions added in on
.
*
* delegate
* function (node, subscription, notifier, filter)
The
* implementation logic for subscription via Y.delegate
or
* node.delegate
. The filter is typically either a selector
* string or a function. You can use
* Y.delegate.compileFilter(selectorString)
to create a
* filter function from a selector string if needed. The filter function
* expects an event object as input and should output either null, a
* matching Node, or an array of matching Nodes. Otherwise, this acts
* like on
DOM event subscriptions. Store subscription
* related objects and information on the subscription
* object. When the criteria have been met to fire the synthetic event,
* call notifier.fire(e)
as noted above.
*
* detachDelegate
* function (node, subscription, notifier)
The
* implementation logic for cleaning up a detached delegate subscription.
* E.g. detach any DOM delegate subscriptions added in
* delegate
.
*
* publishConfig
* (Object) The configuration object that will be used to instantiate
* the underlying CustomEvent. See Notifier's fire
method
* for details.
*
* processArgs
* function (argArray, fromDelegate)
Optional method
* to extract any additional arguments from the subscription
* signature. Using this allows on
or
* delegate
signatures like
* node.on("hover", overCallback,
* outCallback)
.
* When processing an atypical argument signature, make sure the
* args array is returned to the normal signature before returning
* from the function. For example, in the "hover" example
* above, the outCallback
needs to be splice
d
* out of the array. The expected signature of the args array for
* on()
subscriptions is:
*
* [type, callback, target, contextOverride, argN...]
*
* And for delegate()
:
*
* [type, callback, target, filter, contextOverride, argN...]
*
* where target
is the node the event is being
* subscribed for. You can see these signatures documented for
* Y.on()
and Y.delegate()
respectively.
* Whatever gets returned from the function will be stored on the
* subscription
object under
* subscription._extra
.
* subMatch
*
* function (sub, args)
Compares a set of
* subscription arguments against a Subscription object to determine
* if they match. The default implementation compares the callback
* function against the second argument passed to
* Y.on(...)
or node.detach(...)
etc.
*
*
*
* @method define
* @param type {String} the name of the event
* @param config {Object} the prototype definition for the new event (see above)
* @param force {Boolean} override an existing event (use with caution)
* @return {SyntheticEvent} the subclass implementation instance created to
* handle event subscriptions of this type
* @static
* @for Event
* @since 3.1.0
* @in event-synthetic
*/
Y.Event.define = function (type, config, force) {
var eventDef, Impl, synth;
if (type && type.type) {
eventDef = type;
force = config;
} else if (config) {
eventDef = Y.merge({ type: type }, config);
}
if (eventDef) {
if (force || !Y.Node.DOM_EVENTS[eventDef.type]) {
Impl = function () {
SyntheticEvent.apply(this, arguments);
};
Y.extend(Impl, SyntheticEvent, eventDef);
synth = new Impl();
type = synth.type;
Y.Node.DOM_EVENTS[type] = Y.Env.evt.plugins[type] = {
eventDef: synth,
on: function () {
return synth._on(toArray(arguments));
},
delegate: function () {
return synth._on(toArray(arguments), true);
},
detach: function () {
return synth._detach(toArray(arguments));
}
};
}
} else if (isString(type) || isArray(type)) {
Y.Array.each(toArray(type), function (t) {
Y.Node.DOM_EVENTS[t] = 1;
});
}
return synth;
};
}, 'patched-v3.11.0', {"requires": ["node-base", "event-custom-complex"]});
YUI.add('intl', function (Y, NAME) {
var _mods = {},
ROOT_LANG = "yuiRootLang",
ACTIVE_LANG = "yuiActiveLang",
NONE = [];
/**
* Provides utilities to support the management of localized resources (strings and formatting patterns).
*
* @module intl
*/
/**
* The Intl utility provides a central location for managing sets of localized resources (strings and formatting patterns).
*
* @class Intl
* @uses EventTarget
* @static
*/
Y.mix(Y.namespace("Intl"), {
/**
* Private method to retrieve the language hash for a given module.
*
* @method _mod
* @private
*
* @param {String} module The name of the module
* @return {Object} The hash of localized resources for the module, keyed by BCP language tag
*/
_mod : function(module) {
if (!_mods[module]) {
_mods[module] = {};
}
return _mods[module];
},
/**
* Sets the active language for the given module.
*
* Returns false on failure, which would happen if the language had not been registered through the add() method.
*
* @method setLang
*
* @param {String} module The module name.
* @param {String} lang The BCP 47 language tag.
* @return boolean true if successful, false if not.
*/
setLang : function(module, lang) {
var langs = this._mod(module),
currLang = langs[ACTIVE_LANG],
exists = !!langs[lang];
if (exists && lang !== currLang) {
langs[ACTIVE_LANG] = lang;
this.fire("intl:langChange", {module: module, prevVal: currLang, newVal: (lang === ROOT_LANG) ? "" : lang});
}
return exists;
},
/**
* Get the currently active language for the given module.
*
* @method getLang
*
* @param {String} module The module name.
* @return {String} The BCP 47 language tag.
*/
getLang : function(module) {
var lang = this._mod(module)[ACTIVE_LANG];
return (lang === ROOT_LANG) ? "" : lang;
},
/**
* Register a hash of localized resources for the given module and language
*
* @method add
*
* @param {String} module The module name.
* @param {String} lang The BCP 47 language tag.
* @param {Object} strings The hash of localized values, keyed by the string name.
*/
add : function(module, lang, strings) {
lang = lang || ROOT_LANG;
this._mod(module)[lang] = strings;
this.setLang(module, lang);
},
/**
* Gets the module's localized resources for the currently active language (as provided by the getLang method).
*
* Optionally, the localized resources for alternate languages which have been added to Intl (see the add method) can
* be retrieved by providing the BCP 47 language tag as the lang parameter.
*
* @method get
*
* @param {String} module The module name.
* @param {String} key Optional. A single resource key. If not provided, returns a copy (shallow clone) of all resources.
* @param {String} lang Optional. The BCP 47 language tag. If not provided, the module's currently active language is used.
* @return String | Object A copy of the module's localized resources, or a single value if key is provided.
*/
get : function(module, key, lang) {
var mod = this._mod(module),
strs;
lang = lang || mod[ACTIVE_LANG];
strs = mod[lang] || {};
return (key) ? strs[key] : Y.merge(strs);
},
/**
* Gets the list of languages for which localized resources are available for a given module, based on the module
* meta-data (part of loader). If loader is not on the page, returns an empty array.
*
* @method getAvailableLangs
* @param {String} module The name of the module
* @return {Array} The array of languages available.
*/
getAvailableLangs : function(module) {
var loader = Y.Env._loader,
mod = loader && loader.moduleInfo[module],
langs = mod && mod.lang;
return (langs) ? langs.concat() : NONE;
}
});
Y.augment(Y.Intl, Y.EventTarget);
/**
* Notification event to indicate when the lang for a module has changed. There is no default behavior associated with this event,
* so the on and after moments are equivalent.
*
* @event intl:langChange
* @param {EventFacade} e The event facade
* The event facade contains:
*
* module The name of the module for which the language changed
* newVal The new language tag
* prevVal The current language tag
*
*/
Y.Intl.publish("intl:langChange", {emitFacade:true});
}, 'patched-v3.11.0', {"requires": ["intl-base", "event-custom"]});
YUI.add('io-base', function (Y, NAME) {
/**
Base IO functionality. Provides basic XHR transport support.
@module io
@submodule io-base
@for IO
**/
var // List of events that comprise the IO event lifecycle.
EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'],
// Whitelist of used XHR response object properties.
XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'],
win = Y.config.win,
uid = 0;
/**
The IO class is a utility that brokers HTTP requests through a simplified
interface. Specifically, it allows JavaScript to make HTTP requests to
a resource without a page reload. The underlying transport for making
same-domain requests is the XMLHttpRequest object. IO can also use
Flash, if specified as a transport, for cross-domain requests.
@class IO
@constructor
@param {Object} config Object of EventTarget's publish method configurations
used to configure IO's events.
**/
function IO (config) {
var io = this;
io._uid = 'io:' + uid++;
io._init(config);
Y.io._map[io._uid] = io;
}
IO.prototype = {
//--------------------------------------
// Properties
//--------------------------------------
/**
* A counter that increments for each transaction.
*
* @property _id
* @private
* @type {Number}
*/
_id: 0,
/**
* Object of IO HTTP headers sent with each transaction.
*
* @property _headers
* @private
* @type {Object}
*/
_headers: {
'X-Requested-With' : 'XMLHttpRequest'
},
/**
* Object that stores timeout values for any transaction with a defined
* "timeout" configuration property.
*
* @property _timeout
* @private
* @type {Object}
*/
_timeout: {},
//--------------------------------------
// Methods
//--------------------------------------
_init: function(config) {
var io = this, i, len;
io.cfg = config || {};
Y.augment(io, Y.EventTarget);
for (i = 0, len = EVENTS.length; i < len; ++i) {
// Publish IO global events with configurations, if any.
// IO global events are set to broadcast by default.
// These events use the "io:" namespace.
io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config));
// Publish IO transaction events with configurations, if
// any. These events use the "io-trn:" namespace.
io.publish('io-trn:' + EVENTS[i], config);
}
},
/**
* Method that creates a unique transaction object for each request.
*
* @method _create
* @private
* @param {Object} cfg Configuration object subset to determine if
* the transaction is an XDR or file upload,
* requiring an alternate transport.
* @param {Number} id Transaction id
* @return {Object} The transaction object
*/
_create: function(config, id) {
var io = this,
transaction = {
id : Y.Lang.isNumber(id) ? id : io._id++,
uid: io._uid
},
alt = config.xdr ? config.xdr.use : null,
form = config.form && config.form.upload ? 'iframe' : null,
use;
if (alt === 'native') {
// Non-IE and IE >= 10 can use XHR level 2 and not rely on an
// external transport.
alt = Y.UA.ie && !SUPPORTS_CORS ? 'xdr' : null;
// Prevent "pre-flight" OPTIONS request by removing the
// `X-Requested-With` HTTP header from CORS requests. This header
// can be added back on a per-request basis, if desired.
io.setHeader('X-Requested-With');
}
use = alt || form;
transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) :
Y.merge(Y.IO.defaultTransport(), transaction);
if (transaction.notify) {
config.notify = function (e, t, c) { io.notify(e, t, c); };
}
if (!use) {
if (win && win.FormData && config.data instanceof win.FormData) {
transaction.c.upload.onprogress = function (e) {
io.progress(transaction, e, config);
};
transaction.c.onload = function (e) {
io.load(transaction, e, config);
};
transaction.c.onerror = function (e) {
io.error(transaction, e, config);
};
transaction.upload = true;
}
}
return transaction;
},
_destroy: function(transaction) {
if (win && !transaction.notify && !transaction.xdr) {
if (XHR && !transaction.upload) {
transaction.c.onreadystatechange = null;
} else if (transaction.upload) {
transaction.c.upload.onprogress = null;
transaction.c.onload = null;
transaction.c.onerror = null;
} else if (Y.UA.ie && !transaction.e) {
// IE, when using XMLHttpRequest as an ActiveX Object, will throw
// a "Type Mismatch" error if the event handler is set to "null".
transaction.c.abort();
}
}
transaction = transaction.c = null;
},
/**
* Method for creating and firing events.
*
* @method _evt
* @private
* @param {String} eventName Event to be published.
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration data subset for event subscription.
*/
_evt: function(eventName, transaction, config) {
var io = this, params,
args = config['arguments'],
emitFacade = io.cfg.emitFacade,
globalEvent = "io:" + eventName,
trnEvent = "io-trn:" + eventName;
// Workaround for #2532107
this.detach(trnEvent);
if (transaction.e) {
transaction.c = { status: 0, statusText: transaction.e };
}
// Fire event with parameters or an Event Facade.
params = [ emitFacade ?
{
id: transaction.id,
data: transaction.c,
cfg: config,
'arguments': args
} :
transaction.id
];
if (!emitFacade) {
if (eventName === EVENTS[0] || eventName === EVENTS[2]) {
if (args) {
params.push(args);
}
} else {
if (transaction.evt) {
params.push(transaction.evt);
} else {
params.push(transaction.c);
}
if (args) {
params.push(args);
}
}
}
params.unshift(globalEvent);
// Fire global events.
io.fire.apply(io, params);
// Fire transaction events, if receivers are defined.
if (config.on) {
params[0] = trnEvent;
io.once(trnEvent, config.on[eventName], config.context || Y);
io.fire.apply(io, params);
}
},
/**
* Fires event "io:start" and creates, fires a transaction-specific
* start event, if `config.on.start` is defined.
*
* @method start
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
start: function(transaction, config) {
/**
* Signals the start of an IO request.
* @event io:start
*/
this._evt(EVENTS[0], transaction, config);
},
/**
* Fires event "io:complete" and creates, fires a
* transaction-specific "complete" event, if config.on.complete is
* defined.
*
* @method complete
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
complete: function(transaction, config) {
/**
* Signals the completion of the request-response phase of a
* transaction. Response status and data are accessible, if
* available, in this event.
* @event io:complete
*/
this._evt(EVENTS[1], transaction, config);
},
/**
* Fires event "io:end" and creates, fires a transaction-specific "end"
* event, if config.on.end is defined.
*
* @method end
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
end: function(transaction, config) {
/**
* Signals the end of the transaction lifecycle.
* @event io:end
*/
this._evt(EVENTS[2], transaction, config);
this._destroy(transaction);
},
/**
* Fires event "io:success" and creates, fires a transaction-specific
* "success" event, if config.on.success is defined.
*
* @method success
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
success: function(transaction, config) {
/**
* Signals an HTTP response with status in the 2xx range.
* Fires after io:complete.
* @event io:success
*/
this._evt(EVENTS[3], transaction, config);
this.end(transaction, config);
},
/**
* Fires event "io:failure" and creates, fires a transaction-specific
* "failure" event, if config.on.failure is defined.
*
* @method failure
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
failure: function(transaction, config) {
/**
* Signals an HTTP response with status outside of the 2xx range.
* Fires after io:complete.
* @event io:failure
*/
this._evt(EVENTS[4], transaction, config);
this.end(transaction, config);
},
/**
* Fires event "io:progress" and creates, fires a transaction-specific
* "progress" event -- for XMLHttpRequest file upload -- if
* config.on.progress is defined.
*
* @method progress
* @param {Object} transaction Transaction object.
* @param {Object} progress event.
* @param {Object} config Configuration object for the transaction.
*/
progress: function(transaction, e, config) {
/**
* Signals the interactive state during a file upload transaction.
* This event fires after io:start and before io:complete.
* @event io:progress
*/
transaction.evt = e;
this._evt(EVENTS[5], transaction, config);
},
/**
* Fires event "io:complete" and creates, fires a transaction-specific
* "complete" event -- for XMLHttpRequest file upload -- if
* config.on.complete is defined.
*
* @method load
* @param {Object} transaction Transaction object.
* @param {Object} load event.
* @param {Object} config Configuration object for the transaction.
*/
load: function (transaction, e, config) {
transaction.evt = e.target;
this._evt(EVENTS[1], transaction, config);
},
/**
* Fires event "io:failure" and creates, fires a transaction-specific
* "failure" event -- for XMLHttpRequest file upload -- if
* config.on.failure is defined.
*
* @method error
* @param {Object} transaction Transaction object.
* @param {Object} error event.
* @param {Object} config Configuration object for the transaction.
*/
error: function (transaction, e, config) {
transaction.evt = e;
this._evt(EVENTS[4], transaction, config);
},
/**
* Retry an XDR transaction, using the Flash tranport, if the native
* transport fails.
*
* @method _retry
* @private
* @param {Object} transaction Transaction object.
* @param {String} uri Qualified path to transaction resource.
* @param {Object} config Configuration object for the transaction.
*/
_retry: function(transaction, uri, config) {
this._destroy(transaction);
config.xdr.use = 'flash';
return this.send(uri, config, transaction.id);
},
/**
* Method that concatenates string data for HTTP GET transactions.
*
* @method _concat
* @private
* @param {String} uri URI or root data.
* @param {String} data Data to be concatenated onto URI.
* @return {String}
*/
_concat: function(uri, data) {
var fragment = '',
split;
if (uri.indexOf('#') !== -1) {
split = uri.split('#');
uri = split[0];
fragment = '#' + split[1];
}
uri += (uri.indexOf('?') === -1 ? '?' : '&') + data;
return uri + fragment;
},
/**
* Stores default client headers for all transactions. If a label is
* passed with no value argument, the header will be deleted.
*
* @method setHeader
* @param {String} name HTTP header
* @param {String} value HTTP header value
*/
setHeader: function(name, value) {
if (value) {
this._headers[name] = value;
} else {
delete this._headers[name];
}
},
/**
* Method that sets all HTTP headers to be sent in a transaction.
*
* @method _setHeaders
* @private
* @param {Object} transaction - XHR instance for the specific transaction.
* @param {Object} headers - HTTP headers for the specific transaction, as
* defined in the configuration object passed to YUI.io().
*/
_setHeaders: function(transaction, headers) {
headers = Y.merge(this._headers, headers);
Y.Object.each(headers, function(value, name) {
if (value !== 'disable') {
transaction.setRequestHeader(name, headers[name]);
}
});
},
/**
* Starts timeout count if the configuration object has a defined
* timeout property.
*
* @method _startTimeout
* @private
* @param {Object} transaction Transaction object generated by _create().
* @param {Object} timeout Timeout in milliseconds.
*/
_startTimeout: function(transaction, timeout) {
var io = this;
io._timeout[transaction.id] = setTimeout(function() {
io._abort(transaction, 'timeout');
}, timeout);
},
/**
* Clears the timeout interval started by _startTimeout().
*
* @method _clearTimeout
* @private
* @param {Number} id - Transaction id.
*/
_clearTimeout: function(id) {
clearTimeout(this._timeout[id]);
delete this._timeout[id];
},
/**
* Method that determines if a transaction response qualifies as success
* or failure, based on the response HTTP status code, and fires the
* appropriate success or failure events.
*
* @method _result
* @private
* @static
* @param {Object} transaction Transaction object generated by _create().
* @param {Object} config Configuration object passed to io().
*/
_result: function(transaction, config) {
var status;
// Firefox will throw an exception if attempting to access
// an XHR object's status property, after a request is aborted.
try {
status = transaction.c.status;
} catch(e) {
status = 0;
}
// IE reports HTTP 204 as HTTP 1223.
if (status >= 200 && status < 300 || status === 304 || status === 1223) {
this.success(transaction, config);
} else {
this.failure(transaction, config);
}
},
/**
* Event handler bound to onreadystatechange.
*
* @method _rS
* @private
* @param {Object} transaction Transaction object generated by _create().
* @param {Object} config Configuration object passed to YUI.io().
*/
_rS: function(transaction, config) {
var io = this;
if (transaction.c.readyState === 4) {
if (config.timeout) {
io._clearTimeout(transaction.id);
}
// Yield in the event of request timeout or abort.
setTimeout(function() {
io.complete(transaction, config);
io._result(transaction, config);
}, 0);
}
},
/**
* Terminates a transaction due to an explicit abort or timeout.
*
* @method _abort
* @private
* @param {Object} transaction Transaction object generated by _create().
* @param {String} type Identifies timed out or aborted transaction.
*/
_abort: function(transaction, type) {
if (transaction && transaction.c) {
transaction.e = type;
transaction.c.abort();
}
},
/**
* Requests a transaction. `send()` is implemented as `Y.io()`. Each
* transaction may include a configuration object. Its properties are:
*
*
* method
* HTTP method verb (e.g., GET or POST). If this property is not
* not defined, the default value will be GET.
*
* data
* This is the name-value string that will be sent as the
* transaction data. If the request is HTTP GET, the data become
* part of querystring. If HTTP POST, the data are sent in the
* message body.
*
* xdr
* Defines the transport to be used for cross-domain requests.
* By setting this property, the transaction will use the specified
* transport instead of XMLHttpRequest. The properties of the
* transport object are:
*
* use
* The transport to be used: 'flash' or 'native'
* dataType
* Set the value to 'XML' if that is the expected response
* content type.
* credentials
* Set the value to 'true' to set XHR.withCredentials property to true.
*
*
* form
* Form serialization configuration object. Its properties are:
*
* id
* Node object or id of HTML form
* useDisabled
* `true` to also serialize disabled form field values
* (defaults to `false`)
*
*
* on
* Assigns transaction event subscriptions. Available events are:
*
* start
* Fires when a request is sent to a resource.
* complete
* Fires when the transaction is complete.
* success
* Fires when the HTTP response status is within the 2xx
* range.
* failure
* Fires when the HTTP response status is outside the 2xx
* range, if an exception occurs, if the transation is aborted,
* or if the transaction exceeds a configured `timeout`.
* end
* Fires at the conclusion of the transaction
* lifecycle, after `success` or `failure`.
*
*
* Callback functions for `start` and `end` receive the id of the
* transaction as a first argument. For `complete`, `success`, and
* `failure`, callbacks receive the id and the response object
* (usually the XMLHttpRequest instance). If the `arguments`
* property was included in the configuration object passed to
* `Y.io()`, the configured data will be passed to all callbacks as
* the last argument.
*
*
* sync
* Pass `true` to make a same-domain transaction synchronous.
* CAVEAT : This will negatively impact the user
* experience. Have a very good reason if you intend to use
* this.
*
* context
* The "`this'" object for all configured event handlers. If a
* specific context is needed for individual callbacks, bind the
* callback to a context using `Y.bind()`.
*
* headers
* Object map of transaction headers to send to the server. The
* object keys are the header names and the values are the header
* values.
*
* timeout
* Millisecond threshold for the transaction before being
* automatically aborted.
*
* arguments
* User-defined data passed to all registered event handlers.
* This value is available as the second argument in the "start" and
* "end" event handlers. It is the third argument in the "complete",
* "success", and "failure" event handlers. Be sure to quote
* this property name in the transaction configuration as
* "arguments" is a reserved word in JavaScript (e.g.
* `Y.io({ ..., "arguments": stuff })`).
*
*
* @method send
* @public
* @param {String} uri Qualified path to transaction resource.
* @param {Object} config Configuration object for the transaction.
* @param {Number} id Transaction id, if already set.
* @return {Object}
*/
send: function(uri, config, id) {
var transaction, method, i, len, sync, data,
io = this,
u = uri,
response = {};
config = config ? Y.Object(config) : {};
transaction = io._create(config, id);
method = config.method ? config.method.toUpperCase() : 'GET';
sync = config.sync;
data = config.data;
// Serialize a map object into a key-value string using
// querystring-stringify-simple.
if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) {
if (Y.QueryString && Y.QueryString.stringify) {
config.data = data = Y.QueryString.stringify(data);
} else {
}
}
if (config.form) {
if (config.form.upload) {
// This is a file upload transaction, calling
// upload() in io-upload-iframe.
return io.upload(transaction, uri, config);
} else {
// Serialize HTML form data into a key-value string.
data = io._serialize(config.form, data);
}
}
// Convert falsy values to an empty string. This way IE can't be
// rediculous and translate `undefined` to "undefined".
data || (data = '');
if (data) {
switch (method) {
case 'GET':
case 'HEAD':
case 'DELETE':
u = io._concat(u, data);
data = '';
break;
case 'POST':
case 'PUT':
// If Content-Type is defined in the configuration object, or
// or as a default header, it will be used instead of
// 'application/x-www-form-urlencoded; charset=UTF-8'
config.headers = Y.merge({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}, config.headers);
break;
}
}
if (transaction.xdr) {
// Route data to io-xdr module for flash and XDomainRequest.
return io.xdr(u, transaction, config);
}
else if (transaction.notify) {
// Route data to custom transport
return transaction.c.send(transaction, uri, config);
}
if (!sync && !transaction.upload) {
transaction.c.onreadystatechange = function() {
io._rS(transaction, config);
};
}
try {
// Determine if request is to be set as
// synchronous or asynchronous.
transaction.c.open(method, u, !sync, config.username || null, config.password || null);
io._setHeaders(transaction.c, config.headers || {});
io.start(transaction, config);
// Will work only in browsers that implement the
// Cross-Origin Resource Sharing draft.
if (config.xdr && config.xdr.credentials && SUPPORTS_CORS) {
transaction.c.withCredentials = true;
}
// Using "null" with HTTP POST will result in a request
// with no Content-Length header defined.
transaction.c.send(data);
if (sync) {
// Create a response object for synchronous transactions,
// mixing id and arguments properties with the xhr
// properties whitelist.
for (i = 0, len = XHR_PROPS.length; i < len; ++i) {
response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]];
}
response.getAllResponseHeaders = function() {
return transaction.c.getAllResponseHeaders();
};
response.getResponseHeader = function(name) {
return transaction.c.getResponseHeader(name);
};
io.complete(transaction, config);
io._result(transaction, config);
return response;
}
} catch(e) {
if (transaction.xdr) {
// This exception is usually thrown by browsers
// that do not support XMLHttpRequest Level 2.
// Retry the request with the XDR transport set
// to 'flash'. If the Flash transport is not
// initialized or available, the transaction
// will resolve to a transport error.
return io._retry(transaction, uri, config);
} else {
io.complete(transaction, config);
io._result(transaction, config);
}
}
// If config.timeout is defined, and the request is standard XHR,
// initialize timeout polling.
if (config.timeout) {
io._startTimeout(transaction, config.timeout);
}
return {
id: transaction.id,
abort: function() {
return transaction.c ? io._abort(transaction, 'abort') : false;
},
isInProgress: function() {
return transaction.c ? (transaction.c.readyState % 4) : false;
},
io: io
};
}
};
/**
Method for initiating an ajax call. The first argument is the url end
point for the call. The second argument is an object to configure the
transaction and attach event subscriptions. The configuration object
supports the following properties:
method
HTTP method verb (e.g., GET or POST). If this property is not
not defined, the default value will be GET.
data
This is the name-value string that will be sent as the
transaction data. If the request is HTTP GET, the data become
part of querystring. If HTTP POST, the data are sent in the
message body.
xdr
Defines the transport to be used for cross-domain requests.
By setting this property, the transaction will use the specified
transport instead of XMLHttpRequest. The properties of the
transport object are:
use
The transport to be used: 'flash' or 'native'
dataType
Set the value to 'XML' if that is the expected response
content type.
form
Form serialization configuration object. Its properties are:
id
Node object or id of HTML form
useDisabled
`true` to also serialize disabled form field values
(defaults to `false`)
on
Assigns transaction event subscriptions. Available events are:
start
Fires when a request is sent to a resource.
complete
Fires when the transaction is complete.
success
Fires when the HTTP response status is within the 2xx
range.
failure
Fires when the HTTP response status is outside the 2xx
range, if an exception occurs, if the transation is aborted,
or if the transaction exceeds a configured `timeout`.
end
Fires at the conclusion of the transaction
lifecycle, after `success` or `failure`.
Callback functions for `start` and `end` receive the id of the
transaction as a first argument. For `complete`, `success`, and
`failure`, callbacks receive the id and the response object
(usually the XMLHttpRequest instance). If the `arguments`
property was included in the configuration object passed to
`Y.io()`, the configured data will be passed to all callbacks as
the last argument.
sync
Pass `true` to make a same-domain transaction synchronous.
CAVEAT : This will negatively impact the user
experience. Have a very good reason if you intend to use
this.
context
The "`this'" object for all configured event handlers. If a
specific context is needed for individual callbacks, bind the
callback to a context using `Y.bind()`.
headers
Object map of transaction headers to send to the server. The
object keys are the header names and the values are the header
values.
timeout
Millisecond threshold for the transaction before being
automatically aborted.
arguments
User-defined data passed to all registered event handlers.
This value is available as the second argument in the "start" and
"end" event handlers. It is the third argument in the "complete",
"success", and "failure" event handlers. Be sure to quote
this property name in the transaction configuration as
"arguments" is a reserved word in JavaScript (e.g.
`Y.io({ ..., "arguments": stuff })`).
@method io
@static
@param {String} url qualified path to transaction resource.
@param {Object} config configuration object for the transaction.
@return {Object}
@for YUI
**/
Y.io = function(url, config) {
// Calling IO through the static interface will use and reuse
// an instance of IO.
var transaction = Y.io._map['io:0'] || new IO();
return transaction.send.apply(transaction, [url, config]);
};
/**
Method for setting and deleting IO HTTP headers to be sent with every
request.
Hosted as a property on the `io` function (e.g. `Y.io.header`).
@method header
@param {String} name HTTP header
@param {String} value HTTP header value
@static
**/
Y.io.header = function(name, value) {
// Calling IO through the static interface will use and reuse
// an instance of IO.
var transaction = Y.io._map['io:0'] || new IO();
transaction.setHeader(name, value);
};
Y.IO = IO;
// Map of all IO instances created.
Y.io._map = {};
var XHR = win && win.XMLHttpRequest,
XDR = win && win.XDomainRequest,
AX = win && win.ActiveXObject,
// Checks for the presence of the `withCredentials` in an XHR instance
// object, which will be present if the environment supports CORS.
SUPPORTS_CORS = XHR && 'withCredentials' in (new XMLHttpRequest());
Y.mix(Y.IO, {
/**
* The ID of the default IO transport, defaults to `xhr`
* @property _default
* @type {String}
* @static
*/
_default: 'xhr',
/**
*
* @method defaultTransport
* @static
* @param {String} [id] The transport to set as the default, if empty a new transport is created.
* @return {Object} The transport object with a `send` method
*/
defaultTransport: function(id) {
if (id) {
Y.IO._default = id;
} else {
var o = {
c: Y.IO.transports[Y.IO._default](),
notify: Y.IO._default === 'xhr' ? false : true
};
return o;
}
},
/**
* An object hash of custom transports available to IO
* @property transports
* @type {Object}
* @static
*/
transports: {
xhr: function () {
return XHR ? new XMLHttpRequest() :
AX ? new ActiveXObject('Microsoft.XMLHTTP') : null;
},
xdr: function () {
return XDR ? new XDomainRequest() : null;
},
iframe: function () { return {}; },
flash: null,
nodejs: null
},
/**
* Create a custom transport of type and return it's object
* @method customTransport
* @param {String} id The id of the transport to create.
* @static
*/
customTransport: function(id) {
var o = { c: Y.IO.transports[id]() };
o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true;
return o;
}
});
Y.mix(Y.IO.prototype, {
/**
* Fired from the notify method of the transport which in turn fires
* the event on the IO object.
* @method notify
* @param {String} event The name of the event
* @param {Object} transaction The transaction object
* @param {Object} config The configuration object for this transaction
*/
notify: function(event, transaction, config) {
var io = this;
switch (event) {
case 'timeout':
case 'abort':
case 'transport error':
transaction.c = { status: 0, statusText: event };
event = 'failure';
default:
io[event].apply(io, [transaction, config]);
}
}
});
}, 'patched-v3.11.0', {"requires": ["event-custom-base", "querystring-stringify-simple"]});
YUI.add('io-form', function (Y, NAME) {
/**
* Extends IO to enable HTML form data serialization, when specified
* in the transaction's configuration object.
* @module io
* @submodule io-form
* @for IO
*/
var eUC = encodeURIComponent;
/**
* Enumerate through an HTML form's elements collection
* and return a string comprised of key-value pairs.
*
* @method stringify
* @static
* @param {Node|String} form YUI form node or HTML form id
* @param {Object} [options] Configuration options.
* @param {Boolean} [options.useDisabled=false] Whether to include disabled fields.
* @param {Object|String} [options.extra] Extra values to include. May be a query string or an object with key/value pairs.
* @return {String}
*/
Y.IO.stringify = function(form, options) {
options = options || {};
var s = Y.IO.prototype._serialize({
id: form,
useDisabled: options.useDisabled
},
options.extra && typeof options.extra === 'object' ? Y.QueryString.stringify(options.extra) : options.extra);
return s;
};
Y.mix(Y.IO.prototype, {
/**
* Enumerate through an HTML form's elements collection
* and return a string comprised of key-value pairs.
*
* @method _serialize
* @private
* @param {Object} c
* @param {String|Element} c.id YUI form node or HTML form id
* @param {Boolean} c.useDisabled `true` to include disabled fields
* @param {String} s Key-value data defined in the configuration object.
* @return {String}
*/
_serialize: function(c, s) {
var data = [],
df = c.useDisabled || false,
item = 0,
id = (typeof c.id === 'string') ? c.id : c.id.getAttribute('id'),
e, f, n, v, d, i, il, j, jl, o;
if (!id) {
id = Y.guid('io:');
c.id.setAttribute('id', id);
}
f = Y.config.doc.getElementById(id);
if (!f || !f.elements) {
return s || '';
}
// Iterate over the form elements collection to construct the
// label-value pairs.
for (i = 0, il = f.elements.length; i < il; ++i) {
e = f.elements[i];
d = e.disabled;
n = e.name;
if (df ? n : n && !d) {
n = eUC(n) + '=';
v = eUC(e.value);
switch (e.type) {
// Safari, Opera, FF all default options.value from .text if
// value attribute not specified in markup
case 'select-one':
if (e.selectedIndex > -1) {
o = e.options[e.selectedIndex];
data[item++] = n + eUC(o.attributes.value && o.attributes.value.specified ? o.value : o.text);
}
break;
case 'select-multiple':
if (e.selectedIndex > -1) {
for (j = e.selectedIndex, jl = e.options.length; j < jl; ++j) {
o = e.options[j];
if (o.selected) {
data[item++] = n + eUC(o.attributes.value && o.attributes.value.specified ? o.value : o.text);
}
}
}
break;
case 'radio':
case 'checkbox':
if (e.checked) {
data[item++] = n + v;
}
break;
case 'file':
// stub case as XMLHttpRequest will only send the file path as a string.
case undefined:
// stub case for fieldset element which returns undefined.
case 'reset':
// stub case for input type reset button.
case 'button':
// stub case for input type button elements.
break;
case 'submit':
default:
data[item++] = n + v;
}
}
}
if (s) {
data[item++] = s;
}
return data.join('&');
}
}, true);
}, 'patched-v3.11.0', {"requires": ["io-base", "node-base"]});
YUI.add('io-queue', function (Y, NAME) {
/**
Extends IO to implement Queue for synchronous
transaction processing.
@module io
@submodule io-queue
@for IO
**/
var io = Y.io._map['io:0'] || new Y.IO();
Y.mix(Y.IO.prototype, {
/**
* Array of transactions queued for processing
*
* @property _q
* @private
* @static
* @type {Object}
*/
_q: new Y.Queue(),
_qActiveId: null,
_qInit: false,
/**
* Property to determine whether the queue is set to
* 1 (active) or 0 (inactive). When inactive, transactions
* will be stored in the queue until the queue is set to active.
*
* @property _qState
* @private
* @static
* @type {Number}
*/
_qState: 1,
/**
* Method Process the first transaction from the
* queue in FIFO order.
*
* @method _qShift
* @private
* @static
*/
_qShift: function() {
var io = this,
o = io._q.next();
io._qActiveId = o.id;
io._qState = 0;
io.send(o.uri, o.cfg, o.id);
},
/**
* Method for queueing a transaction before the request is sent to the
* resource, to ensure sequential processing.
*
* @method queue
* @static
* @return {Object}
*/
queue: function(uri, c) {
var io = this,
o = { uri: uri, cfg:c, id: this._id++ };
if(!io._qInit) {
Y.on('io:complete', function(id, o) { io._qNext(id); }, io);
io._qInit = true;
}
io._q.add(o);
if (io._qState === 1) {
io._qShift();
}
return o;
},
_qNext: function(id) {
var io = this;
io._qState = 1;
if (io._qActiveId === id && io._q.size() > 0) {
io._qShift();
}
},
/**
* Method for promoting a transaction to the top of the queue.
*
* @method promote
* @static
*/
qPromote: function(o) {
this._q.promote(o);
},
/**
* Method for removing a specific, pending transaction from
* the queue.
*
* @method remove
* @private
* @static
*/
qRemove: function(o) {
this._q.remove(o);
},
/**
* Method for cancel all pending transaction from
* the queue.
*
* @method empty
* @static
* @since 3.7.3
*/
qEmpty: function() {
this._q = new Y.Queue();
},
qStart: function() {
var io = this;
io._qState = 1;
if (io._q.size() > 0) {
io._qShift();
}
},
/**
* Method for setting queue processing to inactive.
* Transaction requests to YUI.io.queue() will be stored in the queue, but
* not processed until the queue is reset to "active".
*
* @method _stop
* @private
* @static
*/
qStop: function() {
this._qState = 0;
},
/**
* Method to query the current size of the queue.
*
* @method _size
* @private
* @static
* @return {Number}
*/
qSize: function() {
return this._q.size();
}
}, true);
function _queue(u, c) {
return io.queue.apply(io, [u, c]);
}
_queue.start = function () { io.qStart(); };
_queue.stop = function () { io.qStop(); };
_queue.promote = function (o) { io.qPromote(o); };
_queue.remove = function (o) { io.qRemove(o); };
_queue.size = function () { io.qSize(); };
_queue.empty = function () { io.qEmpty(); };
Y.io.queue = _queue;
}, 'patched-v3.11.0', {"requires": ["io-base", "queue-promote"]});
YUI.add('io-upload-iframe', function (Y, NAME) {
/**
Extends the IO to enable file uploads, with HTML forms
using an iframe as the transport medium.
@module io
@submodule io-upload-iframe
@for IO
**/
var w = Y.config.win,
d = Y.config.doc,
_std = (d.documentMode && d.documentMode >= 8),
_d = decodeURIComponent,
_end = Y.IO.prototype.end;
/**
* Creates the iframe transported used in file upload
* transactions, and binds the response event handler.
*
* @method _cFrame
* @private
* @param {Object} o Transaction object generated by _create().
* @param {Object} c Configuration object passed to YUI.io().
* @param {Object} io
*/
function _cFrame(o, c, io) {
var i = Y.Node.create('');
i._node.style.position = 'absolute';
i._node.style.top = '-1000px';
i._node.style.left = '-1000px';
Y.one('body').appendChild(i);
// Bind the onload handler to the iframe to detect the file upload response.
Y.on("load", function() { io._uploadComplete(o, c); }, '#io_iframe' + o.id);
}
/**
* Removes the iframe transport used in the file upload
* transaction.
*
* @method _dFrame
* @private
* @param {Number} id The transaction ID used in the iframe's creation.
*/
function _dFrame(id) {
Y.Event.purgeElement('#io_iframe' + id, false);
Y.one('body').removeChild(Y.one('#io_iframe' + id));
}
Y.mix(Y.IO.prototype, {
/**
* Parses the POST data object and creates hidden form elements
* for each key-value, and appends them to the HTML form object.
* @method appendData
* @private
* @static
* @param {Object} f HTML form object.
* @param {String} s The key-value POST data.
* @return {Array} o Array of created fields.
*/
_addData: function(f, s) {
// Serialize an object into a key-value string using
// querystring-stringify-simple.
if (Y.Lang.isObject(s)) {
s = Y.QueryString.stringify(s);
}
var o = [],
m = s.split('='),
i, l;
for (i = 0, l = m.length - 1; i < l; i++) {
var name = _d(m[i].substring(m[i].lastIndexOf('&') + 1));
var input = f.elements[name];
if (!input) {
o[i] = d.createElement('input');
o[i].type = 'hidden';
o[i].name = name;
o[i].value = (i + 1 === l) ? _d(m[i + 1]) : _d(m[i + 1].substring(0, (m[i + 1].lastIndexOf('&'))));
f.appendChild(o[i]);
}
}
return o;
},
/**
* Removes the custom fields created to pass additional POST
* data, along with the HTML form fields.
* @method _removeData
* @private
* @static
* @param {Object} f HTML form object.
* @param {Object} o HTML form fields created from configuration.data.
*/
_removeData: function(f, o) {
var i, l;
for (i = 0, l = o.length; i < l; i++) {
f.removeChild(o[i]);
}
},
/**
* Sets the appropriate attributes and values to the HTML
* form, in preparation of a file upload transaction.
* @method _setAttrs
* @private
* @static
* @param {Object} f HTML form object.
* @param {Object} id The Transaction ID.
* @param {Object} uri Qualified path to transaction resource.
*/
_setAttrs: function(f, id, uri) {
// Track original HTML form attribute values.
this._originalFormAttrs = {
action: f.getAttribute('action'),
target: f.getAttribute('target')
};
f.setAttribute('action', uri);
f.setAttribute('method', 'POST');
f.setAttribute('target', 'io_iframe' + id );
f.setAttribute(Y.UA.ie && !_std ? 'encoding' : 'enctype', 'multipart/form-data');
},
/**
* Reset the HTML form attributes to their original values.
* @method _resetAttrs
* @private
* @static
* @param {Object} f HTML form object.
* @param {Object} a Object of original attributes.
*/
_resetAttrs: function(f, a) {
Y.Object.each(a, function(v, p) {
if (v) {
f.setAttribute(p, v);
}
else {
f.removeAttribute(p);
}
});
},
/**
* Starts timeout count if the configuration object
* has a defined timeout property.
*
* @method _startUploadTimeout
* @private
* @static
* @param {Object} o Transaction object generated by _create().
* @param {Object} c Configuration object passed to YUI.io().
*/
_startUploadTimeout: function(o, c) {
var io = this;
io._timeout[o.id] = w.setTimeout(
function() {
o.status = 0;
o.statusText = 'timeout';
io.complete(o, c);
io.end(o, c);
}, c.timeout);
},
/**
* Clears the timeout interval started by _startUploadTimeout().
* @method _clearUploadTimeout
* @private
* @static
* @param {Number} id - Transaction ID.
*/
_clearUploadTimeout: function(id) {
var io = this;
w.clearTimeout(io._timeout[id]);
delete io._timeout[id];
},
/**
* Bound to the iframe's Load event and processes
* the response data.
* @method _uploadComplete
* @private
* @static
* @param {Object} o The transaction object
* @param {Object} c Configuration object for the transaction.
*/
_uploadComplete: function(o, c) {
var io = this,
d = Y.one('#io_iframe' + o.id).get('contentWindow.document'),
b = d.one('body'),
p;
if (c.timeout) {
io._clearUploadTimeout(o.id);
}
try {
if (b) {
// When a response Content-Type of "text/plain" is used, Firefox and Safari
// will wrap the response string with .
p = b.one('pre:first-child');
o.c.responseText = p ? p.getHTML() : b.getHTML();
}
else {
o.c.responseXML = d._node;
}
}
catch (e) {
o.e = "upload failure";
}
io.complete(o, c);
io.end(o, c);
// The transaction is complete, so call _dFrame to remove
// the event listener bound to the iframe transport, and then
// destroy the iframe.
w.setTimeout( function() { _dFrame(o.id); }, 0);
},
/**
* Uploads HTML form data, inclusive of files/attachments,
* using the iframe created in _create to facilitate the transaction.
* @method _upload
* @private
* @static
* @param {Object} o The transaction object
* @param {Object} uri Qualified path to transaction resource.
* @param {Object} c Configuration object for the transaction.
*/
_upload: function(o, uri, c) {
var io = this,
f = (typeof c.form.id === 'string') ? d.getElementById(c.form.id) : Y.Node.getDOMNode(c.form.id),
fields;
// Initialize the HTML form properties in case they are
// not defined in the HTML form.
io._setAttrs(f, o.id, uri);
if (c.data) {
fields = io._addData(f, c.data);
}
// Start polling if a callback is present and the timeout
// property has been defined.
if (c.timeout) {
io._startUploadTimeout(o, c);
}
// Start file upload.
f.submit();
io.start(o, c);
if (c.data) {
var _onIoEndHandler = io.on('io:end', function (event) {
_onIoEndHandler.detach();
io._removeData(f, fields);
});
}
return {
id: o.id,
abort: function() {
o.status = 0;
o.statusText = 'abort';
if (Y.one('#io_iframe' + o.id)) {
_dFrame(o.id);
io.complete(o, c);
io.end(o, c);
}
else {
return false;
}
},
isInProgress: function() {
return Y.one('#io_iframe' + o.id) ? true : false;
},
io: io
};
},
upload: function(o, uri, c) {
_cFrame(o, c, this);
return this._upload(o, uri, c);
},
end: function(transaction, config) {
var form, io;
if (config) {
form = config.form;
if (form && form.upload) {
io = this;
// Restore HTML form attributes to their original values.
form = (typeof form.id === 'string') ? d.getElementById(form.id) : form.id;
io._resetAttrs(form, this._originalFormAttrs);
}
}
return _end.call(this, transaction, config);
}
}, true);
}, 'patched-v3.11.0', {"requires": ["io-base", "node-base"]});
YUI.add('io-xdr', function (Y, NAME) {
/**
Extends IO to provide an alternate, Flash transport, for making
cross-domain requests.
@module io
@submodule io-xdr
@for IO
**/
// Helpful resources when working with the mess that is XDomainRequest:
// http://www.cypressnorth.com/blog/web-programming-and-development/internet-explorer-aborting-ajax-requests-fixed/
// http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
/**
Fires when the XDR transport is ready for use.
@event io:xdrReady
**/
var E_XDR_READY = Y.publish('io:xdrReady', { fireOnce: true }),
/**
Map of stored configuration objects when using
Flash as the transport for cross-domain requests.
@property _cB
@private
@type {Object}
**/
_cB = {},
/**
Map of transaction simulated readyState values
when XDomainRequest is the transport.
@property _rS
@private
@type {Object}
**/
_rS = {},
// Document reference
d = Y.config.doc,
// Window reference
w = Y.config.win,
// XDomainRequest cross-origin request detection
xdr = w && w.XDomainRequest;
/**
Method that creates the Flash transport swf.
@method _swf
@private
@param {String} uri - location of io.swf.
@param {String} yid - YUI sandbox id.
@param {String} yid - IO instance id.
**/
function _swf(uri, yid, uid) {
var o = '' +
' ' +
' ' +
' ' +
' ',
c = d.createElement('div');
d.body.appendChild(c);
c.innerHTML = o;
}
/**
Creates a response object for XDR transactions, for success
and failure cases.
@method _data
@private
@param {Object} o - Transaction object generated by _create() in io-base.
@param {Boolean} u - Configuration xdr.use.
@param {Boolean} d - Configuration xdr.dataType.
@return {Object}
**/
function _data(o, u, d) {
if (u === 'flash') {
o.c.responseText = decodeURI(o.c.responseText);
}
if (d === 'xml') {
o.c.responseXML = Y.DataType.XML.parse(o.c.responseText);
}
return o;
}
/**
Method for intiating an XDR transaction abort.
@method _abort
@private
@param {Object} o - Transaction object generated by _create() in io-base.
@param {Object} c - configuration object for the transaction.
**/
function _abort(o, c) {
return o.c.abort(o.id, c);
}
/**
Method for determining if an XDR transaction has completed
and all data are received.
@method _isInProgress
@private
@param {Object} o - Transaction object generated by _create() in io-base.
**/
function _isInProgress(o) {
return xdr ? _rS[o.id] !== 4 : o.c.isInProgress(o.id);
}
Y.mix(Y.IO.prototype, {
/**
Map of io transports.
@property _transport
@private
@type {Object}
**/
_transport: {},
/**
Sets event handlers for XDomainRequest transactions.
@method _ieEvt
@private
@static
@param {Object} o - Transaction object generated by _create() in io-base.
@param {Object} c - configuration object for the transaction.
**/
_ieEvt: function(o, c) {
var io = this,
i = o.id,
t = 'timeout';
o.c.onprogress = function() { _rS[i] = 3; };
o.c.onload = function() {
_rS[i] = 4;
io.xdrResponse('success', o, c);
};
o.c.onerror = function() {
_rS[i] = 4;
io.xdrResponse('failure', o, c);
};
o.c.ontimeout = function() {
_rS[i] = 4;
io.xdrResponse(t, o, c);
};
o.c[t] = c[t] || 0;
},
/**
Method for accessing the transport's interface for making a
cross-domain transaction.
@method xdr
@param {String} uri - qualified path to transaction resource.
@param {Object} o - Transaction object generated by _create() in io-base.
@param {Object} c - configuration object for the transaction.
**/
xdr: function(uri, o, c) {
var io = this;
if (c.xdr.use === 'flash') {
// The configuration object cannot be serialized safely
// across Flash's ExternalInterface.
_cB[o.id] = c;
w.setTimeout(function() {
try {
o.c.send(uri, { id: o.id,
uid: o.uid,
method: c.method,
data: c.data,
headers: c.headers });
}
catch(e) {
io.xdrResponse('transport error', o, c);
delete _cB[o.id];
}
}, Y.io.xdr.delay);
}
else if (xdr) {
io._ieEvt(o, c);
o.c.open(c.method || 'GET', uri);
// Make async to protect against IE 8 oddities.
setTimeout(function() {
o.c.send(c.data);
}, 0);
}
else {
o.c.send(uri, o, c);
}
return {
id: o.id,
abort: function() {
return o.c ? _abort(o, c) : false;
},
isInProgress: function() {
return o.c ? _isInProgress(o.id) : false;
},
io: io
};
},
/**
Response controller for cross-domain requests when using the
Flash transport or IE8's XDomainRequest object.
@method xdrResponse
@param {String} e Event name
@param {Object} o Transaction object generated by _create() in io-base.
@param {Object} c Configuration object for the transaction.
@return {Object}
**/
xdrResponse: function(e, o, c) {
c = _cB[o.id] ? _cB[o.id] : c;
var io = this,
m = xdr ? _rS : _cB,
u = c.xdr.use,
d = c.xdr.dataType;
switch (e) {
case 'start':
io.start(o, c);
break;
//case 'complete':
//This case is not used by Flash or XDomainRequest.
//io.complete(o, c);
//break;
case 'success':
io.success(_data(o, u, d), c);
delete m[o.id];
break;
case 'timeout':
case 'abort':
case 'transport error':
o.c = { status: 0, statusText: e };
case 'failure':
io.failure(_data(o, u, d), c);
delete m[o.id];
break;
}
},
/**
Fires event "io:xdrReady"
@method _xdrReady
@private
@param {Number} yid - YUI sandbox id.
@param {Number} uid - IO instance id.
**/
_xdrReady: function(yid, uid) {
Y.fire(E_XDR_READY, yid, uid);
},
/**
Initializes the desired transport.
@method transport
@param {Object} o - object of transport configurations.
**/
transport: function(c) {
if (c.id === 'flash') {
_swf(Y.UA.ie ? c.src + '?d=' + new Date().valueOf().toString() : c.src, Y.id, c.uid);
Y.IO.transports.flash = function() { return d.getElementById('io_swf'); };
}
}
});
/**
Fires event "io:xdrReady"
@method xdrReady
@protected
@static
@param {Number} yid - YUI sandbox id.
@param {Number} uid - IO instance id.
**/
Y.io.xdrReady = function(yid, uid){
var io = Y.io._map[uid];
Y.io.xdr.delay = 0;
io._xdrReady.apply(io, [yid, uid]);
};
Y.io.xdrResponse = function(e, o, c){
var io = Y.io._map[o.uid];
io.xdrResponse.apply(io, [e, o, c]);
};
Y.io.transport = function(c){
var io = Y.io._map['io:0'] || new Y.IO();
c.uid = io._uid;
io.transport.apply(io, [c]);
};
/**
Delay value to calling the Flash transport, in the
event io.swf has not finished loading. Once the E_XDR_READY
event is fired, this value will be set to 0.
@property delay
@static
@type {Number}
**/
Y.io.xdr = { delay : 100 };
}, 'patched-v3.11.0', {"requires": ["io-base", "datatype-xml-parse"]});
YUI.add('json-parse', function (Y, NAME) {
var _JSON = Y.config.global.JSON;
Y.namespace('JSON').parse = function (obj, reviver, space) {
return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space);
};
}, 'patched-v3.11.0', {"requires": ["yui-base"]});
YUI.add('json-stringify', function (Y, NAME) {
/**
* Provides Y.JSON.stringify method for converting objects to JSON strings.
*
* @module json
* @submodule json-stringify
* @for JSON
* @static
*/
var COLON = ':',
_JSON = Y.config.global.JSON;
Y.mix(Y.namespace('JSON'), {
/**
* Serializes a Date instance as a UTC date string. Used internally by
* stringify. Override this method if you need Dates serialized in a
* different format.
*
* @method dateToString
* @param d {Date} The Date to serialize
* @return {String} stringified Date in UTC format YYYY-MM-DDTHH:mm:SSZ
* @deprecated Use a replacer function
* @static
*/
dateToString: function (d) {
function _zeroPad(v) {
return v < 10 ? '0' + v : v;
}
return d.getUTCFullYear() + '-' +
_zeroPad(d.getUTCMonth() + 1) + '-' +
_zeroPad(d.getUTCDate()) + 'T' +
_zeroPad(d.getUTCHours()) + COLON +
_zeroPad(d.getUTCMinutes()) + COLON +
_zeroPad(d.getUTCSeconds()) + 'Z';
},
/**
* Converts an arbitrary value to a JSON string representation.
*
* Objects with cyclical references will trigger an exception.
*
* If a whitelist is provided, only matching object keys will be
* included. Alternately, a replacer function may be passed as the
* second parameter. This function is executed on every value in the
* input, and its return value will be used in place of the original value.
* This is useful to serialize specialized objects or class instances.
*
* If a positive integer or non-empty string is passed as the third
* parameter, the output will be formatted with carriage returns and
* indentation for readability. If a String is passed (such as "\t") it
* will be used once for each indentation level. If a number is passed,
* that number of spaces will be used.
*
* @method stringify
* @param o {MIXED} any arbitrary value to convert to JSON string
* @param w {Array|Function} (optional) whitelist of acceptable object
* keys to include, or a replacer function to modify the
* raw value before serialization
* @param ind {Number|String} (optional) indentation character or depth of
* spaces to format the output.
* @return {string} JSON string representation of the input
* @static
*/
stringify: function () {
return _JSON.stringify.apply(_JSON, arguments);
},
/**
* Number of occurrences of a special character within a single call to
* stringify that should trigger promotion of that character to a dedicated
* preprocess step for future calls. This is only used in environments
* that don't support native JSON, or when useNativeJSONStringify is set to
* false.
*
* So, if set to 50 and an object is passed to stringify that includes
* strings containing the special character \x07 more than 50 times,
* subsequent calls to stringify will process object strings through a
* faster serialization path for \x07 before using the generic, slower,
* replacement process for all special characters.
*
* To prime the preprocessor cache, set this value to 1, then call
* Y.JSON.stringify("(all special characters to
* cache) ");
, then return this setting to a more conservative
* value.
*
* Special characters \ " \b \t \n \f \r are already cached.
*
* @property charCacheThreshold
* @static
* @default 100
* @type {Number}
*/
charCacheThreshold: 100
});
}, 'patched-v3.11.0', {"requires": ["yui-base"]});
YUI.add('node-base', function (Y, NAME) {
/**
* @module node
* @submodule node-base
*/
var methods = [
/**
* Determines whether each node has the given className.
* @method hasClass
* @for Node
* @param {String} className the class name to search for
* @return {Boolean} Whether or not the element has the specified class
*/
'hasClass',
/**
* Adds a class name to each node.
* @method addClass
* @param {String} className the class name to add to the node's class attribute
* @chainable
*/
'addClass',
/**
* Removes a class name from each node.
* @method removeClass
* @param {String} className the class name to remove from the node's class attribute
* @chainable
*/
'removeClass',
/**
* Replace a class with another class for each node.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
* @chainable
*/
'replaceClass',
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @param {String} className the class name to be toggled
* @param {Boolean} force Option to force adding or removing the class.
* @chainable
*/
'toggleClass'
];
Y.Node.importMethod(Y.DOM, methods);
/**
* Determines whether each node has the given className.
* @method hasClass
* @see Node.hasClass
* @for NodeList
* @param {String} className the class name to search for
* @return {Array} An array of booleans for each node bound to the NodeList.
*/
/**
* Adds a class name to each node.
* @method addClass
* @see Node.addClass
* @param {String} className the class name to add to the node's class attribute
* @chainable
*/
/**
* Removes a class name from each node.
* @method removeClass
* @see Node.removeClass
* @param {String} className the class name to remove from the node's class attribute
* @chainable
*/
/**
* Replace a class with another class for each node.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @see Node.replaceClass
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
* @chainable
*/
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @see Node.toggleClass
* @param {String} className the class name to be toggled
* @chainable
*/
Y.NodeList.importMethod(Y.Node.prototype, methods);
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node,
Y_DOM = Y.DOM;
/**
* Returns a new dom node using the provided markup string.
* @method create
* @static
* @param {String} html The markup used to create the element
* Use `Y.Escape.html()`
* to escape html content.
* @param {HTMLDocument} doc An optional document context
* @return {Node} A Node instance bound to a DOM node or fragment
* @for Node
*/
Y_Node.create = function(html, doc) {
if (doc && doc._node) {
doc = doc._node;
}
return Y.one(Y_DOM.create(html, doc));
};
Y.mix(Y_Node.prototype, {
/**
* Creates a new Node using the provided markup string.
* @method create
* @param {String} html The markup used to create the element.
* Use `Y.Escape.html()`
* to escape html content.
* @param {HTMLDocument} doc An optional document context
* @return {Node} A Node instance bound to a DOM node or fragment
*/
create: Y_Node.create,
/**
* Inserts the content before the reference node.
* @method insert
* @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert
* Use `Y.Escape.html()`
* to escape html content.
* @param {Int | Node | HTMLElement | String} where The position to insert at.
* Possible "where" arguments
*
* Y.Node
* The Node to insert before
* HTMLElement
* The element to insert before
* Int
* The index of the child element to insert before
* "replace"
* Replaces the existing HTML
* "before"
* Inserts before the existing HTML
* "before"
* Inserts content before the node
* "after"
* Inserts content after the node
*
* @chainable
*/
insert: function(content, where) {
this._insert(content, where);
return this;
},
_insert: function(content, where) {
var node = this._node,
ret = null;
if (typeof where == 'number') { // allow index
where = this._node.childNodes[where];
} else if (where && where._node) { // Node
where = where._node;
}
if (content && typeof content != 'string') { // allow Node or NodeList/Array instances
content = content._node || content._nodes || content;
}
ret = Y_DOM.addHTML(node, content, where);
return ret;
},
/**
* Inserts the content as the firstChild of the node.
* @method prepend
* @param {String | Node | HTMLElement} content The content to insert
* Use `Y.Escape.html()`
* to escape html content.
* @chainable
*/
prepend: function(content) {
return this.insert(content, 0);
},
/**
* Inserts the content as the lastChild of the node.
* @method append
* @param {String | Node | HTMLElement} content The content to insert
* Use `Y.Escape.html()`
* to escape html content.
* @chainable
*/
append: function(content) {
return this.insert(content, null);
},
/**
* @method appendChild
* @param {String | HTMLElement | Node} node Node to be appended
* Use `Y.Escape.html()`
* to escape html content.
* @return {Node} The appended node
*/
appendChild: function(node) {
return Y_Node.scrubVal(this._insert(node));
},
/**
* @method insertBefore
* @param {String | HTMLElement | Node} newNode Node to be appended
* @param {HTMLElement | Node} refNode Node to be inserted before
* Use `Y.Escape.html()`
* to escape html content.
* @return {Node} The inserted node
*/
insertBefore: function(newNode, refNode) {
return Y.Node.scrubVal(this._insert(newNode, refNode));
},
/**
* Appends the node to the given node.
* @method appendTo
* @param {Node | HTMLElement} node The node to append to
* @chainable
*/
appendTo: function(node) {
Y.one(node).append(this);
return this;
},
/**
* Replaces the node's current content with the content.
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()`
* to escape html content or `set('text')` to add as text.
* @method setContent
* @deprecated Use setHTML
* @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert
* @chainable
*/
setContent: function(content) {
this._insert(content, 'replace');
return this;
},
/**
* Returns the node's current content (e.g. innerHTML)
* @method getContent
* @deprecated Use getHTML
* @return {String} The current content
*/
getContent: function() {
var node = this;
if (node._node.nodeType === 11) { // 11 === Node.DOCUMENT_FRAGMENT_NODE
// "this", when it is a document fragment, must be cloned because
// the nodes contained in the fragment actually disappear once
// the fragment is appended anywhere
node = node.create("
").append(node.cloneNode(true));
}
return node.get("innerHTML");
}
});
/**
* Replaces the node's current html content with the content provided.
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
* @method setHTML
* @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert
* @chainable
*/
Y.Node.prototype.setHTML = Y.Node.prototype.setContent;
/**
* Returns the node's current html content (e.g. innerHTML)
* @method getHTML
* @return {String} The html content
*/
Y.Node.prototype.getHTML = Y.Node.prototype.getContent;
Y.NodeList.importMethod(Y.Node.prototype, [
/**
* Called on each Node instance
* @for NodeList
* @method append
* @see Node.append
*/
'append',
/**
* Called on each Node instance
* @for NodeList
* @method insert
* @see Node.insert
*/
'insert',
/**
* Called on each Node instance
* @for NodeList
* @method appendChild
* @see Node.appendChild
*/
'appendChild',
/**
* Called on each Node instance
* @for NodeList
* @method insertBefore
* @see Node.insertBefore
*/
'insertBefore',
/**
* Called on each Node instance
* @for NodeList
* @method prepend
* @see Node.prepend
*/
'prepend',
/**
* Called on each Node instance
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
* @for NodeList
* @method setContent
* @deprecated Use setHTML
*/
'setContent',
/**
* Called on each Node instance
* @for NodeList
* @method getContent
* @deprecated Use getHTML
*/
'getContent',
/**
* Called on each Node instance
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
* @for NodeList
* @method setHTML
* @see Node.setHTML
*/
'setHTML',
/**
* Called on each Node instance
* @for NodeList
* @method getHTML
* @see Node.getHTML
*/
'getHTML'
]);
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node,
Y_DOM = Y.DOM;
/**
* Static collection of configuration attributes for special handling
* @property ATTRS
* @static
* @type object
*/
Y_Node.ATTRS = {
/**
* Allows for getting and setting the text of an element.
* Formatting is preserved and special characters are treated literally.
* @config text
* @type String
*/
text: {
getter: function() {
return Y_DOM.getText(this._node);
},
setter: function(content) {
Y_DOM.setText(this._node, content);
return content;
}
},
/**
* Allows for getting and setting the text of an element.
* Formatting is preserved and special characters are treated literally.
* @config for
* @type String
*/
'for': {
getter: function() {
return Y_DOM.getAttribute(this._node, 'for');
},
setter: function(val) {
Y_DOM.setAttribute(this._node, 'for', val);
return val;
}
},
'options': {
getter: function() {
return this._node.getElementsByTagName('option');
}
},
/**
* Returns a NodeList instance of all HTMLElement children.
* @readOnly
* @config children
* @type NodeList
*/
'children': {
getter: function() {
var node = this._node,
children = node.children,
childNodes, i, len;
if (!children || (Y.UA.ie && Y.UA.ie < 9)) {
childNodes = node.childNodes;
children = [];
for (i = 0, len = childNodes.length; i < len; ++i) {
if (childNodes[i].tagName && (childNodes[i].nodeType === 1)) {
children[children.length] = childNodes[i];
}
}
}
return Y.all(children);
}
},
value: {
getter: function() {
return Y_DOM.getValue(this._node);
},
setter: function(val) {
Y_DOM.setValue(this._node, val);
return val;
}
}
};
Y.Node.importMethod(Y.DOM, [
/**
* Allows setting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method setAttribute
* @for Node
* @for NodeList
* @chainable
* @param {string} name The attribute name
* @param {string} value The value to set
*/
'setAttribute',
/**
* Allows getting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method getAttribute
* @for Node
* @for NodeList
* @param {string} name The attribute name
* @return {string} The attribute value
*/
'getAttribute'
]);
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node;
var Y_NodeList = Y.NodeList;
/**
* List of events that route to DOM events
* @static
* @property DOM_EVENTS
* @for Node
*/
Y_Node.DOM_EVENTS = {
abort: 1,
beforeunload: 1,
blur: 1,
change: 1,
click: 1,
close: 1,
command: 1,
contextmenu: 1,
dblclick: 1,
DOMMouseScroll: 1,
drag: 1,
dragstart: 1,
dragenter: 1,
dragover: 1,
dragleave: 1,
dragend: 1,
drop: 1,
error: 1,
focus: 1,
key: 1,
keydown: 1,
keypress: 1,
keyup: 1,
load: 1,
message: 1,
mousedown: 1,
mouseenter: 1,
mouseleave: 1,
mousemove: 1,
mousemultiwheel: 1,
mouseout: 1,
mouseover: 1,
mouseup: 1,
mousewheel: 1,
orientationchange: 1,
reset: 1,
resize: 1,
select: 1,
selectstart: 1,
submit: 1,
scroll: 1,
textInput: 1,
unload: 1
};
// Add custom event adaptors to this list. This will make it so
// that delegate, key, available, contentready, etc all will
// be available through Node.on
Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins);
Y.augment(Y_Node, Y.EventTarget);
Y.mix(Y_Node.prototype, {
/**
* Removes event listeners from the node and (optionally) its subtree
* @method purge
* @param {Boolean} recurse (optional) Whether or not to remove listeners from the
* node's subtree
* @param {String} type (optional) Only remove listeners of the specified type
* @chainable
*
*/
purge: function(recurse, type) {
Y.Event.purgeElement(this._node, recurse, type);
return this;
}
});
Y.mix(Y.NodeList.prototype, {
_prepEvtArgs: function(type, fn, context) {
// map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc)
var args = Y.Array(arguments, 0, true);
if (args.length < 2) { // type only (event hash) just add nodes
args[2] = this._nodes;
} else {
args.splice(2, 0, this._nodes);
}
args[3] = context || this; // default to NodeList instance as context
return args;
},
/**
Subscribe a callback function for each `Node` in the collection to execute
in response to a DOM event.
NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in
favor of using event delegation from a parent Node. See the Event user
guide for details.
Most DOM events are associated with a preventable default behavior, such as
link clicks navigating to a new page. Callbacks are passed a
`DOMEventFacade` object as their first argument (usually called `e`) that
can be used to prevent this default behavior with `e.preventDefault()`. See
the `DOMEventFacade` API for all available properties and methods on the
object.
By default, the `this` object will be the `NodeList` that the subscription
came from, not the `Node` that received the event . Use
`e.currentTarget` to refer to the `Node`.
Returning `false` from a callback is supported as an alternative to calling
`e.preventDefault(); e.stopPropagation();`. However, it is recommended to
use the event methods.
@example
Y.all(".sku").on("keydown", function (e) {
if (e.keyCode === 13) {
e.preventDefault();
// Use e.currentTarget to refer to the individual Node
var item = Y.MyApp.searchInventory( e.currentTarget.get('value') );
// etc ...
}
});
@method on
@param {String} type The name of the event
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching that
subscription
@for NodeList
**/
on: function(type, fn, context) {
return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments));
},
/**
* Applies an one-time event listener to each Node bound to the NodeList.
* @method once
* @param {String} type The event being listened for
* @param {Function} fn The handler to call when the event fires
* @param {Object} context The context to call the handler with.
* Default is the NodeList instance.
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
* @for NodeList
*/
once: function(type, fn, context) {
return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments));
},
/**
* Applies an event listener to each Node bound to the NodeList.
* The handler is called only after all on() handlers are called
* and the event is not prevented.
* @method after
* @param {String} type The event being listened for
* @param {Function} fn The handler to call when the event fires
* @param {Object} context The context to call the handler with.
* Default is the NodeList instance.
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
* @for NodeList
*/
after: function(type, fn, context) {
return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments));
},
/**
* Applies an one-time event listener to each Node bound to the NodeList
* that will be called only after all on() handlers are called and the
* event is not prevented.
*
* @method onceAfter
* @param {String} type The event being listened for
* @param {Function} fn The handler to call when the event fires
* @param {Object} context The context to call the handler with.
* Default is the NodeList instance.
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
* @for NodeList
*/
onceAfter: function(type, fn, context) {
return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments));
}
});
Y_NodeList.importMethod(Y.Node.prototype, [
/**
* Called on each Node instance
* @method detach
* @see Node.detach
* @for NodeList
*/
'detach',
/** Called on each Node instance
* @method detachAll
* @see Node.detachAll
* @for NodeList
*/
'detachAll'
]);
/**
Subscribe a callback function to execute in response to a DOM event or custom
event.
Most DOM events are associated with a preventable default behavior such as
link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade`
object as their first argument (usually called `e`) that can be used to
prevent this default behavior with `e.preventDefault()`. See the
`DOMEventFacade` API for all available properties and methods on the object.
If the event name passed as the first parameter is not a whitelisted DOM event,
it will be treated as a custom event subscriptions, allowing
`node.fire('customEventName')` later in the code. Refer to the Event user guide
for the full DOM event whitelist.
By default, the `this` object in the callback will refer to the subscribed
`Node`.
Returning `false` from a callback is supported as an alternative to calling
`e.preventDefault(); e.stopPropagation();`. However, it is recommended to use
the event methods.
@example
Y.one("#my-form").on("submit", function (e) {
e.preventDefault();
// proceed with ajax form submission instead...
});
@method on
@param {String} type The name of the event
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching that
subscription
@for Node
**/
Y.mix(Y.Node.ATTRS, {
offsetHeight: {
setter: function(h) {
Y.DOM.setHeight(this._node, h);
return h;
},
getter: function() {
return this._node.offsetHeight;
}
},
offsetWidth: {
setter: function(w) {
Y.DOM.setWidth(this._node, w);
return w;
},
getter: function() {
return this._node.offsetWidth;
}
}
});
Y.mix(Y.Node.prototype, {
sizeTo: function(w, h) {
var node;
if (arguments.length < 2) {
node = Y.one(w);
w = node.get('offsetWidth');
h = node.get('offsetHeight');
}
this.setAttrs({
offsetWidth: w,
offsetHeight: h
});
}
});
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node;
Y.mix(Y_Node.prototype, {
/**
* Makes the node visible.
* If the "transition" module is loaded, show optionally
* animates the showing of the node using either the default
* transition effect ('fadeIn'), or the given named effect.
* @method show
* @for Node
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @chainable
*/
show: function(callback) {
callback = arguments[arguments.length - 1];
this.toggleView(true, callback);
return this;
},
/**
* The implementation for showing nodes.
* Default is to remove the hidden attribute and reset the CSS style.display property.
* @method _show
* @protected
* @chainable
*/
_show: function() {
this.removeAttribute('hidden');
// For back-compat we need to leave this in for browsers that
// do not visually hide a node via the hidden attribute
// and for users that check visibility based on style display.
this.setStyle('display', '');
},
_isHidden: function() {
return Y.DOM.getAttribute(this._node, 'hidden') === 'true';
},
/**
* Displays or hides the node.
* If the "transition" module is loaded, toggleView optionally
* animates the toggling of the node using given named effect.
* @method toggleView
* @for Node
* @param {String} [name] An optional string value to use as transition effect.
* @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden
* @param {Function} [callback] An optional function to run after the transition completes.
* @chainable
*/
toggleView: function(on, callback) {
this._toggleView.apply(this, arguments);
return this;
},
_toggleView: function(on, callback) {
callback = arguments[arguments.length - 1];
// base on current state if not forcing
if (typeof on != 'boolean') {
on = (this._isHidden()) ? 1 : 0;
}
if (on) {
this._show();
} else {
this._hide();
}
if (typeof callback == 'function') {
callback.call(this);
}
return this;
},
/**
* Hides the node.
* If the "transition" module is loaded, hide optionally
* animates the hiding of the node using either the default
* transition effect ('fadeOut'), or the given named effect.
* @method hide
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @chainable
*/
hide: function(callback) {
callback = arguments[arguments.length - 1];
this.toggleView(false, callback);
return this;
},
/**
* The implementation for hiding nodes.
* Default is to set the hidden attribute to true and set the CSS style.display to 'none'.
* @method _hide
* @protected
* @chainable
*/
_hide: function() {
this.setAttribute('hidden', true);
// For back-compat we need to leave this in for browsers that
// do not visually hide a node via the hidden attribute
// and for users that check visibility based on style display.
this.setStyle('display', 'none');
}
});
Y.NodeList.importMethod(Y.Node.prototype, [
/**
* Makes each node visible.
* If the "transition" module is loaded, show optionally
* animates the showing of the node using either the default
* transition effect ('fadeIn'), or the given named effect.
* @method show
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @for NodeList
* @chainable
*/
'show',
/**
* Hides each node.
* If the "transition" module is loaded, hide optionally
* animates the hiding of the node using either the default
* transition effect ('fadeOut'), or the given named effect.
* @method hide
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @chainable
*/
'hide',
/**
* Displays or hides each node.
* If the "transition" module is loaded, toggleView optionally
* animates the toggling of the nodes using given named effect.
* @method toggleView
* @param {String} [name] An optional string value to use as transition effect.
* @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden
* @param {Function} [callback] An optional function to run after the transition completes.
* @chainable
*/
'toggleView'
]);
if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8
Y.Node.prototype.hasAttribute = function(attr) {
if (attr === 'value') {
if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML
return true;
}
}
return !!(this._node.attributes[attr] &&
this._node.attributes[attr].specified);
};
}
// IE throws an error when calling focus() on an element that's invisible, not
// displayed, or disabled.
Y.Node.prototype.focus = function () {
try {
this._node.focus();
} catch (e) {
}
return this;
};
// IE throws error when setting input.type = 'hidden',
// input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden'
Y.Node.ATTRS.type = {
setter: function(val) {
if (val === 'hidden') {
try {
this._node.type = 'hidden';
} catch(e) {
this.setStyle('display', 'none');
this._inputType = 'hidden';
}
} else {
try { // IE errors when changing the type from "hidden'
this._node.type = val;
} catch (e) {
}
}
return val;
},
getter: function() {
return this._inputType || this._node.type;
},
_bypassProxy: true // don't update DOM when using with Attribute
};
if (Y.config.doc.createElement('form').elements.nodeType) {
// IE: elements collection is also FORM node which trips up scrubVal.
Y.Node.ATTRS.elements = {
getter: function() {
return this.all('input, textarea, button, select');
}
};
}
/**
* Provides methods for managing custom Node data.
*
* @module node
* @main node
* @submodule node-data
*/
Y.mix(Y.Node.prototype, {
_initData: function() {
if (! ('_data' in this)) {
this._data = {};
}
},
/**
* @method getData
* @for Node
* @description Retrieves arbitrary data stored on a Node instance.
* If no data is associated with the Node, it will attempt to retrieve
* a value from the corresponding HTML data attribute. (e.g. node.getData('foo')
* will check node.getAttribute('data-foo')).
* @param {string} name Optional name of the data field to retrieve.
* If no name is given, all data is returned.
* @return {any | Object} Whatever is stored at the given field,
* or an object hash of all fields.
*/
getData: function(name) {
this._initData();
var data = this._data,
ret = data;
if (arguments.length) { // single field
if (name in data) {
ret = data[name];
} else { // initialize from HTML attribute
ret = this._getDataAttribute(name);
}
} else if (typeof data == 'object' && data !== null) { // all fields
ret = {};
Y.Object.each(data, function(v, n) {
ret[n] = v;
});
ret = this._getDataAttributes(ret);
}
return ret;
},
_getDataAttributes: function(ret) {
ret = ret || {};
var i = 0,
attrs = this._node.attributes,
len = attrs.length,
prefix = this.DATA_PREFIX,
prefixLength = prefix.length,
name;
while (i < len) {
name = attrs[i].name;
if (name.indexOf(prefix) === 0) {
name = name.substr(prefixLength);
if (!(name in ret)) { // only merge if not already stored
ret[name] = this._getDataAttribute(name);
}
}
i += 1;
}
return ret;
},
_getDataAttribute: function(name) {
name = this.DATA_PREFIX + name;
var node = this._node,
attrs = node.attributes,
data = attrs && attrs[name] && attrs[name].value;
return data;
},
/**
* @method setData
* @for Node
* @description Stores arbitrary data on a Node instance.
* This is not stored with the DOM node.
* @param {string} name The name of the field to set. If no val
* is given, name is treated as the data and overrides any existing data.
* @param {any} val The value to be assigned to the field.
* @chainable
*/
setData: function(name, val) {
this._initData();
if (arguments.length > 1) {
this._data[name] = val;
} else {
this._data = name;
}
return this;
},
/**
* @method clearData
* @for Node
* @description Clears internally stored data.
* @param {string} name The name of the field to clear. If no name
* is given, all data is cleared.
* @chainable
*/
clearData: function(name) {
if ('_data' in this) {
if (typeof name != 'undefined') {
delete this._data[name];
} else {
delete this._data;
}
}
return this;
}
});
Y.mix(Y.NodeList.prototype, {
/**
* @method getData
* @for NodeList
* @description Retrieves arbitrary data stored on each Node instance
* bound to the NodeList.
* @see Node
* @param {string} name Optional name of the data field to retrieve.
* If no name is given, all data is returned.
* @return {Array} An array containing all of the data for each Node instance.
* or an object hash of all fields.
*/
getData: function(name) {
var args = (arguments.length) ? [name] : [];
return this._invoke('getData', args, true);
},
/**
* @method setData
* @for NodeList
* @description Stores arbitrary data on each Node instance bound to the
* NodeList. This is not stored with the DOM node.
* @param {string} name The name of the field to set. If no name
* is given, name is treated as the data and overrides any existing data.
* @param {any} val The value to be assigned to the field.
* @chainable
*/
setData: function(name, val) {
var args = (arguments.length > 1) ? [name, val] : [name];
return this._invoke('setData', args);
},
/**
* @method clearData
* @for NodeList
* @description Clears data on all Node instances bound to the NodeList.
* @param {string} name The name of the field to clear. If no name
* is given, all data is cleared.
* @chainable
*/
clearData: function(name) {
var args = (arguments.length) ? [name] : [];
return this._invoke('clearData', [name]);
}
});
}, 'patched-v3.11.0', {"requires": ["event-base", "node-core", "dom-base"]});
YUI.add('node-core', function (Y, NAME) {
/**
* The Node Utility provides a DOM-like interface for interacting with DOM nodes.
* @module node
* @main node
* @submodule node-core
*/
/**
* The Node class provides a wrapper for manipulating DOM Nodes.
* Node properties can be accessed via the set/get methods.
* Use `Y.one()` to retrieve Node instances.
*
* NOTE: Node properties are accessed using
* the set
and get
methods.
*
* @class Node
* @constructor
* @param {DOMNode} node the DOM node to be mapped to the Node instance.
* @uses EventTarget
*/
// "globals"
var DOT = '.',
NODE_NAME = 'nodeName',
NODE_TYPE = 'nodeType',
OWNER_DOCUMENT = 'ownerDocument',
TAG_NAME = 'tagName',
UID = '_yuid',
EMPTY_OBJ = {},
_slice = Array.prototype.slice,
Y_DOM = Y.DOM,
Y_Node = function(node) {
if (!this.getDOMNode) { // support optional "new"
return new Y_Node(node);
}
if (typeof node == 'string') {
node = Y_Node._fromString(node);
if (!node) {
return null; // NOTE: return
}
}
var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID];
if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) {
node[UID] = null; // unset existing uid to prevent collision (via clone or hack)
}
uid = uid || Y.stamp(node);
if (!uid) { // stamp failed; likely IE non-HTMLElement
uid = Y.guid();
}
this[UID] = uid;
/**
* The underlying DOM node bound to the Y.Node instance
* @property _node
* @type DOMNode
* @private
*/
this._node = node;
this._stateProxy = node; // when augmented with Attribute
if (this._initPlugins) { // when augmented with Plugin.Host
this._initPlugins();
}
},
// used with previous/next/ancestor tests
_wrapFn = function(fn) {
var ret = null;
if (fn) {
ret = (typeof fn == 'string') ?
function(n) {
return Y.Selector.test(n, fn);
} :
function(n) {
return fn(Y.one(n));
};
}
return ret;
};
// end "globals"
Y_Node.ATTRS = {};
Y_Node.DOM_EVENTS = {};
Y_Node._fromString = function(node) {
if (node) {
if (node.indexOf('doc') === 0) { // doc OR document
node = Y.config.doc;
} else if (node.indexOf('win') === 0) { // win OR window
node = Y.config.win;
} else {
node = Y.Selector.query(node, null, true);
}
}
return node || null;
};
/**
* The name of the component
* @static
* @type String
* @property NAME
*/
Y_Node.NAME = 'node';
/*
* The pattern used to identify ARIA attributes
*/
Y_Node.re_aria = /^(?:role$|aria-)/;
Y_Node.SHOW_TRANSITION = 'fadeIn';
Y_Node.HIDE_TRANSITION = 'fadeOut';
/**
* A list of Node instances that have been created
* @private
* @type Object
* @property _instances
* @static
*
*/
Y_Node._instances = {};
/**
* Retrieves the DOM node bound to a Node instance
* @method getDOMNode
* @static
*
* @param {Node | HTMLNode} node The Node instance or an HTMLNode
* @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed
* as the node argument, it is simply returned.
*/
Y_Node.getDOMNode = function(node) {
if (node) {
return (node.nodeType) ? node : node._node || null;
}
return null;
};
/**
* Checks Node return values and wraps DOM Nodes as Y.Node instances
* and DOM Collections / Arrays as Y.NodeList instances.
* Other return values just pass thru. If undefined is returned (e.g. no return)
* then the Node instance is returned for chainability.
* @method scrubVal
* @static
*
* @param {any} node The Node instance or an HTMLNode
* @return {Node | NodeList | Any} Depends on what is returned from the DOM node.
*/
Y_Node.scrubVal = function(val, node) {
if (val) { // only truthy values are risky
if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function
if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window
val = Y.one(val);
} else if ((val.item && !val._nodes) || // dom collection or Node instance
(val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes
val = Y.all(val);
}
}
} else if (typeof val === 'undefined') {
val = node; // for chaining
} else if (val === null) {
val = null; // IE: DOM null not the same as null
}
return val;
};
/**
* Adds methods to the Y.Node prototype, routing through scrubVal.
* @method addMethod
* @static
*
* @param {String} name The name of the method to add
* @param {Function} fn The function that becomes the method
* @param {Object} context An optional context to call the method with
* (defaults to the Node instance)
* @return {any} Depends on what is returned from the DOM node.
*/
Y_Node.addMethod = function(name, fn, context) {
if (name && fn && typeof fn == 'function') {
Y_Node.prototype[name] = function() {
var args = _slice.call(arguments),
node = this,
ret;
if (args[0] && args[0]._node) {
args[0] = args[0]._node;
}
if (args[1] && args[1]._node) {
args[1] = args[1]._node;
}
args.unshift(node._node);
ret = fn.apply(node, args);
if (ret) { // scrub truthy
ret = Y_Node.scrubVal(ret, node);
}
(typeof ret != 'undefined') || (ret = node);
return ret;
};
} else {
}
};
/**
* Imports utility methods to be added as Y.Node methods.
* @method importMethod
* @static
*
* @param {Object} host The object that contains the method to import.
* @param {String} name The name of the method to import
* @param {String} altName An optional name to use in place of the host name
* @param {Object} context An optional context to call the method with
*/
Y_Node.importMethod = function(host, name, altName) {
if (typeof name == 'string') {
altName = altName || name;
Y_Node.addMethod(altName, host[name], host);
} else {
Y.Array.each(name, function(n) {
Y_Node.importMethod(host, n);
});
}
};
/**
* Retrieves a NodeList based on the given CSS selector.
* @method all
*
* @param {string} selector The CSS selector to test against.
* @return {NodeList} A NodeList instance for the matching HTMLCollection/Array.
* @for YUI
*/
/**
* Returns a single Node instance bound to the node or the
* first element matching the given selector. Returns null if no match found.
* Note: For chaining purposes you may want to
* use Y.all
, which returns a NodeList when no match is found.
* @method one
* @param {String | HTMLElement} node a node or Selector
* @return {Node | null} a Node instance or null if no match found.
* @for YUI
*/
/**
* Returns a single Node instance bound to the node or the
* first element matching the given selector. Returns null if no match found.
* Note: For chaining purposes you may want to
* use Y.all
, which returns a NodeList when no match is found.
* @method one
* @static
* @param {String | HTMLElement} node a node or Selector
* @return {Node | null} a Node instance or null if no match found.
* @for Node
*/
Y_Node.one = function(node) {
var instance = null,
cachedNode,
uid;
if (node) {
if (typeof node == 'string') {
node = Y_Node._fromString(node);
if (!node) {
return null; // NOTE: return
}
} else if (node.getDOMNode) {
return node; // NOTE: return
}
if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc)
uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid;
instance = Y_Node._instances[uid]; // reuse exising instances
cachedNode = instance ? instance._node : null;
if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match
instance = new Y_Node(node);
if (node.nodeType != 11) { // dont cache document fragment
Y_Node._instances[instance[UID]] = instance; // cache node
}
}
}
}
return instance;
};
/**
* The default setter for DOM properties
* Called with instance context (this === the Node instance)
* @method DEFAULT_SETTER
* @static
* @param {String} name The attribute/property being set
* @param {any} val The value to be set
* @return {any} The value
*/
Y_Node.DEFAULT_SETTER = function(name, val) {
var node = this._stateProxy,
strPath;
if (name.indexOf(DOT) > -1) {
strPath = name;
name = name.split(DOT);
// only allow when defined on node
Y.Object.setValue(node, name, val);
} else if (typeof node[name] != 'undefined') { // pass thru DOM properties
node[name] = val;
}
return val;
};
/**
* The default getter for DOM properties
* Called with instance context (this === the Node instance)
* @method DEFAULT_GETTER
* @static
* @param {String} name The attribute/property to look up
* @return {any} The current value
*/
Y_Node.DEFAULT_GETTER = function(name) {
var node = this._stateProxy,
val;
if (name.indexOf && name.indexOf(DOT) > -1) {
val = Y.Object.getValue(node, name.split(DOT));
} else if (typeof node[name] != 'undefined') { // pass thru from DOM
val = node[name];
}
return val;
};
Y.mix(Y_Node.prototype, {
DATA_PREFIX: 'data-',
/**
* The method called when outputting Node instances as strings
* @method toString
* @return {String} A string representation of the Node instance
*/
toString: function() {
var str = this[UID] + ': not bound to a node',
node = this._node,
attrs, id, className;
if (node) {
attrs = node.attributes;
id = (attrs && attrs.id) ? node.getAttribute('id') : null;
className = (attrs && attrs.className) ? node.getAttribute('className') : null;
str = node[NODE_NAME];
if (id) {
str += '#' + id;
}
if (className) {
str += '.' + className.replace(' ', '.');
}
// TODO: add yuid?
str += ' ' + this[UID];
}
return str;
},
/**
* Returns an attribute value on the Node instance.
* Unless pre-configured (via `Node.ATTRS`), get hands
* off to the underlying DOM node. Only valid
* attributes/properties for the node will be queried.
* @method get
* @param {String} attr The attribute
* @return {any} The current value of the attribute
*/
get: function(attr) {
var val;
if (this._getAttr) { // use Attribute imple
val = this._getAttr(attr);
} else {
val = this._get(attr);
}
if (val) {
val = Y_Node.scrubVal(val, this);
} else if (val === null) {
val = null; // IE: DOM null is not true null (even though they ===)
}
return val;
},
/**
* Helper method for get.
* @method _get
* @private
* @param {String} attr The attribute
* @return {any} The current value of the attribute
*/
_get: function(attr) {
var attrConfig = Y_Node.ATTRS[attr],
val;
if (attrConfig && attrConfig.getter) {
val = attrConfig.getter.call(this);
} else if (Y_Node.re_aria.test(attr)) {
val = this._node.getAttribute(attr, 2);
} else {
val = Y_Node.DEFAULT_GETTER.apply(this, arguments);
}
return val;
},
/**
* Sets an attribute on the Node instance.
* Unless pre-configured (via Node.ATTRS), set hands
* off to the underlying DOM node. Only valid
* attributes/properties for the node will be set.
* To set custom attributes use setAttribute.
* @method set
* @param {String} attr The attribute to be set.
* @param {any} val The value to set the attribute to.
* @chainable
*/
set: function(attr, val) {
var attrConfig = Y_Node.ATTRS[attr];
if (this._setAttr) { // use Attribute imple
this._setAttr.apply(this, arguments);
} else { // use setters inline
if (attrConfig && attrConfig.setter) {
attrConfig.setter.call(this, val, attr);
} else if (Y_Node.re_aria.test(attr)) { // special case Aria
this._node.setAttribute(attr, val);
} else {
Y_Node.DEFAULT_SETTER.apply(this, arguments);
}
}
return this;
},
/**
* Sets multiple attributes.
* @method setAttrs
* @param {Object} attrMap an object of name/value pairs to set
* @chainable
*/
setAttrs: function(attrMap) {
if (this._setAttrs) { // use Attribute imple
this._setAttrs(attrMap);
} else { // use setters inline
Y.Object.each(attrMap, function(v, n) {
this.set(n, v);
}, this);
}
return this;
},
/**
* Returns an object containing the values for the requested attributes.
* @method getAttrs
* @param {Array} attrs an array of attributes to get values
* @return {Object} An object with attribute name/value pairs.
*/
getAttrs: function(attrs) {
var ret = {};
if (this._getAttrs) { // use Attribute imple
this._getAttrs(attrs);
} else { // use setters inline
Y.Array.each(attrs, function(v, n) {
ret[v] = this.get(v);
}, this);
}
return ret;
},
/**
* Compares nodes to determine if they match.
* Node instances can be compared to each other and/or HTMLElements.
* @method compareTo
* @param {HTMLElement | Node} refNode The reference node to compare to the node.
* @return {Boolean} True if the nodes match, false if they do not.
*/
compareTo: function(refNode) {
var node = this._node;
if (refNode && refNode._node) {
refNode = refNode._node;
}
return node === refNode;
},
/**
* Determines whether the node is appended to the document.
* @method inDoc
* @param {Node|HTMLElement} doc optional An optional document to check against.
* Defaults to current document.
* @return {Boolean} Whether or not this node is appended to the document.
*/
inDoc: function(doc) {
var node = this._node;
if (node) {
doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT];
if (doc.documentElement) {
return Y_DOM.contains(doc.documentElement, node);
}
}
return false;
},
getById: function(id) {
var node = this._node,
ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]);
if (ret && Y_DOM.contains(node, ret)) {
ret = Y.one(ret);
} else {
ret = null;
}
return ret;
},
/**
* Returns the nearest ancestor that passes the test applied by supplied boolean method.
* @method ancestor
* @param {String | Function} fn A selector string or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* If fn is not passed as an argument, the parent node will be returned.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* @param {String | Function} stopFn optional A selector string or boolean
* method to indicate when the search should stop. The search bails when the function
* returns true or the selector matches.
* If a function is used, it receives the current node being tested as the only argument.
* @return {Node} The matching Node instance or null if not found
*/
ancestor: function(fn, testSelf, stopFn) {
// testSelf is optional, check for stopFn as 2nd arg
if (arguments.length === 2 &&
(typeof testSelf == 'string' || typeof testSelf == 'function')) {
stopFn = testSelf;
}
return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn)));
},
/**
* Returns the ancestors that pass the test applied by supplied boolean method.
* @method ancestors
* @param {String | Function} fn A selector string or boolean method for testing elements.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* If a function is used, it receives the current node being tested as the only argument.
* @return {NodeList} A NodeList instance containing the matching elements
*/
ancestors: function(fn, testSelf, stopFn) {
if (arguments.length === 2 &&
(typeof testSelf == 'string' || typeof testSelf == 'function')) {
stopFn = testSelf;
}
return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn)));
},
/**
* Returns the previous matching sibling.
* Returns the nearest element node sibling if no method provided.
* @method previous
* @param {String | Function} fn A selector or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @return {Node} Node instance or null if not found
*/
previous: function(fn, all) {
return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all));
},
/**
* Returns the next matching sibling.
* Returns the nearest element node sibling if no method provided.
* @method next
* @param {String | Function} fn A selector or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @return {Node} Node instance or null if not found
*/
next: function(fn, all) {
return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all));
},
/**
* Returns all matching siblings.
* Returns all siblings if no method provided.
* @method siblings
* @param {String | Function} fn A selector or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @return {NodeList} NodeList instance bound to found siblings
*/
siblings: function(fn) {
return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn)));
},
/**
* Retrieves a single Node instance, the first element matching the given
* CSS selector.
* Returns null if no match found.
* @method one
*
* @param {string} selector The CSS selector to test against.
* @return {Node | null} A Node instance for the matching HTMLElement or null
* if no match found.
*/
one: function(selector) {
return Y.one(Y.Selector.query(selector, this._node, true));
},
/**
* Retrieves a NodeList based on the given CSS selector.
* @method all
*
* @param {string} selector The CSS selector to test against.
* @return {NodeList} A NodeList instance for the matching HTMLCollection/Array.
*/
all: function(selector) {
var nodelist;
if (this._node) {
nodelist = Y.all(Y.Selector.query(selector, this._node));
nodelist._query = selector;
nodelist._queryRoot = this._node;
}
return nodelist || Y.all([]);
},
// TODO: allow fn test
/**
* Test if the supplied node matches the supplied selector.
* @method test
*
* @param {string} selector The CSS selector to test against.
* @return {boolean} Whether or not the node matches the selector.
*/
test: function(selector) {
return Y.Selector.test(this._node, selector);
},
/**
* Removes the node from its parent.
* Shortcut for myNode.get('parentNode').removeChild(myNode);
* @method remove
* @param {Boolean} destroy whether or not to call destroy() on the node
* after removal.
* @chainable
*
*/
remove: function(destroy) {
var node = this._node;
if (node && node.parentNode) {
node.parentNode.removeChild(node);
}
if (destroy) {
this.destroy();
}
return this;
},
/**
* Replace the node with the other node. This is a DOM update only
* and does not change the node bound to the Node instance.
* Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode);
* @method replace
* @param {Node | HTMLNode} newNode Node to be inserted
* @chainable
*
*/
replace: function(newNode) {
var node = this._node;
if (typeof newNode == 'string') {
newNode = Y_Node.create(newNode);
}
node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node);
return this;
},
/**
* @method replaceChild
* @for Node
* @param {String | HTMLElement | Node} node Node to be inserted
* @param {HTMLElement | Node} refNode Node to be replaced
* @return {Node} The replaced node
*/
replaceChild: function(node, refNode) {
if (typeof node == 'string') {
node = Y_DOM.create(node);
}
return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode)));
},
/**
* Nulls internal node references, removes any plugins and event listeners.
* Note that destroy() will not remove the node from its parent or from the DOM. For that
* functionality, call remove(true).
* @method destroy
* @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the
* node's subtree (default is false)
*
*/
destroy: function(recursive) {
var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid',
instance;
this.purge(); // TODO: only remove events add via this Node
if (this.unplug) { // may not be a PluginHost
this.unplug();
}
this.clearData();
if (recursive) {
Y.NodeList.each(this.all('*'), function(node) {
instance = Y_Node._instances[node[UID]];
if (instance) {
instance.destroy();
} else { // purge in case added by other means
Y.Event.purgeElement(node);
}
});
}
this._node = null;
this._stateProxy = null;
delete Y_Node._instances[this._yuid];
},
/**
* Invokes a method on the Node instance
* @method invoke
* @param {String} method The name of the method to invoke
* @param {Any} a, b, c, etc. Arguments to invoke the method with.
* @return Whatever the underly method returns.
* DOM Nodes and Collections return values
* are converted to Node/NodeList instances.
*
*/
invoke: function(method, a, b, c, d, e) {
var node = this._node,
ret;
if (a && a._node) {
a = a._node;
}
if (b && b._node) {
b = b._node;
}
ret = node[method](a, b, c, d, e);
return Y_Node.scrubVal(ret, this);
},
/**
* @method swap
* @description Swap DOM locations with the given node.
* This does not change which DOM node each Node instance refers to.
* @param {Node} otherNode The node to swap with
* @chainable
*/
swap: Y.config.doc.documentElement.swapNode ?
function(otherNode) {
this._node.swapNode(Y_Node.getDOMNode(otherNode));
} :
function(otherNode) {
otherNode = Y_Node.getDOMNode(otherNode);
var node = this._node,
parent = otherNode.parentNode,
nextSibling = otherNode.nextSibling;
if (nextSibling === node) {
parent.insertBefore(node, otherNode);
} else if (otherNode === node.nextSibling) {
parent.insertBefore(otherNode, node);
} else {
node.parentNode.replaceChild(otherNode, node);
Y_DOM.addHTML(parent, node, nextSibling);
}
return this;
},
hasMethod: function(method) {
var node = this._node;
return !!(node && method in node &&
typeof node[method] != 'unknown' &&
(typeof node[method] == 'function' ||
String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space
},
isFragment: function() {
return (this.get('nodeType') === 11);
},
/**
* Removes and destroys all of the nodes within the node.
* @method empty
* @chainable
*/
empty: function() {
this.get('childNodes').remove().destroy(true);
return this;
},
/**
* Returns the DOM node bound to the Node instance
* @method getDOMNode
* @return {DOMNode}
*/
getDOMNode: function() {
return this._node;
}
}, true);
Y.Node = Y_Node;
Y.one = Y_Node.one;
/**
* The NodeList module provides support for managing collections of Nodes.
* @module node
* @submodule node-core
*/
/**
* The NodeList class provides a wrapper for manipulating DOM NodeLists.
* NodeList properties can be accessed via the set/get methods.
* Use Y.all() to retrieve NodeList instances.
*
* @class NodeList
* @constructor
* @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList.
*/
var NodeList = function(nodes) {
var tmp = [];
if (nodes) {
if (typeof nodes === 'string') { // selector query
this._query = nodes;
nodes = Y.Selector.query(nodes);
} else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window
nodes = [nodes];
} else if (nodes._node) { // Y.Node
nodes = [nodes._node];
} else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes
Y.Array.each(nodes, function(node) {
if (node._node) {
tmp.push(node._node);
}
});
nodes = tmp;
} else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes)
nodes = Y.Array(nodes, 0, true);
}
}
/**
* The underlying array of DOM nodes bound to the Y.NodeList instance
* @property _nodes
* @private
*/
this._nodes = nodes || [];
};
NodeList.NAME = 'NodeList';
/**
* Retrieves the DOM nodes bound to a NodeList instance
* @method getDOMNodes
* @static
*
* @param {NodeList} nodelist The NodeList instance
* @return {Array} The array of DOM nodes bound to the NodeList
*/
NodeList.getDOMNodes = function(nodelist) {
return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist;
};
NodeList.each = function(instance, fn, context) {
var nodes = instance._nodes;
if (nodes && nodes.length) {
Y.Array.each(nodes, fn, context || instance);
} else {
}
};
NodeList.addMethod = function(name, fn, context) {
if (name && fn) {
NodeList.prototype[name] = function() {
var ret = [],
args = arguments;
Y.Array.each(this._nodes, function(node) {
var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid',
instance = Y.Node._instances[node[UID]],
ctx,
result;
if (!instance) {
instance = NodeList._getTempNode(node);
}
ctx = context || instance;
result = fn.apply(ctx, args);
if (result !== undefined && result !== instance) {
ret[ret.length] = result;
}
});
// TODO: remove tmp pointer
return ret.length ? ret : this;
};
} else {
}
};
NodeList.importMethod = function(host, name, altName) {
if (typeof name === 'string') {
altName = altName || name;
NodeList.addMethod(name, host[name]);
} else {
Y.Array.each(name, function(n) {
NodeList.importMethod(host, n);
});
}
};
NodeList._getTempNode = function(node) {
var tmp = NodeList._tempNode;
if (!tmp) {
tmp = Y.Node.create('
');
NodeList._tempNode = tmp;
}
tmp._node = node;
tmp._stateProxy = node;
return tmp;
};
Y.mix(NodeList.prototype, {
_invoke: function(method, args, getter) {
var ret = (getter) ? [] : this;
this.each(function(node) {
var val = node[method].apply(node, args);
if (getter) {
ret.push(val);
}
});
return ret;
},
/**
* Retrieves the Node instance at the given index.
* @method item
*
* @param {Number} index The index of the target Node.
* @return {Node} The Node instance at the given index.
*/
item: function(index) {
return Y.one((this._nodes || [])[index]);
},
/**
* Applies the given function to each Node in the NodeList.
* @method each
* @param {Function} fn The function to apply. It receives 3 arguments:
* the current node instance, the node's index, and the NodeList instance
* @param {Object} context optional An optional context to apply the function with
* Default context is the current Node instance
* @chainable
*/
each: function(fn, context) {
var instance = this;
Y.Array.each(this._nodes, function(node, index) {
node = Y.one(node);
return fn.call(context || node, node, index, instance);
});
return instance;
},
batch: function(fn, context) {
var nodelist = this;
Y.Array.each(this._nodes, function(node, index) {
var instance = Y.Node._instances[node[UID]];
if (!instance) {
instance = NodeList._getTempNode(node);
}
return fn.call(context || instance, instance, index, nodelist);
});
return nodelist;
},
/**
* Executes the function once for each node until a true value is returned.
* @method some
* @param {Function} fn The function to apply. It receives 3 arguments:
* the current node instance, the node's index, and the NodeList instance
* @param {Object} context optional An optional context to execute the function from.
* Default context is the current Node instance
* @return {Boolean} Whether or not the function returned true for any node.
*/
some: function(fn, context) {
var instance = this;
return Y.Array.some(this._nodes, function(node, index) {
node = Y.one(node);
context = context || node;
return fn.call(context, node, index, instance);
});
},
/**
* Creates a documenFragment from the nodes bound to the NodeList instance
* @method toFrag
* @return {Node} a Node instance bound to the documentFragment
*/
toFrag: function() {
return Y.one(Y.DOM._nl2frag(this._nodes));
},
/**
* Returns the index of the node in the NodeList instance
* or -1 if the node isn't found.
* @method indexOf
* @param {Node | DOMNode} node the node to search for
* @return {Int} the index of the node value or -1 if not found
*/
indexOf: function(node) {
return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node));
},
/**
* Filters the NodeList instance down to only nodes matching the given selector.
* @method filter
* @param {String} selector The selector to filter against
* @return {NodeList} NodeList containing the updated collection
* @see Selector
*/
filter: function(selector) {
return Y.all(Y.Selector.filter(this._nodes, selector));
},
/**
* Creates a new NodeList containing all nodes at every n indices, where
* remainder n % index equals r.
* (zero-based index).
* @method modulus
* @param {Int} n The offset to use (return every nth node)
* @param {Int} r An optional remainder to use with the modulus operation (defaults to zero)
* @return {NodeList} NodeList containing the updated collection
*/
modulus: function(n, r) {
r = r || 0;
var nodes = [];
NodeList.each(this, function(node, i) {
if (i % n === r) {
nodes.push(node);
}
});
return Y.all(nodes);
},
/**
* Creates a new NodeList containing all nodes at odd indices
* (zero-based index).
* @method odd
* @return {NodeList} NodeList containing the updated collection
*/
odd: function() {
return this.modulus(2, 1);
},
/**
* Creates a new NodeList containing all nodes at even indices
* (zero-based index), including zero.
* @method even
* @return {NodeList} NodeList containing the updated collection
*/
even: function() {
return this.modulus(2);
},
destructor: function() {
},
/**
* Reruns the initial query, when created using a selector query
* @method refresh
* @chainable
*/
refresh: function() {
var doc,
nodes = this._nodes,
query = this._query,
root = this._queryRoot;
if (query) {
if (!root) {
if (nodes && nodes[0] && nodes[0].ownerDocument) {
root = nodes[0].ownerDocument;
}
}
this._nodes = Y.Selector.query(query, root);
}
return this;
},
/**
* Returns the current number of items in the NodeList.
* @method size
* @return {Int} The number of items in the NodeList.
*/
size: function() {
return this._nodes.length;
},
/**
* Determines if the instance is bound to any nodes
* @method isEmpty
* @return {Boolean} Whether or not the NodeList is bound to any nodes
*/
isEmpty: function() {
return this._nodes.length < 1;
},
toString: function() {
var str = '',
errorMsg = this[UID] + ': not bound to any nodes',
nodes = this._nodes,
node;
if (nodes && nodes[0]) {
node = nodes[0];
str += node[NODE_NAME];
if (node.id) {
str += '#' + node.id;
}
if (node.className) {
str += '.' + node.className.replace(' ', '.');
}
if (nodes.length > 1) {
str += '...[' + nodes.length + ' items]';
}
}
return str || errorMsg;
},
/**
* Returns the DOM node bound to the Node instance
* @method getDOMNodes
* @return {Array}
*/
getDOMNodes: function() {
return this._nodes;
}
}, true);
NodeList.importMethod(Y.Node.prototype, [
/**
* Called on each Node instance. Nulls internal node references,
* removes any plugins and event listeners
* @method destroy
* @param {Boolean} recursivePurge (optional) Whether or not to
* remove listeners from the node's subtree (default is false)
* @see Node.destroy
*/
'destroy',
/**
* Called on each Node instance. Removes and destroys all of the nodes
* within the node
* @method empty
* @chainable
* @see Node.empty
*/
'empty',
/**
* Called on each Node instance. Removes the node from its parent.
* Shortcut for myNode.get('parentNode').removeChild(myNode);
* @method remove
* @param {Boolean} destroy whether or not to call destroy() on the node
* after removal.
* @chainable
* @see Node.remove
*/
'remove',
/**
* Called on each Node instance. Sets an attribute on the Node instance.
* Unless pre-configured (via Node.ATTRS), set hands
* off to the underlying DOM node. Only valid
* attributes/properties for the node will be set.
* To set custom attributes use setAttribute.
* @method set
* @param {String} attr The attribute to be set.
* @param {any} val The value to set the attribute to.
* @chainable
* @see Node.set
*/
'set'
]);
// one-off implementation to convert array of Nodes to NodeList
// e.g. Y.all('input').get('parentNode');
/** Called on each Node instance
* @method get
* @see Node
*/
NodeList.prototype.get = function(attr) {
var ret = [],
nodes = this._nodes,
isNodeList = false,
getTemp = NodeList._getTempNode,
instance,
val;
if (nodes[0]) {
instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]);
val = instance._get(attr);
if (val && val.nodeType) {
isNodeList = true;
}
}
Y.Array.each(nodes, function(node) {
instance = Y.Node._instances[node._yuid];
if (!instance) {
instance = getTemp(node);
}
val = instance._get(attr);
if (!isNodeList) { // convert array of Nodes to NodeList
val = Y.Node.scrubVal(val, instance);
}
ret.push(val);
});
return (isNodeList) ? Y.all(ret) : ret;
};
Y.NodeList = NodeList;
Y.all = function(nodes) {
return new NodeList(nodes);
};
Y.Node.all = Y.all;
/**
* @module node
* @submodule node-core
*/
var Y_NodeList = Y.NodeList,
ArrayProto = Array.prototype,
ArrayMethods = {
/** Returns a new NodeList combining the given NodeList(s)
* @for NodeList
* @method concat
* @param {NodeList | Array} valueN Arrays/NodeLists and/or values to
* concatenate to the resulting NodeList
* @return {NodeList} A new NodeList comprised of this NodeList joined with the input.
*/
'concat': 1,
/** Removes the last from the NodeList and returns it.
* @for NodeList
* @method pop
* @return {Node | null} The last item in the NodeList, or null if the list is empty.
*/
'pop': 0,
/** Adds the given Node(s) to the end of the NodeList.
* @for NodeList
* @method push
* @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList.
*/
'push': 0,
/** Removes the first item from the NodeList and returns it.
* @for NodeList
* @method shift
* @return {Node | null} The first item in the NodeList, or null if the NodeList is empty.
*/
'shift': 0,
/** Returns a new NodeList comprising the Nodes in the given range.
* @for NodeList
* @method slice
* @param {Number} begin Zero-based index at which to begin extraction.
As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence.
* @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end.
slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).
As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.
If end is omitted, slice extracts to the end of the sequence.
* @return {NodeList} A new NodeList comprised of this NodeList joined with the input.
*/
'slice': 1,
/** Changes the content of the NodeList, adding new elements while removing old elements.
* @for NodeList
* @method splice
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
* @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed.
* {Node | DOMNode| element1, ..., elementN
The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.
* @return {NodeList} The element(s) removed.
*/
'splice': 1,
/** Adds the given Node(s) to the beginning of the NodeList.
* @for NodeList
* @method unshift
* @param {Node | DOMNode} nodes One or more nodes to add to the NodeList.
*/
'unshift': 0
};
Y.Object.each(ArrayMethods, function(returnNodeList, name) {
Y_NodeList.prototype[name] = function() {
var args = [],
i = 0,
arg,
ret;
while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists
args.push(arg._node || arg._nodes || arg);
}
ret = ArrayProto[name].apply(this._nodes, args);
if (returnNodeList) {
ret = Y.all(ret);
} else {
ret = Y.Node.scrubVal(ret);
}
return ret;
};
});
/**
* @module node
* @submodule node-core
*/
Y.Array.each([
/**
* Passes through to DOM method.
* @for Node
* @method removeChild
* @param {HTMLElement | Node} node Node to be removed
* @return {Node} The removed node
*/
'removeChild',
/**
* Passes through to DOM method.
* @method hasChildNodes
* @return {Boolean} Whether or not the node has any childNodes
*/
'hasChildNodes',
/**
* Passes through to DOM method.
* @method cloneNode
* @param {Boolean} deep Whether or not to perform a deep clone, which includes
* subtree and attributes
* @return {Node} The clone
*/
'cloneNode',
/**
* Passes through to DOM method.
* @method hasAttribute
* @param {String} attribute The attribute to test for
* @return {Boolean} Whether or not the attribute is present
*/
'hasAttribute',
/**
* Passes through to DOM method.
* @method scrollIntoView
* @chainable
*/
'scrollIntoView',
/**
* Passes through to DOM method.
* @method getElementsByTagName
* @param {String} tagName The tagName to collect
* @return {NodeList} A NodeList representing the HTMLCollection
*/
'getElementsByTagName',
/**
* Passes through to DOM method.
* @method focus
* @chainable
*/
'focus',
/**
* Passes through to DOM method.
* @method blur
* @chainable
*/
'blur',
/**
* Passes through to DOM method.
* Only valid on FORM elements
* @method submit
* @chainable
*/
'submit',
/**
* Passes through to DOM method.
* Only valid on FORM elements
* @method reset
* @chainable
*/
'reset',
/**
* Passes through to DOM method.
* @method select
* @chainable
*/
'select',
/**
* Passes through to DOM method.
* Only valid on TABLE elements
* @method createCaption
* @chainable
*/
'createCaption'
], function(method) {
Y.Node.prototype[method] = function(arg1, arg2, arg3) {
var ret = this.invoke(method, arg1, arg2, arg3);
return ret;
};
});
/**
* Passes through to DOM method.
* @method removeAttribute
* @param {String} attribute The attribute to be removed
* @chainable
*/
// one-off implementation due to IE returning boolean, breaking chaining
Y.Node.prototype.removeAttribute = function(attr) {
var node = this._node;
if (node) {
node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive
}
return this;
};
Y.Node.importMethod(Y.DOM, [
/**
* Determines whether the node is an ancestor of another HTML element in the DOM hierarchy.
* @method contains
* @param {Node | HTMLElement} needle The possible node or descendent
* @return {Boolean} Whether or not this node is the needle its ancestor
*/
'contains',
/**
* Allows setting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method setAttribute
* @for Node
* @chainable
* @param {string} name The attribute name
* @param {string} value The value to set
*/
'setAttribute',
/**
* Allows getting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method getAttribute
* @for Node
* @param {string} name The attribute name
* @return {string} The attribute value
*/
'getAttribute',
/**
* Wraps the given HTML around the node.
* @method wrap
* @param {String} html The markup to wrap around the node.
* @chainable
* @for Node
*/
'wrap',
/**
* Removes the node's parent node.
* @method unwrap
* @chainable
*/
'unwrap',
/**
* Applies a unique ID to the node if none exists
* @method generateID
* @return {String} The existing or generated ID
*/
'generateID'
]);
Y.NodeList.importMethod(Y.Node.prototype, [
/**
* Allows getting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method getAttribute
* @see Node
* @for NodeList
* @param {string} name The attribute name
* @return {string} The attribute value
*/
'getAttribute',
/**
* Allows setting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method setAttribute
* @see Node
* @for NodeList
* @chainable
* @param {string} name The attribute name
* @param {string} value The value to set
*/
'setAttribute',
/**
* Allows for removing attributes on DOM nodes.
* This passes through to the DOM node, allowing for custom attributes.
* @method removeAttribute
* @see Node
* @for NodeList
* @param {string} name The attribute to remove
*/
'removeAttribute',
/**
* Removes the parent node from node in the list.
* @method unwrap
* @chainable
*/
'unwrap',
/**
* Wraps the given HTML around each node.
* @method wrap
* @param {String} html The markup to wrap around the node.
* @chainable
*/
'wrap',
/**
* Applies a unique ID to each node if none exists
* @method generateID
* @return {String} The existing or generated ID
*/
'generateID'
]);
}, 'patched-v3.11.0', {"requires": ["dom-core", "selector"]});
YUI.add('node-event-delegate', function (Y, NAME) {
/**
* Functionality to make the node a delegated event container
* @module node
* @submodule node-event-delegate
*/
/**
* Sets up a delegation listener for an event occurring inside the Node.
* The delegated event will be verified against a supplied selector or
* filtering function to test if the event references at least one node that
* should trigger the subscription callback.
*
* Selector string filters will trigger the callback if the event originated
* from a node that matches it or is contained in a node that matches it.
* Function filters are called for each Node up the parent axis to the
* subscribing container node, and receive at each level the Node and the event
* object. The function should return true (or a truthy value) if that Node
* should trigger the subscription callback. Note, it is possible for filters
* to match multiple Nodes for a single event. In this case, the delegate
* callback will be executed for each matching Node.
*
* For each matching Node, the callback will be executed with its 'this'
* object set to the Node matched by the filter (unless a specific context was
* provided during subscription), and the provided event's
* currentTarget
will also be set to the matching Node. The
* containing Node from which the subscription was originally made can be
* referenced as e.container
.
*
* @method delegate
* @param type {String} the event type to delegate
* @param fn {Function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param spec {String|Function} a selector that must match the target of the
* event or a function to test target and its parents for a match
* @param context {Object} optional argument that specifies what 'this' refers to.
* @param args* {any} 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for Node
*/
Y.Node.prototype.delegate = function(type) {
var args = Y.Array(arguments, 0, true),
index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2;
args.splice(index, 0, this._node);
return Y.delegate.apply(Y, args);
};
}, 'patched-v3.11.0', {"requires": ["node-base", "event-delegate"]});
YUI.add('node-event-simulate', function (Y, NAME) {
/**
* Adds functionality to simulate events.
* @module node
* @submodule node-event-simulate
*/
/**
* Simulates an event on the node.
* @param {String} type The type of event (i.e., "click").
* @param {Object} options (Optional) Extra options to copy onto the event object.
* @return {void}
* @for Node
* @method simulate
*/
Y.Node.prototype.simulate = function (type, options) {
Y.Event.simulate(Y.Node.getDOMNode(this), type, options);
};
/**
* Simulates the higher user level gesture of the given name on this node.
* This method generates a set of low level touch events(Apple specific gesture
* events as well for the iOS platforms) asynchronously. Note that gesture
* simulation is relying on `Y.Event.simulate()` method to generate
* the touch events under the hood. The `Y.Event.simulate()` method
* itself is a synchronous method.
*
* Supported gestures are `tap`, `doubletap`, `press`, `move`, `flick`, `pinch`
* and `rotate`.
*
* The `pinch` gesture is used to simulate the pinching and spreading of two
* fingers. During a pinch simulation, rotation is also possible. Essentially
* `pinch` and `rotate` simulations share the same base implementation to allow
* both pinching and rotation at the same time. The only difference is `pinch`
* requires `start` and `end` option properties while `rotate` requires `rotation`
* option property.
*
* The `pinch` and `rotate` gestures can be described as placing 2 fingers along a
* circle. Pinching and spreading can be described by start and end circles while
* rotation occurs on a single circle. If the radius of the start circle is greater
* than the end circle, the gesture becomes a pinch, otherwise it is a spread spread.
*
* @example
*
* var node = Y.one("#target");
*
* // double tap example
* node.simulateGesture("doubletap", function() {
* // my callback function
* });
*
* // flick example from the center of the node, move 50 pixels down for 50ms)
* node.simulateGesture("flick", {
* axis: y,
* distance: -100
* duration: 50
* }, function() {
* // my callback function
* });
*
* // simulate rotating a node 75 degrees counter-clockwise
* node.simulateGesture("rotate", {
* rotation: -75
* });
*
* // simulate a pinch and a rotation at the same time.
* // fingers start on a circle of radius 100 px, placed at top/bottom
* // fingers end on a circle of radius 50px, placed at right/left
* node.simulateGesture("pinch", {
* r1: 100,
* r2: 50,
* start: 0
* rotation: 90
* });
*
* @method simulateGesture
* @param {String} name The name of the supported gesture to simulate. The
* supported gesture name is one of "tap", "doubletap", "press", "move",
* "flick", "pinch" and "rotate".
* @param {Object} [options] Extra options used to define the gesture behavior:
*
* Valid options properties for the `tap` gesture:
*
* @param {Array} [options.point] (Optional) Indicates the [x,y] coordinates
* where the tap should be simulated. Default is the center of the node
* element.
* @param {Number} [options.hold=10] (Optional) The hold time in milliseconds.
* This is the time between `touchstart` and `touchend` event generation.
* @param {Number} [options.times=1] (Optional) Indicates the number of taps.
* @param {Number} [options.delay=10] (Optional) The number of milliseconds
* before the next tap simulation happens. This is valid only when `times`
* is more than 1.
*
* Valid options properties for the `doubletap` gesture:
*
* @param {Array} [options.point] (Optional) Indicates the [x,y] coordinates
* where the doubletap should be simulated. Default is the center of the
* node element.
*
* Valid options properties for the `press` gesture:
*
* @param {Array} [options.point] (Optional) Indicates the [x,y] coordinates
* where the press should be simulated. Default is the center of the node
* element.
* @param {Number} [options.hold=3000] (Optional) The hold time in milliseconds.
* This is the time between `touchstart` and `touchend` event generation.
* Default is 3000ms (3 seconds).
*
* Valid options properties for the `move` gesture:
*
* @param {Object} [options.path] (Optional) Indicates the path of the finger
* movement. It's an object with three optional properties: `point`,
* `xdist` and `ydist`.
* @param {Array} [options.path.point] A starting point of the gesture.
* Default is the center of the node element.
* @param {Number} [options.path.xdist=200] A distance to move in pixels
* along the X axis. A negative distance value indicates moving left.
* @param {Number} [options.path.ydist=0] A distance to move in pixels
* along the Y axis. A negative distance value indicates moving up.
* @param {Number} [options.duration=1000] (Optional) The duration of the
* gesture in milliseconds.
*
* Valid options properties for the `flick` gesture:
*
* @param {Array} [options.point] (Optional) Indicates the [x, y] coordinates
* where the flick should be simulated. Default is the center of the
* node element.
* @param {String} [options.axis='x'] (Optional) Valid values are either
* "x" or "y". Indicates axis to move along. The flick can move to one of
* 4 directions(left, right, up and down).
* @param {Number} [options.distance=200] (Optional) Distance to move in pixels
* @param {Number} [options.duration=1000] (Optional) The duration of the
* gesture in milliseconds. User given value could be automatically
* adjusted by the framework if it is below the minimum velocity to be
* a flick gesture.
*
* Valid options properties for the `pinch` gesture:
*
* @param {Array} [options.center] (Optional) The center of the circle where
* two fingers are placed. Default is the center of the node element.
* @param {Number} [options.r1] (Required) Pixel radius of the start circle
* where 2 fingers will be on when the gesture starts. The circles are
* centered at the center of the element.
* @param {Number} [options.r2] (Required) Pixel radius of the end circle
* when this gesture ends.
* @param {Number} [options.duration=1000] (Optional) The duration of the
* gesture in milliseconds.
* @param {Number} [options.start=0] (Optional) Starting degree of the first
* finger. The value is relative to the path of the north. Default is 0
* (i.e., 12:00 on a clock).
* @param {Number} [options.rotation=0] (Optional) Degrees to rotate from
* the starting degree. A negative value means rotation to the
* counter-clockwise direction.
*
* Valid options properties for the `rotate` gesture:
*
* @param {Array} [options.center] (Optional) The center of the circle where
* two fingers are placed. Default is the center of the node element.
* @param {Number} [options.r1] (Optional) Pixel radius of the start circle
* where 2 fingers will be on when the gesture starts. The circles are
* centered at the center of the element. Default is a fourth of the node
* element width or height, whichever is smaller.
* @param {Number} [options.r2] (Optional) Pixel radius of the end circle
* when this gesture ends. Default is a fourth of the node element width or
* height, whichever is smaller.
* @param {Number} [options.duration=1000] (Optional) The duration of the
* gesture in milliseconds.
* @param {Number} [options.start=0] (Optional) Starting degree of the first
* finger. The value is relative to the path of the north. Default is 0
* (i.e., 12:00 on a clock).
* @param {Number} [options.rotation] (Required) Degrees to rotate from
* the starting degree. A negative value means rotation to the
* counter-clockwise direction.
*
* @param {Function} [cb] The callback to execute when the asynchronouse gesture
* simulation is completed.
* @param {Error} cb.err An error object if the simulation is failed.
* @return {void}
* @for Node
*/
Y.Node.prototype.simulateGesture = function (name, options, cb) {
Y.Event.simulateGesture(this, name, options, cb);
};
}, 'patched-v3.11.0', {"requires": ["node-base", "event-simulate", "gesture-simulate"]});
YUI.add('node-focusmanager', function (Y, NAME) {
/**
*
The Focus Manager Node Plugin makes it easy to manage focus among
* a Node's descendants. Primarily intended to help with widget development,
* the Focus Manager Node Plugin can be used to improve the keyboard
* accessibility of widgets.
*
*
* When designing widgets that manage a set of descendant controls (i.e. buttons
* in a toolbar, tabs in a tablist, menuitems in a menu, etc.) it is important to
* limit the number of descendants in the browser's default tab flow. The fewer
* number of descendants in the default tab flow, the easier it is for keyboard
* users to navigate between widgets by pressing the tab key. When a widget has
* focus it should provide a set of shortcut keys (typically the arrow keys)
* to move focus among its descendants.
*
*
*
* To this end, the Focus Manager Node Plugin makes it easy to define a Node's
* focusable descendants, define which descendant should be in the default tab
* flow, and define the keys that move focus among each descendant.
* Additionally, as the CSS
* :focus
* pseudo class is not supported on all elements in all
* A-Grade browsers ,
* the Focus Manager Node Plugin provides an easy, cross-browser means of
* styling focus.
*
*
DEPRECATED: The FocusManager Node Plugin has been deprecated as of YUI 3.9.0. This module will be removed from the library in a future version. If you require functionality similar to the one provided by this module, consider taking a look at the various modules in the YUI Gallery .
* @module node-focusmanager
* @deprecated 3.9.0
*/
// Frequently used strings
var ACTIVE_DESCENDANT = "activeDescendant",
ID = "id",
DISABLED = "disabled",
TAB_INDEX = "tabIndex",
FOCUSED = "focused",
FOCUS_CLASS = "focusClass",
CIRCULAR = "circular",
UI = "UI",
KEY = "key",
ACTIVE_DESCENDANT_CHANGE = ACTIVE_DESCENDANT + "Change",
HOST = "host",
// Collection of keys that, when pressed, cause the browser viewport
// to scroll.
scrollKeys = {
37: true,
38: true,
39: true,
40: true
},
clickableElements = {
"a": true,
"button": true,
"input": true,
"object": true
},
// Library shortcuts
Lang = Y.Lang,
UA = Y.UA,
/**
* The NodeFocusManager class is a plugin for a Node instance. The class is used
* via the plug
method of Node
* and should not be instantiated directly.
* @namespace plugin
* @class NodeFocusManager
*/
NodeFocusManager = function () {
NodeFocusManager.superclass.constructor.apply(this, arguments);
};
NodeFocusManager.ATTRS = {
/**
* Boolean indicating that one of the descendants is focused.
*
* @attribute focused
* @readOnly
* @default false
* @type boolean
*/
focused: {
value: false,
readOnly: true
},
/**
* String representing the CSS selector used to define the descendant Nodes
* whose focus should be managed.
*
* @attribute descendants
* @type Y.NodeList
*/
descendants: {
getter: function (value) {
return this.get(HOST).all(value);
}
},
/**
* Node, or index of the Node, representing the descendant that is either
* focused or is focusable (tabIndex
attribute is set to 0).
* The value cannot represent a disabled descendant Node. Use a value of -1
* to remove all descendant Nodes from the default tab flow.
* If no value is specified, the active descendant will be inferred using
* the following criteria:
*
* Examining the tabIndex
attribute of each descendant and
* using the first descendant whose tabIndex
attribute is set
* to 0
* If no default can be inferred then the value is set to either 0 or
* the index of the first enabled descendant.
*
*
* @attribute activeDescendant
* @type Number
*/
activeDescendant: {
setter: function (value) {
var isNumber = Lang.isNumber,
INVALID_VALUE = Y.Attribute.INVALID_VALUE,
descendantsMap = this._descendantsMap,
descendants = this._descendants,
nodeIndex,
returnValue,
oNode;
if (isNumber(value)) {
nodeIndex = value;
returnValue = nodeIndex;
}
else if ((value instanceof Y.Node) && descendantsMap) {
nodeIndex = descendantsMap[value.get(ID)];
if (isNumber(nodeIndex)) {
returnValue = nodeIndex;
}
else {
// The user passed a reference to a Node that wasn't one
// of the descendants.
returnValue = INVALID_VALUE;
}
}
else {
returnValue = INVALID_VALUE;
}
if (descendants) {
oNode = descendants.item(nodeIndex);
if (oNode && oNode.get("disabled")) {
// Setting the "activeDescendant" attribute to the index
// of a disabled descendant is invalid.
returnValue = INVALID_VALUE;
}
}
return returnValue;
}
},
/**
* Object literal representing the keys to be used to navigate between the
* next/previous descendant. The format for the attribute's value is
* { next: "down:40", previous: "down:38" }
. The value for the
* "next" and "previous" properties are used to attach
* key
event listeners. See
* the Using the key Event section of
* the Event documentation for more information on "key" event listeners.
*
* @attribute keys
* @type Object
*/
keys: {
value: {
next: null,
previous: null
}
},
/**
* String representing the name of class applied to the focused active
* descendant Node. Can also be an object literal used to define both the
* class name, and the Node to which the class should be applied. If using
* an object literal, the format is:
* { className: "focus", fn: myFunction }
. The function
* referenced by the fn
property in the object literal will be
* passed a reference to the currently focused active descendant Node.
*
* @attribute focusClass
* @type String|Object
*/
focusClass: { },
/**
* Boolean indicating if focus should be set to the first/last descendant
* when the end or beginning of the descendants has been reached.
*
* @attribute circular
* @type Boolean
* @default true
*/
circular: {
value: true
}
};
Y.extend(NodeFocusManager, Y.Plugin.Base, {
// Protected properties
// Boolean indicating if the NodeFocusManager is active.
_stopped: true,
// NodeList representing the descendants selected via the
// "descendants" attribute.
_descendants: null,
// Object literal mapping the IDs of each descendant to its index in the
// "_descendants" NodeList.
_descendantsMap: null,
// Reference to the Node instance to which the focused class (defined
// by the "focusClass" attribute) is currently applied.
_focusedNode: null,
// Number representing the index of the last descendant Node.
_lastNodeIndex: 0,
// Array of handles for event handlers used for a NodeFocusManager instance.
_eventHandlers: null,
// Protected methods
/**
* @method _initDescendants
* @description Sets the tabIndex
attribute of all of the
* descendants to -1, except the active descendant, whose
* tabIndex
attribute is set to 0.
* @protected
*/
_initDescendants: function () {
var descendants = this.get("descendants"),
descendantsMap = {},
nFirstEnabled = -1,
nDescendants,
nActiveDescendant = this.get(ACTIVE_DESCENDANT),
oNode,
sID,
i = 0;
if (Lang.isUndefined(nActiveDescendant)) {
nActiveDescendant = -1;
}
if (descendants) {
nDescendants = descendants.size();
for (i = 0; i < nDescendants; i++) {
oNode = descendants.item(i);
if (nFirstEnabled === -1 && !oNode.get(DISABLED)) {
nFirstEnabled = i;
}
// If the user didn't specify a value for the
// "activeDescendant" attribute try to infer it from
// the markup.
// Need to pass "2" when using "getAttribute" for IE to get
// the attribute value as it is set in the markup.
// Need to use "parseInt" because IE always returns the
// value as a number, whereas all other browsers return
// the attribute as a string when accessed
// via "getAttribute".
if (nActiveDescendant < 0 &&
parseInt(oNode.getAttribute(TAB_INDEX, 2), 10) === 0) {
nActiveDescendant = i;
}
if (oNode) {
oNode.set(TAB_INDEX, -1);
}
sID = oNode.get(ID);
if (!sID) {
sID = Y.guid();
oNode.set(ID, sID);
}
descendantsMap[sID] = i;
}
// If the user didn't specify a value for the
// "activeDescendant" attribute and no default value could be
// determined from the markup, then default to 0.
if (nActiveDescendant < 0) {
nActiveDescendant = 0;
}
oNode = descendants.item(nActiveDescendant);
// Check to make sure the active descendant isn't disabled,
// and fall back to the first enabled descendant if it is.
if (!oNode || oNode.get(DISABLED)) {
oNode = descendants.item(nFirstEnabled);
nActiveDescendant = nFirstEnabled;
}
this._lastNodeIndex = nDescendants - 1;
this._descendants = descendants;
this._descendantsMap = descendantsMap;
this.set(ACTIVE_DESCENDANT, nActiveDescendant);
// Need to set the "tabIndex" attribute here, since the
// "activeDescendantChange" event handler used to manage
// the setting of the "tabIndex" attribute isn't wired up yet.
if (oNode) {
oNode.set(TAB_INDEX, 0);
}
}
},
/**
* @method _isDescendant
* @description Determines if the specified Node instance is a descendant
* managed by the Focus Manager.
* @param node {Node} Node instance to be checked.
* @return {Boolean} Boolean indicating if the specified Node instance is a
* descendant managed by the Focus Manager.
* @protected
*/
_isDescendant: function (node) {
return (node.get(ID) in this._descendantsMap);
},
/**
* @method _removeFocusClass
* @description Removes the class name representing focus (as specified by
* the "focusClass" attribute) from the Node instance to which it is
* currently applied.
* @protected
*/
_removeFocusClass: function () {
var oFocusedNode = this._focusedNode,
focusClass = this.get(FOCUS_CLASS),
sClassName;
if (focusClass) {
sClassName = Lang.isString(focusClass) ?
focusClass : focusClass.className;
}
if (oFocusedNode && sClassName) {
oFocusedNode.removeClass(sClassName);
}
},
/**
* @method _detachKeyHandler
* @description Detaches the "key" event handlers used to support the "keys"
* attribute.
* @protected
*/
_detachKeyHandler: function () {
var prevKeyHandler = this._prevKeyHandler,
nextKeyHandler = this._nextKeyHandler;
if (prevKeyHandler) {
prevKeyHandler.detach();
}
if (nextKeyHandler) {
nextKeyHandler.detach();
}
},
/**
* @method _preventScroll
* @description Prevents the viewport from scolling when the user presses
* the up, down, left, or right key.
* @protected
*/
_preventScroll: function (event) {
if (scrollKeys[event.keyCode] && this._isDescendant(event.target)) {
event.preventDefault();
}
},
/**
* @method _fireClick
* @description Fires the click event if the enter key is pressed while
* focused on an HTML element that is not natively clickable.
* @protected
*/
_fireClick: function (event) {
var oTarget = event.target,
sNodeName = oTarget.get("nodeName").toLowerCase();
if (event.keyCode === 13 && (!clickableElements[sNodeName] ||
(sNodeName === "a" && !oTarget.getAttribute("href")))) {
oTarget.simulate("click");
}
},
/**
* @method _attachKeyHandler
* @description Attaches the "key" event handlers used to support the "keys"
* attribute.
* @protected
*/
_attachKeyHandler: function () {
this._detachKeyHandler();
var sNextKey = this.get("keys.next"),
sPrevKey = this.get("keys.previous"),
oNode = this.get(HOST),
aHandlers = this._eventHandlers;
if (sPrevKey) {
this._prevKeyHandler =
Y.on(KEY, Y.bind(this._focusPrevious, this), oNode, sPrevKey);
}
if (sNextKey) {
this._nextKeyHandler =
Y.on(KEY, Y.bind(this._focusNext, this), oNode, sNextKey);
}
// In Opera it is necessary to call the "preventDefault" method in
// response to the user pressing the arrow keys in order to prevent
// the viewport from scrolling when the user is moving focus among
// the focusable descendants.
if (UA.opera) {
aHandlers.push(oNode.on("keypress", this._preventScroll, this));
}
// For all browsers except Opera: HTML elements that are not natively
// focusable but made focusable via the tabIndex attribute don't
// fire a click event when the user presses the enter key. It is
// possible to work around this problem by simplying dispatching a
// click event in response to the user pressing the enter key.
if (!UA.opera) {
aHandlers.push(oNode.on("keypress", this._fireClick, this));
}
},
/**
* @method _detachEventHandlers
* @description Detaches all event handlers used by the Focus Manager.
* @protected
*/
_detachEventHandlers: function () {
this._detachKeyHandler();
var aHandlers = this._eventHandlers;
if (aHandlers) {
Y.Array.each(aHandlers, function (handle) {
handle.detach();
});
this._eventHandlers = null;
}
},
/**
* @method _detachEventHandlers
* @description Attaches all event handlers used by the Focus Manager.
* @protected
*/
_attachEventHandlers: function () {
var descendants = this._descendants,
aHandlers,
oDocument,
handle;
if (descendants && descendants.size()) {
aHandlers = this._eventHandlers || [];
oDocument = this.get(HOST).get("ownerDocument");
if (aHandlers.length === 0) {
aHandlers.push(oDocument.on("focus", this._onDocFocus, this));
aHandlers.push(oDocument.on("mousedown",
this._onDocMouseDown, this));
aHandlers.push(
this.after("keysChange", this._attachKeyHandler));
aHandlers.push(
this.after("descendantsChange", this._initDescendants));
aHandlers.push(
this.after(ACTIVE_DESCENDANT_CHANGE,
this._afterActiveDescendantChange));
// For performance: defer attaching all key-related event
// handlers until the first time one of the specified
// descendants receives focus.
handle = this.after("focusedChange", Y.bind(function (event) {
if (event.newVal) {
this._attachKeyHandler();
// Detach this "focusedChange" handler so that the
// key-related handlers only get attached once.
handle.detach();
}
}, this));
aHandlers.push(handle);
}
this._eventHandlers = aHandlers;
}
},
// Protected event handlers
/**
* @method _onDocMouseDown
* @description "mousedown" event handler for the owner document of the
* Focus Manager's Node.
* @protected
* @param event {Object} Object representing the DOM event.
*/
_onDocMouseDown: function (event) {
var oHost = this.get(HOST),
oTarget = event.target,
bChildNode = oHost.contains(oTarget),
node,
getFocusable = function (node) {
var returnVal = false;
if (!node.compareTo(oHost)) {
returnVal = this._isDescendant(node) ? node :
getFocusable.call(this, node.get("parentNode"));
}
return returnVal;
};
if (bChildNode) {
// Check to make sure that the target isn't a child node of one
// of the focusable descendants.
node = getFocusable.call(this, oTarget);
if (node) {
oTarget = node;
}
else if (!node && this.get(FOCUSED)) {
// The target was a non-focusable descendant of the root
// node, so the "focused" attribute should be set to false.
this._set(FOCUSED, false);
this._onDocFocus(event);
}
}
if (bChildNode && this._isDescendant(oTarget)) {
// Fix general problem in Webkit: mousing down on a button or an
// anchor element doesn't focus it.
// For all browsers: makes sure that the descendant that
// was the target of the mousedown event is now considered the
// active descendant.
this.focus(oTarget);
}
else if (UA.webkit && this.get(FOCUSED) &&
(!bChildNode || (bChildNode && !this._isDescendant(oTarget)))) {
// Fix for Webkit:
// Document doesn't receive focus in Webkit when the user mouses
// down on it, so the "focused" attribute won't get set to the
// correct value.
// The goal is to force a blur if the user moused down on
// either: 1) A descendant node, but not one that managed by
// the FocusManager, or 2) an element outside of the
// FocusManager
this._set(FOCUSED, false);
this._onDocFocus(event);
}
},
/**
* @method _onDocFocus
* @description "focus" event handler for the owner document of the
* Focus Manager's Node.
* @protected
* @param event {Object} Object representing the DOM event.
*/
_onDocFocus: function (event) {
var oTarget = this._focusTarget || event.target,
bFocused = this.get(FOCUSED),
focusClass = this.get(FOCUS_CLASS),
oFocusedNode = this._focusedNode,
bInCollection;
if (this._focusTarget) {
this._focusTarget = null;
}
if (this.get(HOST).contains(oTarget)) {
// The target is a descendant of the root Node.
bInCollection = this._isDescendant(oTarget);
if (!bFocused && bInCollection) {
// The user has focused a focusable descendant.
bFocused = true;
}
else if (bFocused && !bInCollection) {
// The user has focused a child of the root Node that is
// not one of the descendants managed by this Focus Manager
// so clear the currently focused descendant.
bFocused = false;
}
}
else {
// The target is some other node in the document.
bFocused = false;
}
if (focusClass) {
if (oFocusedNode && (!oFocusedNode.compareTo(oTarget) || !bFocused)) {
this._removeFocusClass();
}
if (bInCollection && bFocused) {
if (focusClass.fn) {
oTarget = focusClass.fn(oTarget);
oTarget.addClass(focusClass.className);
}
else {
oTarget.addClass(focusClass);
}
this._focusedNode = oTarget;
}
}
this._set(FOCUSED, bFocused);
},
/**
* @method _focusNext
* @description Keydown event handler that moves focus to the next
* enabled descendant.
* @protected
* @param event {Object} Object representing the DOM event.
* @param activeDescendant {Number} Number representing the index of the
* next descendant to be focused
*/
_focusNext: function (event, activeDescendant) {
var nActiveDescendant = activeDescendant || this.get(ACTIVE_DESCENDANT),
oNode;
if (this._isDescendant(event.target) &&
(nActiveDescendant <= this._lastNodeIndex)) {
nActiveDescendant = nActiveDescendant + 1;
if (nActiveDescendant === (this._lastNodeIndex + 1) &&
this.get(CIRCULAR)) {
nActiveDescendant = 0;
}
oNode = this._descendants.item(nActiveDescendant);
if (oNode) {
if (oNode.get("disabled")) {
this._focusNext(event, nActiveDescendant);
}
else {
this.focus(nActiveDescendant);
}
}
}
this._preventScroll(event);
},
/**
* @method _focusPrevious
* @description Keydown event handler that moves focus to the previous
* enabled descendant.
* @protected
* @param event {Object} Object representing the DOM event.
* @param activeDescendant {Number} Number representing the index of the
* next descendant to be focused.
*/
_focusPrevious: function (event, activeDescendant) {
var nActiveDescendant = activeDescendant || this.get(ACTIVE_DESCENDANT),
oNode;
if (this._isDescendant(event.target) && nActiveDescendant >= 0) {
nActiveDescendant = nActiveDescendant - 1;
if (nActiveDescendant === -1 && this.get(CIRCULAR)) {
nActiveDescendant = this._lastNodeIndex;
}
oNode = this._descendants.item(nActiveDescendant);
if (oNode) {
if (oNode.get("disabled")) {
this._focusPrevious(event, nActiveDescendant);
}
else {
this.focus(nActiveDescendant);
}
}
}
this._preventScroll(event);
},
/**
* @method _afterActiveDescendantChange
* @description afterChange event handler for the
* "activeDescendant" attribute.
* @protected
* @param event {Object} Object representing the change event.
*/
_afterActiveDescendantChange: function (event) {
var oNode = this._descendants.item(event.prevVal);
if (oNode) {
oNode.set(TAB_INDEX, -1);
}
oNode = this._descendants.item(event.newVal);
if (oNode) {
oNode.set(TAB_INDEX, 0);
}
},
// Public methods
initializer: function (config) {
this.start();
},
destructor: function () {
this.stop();
this.get(HOST).focusManager = null;
},
/**
* @method focus
* @description Focuses the active descendant and sets the
* focused
attribute to true.
* @param index {Number} Optional. Number representing the index of the
* descendant to be set as the active descendant.
* @param index {Node} Optional. Node instance representing the
* descendant to be set as the active descendant.
*/
focus: function (index) {
if (Lang.isUndefined(index)) {
index = this.get(ACTIVE_DESCENDANT);
}
this.set(ACTIVE_DESCENDANT, index, { src: UI });
var oNode = this._descendants.item(this.get(ACTIVE_DESCENDANT));
if (oNode) {
oNode.focus();
// In Opera focusing a element programmatically
// will result in the document-level focus event handler
// "_onDocFocus" being called, resulting in the handler
// incorrectly setting the "focused" Attribute to false. To fix
// this, set a flag ("_focusTarget") that the "_onDocFocus" method
// can look for to properly handle this edge case.
if (UA.opera && oNode.get("nodeName").toLowerCase() === "button") {
this._focusTarget = oNode;
}
}
},
/**
* @method blur
* @description Blurs the current active descendant and sets the
* focused
attribute to false.
*/
blur: function () {
var oNode;
if (this.get(FOCUSED)) {
oNode = this._descendants.item(this.get(ACTIVE_DESCENDANT));
if (oNode) {
oNode.blur();
// For Opera and Webkit: Blurring an element in either browser
// doesn't result in another element (such as the document)
// being focused. Therefore, the "_onDocFocus" method
// responsible for managing the application and removal of the
// focus indicator class name is never called.
this._removeFocusClass();
}
this._set(FOCUSED, false, { src: UI });
}
},
/**
* @method start
* @description Enables the Focus Manager.
*/
start: function () {
if (this._stopped) {
this._initDescendants();
this._attachEventHandlers();
this._stopped = false;
}
},
/**
* @method stop
* @description Disables the Focus Manager by detaching all event handlers.
*/
stop: function () {
if (!this._stopped) {
this._detachEventHandlers();
this._descendants = null;
this._focusedNode = null;
this._lastNodeIndex = 0;
this._stopped = true;
}
},
/**
* @method refresh
* @description Refreshes the Focus Manager's descendants by re-executing the
* CSS selector query specified by the descendants
attribute.
*/
refresh: function () {
this._initDescendants();
if (!this._eventHandlers) {
this._attachEventHandlers();
}
}
});
NodeFocusManager.NAME = "nodeFocusManager";
NodeFocusManager.NS = "focusManager";
Y.namespace("Plugin");
Y.Plugin.NodeFocusManager = NodeFocusManager;
}, 'patched-v3.11.0', {"requires": ["attribute", "node", "plugin", "node-event-simulate", "event-key", "event-focus"]});
YUI.add('node-pluginhost', function (Y, NAME) {
/**
* @module node
* @submodule node-pluginhost
*/
/**
* Registers plugins to be instantiated at the class level (plugins
* which should be plugged into every instance of Node by default).
*
* @method plug
* @static
* @for Node
* @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined)
* @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin
*/
Y.Node.plug = function() {
var args = Y.Array(arguments);
args.unshift(Y.Node);
Y.Plugin.Host.plug.apply(Y.Base, args);
return Y.Node;
};
/**
* Unregisters any class level plugins which have been registered by the Node
*
* @method unplug
* @static
*
* @param {Function | Array} plugin The plugin class, or an array of plugin classes
*/
Y.Node.unplug = function() {
var args = Y.Array(arguments);
args.unshift(Y.Node);
Y.Plugin.Host.unplug.apply(Y.Base, args);
return Y.Node;
};
Y.mix(Y.Node, Y.Plugin.Host, false, null, 1);
// allow batching of plug/unplug via NodeList
// doesn't use NodeList.importMethod because we need real Nodes (not tmpNode)
/**
* Adds a plugin to each node in the NodeList.
* This will instantiate the plugin and attach it to the configured namespace on each node
* @method plug
* @for NodeList
* @param P {Function | Object |Array} Accepts the plugin class, or an
* object with a "fn" property specifying the plugin class and
* a "cfg" property specifying the configuration for the Plugin.
*
* Additionally an Array can also be passed in, with the above function or
* object values, allowing the user to add multiple plugins in a single call.
*
* @param config (Optional) If the first argument is the plugin class, the second argument
* can be the configuration for the plugin.
* @chainable
*/
Y.NodeList.prototype.plug = function() {
var args = arguments;
Y.NodeList.each(this, function(node) {
Y.Node.prototype.plug.apply(Y.one(node), args);
});
return this;
};
/**
* Removes a plugin from all nodes in the NodeList. This will destroy the
* plugin instance and delete the namespace each node.
* @method unplug
* @for NodeList
* @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided,
* all registered plugins are unplugged.
* @chainable
*/
Y.NodeList.prototype.unplug = function() {
var args = arguments;
Y.NodeList.each(this, function(node) {
Y.Node.prototype.unplug.apply(Y.one(node), args);
});
return this;
};
}, 'patched-v3.11.0', {"requires": ["node-base", "pluginhost"]});
YUI.add('node-screen', function (Y, NAME) {
/**
* Extended Node interface for managing regions and screen positioning.
* Adds support for positioning elements and normalizes window size and scroll detection.
* @module node
* @submodule node-screen
*/
// these are all "safe" returns, no wrapping required
Y.each([
/**
* Returns the inner width of the viewport (exludes scrollbar).
* @config winWidth
* @for Node
* @type {Int}
*/
'winWidth',
/**
* Returns the inner height of the viewport (exludes scrollbar).
* @config winHeight
* @type {Int}
*/
'winHeight',
/**
* Document width
* @config docWidth
* @type {Int}
*/
'docWidth',
/**
* Document height
* @config docHeight
* @type {Int}
*/
'docHeight',
/**
* Pixel distance the page has been scrolled horizontally
* @config docScrollX
* @type {Int}
*/
'docScrollX',
/**
* Pixel distance the page has been scrolled vertically
* @config docScrollY
* @type {Int}
*/
'docScrollY'
],
function(name) {
Y.Node.ATTRS[name] = {
getter: function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(Y.Node.getDOMNode(this));
return Y.DOM[name].apply(this, args);
}
};
}
);
Y.Node.ATTRS.scrollLeft = {
getter: function() {
var node = Y.Node.getDOMNode(this);
return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node);
},
setter: function(val) {
var node = Y.Node.getDOMNode(this);
if (node) {
if ('scrollLeft' in node) {
node.scrollLeft = val;
} else if (node.document || node.nodeType === 9) {
Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc
}
} else {
}
}
};
Y.Node.ATTRS.scrollTop = {
getter: function() {
var node = Y.Node.getDOMNode(this);
return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node);
},
setter: function(val) {
var node = Y.Node.getDOMNode(this);
if (node) {
if ('scrollTop' in node) {
node.scrollTop = val;
} else if (node.document || node.nodeType === 9) {
Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc
}
} else {
}
}
};
Y.Node.importMethod(Y.DOM, [
/**
* Gets the current position of the node in page coordinates.
* @method getXY
* @for Node
* @return {Array} The XY position of the node
*/
'getXY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setXY
* @param {Array} xy Contains X & Y values for new position (coordinates are page-based)
* @chainable
*/
'setXY',
/**
* Gets the current position of the node in page coordinates.
* @method getX
* @return {Int} The X position of the node
*/
'getX',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setX
* @param {Int} x X value for new position (coordinates are page-based)
* @chainable
*/
'setX',
/**
* Gets the current position of the node in page coordinates.
* @method getY
* @return {Int} The Y position of the node
*/
'getY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setY
* @param {Int} y Y value for new position (coordinates are page-based)
* @chainable
*/
'setY',
/**
* Swaps the XY position of this node with another node.
* @method swapXY
* @param {Node | HTMLElement} otherNode The node to swap with.
* @chainable
*/
'swapXY'
]);
/**
* @module node
* @submodule node-screen
*/
/**
* Returns a region object for the node
* @config region
* @for Node
* @type Node
*/
Y.Node.ATTRS.region = {
getter: function() {
var node = this.getDOMNode(),
region;
if (node && !node.tagName) {
if (node.nodeType === 9) { // document
node = node.documentElement;
}
}
if (Y.DOM.isWindow(node)) {
region = Y.DOM.viewportRegion(node);
} else {
region = Y.DOM.region(node);
}
return region;
}
};
/**
* Returns a region object for the node's viewport
* @config viewportRegion
* @type Node
*/
Y.Node.ATTRS.viewportRegion = {
getter: function() {
return Y.DOM.viewportRegion(Y.Node.getDOMNode(this));
}
};
Y.Node.importMethod(Y.DOM, 'inViewportRegion');
// these need special treatment to extract 2nd node arg
/**
* Compares the intersection of the node with another node or region
* @method intersect
* @for Node
* @param {Node|Object} node2 The node or region to compare with.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Object} An object representing the intersection of the regions.
*/
Y.Node.prototype.intersect = function(node2, altRegion) {
var node1 = Y.Node.getDOMNode(this);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
node2 = Y.Node.getDOMNode(node2);
}
return Y.DOM.intersect(node1, node2, altRegion);
};
/**
* Determines whether or not the node is within the giving region.
* @method inRegion
* @param {Node|Object} node2 The node or region to compare with.
* @param {Boolean} all Whether or not all of the node must be in the region.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Boolean} True if in region, false if not.
*/
Y.Node.prototype.inRegion = function(node2, all, altRegion) {
var node1 = Y.Node.getDOMNode(this);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
node2 = Y.Node.getDOMNode(node2);
}
return Y.DOM.inRegion(node1, node2, all, altRegion);
};
}, 'patched-v3.11.0', {"requires": ["dom-screen", "node-base"]});
YUI.add('node-style', function (Y, NAME) {
(function(Y) {
/**
* Extended Node interface for managing node styles.
* @module node
* @submodule node-style
*/
Y.mix(Y.Node.prototype, {
/**
* Sets a style property of the node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyle
* @param {String} attr The style attribute to set.
* @param {String|Number} val The value.
* @chainable
*/
setStyle: function(attr, val) {
Y.DOM.setStyle(this._node, attr, val);
return this;
},
/**
* Sets multiple style properties on the node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyles
* @param {Object} hash An object literal of property:value pairs.
* @chainable
*/
setStyles: function(hash) {
Y.DOM.setStyles(this._node, hash);
return this;
},
/**
* Returns the style's current value.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getStyle
* @for Node
* @param {String} attr The style attribute to retrieve.
* @return {String} The current value of the style property for the element.
*/
getStyle: function(attr) {
return Y.DOM.getStyle(this._node, attr);
},
/**
* Returns the computed value for the given style property.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getComputedStyle
* @param {String} attr The style attribute to retrieve.
* @return {String} The computed value of the style property for the element.
*/
getComputedStyle: function(attr) {
return Y.DOM.getComputedStyle(this._node, attr);
}
});
/**
* Returns an array of values for each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getStyle
* @for NodeList
* @see Node.getStyle
* @param {String} attr The style attribute to retrieve.
* @return {Array} The current values of the style property for the element.
*/
/**
* Returns an array of the computed value for each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getComputedStyle
* @see Node.getComputedStyle
* @param {String} attr The style attribute to retrieve.
* @return {Array} The computed values for each node.
*/
/**
* Sets a style property on each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyle
* @see Node.setStyle
* @param {String} attr The style attribute to set.
* @param {String|Number} val The value.
* @chainable
*/
/**
* Sets multiple style properties on each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyles
* @see Node.setStyles
* @param {Object} hash An object literal of property:value pairs.
* @chainable
*/
// These are broken out to handle undefined return (avoid false positive for
// chainable)
Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']);
})(Y);
}, 'patched-v3.11.0', {"requires": ["dom-style", "node-base"]});
YUI.add('oop', function (Y, NAME) {
/**
Adds object inheritance and manipulation utilities to the YUI instance. This
module is required by most YUI components.
@module oop
**/
var L = Y.Lang,
A = Y.Array,
OP = Object.prototype,
CLONE_MARKER = '_~yuim~_',
hasOwn = OP.hasOwnProperty,
toString = OP.toString;
function dispatch(o, f, c, proto, action) {
if (o && o[action] && o !== Y) {
return o[action].call(o, f, c);
} else {
switch (A.test(o)) {
case 1:
return A[action](o, f, c);
case 2:
return A[action](Y.Array(o, 0, true), f, c);
default:
return Y.Object[action](o, f, c, proto);
}
}
}
/**
Augments the _receiver_ with prototype properties from the _supplier_. The
receiver may be a constructor function or an object. The supplier must be a
constructor function.
If the _receiver_ is an object, then the _supplier_ constructor will be called
immediately after _receiver_ is augmented, with _receiver_ as the `this` object.
If the _receiver_ is a constructor function, then all prototype methods of
_supplier_ that are copied to _receiver_ will be sequestered, and the
_supplier_ constructor will not be called immediately. The first time any
sequestered method is called on the _receiver_'s prototype, all sequestered
methods will be immediately copied to the _receiver_'s prototype, the
_supplier_'s constructor will be executed, and finally the newly unsequestered
method that was called will be executed.
This sequestering logic sounds like a bunch of complicated voodoo, but it makes
it cheap to perform frequent augmentation by ensuring that suppliers'
constructors are only called if a supplied method is actually used. If none of
the supplied methods is ever used, then there's no need to take the performance
hit of calling the _supplier_'s constructor.
@method augment
@param {Function|Object} receiver Object or function to be augmented.
@param {Function} supplier Function that supplies the prototype properties with
which to augment the _receiver_.
@param {Boolean} [overwrite=false] If `true`, properties already on the receiver
will be overwritten if found on the supplier's prototype.
@param {String[]} [whitelist] An array of property names. If specified,
only the whitelisted prototype properties will be applied to the receiver, and
all others will be ignored.
@param {Array|any} [args] Argument or array of arguments to pass to the
supplier's constructor when initializing.
@return {Function} Augmented object.
@for YUI
**/
Y.augment = function (receiver, supplier, overwrite, whitelist, args) {
var rProto = receiver.prototype,
sequester = rProto && supplier,
sProto = supplier.prototype,
to = rProto || receiver,
copy,
newPrototype,
replacements,
sequestered,
unsequester;
args = args ? Y.Array(args) : [];
if (sequester) {
newPrototype = {};
replacements = {};
sequestered = {};
copy = function (value, key) {
if (overwrite || !(key in rProto)) {
if (toString.call(value) === '[object Function]') {
sequestered[key] = value;
newPrototype[key] = replacements[key] = function () {
return unsequester(this, value, arguments);
};
} else {
newPrototype[key] = value;
}
}
};
unsequester = function (instance, fn, fnArgs) {
// Unsequester all sequestered functions.
for (var key in sequestered) {
if (hasOwn.call(sequestered, key)
&& instance[key] === replacements[key]) {
instance[key] = sequestered[key];
}
}
// Execute the supplier constructor.
supplier.apply(instance, args);
// Finally, execute the original sequestered function.
return fn.apply(instance, fnArgs);
};
if (whitelist) {
Y.Array.each(whitelist, function (name) {
if (name in sProto) {
copy(sProto[name], name);
}
});
} else {
Y.Object.each(sProto, copy, null, true);
}
}
Y.mix(to, newPrototype || sProto, overwrite, whitelist);
if (!sequester) {
supplier.apply(to, args);
}
return receiver;
};
/**
* Copies object properties from the supplier to the receiver. If the target has
* the property, and the property is an object, the target object will be
* augmented with the supplier's value.
*
* @method aggregate
* @param {Object} receiver Object to receive the augmentation.
* @param {Object} supplier Object that supplies the properties with which to
* augment the receiver.
* @param {Boolean} [overwrite=false] If `true`, properties already on the receiver
* will be overwritten if found on the supplier.
* @param {String[]} [whitelist] Whitelist. If supplied, only properties in this
* list will be applied to the receiver.
* @return {Object} Augmented object.
*/
Y.aggregate = function(r, s, ov, wl) {
return Y.mix(r, s, ov, wl, 0, true);
};
/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
* Static members will not be inherited.
*
* @method extend
* @param {function} r the object to modify.
* @param {function} s the object to inherit.
* @param {object} px prototype properties to add/override.
* @param {object} sx static properties to add/override.
* @return {object} the extended object.
*/
Y.extend = function(r, s, px, sx) {
if (!s || !r) {
Y.error('extend failed, verify dependencies');
}
var sp = s.prototype, rp = Y.Object(sp);
r.prototype = rp;
rp.constructor = r;
r.superclass = sp;
// assign constructor property
if (s != Object && sp.constructor == OP.constructor) {
sp.constructor = s;
}
// add prototype overrides
if (px) {
Y.mix(rp, px, true);
}
// add object overrides
if (sx) {
Y.mix(r, sx, true);
}
return r;
};
/**
* Executes the supplied function for each item in
* a collection. Supports arrays, objects, and
* NodeLists
* @method each
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {YUI} the YUI instance.
*/
Y.each = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'each');
};
/**
* Executes the supplied function for each item in
* a collection. The operation stops if the function
* returns true. Supports arrays, objects, and
* NodeLists.
* @method some
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {boolean} true if the function ever returns true,
* false otherwise.
*/
Y.some = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'some');
};
/**
Deep object/array copy. Function clones are actually wrappers around the
original function. Array-like objects are treated as arrays. Primitives are
returned untouched. Optionally, a function can be provided to handle other data
types, filter keys, validate values, etc.
**Note:** Cloning a non-trivial object is a reasonably heavy operation, due to
the need to recursively iterate down non-primitive properties. Clone should be
used only when a deep clone down to leaf level properties is explicitly
required. This method will also
In many cases (for example, when trying to isolate objects used as hashes for
configuration properties), a shallow copy, using `Y.merge()` is normally
sufficient. If more than one level of isolation is required, `Y.merge()` can be
used selectively at each level which needs to be isolated from the original
without going all the way to leaf properties.
@method clone
@param {object} o what to clone.
@param {boolean} safe if true, objects will not have prototype items from the
source. If false, they will. In this case, the original is initially
protected, but the clone is not completely immune from changes to the source
object prototype. Also, cloned prototype items that are deleted from the
clone will result in the value of the source prototype being exposed. If
operating on a non-safe clone, items should be nulled out rather than
deleted.
@param {function} f optional function to apply to each item in a collection; it
will be executed prior to applying the value to the new object.
Return false to prevent the copy.
@param {object} c optional execution context for f.
@param {object} owner Owner object passed when clone is iterating an object.
Used to set up context for cloned functions.
@param {object} cloned hash of previously cloned objects to avoid multiple
clones.
@return {Array|Object} the cloned object.
**/
Y.clone = function(o, safe, f, c, owner, cloned) {
var o2, marked, stamp;
// Does not attempt to clone:
//
// * Non-typeof-object values, "primitive" values don't need cloning.
//
// * YUI instances, cloning complex object like YUI instances is not
// advised, this is like cloning the world.
//
// * DOM nodes (#2528250), common host objects like DOM nodes cannot be
// "subclassed" in Firefox and old versions of IE. Trying to use
// `Object.create()` or `Y.extend()` on a DOM node will throw an error in
// these browsers.
//
// Instad, the passed-in `o` will be return as-is when it matches one of the
// above criteria.
if (!L.isObject(o) ||
Y.instanceOf(o, YUI) ||
(o.addEventListener || o.attachEvent)) {
return o;
}
marked = cloned || {};
switch (L.type(o)) {
case 'date':
return new Date(o);
case 'regexp':
// if we do this we need to set the flags too
// return new RegExp(o.source);
return o;
case 'function':
// o2 = Y.bind(o, owner);
// break;
return o;
case 'array':
o2 = [];
break;
default:
// #2528250 only one clone of a given object should be created.
if (o[CLONE_MARKER]) {
return marked[o[CLONE_MARKER]];
}
stamp = Y.guid();
o2 = (safe) ? {} : Y.Object(o);
o[CLONE_MARKER] = stamp;
marked[stamp] = o;
}
Y.each(o, function(v, k) {
if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) {
if (k !== CLONE_MARKER) {
if (k == 'prototype') {
// skip the prototype
// } else if (o[k] === o) {
// this[k] = this;
} else {
this[k] =
Y.clone(v, safe, f, c, owner || o, marked);
}
}
}
}, o2);
if (!cloned) {
Y.Object.each(marked, function(v, k) {
if (v[CLONE_MARKER]) {
try {
delete v[CLONE_MARKER];
} catch (e) {
v[CLONE_MARKER] = null;
}
}
}, this);
marked = null;
}
return o2;
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the beginning of the arguments collection the
* supplied to the function.
*
* @method bind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to include before the arguments the
* function is executed with.
* @return {function} the wrapped function.
*/
Y.bind = function(f, c) {
var xargs = arguments.length > 2 ?
Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
xargs.concat(Y.Array(arguments, 0, true)) : arguments;
return fn.apply(c || fn, args);
};
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the end of the arguments the function
* is executed with.
*
* @method rbind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to append to the end of
* arguments collection supplied to the function.
* @return {function} the wrapped function.
*/
Y.rbind = function(f, c) {
var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
Y.Array(arguments, 0, true).concat(xargs) : arguments;
return fn.apply(c || fn, args);
};
};
}, 'patched-v3.11.0', {"requires": ["yui-base"]});
YUI.add('plugin', function (Y, NAME) {
/**
* Provides the base Plugin class, which plugin developers should extend, when creating custom plugins
*
* @module plugin
*/
/**
* The base class for all Plugin instances.
*
* @class Plugin.Base
* @extends Base
* @param {Object} config Configuration object with property name/value pairs.
*/
function Plugin(config) {
if (! (this.hasImpl && this.hasImpl(Y.Plugin.Base)) ) {
Plugin.superclass.constructor.apply(this, arguments);
} else {
Plugin.prototype.initializer.apply(this, arguments);
}
}
/**
* Object defining the set of attributes supported by the Plugin.Base class
*
* @property ATTRS
* @type Object
* @static
*/
Plugin.ATTRS = {
/**
* The plugin's host object.
*
* @attribute host
* @writeonce
* @type Plugin.Host
*/
host : {
writeOnce: true
}
};
/**
* The string identifying the Plugin.Base class. Plugins extending
* Plugin.Base should set their own NAME value.
*
* @property NAME
* @type String
* @static
*/
Plugin.NAME = 'plugin';
/**
* The name of the property the the plugin will be attached to
* when plugged into a Plugin Host. Plugins extending Plugin.Base,
* should set their own NS value.
*
* @property NS
* @type String
* @static
*/
Plugin.NS = 'plugin';
Y.extend(Plugin, Y.Base, {
/**
* The list of event handles for event listeners or AOP injected methods
* applied by the plugin to the host object.
*
* @property _handles
* @private
* @type Array
* @value null
*/
_handles: null,
/**
* Initializer lifecycle implementation.
*
* @method initializer
* @param {Object} config Configuration object with property name/value pairs.
*/
initializer : function(config) {
this._handles = [];
},
/**
* Destructor lifecycle implementation.
*
* Removes any event listeners or injected methods applied by the Plugin
*
* @method destructor
*/
destructor: function() {
// remove all handles
if (this._handles) {
for (var i = 0, l = this._handles.length; i < l; i++) {
this._handles[i].detach();
}
}
},
/**
* Listens for the "on" moment of events fired by the host,
* or injects code "before" a given method on the host.
*
* @method doBefore
*
* @param strMethod {String} The event to listen for, or method to inject logic before.
* @param fn {Function} The handler function. For events, the "on" moment listener. For methods, the function to execute before the given method is executed.
* @param context {Object} An optional context to call the handler with. The default context is the plugin instance.
* @return handle {EventHandle} The detach handle for the handler.
*/
doBefore: function(strMethod, fn, context) {
var host = this.get("host"), handle;
if (strMethod in host) { // method
handle = this.beforeHostMethod(strMethod, fn, context);
} else if (host.on) { // event
handle = this.onHostEvent(strMethod, fn, context);
}
return handle;
},
/**
* Listens for the "after" moment of events fired by the host,
* or injects code "after" a given method on the host.
*
* @method doAfter
*
* @param strMethod {String} The event to listen for, or method to inject logic after.
* @param fn {Function} The handler function. For events, the "after" moment listener. For methods, the function to execute after the given method is executed.
* @param context {Object} An optional context to call the handler with. The default context is the plugin instance.
* @return handle {EventHandle} The detach handle for the listener.
*/
doAfter: function(strMethod, fn, context) {
var host = this.get("host"), handle;
if (strMethod in host) { // method
handle = this.afterHostMethod(strMethod, fn, context);
} else if (host.after) { // event
handle = this.afterHostEvent(strMethod, fn, context);
}
return handle;
},
/**
* Listens for the "on" moment of events fired by the host object.
*
* Listeners attached through this method will be detached when the plugin is unplugged.
*
* @method onHostEvent
* @param {String | Object} type The event type.
* @param {Function} fn The listener.
* @param {Object} context The execution context. Defaults to the plugin instance.
* @return handle {EventHandle} The detach handle for the listener.
*/
onHostEvent : function(type, fn, context) {
var handle = this.get("host").on(type, fn, context || this);
this._handles.push(handle);
return handle;
},
/**
* Listens for the "on" moment of events fired by the host object one time only.
* The listener is immediately detached when it is executed.
*
* Listeners attached through this method will be detached when the plugin is unplugged.
*
* @method onceHostEvent
* @param {String | Object} type The event type.
* @param {Function} fn The listener.
* @param {Object} context The execution context. Defaults to the plugin instance.
* @return handle {EventHandle} The detach handle for the listener.
*/
onceHostEvent : function(type, fn, context) {
var handle = this.get("host").once(type, fn, context || this);
this._handles.push(handle);
return handle;
},
/**
* Listens for the "after" moment of events fired by the host object.
*
* Listeners attached through this method will be detached when the plugin is unplugged.
*
* @method afterHostEvent
* @param {String | Object} type The event type.
* @param {Function} fn The listener.
* @param {Object} context The execution context. Defaults to the plugin instance.
* @return handle {EventHandle} The detach handle for the listener.
*/
afterHostEvent : function(type, fn, context) {
var handle = this.get("host").after(type, fn, context || this);
this._handles.push(handle);
return handle;
},
/**
* Listens for the "after" moment of events fired by the host object one time only.
* The listener is immediately detached when it is executed.
*
* Listeners attached through this method will be detached when the plugin is unplugged.
*
* @method onceAfterHostEvent
* @param {String | Object} type The event type.
* @param {Function} fn The listener.
* @param {Object} context The execution context. Defaults to the plugin instance.
* @return handle {EventHandle} The detach handle for the listener.
*/
onceAfterHostEvent : function(type, fn, context) {
var handle = this.get("host").onceAfter(type, fn, context || this);
this._handles.push(handle);
return handle;
},
/**
* Injects a function to be executed before a given method on host object.
*
* The function will be detached when the plugin is unplugged.
*
* @method beforeHostMethod
* @param {String} method The name of the method to inject the function before.
* @param {Function} fn The function to inject.
* @param {Object} context The execution context. Defaults to the plugin instance.
* @return handle {EventHandle} The detach handle for the injected function.
*/
beforeHostMethod : function(strMethod, fn, context) {
var handle = Y.Do.before(fn, this.get("host"), strMethod, context || this);
this._handles.push(handle);
return handle;
},
/**
* Injects a function to be executed after a given method on host object.
*
* The function will be detached when the plugin is unplugged.
*
* @method afterHostMethod
* @param {String} method The name of the method to inject the function after.
* @param {Function} fn The function to inject.
* @param {Object} context The execution context. Defaults to the plugin instance.
* @return handle {EventHandle} The detach handle for the injected function.
*/
afterHostMethod : function(strMethod, fn, context) {
var handle = Y.Do.after(fn, this.get("host"), strMethod, context || this);
this._handles.push(handle);
return handle;
},
toString: function() {
return this.constructor.NAME + '[' + this.constructor.NS + ']';
}
});
Y.namespace("Plugin").Base = Plugin;
}, 'patched-v3.11.0', {"requires": ["base-base"]});
YUI.add('pluginhost-base', function (Y, NAME) {
/**
* Provides the augmentable PluginHost interface, which can be added to any class.
* @module pluginhost
*/
/**
* Provides the augmentable PluginHost interface, which can be added to any class.
* @module pluginhost-base
*/
/**
*
* An augmentable class, which provides the augmented class with the ability to host plugins.
* It adds plug and unplug methods to the augmented class, which can
* be used to add or remove plugins from instances of the class.
*
*
* Plugins can also be added through the constructor configuration object passed to the host class' constructor using
* the "plugins" property. Supported values for the "plugins" property are those defined by the plug method.
*
* For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host):
*
* var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]});
*
*
*
* Plug.Host's protected _initPlugins and _destroyPlugins
* methods should be invoked by the host class at the appropriate point in the host's lifecyle.
*
*
* @class Plugin.Host
*/
var L = Y.Lang;
function PluginHost() {
this._plugins = {};
}
PluginHost.prototype = {
/**
* Adds a plugin to the host object. This will instantiate the
* plugin and attach it to the configured namespace on the host object.
*
* @method plug
* @chainable
* @param P {Function | Object |Array} Accepts the plugin class, or an
* object with a "fn" property specifying the plugin class and
* a "cfg" property specifying the configuration for the Plugin.
*
* Additionally an Array can also be passed in, with the above function or
* object values, allowing the user to add multiple plugins in a single call.
*
* @param config (Optional) If the first argument is the plugin class, the second argument
* can be the configuration for the plugin.
* @return {Base} A reference to the host object
*/
plug: function(Plugin, config) {
var i, ln, ns;
if (L.isArray(Plugin)) {
for (i = 0, ln = Plugin.length; i < ln; i++) {
this.plug(Plugin[i]);
}
} else {
if (Plugin && !L.isFunction(Plugin)) {
config = Plugin.cfg;
Plugin = Plugin.fn;
}
// Plugin should be fn by now
if (Plugin && Plugin.NS) {
ns = Plugin.NS;
config = config || {};
config.host = this;
if (this.hasPlugin(ns)) {
// Update config
if (this[ns].setAttrs) {
this[ns].setAttrs(config);
}
} else {
// Create new instance
this[ns] = new Plugin(config);
this._plugins[ns] = Plugin;
}
}
}
return this;
},
/**
* Removes a plugin from the host object. This will destroy the
* plugin instance and delete the namespace from the host object.
*
* @method unplug
* @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided,
* all registered plugins are unplugged.
* @return {Base} A reference to the host object
* @chainable
*/
unplug: function(plugin) {
var ns = plugin,
plugins = this._plugins;
if (plugin) {
if (L.isFunction(plugin)) {
ns = plugin.NS;
if (ns && (!plugins[ns] || plugins[ns] !== plugin)) {
ns = null;
}
}
if (ns) {
if (this[ns]) {
if (this[ns].destroy) {
this[ns].destroy();
}
delete this[ns];
}
if (plugins[ns]) {
delete plugins[ns];
}
}
} else {
for (ns in this._plugins) {
if (this._plugins.hasOwnProperty(ns)) {
this.unplug(ns);
}
}
}
return this;
},
/**
* Determines if a plugin has plugged into this host.
*
* @method hasPlugin
* @param {String} ns The plugin's namespace
* @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not.
*/
hasPlugin : function(ns) {
return (this._plugins[ns] && this[ns]);
},
/**
* Initializes static plugins registered on the host (using the
* Base.plug static method) and any plugins passed to the
* instance through the "plugins" configuration property.
*
* @method _initPlugins
* @param {Config} config The configuration object with property name/value pairs.
* @private
*/
_initPlugins: function(config) {
this._plugins = this._plugins || {};
if (this._initConfigPlugins) {
this._initConfigPlugins(config);
}
},
/**
* Unplugs and destroys all plugins on the host
* @method _destroyPlugins
* @private
*/
_destroyPlugins: function() {
this.unplug();
}
};
Y.namespace("Plugin").Host = PluginHost;
}, 'patched-v3.11.0', {"requires": ["yui-base"]});
YUI.add('pluginhost-config', function (Y, NAME) {
/**
* Adds pluginhost constructor configuration and static configuration support
* @submodule pluginhost-config
*/
var PluginHost = Y.Plugin.Host,
L = Y.Lang;
/**
* A protected initialization method, used by the host class to initialize
* plugin configurations passed the constructor, through the config object.
*
* Host objects should invoke this method at the appropriate time in their
* construction lifecycle.
*
* @method _initConfigPlugins
* @param {Object} config The configuration object passed to the constructor
* @protected
* @for Plugin.Host
*/
PluginHost.prototype._initConfigPlugins = function(config) {
// Class Configuration
var classes = (this._getClasses) ? this._getClasses() : [this.constructor],
plug = [],
unplug = {},
constructor, i, classPlug, classUnplug, pluginClassName;
// TODO: Room for optimization. Can we apply statically/unplug in same pass?
for (i = classes.length - 1; i >= 0; i--) {
constructor = classes[i];
classUnplug = constructor._UNPLUG;
if (classUnplug) {
// subclasses over-write
Y.mix(unplug, classUnplug, true);
}
classPlug = constructor._PLUG;
if (classPlug) {
// subclasses over-write
Y.mix(plug, classPlug, true);
}
}
for (pluginClassName in plug) {
if (plug.hasOwnProperty(pluginClassName)) {
if (!unplug[pluginClassName]) {
this.plug(plug[pluginClassName]);
}
}
}
// User Configuration
if (config && config.plugins) {
this.plug(config.plugins);
}
};
/**
* Registers plugins to be instantiated at the class level (plugins
* which should be plugged into every instance of the class by default).
*
* @method plug
* @static
*
* @param {Function} hostClass The host class on which to register the plugins
* @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined)
* @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin
* @for Plugin.Host
*/
PluginHost.plug = function(hostClass, plugin, config) {
// Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ]
var p, i, l, name;
if (hostClass !== Y.Base) {
hostClass._PLUG = hostClass._PLUG || {};
if (!L.isArray(plugin)) {
if (config) {
plugin = {fn:plugin, cfg:config};
}
plugin = [plugin];
}
for (i = 0, l = plugin.length; i < l;i++) {
p = plugin[i];
name = p.NAME || p.fn.NAME;
hostClass._PLUG[name] = p;
}
}
};
/**
* Unregisters any class level plugins which have been registered by the host class, or any
* other class in the hierarchy.
*
* @method unplug
* @static
*
* @param {Function} hostClass The host class from which to unregister the plugins
* @param {Function | Array} plugin The plugin class, or an array of plugin classes
* @for Plugin.Host
*/
PluginHost.unplug = function(hostClass, plugin) {
var p, i, l, name;
if (hostClass !== Y.Base) {
hostClass._UNPLUG = hostClass._UNPLUG || {};
if (!L.isArray(plugin)) {
plugin = [plugin];
}
for (i = 0, l = plugin.length; i < l; i++) {
p = plugin[i];
name = p.NAME;
if (!hostClass._PLUG[name]) {
hostClass._UNPLUG[name] = p;
} else {
delete hostClass._PLUG[name];
}
}
}
};
}, 'patched-v3.11.0', {"requires": ["pluginhost-base"]});
YUI.add('querystring-stringify-simple', function (Y, NAME) {
/*global Y */
/**
* Provides Y.QueryString.stringify method for converting objects to Query Strings.
* This is a subset implementation of the full querystring-stringify.
* This module provides the bare minimum functionality (encoding a hash of simple values),
* without the additional support for nested data structures. Every key-value pair is
* encoded by encodeURIComponent.
* This module provides a minimalistic way for io to handle single-level objects
* as transaction data.
*
* @module querystring
* @submodule querystring-stringify-simple
*/
var QueryString = Y.namespace("QueryString"),
EUC = encodeURIComponent;
QueryString.stringify = function (obj, c) {
var qs = [],
// Default behavior is false; standard key notation.
s = c && c.arrayKey ? true : false,
key, i, l;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (Y.Lang.isArray(obj[key])) {
for (i = 0, l = obj[key].length; i < l; i++) {
qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i]));
}
}
else {
qs.push(EUC(key) + '=' + EUC(obj[key]));
}
}
}
return qs.join('&');
};
}, 'patched-v3.11.0', {"requires": ["yui-base"]});
YUI.add('queue-promote', function (Y, NAME) {
/**
* Adds methods promote, remove, and indexOf to Queue instances.
*
* @module queue-promote
* @for Queue
*/
Y.mix(Y.Queue.prototype, {
/**
* Returns the current index in the queue of the specified item
*
* @method indexOf
* @param needle {MIXED} the item to search for
* @return {Number} the index of the item or -1 if not found
*/
indexOf : function (callback) {
return Y.Array.indexOf(this._q, callback);
},
/**
* Moves the referenced item to the head of the queue
*
* @method promote
* @param item {MIXED} an item in the queue
*/
promote : function (callback) {
var index = this.indexOf(callback);
if (index > -1) {
this._q.unshift(this._q.splice(index,1)[0]);
}
},
/**
* Removes the referenced item from the queue
*
* @method remove
* @param item {MIXED} an item in the queue
*/
remove : function (callback) {
var index = this.indexOf(callback);
if (index > -1) {
this._q.splice(index,1);
}
}
});
}, 'patched-v3.11.0', {"requires": ["yui-base"]});
YUI.add('selector-css2', function (Y, NAME) {
/**
* The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements.
* @module dom
* @submodule selector-css2
* @for Selector
*/
/*
* Provides helper methods for collecting and filtering DOM elements.
*/
var PARENT_NODE = 'parentNode',
TAG_NAME = 'tagName',
ATTRIBUTES = 'attributes',
COMBINATOR = 'combinator',
PSEUDOS = 'ps