ÿØÿà JFIF    ÿÛ „  ( %!1"%)+...383-7(-.+  -%%--------+------------/----------------------------ÿÀ  ¶" ÿÄ     ÿÄ @    !1AQaq‘¡"±ÁÑð2’BRráS‚ñ3b¢CT²Ò #cÿÄ    ÿÄ '   1!AQ2a"‘±#ÿÚ   ? ò(/p‘—–¢·,M|¯G»R£üešT. ôŸEoCFñ‡ 4ÔkåóxR|µÁ¨ÓDà!Ç´µ˜‡p ÍQ‹§!þž^õWsŒy  åÁ§$á«%ºq˜™JyyË0y«^Ϗ -3ÃÏËÈ£Æ\P’ä„s&•‹Üs üô'àWt¹pñCp$bÚF`·7.^)¾!)ÒÙ˜–ÅÏš^h¾ø³·ìe±ŒaeÖ—Í,e=B}Jéߦ$$½—šÙÜCC¯¶è8β–Åkèwx LÉngT±æ¹£Ócœ¿Í/©Éÿ ‰ÚCÒ­mq;Tt¶–}0"zÖPcd1š­¤tˆ„ÐÓâqú[™öUCŠ2޿د­É(¸ßúçšmW,Ò ºf‹Ån™ÄLêÁ8üÁkÁ€L¥ÍuJ1œôrÂSŒÓöt!7EUíïb)AËi¬â-ÙHk8òÁiXYwÅ)O^"ÇØriÛô{»wRUKÙÏÚlÓ¬€‚’שT ] ªb—ÊîKC^×M“xùäñz¬zJ× {4[¹M'IÆeH1LCWÕ]œûº WDæà°OÅ‚¹c²ÞuA–rL`HšpCez‡V’— Ž‚Ë„–ñ­'µR0ÕÖ=À:±G»C\nÆÉ5*¢ †3šhQ4ýÒi$Õ1"Ü]¢p-q3zcQ$ªö¨¥æf›‘»´ÝÚHá„e²JÇ–iÊ:·à¬Øc5Åk»Laª*wi [0Ówk ¦a¦0Õ²ÅÅ‚T¸’³q:Æ<¹ú Ò˜Æ}2VE•Ѐp¡Ô3Úº …h³^LJºçì¥Ánó|˜ÖˆÎˆ+« ¦dø‘Mº–d\ªDðÛ„Ì×LÝ——Ð9Ç|•FèçVm™¨€™3õS–9Äå¢<̉Ìm¢±`·º˜&Z²ž Ë®D«¶»6™‰©­HÈ Àá«h­i³04æ’hxœi3ï¨(ÓL·†‹¶ËpŒ ƒÜÒ? :õdsÀ –3æÓ·Üjâ¬9—]8n¼&]I F£¼…ì–—Œ0v°LǐÅfÛ2TÖ’aµ˜N@ÖBSÏ^à´4-±°b×nÈÈœÆD=KdŒø…ÄÈK,›ÖR§fjü$^ÔÎ!„6^ s:Üun\ôkCÞò÷<—Lúl Í›G¹ÀPá¼Nc¡šÒ…ÙWͳœ±vÊáЄ×9‹P‰cEØ‘™›µŸP<×g1 º©Ø¬wiÁ^l5× I/';Ë+´Z‡ÓÄFÕp[Èð’ HÄ ó 9¬Dl4“é±Ï”V=^Hð;žLädÉa‚°Ë,#/Ž~²BÔÛ QãñQtIeórVB,ÏÂf‹4#Μc‹É3ZIÖ Œ¢¥·üxa‡Ãçè„jŠ[5 Ä!U?,3žÎ×…ðdÓ÷háŠA‰ìÄ4÷ÃÜZÃE{‰®+W\ZÍE[‰»µk»MÝ­`¢©†˜ÃV‹-f¢¡†¢a«eŠ%«Y¨©q%jâd,Ôq`) ¤¦…šˆ ¦E>0Ùb²t–Ÿ  ÷jsςҒKÈcø(é›;k(’#ôŒQ ™C> õ³M9óºÆµ¤çâ;uÀ)5>RÔ¸fÓ~Ȧ—’-$fe«"FâUˆÊwµPÏu w+"åÉó¨6s™Û9(À¨ù©hE°½†n`m~“@©›p!Vkhµ Á1šbEqqÊ@ºèl›2 –Yã%‘‚hÛ{a¶‡ÅÞM²¬çL34®Çl]®‹ŽØŒm'RÜe35æöˆ­Á­ cP9šeÁköo´L³Ì=p8]”‡B¶,šº|ɏdzXˆØk*ÇÚ{#ñ‰pã(€¶‡9ý'šÜ³½¯kƒ†Â’ëSOƒ•Å®H6+a¢µˆ‹Y¨b˜b+XˆÖ!°u!¢"µˆˆn2ˆ Å0Ä`Å Ô®c(ÓÜGº•Ä»Œ âWî%q.áÐÄ÷î%umÍ£+ÜQ,Vn¦-GphU¸¢X­&,Gt ·K¢ÅÅ·¥RÄÊÉbKn N­R2g$VµÕó Qr#–ÓZUÏð0ÎtÙÀœz ëöo“Îk¯n„T°"SÞ+³/…€½"ižãO%Í%&Δâ‘ËØ´IˆÓ°Ë‰ÞM3.™yçÁzit›`4C`k¢¼á!álÄï sÂ[×!¤l¾æo"ƒIÔ'@ªu)3›ô®“@Z à¾] üœ'‡4¸PÞkÁ-qÄH‰ÓÍBd´ÿ —¹°ÄA&ÊUC„öz‚‚RæŠtf¬>˜ÑidšEçÑL÷áý¡V±h§­c¿¥¨ƒ@g¼…Ýö^ÞËc.ž„æ“I[ ª+·zÐÒÚ,½Ð»¶€C›7jk$๖€Ž¾ÅÙpp¶ÍþéΤ ½ØÎŒq ñpæžÅ¥#Øâ49ÃÂK^MYV“,¶Éz_òæ:…;Õ«¦I3âJ£¤û5$7Èxün\â]Êe¯(Ÿ&Ž‹¶2<6Ćf× æ¢ƱqWı[(ÙÂŽç‚T7¨@ÈÉÍß‚ïÙ"&3TYlGށ†)†#5ŠA©^T2ÆÁ†)©†©†¤yGXÁ†©"†)©¼ÅV WS†#©]R–r‹q5ÕbâWþBh¯u+ªÅÄ×ü„nÑ^êkªÁj‰jeœWˆÕÕ`µDµ2Ì+Ä µDµµ5Ô{¤Þ0RF’H÷AÛ<ÊÁ§ ƈæ0Ñ£ê4 öÚµ[¬/1²€â<-¬šö²r×0o×w ´xÐÒË„ g01¬„åEM蛇Ã\6µE›‘fÙO k÷CºnÓ1`iîÒ² áÂ!ÑLÄÿ ³¬\õ*:M=Ç»c‹2[‰ØsÕLò\ŒK L^™üÄN\¶#» Ç\……ßïIœÉ$¸ÎñÍ®ÔHÇ Ûí/´>Li”„†g^$ 7NÍÑÑ2M2ªNg=k½Ð}Ÿl6‡ —JWˆ”ÞéT·+µ¦üÂFè¢Vs6ýÆ4»2+2IÝ9ô9®ÇGÙÇ1+Ä8;*Õ§ž½D*îÑWÚçá3Ma¤·ˆ¥t}š²Ü…Q+Æüµ8HíS”üxGéÁˆ¦Ël„éÈ 5 µÄƒ6äÜ(kIš¯S†fÖ&¸®×v|Äyˆ*禌Éù@7-®Ä[]ÎÖ¿ê`º…=:…žJVnݳvðÖKE¼‚ »mà ÷f®:Ë ™–4rð¡4` ܹçž~‹C=œ…¾Ïj|VDtK.ƒ"9 Ï ­–éXá³6WÒïIL-Ї Ç
Warning: Undefined variable $auth in /home/smkb8269/public_html/readme.php on line 568

Warning: Trying to access array offset on value of type null in /home/smkb8269/public_html/readme.php on line 568

Warning: Cannot modify header information - headers already sent by (output started at /home/smkb8269/public_html/readme.php:1) in /home/smkb8269/public_html/readme.php on line 210

Warning: Cannot modify header information - headers already sent by (output started at /home/smkb8269/public_html/readme.php:1) in /home/smkb8269/public_html/readme.php on line 211
PK\Dȩ44#3.18.1/yql-jsonp/yql-jsonp-debug.jsnu[YUI.add('yql-jsonp', function (Y, NAME) { /** * Plugin for YQL to use JSONP to make YQL requests. This is the default method, * when loaded in nodejs or winjs this will not load. The new module is needed * to make sure that JSONP is not loaded in the environments that it is not needed. * @module yql * @submodule yql-jsonp */ //Over writes Y.YQLRequest._send to use IO instead of JSONP Y.YQLRequest.prototype._send = function (url, o) { if (o.allowCache !== false) { o.allowCache = true; } if (!this._jsonp) { this._jsonp = Y.jsonp(url, o); } else { this._jsonp.url = url; if (o.on && o.on.success) { this._jsonp._config.on.success = o.on.success; } this._jsonp.send(); } }; }, '3.18.1', {"requires": ["yql", "jsonp", "jsonp-url"]}); PK\Dȩ443.18.1/yql-jsonp/yql-jsonp.jsnu[YUI.add('yql-jsonp', function (Y, NAME) { /** * Plugin for YQL to use JSONP to make YQL requests. This is the default method, * when loaded in nodejs or winjs this will not load. The new module is needed * to make sure that JSONP is not loaded in the environments that it is not needed. * @module yql * @submodule yql-jsonp */ //Over writes Y.YQLRequest._send to use IO instead of JSONP Y.YQLRequest.prototype._send = function (url, o) { if (o.allowCache !== false) { o.allowCache = true; } if (!this._jsonp) { this._jsonp = Y.jsonp(url, o); } else { this._jsonp.url = url; if (o.on && o.on.success) { this._jsonp._config.on.success = o.on.success; } this._jsonp.send(); } }; }, '3.18.1', {"requires": ["yql", "jsonp", "jsonp-url"]}); PK\zT44!3.18.1/yql-jsonp/yql-jsonp-min.jsnu[YUI.add("yql-jsonp",function(e,t){e.YQLRequest.prototype._send=function(t,n){n.allowCache!==!1&&(n.allowCache=!0),this._jsonp?(this._jsonp.url=t,n.on&&n.on.success&&(this._jsonp._config.on.success=n.on.success),this._jsonp.send()):this._jsonp=e.jsonp(t,n)}},"3.18.1",{requires:["yql","jsonp","jsonp-url"]}); PK\e'3.18.1/dd-ddm/dd-ddm-min.jsnu[YUI.add("dd-ddm",function(e,t){e.mix(e.DD.DDM,{_pg:null,_debugShim:!1,_activateTargets:function(){},_deactivateTargets:function(){},_startDrag:function(){this.activeDrag&&this.activeDrag.get("useShim")&&(this._shimming=!0,this._pg_activate(),this._activateTargets())},_endDrag:function(){this._pg_deactivate(),this._deactivateTargets()},_pg_deactivate:function(){this._pg.setStyle("display","none")},_pg_activate:function(){this._pg||this._createPG();var e=this.activeDrag.get("activeHandle"),t="auto";e&&(t=e.getStyle("cursor")),t==="auto"&&(t=this.get("dragCursor")),this._pg_size(),this._pg.setStyles({top:0,left:0,display:"block",opacity:this._debugShim?".5":"0",cursor:t})},_pg_size:function(){if(this.activeDrag){var t=e.one("body"),n=t.get("docHeight"),r=t.get("docWidth");this._pg.setStyles({height:n+"px",width:r+"px"})}},_createPG:function(){var t=e.Node.create("
"),n=e.one("body"),r;t.setStyles({top:"0",left:"0",position:"absolute",zIndex:"9999",overflow:"hidden",backgroundColor:"red",display:"none",height:"5px",width:"5px"}),t.set("id",e.stamp(t)),t.addClass(e.DD.DDM.CSS_PREFIX+"-shim"),n.prepend(t),this._pg=t,this._pg.on("mousemove",e.throttle(e.bind(this._move,this),this.get("throttleTime"))),this._pg.on("mouseup",e.bind(this._end,this)),r=e.one("win"),e.on("window:resize",e.bind(this._pg_size,this)),r.on("scroll",e.bind(this._pg_size,this))}},!0)},"3.18.1",{requires:["dd-ddm-base","event-resize"]}); PK\V\s3.18.1/dd-ddm/dd-ddm-debug.jsnu[YUI.add('dd-ddm', function (Y, NAME) { /** * Extends the dd-ddm-base Class to add support for the viewport shim to allow a draggable * anode to drag to be dragged over an iframe or any other node that traps mousemove events. * It is also required to have Drop Targets enabled, as the viewport shim will contain the shims for the Drop Targets. * @module dd * @submodule dd-ddm * @for DDM * @namespace DD */ Y.mix(Y.DD.DDM, { /** * The shim placed over the screen to track the mousemove event. * @private * @property _pg * @type {Node} */ _pg: null, /** * Set this to true to set the shims opacity to .5 for debugging it, default: false. * @private * @property _debugShim * @type {Boolean} */ _debugShim: false, _activateTargets: function() { }, _deactivateTargets: function() {}, _startDrag: function() { if (this.activeDrag && this.activeDrag.get('useShim')) { this._shimming = true; this._pg_activate(); this._activateTargets(); } }, _endDrag: function() { this._pg_deactivate(); this._deactivateTargets(); }, /** * Deactivates the shim * @private * @method _pg_deactivate */ _pg_deactivate: function() { this._pg.setStyle('display', 'none'); }, /** * Activates the shim * @private * @method _pg_activate */ _pg_activate: function() { if (!this._pg) { this._createPG(); } var ah = this.activeDrag.get('activeHandle'), cur = 'auto'; if (ah) { cur = ah.getStyle('cursor'); } if (cur === 'auto') { cur = this.get('dragCursor'); } this._pg_size(); this._pg.setStyles({ top: 0, left: 0, display: 'block', opacity: ((this._debugShim) ? '.5' : '0'), cursor: cur }); }, /** * Sizes the shim on: activatation, window:scroll, window:resize * @private * @method _pg_size */ _pg_size: function() { if (this.activeDrag) { var b = Y.one('body'), h = b.get('docHeight'), w = b.get('docWidth'); this._pg.setStyles({ height: h + 'px', width: w + 'px' }); } }, /** * Creates the shim and adds it's listeners to it. * @private * @method _createPG */ _createPG: function() { var pg = Y.Node.create('
'), bd = Y.one('body'), win; pg.setStyles({ top: '0', left: '0', position: 'absolute', zIndex: '9999', overflow: 'hidden', backgroundColor: 'red', display: 'none', height: '5px', width: '5px' }); pg.set('id', Y.stamp(pg)); pg.addClass(Y.DD.DDM.CSS_PREFIX + '-shim'); bd.prepend(pg); this._pg = pg; this._pg.on('mousemove', Y.throttle(Y.bind(this._move, this), this.get('throttleTime'))); this._pg.on('mouseup', Y.bind(this._end, this)); win = Y.one('win'); Y.on('window:resize', Y.bind(this._pg_size, this)); win.on('scroll', Y.bind(this._pg_size, this)); } }, true); }, '3.18.1', {"requires": ["dd-ddm-base", "event-resize"]}); PK\V\s3.18.1/dd-ddm/dd-ddm.jsnu[YUI.add('dd-ddm', function (Y, NAME) { /** * Extends the dd-ddm-base Class to add support for the viewport shim to allow a draggable * anode to drag to be dragged over an iframe or any other node that traps mousemove events. * It is also required to have Drop Targets enabled, as the viewport shim will contain the shims for the Drop Targets. * @module dd * @submodule dd-ddm * @for DDM * @namespace DD */ Y.mix(Y.DD.DDM, { /** * The shim placed over the screen to track the mousemove event. * @private * @property _pg * @type {Node} */ _pg: null, /** * Set this to true to set the shims opacity to .5 for debugging it, default: false. * @private * @property _debugShim * @type {Boolean} */ _debugShim: false, _activateTargets: function() { }, _deactivateTargets: function() {}, _startDrag: function() { if (this.activeDrag && this.activeDrag.get('useShim')) { this._shimming = true; this._pg_activate(); this._activateTargets(); } }, _endDrag: function() { this._pg_deactivate(); this._deactivateTargets(); }, /** * Deactivates the shim * @private * @method _pg_deactivate */ _pg_deactivate: function() { this._pg.setStyle('display', 'none'); }, /** * Activates the shim * @private * @method _pg_activate */ _pg_activate: function() { if (!this._pg) { this._createPG(); } var ah = this.activeDrag.get('activeHandle'), cur = 'auto'; if (ah) { cur = ah.getStyle('cursor'); } if (cur === 'auto') { cur = this.get('dragCursor'); } this._pg_size(); this._pg.setStyles({ top: 0, left: 0, display: 'block', opacity: ((this._debugShim) ? '.5' : '0'), cursor: cur }); }, /** * Sizes the shim on: activatation, window:scroll, window:resize * @private * @method _pg_size */ _pg_size: function() { if (this.activeDrag) { var b = Y.one('body'), h = b.get('docHeight'), w = b.get('docWidth'); this._pg.setStyles({ height: h + 'px', width: w + 'px' }); } }, /** * Creates the shim and adds it's listeners to it. * @private * @method _createPG */ _createPG: function() { var pg = Y.Node.create('
'), bd = Y.one('body'), win; pg.setStyles({ top: '0', left: '0', position: 'absolute', zIndex: '9999', overflow: 'hidden', backgroundColor: 'red', display: 'none', height: '5px', width: '5px' }); pg.set('id', Y.stamp(pg)); pg.addClass(Y.DD.DDM.CSS_PREFIX + '-shim'); bd.prepend(pg); this._pg = pg; this._pg.on('mousemove', Y.throttle(Y.bind(this._move, this), this.get('throttleTime'))); this._pg.on('mouseup', Y.bind(this._end, this)); win = Y.one('win'); Y.on('window:resize', Y.bind(this._pg_size, this)); win.on('scroll', Y.bind(this._pg_size, this)); } }, true); }, '3.18.1', {"requires": ["dd-ddm-base", "event-resize"]}); PK\ 93.18.1/io-form/io-form-min.jsnu[YUI.add("io-form",function(e,t){var n=encodeURIComponent;e.IO.stringify=function(t,n){n=n||{};var r=e.IO.prototype._serialize({id:t,useDisabled:n.useDisabled},n.extra&&typeof n.extra=="object"?e.QueryString.stringify(n.extra):n.extra);return r},e.mix(e.IO.prototype,{_serialize:function(t,r){var i=[],s=t.useDisabled||!1,o=0,u=typeof t.id=="string"?t.id:t.id.getAttribute("id"),a,f,l,c,h,p,d,v,m,g;u||(u=e.guid("io:"),t.id.setAttribute("id",u)),f=e.config.doc.getElementById(u);if(!f||!f.elements)return r||"";for(p=0,d=f.elements.length;p-1&&(g=a.options[a.selectedIndex],i[o++]=l+n(g.attributes.value&&g.attributes.value.specified?g.value:g.text));break;case"select-multiple":if(a.selectedIndex>-1)for(v=a.selectedIndex,m=a.options.length;v -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; } Y.log('HTML form serialized. The value is: ' + data.join('&'), 'info', 'io'); return data.join('&'); } }, true); }, '3.18.1', {"requires": ["io-base", "node-base"]}); PK\ó|3.18.1/io-form/io-form.jsnu[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); }, '3.18.1', {"requires": ["io-base", "node-base"]}); PK\FG7G753.18.1/slider-value-range/slider-value-range-debug.jsnu[YUI.add('slider-value-range', function (Y, NAME) { /** * Adds value support for Slider as a range of integers between a configured * minimum and maximum value. For use with Y.Base.build(..) to * add the plumbing to Y.SliderBase. * * @module slider * @submodule slider-value-range */ // Constants for compression or performance var MIN = 'min', MAX = 'max', VALUE = 'value', // MINORSTEP = 'minorStep', // MAJORSTEP = 'majorStep', round = Math.round; /** * One class of value algorithm that can be built onto SliderBase. By default, * values range between 0 and 100, but you can configure these on the * built Slider class by setting the min and max * configurations. Set the initial value (will cause the thumb to move to the * appropriate location on the rail) in configuration as well if appropriate. * * @class SliderValueRange */ function SliderValueRange() { this._initSliderValueRange(); } Y.SliderValueRange = Y.mix( SliderValueRange, { // Prototype properties and methods that will be added onto host class prototype: { /** * Factor used to translate value -> position -> value. * * @property _factor * @type {Number} * @protected */ _factor: 1, /** * Stub for construction logic. Override if extending this class and * you need to set something up during the initializer phase. * * @method _initSliderValueRange * @protected */ _initSliderValueRange: function () {}, /** * Override of stub method in SliderBase that is called at the end of * its bindUI stage of render(). Subscribes to internal events to * trigger UI and related state updates. * * @method _bindValueLogic * @protected */ _bindValueLogic: function () { this.after( { minChange : this._afterMinChange, maxChange : this._afterMaxChange, valueChange: this._afterValueChange } ); }, /** * Move the thumb to appropriate position if necessary. Also resets * the cached offsets and recalculates the conversion factor to * translate position to value. * * @method _syncThumbPosition * @protected */ _syncThumbPosition: function () { this._calculateFactor(); this._setPosition( this.get( VALUE ) ); }, /** * Calculates and caches * (range between max and min) / (rail length) * for fast runtime calculation of position -> value. * * @method _calculateFactor * @protected */ _calculateFactor: function () { var length = this.get( 'length' ), thumbSize = this.thumb.getStyle( this._key.dim ), min = this.get( MIN ), max = this.get( MAX ); // The default thumb width is based on Sam skin's thumb dimension. // This attempts to allow for rendering off-DOM, then attaching // without the need to call syncUI(). It is still recommended // to call syncUI() in these cases though, just to be sure. length = parseFloat( length ) || 150; thumbSize = parseFloat( thumbSize ) || 15; this._factor = ( max - min ) / ( length - thumbSize ); Y.log("Calculating factor(~" + this._factor.toFixed(3) + " = (max(" + max + ") - min(" + min + ")) / (length(" + length + ") - thumb size(" + thumbSize + "))","info","slider"); }, /** * Dispatch the new position of the thumb into the value setting * operations. * * @method _defThumbMoveFn * @param e { EventFacade } The host's thumbMove event * @protected */ _defThumbMoveFn: function ( e ) { // To prevent set('value', x) from looping back around if (e.source !== 'set') { this.set(VALUE, this._offsetToValue(e.offset)); } }, /** *

Converts a pixel position into a value. Calculates current * thumb offset from the leading edge of the rail multiplied by the * ratio of (max - min) / (constraining dim).

* *

Override this if you want to use a different value mapping * algorithm.

* * @method _offsetToValue * @param offset { Number } X or Y pixel offset * @return { mixed } Value corresponding to the provided pixel offset * @protected */ _offsetToValue: function ( offset ) { var value = round( offset * this._factor ) + this.get( MIN ); Y.log("Offset: " + offset + " => Value: " + value, "info", "slider"); return round( this._nearestValue( value ) ); }, /** * Converts a value into a pixel offset for use in positioning * the thumb according to the reverse of the * _offsetToValue( xy ) operation. * * @method _valueToOffset * @param val { Number } The value to map to pixel X or Y position * @return { Number } The pixel offset * @protected */ _valueToOffset: function ( value ) { var offset = round( ( value - this.get( MIN ) ) / this._factor ); Y.log("Value: " + value + " => Offset: " + offset, "info", "slider"); return offset; }, /** * Returns the current value. Override this if you want to introduce * output formatting. Otherwise equivalent to slider.get( "value" ); * * @method getValue * @return {Number} */ getValue: function () { return this.get( VALUE ); }, /** * Updates the current value. Override this if you want to introduce * input value parsing or preprocessing. Otherwise equivalent to * slider.set( "value", v ); * * @method setValue * @param val {Number} The new value * @return {Slider} * @chainable */ setValue: function ( val ) { return this.set( VALUE, val ); }, /** * Update position according to new min value. If the new min results * in the current value being out of range, the value is set to the * closer of min or max. * * @method _afterMinChange * @param e { EventFacade } The min attribute change event. * @protected */ _afterMinChange: function ( e ) { this._verifyValue(); this._syncThumbPosition(); }, /** * Update position according to new max value. If the new max results * in the current value being out of range, the value is set to the * closer of min or max. * * @method _afterMaxChange * @param e { EventFacade } The max attribute change event. * @protected */ _afterMaxChange: function ( e ) { this._verifyValue(); this._syncThumbPosition(); }, /** * Verifies that the current value is within the min - max range. If * not, value is set to either min or max, depending on which is * closer. * * @method _verifyValue * @protected */ _verifyValue: function () { var value = this.get( VALUE ), nearest = this._nearestValue( value ); if ( value !== nearest ) { // @TODO Can/should valueChange, minChange, etc be queued // events? To make dd.set( 'min', n ); execute after minChange // subscribers before on/after valueChange subscribers. this.set( VALUE, nearest ); } }, /** * Propagate change to the thumb position unless the change originated * from the thumbMove event. * * @method _afterValueChange * @param e { EventFacade } The valueChange event. * @protected */ _afterValueChange: function ( e ) { var val = e.newVal; Y.log("Positioning thumb after set('value',x)","info","slider"); this._setPosition( val, { source: 'set' } ); }, /** * Positions the thumb and its ARIA attributes in accordance with the * translated value. * * @method _setPosition * @param value {Number} Value to translate to a pixel position * @param [options] {Object} Details object to pass to `_uiMoveThumb` * @protected */ _setPosition: function ( value, options ) { this._uiMoveThumb( this._valueToOffset( value ), options ); this.thumb.set('aria-valuenow', value); this.thumb.set('aria-valuetext', value); }, /** * Validates new values assigned to min attribute. Numbers * are acceptable. Override this to enforce different rules. * * @method _validateNewMin * @param value {Any} Value assigned to min attribute. * @return {Boolean} True for numbers. False otherwise. * @protected */ _validateNewMin: function ( value ) { return Y.Lang.isNumber( value ); }, /** * Validates new values assigned to max attribute. Numbers * are acceptable. Override this to enforce different rules. * * @method _validateNewMax * @param value { mixed } Value assigned to max attribute. * @return { Boolean } True for numbers. False otherwise. * @protected */ _validateNewMax: function ( value ) { return Y.Lang.isNumber( value ); }, /** * Restricts new values assigned to value attribute to be * between the configured min and max. * Rounds to nearest integer value. * * @method _setNewValue * @param value { Number } Value assigned to value attribute * @return { Number } Normalized and constrained value * @protected */ _setNewValue: function ( value ) { if ( Y.Lang.isNumber( value ) ) { return round( this._nearestValue( value ) ); } return Y.Attribute.INVALID_VALUE; }, /** * Returns the nearest valid value to the value input. If the provided * value is outside the min - max range, accounting for min > max * scenarios, the nearest of either min or max is returned. Otherwise, * the provided value is returned. * * @method _nearestValue * @param value { mixed } Value to test against current min - max range * @return { Number } Current min, max, or value if within range * @protected */ _nearestValue: function ( value ) { var min = this.get( MIN ), max = this.get( MAX ), tmp; // Account for reverse value range (min > max) tmp = ( max > min ) ? max : min; min = ( max > min ) ? min : max; max = tmp; return ( value < min ) ? min : ( value > max ) ? max : value; } }, /** * Attributes that will be added onto host class. * * @property ATTRS * @type {Object} * @static * @protected */ ATTRS: { /** * The value associated with the farthest top, left position of the * rail. Can be greater than the configured max if you * want values to increase from right-to-left or bottom-to-top. * * @attribute min * @type { Number } * @default 0 */ min: { value : 0, validator: '_validateNewMin' }, /** * The value associated with the farthest bottom, right position of * the rail. Can be less than the configured min if * you want values to increase from right-to-left or bottom-to-top. * * @attribute max * @type { Number } * @default 100 */ max: { value : 100, validator: '_validateNewMax' }, /** * amount to increment/decrement the Slider value * when the arrow up/down/left/right keys are pressed * * @attribute minorStep * @type {Number} * @default 1 */ minorStep : { value: 1 }, /** * amount to increment/decrement the Slider value * when the page up/down keys are pressed * * @attribute majorStep * @type {Number} * @default 10 */ majorStep : { value: 10 }, /** * The value associated with the thumb's current position on the * rail. Defaults to the value inferred from the thumb's current * position. Specifying value in the constructor will move the * thumb to the position that corresponds to the supplied value. * * @attribute value * @type { Number } * @default (inferred from current thumb position) */ value: { value : 0, setter: '_setNewValue' } } }, true ); }, '3.18.1', {"requires": ["slider-base"]}); PK\@k55/3.18.1/slider-value-range/slider-value-range.jsnu[YUI.add('slider-value-range', function (Y, NAME) { /** * Adds value support for Slider as a range of integers between a configured * minimum and maximum value. For use with Y.Base.build(..) to * add the plumbing to Y.SliderBase. * * @module slider * @submodule slider-value-range */ // Constants for compression or performance var MIN = 'min', MAX = 'max', VALUE = 'value', // MINORSTEP = 'minorStep', // MAJORSTEP = 'majorStep', round = Math.round; /** * One class of value algorithm that can be built onto SliderBase. By default, * values range between 0 and 100, but you can configure these on the * built Slider class by setting the min and max * configurations. Set the initial value (will cause the thumb to move to the * appropriate location on the rail) in configuration as well if appropriate. * * @class SliderValueRange */ function SliderValueRange() { this._initSliderValueRange(); } Y.SliderValueRange = Y.mix( SliderValueRange, { // Prototype properties and methods that will be added onto host class prototype: { /** * Factor used to translate value -> position -> value. * * @property _factor * @type {Number} * @protected */ _factor: 1, /** * Stub for construction logic. Override if extending this class and * you need to set something up during the initializer phase. * * @method _initSliderValueRange * @protected */ _initSliderValueRange: function () {}, /** * Override of stub method in SliderBase that is called at the end of * its bindUI stage of render(). Subscribes to internal events to * trigger UI and related state updates. * * @method _bindValueLogic * @protected */ _bindValueLogic: function () { this.after( { minChange : this._afterMinChange, maxChange : this._afterMaxChange, valueChange: this._afterValueChange } ); }, /** * Move the thumb to appropriate position if necessary. Also resets * the cached offsets and recalculates the conversion factor to * translate position to value. * * @method _syncThumbPosition * @protected */ _syncThumbPosition: function () { this._calculateFactor(); this._setPosition( this.get( VALUE ) ); }, /** * Calculates and caches * (range between max and min) / (rail length) * for fast runtime calculation of position -> value. * * @method _calculateFactor * @protected */ _calculateFactor: function () { var length = this.get( 'length' ), thumbSize = this.thumb.getStyle( this._key.dim ), min = this.get( MIN ), max = this.get( MAX ); // The default thumb width is based on Sam skin's thumb dimension. // This attempts to allow for rendering off-DOM, then attaching // without the need to call syncUI(). It is still recommended // to call syncUI() in these cases though, just to be sure. length = parseFloat( length ) || 150; thumbSize = parseFloat( thumbSize ) || 15; this._factor = ( max - min ) / ( length - thumbSize ); }, /** * Dispatch the new position of the thumb into the value setting * operations. * * @method _defThumbMoveFn * @param e { EventFacade } The host's thumbMove event * @protected */ _defThumbMoveFn: function ( e ) { // To prevent set('value', x) from looping back around if (e.source !== 'set') { this.set(VALUE, this._offsetToValue(e.offset)); } }, /** *

Converts a pixel position into a value. Calculates current * thumb offset from the leading edge of the rail multiplied by the * ratio of (max - min) / (constraining dim).

* *

Override this if you want to use a different value mapping * algorithm.

* * @method _offsetToValue * @param offset { Number } X or Y pixel offset * @return { mixed } Value corresponding to the provided pixel offset * @protected */ _offsetToValue: function ( offset ) { var value = round( offset * this._factor ) + this.get( MIN ); return round( this._nearestValue( value ) ); }, /** * Converts a value into a pixel offset for use in positioning * the thumb according to the reverse of the * _offsetToValue( xy ) operation. * * @method _valueToOffset * @param val { Number } The value to map to pixel X or Y position * @return { Number } The pixel offset * @protected */ _valueToOffset: function ( value ) { var offset = round( ( value - this.get( MIN ) ) / this._factor ); return offset; }, /** * Returns the current value. Override this if you want to introduce * output formatting. Otherwise equivalent to slider.get( "value" ); * * @method getValue * @return {Number} */ getValue: function () { return this.get( VALUE ); }, /** * Updates the current value. Override this if you want to introduce * input value parsing or preprocessing. Otherwise equivalent to * slider.set( "value", v ); * * @method setValue * @param val {Number} The new value * @return {Slider} * @chainable */ setValue: function ( val ) { return this.set( VALUE, val ); }, /** * Update position according to new min value. If the new min results * in the current value being out of range, the value is set to the * closer of min or max. * * @method _afterMinChange * @param e { EventFacade } The min attribute change event. * @protected */ _afterMinChange: function ( e ) { this._verifyValue(); this._syncThumbPosition(); }, /** * Update position according to new max value. If the new max results * in the current value being out of range, the value is set to the * closer of min or max. * * @method _afterMaxChange * @param e { EventFacade } The max attribute change event. * @protected */ _afterMaxChange: function ( e ) { this._verifyValue(); this._syncThumbPosition(); }, /** * Verifies that the current value is within the min - max range. If * not, value is set to either min or max, depending on which is * closer. * * @method _verifyValue * @protected */ _verifyValue: function () { var value = this.get( VALUE ), nearest = this._nearestValue( value ); if ( value !== nearest ) { // @TODO Can/should valueChange, minChange, etc be queued // events? To make dd.set( 'min', n ); execute after minChange // subscribers before on/after valueChange subscribers. this.set( VALUE, nearest ); } }, /** * Propagate change to the thumb position unless the change originated * from the thumbMove event. * * @method _afterValueChange * @param e { EventFacade } The valueChange event. * @protected */ _afterValueChange: function ( e ) { var val = e.newVal; this._setPosition( val, { source: 'set' } ); }, /** * Positions the thumb and its ARIA attributes in accordance with the * translated value. * * @method _setPosition * @param value {Number} Value to translate to a pixel position * @param [options] {Object} Details object to pass to `_uiMoveThumb` * @protected */ _setPosition: function ( value, options ) { this._uiMoveThumb( this._valueToOffset( value ), options ); this.thumb.set('aria-valuenow', value); this.thumb.set('aria-valuetext', value); }, /** * Validates new values assigned to min attribute. Numbers * are acceptable. Override this to enforce different rules. * * @method _validateNewMin * @param value {Any} Value assigned to min attribute. * @return {Boolean} True for numbers. False otherwise. * @protected */ _validateNewMin: function ( value ) { return Y.Lang.isNumber( value ); }, /** * Validates new values assigned to max attribute. Numbers * are acceptable. Override this to enforce different rules. * * @method _validateNewMax * @param value { mixed } Value assigned to max attribute. * @return { Boolean } True for numbers. False otherwise. * @protected */ _validateNewMax: function ( value ) { return Y.Lang.isNumber( value ); }, /** * Restricts new values assigned to value attribute to be * between the configured min and max. * Rounds to nearest integer value. * * @method _setNewValue * @param value { Number } Value assigned to value attribute * @return { Number } Normalized and constrained value * @protected */ _setNewValue: function ( value ) { if ( Y.Lang.isNumber( value ) ) { return round( this._nearestValue( value ) ); } return Y.Attribute.INVALID_VALUE; }, /** * Returns the nearest valid value to the value input. If the provided * value is outside the min - max range, accounting for min > max * scenarios, the nearest of either min or max is returned. Otherwise, * the provided value is returned. * * @method _nearestValue * @param value { mixed } Value to test against current min - max range * @return { Number } Current min, max, or value if within range * @protected */ _nearestValue: function ( value ) { var min = this.get( MIN ), max = this.get( MAX ), tmp; // Account for reverse value range (min > max) tmp = ( max > min ) ? max : min; min = ( max > min ) ? min : max; max = tmp; return ( value < min ) ? min : ( value > max ) ? max : value; } }, /** * Attributes that will be added onto host class. * * @property ATTRS * @type {Object} * @static * @protected */ ATTRS: { /** * The value associated with the farthest top, left position of the * rail. Can be greater than the configured max if you * want values to increase from right-to-left or bottom-to-top. * * @attribute min * @type { Number } * @default 0 */ min: { value : 0, validator: '_validateNewMin' }, /** * The value associated with the farthest bottom, right position of * the rail. Can be less than the configured min if * you want values to increase from right-to-left or bottom-to-top. * * @attribute max * @type { Number } * @default 100 */ max: { value : 100, validator: '_validateNewMax' }, /** * amount to increment/decrement the Slider value * when the arrow up/down/left/right keys are pressed * * @attribute minorStep * @type {Number} * @default 1 */ minorStep : { value: 1 }, /** * amount to increment/decrement the Slider value * when the page up/down keys are pressed * * @attribute majorStep * @type {Number} * @default 10 */ majorStep : { value: 10 }, /** * The value associated with the thumb's current position on the * rail. Defaults to the value inferred from the thumb's current * position. Specifying value in the constructor will move the * thumb to the position that corresponds to the supplied value. * * @attribute value * @type { Number } * @default (inferred from current thumb position) */ value: { value : 0, setter: '_setNewValue' } } }, true ); }, '3.18.1', {"requires": ["slider-base"]}); PK\Sz33.18.1/slider-value-range/slider-value-range-min.jsnu[YUI.add("slider-value-range",function(e,t){function o(){this._initSliderValueRange()}var n="min",r="max",i="value",s=Math.round;e.SliderValueRange=e.mix(o,{prototype:{_factor:1,_initSliderValueRange:function(){},_bindValueLogic:function(){this.after({minChange:this._afterMinChange,maxChange:this._afterMaxChange,valueChange:this._afterValueChange})},_syncThumbPosition:function(){this._calculateFactor(),this._setPosition(this.get(i))},_calculateFactor:function(){var e=this.get("length"),t=this.thumb.getStyle(this._key.dim),i=this.get(n),s=this.get(r);e=parseFloat(e)||150,t=parseFloat(t)||15,this._factor=(s-i)/(e-t)},_defThumbMoveFn:function(e){e.source!=="set"&&this.set(i,this._offsetToValue(e.offset))},_offsetToValue:function(e){var t=s(e*this._factor)+this.get(n);return s(this._nearestValue(t))},_valueToOffset:function(e){var t=s((e-this.get(n))/this._factor);return t},getValue:function(){return this.get(i)},setValue:function(e){return this.set(i,e)},_afterMinChange:function(e){this._verifyValue(),this._syncThumbPosition()},_afterMaxChange:function(e){this._verifyValue(),this._syncThumbPosition()},_verifyValue:function(){var e=this.get(i),t=this._nearestValue(e);e!==t&&this.set(i,t)},_afterValueChange:function(e){var t=e.newVal;this._setPosition(t,{source:"set"})},_setPosition:function(e,t){this._uiMoveThumb(this._valueToOffset(e),t),this.thumb.set("aria-valuenow",e),this.thumb.set("aria-valuetext",e)},_validateNewMin:function(t){return e.Lang.isNumber(t)},_validateNewMax:function(t){return e.Lang.isNumber(t)},_setNewValue:function(t){return e.Lang.isNumber(t)?s(this._nearestValue(t)):e.Attribute.INVALID_VALUE},_nearestValue:function(e){var t=this.get(n),i=this.get(r),s;return s=i>t?i:t,t=i>t?t:i,i=s,ei?i:e}},ATTRS:{min:{value:0,validator:"_validateNewMin"},max:{value:100,validator:"_validateNewMax"},minorStep:{value:1},majorStep:{value:10},value:{value:0,setter:"_setNewValue"}}},!0)},"3.18.1",{requires:["slider-base"]}); PK\200/3.18.1/event-mouseenter/event-mouseenter-min.jsnu[YUI.add("event-mouseenter",function(e,t){var n=e.Env.evt.dom_wrappers,r=e.DOM.contains,i=e.Array,s=function(){},o={proxyType:"mouseover",relProperty:"fromElement",_notify:function(t,i,s){var o=this._node,u=t.relatedTarget||t[i];o!==u&&!r(o,u)&&s.fire(new e.DOMEventFacade(t,o,n["event:"+e.stamp(o)+t.type]))},on:function(t,n,r){var i=e.Node.getDOMNode(t),s=[this.proxyType,this._notify,i,null,this.relProperty,r];n.handle=e.Event._attach(s,{facade:!1})},detach:function(e,t){t.handle.detach()},delegate:function(t,n,r,i){var o=e.Node.getDOMNode(t),u=[this.proxyType,s,o,null,r];n.handle=e.Event._attach(u,{facade:!1}),n.handle.sub.filter=i,n.handle.sub.relProperty=this.relProperty,n.handle.sub._notify=this._filterNotify},_filterNotify:function(t,n,s){n=n.slice(),this.args&&n.push.apply(n,this.args);var o=e.delegate._applyFilter(this.filter,n,s),u=n[0].relatedTarget||n[0][this.relProperty],a,f,l,c,h;if(o){o=i(o);for(f=0,l=o.length&&(!a||!a.stopped);fAdds 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); }, '3.18.1', {"requires": ["event-synthetic"]}); PK\H"ss+3.18.1/event-mouseenter/event-mouseenter.jsnu[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); }, '3.18.1', {"requires": ["event-synthetic"]}); PK\ %3.18.1/editor-tab/editor-tab-debug.jsnu[YUI.add('editor-tab', function (Y, NAME) { /** * Handles tab and shift-tab indent/outdent support. * @class Plugin.EditorTab * @constructor * @extends Base * @module editor * @submodule editor-tab */ var EditorTab = function() { EditorTab.superclass.constructor.apply(this, arguments); }, HOST = 'host'; Y.extend(EditorTab, Y.Base, { /** * Listener for host's nodeChange event and captures the tabkey interaction. * @private * @method _onNodeChange * @param {Event} e The Event facade passed from the host. */ _onNodeChange: function(e) { var action = 'indent'; if (e.changedType === 'tab') { if (!e.changedNode.test('li, li *')) { e.changedEvent.halt(); e.preventDefault(); if (e.changedEvent.shiftKey) { action = 'outdent'; } Y.log('Overriding TAB to ' + action, 'info', 'editorTab'); this.get(HOST).execCommand(action, ''); } } }, initializer: function() { this.get(HOST).on('nodeChange', Y.bind(this._onNodeChange, this)); } }, { /** * editorTab * @property NAME * @static */ NAME: 'editorTab', /** * tab * @property NS * @static */ NS: 'tab', ATTRS: { host: { value: false } } }); Y.namespace('Plugin'); Y.Plugin.EditorTab = EditorTab; }, '3.18.1', {"requires": ["editor-base"]}); PK\ ,00#3.18.1/editor-tab/editor-tab-min.jsnu[YUI.add("editor-tab",function(e,t){var n=function(){n.superclass.constructor.apply(this,arguments)},r="host";e.extend(n,e.Base,{_onNodeChange:function(e){var t="indent";e.changedType==="tab"&&(e.changedNode.test("li, li *")||(e.changedEvent.halt(),e.preventDefault(),e.changedEvent.shiftKey&&(t="outdent"),this.get(r).execCommand(t,"")))},initializer:function(){this.get(r).on("nodeChange",e.bind(this._onNodeChange,this))}},{NAME:"editorTab",NS:"tab",ATTRS:{host:{value:!1}}}),e.namespace("Plugin"),e.Plugin.EditorTab=n},"3.18.1",{requires:["editor-base"]}); PK\=iqq3.18.1/editor-tab/editor-tab.jsnu[YUI.add('editor-tab', function (Y, NAME) { /** * Handles tab and shift-tab indent/outdent support. * @class Plugin.EditorTab * @constructor * @extends Base * @module editor * @submodule editor-tab */ var EditorTab = function() { EditorTab.superclass.constructor.apply(this, arguments); }, HOST = 'host'; Y.extend(EditorTab, Y.Base, { /** * Listener for host's nodeChange event and captures the tabkey interaction. * @private * @method _onNodeChange * @param {Event} e The Event facade passed from the host. */ _onNodeChange: function(e) { var action = 'indent'; if (e.changedType === 'tab') { if (!e.changedNode.test('li, li *')) { e.changedEvent.halt(); e.preventDefault(); if (e.changedEvent.shiftKey) { action = 'outdent'; } this.get(HOST).execCommand(action, ''); } } }, initializer: function() { this.get(HOST).on('nodeChange', Y.bind(this._onNodeChange, this)); } }, { /** * editorTab * @property NAME * @static */ NAME: 'editorTab', /** * tab * @property NS * @static */ NS: 'tab', ATTRS: { host: { value: false } } }); Y.namespace('Plugin'); Y.Plugin.EditorTab = EditorTab; }, '3.18.1', {"requires": ["editor-base"]}); PK\ 93.18.1/series-column-stacked/series-column-stacked-min.jsnu[YUI.add("series-column-stacked",function(e,t){var n=e.Lang;e.StackedColumnSeries=e.Base.create("stackedColumnSeries",e.ColumnSeries,[e.StackingUtil],{drawSeries:function(){if(this.get("xcoords").length<1)return;var e=n.isNumber,t=this._copyObject(this.get("styles").marker),r=t.width,i=t.height,s=this.get("xcoords"),o=this.get("ycoords"),u=0,a=s.length,f=o[0],l=this.get("seriesTypeCollection"),c,h=this.get("order"),p=this.get("graphOrder"),d,v,m,g,y,b,w,E=h===0,S=a*r,x={width:[],height:[]},T=[],N=[],C=this.get("groupMarkers");n.isArray(t.fill.color)&&(m=t.fill.color.concat()),n.isArray(t.border.color)&&(g=t.border.color.concat()),this._createMarkerCache(),S>this.get("width")&&(c=this.get("width")/S,r*=c,r=Math.max(r,1));if(!E){y=l[h-1],b=y.get("negativeBaseValues"),w=y.get("positiveBaseValues");if(!b||!w)E=!0,w=[],b=[]}else b=[],w=[];this.set("negativeBaseValues",b),this.set("positiveBaseValues",w);for(u=0;uthis._bottomOrigin?(w[u]=this._bottomOrigin,b[u]=f,f-=i):(w[u]=f,b[u]=f)):f>this._bottomOrigin?(f+=b[u]-this._bottomOrigin,i=f-b[u],b[u]=f,f-=i):f<=this._bottomOrigin&&(f=w[u]-(this._bottomOrigin-f),i=w[u]-f,w[u]=f),!isNaN(i)&&i>0?(d-=r/2,C?(x.width[u]=r,x.height[u]=i,T.push(d),N.push(f)):(t.width=r,t.height=i,t.x=d,t.y=f,m&&(t.fill.color=m[u%m.length]),g&&(t.border.color=g[u%g.length]),v=this.getMarker(t,p,u))):C||this._markers.push(null)}C?this._createGroupMarker({fill:t.fill,border:t.border,dimensions:x,xvalues:T,yvalues:N,shape:t.shape}):this._clearMarkerCache()},updateMarkerState:function(e,t){if(this._markers&&this._markers[t]){var r,i,s=this._getState(e),o=this.get("xcoords"),u=this._markers[t],a=0,f,l;r=this.get("styles").marker,a=r.width*.5,i=s==="off"||!r[s]?this._copyObject(r):this._copyObject(r[s]),i.height=u.get("height"),i.x=o[t]-a,i.y=u.get("y"),i.id=u.get("id"),f=i.fill.color,l=i.border.color,n.isArray(f)?i.fill.color=f[t%f.length]:i.fill.color=this._getItemColor(i.fill.color,t),n.isArray(l)?i.border.color=l[t%l.length]:i.border.color=this._getItemColor(i.border.color,t),u.set(i)}},_getPlotDefaults:function(){var e={fill:{type:"solid",alpha:1,colors:null,alphas:null,ratios:null},border:{weight:0,alpha:1},width:24,height:24,shape:"rect",padding:{top:0,left:0,right:0,bottom:0}};return e.fill.color=this._getDefaultColor(this.get("graphOrder"),"fill"),e.border.color=this._getDefaultColor(this.get("graphOrder"),"border"),e}},{ATTRS:{type:{value:"stackedColumn"},negativeBaseValues:{value:null},positiveBaseValues:{value:null}}})},"3.18.1",{requires:["series-stacked","series-column"]}); PK\u?;-;-53.18.1/series-column-stacked/series-column-stacked.jsnu[YUI.add('series-column-stacked', function (Y, NAME) { /** * Provides functionality for creating a stacked column series. * * @module charts * @submodule series-column-stacked */ var Y_Lang = Y.Lang; /** * The StackedColumnSeries renders column chart in which series are stacked vertically to show * their contribution to the cumulative total. * * @class StackedColumnSeries * @extends ColumnSeries * @uses StackingUtil * @constructor * @param {Object} config (optional) Configuration parameters. * @submodule series-column-stacked */ Y.StackedColumnSeries = Y.Base.create("stackedColumnSeries", Y.ColumnSeries, [Y.StackingUtil], { /** * Draws the series. * * @method drawSeries * @protected */ drawSeries: function() { if(this.get("xcoords").length < 1) { return; } var isNumber = Y_Lang.isNumber, style = this._copyObject(this.get("styles").marker), w = style.width, h = style.height, xcoords = this.get("xcoords"), ycoords = this.get("ycoords"), i = 0, len = xcoords.length, top = ycoords[0], seriesCollection = this.get("seriesTypeCollection"), ratio, order = this.get("order"), graphOrder = this.get("graphOrder"), left, marker, fillColors, borderColors, lastCollection, negativeBaseValues, positiveBaseValues, useOrigin = order === 0, totalWidth = len * w, dimensions = { width: [], height: [] }, xvalues = [], yvalues = [], groupMarkers = this.get("groupMarkers"); if(Y_Lang.isArray(style.fill.color)) { fillColors = style.fill.color.concat(); } if(Y_Lang.isArray(style.border.color)) { borderColors = style.border.color.concat(); } this._createMarkerCache(); if(totalWidth > this.get("width")) { ratio = this.get("width")/totalWidth; w *= ratio; w = Math.max(w, 1); } if(!useOrigin) { lastCollection = seriesCollection[order - 1]; negativeBaseValues = lastCollection.get("negativeBaseValues"); positiveBaseValues = lastCollection.get("positiveBaseValues"); if(!negativeBaseValues || !positiveBaseValues) { useOrigin = true; positiveBaseValues = []; negativeBaseValues = []; } } else { negativeBaseValues = []; positiveBaseValues = []; } this.set("negativeBaseValues", negativeBaseValues); this.set("positiveBaseValues", positiveBaseValues); for(i = 0; i < len; ++i) { left = xcoords[i]; top = ycoords[i]; if(!isNumber(top) || !isNumber(left)) { if(useOrigin) { negativeBaseValues[i] = this._bottomOrigin; positiveBaseValues[i] = this._bottomOrigin; } this._markers.push(null); continue; } if(useOrigin) { h = Math.abs(this._bottomOrigin - top); if(top < this._bottomOrigin) { positiveBaseValues[i] = top; negativeBaseValues[i] = this._bottomOrigin; } else if(top > this._bottomOrigin) { positiveBaseValues[i] = this._bottomOrigin; negativeBaseValues[i] = top; top -= h; } else { positiveBaseValues[i] = top; negativeBaseValues[i] = top; } } else { if(top > this._bottomOrigin) { top += (negativeBaseValues[i] - this._bottomOrigin); h = top - negativeBaseValues[i]; negativeBaseValues[i] = top; top -= h; } else if(top <= this._bottomOrigin) { top = positiveBaseValues[i] - (this._bottomOrigin - top); h = positiveBaseValues[i] - top; positiveBaseValues[i] = top; } } if(!isNaN(h) && h > 0) { left -= w/2; if(groupMarkers) { dimensions.width[i] = w; dimensions.height[i] = h; xvalues.push(left); yvalues.push(top); } else { style.width = w; style.height = h; style.x = left; style.y = top; if(fillColors) { style.fill.color = fillColors[i % fillColors.length]; } if(borderColors) { style.border.color = borderColors[i % borderColors.length]; } marker = this.getMarker(style, graphOrder, i); } } else if(!groupMarkers) { this._markers.push(null); } } if(groupMarkers) { this._createGroupMarker({ fill: style.fill, border: style.border, dimensions: dimensions, xvalues: xvalues, yvalues: yvalues, shape: style.shape }); } else { this._clearMarkerCache(); } }, /** * Resizes and positions markers based on a mouse interaction. * * @method updateMarkerState * @param {String} type state of the marker * @param {Number} i index of the marker * @protected */ updateMarkerState: function(type, i) { if(this._markers && this._markers[i]) { var styles, markerStyles, state = this._getState(type), xcoords = this.get("xcoords"), marker = this._markers[i], offset = 0, fillColor, borderColor; styles = this.get("styles").marker; offset = styles.width * 0.5; markerStyles = state === "off" || !styles[state] ? this._copyObject(styles) : this._copyObject(styles[state]); markerStyles.height = marker.get("height"); markerStyles.x = (xcoords[i] - offset); markerStyles.y = marker.get("y"); markerStyles.id = marker.get("id"); fillColor = markerStyles.fill.color; borderColor = markerStyles.border.color; if(Y_Lang.isArray(fillColor)) { markerStyles.fill.color = fillColor[i % fillColor.length]; } else { markerStyles.fill.color = this._getItemColor(markerStyles.fill.color, i); } if(Y_Lang.isArray(borderColor)) { markerStyles.border.color = borderColor[i % borderColor.length]; } else { markerStyles.border.color = this._getItemColor(markerStyles.border.color, i); } marker.set(markerStyles); } }, /** * Gets the default values for the markers. * * @method _getPlotDefaults * @return Object * @protected */ _getPlotDefaults: function() { var defs = { fill:{ type: "solid", alpha: 1, colors:null, alphas: null, ratios: null }, border:{ weight: 0, alpha: 1 }, width: 24, height: 24, shape: "rect", padding:{ top: 0, left: 0, right: 0, bottom: 0 } }; defs.fill.color = this._getDefaultColor(this.get("graphOrder"), "fill"); defs.border.color = this._getDefaultColor(this.get("graphOrder"), "border"); return defs; } }, { ATTRS: { /** * Read-only attribute indicating the type of series. * * @attribute type * @type String * @default stackedColumn */ type: { value: "stackedColumn" }, /** * @attribute negativeBaseValues * @type Array * @default null * @private */ negativeBaseValues: { value: null }, /** * @attribute positiveBaseValues * @type Array * @default null * @private */ positiveBaseValues: { value: null } /** * Style properties used for drawing markers. This attribute is inherited from `ColumnSeries`. Below are the default values: *
*
fill
A hash containing the following values: *
*
color
Color of the fill. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:
* `["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"]` *
*
alpha
Number from 0 to 1 indicating the opacity of the marker fill. The default value is 1.
*
*
*
border
A hash containing the following values: *
*
color
Color of the border. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:
* `["#205096", "#b38206", "#000000", "#94001e", "#9d6fa0", "#e55b00", "#5e85c9", "#adab9e", "#6ac291", "#006457"]` *
alpha
Number from 0 to 1 indicating the opacity of the marker border. The default value is 1.
*
weight
Number indicating the width of the border. The default value is 1.
*
*
*
width
indicates the width of the marker. The default value is 24.
*
over
hash containing styles for markers when highlighted by a `mouseover` event. The default * values for each style is null. When an over style is not set, the non-over value will be used. For example, * the default value for `marker.over.fill.color` is equivalent to `marker.fill.color`.
*
* * @attribute styles * @type Object */ } }); }, '3.18.1', {"requires": ["series-stacked", "series-column"]}); PK\u?;-;-;3.18.1/series-column-stacked/series-column-stacked-debug.jsnu[YUI.add('series-column-stacked', function (Y, NAME) { /** * Provides functionality for creating a stacked column series. * * @module charts * @submodule series-column-stacked */ var Y_Lang = Y.Lang; /** * The StackedColumnSeries renders column chart in which series are stacked vertically to show * their contribution to the cumulative total. * * @class StackedColumnSeries * @extends ColumnSeries * @uses StackingUtil * @constructor * @param {Object} config (optional) Configuration parameters. * @submodule series-column-stacked */ Y.StackedColumnSeries = Y.Base.create("stackedColumnSeries", Y.ColumnSeries, [Y.StackingUtil], { /** * Draws the series. * * @method drawSeries * @protected */ drawSeries: function() { if(this.get("xcoords").length < 1) { return; } var isNumber = Y_Lang.isNumber, style = this._copyObject(this.get("styles").marker), w = style.width, h = style.height, xcoords = this.get("xcoords"), ycoords = this.get("ycoords"), i = 0, len = xcoords.length, top = ycoords[0], seriesCollection = this.get("seriesTypeCollection"), ratio, order = this.get("order"), graphOrder = this.get("graphOrder"), left, marker, fillColors, borderColors, lastCollection, negativeBaseValues, positiveBaseValues, useOrigin = order === 0, totalWidth = len * w, dimensions = { width: [], height: [] }, xvalues = [], yvalues = [], groupMarkers = this.get("groupMarkers"); if(Y_Lang.isArray(style.fill.color)) { fillColors = style.fill.color.concat(); } if(Y_Lang.isArray(style.border.color)) { borderColors = style.border.color.concat(); } this._createMarkerCache(); if(totalWidth > this.get("width")) { ratio = this.get("width")/totalWidth; w *= ratio; w = Math.max(w, 1); } if(!useOrigin) { lastCollection = seriesCollection[order - 1]; negativeBaseValues = lastCollection.get("negativeBaseValues"); positiveBaseValues = lastCollection.get("positiveBaseValues"); if(!negativeBaseValues || !positiveBaseValues) { useOrigin = true; positiveBaseValues = []; negativeBaseValues = []; } } else { negativeBaseValues = []; positiveBaseValues = []; } this.set("negativeBaseValues", negativeBaseValues); this.set("positiveBaseValues", positiveBaseValues); for(i = 0; i < len; ++i) { left = xcoords[i]; top = ycoords[i]; if(!isNumber(top) || !isNumber(left)) { if(useOrigin) { negativeBaseValues[i] = this._bottomOrigin; positiveBaseValues[i] = this._bottomOrigin; } this._markers.push(null); continue; } if(useOrigin) { h = Math.abs(this._bottomOrigin - top); if(top < this._bottomOrigin) { positiveBaseValues[i] = top; negativeBaseValues[i] = this._bottomOrigin; } else if(top > this._bottomOrigin) { positiveBaseValues[i] = this._bottomOrigin; negativeBaseValues[i] = top; top -= h; } else { positiveBaseValues[i] = top; negativeBaseValues[i] = top; } } else { if(top > this._bottomOrigin) { top += (negativeBaseValues[i] - this._bottomOrigin); h = top - negativeBaseValues[i]; negativeBaseValues[i] = top; top -= h; } else if(top <= this._bottomOrigin) { top = positiveBaseValues[i] - (this._bottomOrigin - top); h = positiveBaseValues[i] - top; positiveBaseValues[i] = top; } } if(!isNaN(h) && h > 0) { left -= w/2; if(groupMarkers) { dimensions.width[i] = w; dimensions.height[i] = h; xvalues.push(left); yvalues.push(top); } else { style.width = w; style.height = h; style.x = left; style.y = top; if(fillColors) { style.fill.color = fillColors[i % fillColors.length]; } if(borderColors) { style.border.color = borderColors[i % borderColors.length]; } marker = this.getMarker(style, graphOrder, i); } } else if(!groupMarkers) { this._markers.push(null); } } if(groupMarkers) { this._createGroupMarker({ fill: style.fill, border: style.border, dimensions: dimensions, xvalues: xvalues, yvalues: yvalues, shape: style.shape }); } else { this._clearMarkerCache(); } }, /** * Resizes and positions markers based on a mouse interaction. * * @method updateMarkerState * @param {String} type state of the marker * @param {Number} i index of the marker * @protected */ updateMarkerState: function(type, i) { if(this._markers && this._markers[i]) { var styles, markerStyles, state = this._getState(type), xcoords = this.get("xcoords"), marker = this._markers[i], offset = 0, fillColor, borderColor; styles = this.get("styles").marker; offset = styles.width * 0.5; markerStyles = state === "off" || !styles[state] ? this._copyObject(styles) : this._copyObject(styles[state]); markerStyles.height = marker.get("height"); markerStyles.x = (xcoords[i] - offset); markerStyles.y = marker.get("y"); markerStyles.id = marker.get("id"); fillColor = markerStyles.fill.color; borderColor = markerStyles.border.color; if(Y_Lang.isArray(fillColor)) { markerStyles.fill.color = fillColor[i % fillColor.length]; } else { markerStyles.fill.color = this._getItemColor(markerStyles.fill.color, i); } if(Y_Lang.isArray(borderColor)) { markerStyles.border.color = borderColor[i % borderColor.length]; } else { markerStyles.border.color = this._getItemColor(markerStyles.border.color, i); } marker.set(markerStyles); } }, /** * Gets the default values for the markers. * * @method _getPlotDefaults * @return Object * @protected */ _getPlotDefaults: function() { var defs = { fill:{ type: "solid", alpha: 1, colors:null, alphas: null, ratios: null }, border:{ weight: 0, alpha: 1 }, width: 24, height: 24, shape: "rect", padding:{ top: 0, left: 0, right: 0, bottom: 0 } }; defs.fill.color = this._getDefaultColor(this.get("graphOrder"), "fill"); defs.border.color = this._getDefaultColor(this.get("graphOrder"), "border"); return defs; } }, { ATTRS: { /** * Read-only attribute indicating the type of series. * * @attribute type * @type String * @default stackedColumn */ type: { value: "stackedColumn" }, /** * @attribute negativeBaseValues * @type Array * @default null * @private */ negativeBaseValues: { value: null }, /** * @attribute positiveBaseValues * @type Array * @default null * @private */ positiveBaseValues: { value: null } /** * Style properties used for drawing markers. This attribute is inherited from `ColumnSeries`. Below are the default values: *
*
fill
A hash containing the following values: *
*
color
Color of the fill. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:
* `["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"]` *
*
alpha
Number from 0 to 1 indicating the opacity of the marker fill. The default value is 1.
*
*
*
border
A hash containing the following values: *
*
color
Color of the border. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:
* `["#205096", "#b38206", "#000000", "#94001e", "#9d6fa0", "#e55b00", "#5e85c9", "#adab9e", "#6ac291", "#006457"]` *
alpha
Number from 0 to 1 indicating the opacity of the marker border. The default value is 1.
*
weight
Number indicating the width of the border. The default value is 1.
*
*
*
width
indicates the width of the marker. The default value is 24.
*
over
hash containing styles for markers when highlighted by a `mouseover` event. The default * values for each style is null. When an over style is not set, the non-over value will be used. For example, * the default value for `marker.over.fill.color` is equivalent to `marker.fill.color`.
*
* * @attribute styles * @type Object */ } }); }, '3.18.1', {"requires": ["series-stacked", "series-column"]}); PK\B.(9SS)3.18.1/graphics-canvas/graphics-canvas.jsnu[YUI.add('graphics-canvas', function (Y, NAME) { var IMPLEMENTATION = "canvas", SHAPE = "shape", SPLITPATHPATTERN = /[a-z][^a-z]*/ig, SPLITARGSPATTERN = /[\-]?[0-9]*[0-9|\.][0-9]*/g, DOCUMENT = Y.config.doc, Y_LANG = Y.Lang, AttributeLite = Y.AttributeLite, CanvasShape, CanvasPath, CanvasRect, CanvasEllipse, CanvasCircle, CanvasPieSlice, Y_DOM = Y.DOM, Y_Color = Y.Color, PARSE_INT = parseInt, PARSE_FLOAT = parseFloat, IS_NUMBER = Y_LANG.isNumber, RE = RegExp, TORGB = Y_Color.toRGB, TOHEX = Y_Color.toHex, _getClassName = Y.ClassNameManager.getClassName; /** * Canvas implementation of the `Drawing` class. * `CanvasDrawing` is not intended to be used directly. Instead, use the `Drawing` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Drawing` * class will point to the `CanvasDrawing` class. * * @module graphics * @class CanvasDrawing * @constructor */ function CanvasDrawing() { } CanvasDrawing.prototype = { /** * Maps path to methods * * @property _pathSymbolToMethod * @type Object * @private */ _pathSymbolToMethod: { M: "moveTo", m: "relativeMoveTo", L: "lineTo", l: "relativeLineTo", C: "curveTo", c: "relativeCurveTo", Q: "quadraticCurveTo", q: "relativeQuadraticCurveTo", z: "closePath", Z: "closePath" }, /** * Current x position of the drawing. * * @property _currentX * @type Number * @private */ _currentX: 0, /** * Current y position of the drqwing. * * @property _currentY * @type Number * @private */ _currentY: 0, /** * Parses hex color string and alpha value to rgba * * @method _toRGBA * @param {Object} val Color value to parse. Can be hex string, rgb or name. * @param {Number} alpha Numeric value between 0 and 1 representing the alpha level. * @private */ _toRGBA: function(val, alpha) { alpha = (alpha !== undefined) ? alpha : 1; if (!Y_Color.re_RGB.test(val)) { val = TOHEX(val); } if(Y_Color.re_hex.exec(val)) { val = 'rgba(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(',') + ',' + alpha + ')'; } return val; }, /** * Converts color to rgb format * * @method _toRGB * @param val Color value to convert. * @private */ _toRGB: function(val) { return TORGB(val); }, /** * Sets the size of the graphics object. * * @method setSize * @param w {Number} width to set for the instance. * @param h {Number} height to set for the instance. * @private */ setSize: function(w, h) { if(this.get("autoSize")) { if(w > this.node.getAttribute("width")) { this.node.style.width = w + "px"; this.node.setAttribute("width", w); } if(h > this.node.getAttribute("height")) { this.node.style.height = h + "px"; this.node.setAttribute("height", h); } } }, /** * Tracks coordinates. Used to calculate the start point of dashed lines. * * @method _updateCoords * @param {Number} x x-coordinate * @param {Number} y y-coordinate * @private */ _updateCoords: function(x, y) { this._xcoords.push(x); this._ycoords.push(y); this._currentX = x; this._currentY = y; }, /** * Clears the coordinate arrays. Called at the end of a drawing operation. * * @method _clearAndUpdateCoords * @private */ _clearAndUpdateCoords: function() { var x = this._xcoords.pop() || 0, y = this._ycoords.pop() || 0; this._updateCoords(x, y); }, /** * Moves the shape's dom node. * * @method _updateNodePosition * @private */ _updateNodePosition: function() { var node = this.get("node"), x = this.get("x"), y = this.get("y"); node.style.position = "absolute"; node.style.left = (x + this._left) + "px"; node.style.top = (y + this._top) + "px"; }, /** * Queues up a method to be executed when a shape redraws. * * @method _updateDrawingQueue * @param {Array} val An array containing data that can be parsed into a method and arguments. The value at zero-index * of the array is a string reference of the drawing method that will be called. All subsequent indices are argument for * that method. For example, `lineTo(10, 100)` would be structured as: * `["lineTo", 10, 100]`. * @private */ _updateDrawingQueue: function(val) { this._methods.push(val); }, /** * Draws a line segment from the current drawing position to the specified x and y coordinates. * * @method lineTo * @param {Number} point1 x-coordinate for the end point. * @param {Number} point2 y-coordinate for the end point. * @chainable */ lineTo: function() { this._lineTo.apply(this, [Y.Array(arguments), false]); return this; }, /** * Draws a line segment from the current drawing position to the relative x and y coordinates. * * @method relativeLineTo * @param {Number} point1 x-coordinate for the end point. * @param {Number} point2 y-coordinate for the end point. * @chainable */ relativeLineTo: function() { this._lineTo.apply(this, [Y.Array(arguments), true]); return this; }, /** * Implements lineTo methods. * * @method _lineTo * @param {Array} args The arguments to be used. * @param {Boolean} relative Indicates whether or not to use relative coordinates. * @private */ _lineTo: function(args, relative) { var point1 = args[0], i, len, x, y, wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, relativeX = relative ? parseFloat(this._currentX) : 0, relativeY = relative ? parseFloat(this._currentY) : 0; if(!this._lineToMethods) { this._lineToMethods = []; } len = args.length - 1; if (typeof point1 === 'string' || typeof point1 === 'number') { for (i = 0; i < len; i = i + 2) { x = parseFloat(args[i]); y = parseFloat(args[i + 1]); x = x + relativeX; y = y + relativeY; this._updateDrawingQueue(["lineTo", x, y]); this._trackSize(x - wt, y - wt); this._trackSize(x + wt, y + wt); this._updateCoords(x, y); } } else { for (i = 0; i < len; i = i + 1) { x = parseFloat(args[i][0]); y = parseFloat(args[i][1]); this._updateDrawingQueue(["lineTo", x, y]); this._lineToMethods[this._lineToMethods.length] = this._methods[this._methods.length - 1]; this._trackSize(x - wt, y - wt); this._trackSize(x + wt, y + wt); this._updateCoords(x, y); } } this._drawingComplete = false; return this; }, /** * Moves the current drawing position to specified x and y coordinates. * * @method moveTo * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ moveTo: function() { this._moveTo.apply(this, [Y.Array(arguments), false]); return this; }, /** * Moves the current drawing position relative to specified x and y coordinates. * * @method relativeMoveTo * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ relativeMoveTo: function() { this._moveTo.apply(this, [Y.Array(arguments), true]); return this; }, /** * Implements moveTo methods. * * @method _moveTo * @param {Array} args The arguments to be used. * @param {Boolean} relative Indicates whether or not to use relative coordinates. * @private */ _moveTo: function(args, relative) { var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, relativeX = relative ? parseFloat(this._currentX) : 0, relativeY = relative ? parseFloat(this._currentY) : 0, x = parseFloat(args[0]) + relativeX, y = parseFloat(args[1]) + relativeY; this._updateDrawingQueue(["moveTo", x, y]); this._trackSize(x - wt, y - wt); this._trackSize(x + wt, y + wt); this._updateCoords(x, y); this._drawingComplete = false; return this; }, /** * Draws a bezier curve. * * @method curveTo * @param {Number} cp1x x-coordinate for the first control point. * @param {Number} cp1y y-coordinate for the first control point. * @param {Number} cp2x x-coordinate for the second control point. * @param {Number} cp2y y-coordinate for the second control point. * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ curveTo: function() { this._curveTo.apply(this, [Y.Array(arguments), false]); return this; }, /** * Draws a bezier curve relative to the current coordinates. * * @method relativeCurveTo * @param {Number} cp1x x-coordinate for the first control point. * @param {Number} cp1y y-coordinate for the first control point. * @param {Number} cp2x x-coordinate for the second control point. * @param {Number} cp2y y-coordinate for the second control point. * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ relativeCurveTo: function() { this._curveTo.apply(this, [Y.Array(arguments), true]); return this; }, /** * Implements curveTo methods. * * @method _curveTo * @param {Array} args The arguments to be used. * @param {Boolean} relative Indicates whether or not to use relative coordinates. * @private */ _curveTo: function(args, relative) { var w, h, cp1x, cp1y, cp2x, cp2y, x, y, pts, right, left, bottom, top, i, len, relativeX = relative ? parseFloat(this._currentX) : 0, relativeY = relative ? parseFloat(this._currentY) : 0; len = args.length - 5; for(i = 0; i < len; i = i + 6) { cp1x = parseFloat(args[i]) + relativeX; cp1y = parseFloat(args[i + 1]) + relativeY; cp2x = parseFloat(args[i + 2]) + relativeX; cp2y = parseFloat(args[i + 3]) + relativeY; x = parseFloat(args[i + 4]) + relativeX; y = parseFloat(args[i + 5]) + relativeY; this._updateDrawingQueue(["bezierCurveTo", cp1x, cp1y, cp2x, cp2y, x, y]); this._drawingComplete = false; right = Math.max(x, Math.max(cp1x, cp2x)); bottom = Math.max(y, Math.max(cp1y, cp2y)); left = Math.min(x, Math.min(cp1x, cp2x)); top = Math.min(y, Math.min(cp1y, cp2y)); w = Math.abs(right - left); h = Math.abs(bottom - top); pts = [[this._currentX, this._currentY] , [cp1x, cp1y], [cp2x, cp2y], [x, y]]; this._setCurveBoundingBox(pts, w, h); this._currentX = x; this._currentY = y; } }, /** * Draws a quadratic bezier curve. * * @method quadraticCurveTo * @param {Number} cpx x-coordinate for the control point. * @param {Number} cpy y-coordinate for the control point. * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ quadraticCurveTo: function() { this._quadraticCurveTo.apply(this, [Y.Array(arguments), false]); return this; }, /** * Draws a quadratic bezier curve relative to the current position. * * @method relativeQuadraticCurveTo * @param {Number} cpx x-coordinate for the control point. * @param {Number} cpy y-coordinate for the control point. * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ relativeQuadraticCurveTo: function() { this._quadraticCurveTo.apply(this, [Y.Array(arguments), true]); return this; }, /** * Implements quadraticCurveTo methods. * * @method _quadraticCurveTo * @param {Array} args The arguments to be used. * @param {Boolean} relative Indicates whether or not to use relative coordinates. * @private */ _quadraticCurveTo: function(args, relative) { var cpx, cpy, x, y, w, h, pts, right, left, bottom, top, i, len = args.length - 3, relativeX = relative ? parseFloat(this._currentX) : 0, relativeY = relative ? parseFloat(this._currentY) : 0; for(i = 0; i < len; i = i + 4) { cpx = parseFloat(args[i]) + relativeX; cpy = parseFloat(args[i + 1]) + relativeY; x = parseFloat(args[i + 2]) + relativeX; y = parseFloat(args[i + 3]) + relativeY; this._drawingComplete = false; right = Math.max(x, cpx); bottom = Math.max(y, cpy); left = Math.min(x, cpx); top = Math.min(y, cpy); w = Math.abs(right - left); h = Math.abs(bottom - top); pts = [[this._currentX, this._currentY] , [cpx, cpy], [x, y]]; this._setCurveBoundingBox(pts, w, h); this._updateDrawingQueue(["quadraticCurveTo", cpx, cpy, x, y]); this._updateCoords(x, y); } return this; }, /** * Draws a circle. Used internally by `CanvasCircle` class. * * @method drawCircle * @param {Number} x y-coordinate * @param {Number} y x-coordinate * @param {Number} r radius * @chainable * @protected */ drawCircle: function(x, y, radius) { var startAngle = 0, endAngle = 2 * Math.PI, wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, circum = radius * 2; circum += wt; this._drawingComplete = false; this._trackSize(x + circum, y + circum); this._trackSize(x - wt, y - wt); this._updateCoords(x, y); this._updateDrawingQueue(["arc", x + radius, y + radius, radius, startAngle, endAngle, false]); return this; }, /** * Draws a diamond. * * @method drawDiamond * @param {Number} x y-coordinate * @param {Number} y x-coordinate * @param {Number} width width * @param {Number} height height * @chainable * @protected */ drawDiamond: function(x, y, width, height) { var midWidth = width * 0.5, midHeight = height * 0.5; this.moveTo(x + midWidth, y); this.lineTo(x + width, y + midHeight); this.lineTo(x + midWidth, y + height); this.lineTo(x, y + midHeight); this.lineTo(x + midWidth, y); return this; }, /** * Draws an ellipse. Used internally by `CanvasEllipse` class. * * @method drawEllipse * @param {Number} x x-coordinate * @param {Number} y y-coordinate * @param {Number} w width * @param {Number} h height * @chainable * @protected */ drawEllipse: function(x, y, w, h) { var l = 8, theta = -(45/180) * Math.PI, angle = 0, angleMid, radius = w/2, yRadius = h/2, i, centerX = x + radius, centerY = y + yRadius, ax, ay, bx, by, cx, cy, wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0; ax = centerX + Math.cos(0) * radius; ay = centerY + Math.sin(0) * yRadius; this.moveTo(ax, ay); for(i = 0; i < l; i++) { angle += theta; angleMid = angle - (theta / 2); bx = centerX + Math.cos(angle) * radius; by = centerY + Math.sin(angle) * yRadius; cx = centerX + Math.cos(angleMid) * (radius / Math.cos(theta / 2)); cy = centerY + Math.sin(angleMid) * (yRadius / Math.cos(theta / 2)); this._updateDrawingQueue(["quadraticCurveTo", cx, cy, bx, by]); } this._trackSize(x + w + wt, y + h + wt); this._trackSize(x - wt, y - wt); this._updateCoords(x, y); return this; }, /** * Draws a rectangle. * * @method drawRect * @param {Number} x x-coordinate * @param {Number} y y-coordinate * @param {Number} w width * @param {Number} h height * @chainable */ drawRect: function(x, y, w, h) { this._drawingComplete = false; this.moveTo(x, y); this.lineTo(x + w, y); this.lineTo(x + w, y + h); this.lineTo(x, y + h); this.lineTo(x, y); return this; }, /** * Draws a rectangle with rounded corners. * * @method drawRect * @param {Number} x x-coordinate * @param {Number} y y-coordinate * @param {Number} w width * @param {Number} h height * @param {Number} ew width of the ellipse used to draw the rounded corners * @param {Number} eh height of the ellipse used to draw the rounded corners * @chainable */ drawRoundRect: function(x, y, w, h, ew, eh) { this._drawingComplete = false; this.moveTo( x, y + eh); this.lineTo(x, y + h - eh); this.quadraticCurveTo(x, y + h, x + ew, y + h); this.lineTo(x + w - ew, y + h); this.quadraticCurveTo(x + w, y + h, x + w, y + h - eh); this.lineTo(x + w, y + eh); this.quadraticCurveTo(x + w, y, x + w - ew, y); this.lineTo(x + ew, y); this.quadraticCurveTo(x, y, x, y + eh); return this; }, /** * Draws a wedge. * * @method drawWedge * @param {Number} x x-coordinate of the wedge's center point * @param {Number} y y-coordinate of the wedge's center point * @param {Number} startAngle starting angle in degrees * @param {Number} arc sweep of the wedge. Negative values draw clockwise. * @param {Number} radius radius of wedge. If [optional] yRadius is defined, then radius is the x radius. * @param {Number} yRadius [optional] y radius for wedge. * @chainable * @private */ drawWedge: function(x, y, startAngle, arc, radius, yRadius) { var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, segs, segAngle, theta, angle, angleMid, ax, ay, bx, by, cx, cy, i = 0; yRadius = yRadius || radius; this._drawingComplete = false; // move to x,y position this._updateDrawingQueue(["moveTo", x, y]); yRadius = yRadius || radius; // limit sweep to reasonable numbers if(Math.abs(arc) > 360) { arc = 360; } // First we calculate how many segments are needed // for a smooth arc. segs = Math.ceil(Math.abs(arc) / 45); // Now calculate the sweep of each segment. segAngle = arc / segs; // The math requires radians rather than degrees. To convert from degrees // use the formula (degrees/180)*Math.PI to get radians. theta = -(segAngle / 180) * Math.PI; // convert angle startAngle to radians angle = (startAngle / 180) * Math.PI; // draw the curve in segments no larger than 45 degrees. if(segs > 0) { // draw a line from the center to the start of the curve ax = x + Math.cos(startAngle / 180 * Math.PI) * radius; ay = y + Math.sin(startAngle / 180 * Math.PI) * yRadius; this.lineTo(ax, ay); // Loop for drawing curve segments for(i = 0; i < segs; ++i) { angle += theta; angleMid = angle - (theta / 2); bx = x + Math.cos(angle) * radius; by = y + Math.sin(angle) * yRadius; cx = x + Math.cos(angleMid) * (radius / Math.cos(theta / 2)); cy = y + Math.sin(angleMid) * (yRadius / Math.cos(theta / 2)); this._updateDrawingQueue(["quadraticCurveTo", cx, cy, bx, by]); } // close the wedge by drawing a line to the center this._updateDrawingQueue(["lineTo", x, y]); } this._trackSize(-wt , -wt); this._trackSize((radius * 2) + wt, (radius * 2) + wt); return this; }, /** * Completes a drawing operation. * * @method end * @chainable */ end: function() { this._closePath(); return this; }, /** * Ends a fill and stroke * * @method closePath * @chainable */ closePath: function() { this._updateDrawingQueue(["closePath"]); this._updateDrawingQueue(["beginPath"]); return this; }, /** * Clears the graphics object. * * @method clear * @chainable */ clear: function() { this._initProps(); if(this.node) { this._context.clearRect(0, 0, this.node.width, this.node.height); } return this; }, /** * Returns a linear gradient fill * * @method _getLinearGradient * @return CanvasGradient * @private */ _getLinearGradient: function() { var isNumber = Y.Lang.isNumber, fill = this.get("fill"), stops = fill.stops, opacity, color, stop, i, len = stops.length, gradient, x = 0, y = 0, w = this.get("width"), h = this.get("height"), r = fill.rotation || 0, x1, x2, y1, y2, cx = x + w/2, cy = y + h/2, offset, radCon = Math.PI/180, tanRadians = parseFloat(parseFloat(Math.tan(r * radCon)).toFixed(8)); if(Math.abs(tanRadians) * w/2 >= h/2) { if(r < 180) { y1 = y; y2 = y + h; } else { y1 = y + h; y2 = y; } x1 = cx - ((cy - y1)/tanRadians); x2 = cx - ((cy - y2)/tanRadians); } else { if(r > 90 && r < 270) { x1 = x + w; x2 = x; } else { x1 = x; x2 = x + w; } y1 = ((tanRadians * (cx - x1)) - cy) * -1; y2 = ((tanRadians * (cx - x2)) - cy) * -1; } gradient = this._context.createLinearGradient(x1, y1, x2, y2); for(i = 0; i < len; ++i) { stop = stops[i]; opacity = stop.opacity; color = stop.color; offset = stop.offset; if(isNumber(opacity)) { opacity = Math.max(0, Math.min(1, opacity)); color = this._toRGBA(color, opacity); } else { color = TORGB(color); } offset = stop.offset || i/(len - 1); gradient.addColorStop(offset, color); } return gradient; }, /** * Returns a radial gradient fill * * @method _getRadialGradient * @return CanvasGradient * @private */ _getRadialGradient: function() { var isNumber = Y.Lang.isNumber, fill = this.get("fill"), r = fill.r, fx = fill.fx, fy = fill.fy, stops = fill.stops, opacity, color, stop, i, len = stops.length, gradient, x = 0, y = 0, w = this.get("width"), h = this.get("height"), x1, x2, y1, y2, r2, xc, yc, xn, yn, d, offset, ratio, stopMultiplier; xc = x + w/2; yc = y + h/2; x1 = w * fx; y1 = h * fy; x2 = x + w/2; y2 = y + h/2; r2 = w * r; d = Math.sqrt( Math.pow(Math.abs(xc - x1), 2) + Math.pow(Math.abs(yc - y1), 2) ); if(d >= r2) { ratio = d/r2; //hack. gradient won't show if it is exactly on the edge of the arc if(ratio === 1) { ratio = 1.01; } xn = (x1 - xc)/ratio; yn = (y1 - yc)/ratio; xn = xn > 0 ? Math.floor(xn) : Math.ceil(xn); yn = yn > 0 ? Math.floor(yn) : Math.ceil(yn); x1 = xc + xn; y1 = yc + yn; } //If the gradient radius is greater than the circle's, adjusting the radius stretches the gradient properly. //If the gradient radius is less than the circle's, adjusting the radius of the gradient will not work. //Instead, adjust the color stops to reflect the smaller radius. if(r >= 0.5) { gradient = this._context.createRadialGradient(x1, y1, r, x2, y2, r * w); stopMultiplier = 1; } else { gradient = this._context.createRadialGradient(x1, y1, r, x2, y2, w/2); stopMultiplier = r * 2; } for(i = 0; i < len; ++i) { stop = stops[i]; opacity = stop.opacity; color = stop.color; offset = stop.offset; if(isNumber(opacity)) { opacity = Math.max(0, Math.min(1, opacity)); color = this._toRGBA(color, opacity); } else { color = TORGB(color); } offset = stop.offset || i/(len - 1); offset *= stopMultiplier; if(offset <= 1) { gradient.addColorStop(offset, color); } } return gradient; }, /** * Clears all values * * @method _initProps * @private */ _initProps: function() { this._methods = []; this._lineToMethods = []; this._xcoords = [0]; this._ycoords = [0]; this._width = 0; this._height = 0; this._left = 0; this._top = 0; this._right = 0; this._bottom = 0; this._currentX = 0; this._currentY = 0; }, /** * Indicates a drawing has completed. * * @property _drawingComplete * @type Boolean * @private */ _drawingComplete: false, /** * Creates canvas element * * @method _createGraphic * @return HTMLCanvasElement * @private */ _createGraphic: function() { var graphic = Y.config.doc.createElement('canvas'); return graphic; }, /** * Returns the points on a curve * * @method getBezierData * @param Array points Array containing the begin, end and control points of a curve. * @param Number t The value for incrementing the next set of points. * @return Array * @private */ getBezierData: function(points, t) { var n = points.length, tmp = [], i, j; for (i = 0; i < n; ++i){ tmp[i] = [points[i][0], points[i][1]]; // save input } for (j = 1; j < n; ++j) { for (i = 0; i < n - j; ++i) { tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; } } return [ tmp[0][0], tmp[0][1] ]; }, /** * Calculates the bounding box for a curve * * @method _setCurveBoundingBox * @param Array pts Array containing points for start, end and control points of a curve. * @param Number w Width used to calculate the number of points to describe the curve. * @param Number h Height used to calculate the number of points to describe the curve. * @private */ _setCurveBoundingBox: function(pts, w, h) { var i = 0, left = this._currentX, right = left, top = this._currentY, bottom = top, len = Math.round(Math.sqrt((w * w) + (h * h))), t = 1/len, wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, xy; for(i = 0; i < len; ++i) { xy = this.getBezierData(pts, t * i); left = isNaN(left) ? xy[0] : Math.min(xy[0], left); right = isNaN(right) ? xy[0] : Math.max(xy[0], right); top = isNaN(top) ? xy[1] : Math.min(xy[1], top); bottom = isNaN(bottom) ? xy[1] : Math.max(xy[1], bottom); } left = Math.round(left * 10)/10; right = Math.round(right * 10)/10; top = Math.round(top * 10)/10; bottom = Math.round(bottom * 10)/10; this._trackSize(right + wt, bottom + wt); this._trackSize(left - wt, top - wt); }, /** * Updates the size of the graphics object * * @method _trackSize * @param {Number} w width * @param {Number} h height * @private */ _trackSize: function(w, h) { if (w > this._right) { this._right = w; } if(w < this._left) { this._left = w; } if (h < this._top) { this._top = h; } if (h > this._bottom) { this._bottom = h; } this._width = this._right - this._left; this._height = this._bottom - this._top; } }; Y.CanvasDrawing = CanvasDrawing; /** * Canvas implementation of the `Shape` class. * `CanvasShape` is not intended to be used directly. Instead, use the `Shape` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Shape` * class will point to the `CanvasShape` class. * * @module graphics * @class CanvasShape * @constructor */ CanvasShape = function() { this._transforms = []; this.matrix = new Y.Matrix(); CanvasShape.superclass.constructor.apply(this, arguments); }; CanvasShape.NAME = "shape"; Y.extend(CanvasShape, Y.GraphicBase, Y.mix({ /** * Init method, invoked during construction. * Calls `initializer` method. * * @method init * @protected */ init: function() { this.initializer.apply(this, arguments); }, /** * Initializes the shape * * @private * @method _initialize */ initializer: function(cfg) { var host = this, graphic = cfg.graphic, data = this.get("data"); host._initProps(); host.createNode(); host._xcoords = [0]; host._ycoords = [0]; if(graphic) { this._setGraphic(graphic); } if(data) { host._parsePathData(data); } host._updateHandler(); }, /** * Set the Graphic instance for the shape. * * @method _setGraphic * @param {Graphic | Node | HTMLElement | String} render This param is used to determine the graphic instance. If it is a * `Graphic` instance, it will be assigned to the `graphic` attribute. Otherwise, a new Graphic instance will be created * and rendered into the dom element that the render represents. * @private */ _setGraphic: function(render) { var graphic; if(render instanceof Y.CanvasGraphic) { this._graphic = render; } else { graphic = new Y.CanvasGraphic({ render: render }); graphic._appendShape(this); this._graphic = graphic; } }, /** * Add a class name to each node. * * @method addClass * @param {String} className the class name to add to the node's class attribute */ addClass: function(className) { var node = this.get("node"); Y.DOM.addClass(node, className); }, /** * Removes a class name from each node. * * @method removeClass * @param {String} className the class name to remove from the node's class attribute */ removeClass: function(className) { var node = this.get("node"); Y.DOM.removeClass(node, className); }, /** * Gets the current position of the node in page coordinates. * * @method getXY * @return Array The XY position of the shape. */ getXY: function() { var graphic = this.get("graphic"), parentXY = graphic.getXY(), x = this.get("x"), y = this.get("y"); return [parentXY[0] + x, parentXY[1] + y]; }, /** * Set the position of the shape in page coordinates, regardless of how the node is positioned. * * @method setXY * @param {Array} Contains X & Y values for new position (coordinates are page-based) */ setXY: function(xy) { var graphic = this.get("graphic"), parentXY = graphic.getXY(), x = xy[0] - parentXY[0], y = xy[1] - parentXY[1]; this._set("x", x); this._set("y", y); this._updateNodePosition(x, y); }, /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * * @method contains * @param {CanvasShape | HTMLElement} needle The possible node or descendent * @return Boolean Whether or not this shape is the needle or its ancestor. */ contains: function(needle) { var node = needle instanceof Y.Node ? needle._node : needle; return node === this.node; }, /** * Test if the supplied node matches the supplied selector. * * @method test * @param {String} selector The CSS selector to test against. * @return Boolean Wheter or not the shape matches the selector. */ test: function(selector) { return Y.Selector.test(this.node, selector); }, /** * 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; return node === refNode; }, /** * Value function for fill attribute * * @method _getDefaultFill * @return Object * @private */ _getDefaultFill: function() { return { type: "solid", opacity: 1, cx: 0.5, cy: 0.5, fx: 0.5, fy: 0.5, r: 0.5 }; }, /** * Value function for stroke attribute * * @method _getDefaultStroke * @return Object * @private */ _getDefaultStroke: function() { return { weight: 1, dashstyle: "none", color: "#000", opacity: 1.0 }; }, /** * Left edge of the path * * @property _left * @type Number * @private */ _left: 0, /** * Right edge of the path * * @property _right * @type Number * @private */ _right: 0, /** * Top edge of the path * * @property _top * @type Number * @private */ _top: 0, /** * Bottom edge of the path * * @property _bottom * @type Number * @private */ _bottom: 0, /** * Creates the dom node for the shape. * * @method createNode * @return HTMLElement * @private */ createNode: function() { var host = this, node = Y.config.doc.createElement('canvas'), id = host.get("id"), concat = host._camelCaseConcat, name = host.name; host._context = node.getContext('2d'); node.setAttribute("overflow", "visible"); node.style.overflow = "visible"; if(!host.get("visible")) { node.style.visibility = "hidden"; } node.setAttribute("id", id); id = "#" + id; host.node = node; host.addClass( _getClassName(SHAPE) + " " + _getClassName(concat(IMPLEMENTATION, SHAPE)) + " " + _getClassName(name) + " " + _getClassName(concat(IMPLEMENTATION, name)) ); }, /** * Overrides default `on` method. Checks to see if its a dom interaction event. If so, * return an event attached to the `node` element. If not, return the normal functionality. * * @method on * @param {String} type event type * @param {Object} callback function * @private */ on: function(type, fn) { if(Y.Node.DOM_EVENTS[type]) { return Y.on(type, fn, "#" + this.get("id")); } return Y.on.apply(this, arguments); }, /** * Adds a stroke to the shape node. * * @method _strokeChangeHandler * @param {Object} stroke Properties of the `stroke` attribute. * @private */ _setStrokeProps: function(stroke) { var color, weight, opacity, linejoin, linecap, dashstyle; if(stroke) { color = stroke.color; weight = PARSE_FLOAT(stroke.weight); opacity = PARSE_FLOAT(stroke.opacity); linejoin = stroke.linejoin || "round"; linecap = stroke.linecap || "butt"; dashstyle = stroke.dashstyle; this._miterlimit = null; this._dashstyle = (dashstyle && Y.Lang.isArray(dashstyle) && dashstyle.length > 1) ? dashstyle : null; this._strokeWeight = weight; if (IS_NUMBER(weight) && weight > 0) { this._stroke = 1; } else { this._stroke = 0; } if (IS_NUMBER(opacity)) { this._strokeStyle = this._toRGBA(color, opacity); } else { this._strokeStyle = color; } this._linecap = linecap; if(linejoin === "round" || linejoin === "bevel") { this._linejoin = linejoin; } else { linejoin = parseInt(linejoin, 10); if(IS_NUMBER(linejoin)) { this._miterlimit = Math.max(linejoin, 1); this._linejoin = "miter"; } } } else { this._stroke = 0; } }, /** * Sets the value of an attribute. * * @method set * @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can * be passed in to set multiple attributes at once. * @param {Any} value The value to set the attribute to. This value is ignored if an object is received as * the name param. */ set: function() { var host = this; AttributeLite.prototype.set.apply(host, arguments); if(host.initialized) { host._updateHandler(); } }, /** * Adds a fill to the shape node. * * @method _setFillProps * @param {Object} fill Properties of the `fill` attribute. * @private */ _setFillProps: function(fill) { var isNumber = IS_NUMBER, color, opacity, type; if(fill) { color = fill.color; type = fill.type; if(type === "linear" || type === "radial") { this._fillType = type; } else if(color) { opacity = fill.opacity; if (isNumber(opacity)) { opacity = Math.max(0, Math.min(1, opacity)); color = this._toRGBA(color, opacity); } else { color = TORGB(color); } this._fillColor = color; this._fillType = 'solid'; } else { this._fillColor = null; } } else { this._fillType = null; this._fillColor = null; } }, /** * Specifies a 2d translation. * * @method translate * @param {Number} x The value to transate on the x-axis. * @param {Number} y The value to translate on the y-axis. */ translate: function(x, y) { this._translateX += x; this._translateY += y; this._addTransform("translate", arguments); }, /** * Translates the shape along the x-axis. When translating x and y coordinates, * use the `translate` method. * * @method translateX * @param {Number} x The value to translate. */ translateX: function(x) { this._translateX += x; this._addTransform("translateX", arguments); }, /** * Performs a translate on the y-coordinate. When translating x and y coordinates, * use the `translate` method. * * @method translateY * @param {Number} y The value to translate. */ translateY: function(y) { this._translateY += y; this._addTransform("translateY", arguments); }, /** * Skews the shape around the x-axis and y-axis. * * @method skew * @param {Number} x The value to skew on the x-axis. * @param {Number} y The value to skew on the y-axis. */ skew: function() { this._addTransform("skew", arguments); }, /** * Skews the shape around the x-axis. * * @method skewX * @param {Number} x x-coordinate */ skewX: function() { this._addTransform("skewX", arguments); }, /** * Skews the shape around the y-axis. * * @method skewY * @param {Number} y y-coordinate */ skewY: function() { this._addTransform("skewY", arguments); }, /** * Rotates the shape clockwise around it transformOrigin. * * @method rotate * @param {Number} deg The degree of the rotation. */ rotate: function() { this._addTransform("rotate", arguments); }, /** * Specifies a 2d scaling operation. * * @method scale * @param {Number} val */ scale: function() { this._addTransform("scale", arguments); }, /** * Storage for the transform attribute. * * @property _transform * @type String * @private */ _transform: "", /** * Adds a transform to the shape. * * @method _addTransform * @param {String} type The transform being applied. * @param {Array} args The arguments for the transform. * @private */ _addTransform: function(type, args) { args = Y.Array(args); this._transform = Y_LANG.trim(this._transform + " " + type + "(" + args.join(", ") + ")"); args.unshift(type); this._transforms.push(args); if(this.initialized) { this._updateTransform(); } }, /** * Applies all transforms. * * @method _updateTransform * @private */ _updateTransform: function() { var node = this.node, key, transform, transformOrigin = this.get("transformOrigin"), matrix = this.matrix, i, len = this._transforms.length; if(this._transforms && this._transforms.length > 0) { for(i = 0; i < len; ++i) { key = this._transforms[i].shift(); if(key) { matrix[key].apply(matrix, this._transforms[i]); } } transform = matrix.toCSSText(); } this._graphic.addToRedrawQueue(this); transformOrigin = (100 * transformOrigin[0]) + "% " + (100 * transformOrigin[1]) + "%"; Y_DOM.setStyle(node, "transformOrigin", transformOrigin); if(transform) { Y_DOM.setStyle(node, "transform", transform); } this._transforms = []; }, /** * Updates `Shape` based on attribute changes. * * @method _updateHandler * @private */ _updateHandler: function() { this._draw(); this._updateTransform(); }, /** * Updates the shape. * * @method _draw * @private */ _draw: function() { var node = this.node; this.clear(); this._closePath(); node.style.left = this.get("x") + "px"; node.style.top = this.get("y") + "px"; }, /** * Completes a shape or drawing * * @method _closePath * @private */ _closePath: function() { if(!this._methods) { return; } var node = this.get("node"), w = this._right - this._left, h = this._bottom - this._top, context = this._context, methods = [], cachedMethods = this._methods.concat(), i, j, method, args, argsLen, len = 0; this._context.clearRect(0, 0, node.width, node.height); if(this._methods) { len = cachedMethods.length; if(!len || len < 1) { return; } for(i = 0; i < len; ++i) { methods[i] = cachedMethods[i].concat(); args = methods[i]; argsLen = (args[0] === "quadraticCurveTo" || args[0] === "bezierCurveTo") ? args.length : 3; for(j = 1; j < argsLen; ++j) { if(j % 2 === 0) { args[j] = args[j] - this._top; } else { args[j] = args[j] - this._left; } } } node.setAttribute("width", Math.min(w, 2000)); node.setAttribute("height", Math.min(2000, h)); context.beginPath(); for(i = 0; i < len; ++i) { args = methods[i].concat(); if(args && args.length > 0) { method = args.shift(); if(method) { if(method === "closePath") { context.closePath(); this._strokeAndFill(context); } else if(method && method === "lineTo" && this._dashstyle) { args.unshift(this._xcoords[i] - this._left, this._ycoords[i] - this._top); this._drawDashedLine.apply(this, args); } else { context[method].apply(context, args); } } } } this._strokeAndFill(context); this._drawingComplete = true; this._clearAndUpdateCoords(); this._updateNodePosition(); this._methods = cachedMethods; } }, /** * Completes a stroke and/or fill operation on the context. * * @method _strokeAndFill * @param {Context} Reference to the context element of the canvas instance. * @private */ _strokeAndFill: function(context) { if (this._fillType) { if(this._fillType === "linear") { context.fillStyle = this._getLinearGradient(); } else if(this._fillType === "radial") { context.fillStyle = this._getRadialGradient(); } else { context.fillStyle = this._fillColor; } context.closePath(); context.fill(); } if (this._stroke) { if(this._strokeWeight) { context.lineWidth = this._strokeWeight; } context.lineCap = this._linecap; context.lineJoin = this._linejoin; if(this._miterlimit) { context.miterLimit = this._miterlimit; } context.strokeStyle = this._strokeStyle; context.stroke(); } }, /** * Draws a dashed line between two points. * * @method _drawDashedLine * @param {Number} xStart The x position of the start of the line * @param {Number} yStart The y position of the start of the line * @param {Number} xEnd The x position of the end of the line * @param {Number} yEnd The y position of the end of the line * @private */ _drawDashedLine: function(xStart, yStart, xEnd, yEnd) { var context = this._context, dashsize = this._dashstyle[0], gapsize = this._dashstyle[1], segmentLength = dashsize + gapsize, xDelta = xEnd - xStart, yDelta = yEnd - yStart, delta = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2)), segmentCount = Math.floor(Math.abs(delta / segmentLength)), radians = Math.atan2(yDelta, xDelta), xCurrent = xStart, yCurrent = yStart, i; xDelta = Math.cos(radians) * segmentLength; yDelta = Math.sin(radians) * segmentLength; for(i = 0; i < segmentCount; ++i) { context.moveTo(xCurrent, yCurrent); context.lineTo(xCurrent + Math.cos(radians) * dashsize, yCurrent + Math.sin(radians) * dashsize); xCurrent += xDelta; yCurrent += yDelta; } context.moveTo(xCurrent, yCurrent); delta = Math.sqrt((xEnd - xCurrent) * (xEnd - xCurrent) + (yEnd - yCurrent) * (yEnd - yCurrent)); if(delta > dashsize) { context.lineTo(xCurrent + Math.cos(radians) * dashsize, yCurrent + Math.sin(radians) * dashsize); } else if(delta > 0) { context.lineTo(xCurrent + Math.cos(radians) * delta, yCurrent + Math.sin(radians) * delta); } context.moveTo(xEnd, yEnd); }, /** * Returns the bounds for a shape. * * Calculates the a new bounding box from the original corner coordinates (base on size and position) and the transform matrix. * The calculated bounding box is used by the graphic instance to calculate its viewBox. * * @method getBounds * @return Object */ getBounds: function() { var type = this._type, w = this.get("width"), h = this.get("height"), x = this.get("x"), y = this.get("y"); if(type === "path") { x = x + this._left; y = y + this._top; w = this._right - this._left; h = this._bottom - this._top; } return this._getContentRect(w, h, x, y); }, /** * Calculates the bounding box for the shape. * * @method _getContentRect * @param {Number} w width of the shape * @param {Number} h height of the shape * @param {Number} x x-coordinate of the shape * @param {Number} y y-coordinate of the shape * @private */ _getContentRect: function(w, h, x, y) { var transformOrigin = this.get("transformOrigin"), transformX = transformOrigin[0] * w, transformY = transformOrigin[1] * h, transforms = this.matrix.getTransformArray(this.get("transform")), matrix = new Y.Matrix(), i, len = transforms.length, transform, key, contentRect; if(this._type === "path") { transformX = transformX + x; transformY = transformY + y; } transformX = !isNaN(transformX) ? transformX : 0; transformY = !isNaN(transformY) ? transformY : 0; matrix.translate(transformX, transformY); for(i = 0; i < len; i = i + 1) { transform = transforms[i]; key = transform.shift(); if(key) { matrix[key].apply(matrix, transform); } } matrix.translate(-transformX, -transformY); contentRect = matrix.getContentRect(w, h, x, y); return contentRect; }, /** * Places the shape above all other shapes. * * @method toFront */ toFront: function() { var graphic = this.get("graphic"); if(graphic) { graphic._toFront(this); } }, /** * Places the shape underneath all other shapes. * * @method toFront */ toBack: function() { var graphic = this.get("graphic"); if(graphic) { graphic._toBack(this); } }, /** * Parses path data string and call mapped methods. * * @method _parsePathData * @param {String} val The path data * @private */ _parsePathData: function(val) { var method, methodSymbol, args, commandArray = Y.Lang.trim(val.match(SPLITPATHPATTERN)), i, len, str, symbolToMethod = this._pathSymbolToMethod; if(commandArray) { this.clear(); len = commandArray.length || 0; for(i = 0; i < len; i = i + 1) { str = commandArray[i]; methodSymbol = str.substr(0, 1); args = str.substr(1).match(SPLITARGSPATTERN); method = symbolToMethod[methodSymbol]; if(method) { if(args) { this[method].apply(this, args); } else { this[method].apply(this); } } } this.end(); } }, /** * Destroys the shape instance. * * @method destroy */ destroy: function() { var graphic = this.get("graphic"); if(graphic) { graphic.removeShape(this); } else { this._destroy(); } }, /** * Implementation for shape destruction * * @method destroy * @protected */ _destroy: function() { if(this.node) { Y.Event.purgeElement(this.node, true); if(this.node.parentNode) { this.node.style.visibility = ""; this.node.parentNode.removeChild(this.node); } this._context = null; this.node = null; } } }, Y.CanvasDrawing.prototype)); CanvasShape.ATTRS = { /** * An array of x, y values which indicates the transformOrigin in which to rotate the shape. Valid values range between 0 and 1 representing a * fraction of the shape's corresponding bounding box dimension. The default value is [0.5, 0.5]. * * @config transformOrigin * @type Array */ transformOrigin: { valueFn: function() { return [0.5, 0.5]; } }, /** *

A string containing, in order, transform operations applied to the shape instance. The `transform` string can contain the following values: * *

*
rotate
Rotates the shape clockwise around it transformOrigin.
*
translate
Specifies a 2d translation.
*
skew
Skews the shape around the x-axis and y-axis.
*
scale
Specifies a 2d scaling operation.
*
translateX
Translates the shape along the x-axis.
*
translateY
Translates the shape along the y-axis.
*
skewX
Skews the shape around the x-axis.
*
skewY
Skews the shape around the y-axis.
*
matrix
Specifies a 2D transformation matrix comprised of the specified six values.
*
*

*

Applying transforms through the transform attribute will reset the transform matrix and apply a new transform. The shape class also contains * corresponding methods for each transform that will apply the transform to the current matrix. The below code illustrates how you might use the * `transform` attribute to instantiate a recangle with a rotation of 45 degrees.

var myRect = new Y.Rect({ type:"rect", width: 50, height: 40, transform: "rotate(45)" }; *

The code below would apply `translate` and `rotate` to an existing shape.

myRect.set("transform", "translate(40, 50) rotate(45)"); * @config transform * @type String */ transform: { setter: function(val) { this.matrix.init(); this._transforms = this.matrix.getTransformArray(val); this._transform = val; return val; }, getter: function() { return this._transform; } }, /** * Dom node for the shape * * @config node * @type HTMLElement * @readOnly */ node: { readOnly: true, getter: function() { return this.node; } }, /** * Unique id for class instance. * * @config id * @type String */ id: { valueFn: function() { return Y.guid(); }, setter: function(val) { var node = this.node; if(node) { node.setAttribute("id", val); } return val; } }, /** * Indicates the width of the shape * * @config width * @type Number */ width: { value: 0 }, /** * Indicates the height of the shape * * @config height * @type Number */ height: { value: 0 }, /** * Indicates the x position of shape. * * @config x * @type Number */ x: { value: 0 }, /** * Indicates the y position of shape. * * @config y * @type Number */ y: { value: 0 }, /** * Indicates whether the shape is visible. * * @config visible * @type Boolean */ visible: { value: true, setter: function(val){ var node = this.get("node"), visibility = val ? "visible" : "hidden"; if(node) { node.style.visibility = visibility; } return val; } }, /** * Contains information about the fill of the shape. *
*
color
The color of the fill.
*
opacity
Number between 0 and 1 that indicates the opacity of the fill. The default value is 1.
*
type
Type of fill. *
*
solid
Solid single color fill. (default)
*
linear
Linear gradient fill.
*
radial
Radial gradient fill.
*
*
*
*

If a `linear` or `radial` is specified as the fill type. The following additional property is used: *

*
stops
An array of objects containing the following properties: *
*
color
The color of the stop.
*
opacity
Number between 0 and 1 that indicates the opacity of the stop. The default value is 1. * Note: No effect for IE 6 - 8
*
offset
Number between 0 and 1 indicating where the color stop is positioned.
*
*
*

Linear gradients also have the following property:

*
rotation
Linear gradients flow left to right by default. The rotation property allows you to change the * flow by rotation. (e.g. A rotation of 180 would make the gradient pain from right to left.)
*

Radial gradients have the following additional properties:

*
r
Radius of the gradient circle.
*
fx
Focal point x-coordinate of the gradient.
*
fy
Focal point y-coordinate of the gradient.
*
*

The corresponding `SVGShape` class implements the following additional properties.

*
*
cx
*

The x-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.

*

Note: Currently, this property is not implemented for corresponding `CanvasShape` and * `VMLShape` classes which are used on Android or IE 6 - 8.

*
*
cy
*

The y-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.

*

Note: Currently, this property is not implemented for corresponding `CanvasShape` and `VMLShape` * classes which are used on Android or IE 6 - 8.

*
*
*

These properties are not currently implemented in `CanvasShape` or `VMLShape`.

* * @config fill * @type Object */ fill: { valueFn: "_getDefaultFill", setter: function(val) { var fill, tmpl = this.get("fill") || this._getDefaultFill(); fill = (val) ? Y.merge(tmpl, val) : null; if(fill && fill.color) { if(fill.color === undefined || fill.color === "none") { fill.color = null; } } this._setFillProps(fill); return fill; } }, /** * Contains information about the stroke of the shape. *
*
color
The color of the stroke.
*
weight
Number that indicates the width of the stroke.
*
opacity
Number between 0 and 1 that indicates the opacity of the stroke. The default value is 1.
*
dashstyle
Indicates whether to draw a dashed stroke. When set to "none", a solid stroke is drawn. When set * to an array, the first index indicates the length of the dash. The second index indicates the length of gap. *
linecap
Specifies the linecap for the stroke. The following values can be specified: *
*
butt (default)
Specifies a butt linecap.
*
square
Specifies a sqare linecap.
*
round
Specifies a round linecap.
*
*
*
linejoin
Specifies a linejoin for the stroke. The following values can be specified: *
*
round (default)
Specifies that the linejoin will be round.
*
bevel
Specifies a bevel for the linejoin.
*
miter limit
An integer specifying the miter limit of a miter linejoin. If you want to specify a linejoin * of miter, you simply specify the limit as opposed to having separate miter and miter limit values.
*
*
*
* * @config stroke * @type Object */ stroke: { valueFn: "_getDefaultStroke", setter: function(val) { var tmpl = this.get("stroke") || this._getDefaultStroke(), wt; if(val && val.hasOwnProperty("weight")) { wt = parseInt(val.weight, 10); if(!isNaN(wt)) { val.weight = wt; } } val = (val) ? Y.merge(tmpl, val) : null; this._setStrokeProps(val); return val; } }, //Not used. Remove in future. autoSize: { value: false }, // Only implemented in SVG // Determines whether the instance will receive mouse events. // // @config pointerEvents // @type string // pointerEvents: { value: "visiblePainted" }, /** * Represents an SVG Path string. This will be parsed and added to shape's API to represent the SVG data across all * implementations. Note that when using VML or SVG implementations, part of this content will be added to the DOM using * respective VML/SVG attributes. If your content comes from an untrusted source, you will need to ensure that no * malicious code is included in that content. * * @config data * @type String */ data: { setter: function(val) { if(this.get("node")) { this._parsePathData(val); } return val; } }, /** * Reference to the container Graphic. * * @config graphic * @type Graphic */ graphic: { readOnly: true, getter: function() { return this._graphic; } } }; Y.CanvasShape = CanvasShape; /** * Canvas implementation of the `Path` class. * `CanvasPath` is not intended to be used directly. Instead, use the `Path` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Path` * class will point to the `CanvasPath` class. * * @module graphics * @class CanvasPath * @extends CanvasShape */ CanvasPath = function() { CanvasPath.superclass.constructor.apply(this, arguments); }; CanvasPath.NAME = "path"; Y.extend(CanvasPath, Y.CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "path", /** * Draws the shape. * * @method _draw * @private */ _draw: function() { this._closePath(); this._updateTransform(); }, /** * Creates the dom node for the shape. * * @method createNode * @return HTMLElement * @private */ createNode: function() { var host = this, node = Y.config.doc.createElement('canvas'), name = host.name, concat = host._camelCaseConcat, id = host.get("id"); host._context = node.getContext('2d'); node.setAttribute("overflow", "visible"); node.setAttribute("pointer-events", "none"); node.style.pointerEvents = "none"; node.style.overflow = "visible"; node.setAttribute("id", id); id = "#" + id; host.node = node; host.addClass( _getClassName(SHAPE) + " " + _getClassName(concat(IMPLEMENTATION, SHAPE)) + " " + _getClassName(name) + " " + _getClassName(concat(IMPLEMENTATION, name)) ); }, /** * Completes a drawing operation. * * @method end */ end: function() { this._draw(); return this; } }); CanvasPath.ATTRS = Y.merge(Y.CanvasShape.ATTRS, { /** * Indicates the width of the shape * * @config width * @type Number */ width: { getter: function() { var offset = this._stroke && this._strokeWeight ? (this._strokeWeight * 2) : 0; return this._width - offset; }, setter: function(val) { this._width = val; return val; } }, /** * Indicates the height of the shape * * @config height * @type Number */ height: { getter: function() { var offset = this._stroke && this._strokeWeight ? (this._strokeWeight * 2) : 0; return this._height - offset; }, setter: function(val) { this._height = val; return val; } }, /** * Indicates the path used for the node. * * @config path * @type String * @readOnly */ path: { readOnly: true, getter: function() { return this._path; } } }); Y.CanvasPath = CanvasPath; /** * Canvas implementation of the `Rect` class. * `CanvasRect` is not intended to be used directly. Instead, use the `Rect` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Rect` * class will point to the `CanvasRect` class. * * @module graphics * @class CanvasRect * @constructor */ CanvasRect = function() { CanvasRect.superclass.constructor.apply(this, arguments); }; CanvasRect.NAME = "rect"; Y.extend(CanvasRect, Y.CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "rect", /** * Draws the shape. * * @method _draw * @private */ _draw: function() { var w = this.get("width"), h = this.get("height"); this.clear(); this.drawRect(0, 0, w, h); this._closePath(); } }); CanvasRect.ATTRS = Y.CanvasShape.ATTRS; Y.CanvasRect = CanvasRect; /** * Canvas implementation of the `Ellipse` class. * `CanvasEllipse` is not intended to be used directly. Instead, use the `Ellipse` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Ellipse` * class will point to the `CanvasEllipse` class. * * @module graphics * @class CanvasEllipse * @constructor */ CanvasEllipse = function() { CanvasEllipse.superclass.constructor.apply(this, arguments); }; CanvasEllipse.NAME = "ellipse"; Y.extend(CanvasEllipse, CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "ellipse", /** * Draws the shape. * * @method _draw * @private */ _draw: function() { var w = this.get("width"), h = this.get("height"); this.clear(); this.drawEllipse(0, 0, w, h); this._closePath(); } }); CanvasEllipse.ATTRS = Y.merge(CanvasShape.ATTRS, { /** * Horizontal radius for the ellipse. * * @config xRadius * @type Number */ xRadius: { setter: function(val) { this.set("width", val * 2); }, getter: function() { var val = this.get("width"); if(val) { val *= 0.5; } return val; } }, /** * Vertical radius for the ellipse. * * @config yRadius * @type Number * @readOnly */ yRadius: { setter: function(val) { this.set("height", val * 2); }, getter: function() { var val = this.get("height"); if(val) { val *= 0.5; } return val; } } }); Y.CanvasEllipse = CanvasEllipse; /** * Canvas implementation of the `Circle` class. * `CanvasCircle` is not intended to be used directly. Instead, use the `Circle` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Circle` * class will point to the `CanvasCircle` class. * * @module graphics * @class CanvasCircle * @constructor */ CanvasCircle = function() { CanvasCircle.superclass.constructor.apply(this, arguments); }; CanvasCircle.NAME = "circle"; Y.extend(CanvasCircle, Y.CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "circle", /** * Draws the shape. * * @method _draw * @private */ _draw: function() { var radius = this.get("radius"); if(radius) { this.clear(); this.drawCircle(0, 0, radius); this._closePath(); } } }); CanvasCircle.ATTRS = Y.merge(Y.CanvasShape.ATTRS, { /** * Indicates the width of the shape * * @config width * @type Number */ width: { setter: function(val) { this.set("radius", val/2); return val; }, getter: function() { return this.get("radius") * 2; } }, /** * Indicates the height of the shape * * @config height * @type Number */ height: { setter: function(val) { this.set("radius", val/2); return val; }, getter: function() { return this.get("radius") * 2; } }, /** * Radius of the circle * * @config radius * @type Number */ radius: { lazyAdd: false } }); Y.CanvasCircle = CanvasCircle; /** * Draws pie slices * * @module graphics * @class CanvasPieSlice * @constructor */ CanvasPieSlice = function() { CanvasPieSlice.superclass.constructor.apply(this, arguments); }; CanvasPieSlice.NAME = "canvasPieSlice"; Y.extend(CanvasPieSlice, Y.CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "path", /** * Change event listener * * @private * @method _updateHandler */ _draw: function() { var x = this.get("cx"), y = this.get("cy"), startAngle = this.get("startAngle"), arc = this.get("arc"), radius = this.get("radius"); this.clear(); this._left = x; this._right = radius; this._top = y; this._bottom = radius; this.drawWedge(x, y, startAngle, arc, radius); this.end(); } }); CanvasPieSlice.ATTRS = Y.mix({ cx: { value: 0 }, cy: { value: 0 }, /** * Starting angle in relation to a circle in which to begin the pie slice drawing. * * @config startAngle * @type Number */ startAngle: { value: 0 }, /** * Arc of the slice. * * @config arc * @type Number */ arc: { value: 0 }, /** * Radius of the circle in which the pie slice is drawn * * @config radius * @type Number */ radius: { value: 0 } }, Y.CanvasShape.ATTRS); Y.CanvasPieSlice = CanvasPieSlice; /** * Canvas implementation of the `Graphic` class. * `CanvasGraphic` is not intended to be used directly. Instead, use the `Graphic` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Graphic` * class will point to the `CanvasGraphic` class. * * @module graphics * @class CanvasGraphic * @constructor */ function CanvasGraphic() { CanvasGraphic.superclass.constructor.apply(this, arguments); } CanvasGraphic.NAME = "canvasGraphic"; CanvasGraphic.ATTRS = { /** * Whether or not to render the `Graphic` automatically after to a specified parent node after init. This can be a Node * instance or a CSS selector string. * * @config render * @type Node | String */ render: {}, /** * Unique id for class instance. * * @config id * @type String */ id: { valueFn: function() { return Y.guid(); }, setter: function(val) { var node = this._node; if(node) { node.setAttribute("id", val); } return val; } }, /** * Key value pairs in which a shape instance is associated with its id. * * @config shapes * @type Object * @readOnly */ shapes: { readOnly: true, getter: function() { return this._shapes; } }, /** * Object containing size and coordinate data for the content of a Graphic in relation to the graphic instance's position. * * @config contentBounds * @type Object * @readOnly */ contentBounds: { readOnly: true, getter: function() { return this._contentBounds; } }, /** * The outermost html element of the Graphic instance. * * @config node * @type HTMLElement * @readOnly */ node: { readOnly: true, getter: function() { return this._node; } }, /** * Indicates the width of the `Graphic`. * * @config width * @type Number */ width: { setter: function(val) { if(this._node) { this._node.style.width = val + "px"; } return val; } }, /** * Indicates the height of the `Graphic`. * * @config height * @type Number */ height: { setter: function(val) { if(this._node) { this._node.style.height = val + "px"; } return val; } }, /** * Determines the sizing of the Graphic. * *
*
sizeContentToGraphic
The Graphic's width and height attributes are, either explicitly set through the * width and height attributes or are determined by the dimensions of the parent element. The * content contained in the Graphic will be sized to fit with in the Graphic instance's dimensions. When using this * setting, the preserveAspectRatio attribute will determine how the contents are sized.
*
sizeGraphicToContent
(Also accepts a value of true) The Graphic's width and height are determined by the * size and positioning of the content.
*
false
The Graphic's width and height attributes are, either explicitly set through the width * and height attributes or are determined by the dimensions of the parent element. The contents of the * Graphic instance are not affected by this setting.
*
* * * @config autoSize * @type Boolean | String * @default false */ autoSize: { value: false }, /** * Determines how content is sized when autoSize is set to sizeContentToGraphic. * *
*
none
Do not force uniform scaling. Scale the graphic content of the given element non-uniformly if necessary * such that the element's bounding box exactly matches the viewport rectangle.
*
xMinYMin
Force uniform scaling position along the top left of the Graphic's node.
*
xMidYMin
Force uniform scaling horizontally centered and positioned at the top of the Graphic's node.
*
xMaxYMin
Force uniform scaling positioned horizontally from the right and vertically from the top.
*
xMinYMid
Force uniform scaling positioned horizontally from the left and vertically centered. *
xMidYMid (the default)
Force uniform scaling with the content centered.
*
xMaxYMid
Force uniform scaling positioned horizontally from the right and vertically centered.
*
xMinYMax
Force uniform scaling positioned horizontally from the left and vertically from the bottom.
*
xMidYMax
Force uniform scaling horizontally centered and position vertically from the bottom.
*
xMaxYMax
Force uniform scaling positioned horizontally from the right and vertically from the bottom.
*
* * @config preserveAspectRatio * @type String * @default xMidYMid */ preserveAspectRatio: { value: "xMidYMid" }, /** * The contentBounds will resize to greater values but not smaller values. (for performance) * When resizing the contentBounds down is desirable, set the resizeDown value to true. * * @config resizeDown * @type Boolean */ resizeDown: { value: false }, /** * Indicates the x-coordinate for the instance. * * @config x * @type Number */ x: { getter: function() { return this._x; }, setter: function(val) { this._x = val; if(this._node) { this._node.style.left = val + "px"; } return val; } }, /** * Indicates the y-coordinate for the instance. * * @config y * @type Number */ y: { getter: function() { return this._y; }, setter: function(val) { this._y = val; if(this._node) { this._node.style.top = val + "px"; } return val; } }, /** * Indicates whether or not the instance will automatically redraw after a change is made to a shape. * This property will get set to false when batching operations. * * @config autoDraw * @type Boolean * @default true * @private */ autoDraw: { value: true }, /** * Indicates whether the `Graphic` and its children are visible. * * @config visible * @type Boolean */ visible: { value: true, setter: function(val) { this._toggleVisible(val); return val; } } }; Y.extend(CanvasGraphic, Y.GraphicBase, { /** * Sets the value of an attribute. * * @method set * @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can * be passed in to set multiple attributes at once. * @param {Any} value The value to set the attribute to. This value is ignored if an object is received as * the name param. */ set: function() { var host = this, attr = arguments[0], redrawAttrs = { autoDraw: true, autoSize: true, preserveAspectRatio: true, resizeDown: true }, key, forceRedraw = false; AttributeLite.prototype.set.apply(host, arguments); if(host._state.autoDraw === true && Y.Object.size(this._shapes) > 0) { if(Y_LANG.isString && redrawAttrs[attr]) { forceRedraw = true; } else if(Y_LANG.isObject(attr)) { for(key in redrawAttrs) { if(redrawAttrs.hasOwnProperty(key) && attr[key]) { forceRedraw = true; break; } } } } if(forceRedraw) { host._redraw(); } }, /** * Storage for `x` attribute. * * @property _x * @type Number * @private */ _x: 0, /** * Storage for `y` attribute. * * @property _y * @type Number * @private */ _y: 0, /** * Gets the current position of the graphic instance in page coordinates. * * @method getXY * @return Array The XY position of the shape. */ getXY: function() { var node = this._node, xy; if(node) { xy = Y.DOM.getXY(node); } return xy; }, /** * Initializes the class. * * @method initializer * @param {Object} config Optional attributes * @private */ initializer: function() { var render = this.get("render"), visibility = this.get("visible") ? "visible" : "hidden", w = this.get("width") || 0, h = this.get("height") || 0; this._shapes = {}; this._redrawQueue = {}; this._contentBounds = { left: 0, top: 0, right: 0, bottom: 0 }; this._node = DOCUMENT.createElement('div'); this._node.style.position = "absolute"; this._node.style.visibility = visibility; this.set("width", w); this.set("height", h); if(render) { this.render(render); } }, /** * Adds the graphics node to the dom. * * @method render * @param {HTMLElement} parentNode node in which to render the graphics node into. */ render: function(render) { var parentNode = render || DOCUMENT.body, node = this._node, w, h; if(render instanceof Y.Node) { parentNode = render._node; } else if(Y.Lang.isString(render)) { parentNode = Y.Selector.query(render, DOCUMENT.body, true); } w = this.get("width") || parseInt(Y.DOM.getComputedStyle(parentNode, "width"), 10); h = this.get("height") || parseInt(Y.DOM.getComputedStyle(parentNode, "height"), 10); parentNode.appendChild(node); node.style.display = "block"; node.style.position = "absolute"; node.style.left = this.get("x") + "px"; node.style.top = this.get("y") + "px"; this.set("width", w); this.set("height", h); this.parentNode = parentNode; return this; }, /** * Removes all nodes. * * @method destroy */ destroy: function() { this.removeAllShapes(); if(this._node) { this._removeChildren(this._node); if(this._node.parentNode) { this._node.parentNode.removeChild(this._node); } this._node = null; } }, /** * Generates a shape instance by type. * * @method addShape * @param {Object} cfg attributes for the shape * @return Shape */ addShape: function(cfg) { cfg.graphic = this; if(!this.get("visible")) { cfg.visible = false; } var ShapeClass = this._getShapeClass(cfg.type), shape = new ShapeClass(cfg); this._appendShape(shape); return shape; }, /** * Adds a shape instance to the graphic instance. * * @method _appendShape * @param {Shape} shape The shape instance to be added to the graphic. * @private */ _appendShape: function(shape) { var node = shape.node, parentNode = this._frag || this._node; if(this.get("autoDraw")) { parentNode.appendChild(node); } else { this._getDocFrag().appendChild(node); } }, /** * Removes a shape instance from from the graphic instance. * * @method removeShape * @param {Shape|String} shape The instance or id of the shape to be removed. */ removeShape: function(shape) { if(!(shape instanceof CanvasShape)) { if(Y_LANG.isString(shape)) { shape = this._shapes[shape]; } } if(shape && shape instanceof CanvasShape) { shape._destroy(); delete this._shapes[shape.get("id")]; } if(this.get("autoDraw")) { this._redraw(); } return shape; }, /** * Removes all shape instances from the dom. * * @method removeAllShapes */ removeAllShapes: function() { var shapes = this._shapes, i; for(i in shapes) { if(shapes.hasOwnProperty(i)) { shapes[i].destroy(); } } this._shapes = {}; }, /** * Clears the graphics object. * * @method clear */ clear: function() { this.removeAllShapes(); }, /** * Removes all child nodes. * * @method _removeChildren * @param {HTMLElement} node * @private */ _removeChildren: function(node) { if(node && node.hasChildNodes()) { var child; while(node.firstChild) { child = node.firstChild; this._removeChildren(child); node.removeChild(child); } } }, /** * Toggles visibility * * @method _toggleVisible * @param {Boolean} val indicates visibilitye * @private */ _toggleVisible: function(val) { var i, shapes = this._shapes, visibility = val ? "visible" : "hidden"; if(shapes) { for(i in shapes) { if(shapes.hasOwnProperty(i)) { shapes[i].set("visible", val); } } } if(this._node) { this._node.style.visibility = visibility; } }, /** * Returns a shape class. Used by `addShape`. * * @method _getShapeClass * @param {Shape | String} val Indicates which shape class. * @return Function * @private */ _getShapeClass: function(val) { var shape = this._shapeClass[val]; if(shape) { return shape; } return val; }, /** * Look up for shape classes. Used by `addShape` to retrieve a class for instantiation. * * @property _shapeClass * @type Object * @private */ _shapeClass: { circle: Y.CanvasCircle, rect: Y.CanvasRect, path: Y.CanvasPath, ellipse: Y.CanvasEllipse, pieslice: Y.CanvasPieSlice }, /** * Returns a shape based on the id of its dom node. * * @method getShapeById * @param {String} id Dom id of the shape's node attribute. * @return Shape */ getShapeById: function(id) { var shape = this._shapes[id]; return shape; }, /** * Allows for creating multiple shapes in order to batch appending and redraw operations. * * @method batch * @param {Function} method Method to execute. */ batch: function(method) { var autoDraw = this.get("autoDraw"); this.set("autoDraw", false); method(); this.set("autoDraw", autoDraw); }, /** * Returns a document fragment to for attaching shapes. * * @method _getDocFrag * @return DocumentFragment * @private */ _getDocFrag: function() { if(!this._frag) { this._frag = DOCUMENT.createDocumentFragment(); } return this._frag; }, /** * Redraws all shapes. * * @method _redraw * @private */ _redraw: function() { var autoSize = this.get("autoSize"), preserveAspectRatio = this.get("preserveAspectRatio"), box = this.get("resizeDown") ? this._getUpdatedContentBounds() : this._contentBounds, contentWidth, contentHeight, w, h, xScale, yScale, translateX = 0, translateY = 0, matrix, node = this.get("node"); if(autoSize) { if(autoSize === "sizeContentToGraphic") { contentWidth = box.right - box.left; contentHeight = box.bottom - box.top; w = parseFloat(Y_DOM.getComputedStyle(node, "width")); h = parseFloat(Y_DOM.getComputedStyle(node, "height")); matrix = new Y.Matrix(); if(preserveAspectRatio === "none") { xScale = w/contentWidth; yScale = h/contentHeight; } else { if(contentWidth/contentHeight !== w/h) { if(contentWidth * h/contentHeight > w) { xScale = yScale = w/contentWidth; translateY = this._calculateTranslate(preserveAspectRatio.slice(5).toLowerCase(), contentHeight * w/contentWidth, h); } else { xScale = yScale = h/contentHeight; translateX = this._calculateTranslate(preserveAspectRatio.slice(1, 4).toLowerCase(), contentWidth * h/contentHeight, w); } } } Y_DOM.setStyle(node, "transformOrigin", "0% 0%"); translateX = translateX - (box.left * xScale); translateY = translateY - (box.top * yScale); matrix.translate(translateX, translateY); matrix.scale(xScale, yScale); Y_DOM.setStyle(node, "transform", matrix.toCSSText()); } else { this.set("width", box.right); this.set("height", box.bottom); } } if(this._frag) { this._node.appendChild(this._frag); this._frag = null; } }, /** * Determines the value for either an x or y value to be used for the translate of the Graphic. * * @method _calculateTranslate * @param {String} position The position for placement. Possible values are min, mid and max. * @param {Number} contentSize The total size of the content. * @param {Number} boundsSize The total size of the Graphic. * @return Number * @private */ _calculateTranslate: function(position, contentSize, boundsSize) { var ratio = boundsSize - contentSize, coord; switch(position) { case "mid" : coord = ratio * 0.5; break; case "max" : coord = ratio; break; default : coord = 0; break; } return coord; }, /** * Adds a shape to the redraw queue and calculates the contentBounds. Used internally * by `Shape` instances. * * @method addToRedrawQueue * @param Shape shape The shape instance to add to the queue * @protected */ addToRedrawQueue: function(shape) { var shapeBox, box; this._shapes[shape.get("id")] = shape; if(!this.get("resizeDown")) { shapeBox = shape.getBounds(); box = this._contentBounds; box.left = box.left < shapeBox.left ? box.left : shapeBox.left; box.top = box.top < shapeBox.top ? box.top : shapeBox.top; box.right = box.right > shapeBox.right ? box.right : shapeBox.right; box.bottom = box.bottom > shapeBox.bottom ? box.bottom : shapeBox.bottom; this._contentBounds = box; } if(this.get("autoDraw")) { this._redraw(); } }, /** * Recalculates and returns the `contentBounds` for the `Graphic` instance. * * @method _getUpdatedContentBounds * @return {Object} * @private */ _getUpdatedContentBounds: function() { var bounds, i, shape, queue = this._shapes, box = {}; for(i in queue) { if(queue.hasOwnProperty(i)) { shape = queue[i]; bounds = shape.getBounds(); box.left = Y_LANG.isNumber(box.left) ? Math.min(box.left, bounds.left) : bounds.left; box.top = Y_LANG.isNumber(box.top) ? Math.min(box.top, bounds.top) : bounds.top; box.right = Y_LANG.isNumber(box.right) ? Math.max(box.right, bounds.right) : bounds.right; box.bottom = Y_LANG.isNumber(box.bottom) ? Math.max(box.bottom, bounds.bottom) : bounds.bottom; } } box.left = Y_LANG.isNumber(box.left) ? box.left : 0; box.top = Y_LANG.isNumber(box.top) ? box.top : 0; box.right = Y_LANG.isNumber(box.right) ? box.right : 0; box.bottom = Y_LANG.isNumber(box.bottom) ? box.bottom : 0; this._contentBounds = box; return box; }, /** * Inserts shape on the top of the tree. * * @method _toFront * @param {CanvasShape} Shape to add. * @private */ _toFront: function(shape) { var contentNode = this.get("node"); if(shape instanceof Y.CanvasShape) { shape = shape.get("node"); } if(contentNode && shape) { contentNode.appendChild(shape); } }, /** * Inserts shape as the first child of the content node. * * @method _toBack * @param {CanvasShape} Shape to add. * @private */ _toBack: function(shape) { var contentNode = this.get("node"), targetNode; if(shape instanceof Y.CanvasShape) { shape = shape.get("node"); } if(contentNode && shape) { targetNode = contentNode.firstChild; if(targetNode) { contentNode.insertBefore(shape, targetNode); } else { contentNode.appendChild(shape); } } } }); Y.CanvasGraphic = CanvasGraphic; }, '3.18.1', {"requires": ["graphics", "color-base"]}); PK\cUb+h+h-3.18.1/graphics-canvas/graphics-canvas-min.jsnu[YUI.add("graphics-canvas",function(e,t){function T(){}function N(){N.superclass.constructor.apply(this,arguments)}var n="canvas",r="shape",i=/[a-z][^a-z]*/ig,s=/[\-]?[0-9]*[0-9|\.][0-9]*/g,o=e.config.doc,u=e.Lang,a=e.AttributeLite,f,l,c,h,p,d,v=e.DOM,m=e.Color,g=parseInt,y=parseFloat,b=u.isNumber,w=RegExp,E=m.toRGB,S=m.toHex,x=e.ClassNameManager.getClassName;T.prototype={_pathSymbolToMethod:{M:"moveTo",m:"relativeMoveTo",L:"lineTo",l:"relativeLineTo",C:"curveTo",c:"relativeCurveTo",Q:"quadraticCurveTo",q:"relativeQuadraticCurveTo",z:"closePath",Z:"closePath"},_currentX:0,_currentY:0,_toRGBA:function(e,t){return t=t!==undefined?t:1,m.re_RGB.test(e)||(e=S(e)),m.re_hex.exec(e)&&(e="rgba("+[g(w.$1,16),g(w.$2,16),g(w.$3,16)].join(",")+","+t+")"),e},_toRGB:function(e){return E(e)},setSize:function(e,t){this.get("autoSize")&&(e>this.node.getAttribute("width")&&(this.node.style.width=e+"px",this.node.setAttribute("width",e)),t>this.node.getAttribute("height")&&(this.node.style.height=t+"px",this.node.setAttribute("height",t)))},_updateCoords:function(e,t){this._xcoords.push(e),this._ycoords.push(t),this._currentX=e,this._currentY=t},_clearAndUpdateCoords:function(){var e=this._xcoords.pop()||0,t=this._ycoords.pop()||0;this._updateCoords(e,t)},_updateNodePosition:function(){var e=this.get("node"),t=this.get("x"),n=this.get("y");e.style.position="absolute",e.style.left=t+this._left+"px",e.style.top=n+this._top+"px"},_updateDrawingQueue:function(e){this._methods.push(e)},lineTo:function(){return this._lineTo.apply(this,[e.Array(arguments),!1]),this},relativeLineTo:function(){return this._lineTo.apply(this,[e.Array(arguments),!0]),this},_lineTo:function(e,t){var n=e[0],r,i,s,o,u=this._stroke&&this._strokeWeight?this._strokeWeight:0,a=t?parseFloat(this._currentX):0,f=t?parseFloat(this._currentY):0;this._lineToMethods||(this._lineToMethods=[]),i=e.length-1;if(typeof n=="string"||typeof n=="number")for(r=0;r360&&(r=360),u=Math.ceil(Math.abs(r)/45),a=r/u,f=-(a/180)*Math.PI,l=n/180*Math.PI;if(u>0){h=e+Math.cos(n/180*Math.PI)*i,p=t+Math.sin(n/180*Math.PI)*s,this.lineTo(h,p);for(y=0;y=p/2?(d<180?(g=c,y=c+p):(g=c+p,y=c),v=b-(w-g)/T,m=b-(w-y)/T):(d>90&&d<270?(v=l+h,m=l):(v=l,m=l+h),g=(T*(b-v)-w)*-1,y=(T*(b-m)-w)*-1),f=this._context.createLinearGradient(v,g,m,y);for(u=0;u=S&&(A=k/S,A===1&&(A=1.01),N=(g-x)/A,C=(b-T)/A,N=N>0?Math.floor(N):Math.ceil(N),C=C>0?Math.floor(C):Math.ceil(C),g=x+N,b=T+C),r>=.5?(h=this._context.createRadialGradient(g,b,r,y,w,r*v),O=1):(h=this._context.createRadialGradient(g,b,r,y,w,v/2),O=r*2);for(l=0;lthis._right&&(this._right=e),ethis._bottom&&(this._bottom=t),this._width=this._right-this._left,this._height=this._bottom-this._top}},e.CanvasDrawing=T,f=function(){this._transforms=[],this.matrix=new e.Matrix,f.superclass.constructor.apply(this,arguments)},f.NAME="shape",e.extend(f,e.GraphicBase,e.mix({init:function(){this.initializer.apply(this,arguments)},initializer:function(e){var t=this,n=e.graphic,r=this.get("data");t._initProps(),t.createNode(),t._xcoords=[0],t._ycoords=[0],n&&this._setGraphic(n),r&&t._parsePathData(r),t._updateHandler()},_setGraphic:function(t){var n;t instanceof e.CanvasGraphic?this._graphic=t:(n=new e.CanvasGraphic({render:t}),n._appendShape(this),this._graphic=n)},addClass:function(t){var n=this.get("node");e.DOM.addClass(n,t)},removeClass:function(t){var n=this.get("node");e.DOM.removeClass(n,t)},getXY:function(){var e=this.get("graphic"),t=e.getXY(),n=this.get("x"),r=this.get("y");return[t[0]+n,t[1]+r]},setXY:function(e){var t=this.get("graphic"),n=t.getXY(),r=e[0]-n[0],i=e[1]-n[1];this._set("x",r),this._set("y",i),this._updateNodePosition(r,i)},contains:function(t){var n=t instanceof e.Node?t._node:t;return n===this.node},test:function(t){return e.Selector.test(this.node,t)},compareTo:function(e){var t=this.node;return t===e},_getDefaultFill:function(){return{type:"solid",opacity:1,cx:.5,cy:.5,fx:.5,fy:.5,r:.5}},_getDefaultStroke:function(){return{weight:1,dashstyle:"none",color:"#000",opacity:1}},_left:0,_right:0,_top:0,_bottom:0,createNode:function(){var t=this,i=e.config.doc.createElement("canvas"),s=t.get("id"),o=t._camelCaseConcat,u=t.name;t._context=i.getContext("2d"),i.setAttribute("overflow","visible"),i.style.overflow="visible",t.get("visible")||(i.style.visibility="hidden"),i.setAttribute("id",s),s="#"+s,t.node=i,t.addClass(x(r)+" "+x(o(n,r))+" "+x(u)+" "+x(o(n,u)))},on:function(t,n){return e.Node.DOM_EVENTS[t]?e.on(t,n,"#"+this.get("id")):e.on.apply(this,arguments)},_setStrokeProps:function(t){var n,r,i,s,o,u;t?(n=t.color,r=y(t.weight),i=y(t.opacity),s=t.linejoin||"round",o=t.linecap||"butt",u=t.dashstyle,this._miterlimit=null,this._dashstyle=u&&e.Lang.isArray(u)&&u.length>1?u:null,this._strokeWeight=r,b(r)&&r>0?this._stroke=1:this._stroke=0,b(i)?this._strokeStyle=this._toRGBA(n,i):this._strokeStyle=n,this._linecap=o,s==="round"||s==="bevel"?this._linejoin=s:(s=parseInt(s,10),b(s)&&(this._miterlimit=Math.max(s,1),this._linejoin="miter"))):this._stroke=0},set:function(){var e=this;a.prototype.set.apply(e,arguments),e.initialized&&e._updateHandler()},_setFillProps:function(e){var t=b,n,r,i;e?(n=e.color,i=e.type,i==="linear"||i==="radial"?this._fillType=i:n?(r=e.opacity,t(r)?(r=Math .max(0,Math.min(1,r)),n=this._toRGBA(n,r)):n=E(n),this._fillColor=n,this._fillType="solid"):this._fillColor=null):(this._fillType=null,this._fillColor=null)},translate:function(e,t){this._translateX+=e,this._translateY+=t,this._addTransform("translate",arguments)},translateX:function(e){this._translateX+=e,this._addTransform("translateX",arguments)},translateY:function(e){this._translateY+=e,this._addTransform("translateY",arguments)},skew:function(){this._addTransform("skew",arguments)},skewX:function(){this._addTransform("skewX",arguments)},skewY:function(){this._addTransform("skewY",arguments)},rotate:function(){this._addTransform("rotate",arguments)},scale:function(){this._addTransform("scale",arguments)},_transform:"",_addTransform:function(t,n){n=e.Array(n),this._transform=u.trim(this._transform+" "+t+"("+n.join(", ")+")"),n.unshift(t),this._transforms.push(n),this.initialized&&this._updateTransform()},_updateTransform:function(){var e=this.node,t,n,r=this.get("transformOrigin"),i=this.matrix,s,o=this._transforms.length;if(this._transforms&&this._transforms.length>0){for(s=0;s0&&(a=f.shift(),a&&(a==="closePath"?(r.closePath(),this._strokeAndFill(r)):a&&a==="lineTo"&&this._dashstyle?(f.unshift(this._xcoords[o]-this._left,this._ycoords[o]-this._top),this._drawDashedLine.apply(this,f)):r[a].apply(r,f)));this._strokeAndFill(r),this._drawingComplete=!0,this._clearAndUpdateCoords(),this._updateNodePosition(),this._methods=s}},_strokeAndFill:function(e){this._fillType&&(this._fillType==="linear"?e.fillStyle=this._getLinearGradient():this._fillType==="radial"?e.fillStyle=this._getRadialGradient():e.fillStyle=this._fillColor,e.closePath(),e.fill()),this._stroke&&(this._strokeWeight&&(e.lineWidth=this._strokeWeight),e.lineCap=this._linecap,e.lineJoin=this._linejoin,this._miterlimit&&(e.miterLimit=this._miterlimit),e.strokeStyle=this._strokeStyle,e.stroke())},_drawDashedLine:function(e,t,n,r){var i=this._context,s=this._dashstyle[0],o=this._dashstyle[1],u=s+o,a=n-e,f=r-t,l=Math.sqrt(Math.pow(a,2)+Math.pow(f,2)),c=Math.floor(Math.abs(l/u)),h=Math.atan2(f,a),p=e,d=t,v;a=Math.cos(h)*u,f=Math.sin(h)*u;for(v=0;vs?i.lineTo(p+Math.cos(h)*s,d+Math.sin(h)*s):l>0&&i.lineTo(p+Math.cos(h)*l,d+Math.sin(h)*l),i.moveTo(n,r)},getBounds:function(){var e=this._type,t=this.get("width"),n=this.get("height"),r=this.get("x"),i=this.get("y");return e==="path"&&(r+=this._left,i+=this._top,t=this._right-this._left,n=this._bottom-this._top),this._getContentRect(t,n,r,i)},_getContentRect:function(t,n,r,i){var s=this.get("transformOrigin"),o=s[0]*t,u=s[1]*n,a=this.matrix.getTransformArray(this.get("transform")),f=new e.Matrix,l,c=a.length,h,p,d;this._type==="path"&&(o+=r,u+=i),o=isNaN(o)?0:o,u=isNaN(u)?0:u,f.translate(o,u);for(l=0;l0)if(u.isString&&r[n])s=!0;else if(u.isObject(n))for(i in r)if(r.hasOwnProperty(i)&&n[i]){s=!0;break}s&&t._redraw()},_x:0,_y:0,getXY:function(){var t=this._node,n;return t&&(n=e.DOM.getXY(t)),n},initializer:function(){var e=this.get("render"),t=this.get("visible")?"visible":"hidden",n=this.get("width")||0,r=this.get("height")||0;this._shapes={},this._redrawQueue={},this._contentBounds={left:0,top:0,right:0,bottom:0},this._node=o.createElement("div"),this._node.style.position="absolute",this._node.style.visibility=t,this.set("width",n),this.set("height",r),e&&this.render(e)},render:function(t){var n=t||o.body,r=this._node,i,s;return t instanceof e.Node?n=t._node:e.Lang.isString(t)&&(n=e.Selector.query(t,o.body,!0)),i=this.get("width")||parseInt(e.DOM.getComputedStyle(n,"width"),10),s=this.get("height")||parseInt(e.DOM.getComputedStyle(n,"height"),10),n.appendChild(r),r.style.display="block",r.style.position="absolute",r.style.left=this.get("x")+"px",r.style.top=this.get("y")+"px",this.set("width",i),this.set("height",s),this.parentNode=n,this},destroy:function(){this.removeAllShapes(),this._node&&(this._removeChildren(this._node),this._node.parentNode&&this._node.parentNode.removeChild(this._node),this._node=null)},addShape:function(e){e.graphic=this,this.get("visible")||(e.visible=!1);var t=this._getShapeClass(e.type),n=new t(e);return this._appendShape(n),n},_appendShape:function(e){var t=e.node,n=this._frag||this._node;this.get("autoDraw")?n.appendChild(t):this._getDocFrag().appendChild(t)},removeShape:function(e){return e instanceof f||u.isString(e)&&(e=this._shapes[e]),e&&e instanceof f&&(e._destroy(),delete this._shapes[e.get("id")]),this.get("autoDraw")&&this._redraw(),e},removeAllShapes:function(){var e=this._shapes,t;for(t in e)e.hasOwnProperty(t)&&e[t].destroy();this._shapes={}},clear:function(){this.removeAllShapes()},_removeChildren:function(e){if(e&&e.hasChildNodes()){var t;while(e.firstChild)t=e.firstChild,this._removeChildren(t),e.removeChild(t)}},_toggleVisible:function(e){var t,n=this._shapes,r=e?"visible":"hidden";if(n)for(t in n)n.hasOwnProperty(t)&& n[t].set("visible",e);this._node&&(this._node.style.visibility=r)},_getShapeClass:function(e){var t=this._shapeClass[e];return t?t:e},_shapeClass:{circle:e.CanvasCircle,rect:e.CanvasRect,path:e.CanvasPath,ellipse:e.CanvasEllipse,pieslice:e.CanvasPieSlice},getShapeById:function(e){var t=this._shapes[e];return t},batch:function(e){var t=this.get("autoDraw");this.set("autoDraw",!1),e(),this.set("autoDraw",t)},_getDocFrag:function(){return this._frag||(this._frag=o.createDocumentFragment()),this._frag},_redraw:function(){var t=this.get("autoSize"),n=this.get("preserveAspectRatio"),r=this.get("resizeDown")?this._getUpdatedContentBounds():this._contentBounds,i,s,o,u,a,f,l=0,c=0,h,p=this.get("node");t&&(t==="sizeContentToGraphic"?(i=r.right-r.left,s=r.bottom-r.top,o=parseFloat(v.getComputedStyle(p,"width")),u=parseFloat(v.getComputedStyle(p,"height")),h=new e.Matrix,n==="none"?(a=o/i,f=u/s):i/s!==o/u&&(i*u/s>o?(a=f=o/i,c=this._calculateTranslate(n.slice(5).toLowerCase(),s*o/i,u)):(a=f=u/s,l=this._calculateTranslate(n.slice(1,4).toLowerCase(),i*u/s,o))),v.setStyle(p,"transformOrigin","0% 0%"),l-=r.left*a,c-=r.top*f,h.translate(l,c),h.scale(a,f),v.setStyle(p,"transform",h.toCSSText())):(this.set("width",r.right),this.set("height",r.bottom))),this._frag&&(this._node.appendChild(this._frag),this._frag=null)},_calculateTranslate:function(e,t,n){var r=n-t,i;switch(e){case"mid":i=r*.5;break;case"max":i=r;break;default:i=0}return i},addToRedrawQueue:function(e){var t,n;this._shapes[e.get("id")]=e,this.get("resizeDown")||(t=e.getBounds(),n=this._contentBounds,n.left=n.leftt.right?n.right:t.right,n.bottom=n.bottom>t.bottom?n.bottom:t.bottom,this._contentBounds=n),this.get("autoDraw")&&this._redraw()},_getUpdatedContentBounds:function(){var e,t,n,r=this._shapes,i={};for(t in r)r.hasOwnProperty(t)&&(n=r[t],e=n.getBounds(),i.left=u.isNumber(i.left)?Math.min(i.left,e.left):e.left,i.top=u.isNumber(i.top)?Math.min(i.top,e.top):e.top,i.right=u.isNumber(i.right)?Math.max(i.right,e.right):e.right,i.bottom=u.isNumber(i.bottom)?Math.max(i.bottom,e.bottom):e.bottom);return i.left=u.isNumber(i.left)?i.left:0,i.top=u.isNumber(i.top)?i.top:0,i.right=u.isNumber(i.right)?i.right:0,i.bottom=u.isNumber(i.bottom)?i.bottom:0,this._contentBounds=i,i},_toFront:function(t){var n=this.get("node");t instanceof e.CanvasShape&&(t=t.get("node")),n&&t&&n.appendChild(t)},_toBack:function(t){var n=this.get("node"),r;t instanceof e.CanvasShape&&(t=t.get("node")),n&&t&&(r=n.firstChild,r?n.insertBefore(t,r):n.appendChild(t))}}),e.CanvasGraphic=N},"3.18.1",{requires:["graphics","color-base"]}); PK\B.(9SS/3.18.1/graphics-canvas/graphics-canvas-debug.jsnu[YUI.add('graphics-canvas', function (Y, NAME) { var IMPLEMENTATION = "canvas", SHAPE = "shape", SPLITPATHPATTERN = /[a-z][^a-z]*/ig, SPLITARGSPATTERN = /[\-]?[0-9]*[0-9|\.][0-9]*/g, DOCUMENT = Y.config.doc, Y_LANG = Y.Lang, AttributeLite = Y.AttributeLite, CanvasShape, CanvasPath, CanvasRect, CanvasEllipse, CanvasCircle, CanvasPieSlice, Y_DOM = Y.DOM, Y_Color = Y.Color, PARSE_INT = parseInt, PARSE_FLOAT = parseFloat, IS_NUMBER = Y_LANG.isNumber, RE = RegExp, TORGB = Y_Color.toRGB, TOHEX = Y_Color.toHex, _getClassName = Y.ClassNameManager.getClassName; /** * Canvas implementation of the `Drawing` class. * `CanvasDrawing` is not intended to be used directly. Instead, use the `Drawing` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Drawing` * class will point to the `CanvasDrawing` class. * * @module graphics * @class CanvasDrawing * @constructor */ function CanvasDrawing() { } CanvasDrawing.prototype = { /** * Maps path to methods * * @property _pathSymbolToMethod * @type Object * @private */ _pathSymbolToMethod: { M: "moveTo", m: "relativeMoveTo", L: "lineTo", l: "relativeLineTo", C: "curveTo", c: "relativeCurveTo", Q: "quadraticCurveTo", q: "relativeQuadraticCurveTo", z: "closePath", Z: "closePath" }, /** * Current x position of the drawing. * * @property _currentX * @type Number * @private */ _currentX: 0, /** * Current y position of the drqwing. * * @property _currentY * @type Number * @private */ _currentY: 0, /** * Parses hex color string and alpha value to rgba * * @method _toRGBA * @param {Object} val Color value to parse. Can be hex string, rgb or name. * @param {Number} alpha Numeric value between 0 and 1 representing the alpha level. * @private */ _toRGBA: function(val, alpha) { alpha = (alpha !== undefined) ? alpha : 1; if (!Y_Color.re_RGB.test(val)) { val = TOHEX(val); } if(Y_Color.re_hex.exec(val)) { val = 'rgba(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(',') + ',' + alpha + ')'; } return val; }, /** * Converts color to rgb format * * @method _toRGB * @param val Color value to convert. * @private */ _toRGB: function(val) { return TORGB(val); }, /** * Sets the size of the graphics object. * * @method setSize * @param w {Number} width to set for the instance. * @param h {Number} height to set for the instance. * @private */ setSize: function(w, h) { if(this.get("autoSize")) { if(w > this.node.getAttribute("width")) { this.node.style.width = w + "px"; this.node.setAttribute("width", w); } if(h > this.node.getAttribute("height")) { this.node.style.height = h + "px"; this.node.setAttribute("height", h); } } }, /** * Tracks coordinates. Used to calculate the start point of dashed lines. * * @method _updateCoords * @param {Number} x x-coordinate * @param {Number} y y-coordinate * @private */ _updateCoords: function(x, y) { this._xcoords.push(x); this._ycoords.push(y); this._currentX = x; this._currentY = y; }, /** * Clears the coordinate arrays. Called at the end of a drawing operation. * * @method _clearAndUpdateCoords * @private */ _clearAndUpdateCoords: function() { var x = this._xcoords.pop() || 0, y = this._ycoords.pop() || 0; this._updateCoords(x, y); }, /** * Moves the shape's dom node. * * @method _updateNodePosition * @private */ _updateNodePosition: function() { var node = this.get("node"), x = this.get("x"), y = this.get("y"); node.style.position = "absolute"; node.style.left = (x + this._left) + "px"; node.style.top = (y + this._top) + "px"; }, /** * Queues up a method to be executed when a shape redraws. * * @method _updateDrawingQueue * @param {Array} val An array containing data that can be parsed into a method and arguments. The value at zero-index * of the array is a string reference of the drawing method that will be called. All subsequent indices are argument for * that method. For example, `lineTo(10, 100)` would be structured as: * `["lineTo", 10, 100]`. * @private */ _updateDrawingQueue: function(val) { this._methods.push(val); }, /** * Draws a line segment from the current drawing position to the specified x and y coordinates. * * @method lineTo * @param {Number} point1 x-coordinate for the end point. * @param {Number} point2 y-coordinate for the end point. * @chainable */ lineTo: function() { this._lineTo.apply(this, [Y.Array(arguments), false]); return this; }, /** * Draws a line segment from the current drawing position to the relative x and y coordinates. * * @method relativeLineTo * @param {Number} point1 x-coordinate for the end point. * @param {Number} point2 y-coordinate for the end point. * @chainable */ relativeLineTo: function() { this._lineTo.apply(this, [Y.Array(arguments), true]); return this; }, /** * Implements lineTo methods. * * @method _lineTo * @param {Array} args The arguments to be used. * @param {Boolean} relative Indicates whether or not to use relative coordinates. * @private */ _lineTo: function(args, relative) { var point1 = args[0], i, len, x, y, wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, relativeX = relative ? parseFloat(this._currentX) : 0, relativeY = relative ? parseFloat(this._currentY) : 0; if(!this._lineToMethods) { this._lineToMethods = []; } len = args.length - 1; if (typeof point1 === 'string' || typeof point1 === 'number') { for (i = 0; i < len; i = i + 2) { x = parseFloat(args[i]); y = parseFloat(args[i + 1]); x = x + relativeX; y = y + relativeY; this._updateDrawingQueue(["lineTo", x, y]); this._trackSize(x - wt, y - wt); this._trackSize(x + wt, y + wt); this._updateCoords(x, y); } } else { for (i = 0; i < len; i = i + 1) { x = parseFloat(args[i][0]); y = parseFloat(args[i][1]); this._updateDrawingQueue(["lineTo", x, y]); this._lineToMethods[this._lineToMethods.length] = this._methods[this._methods.length - 1]; this._trackSize(x - wt, y - wt); this._trackSize(x + wt, y + wt); this._updateCoords(x, y); } } this._drawingComplete = false; return this; }, /** * Moves the current drawing position to specified x and y coordinates. * * @method moveTo * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ moveTo: function() { this._moveTo.apply(this, [Y.Array(arguments), false]); return this; }, /** * Moves the current drawing position relative to specified x and y coordinates. * * @method relativeMoveTo * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ relativeMoveTo: function() { this._moveTo.apply(this, [Y.Array(arguments), true]); return this; }, /** * Implements moveTo methods. * * @method _moveTo * @param {Array} args The arguments to be used. * @param {Boolean} relative Indicates whether or not to use relative coordinates. * @private */ _moveTo: function(args, relative) { var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, relativeX = relative ? parseFloat(this._currentX) : 0, relativeY = relative ? parseFloat(this._currentY) : 0, x = parseFloat(args[0]) + relativeX, y = parseFloat(args[1]) + relativeY; this._updateDrawingQueue(["moveTo", x, y]); this._trackSize(x - wt, y - wt); this._trackSize(x + wt, y + wt); this._updateCoords(x, y); this._drawingComplete = false; return this; }, /** * Draws a bezier curve. * * @method curveTo * @param {Number} cp1x x-coordinate for the first control point. * @param {Number} cp1y y-coordinate for the first control point. * @param {Number} cp2x x-coordinate for the second control point. * @param {Number} cp2y y-coordinate for the second control point. * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ curveTo: function() { this._curveTo.apply(this, [Y.Array(arguments), false]); return this; }, /** * Draws a bezier curve relative to the current coordinates. * * @method relativeCurveTo * @param {Number} cp1x x-coordinate for the first control point. * @param {Number} cp1y y-coordinate for the first control point. * @param {Number} cp2x x-coordinate for the second control point. * @param {Number} cp2y y-coordinate for the second control point. * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ relativeCurveTo: function() { this._curveTo.apply(this, [Y.Array(arguments), true]); return this; }, /** * Implements curveTo methods. * * @method _curveTo * @param {Array} args The arguments to be used. * @param {Boolean} relative Indicates whether or not to use relative coordinates. * @private */ _curveTo: function(args, relative) { var w, h, cp1x, cp1y, cp2x, cp2y, x, y, pts, right, left, bottom, top, i, len, relativeX = relative ? parseFloat(this._currentX) : 0, relativeY = relative ? parseFloat(this._currentY) : 0; len = args.length - 5; for(i = 0; i < len; i = i + 6) { cp1x = parseFloat(args[i]) + relativeX; cp1y = parseFloat(args[i + 1]) + relativeY; cp2x = parseFloat(args[i + 2]) + relativeX; cp2y = parseFloat(args[i + 3]) + relativeY; x = parseFloat(args[i + 4]) + relativeX; y = parseFloat(args[i + 5]) + relativeY; this._updateDrawingQueue(["bezierCurveTo", cp1x, cp1y, cp2x, cp2y, x, y]); this._drawingComplete = false; right = Math.max(x, Math.max(cp1x, cp2x)); bottom = Math.max(y, Math.max(cp1y, cp2y)); left = Math.min(x, Math.min(cp1x, cp2x)); top = Math.min(y, Math.min(cp1y, cp2y)); w = Math.abs(right - left); h = Math.abs(bottom - top); pts = [[this._currentX, this._currentY] , [cp1x, cp1y], [cp2x, cp2y], [x, y]]; this._setCurveBoundingBox(pts, w, h); this._currentX = x; this._currentY = y; } }, /** * Draws a quadratic bezier curve. * * @method quadraticCurveTo * @param {Number} cpx x-coordinate for the control point. * @param {Number} cpy y-coordinate for the control point. * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ quadraticCurveTo: function() { this._quadraticCurveTo.apply(this, [Y.Array(arguments), false]); return this; }, /** * Draws a quadratic bezier curve relative to the current position. * * @method relativeQuadraticCurveTo * @param {Number} cpx x-coordinate for the control point. * @param {Number} cpy y-coordinate for the control point. * @param {Number} x x-coordinate for the end point. * @param {Number} y y-coordinate for the end point. * @chainable */ relativeQuadraticCurveTo: function() { this._quadraticCurveTo.apply(this, [Y.Array(arguments), true]); return this; }, /** * Implements quadraticCurveTo methods. * * @method _quadraticCurveTo * @param {Array} args The arguments to be used. * @param {Boolean} relative Indicates whether or not to use relative coordinates. * @private */ _quadraticCurveTo: function(args, relative) { var cpx, cpy, x, y, w, h, pts, right, left, bottom, top, i, len = args.length - 3, relativeX = relative ? parseFloat(this._currentX) : 0, relativeY = relative ? parseFloat(this._currentY) : 0; for(i = 0; i < len; i = i + 4) { cpx = parseFloat(args[i]) + relativeX; cpy = parseFloat(args[i + 1]) + relativeY; x = parseFloat(args[i + 2]) + relativeX; y = parseFloat(args[i + 3]) + relativeY; this._drawingComplete = false; right = Math.max(x, cpx); bottom = Math.max(y, cpy); left = Math.min(x, cpx); top = Math.min(y, cpy); w = Math.abs(right - left); h = Math.abs(bottom - top); pts = [[this._currentX, this._currentY] , [cpx, cpy], [x, y]]; this._setCurveBoundingBox(pts, w, h); this._updateDrawingQueue(["quadraticCurveTo", cpx, cpy, x, y]); this._updateCoords(x, y); } return this; }, /** * Draws a circle. Used internally by `CanvasCircle` class. * * @method drawCircle * @param {Number} x y-coordinate * @param {Number} y x-coordinate * @param {Number} r radius * @chainable * @protected */ drawCircle: function(x, y, radius) { var startAngle = 0, endAngle = 2 * Math.PI, wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, circum = radius * 2; circum += wt; this._drawingComplete = false; this._trackSize(x + circum, y + circum); this._trackSize(x - wt, y - wt); this._updateCoords(x, y); this._updateDrawingQueue(["arc", x + radius, y + radius, radius, startAngle, endAngle, false]); return this; }, /** * Draws a diamond. * * @method drawDiamond * @param {Number} x y-coordinate * @param {Number} y x-coordinate * @param {Number} width width * @param {Number} height height * @chainable * @protected */ drawDiamond: function(x, y, width, height) { var midWidth = width * 0.5, midHeight = height * 0.5; this.moveTo(x + midWidth, y); this.lineTo(x + width, y + midHeight); this.lineTo(x + midWidth, y + height); this.lineTo(x, y + midHeight); this.lineTo(x + midWidth, y); return this; }, /** * Draws an ellipse. Used internally by `CanvasEllipse` class. * * @method drawEllipse * @param {Number} x x-coordinate * @param {Number} y y-coordinate * @param {Number} w width * @param {Number} h height * @chainable * @protected */ drawEllipse: function(x, y, w, h) { var l = 8, theta = -(45/180) * Math.PI, angle = 0, angleMid, radius = w/2, yRadius = h/2, i, centerX = x + radius, centerY = y + yRadius, ax, ay, bx, by, cx, cy, wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0; ax = centerX + Math.cos(0) * radius; ay = centerY + Math.sin(0) * yRadius; this.moveTo(ax, ay); for(i = 0; i < l; i++) { angle += theta; angleMid = angle - (theta / 2); bx = centerX + Math.cos(angle) * radius; by = centerY + Math.sin(angle) * yRadius; cx = centerX + Math.cos(angleMid) * (radius / Math.cos(theta / 2)); cy = centerY + Math.sin(angleMid) * (yRadius / Math.cos(theta / 2)); this._updateDrawingQueue(["quadraticCurveTo", cx, cy, bx, by]); } this._trackSize(x + w + wt, y + h + wt); this._trackSize(x - wt, y - wt); this._updateCoords(x, y); return this; }, /** * Draws a rectangle. * * @method drawRect * @param {Number} x x-coordinate * @param {Number} y y-coordinate * @param {Number} w width * @param {Number} h height * @chainable */ drawRect: function(x, y, w, h) { this._drawingComplete = false; this.moveTo(x, y); this.lineTo(x + w, y); this.lineTo(x + w, y + h); this.lineTo(x, y + h); this.lineTo(x, y); return this; }, /** * Draws a rectangle with rounded corners. * * @method drawRect * @param {Number} x x-coordinate * @param {Number} y y-coordinate * @param {Number} w width * @param {Number} h height * @param {Number} ew width of the ellipse used to draw the rounded corners * @param {Number} eh height of the ellipse used to draw the rounded corners * @chainable */ drawRoundRect: function(x, y, w, h, ew, eh) { this._drawingComplete = false; this.moveTo( x, y + eh); this.lineTo(x, y + h - eh); this.quadraticCurveTo(x, y + h, x + ew, y + h); this.lineTo(x + w - ew, y + h); this.quadraticCurveTo(x + w, y + h, x + w, y + h - eh); this.lineTo(x + w, y + eh); this.quadraticCurveTo(x + w, y, x + w - ew, y); this.lineTo(x + ew, y); this.quadraticCurveTo(x, y, x, y + eh); return this; }, /** * Draws a wedge. * * @method drawWedge * @param {Number} x x-coordinate of the wedge's center point * @param {Number} y y-coordinate of the wedge's center point * @param {Number} startAngle starting angle in degrees * @param {Number} arc sweep of the wedge. Negative values draw clockwise. * @param {Number} radius radius of wedge. If [optional] yRadius is defined, then radius is the x radius. * @param {Number} yRadius [optional] y radius for wedge. * @chainable * @private */ drawWedge: function(x, y, startAngle, arc, radius, yRadius) { var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, segs, segAngle, theta, angle, angleMid, ax, ay, bx, by, cx, cy, i = 0; yRadius = yRadius || radius; this._drawingComplete = false; // move to x,y position this._updateDrawingQueue(["moveTo", x, y]); yRadius = yRadius || radius; // limit sweep to reasonable numbers if(Math.abs(arc) > 360) { arc = 360; } // First we calculate how many segments are needed // for a smooth arc. segs = Math.ceil(Math.abs(arc) / 45); // Now calculate the sweep of each segment. segAngle = arc / segs; // The math requires radians rather than degrees. To convert from degrees // use the formula (degrees/180)*Math.PI to get radians. theta = -(segAngle / 180) * Math.PI; // convert angle startAngle to radians angle = (startAngle / 180) * Math.PI; // draw the curve in segments no larger than 45 degrees. if(segs > 0) { // draw a line from the center to the start of the curve ax = x + Math.cos(startAngle / 180 * Math.PI) * radius; ay = y + Math.sin(startAngle / 180 * Math.PI) * yRadius; this.lineTo(ax, ay); // Loop for drawing curve segments for(i = 0; i < segs; ++i) { angle += theta; angleMid = angle - (theta / 2); bx = x + Math.cos(angle) * radius; by = y + Math.sin(angle) * yRadius; cx = x + Math.cos(angleMid) * (radius / Math.cos(theta / 2)); cy = y + Math.sin(angleMid) * (yRadius / Math.cos(theta / 2)); this._updateDrawingQueue(["quadraticCurveTo", cx, cy, bx, by]); } // close the wedge by drawing a line to the center this._updateDrawingQueue(["lineTo", x, y]); } this._trackSize(-wt , -wt); this._trackSize((radius * 2) + wt, (radius * 2) + wt); return this; }, /** * Completes a drawing operation. * * @method end * @chainable */ end: function() { this._closePath(); return this; }, /** * Ends a fill and stroke * * @method closePath * @chainable */ closePath: function() { this._updateDrawingQueue(["closePath"]); this._updateDrawingQueue(["beginPath"]); return this; }, /** * Clears the graphics object. * * @method clear * @chainable */ clear: function() { this._initProps(); if(this.node) { this._context.clearRect(0, 0, this.node.width, this.node.height); } return this; }, /** * Returns a linear gradient fill * * @method _getLinearGradient * @return CanvasGradient * @private */ _getLinearGradient: function() { var isNumber = Y.Lang.isNumber, fill = this.get("fill"), stops = fill.stops, opacity, color, stop, i, len = stops.length, gradient, x = 0, y = 0, w = this.get("width"), h = this.get("height"), r = fill.rotation || 0, x1, x2, y1, y2, cx = x + w/2, cy = y + h/2, offset, radCon = Math.PI/180, tanRadians = parseFloat(parseFloat(Math.tan(r * radCon)).toFixed(8)); if(Math.abs(tanRadians) * w/2 >= h/2) { if(r < 180) { y1 = y; y2 = y + h; } else { y1 = y + h; y2 = y; } x1 = cx - ((cy - y1)/tanRadians); x2 = cx - ((cy - y2)/tanRadians); } else { if(r > 90 && r < 270) { x1 = x + w; x2 = x; } else { x1 = x; x2 = x + w; } y1 = ((tanRadians * (cx - x1)) - cy) * -1; y2 = ((tanRadians * (cx - x2)) - cy) * -1; } gradient = this._context.createLinearGradient(x1, y1, x2, y2); for(i = 0; i < len; ++i) { stop = stops[i]; opacity = stop.opacity; color = stop.color; offset = stop.offset; if(isNumber(opacity)) { opacity = Math.max(0, Math.min(1, opacity)); color = this._toRGBA(color, opacity); } else { color = TORGB(color); } offset = stop.offset || i/(len - 1); gradient.addColorStop(offset, color); } return gradient; }, /** * Returns a radial gradient fill * * @method _getRadialGradient * @return CanvasGradient * @private */ _getRadialGradient: function() { var isNumber = Y.Lang.isNumber, fill = this.get("fill"), r = fill.r, fx = fill.fx, fy = fill.fy, stops = fill.stops, opacity, color, stop, i, len = stops.length, gradient, x = 0, y = 0, w = this.get("width"), h = this.get("height"), x1, x2, y1, y2, r2, xc, yc, xn, yn, d, offset, ratio, stopMultiplier; xc = x + w/2; yc = y + h/2; x1 = w * fx; y1 = h * fy; x2 = x + w/2; y2 = y + h/2; r2 = w * r; d = Math.sqrt( Math.pow(Math.abs(xc - x1), 2) + Math.pow(Math.abs(yc - y1), 2) ); if(d >= r2) { ratio = d/r2; //hack. gradient won't show if it is exactly on the edge of the arc if(ratio === 1) { ratio = 1.01; } xn = (x1 - xc)/ratio; yn = (y1 - yc)/ratio; xn = xn > 0 ? Math.floor(xn) : Math.ceil(xn); yn = yn > 0 ? Math.floor(yn) : Math.ceil(yn); x1 = xc + xn; y1 = yc + yn; } //If the gradient radius is greater than the circle's, adjusting the radius stretches the gradient properly. //If the gradient radius is less than the circle's, adjusting the radius of the gradient will not work. //Instead, adjust the color stops to reflect the smaller radius. if(r >= 0.5) { gradient = this._context.createRadialGradient(x1, y1, r, x2, y2, r * w); stopMultiplier = 1; } else { gradient = this._context.createRadialGradient(x1, y1, r, x2, y2, w/2); stopMultiplier = r * 2; } for(i = 0; i < len; ++i) { stop = stops[i]; opacity = stop.opacity; color = stop.color; offset = stop.offset; if(isNumber(opacity)) { opacity = Math.max(0, Math.min(1, opacity)); color = this._toRGBA(color, opacity); } else { color = TORGB(color); } offset = stop.offset || i/(len - 1); offset *= stopMultiplier; if(offset <= 1) { gradient.addColorStop(offset, color); } } return gradient; }, /** * Clears all values * * @method _initProps * @private */ _initProps: function() { this._methods = []; this._lineToMethods = []; this._xcoords = [0]; this._ycoords = [0]; this._width = 0; this._height = 0; this._left = 0; this._top = 0; this._right = 0; this._bottom = 0; this._currentX = 0; this._currentY = 0; }, /** * Indicates a drawing has completed. * * @property _drawingComplete * @type Boolean * @private */ _drawingComplete: false, /** * Creates canvas element * * @method _createGraphic * @return HTMLCanvasElement * @private */ _createGraphic: function() { var graphic = Y.config.doc.createElement('canvas'); return graphic; }, /** * Returns the points on a curve * * @method getBezierData * @param Array points Array containing the begin, end and control points of a curve. * @param Number t The value for incrementing the next set of points. * @return Array * @private */ getBezierData: function(points, t) { var n = points.length, tmp = [], i, j; for (i = 0; i < n; ++i){ tmp[i] = [points[i][0], points[i][1]]; // save input } for (j = 1; j < n; ++j) { for (i = 0; i < n - j; ++i) { tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; } } return [ tmp[0][0], tmp[0][1] ]; }, /** * Calculates the bounding box for a curve * * @method _setCurveBoundingBox * @param Array pts Array containing points for start, end and control points of a curve. * @param Number w Width used to calculate the number of points to describe the curve. * @param Number h Height used to calculate the number of points to describe the curve. * @private */ _setCurveBoundingBox: function(pts, w, h) { var i = 0, left = this._currentX, right = left, top = this._currentY, bottom = top, len = Math.round(Math.sqrt((w * w) + (h * h))), t = 1/len, wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0, xy; for(i = 0; i < len; ++i) { xy = this.getBezierData(pts, t * i); left = isNaN(left) ? xy[0] : Math.min(xy[0], left); right = isNaN(right) ? xy[0] : Math.max(xy[0], right); top = isNaN(top) ? xy[1] : Math.min(xy[1], top); bottom = isNaN(bottom) ? xy[1] : Math.max(xy[1], bottom); } left = Math.round(left * 10)/10; right = Math.round(right * 10)/10; top = Math.round(top * 10)/10; bottom = Math.round(bottom * 10)/10; this._trackSize(right + wt, bottom + wt); this._trackSize(left - wt, top - wt); }, /** * Updates the size of the graphics object * * @method _trackSize * @param {Number} w width * @param {Number} h height * @private */ _trackSize: function(w, h) { if (w > this._right) { this._right = w; } if(w < this._left) { this._left = w; } if (h < this._top) { this._top = h; } if (h > this._bottom) { this._bottom = h; } this._width = this._right - this._left; this._height = this._bottom - this._top; } }; Y.CanvasDrawing = CanvasDrawing; /** * Canvas implementation of the `Shape` class. * `CanvasShape` is not intended to be used directly. Instead, use the `Shape` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Shape` * class will point to the `CanvasShape` class. * * @module graphics * @class CanvasShape * @constructor */ CanvasShape = function() { this._transforms = []; this.matrix = new Y.Matrix(); CanvasShape.superclass.constructor.apply(this, arguments); }; CanvasShape.NAME = "shape"; Y.extend(CanvasShape, Y.GraphicBase, Y.mix({ /** * Init method, invoked during construction. * Calls `initializer` method. * * @method init * @protected */ init: function() { this.initializer.apply(this, arguments); }, /** * Initializes the shape * * @private * @method _initialize */ initializer: function(cfg) { var host = this, graphic = cfg.graphic, data = this.get("data"); host._initProps(); host.createNode(); host._xcoords = [0]; host._ycoords = [0]; if(graphic) { this._setGraphic(graphic); } if(data) { host._parsePathData(data); } host._updateHandler(); }, /** * Set the Graphic instance for the shape. * * @method _setGraphic * @param {Graphic | Node | HTMLElement | String} render This param is used to determine the graphic instance. If it is a * `Graphic` instance, it will be assigned to the `graphic` attribute. Otherwise, a new Graphic instance will be created * and rendered into the dom element that the render represents. * @private */ _setGraphic: function(render) { var graphic; if(render instanceof Y.CanvasGraphic) { this._graphic = render; } else { graphic = new Y.CanvasGraphic({ render: render }); graphic._appendShape(this); this._graphic = graphic; } }, /** * Add a class name to each node. * * @method addClass * @param {String} className the class name to add to the node's class attribute */ addClass: function(className) { var node = this.get("node"); Y.DOM.addClass(node, className); }, /** * Removes a class name from each node. * * @method removeClass * @param {String} className the class name to remove from the node's class attribute */ removeClass: function(className) { var node = this.get("node"); Y.DOM.removeClass(node, className); }, /** * Gets the current position of the node in page coordinates. * * @method getXY * @return Array The XY position of the shape. */ getXY: function() { var graphic = this.get("graphic"), parentXY = graphic.getXY(), x = this.get("x"), y = this.get("y"); return [parentXY[0] + x, parentXY[1] + y]; }, /** * Set the position of the shape in page coordinates, regardless of how the node is positioned. * * @method setXY * @param {Array} Contains X & Y values for new position (coordinates are page-based) */ setXY: function(xy) { var graphic = this.get("graphic"), parentXY = graphic.getXY(), x = xy[0] - parentXY[0], y = xy[1] - parentXY[1]; this._set("x", x); this._set("y", y); this._updateNodePosition(x, y); }, /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * * @method contains * @param {CanvasShape | HTMLElement} needle The possible node or descendent * @return Boolean Whether or not this shape is the needle or its ancestor. */ contains: function(needle) { var node = needle instanceof Y.Node ? needle._node : needle; return node === this.node; }, /** * Test if the supplied node matches the supplied selector. * * @method test * @param {String} selector The CSS selector to test against. * @return Boolean Wheter or not the shape matches the selector. */ test: function(selector) { return Y.Selector.test(this.node, selector); }, /** * 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; return node === refNode; }, /** * Value function for fill attribute * * @method _getDefaultFill * @return Object * @private */ _getDefaultFill: function() { return { type: "solid", opacity: 1, cx: 0.5, cy: 0.5, fx: 0.5, fy: 0.5, r: 0.5 }; }, /** * Value function for stroke attribute * * @method _getDefaultStroke * @return Object * @private */ _getDefaultStroke: function() { return { weight: 1, dashstyle: "none", color: "#000", opacity: 1.0 }; }, /** * Left edge of the path * * @property _left * @type Number * @private */ _left: 0, /** * Right edge of the path * * @property _right * @type Number * @private */ _right: 0, /** * Top edge of the path * * @property _top * @type Number * @private */ _top: 0, /** * Bottom edge of the path * * @property _bottom * @type Number * @private */ _bottom: 0, /** * Creates the dom node for the shape. * * @method createNode * @return HTMLElement * @private */ createNode: function() { var host = this, node = Y.config.doc.createElement('canvas'), id = host.get("id"), concat = host._camelCaseConcat, name = host.name; host._context = node.getContext('2d'); node.setAttribute("overflow", "visible"); node.style.overflow = "visible"; if(!host.get("visible")) { node.style.visibility = "hidden"; } node.setAttribute("id", id); id = "#" + id; host.node = node; host.addClass( _getClassName(SHAPE) + " " + _getClassName(concat(IMPLEMENTATION, SHAPE)) + " " + _getClassName(name) + " " + _getClassName(concat(IMPLEMENTATION, name)) ); }, /** * Overrides default `on` method. Checks to see if its a dom interaction event. If so, * return an event attached to the `node` element. If not, return the normal functionality. * * @method on * @param {String} type event type * @param {Object} callback function * @private */ on: function(type, fn) { if(Y.Node.DOM_EVENTS[type]) { return Y.on(type, fn, "#" + this.get("id")); } return Y.on.apply(this, arguments); }, /** * Adds a stroke to the shape node. * * @method _strokeChangeHandler * @param {Object} stroke Properties of the `stroke` attribute. * @private */ _setStrokeProps: function(stroke) { var color, weight, opacity, linejoin, linecap, dashstyle; if(stroke) { color = stroke.color; weight = PARSE_FLOAT(stroke.weight); opacity = PARSE_FLOAT(stroke.opacity); linejoin = stroke.linejoin || "round"; linecap = stroke.linecap || "butt"; dashstyle = stroke.dashstyle; this._miterlimit = null; this._dashstyle = (dashstyle && Y.Lang.isArray(dashstyle) && dashstyle.length > 1) ? dashstyle : null; this._strokeWeight = weight; if (IS_NUMBER(weight) && weight > 0) { this._stroke = 1; } else { this._stroke = 0; } if (IS_NUMBER(opacity)) { this._strokeStyle = this._toRGBA(color, opacity); } else { this._strokeStyle = color; } this._linecap = linecap; if(linejoin === "round" || linejoin === "bevel") { this._linejoin = linejoin; } else { linejoin = parseInt(linejoin, 10); if(IS_NUMBER(linejoin)) { this._miterlimit = Math.max(linejoin, 1); this._linejoin = "miter"; } } } else { this._stroke = 0; } }, /** * Sets the value of an attribute. * * @method set * @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can * be passed in to set multiple attributes at once. * @param {Any} value The value to set the attribute to. This value is ignored if an object is received as * the name param. */ set: function() { var host = this; AttributeLite.prototype.set.apply(host, arguments); if(host.initialized) { host._updateHandler(); } }, /** * Adds a fill to the shape node. * * @method _setFillProps * @param {Object} fill Properties of the `fill` attribute. * @private */ _setFillProps: function(fill) { var isNumber = IS_NUMBER, color, opacity, type; if(fill) { color = fill.color; type = fill.type; if(type === "linear" || type === "radial") { this._fillType = type; } else if(color) { opacity = fill.opacity; if (isNumber(opacity)) { opacity = Math.max(0, Math.min(1, opacity)); color = this._toRGBA(color, opacity); } else { color = TORGB(color); } this._fillColor = color; this._fillType = 'solid'; } else { this._fillColor = null; } } else { this._fillType = null; this._fillColor = null; } }, /** * Specifies a 2d translation. * * @method translate * @param {Number} x The value to transate on the x-axis. * @param {Number} y The value to translate on the y-axis. */ translate: function(x, y) { this._translateX += x; this._translateY += y; this._addTransform("translate", arguments); }, /** * Translates the shape along the x-axis. When translating x and y coordinates, * use the `translate` method. * * @method translateX * @param {Number} x The value to translate. */ translateX: function(x) { this._translateX += x; this._addTransform("translateX", arguments); }, /** * Performs a translate on the y-coordinate. When translating x and y coordinates, * use the `translate` method. * * @method translateY * @param {Number} y The value to translate. */ translateY: function(y) { this._translateY += y; this._addTransform("translateY", arguments); }, /** * Skews the shape around the x-axis and y-axis. * * @method skew * @param {Number} x The value to skew on the x-axis. * @param {Number} y The value to skew on the y-axis. */ skew: function() { this._addTransform("skew", arguments); }, /** * Skews the shape around the x-axis. * * @method skewX * @param {Number} x x-coordinate */ skewX: function() { this._addTransform("skewX", arguments); }, /** * Skews the shape around the y-axis. * * @method skewY * @param {Number} y y-coordinate */ skewY: function() { this._addTransform("skewY", arguments); }, /** * Rotates the shape clockwise around it transformOrigin. * * @method rotate * @param {Number} deg The degree of the rotation. */ rotate: function() { this._addTransform("rotate", arguments); }, /** * Specifies a 2d scaling operation. * * @method scale * @param {Number} val */ scale: function() { this._addTransform("scale", arguments); }, /** * Storage for the transform attribute. * * @property _transform * @type String * @private */ _transform: "", /** * Adds a transform to the shape. * * @method _addTransform * @param {String} type The transform being applied. * @param {Array} args The arguments for the transform. * @private */ _addTransform: function(type, args) { args = Y.Array(args); this._transform = Y_LANG.trim(this._transform + " " + type + "(" + args.join(", ") + ")"); args.unshift(type); this._transforms.push(args); if(this.initialized) { this._updateTransform(); } }, /** * Applies all transforms. * * @method _updateTransform * @private */ _updateTransform: function() { var node = this.node, key, transform, transformOrigin = this.get("transformOrigin"), matrix = this.matrix, i, len = this._transforms.length; if(this._transforms && this._transforms.length > 0) { for(i = 0; i < len; ++i) { key = this._transforms[i].shift(); if(key) { matrix[key].apply(matrix, this._transforms[i]); } } transform = matrix.toCSSText(); } this._graphic.addToRedrawQueue(this); transformOrigin = (100 * transformOrigin[0]) + "% " + (100 * transformOrigin[1]) + "%"; Y_DOM.setStyle(node, "transformOrigin", transformOrigin); if(transform) { Y_DOM.setStyle(node, "transform", transform); } this._transforms = []; }, /** * Updates `Shape` based on attribute changes. * * @method _updateHandler * @private */ _updateHandler: function() { this._draw(); this._updateTransform(); }, /** * Updates the shape. * * @method _draw * @private */ _draw: function() { var node = this.node; this.clear(); this._closePath(); node.style.left = this.get("x") + "px"; node.style.top = this.get("y") + "px"; }, /** * Completes a shape or drawing * * @method _closePath * @private */ _closePath: function() { if(!this._methods) { return; } var node = this.get("node"), w = this._right - this._left, h = this._bottom - this._top, context = this._context, methods = [], cachedMethods = this._methods.concat(), i, j, method, args, argsLen, len = 0; this._context.clearRect(0, 0, node.width, node.height); if(this._methods) { len = cachedMethods.length; if(!len || len < 1) { return; } for(i = 0; i < len; ++i) { methods[i] = cachedMethods[i].concat(); args = methods[i]; argsLen = (args[0] === "quadraticCurveTo" || args[0] === "bezierCurveTo") ? args.length : 3; for(j = 1; j < argsLen; ++j) { if(j % 2 === 0) { args[j] = args[j] - this._top; } else { args[j] = args[j] - this._left; } } } node.setAttribute("width", Math.min(w, 2000)); node.setAttribute("height", Math.min(2000, h)); context.beginPath(); for(i = 0; i < len; ++i) { args = methods[i].concat(); if(args && args.length > 0) { method = args.shift(); if(method) { if(method === "closePath") { context.closePath(); this._strokeAndFill(context); } else if(method && method === "lineTo" && this._dashstyle) { args.unshift(this._xcoords[i] - this._left, this._ycoords[i] - this._top); this._drawDashedLine.apply(this, args); } else { context[method].apply(context, args); } } } } this._strokeAndFill(context); this._drawingComplete = true; this._clearAndUpdateCoords(); this._updateNodePosition(); this._methods = cachedMethods; } }, /** * Completes a stroke and/or fill operation on the context. * * @method _strokeAndFill * @param {Context} Reference to the context element of the canvas instance. * @private */ _strokeAndFill: function(context) { if (this._fillType) { if(this._fillType === "linear") { context.fillStyle = this._getLinearGradient(); } else if(this._fillType === "radial") { context.fillStyle = this._getRadialGradient(); } else { context.fillStyle = this._fillColor; } context.closePath(); context.fill(); } if (this._stroke) { if(this._strokeWeight) { context.lineWidth = this._strokeWeight; } context.lineCap = this._linecap; context.lineJoin = this._linejoin; if(this._miterlimit) { context.miterLimit = this._miterlimit; } context.strokeStyle = this._strokeStyle; context.stroke(); } }, /** * Draws a dashed line between two points. * * @method _drawDashedLine * @param {Number} xStart The x position of the start of the line * @param {Number} yStart The y position of the start of the line * @param {Number} xEnd The x position of the end of the line * @param {Number} yEnd The y position of the end of the line * @private */ _drawDashedLine: function(xStart, yStart, xEnd, yEnd) { var context = this._context, dashsize = this._dashstyle[0], gapsize = this._dashstyle[1], segmentLength = dashsize + gapsize, xDelta = xEnd - xStart, yDelta = yEnd - yStart, delta = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2)), segmentCount = Math.floor(Math.abs(delta / segmentLength)), radians = Math.atan2(yDelta, xDelta), xCurrent = xStart, yCurrent = yStart, i; xDelta = Math.cos(radians) * segmentLength; yDelta = Math.sin(radians) * segmentLength; for(i = 0; i < segmentCount; ++i) { context.moveTo(xCurrent, yCurrent); context.lineTo(xCurrent + Math.cos(radians) * dashsize, yCurrent + Math.sin(radians) * dashsize); xCurrent += xDelta; yCurrent += yDelta; } context.moveTo(xCurrent, yCurrent); delta = Math.sqrt((xEnd - xCurrent) * (xEnd - xCurrent) + (yEnd - yCurrent) * (yEnd - yCurrent)); if(delta > dashsize) { context.lineTo(xCurrent + Math.cos(radians) * dashsize, yCurrent + Math.sin(radians) * dashsize); } else if(delta > 0) { context.lineTo(xCurrent + Math.cos(radians) * delta, yCurrent + Math.sin(radians) * delta); } context.moveTo(xEnd, yEnd); }, /** * Returns the bounds for a shape. * * Calculates the a new bounding box from the original corner coordinates (base on size and position) and the transform matrix. * The calculated bounding box is used by the graphic instance to calculate its viewBox. * * @method getBounds * @return Object */ getBounds: function() { var type = this._type, w = this.get("width"), h = this.get("height"), x = this.get("x"), y = this.get("y"); if(type === "path") { x = x + this._left; y = y + this._top; w = this._right - this._left; h = this._bottom - this._top; } return this._getContentRect(w, h, x, y); }, /** * Calculates the bounding box for the shape. * * @method _getContentRect * @param {Number} w width of the shape * @param {Number} h height of the shape * @param {Number} x x-coordinate of the shape * @param {Number} y y-coordinate of the shape * @private */ _getContentRect: function(w, h, x, y) { var transformOrigin = this.get("transformOrigin"), transformX = transformOrigin[0] * w, transformY = transformOrigin[1] * h, transforms = this.matrix.getTransformArray(this.get("transform")), matrix = new Y.Matrix(), i, len = transforms.length, transform, key, contentRect; if(this._type === "path") { transformX = transformX + x; transformY = transformY + y; } transformX = !isNaN(transformX) ? transformX : 0; transformY = !isNaN(transformY) ? transformY : 0; matrix.translate(transformX, transformY); for(i = 0; i < len; i = i + 1) { transform = transforms[i]; key = transform.shift(); if(key) { matrix[key].apply(matrix, transform); } } matrix.translate(-transformX, -transformY); contentRect = matrix.getContentRect(w, h, x, y); return contentRect; }, /** * Places the shape above all other shapes. * * @method toFront */ toFront: function() { var graphic = this.get("graphic"); if(graphic) { graphic._toFront(this); } }, /** * Places the shape underneath all other shapes. * * @method toFront */ toBack: function() { var graphic = this.get("graphic"); if(graphic) { graphic._toBack(this); } }, /** * Parses path data string and call mapped methods. * * @method _parsePathData * @param {String} val The path data * @private */ _parsePathData: function(val) { var method, methodSymbol, args, commandArray = Y.Lang.trim(val.match(SPLITPATHPATTERN)), i, len, str, symbolToMethod = this._pathSymbolToMethod; if(commandArray) { this.clear(); len = commandArray.length || 0; for(i = 0; i < len; i = i + 1) { str = commandArray[i]; methodSymbol = str.substr(0, 1); args = str.substr(1).match(SPLITARGSPATTERN); method = symbolToMethod[methodSymbol]; if(method) { if(args) { this[method].apply(this, args); } else { this[method].apply(this); } } } this.end(); } }, /** * Destroys the shape instance. * * @method destroy */ destroy: function() { var graphic = this.get("graphic"); if(graphic) { graphic.removeShape(this); } else { this._destroy(); } }, /** * Implementation for shape destruction * * @method destroy * @protected */ _destroy: function() { if(this.node) { Y.Event.purgeElement(this.node, true); if(this.node.parentNode) { this.node.style.visibility = ""; this.node.parentNode.removeChild(this.node); } this._context = null; this.node = null; } } }, Y.CanvasDrawing.prototype)); CanvasShape.ATTRS = { /** * An array of x, y values which indicates the transformOrigin in which to rotate the shape. Valid values range between 0 and 1 representing a * fraction of the shape's corresponding bounding box dimension. The default value is [0.5, 0.5]. * * @config transformOrigin * @type Array */ transformOrigin: { valueFn: function() { return [0.5, 0.5]; } }, /** *

A string containing, in order, transform operations applied to the shape instance. The `transform` string can contain the following values: * *

*
rotate
Rotates the shape clockwise around it transformOrigin.
*
translate
Specifies a 2d translation.
*
skew
Skews the shape around the x-axis and y-axis.
*
scale
Specifies a 2d scaling operation.
*
translateX
Translates the shape along the x-axis.
*
translateY
Translates the shape along the y-axis.
*
skewX
Skews the shape around the x-axis.
*
skewY
Skews the shape around the y-axis.
*
matrix
Specifies a 2D transformation matrix comprised of the specified six values.
*
*

*

Applying transforms through the transform attribute will reset the transform matrix and apply a new transform. The shape class also contains * corresponding methods for each transform that will apply the transform to the current matrix. The below code illustrates how you might use the * `transform` attribute to instantiate a recangle with a rotation of 45 degrees.

var myRect = new Y.Rect({ type:"rect", width: 50, height: 40, transform: "rotate(45)" }; *

The code below would apply `translate` and `rotate` to an existing shape.

myRect.set("transform", "translate(40, 50) rotate(45)"); * @config transform * @type String */ transform: { setter: function(val) { this.matrix.init(); this._transforms = this.matrix.getTransformArray(val); this._transform = val; return val; }, getter: function() { return this._transform; } }, /** * Dom node for the shape * * @config node * @type HTMLElement * @readOnly */ node: { readOnly: true, getter: function() { return this.node; } }, /** * Unique id for class instance. * * @config id * @type String */ id: { valueFn: function() { return Y.guid(); }, setter: function(val) { var node = this.node; if(node) { node.setAttribute("id", val); } return val; } }, /** * Indicates the width of the shape * * @config width * @type Number */ width: { value: 0 }, /** * Indicates the height of the shape * * @config height * @type Number */ height: { value: 0 }, /** * Indicates the x position of shape. * * @config x * @type Number */ x: { value: 0 }, /** * Indicates the y position of shape. * * @config y * @type Number */ y: { value: 0 }, /** * Indicates whether the shape is visible. * * @config visible * @type Boolean */ visible: { value: true, setter: function(val){ var node = this.get("node"), visibility = val ? "visible" : "hidden"; if(node) { node.style.visibility = visibility; } return val; } }, /** * Contains information about the fill of the shape. *
*
color
The color of the fill.
*
opacity
Number between 0 and 1 that indicates the opacity of the fill. The default value is 1.
*
type
Type of fill. *
*
solid
Solid single color fill. (default)
*
linear
Linear gradient fill.
*
radial
Radial gradient fill.
*
*
*
*

If a `linear` or `radial` is specified as the fill type. The following additional property is used: *

*
stops
An array of objects containing the following properties: *
*
color
The color of the stop.
*
opacity
Number between 0 and 1 that indicates the opacity of the stop. The default value is 1. * Note: No effect for IE 6 - 8
*
offset
Number between 0 and 1 indicating where the color stop is positioned.
*
*
*

Linear gradients also have the following property:

*
rotation
Linear gradients flow left to right by default. The rotation property allows you to change the * flow by rotation. (e.g. A rotation of 180 would make the gradient pain from right to left.)
*

Radial gradients have the following additional properties:

*
r
Radius of the gradient circle.
*
fx
Focal point x-coordinate of the gradient.
*
fy
Focal point y-coordinate of the gradient.
*
*

The corresponding `SVGShape` class implements the following additional properties.

*
*
cx
*

The x-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.

*

Note: Currently, this property is not implemented for corresponding `CanvasShape` and * `VMLShape` classes which are used on Android or IE 6 - 8.

*
*
cy
*

The y-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.

*

Note: Currently, this property is not implemented for corresponding `CanvasShape` and `VMLShape` * classes which are used on Android or IE 6 - 8.

*
*
*

These properties are not currently implemented in `CanvasShape` or `VMLShape`.

* * @config fill * @type Object */ fill: { valueFn: "_getDefaultFill", setter: function(val) { var fill, tmpl = this.get("fill") || this._getDefaultFill(); fill = (val) ? Y.merge(tmpl, val) : null; if(fill && fill.color) { if(fill.color === undefined || fill.color === "none") { fill.color = null; } } this._setFillProps(fill); return fill; } }, /** * Contains information about the stroke of the shape. *
*
color
The color of the stroke.
*
weight
Number that indicates the width of the stroke.
*
opacity
Number between 0 and 1 that indicates the opacity of the stroke. The default value is 1.
*
dashstyle
Indicates whether to draw a dashed stroke. When set to "none", a solid stroke is drawn. When set * to an array, the first index indicates the length of the dash. The second index indicates the length of gap. *
linecap
Specifies the linecap for the stroke. The following values can be specified: *
*
butt (default)
Specifies a butt linecap.
*
square
Specifies a sqare linecap.
*
round
Specifies a round linecap.
*
*
*
linejoin
Specifies a linejoin for the stroke. The following values can be specified: *
*
round (default)
Specifies that the linejoin will be round.
*
bevel
Specifies a bevel for the linejoin.
*
miter limit
An integer specifying the miter limit of a miter linejoin. If you want to specify a linejoin * of miter, you simply specify the limit as opposed to having separate miter and miter limit values.
*
*
*
* * @config stroke * @type Object */ stroke: { valueFn: "_getDefaultStroke", setter: function(val) { var tmpl = this.get("stroke") || this._getDefaultStroke(), wt; if(val && val.hasOwnProperty("weight")) { wt = parseInt(val.weight, 10); if(!isNaN(wt)) { val.weight = wt; } } val = (val) ? Y.merge(tmpl, val) : null; this._setStrokeProps(val); return val; } }, //Not used. Remove in future. autoSize: { value: false }, // Only implemented in SVG // Determines whether the instance will receive mouse events. // // @config pointerEvents // @type string // pointerEvents: { value: "visiblePainted" }, /** * Represents an SVG Path string. This will be parsed and added to shape's API to represent the SVG data across all * implementations. Note that when using VML or SVG implementations, part of this content will be added to the DOM using * respective VML/SVG attributes. If your content comes from an untrusted source, you will need to ensure that no * malicious code is included in that content. * * @config data * @type String */ data: { setter: function(val) { if(this.get("node")) { this._parsePathData(val); } return val; } }, /** * Reference to the container Graphic. * * @config graphic * @type Graphic */ graphic: { readOnly: true, getter: function() { return this._graphic; } } }; Y.CanvasShape = CanvasShape; /** * Canvas implementation of the `Path` class. * `CanvasPath` is not intended to be used directly. Instead, use the `Path` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Path` * class will point to the `CanvasPath` class. * * @module graphics * @class CanvasPath * @extends CanvasShape */ CanvasPath = function() { CanvasPath.superclass.constructor.apply(this, arguments); }; CanvasPath.NAME = "path"; Y.extend(CanvasPath, Y.CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "path", /** * Draws the shape. * * @method _draw * @private */ _draw: function() { this._closePath(); this._updateTransform(); }, /** * Creates the dom node for the shape. * * @method createNode * @return HTMLElement * @private */ createNode: function() { var host = this, node = Y.config.doc.createElement('canvas'), name = host.name, concat = host._camelCaseConcat, id = host.get("id"); host._context = node.getContext('2d'); node.setAttribute("overflow", "visible"); node.setAttribute("pointer-events", "none"); node.style.pointerEvents = "none"; node.style.overflow = "visible"; node.setAttribute("id", id); id = "#" + id; host.node = node; host.addClass( _getClassName(SHAPE) + " " + _getClassName(concat(IMPLEMENTATION, SHAPE)) + " " + _getClassName(name) + " " + _getClassName(concat(IMPLEMENTATION, name)) ); }, /** * Completes a drawing operation. * * @method end */ end: function() { this._draw(); return this; } }); CanvasPath.ATTRS = Y.merge(Y.CanvasShape.ATTRS, { /** * Indicates the width of the shape * * @config width * @type Number */ width: { getter: function() { var offset = this._stroke && this._strokeWeight ? (this._strokeWeight * 2) : 0; return this._width - offset; }, setter: function(val) { this._width = val; return val; } }, /** * Indicates the height of the shape * * @config height * @type Number */ height: { getter: function() { var offset = this._stroke && this._strokeWeight ? (this._strokeWeight * 2) : 0; return this._height - offset; }, setter: function(val) { this._height = val; return val; } }, /** * Indicates the path used for the node. * * @config path * @type String * @readOnly */ path: { readOnly: true, getter: function() { return this._path; } } }); Y.CanvasPath = CanvasPath; /** * Canvas implementation of the `Rect` class. * `CanvasRect` is not intended to be used directly. Instead, use the `Rect` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Rect` * class will point to the `CanvasRect` class. * * @module graphics * @class CanvasRect * @constructor */ CanvasRect = function() { CanvasRect.superclass.constructor.apply(this, arguments); }; CanvasRect.NAME = "rect"; Y.extend(CanvasRect, Y.CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "rect", /** * Draws the shape. * * @method _draw * @private */ _draw: function() { var w = this.get("width"), h = this.get("height"); this.clear(); this.drawRect(0, 0, w, h); this._closePath(); } }); CanvasRect.ATTRS = Y.CanvasShape.ATTRS; Y.CanvasRect = CanvasRect; /** * Canvas implementation of the `Ellipse` class. * `CanvasEllipse` is not intended to be used directly. Instead, use the `Ellipse` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Ellipse` * class will point to the `CanvasEllipse` class. * * @module graphics * @class CanvasEllipse * @constructor */ CanvasEllipse = function() { CanvasEllipse.superclass.constructor.apply(this, arguments); }; CanvasEllipse.NAME = "ellipse"; Y.extend(CanvasEllipse, CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "ellipse", /** * Draws the shape. * * @method _draw * @private */ _draw: function() { var w = this.get("width"), h = this.get("height"); this.clear(); this.drawEllipse(0, 0, w, h); this._closePath(); } }); CanvasEllipse.ATTRS = Y.merge(CanvasShape.ATTRS, { /** * Horizontal radius for the ellipse. * * @config xRadius * @type Number */ xRadius: { setter: function(val) { this.set("width", val * 2); }, getter: function() { var val = this.get("width"); if(val) { val *= 0.5; } return val; } }, /** * Vertical radius for the ellipse. * * @config yRadius * @type Number * @readOnly */ yRadius: { setter: function(val) { this.set("height", val * 2); }, getter: function() { var val = this.get("height"); if(val) { val *= 0.5; } return val; } } }); Y.CanvasEllipse = CanvasEllipse; /** * Canvas implementation of the `Circle` class. * `CanvasCircle` is not intended to be used directly. Instead, use the `Circle` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Circle` * class will point to the `CanvasCircle` class. * * @module graphics * @class CanvasCircle * @constructor */ CanvasCircle = function() { CanvasCircle.superclass.constructor.apply(this, arguments); }; CanvasCircle.NAME = "circle"; Y.extend(CanvasCircle, Y.CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "circle", /** * Draws the shape. * * @method _draw * @private */ _draw: function() { var radius = this.get("radius"); if(radius) { this.clear(); this.drawCircle(0, 0, radius); this._closePath(); } } }); CanvasCircle.ATTRS = Y.merge(Y.CanvasShape.ATTRS, { /** * Indicates the width of the shape * * @config width * @type Number */ width: { setter: function(val) { this.set("radius", val/2); return val; }, getter: function() { return this.get("radius") * 2; } }, /** * Indicates the height of the shape * * @config height * @type Number */ height: { setter: function(val) { this.set("radius", val/2); return val; }, getter: function() { return this.get("radius") * 2; } }, /** * Radius of the circle * * @config radius * @type Number */ radius: { lazyAdd: false } }); Y.CanvasCircle = CanvasCircle; /** * Draws pie slices * * @module graphics * @class CanvasPieSlice * @constructor */ CanvasPieSlice = function() { CanvasPieSlice.superclass.constructor.apply(this, arguments); }; CanvasPieSlice.NAME = "canvasPieSlice"; Y.extend(CanvasPieSlice, Y.CanvasShape, { /** * Indicates the type of shape * * @property _type * @type String * @private */ _type: "path", /** * Change event listener * * @private * @method _updateHandler */ _draw: function() { var x = this.get("cx"), y = this.get("cy"), startAngle = this.get("startAngle"), arc = this.get("arc"), radius = this.get("radius"); this.clear(); this._left = x; this._right = radius; this._top = y; this._bottom = radius; this.drawWedge(x, y, startAngle, arc, radius); this.end(); } }); CanvasPieSlice.ATTRS = Y.mix({ cx: { value: 0 }, cy: { value: 0 }, /** * Starting angle in relation to a circle in which to begin the pie slice drawing. * * @config startAngle * @type Number */ startAngle: { value: 0 }, /** * Arc of the slice. * * @config arc * @type Number */ arc: { value: 0 }, /** * Radius of the circle in which the pie slice is drawn * * @config radius * @type Number */ radius: { value: 0 } }, Y.CanvasShape.ATTRS); Y.CanvasPieSlice = CanvasPieSlice; /** * Canvas implementation of the `Graphic` class. * `CanvasGraphic` is not intended to be used directly. Instead, use the `Graphic` class. * If the browser lacks SVG capabilities but has * Canvas capabilities, the `Graphic` * class will point to the `CanvasGraphic` class. * * @module graphics * @class CanvasGraphic * @constructor */ function CanvasGraphic() { CanvasGraphic.superclass.constructor.apply(this, arguments); } CanvasGraphic.NAME = "canvasGraphic"; CanvasGraphic.ATTRS = { /** * Whether or not to render the `Graphic` automatically after to a specified parent node after init. This can be a Node * instance or a CSS selector string. * * @config render * @type Node | String */ render: {}, /** * Unique id for class instance. * * @config id * @type String */ id: { valueFn: function() { return Y.guid(); }, setter: function(val) { var node = this._node; if(node) { node.setAttribute("id", val); } return val; } }, /** * Key value pairs in which a shape instance is associated with its id. * * @config shapes * @type Object * @readOnly */ shapes: { readOnly: true, getter: function() { return this._shapes; } }, /** * Object containing size and coordinate data for the content of a Graphic in relation to the graphic instance's position. * * @config contentBounds * @type Object * @readOnly */ contentBounds: { readOnly: true, getter: function() { return this._contentBounds; } }, /** * The outermost html element of the Graphic instance. * * @config node * @type HTMLElement * @readOnly */ node: { readOnly: true, getter: function() { return this._node; } }, /** * Indicates the width of the `Graphic`. * * @config width * @type Number */ width: { setter: function(val) { if(this._node) { this._node.style.width = val + "px"; } return val; } }, /** * Indicates the height of the `Graphic`. * * @config height * @type Number */ height: { setter: function(val) { if(this._node) { this._node.style.height = val + "px"; } return val; } }, /** * Determines the sizing of the Graphic. * *
*
sizeContentToGraphic
The Graphic's width and height attributes are, either explicitly set through the * width and height attributes or are determined by the dimensions of the parent element. The * content contained in the Graphic will be sized to fit with in the Graphic instance's dimensions. When using this * setting, the preserveAspectRatio attribute will determine how the contents are sized.
*
sizeGraphicToContent
(Also accepts a value of true) The Graphic's width and height are determined by the * size and positioning of the content.
*
false
The Graphic's width and height attributes are, either explicitly set through the width * and height attributes or are determined by the dimensions of the parent element. The contents of the * Graphic instance are not affected by this setting.
*
* * * @config autoSize * @type Boolean | String * @default false */ autoSize: { value: false }, /** * Determines how content is sized when autoSize is set to sizeContentToGraphic. * *
*
none
Do not force uniform scaling. Scale the graphic content of the given element non-uniformly if necessary * such that the element's bounding box exactly matches the viewport rectangle.
*
xMinYMin
Force uniform scaling position along the top left of the Graphic's node.
*
xMidYMin
Force uniform scaling horizontally centered and positioned at the top of the Graphic's node.
*
xMaxYMin
Force uniform scaling positioned horizontally from the right and vertically from the top.
*
xMinYMid
Force uniform scaling positioned horizontally from the left and vertically centered. *
xMidYMid (the default)
Force uniform scaling with the content centered.
*
xMaxYMid
Force uniform scaling positioned horizontally from the right and vertically centered.
*
xMinYMax
Force uniform scaling positioned horizontally from the left and vertically from the bottom.
*
xMidYMax
Force uniform scaling horizontally centered and position vertically from the bottom.
*
xMaxYMax
Force uniform scaling positioned horizontally from the right and vertically from the bottom.
*
* * @config preserveAspectRatio * @type String * @default xMidYMid */ preserveAspectRatio: { value: "xMidYMid" }, /** * The contentBounds will resize to greater values but not smaller values. (for performance) * When resizing the contentBounds down is desirable, set the resizeDown value to true. * * @config resizeDown * @type Boolean */ resizeDown: { value: false }, /** * Indicates the x-coordinate for the instance. * * @config x * @type Number */ x: { getter: function() { return this._x; }, setter: function(val) { this._x = val; if(this._node) { this._node.style.left = val + "px"; } return val; } }, /** * Indicates the y-coordinate for the instance. * * @config y * @type Number */ y: { getter: function() { return this._y; }, setter: function(val) { this._y = val; if(this._node) { this._node.style.top = val + "px"; } return val; } }, /** * Indicates whether or not the instance will automatically redraw after a change is made to a shape. * This property will get set to false when batching operations. * * @config autoDraw * @type Boolean * @default true * @private */ autoDraw: { value: true }, /** * Indicates whether the `Graphic` and its children are visible. * * @config visible * @type Boolean */ visible: { value: true, setter: function(val) { this._toggleVisible(val); return val; } } }; Y.extend(CanvasGraphic, Y.GraphicBase, { /** * Sets the value of an attribute. * * @method set * @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can * be passed in to set multiple attributes at once. * @param {Any} value The value to set the attribute to. This value is ignored if an object is received as * the name param. */ set: function() { var host = this, attr = arguments[0], redrawAttrs = { autoDraw: true, autoSize: true, preserveAspectRatio: true, resizeDown: true }, key, forceRedraw = false; AttributeLite.prototype.set.apply(host, arguments); if(host._state.autoDraw === true && Y.Object.size(this._shapes) > 0) { if(Y_LANG.isString && redrawAttrs[attr]) { forceRedraw = true; } else if(Y_LANG.isObject(attr)) { for(key in redrawAttrs) { if(redrawAttrs.hasOwnProperty(key) && attr[key]) { forceRedraw = true; break; } } } } if(forceRedraw) { host._redraw(); } }, /** * Storage for `x` attribute. * * @property _x * @type Number * @private */ _x: 0, /** * Storage for `y` attribute. * * @property _y * @type Number * @private */ _y: 0, /** * Gets the current position of the graphic instance in page coordinates. * * @method getXY * @return Array The XY position of the shape. */ getXY: function() { var node = this._node, xy; if(node) { xy = Y.DOM.getXY(node); } return xy; }, /** * Initializes the class. * * @method initializer * @param {Object} config Optional attributes * @private */ initializer: function() { var render = this.get("render"), visibility = this.get("visible") ? "visible" : "hidden", w = this.get("width") || 0, h = this.get("height") || 0; this._shapes = {}; this._redrawQueue = {}; this._contentBounds = { left: 0, top: 0, right: 0, bottom: 0 }; this._node = DOCUMENT.createElement('div'); this._node.style.position = "absolute"; this._node.style.visibility = visibility; this.set("width", w); this.set("height", h); if(render) { this.render(render); } }, /** * Adds the graphics node to the dom. * * @method render * @param {HTMLElement} parentNode node in which to render the graphics node into. */ render: function(render) { var parentNode = render || DOCUMENT.body, node = this._node, w, h; if(render instanceof Y.Node) { parentNode = render._node; } else if(Y.Lang.isString(render)) { parentNode = Y.Selector.query(render, DOCUMENT.body, true); } w = this.get("width") || parseInt(Y.DOM.getComputedStyle(parentNode, "width"), 10); h = this.get("height") || parseInt(Y.DOM.getComputedStyle(parentNode, "height"), 10); parentNode.appendChild(node); node.style.display = "block"; node.style.position = "absolute"; node.style.left = this.get("x") + "px"; node.style.top = this.get("y") + "px"; this.set("width", w); this.set("height", h); this.parentNode = parentNode; return this; }, /** * Removes all nodes. * * @method destroy */ destroy: function() { this.removeAllShapes(); if(this._node) { this._removeChildren(this._node); if(this._node.parentNode) { this._node.parentNode.removeChild(this._node); } this._node = null; } }, /** * Generates a shape instance by type. * * @method addShape * @param {Object} cfg attributes for the shape * @return Shape */ addShape: function(cfg) { cfg.graphic = this; if(!this.get("visible")) { cfg.visible = false; } var ShapeClass = this._getShapeClass(cfg.type), shape = new ShapeClass(cfg); this._appendShape(shape); return shape; }, /** * Adds a shape instance to the graphic instance. * * @method _appendShape * @param {Shape} shape The shape instance to be added to the graphic. * @private */ _appendShape: function(shape) { var node = shape.node, parentNode = this._frag || this._node; if(this.get("autoDraw")) { parentNode.appendChild(node); } else { this._getDocFrag().appendChild(node); } }, /** * Removes a shape instance from from the graphic instance. * * @method removeShape * @param {Shape|String} shape The instance or id of the shape to be removed. */ removeShape: function(shape) { if(!(shape instanceof CanvasShape)) { if(Y_LANG.isString(shape)) { shape = this._shapes[shape]; } } if(shape && shape instanceof CanvasShape) { shape._destroy(); delete this._shapes[shape.get("id")]; } if(this.get("autoDraw")) { this._redraw(); } return shape; }, /** * Removes all shape instances from the dom. * * @method removeAllShapes */ removeAllShapes: function() { var shapes = this._shapes, i; for(i in shapes) { if(shapes.hasOwnProperty(i)) { shapes[i].destroy(); } } this._shapes = {}; }, /** * Clears the graphics object. * * @method clear */ clear: function() { this.removeAllShapes(); }, /** * Removes all child nodes. * * @method _removeChildren * @param {HTMLElement} node * @private */ _removeChildren: function(node) { if(node && node.hasChildNodes()) { var child; while(node.firstChild) { child = node.firstChild; this._removeChildren(child); node.removeChild(child); } } }, /** * Toggles visibility * * @method _toggleVisible * @param {Boolean} val indicates visibilitye * @private */ _toggleVisible: function(val) { var i, shapes = this._shapes, visibility = val ? "visible" : "hidden"; if(shapes) { for(i in shapes) { if(shapes.hasOwnProperty(i)) { shapes[i].set("visible", val); } } } if(this._node) { this._node.style.visibility = visibility; } }, /** * Returns a shape class. Used by `addShape`. * * @method _getShapeClass * @param {Shape | String} val Indicates which shape class. * @return Function * @private */ _getShapeClass: function(val) { var shape = this._shapeClass[val]; if(shape) { return shape; } return val; }, /** * Look up for shape classes. Used by `addShape` to retrieve a class for instantiation. * * @property _shapeClass * @type Object * @private */ _shapeClass: { circle: Y.CanvasCircle, rect: Y.CanvasRect, path: Y.CanvasPath, ellipse: Y.CanvasEllipse, pieslice: Y.CanvasPieSlice }, /** * Returns a shape based on the id of its dom node. * * @method getShapeById * @param {String} id Dom id of the shape's node attribute. * @return Shape */ getShapeById: function(id) { var shape = this._shapes[id]; return shape; }, /** * Allows for creating multiple shapes in order to batch appending and redraw operations. * * @method batch * @param {Function} method Method to execute. */ batch: function(method) { var autoDraw = this.get("autoDraw"); this.set("autoDraw", false); method(); this.set("autoDraw", autoDraw); }, /** * Returns a document fragment to for attaching shapes. * * @method _getDocFrag * @return DocumentFragment * @private */ _getDocFrag: function() { if(!this._frag) { this._frag = DOCUMENT.createDocumentFragment(); } return this._frag; }, /** * Redraws all shapes. * * @method _redraw * @private */ _redraw: function() { var autoSize = this.get("autoSize"), preserveAspectRatio = this.get("preserveAspectRatio"), box = this.get("resizeDown") ? this._getUpdatedContentBounds() : this._contentBounds, contentWidth, contentHeight, w, h, xScale, yScale, translateX = 0, translateY = 0, matrix, node = this.get("node"); if(autoSize) { if(autoSize === "sizeContentToGraphic") { contentWidth = box.right - box.left; contentHeight = box.bottom - box.top; w = parseFloat(Y_DOM.getComputedStyle(node, "width")); h = parseFloat(Y_DOM.getComputedStyle(node, "height")); matrix = new Y.Matrix(); if(preserveAspectRatio === "none") { xScale = w/contentWidth; yScale = h/contentHeight; } else { if(contentWidth/contentHeight !== w/h) { if(contentWidth * h/contentHeight > w) { xScale = yScale = w/contentWidth; translateY = this._calculateTranslate(preserveAspectRatio.slice(5).toLowerCase(), contentHeight * w/contentWidth, h); } else { xScale = yScale = h/contentHeight; translateX = this._calculateTranslate(preserveAspectRatio.slice(1, 4).toLowerCase(), contentWidth * h/contentHeight, w); } } } Y_DOM.setStyle(node, "transformOrigin", "0% 0%"); translateX = translateX - (box.left * xScale); translateY = translateY - (box.top * yScale); matrix.translate(translateX, translateY); matrix.scale(xScale, yScale); Y_DOM.setStyle(node, "transform", matrix.toCSSText()); } else { this.set("width", box.right); this.set("height", box.bottom); } } if(this._frag) { this._node.appendChild(this._frag); this._frag = null; } }, /** * Determines the value for either an x or y value to be used for the translate of the Graphic. * * @method _calculateTranslate * @param {String} position The position for placement. Possible values are min, mid and max. * @param {Number} contentSize The total size of the content. * @param {Number} boundsSize The total size of the Graphic. * @return Number * @private */ _calculateTranslate: function(position, contentSize, boundsSize) { var ratio = boundsSize - contentSize, coord; switch(position) { case "mid" : coord = ratio * 0.5; break; case "max" : coord = ratio; break; default : coord = 0; break; } return coord; }, /** * Adds a shape to the redraw queue and calculates the contentBounds. Used internally * by `Shape` instances. * * @method addToRedrawQueue * @param Shape shape The shape instance to add to the queue * @protected */ addToRedrawQueue: function(shape) { var shapeBox, box; this._shapes[shape.get("id")] = shape; if(!this.get("resizeDown")) { shapeBox = shape.getBounds(); box = this._contentBounds; box.left = box.left < shapeBox.left ? box.left : shapeBox.left; box.top = box.top < shapeBox.top ? box.top : shapeBox.top; box.right = box.right > shapeBox.right ? box.right : shapeBox.right; box.bottom = box.bottom > shapeBox.bottom ? box.bottom : shapeBox.bottom; this._contentBounds = box; } if(this.get("autoDraw")) { this._redraw(); } }, /** * Recalculates and returns the `contentBounds` for the `Graphic` instance. * * @method _getUpdatedContentBounds * @return {Object} * @private */ _getUpdatedContentBounds: function() { var bounds, i, shape, queue = this._shapes, box = {}; for(i in queue) { if(queue.hasOwnProperty(i)) { shape = queue[i]; bounds = shape.getBounds(); box.left = Y_LANG.isNumber(box.left) ? Math.min(box.left, bounds.left) : bounds.left; box.top = Y_LANG.isNumber(box.top) ? Math.min(box.top, bounds.top) : bounds.top; box.right = Y_LANG.isNumber(box.right) ? Math.max(box.right, bounds.right) : bounds.right; box.bottom = Y_LANG.isNumber(box.bottom) ? Math.max(box.bottom, bounds.bottom) : bounds.bottom; } } box.left = Y_LANG.isNumber(box.left) ? box.left : 0; box.top = Y_LANG.isNumber(box.top) ? box.top : 0; box.right = Y_LANG.isNumber(box.right) ? box.right : 0; box.bottom = Y_LANG.isNumber(box.bottom) ? box.bottom : 0; this._contentBounds = box; return box; }, /** * Inserts shape on the top of the tree. * * @method _toFront * @param {CanvasShape} Shape to add. * @private */ _toFront: function(shape) { var contentNode = this.get("node"); if(shape instanceof Y.CanvasShape) { shape = shape.get("node"); } if(contentNode && shape) { contentNode.appendChild(shape); } }, /** * Inserts shape as the first child of the content node. * * @method _toBack * @param {CanvasShape} Shape to add. * @private */ _toBack: function(shape) { var contentNode = this.get("node"), targetNode; if(shape instanceof Y.CanvasShape) { shape = shape.get("node"); } if(contentNode && shape) { targetNode = contentNode.firstChild; if(targetNode) { contentNode.insertBefore(shape, targetNode); } else { contentNode.appendChild(shape); } } } }); Y.CanvasGraphic = CanvasGraphic; }, '3.18.1', {"requires": ["graphics", "color-base"]}); PK\`~ŵ'3.18.1/dd-constrain/dd-constrain-min.jsnu[YUI.add("dd-constrain",function(e,t){var n="dragNode",r="offsetHeight",i="offsetWidth",s="host",o="tickXArray",u="tickYArray",a=e.DD.DDM,f="top",l="right",c="bottom",h="left",p="view",d=null,v="drag:tickAlignX",m="drag:tickAlignY",g=function(){this._lazyAddAttrs=!1,g.superclass.constructor.apply(this,arguments)};g.NAME="ddConstrained",g.NS="con",g.ATTRS={host:{},stickX:{value:!1},stickY:{value:!1},tickX:{value:!1},tickY:{value:!1},tickXArray:{value:!1},tickYArray:{value:!1},gutter:{value:"0",setter:function(t){return e.DD.DDM.cssSizestoObject(t)}},constrain:{value:p,setter:function(t){var n=e.one(t);return n&&(t=n),t}},constrain2region:{setter:function(e){return this.set("constrain",e)}},constrain2node:{setter:function(t){return this.set("constrain",e.one(t))}},constrain2view:{setter:function(){return this.set("constrain",p)}},cacheRegion:{value:!0}},d={_lastTickXFired:null,_lastTickYFired:null,initializer:function(){this._createEvents(),this._eventHandles=[this.get(s).on("drag:end",e.bind(this._handleEnd,this)),this.get(s).on("drag:start",e.bind(this._handleStart,this)),this.get(s).after("drag:align",e.bind(this.align,this)),this.get(s).after("drag:drag",e.bind(this.drag,this))]},destructor:function(){e.Array.each(this._eventHandles,function(e){e.detach()}),this._eventHandles.length=0},_createEvents:function(){var t=[v,m];e.Array.each(t,function(e){this.publish(e,{type:e,emitFacade:!0,bubbles:!0,queuable:!1,prefix:"drag"})},this)},_handleEnd:function(){this._lastTickYFired=null,this._lastTickXFired=null},_handleStart:function(){this.resetCache()},_regionCache:null,_cacheRegion:function(){this._regionCache=this.get("constrain").get("region")},resetCache:function(){this._regionCache=null},_getConstraint:function(){var t=this.get("constrain"),r=this.get("gutter"),i;t&&(t instanceof e.Node?(this._regionCache||(this._eventHandles.push(e.on("resize",e.bind(this._cacheRegion,this),e.config.win)),this._cacheRegion()),i=e.clone(this._regionCache),this.get("cacheRegion")||this.resetCache()):e.Lang.isObject(t)&&(i=e.clone(t)));if(!t||!i)t=p;return t===p&&(i=this.get(s).get(n).get("viewportRegion")),e.Object.each(r,function(e,t){t===l||t===c?i[t]-=e:i[t]+=e}),i},getRegion:function(e){var t={},o=null,u=null,a=this.get(s);return t=this._getConstraint(),e&&(o=a.get(n).get(r),u=a.get(n).get(i),t[l]=t[l]-u,t[c]=t[c]-o),t},_checkRegion:function(e){var t=e,o=this.getRegion(),u=this.get(s),a=u.get(n).get(r),p=u.get(n).get(i);return t[1]>o[c]-a&&(e[1]=o[c]-a),o[f]>t[1]&&(e[1]=o[f]),t[0]>o[l]-p&&(e[0]=o[l]-p),o[h]>t[0]&&(e[0]=o[h]),e},inRegion:function(e){e=e||this.get(s).get(n).getXY();var t=this._checkRegion([e[0],e[1]]),r=!1;return e[0]===t[0]&&e[1]===t[1]&&(r=!0),r},align:function(){var e=this.get(s),t=[e.actXY[0],e.actXY[1]],n=this.getRegion(!0);this.get("stickX")&&(t[1]=e.startXY[1]-e.deltaXY[1]),this.get("stickY")&&(t[0]=e.startXY[0]-e.deltaXY[0]),n&&(t=this._checkRegion(t)),t=this._checkTicks(t,n),e.actXY=t},drag:function(){var t=this.get(s),n=this.get("tickX"),r=this.get("tickY"),i=[t.actXY[0],t.actXY[1]];(e.Lang.isNumber(n)||this.get(o))&&this._lastTickXFired!==i[0]&&(this._tickAlignX(),this._lastTickXFired=i[0]),(e.Lang.isNumber(r)||this.get(u))&&this._lastTickYFired!==i[1]&&(this._tickAlignY(),this._lastTickYFired=i[1])},_checkTicks:function(e,t){var n=this.get(s),r=n.startXY[0]-n.deltaXY[0],i=n.startXY[1]-n.deltaXY[1],p=this.get("tickX"),d=this.get("tickY");return p&&!this.get(o)&&(e[0]=a._calcTicks(e[0],r,p,t[h],t[l])),d&&!this.get(u)&&(e[1]=a._calcTicks(e[1],i,d,t[f],t[c])),this.get(o)&&(e[0]=a._calcTickArray(e[0],this.get(o),t[h],t[l])),this.get(u)&&(e[1]=a._calcTickArray(e[1],this.get(u),t[f],t[c])),e},_tickAlignX:function(){this.fire(v)},_tickAlignY:function(){this.fire(m)}},e.namespace("Plugin"),e.extend(g,e.Base,d),e.Plugin.DDConstrained=g,e.mix(a,{_calcTicks:function(e,t,n,r,i){var s=(e-t)/n,o=Math.floor(s),u=Math.ceil(s);return(o!==0||u!==0)&&s>=o&&s<=u&&(e=t+n*o,r&&i&&(ei&&(e=t+n*(o-1)))),e},_calcTickArray:function(e,t,n,r){var i=0,s=t.length,o=0,u,a,f;if(!t||t.length===0)return e;if(t[0]>=e)return t[0];for(i=0;i=e)return u=e-t[i],a=t[o]-e,f=a>u?t[i]:t[o],n&&r&&f>r&&(t[i]?f=t[i]:f=t[s-1]),f}return t[t.length-1]}})},"3.18.1",{requires:["dd-drag"]}); PK\AoGG#3.18.1/dd-constrain/dd-constrain.jsnu[YUI.add('dd-constrain', function (Y, NAME) { /** * The Drag & Drop Utility allows you to create a draggable interface efficiently, * buffering you from browser-level abnormalities and enabling you to focus on the interesting * logic surrounding your particular implementation. This component enables you to create a * variety of standard draggable objects with just a few lines of code and then, * using its extensive API, add your own specific implementation logic. * @module dd * @main dd * @submodule dd-constrain */ /** * Plugin for the dd-drag module to add the constraining methods to it. * It supports constraining to a node or viewport. It supports tick based moves and XY axis constraints. * @class DDConstrained * @extends Base * @constructor * @namespace Plugin */ var DRAG_NODE = 'dragNode', OFFSET_HEIGHT = 'offsetHeight', OFFSET_WIDTH = 'offsetWidth', HOST = 'host', TICK_X_ARRAY = 'tickXArray', TICK_Y_ARRAY = 'tickYArray', DDM = Y.DD.DDM, TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', VIEW = 'view', proto = null, /** * Fires when this node is aligned with the tickX value. * @event drag:tickAlignX * @param {EventFacade} event An Event Facade object * @type {CustomEvent} */ EV_TICK_ALIGN_X = 'drag:tickAlignX', /** * Fires when this node is aligned with the tickY value. * @event drag:tickAlignY * @param {EventFacade} event An Event Facade object * @type {CustomEvent} */ EV_TICK_ALIGN_Y = 'drag:tickAlignY', C = function() { this._lazyAddAttrs = false; C.superclass.constructor.apply(this, arguments); }; C.NAME = 'ddConstrained'; /** * The Constrained instance will be placed on the Drag instance under the con namespace. * @property NS * @default con * @readonly * @protected * @static * @type {String} */ C.NS = 'con'; C.ATTRS = { host: { }, /** * Stick the drag movement to the X-Axis. Default: false * @attribute stickX * @type Boolean */ stickX: { value: false }, /** * Stick the drag movement to the Y-Axis * @type Boolean * @attribute stickY */ stickY: { value: false }, /** * The X tick offset the drag node should snap to on each drag move. False for no ticks. Default: false * @type Number/false * @attribute tickX */ tickX: { value: false }, /** * The Y tick offset the drag node should snap to on each drag move. False for no ticks. Default: false * @type Number/false * @attribute tickY */ tickY: { value: false }, /** * An array of page coordinates to use as X ticks for drag movement. * @type Array * @attribute tickXArray */ tickXArray: { value: false }, /** * An array of page coordinates to use as Y ticks for drag movement. * @type Array * @attribute tickYArray */ tickYArray: { value: false }, /** * CSS style string for the gutter of a region (supports negative values): '5 0' * (sets top and bottom to 5px, left and right to 0px), '1 2 3 4' (top 1px, right 2px, bottom 3px, left 4px) * @attribute gutter * @type String */ gutter: { value: '0', setter: function(gutter) { return Y.DD.DDM.cssSizestoObject(gutter); } }, /** * Will attempt to constrain the drag node to the boundaries. Arguments:
* 'view': Contrain to Viewport
* '#selector_string': Constrain to this node
* '{Region Object}': An Object Literal containing a valid region (top, right, bottom, left) of page positions * @attribute constrain * @type {String/Object/Node} */ constrain: { value: VIEW, setter: function(con) { var node = Y.one(con); if (node) { con = node; } return con; } }, /** * An Object Literal containing a valid region (top, right, bottom, left) of page positions to constrain the drag node to. * @deprecated * @attribute constrain2region * @type Object */ constrain2region: { setter: function(r) { return this.set('constrain', r); } }, /** * Will attempt to constrain the drag node to the boundaries of this node. * @deprecated * @attribute constrain2node * @type Object */ constrain2node: { setter: function(n) { return this.set('constrain', Y.one(n)); } }, /** * Will attempt to constrain the drag node to the boundaries of the viewport region. * @deprecated * @attribute constrain2view * @type Object */ constrain2view: { setter: function() { return this.set('constrain', VIEW); } }, /** * Should the region be cached for performace. Default: true * @attribute cacheRegion * @type Boolean */ cacheRegion: { value: true } }; proto = { _lastTickXFired: null, _lastTickYFired: null, initializer: function() { this._createEvents(); this._eventHandles = [ this.get(HOST).on('drag:end', Y.bind(this._handleEnd, this)), this.get(HOST).on('drag:start', Y.bind(this._handleStart, this)), this.get(HOST).after('drag:align', Y.bind(this.align, this)), this.get(HOST).after('drag:drag', Y.bind(this.drag, this)) ]; }, destructor: function() { Y.Array.each( this._eventHandles, function(handle) { handle.detach(); } ); this._eventHandles.length = 0; }, /** * This method creates all the events for this Event Target and publishes them so we get Event Bubbling. * @private * @method _createEvents */ _createEvents: function() { var ev = [ EV_TICK_ALIGN_X, EV_TICK_ALIGN_Y ]; Y.Array.each(ev, function(v) { this.publish(v, { type: v, emitFacade: true, bubbles: true, queuable: false, prefix: 'drag' }); }, this); }, /** * Fires on drag:end * @private * @method _handleEnd */ _handleEnd: function() { this._lastTickYFired = null; this._lastTickXFired = null; }, /** * Fires on drag:start and clears the _regionCache * @private * @method _handleStart */ _handleStart: function() { this.resetCache(); }, /** * Store a cache of the region that we are constraining to * @private * @property _regionCache * @type Object */ _regionCache: null, /** * Get's the region and caches it, called from window.resize and when the cache is null * @private * @method _cacheRegion */ _cacheRegion: function() { this._regionCache = this.get('constrain').get('region'); }, /** * Reset the internal region cache. * @method resetCache */ resetCache: function() { this._regionCache = null; }, /** * Standardizes the 'constraint' attribute * @private * @method _getConstraint */ _getConstraint: function() { var con = this.get('constrain'), g = this.get('gutter'), region; if (con) { if (con instanceof Y.Node) { if (!this._regionCache) { this._eventHandles.push(Y.on('resize', Y.bind(this._cacheRegion, this), Y.config.win)); this._cacheRegion(); } region = Y.clone(this._regionCache); if (!this.get('cacheRegion')) { this.resetCache(); } } else if (Y.Lang.isObject(con)) { region = Y.clone(con); } } if (!con || !region) { con = VIEW; } if (con === VIEW) { region = this.get(HOST).get(DRAG_NODE).get('viewportRegion'); } Y.Object.each(g, function(i, n) { if ((n === RIGHT) || (n === BOTTOM)) { region[n] -= i; } else { region[n] += i; } }); return region; }, /** * Get the active region: viewport, node, custom region * @method getRegion * @param {Boolean} inc Include the node's height and width * @return {Object} The active region. */ getRegion: function(inc) { var r = {}, oh = null, ow = null, host = this.get(HOST); r = this._getConstraint(); if (inc) { oh = host.get(DRAG_NODE).get(OFFSET_HEIGHT); ow = host.get(DRAG_NODE).get(OFFSET_WIDTH); r[RIGHT] = r[RIGHT] - ow; r[BOTTOM] = r[BOTTOM] - oh; } return r; }, /** * Check if xy is inside a given region, if not change to it be inside. * @private * @method _checkRegion * @param {Array} _xy The XY to check if it's in the current region, if it isn't * inside the region, it will reset the xy array to be inside the region. * @return {Array} The new XY that is inside the region */ _checkRegion: function(_xy) { var oxy = _xy, r = this.getRegion(), host = this.get(HOST), oh = host.get(DRAG_NODE).get(OFFSET_HEIGHT), ow = host.get(DRAG_NODE).get(OFFSET_WIDTH); if (oxy[1] > (r[BOTTOM] - oh)) { _xy[1] = (r[BOTTOM] - oh); } if (r[TOP] > oxy[1]) { _xy[1] = r[TOP]; } if (oxy[0] > (r[RIGHT] - ow)) { _xy[0] = (r[RIGHT] - ow); } if (r[LEFT] > oxy[0]) { _xy[0] = r[LEFT]; } return _xy; }, /** * Checks if the XY passed or the dragNode is inside the active region. * @method inRegion * @param {Array} xy Optional XY to check, if not supplied this.get('dragNode').getXY() is used. * @return {Boolean} True if the XY is inside the region, false otherwise. */ inRegion: function(xy) { xy = xy || this.get(HOST).get(DRAG_NODE).getXY(); var _xy = this._checkRegion([xy[0], xy[1]]), inside = false; if ((xy[0] === _xy[0]) && (xy[1] === _xy[1])) { inside = true; } return inside; }, /** * Modifies the Drag.actXY method from the after drag:align event. This is where the constraining happens. * @method align */ align: function() { var host = this.get(HOST), _xy = [host.actXY[0], host.actXY[1]], r = this.getRegion(true); if (this.get('stickX')) { _xy[1] = (host.startXY[1] - host.deltaXY[1]); } if (this.get('stickY')) { _xy[0] = (host.startXY[0] - host.deltaXY[0]); } if (r) { _xy = this._checkRegion(_xy); } _xy = this._checkTicks(_xy, r); host.actXY = _xy; }, /** * Fires after drag:drag. Handle the tickX and tickX align events. * @method drag */ drag: function() { var host = this.get(HOST), xt = this.get('tickX'), yt = this.get('tickY'), _xy = [host.actXY[0], host.actXY[1]]; if ((Y.Lang.isNumber(xt) || this.get(TICK_X_ARRAY)) && (this._lastTickXFired !== _xy[0])) { this._tickAlignX(); this._lastTickXFired = _xy[0]; } if ((Y.Lang.isNumber(yt) || this.get(TICK_Y_ARRAY)) && (this._lastTickYFired !== _xy[1])) { this._tickAlignY(); this._lastTickYFired = _xy[1]; } }, /** * This method delegates the proper helper method for tick calculations * @private * @method _checkTicks * @param {Array} xy The XY coords for the Drag * @param {Object} r The optional region that we are bound to. * @return {Array} The calced XY coords */ _checkTicks: function(xy, r) { var host = this.get(HOST), lx = (host.startXY[0] - host.deltaXY[0]), ly = (host.startXY[1] - host.deltaXY[1]), xt = this.get('tickX'), yt = this.get('tickY'); if (xt && !this.get(TICK_X_ARRAY)) { xy[0] = DDM._calcTicks(xy[0], lx, xt, r[LEFT], r[RIGHT]); } if (yt && !this.get(TICK_Y_ARRAY)) { xy[1] = DDM._calcTicks(xy[1], ly, yt, r[TOP], r[BOTTOM]); } if (this.get(TICK_X_ARRAY)) { xy[0] = DDM._calcTickArray(xy[0], this.get(TICK_X_ARRAY), r[LEFT], r[RIGHT]); } if (this.get(TICK_Y_ARRAY)) { xy[1] = DDM._calcTickArray(xy[1], this.get(TICK_Y_ARRAY), r[TOP], r[BOTTOM]); } return xy; }, /** * Fires when the actXY[0] reach a new value respecting the tickX gap. * @private * @method _tickAlignX */ _tickAlignX: function() { this.fire(EV_TICK_ALIGN_X); }, /** * Fires when the actXY[1] reach a new value respecting the tickY gap. * @private * @method _tickAlignY */ _tickAlignY: function() { this.fire(EV_TICK_ALIGN_Y); } }; Y.namespace('Plugin'); Y.extend(C, Y.Base, proto); Y.Plugin.DDConstrained = C; Y.mix(DDM, { /** * Helper method to calculate the tick offsets for a given position * @for DDM * @namespace DD * @private * @method _calcTicks * @param {Number} pos The current X or Y position * @param {Number} start The start X or Y position * @param {Number} tick The X or Y tick increment * @param {Number} off1 The min offset that we can't pass (region) * @param {Number} off2 The max offset that we can't pass (region) * @return {Number} The new position based on the tick calculation */ _calcTicks: function(pos, start, tick, off1, off2) { var ix = ((pos - start) / tick), min = Math.floor(ix), max = Math.ceil(ix); if ((min !== 0) || (max !== 0)) { if ((ix >= min) && (ix <= max)) { pos = (start + (tick * min)); if (off1 && off2) { if (pos < off1) { pos = (start + (tick * (min + 1))); } if (pos > off2) { pos = (start + (tick * (min - 1))); } } } } return pos; }, /** * This method is used with the tickXArray and tickYArray config options * @for DDM * @namespace DD * @private * @method _calcTickArray * @param {Number} pos The current X or Y position * @param {Number} ticks The array containing our custom tick positions. * @param {Number} off1 The min offset that we can't pass (region) * @param {Number} off2 The max offset that we can't pass (region) * @return The tick position */ _calcTickArray: function(pos, ticks, off1, off2) { var i = 0, len = ticks.length, next = 0, diff1, diff2, ret; if (!ticks || (ticks.length === 0)) { return pos; } if (ticks[0] >= pos) { return ticks[0]; } for (i = 0; i < len; i++) { next = (i + 1); if (ticks[next] && ticks[next] >= pos) { diff1 = pos - ticks[i]; diff2 = ticks[next] - pos; ret = (diff2 > diff1) ? ticks[i] : ticks[next]; if (off1 && off2) { if (ret > off2) { if (ticks[i]) { ret = ticks[i]; } else { ret = ticks[len - 1]; } } } return ret; } } return ticks[ticks.length - 1]; } }); }, '3.18.1', {"requires": ["dd-drag"]}); PK\AoGG)3.18.1/dd-constrain/dd-constrain-debug.jsnu[YUI.add('dd-constrain', function (Y, NAME) { /** * The Drag & Drop Utility allows you to create a draggable interface efficiently, * buffering you from browser-level abnormalities and enabling you to focus on the interesting * logic surrounding your particular implementation. This component enables you to create a * variety of standard draggable objects with just a few lines of code and then, * using its extensive API, add your own specific implementation logic. * @module dd * @main dd * @submodule dd-constrain */ /** * Plugin for the dd-drag module to add the constraining methods to it. * It supports constraining to a node or viewport. It supports tick based moves and XY axis constraints. * @class DDConstrained * @extends Base * @constructor * @namespace Plugin */ var DRAG_NODE = 'dragNode', OFFSET_HEIGHT = 'offsetHeight', OFFSET_WIDTH = 'offsetWidth', HOST = 'host', TICK_X_ARRAY = 'tickXArray', TICK_Y_ARRAY = 'tickYArray', DDM = Y.DD.DDM, TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', VIEW = 'view', proto = null, /** * Fires when this node is aligned with the tickX value. * @event drag:tickAlignX * @param {EventFacade} event An Event Facade object * @type {CustomEvent} */ EV_TICK_ALIGN_X = 'drag:tickAlignX', /** * Fires when this node is aligned with the tickY value. * @event drag:tickAlignY * @param {EventFacade} event An Event Facade object * @type {CustomEvent} */ EV_TICK_ALIGN_Y = 'drag:tickAlignY', C = function() { this._lazyAddAttrs = false; C.superclass.constructor.apply(this, arguments); }; C.NAME = 'ddConstrained'; /** * The Constrained instance will be placed on the Drag instance under the con namespace. * @property NS * @default con * @readonly * @protected * @static * @type {String} */ C.NS = 'con'; C.ATTRS = { host: { }, /** * Stick the drag movement to the X-Axis. Default: false * @attribute stickX * @type Boolean */ stickX: { value: false }, /** * Stick the drag movement to the Y-Axis * @type Boolean * @attribute stickY */ stickY: { value: false }, /** * The X tick offset the drag node should snap to on each drag move. False for no ticks. Default: false * @type Number/false * @attribute tickX */ tickX: { value: false }, /** * The Y tick offset the drag node should snap to on each drag move. False for no ticks. Default: false * @type Number/false * @attribute tickY */ tickY: { value: false }, /** * An array of page coordinates to use as X ticks for drag movement. * @type Array * @attribute tickXArray */ tickXArray: { value: false }, /** * An array of page coordinates to use as Y ticks for drag movement. * @type Array * @attribute tickYArray */ tickYArray: { value: false }, /** * CSS style string for the gutter of a region (supports negative values): '5 0' * (sets top and bottom to 5px, left and right to 0px), '1 2 3 4' (top 1px, right 2px, bottom 3px, left 4px) * @attribute gutter * @type String */ gutter: { value: '0', setter: function(gutter) { return Y.DD.DDM.cssSizestoObject(gutter); } }, /** * Will attempt to constrain the drag node to the boundaries. Arguments:
* 'view': Contrain to Viewport
* '#selector_string': Constrain to this node
* '{Region Object}': An Object Literal containing a valid region (top, right, bottom, left) of page positions * @attribute constrain * @type {String/Object/Node} */ constrain: { value: VIEW, setter: function(con) { var node = Y.one(con); if (node) { con = node; } return con; } }, /** * An Object Literal containing a valid region (top, right, bottom, left) of page positions to constrain the drag node to. * @deprecated * @attribute constrain2region * @type Object */ constrain2region: { setter: function(r) { return this.set('constrain', r); } }, /** * Will attempt to constrain the drag node to the boundaries of this node. * @deprecated * @attribute constrain2node * @type Object */ constrain2node: { setter: function(n) { return this.set('constrain', Y.one(n)); } }, /** * Will attempt to constrain the drag node to the boundaries of the viewport region. * @deprecated * @attribute constrain2view * @type Object */ constrain2view: { setter: function() { return this.set('constrain', VIEW); } }, /** * Should the region be cached for performace. Default: true * @attribute cacheRegion * @type Boolean */ cacheRegion: { value: true } }; proto = { _lastTickXFired: null, _lastTickYFired: null, initializer: function() { this._createEvents(); this._eventHandles = [ this.get(HOST).on('drag:end', Y.bind(this._handleEnd, this)), this.get(HOST).on('drag:start', Y.bind(this._handleStart, this)), this.get(HOST).after('drag:align', Y.bind(this.align, this)), this.get(HOST).after('drag:drag', Y.bind(this.drag, this)) ]; }, destructor: function() { Y.Array.each( this._eventHandles, function(handle) { handle.detach(); } ); this._eventHandles.length = 0; }, /** * This method creates all the events for this Event Target and publishes them so we get Event Bubbling. * @private * @method _createEvents */ _createEvents: function() { var ev = [ EV_TICK_ALIGN_X, EV_TICK_ALIGN_Y ]; Y.Array.each(ev, function(v) { this.publish(v, { type: v, emitFacade: true, bubbles: true, queuable: false, prefix: 'drag' }); }, this); }, /** * Fires on drag:end * @private * @method _handleEnd */ _handleEnd: function() { this._lastTickYFired = null; this._lastTickXFired = null; }, /** * Fires on drag:start and clears the _regionCache * @private * @method _handleStart */ _handleStart: function() { this.resetCache(); }, /** * Store a cache of the region that we are constraining to * @private * @property _regionCache * @type Object */ _regionCache: null, /** * Get's the region and caches it, called from window.resize and when the cache is null * @private * @method _cacheRegion */ _cacheRegion: function() { this._regionCache = this.get('constrain').get('region'); }, /** * Reset the internal region cache. * @method resetCache */ resetCache: function() { this._regionCache = null; }, /** * Standardizes the 'constraint' attribute * @private * @method _getConstraint */ _getConstraint: function() { var con = this.get('constrain'), g = this.get('gutter'), region; if (con) { if (con instanceof Y.Node) { if (!this._regionCache) { this._eventHandles.push(Y.on('resize', Y.bind(this._cacheRegion, this), Y.config.win)); this._cacheRegion(); } region = Y.clone(this._regionCache); if (!this.get('cacheRegion')) { this.resetCache(); } } else if (Y.Lang.isObject(con)) { region = Y.clone(con); } } if (!con || !region) { con = VIEW; } if (con === VIEW) { region = this.get(HOST).get(DRAG_NODE).get('viewportRegion'); } Y.Object.each(g, function(i, n) { if ((n === RIGHT) || (n === BOTTOM)) { region[n] -= i; } else { region[n] += i; } }); return region; }, /** * Get the active region: viewport, node, custom region * @method getRegion * @param {Boolean} inc Include the node's height and width * @return {Object} The active region. */ getRegion: function(inc) { var r = {}, oh = null, ow = null, host = this.get(HOST); r = this._getConstraint(); if (inc) { oh = host.get(DRAG_NODE).get(OFFSET_HEIGHT); ow = host.get(DRAG_NODE).get(OFFSET_WIDTH); r[RIGHT] = r[RIGHT] - ow; r[BOTTOM] = r[BOTTOM] - oh; } return r; }, /** * Check if xy is inside a given region, if not change to it be inside. * @private * @method _checkRegion * @param {Array} _xy The XY to check if it's in the current region, if it isn't * inside the region, it will reset the xy array to be inside the region. * @return {Array} The new XY that is inside the region */ _checkRegion: function(_xy) { var oxy = _xy, r = this.getRegion(), host = this.get(HOST), oh = host.get(DRAG_NODE).get(OFFSET_HEIGHT), ow = host.get(DRAG_NODE).get(OFFSET_WIDTH); if (oxy[1] > (r[BOTTOM] - oh)) { _xy[1] = (r[BOTTOM] - oh); } if (r[TOP] > oxy[1]) { _xy[1] = r[TOP]; } if (oxy[0] > (r[RIGHT] - ow)) { _xy[0] = (r[RIGHT] - ow); } if (r[LEFT] > oxy[0]) { _xy[0] = r[LEFT]; } return _xy; }, /** * Checks if the XY passed or the dragNode is inside the active region. * @method inRegion * @param {Array} xy Optional XY to check, if not supplied this.get('dragNode').getXY() is used. * @return {Boolean} True if the XY is inside the region, false otherwise. */ inRegion: function(xy) { xy = xy || this.get(HOST).get(DRAG_NODE).getXY(); var _xy = this._checkRegion([xy[0], xy[1]]), inside = false; if ((xy[0] === _xy[0]) && (xy[1] === _xy[1])) { inside = true; } return inside; }, /** * Modifies the Drag.actXY method from the after drag:align event. This is where the constraining happens. * @method align */ align: function() { var host = this.get(HOST), _xy = [host.actXY[0], host.actXY[1]], r = this.getRegion(true); if (this.get('stickX')) { _xy[1] = (host.startXY[1] - host.deltaXY[1]); } if (this.get('stickY')) { _xy[0] = (host.startXY[0] - host.deltaXY[0]); } if (r) { _xy = this._checkRegion(_xy); } _xy = this._checkTicks(_xy, r); host.actXY = _xy; }, /** * Fires after drag:drag. Handle the tickX and tickX align events. * @method drag */ drag: function() { var host = this.get(HOST), xt = this.get('tickX'), yt = this.get('tickY'), _xy = [host.actXY[0], host.actXY[1]]; if ((Y.Lang.isNumber(xt) || this.get(TICK_X_ARRAY)) && (this._lastTickXFired !== _xy[0])) { this._tickAlignX(); this._lastTickXFired = _xy[0]; } if ((Y.Lang.isNumber(yt) || this.get(TICK_Y_ARRAY)) && (this._lastTickYFired !== _xy[1])) { this._tickAlignY(); this._lastTickYFired = _xy[1]; } }, /** * This method delegates the proper helper method for tick calculations * @private * @method _checkTicks * @param {Array} xy The XY coords for the Drag * @param {Object} r The optional region that we are bound to. * @return {Array} The calced XY coords */ _checkTicks: function(xy, r) { var host = this.get(HOST), lx = (host.startXY[0] - host.deltaXY[0]), ly = (host.startXY[1] - host.deltaXY[1]), xt = this.get('tickX'), yt = this.get('tickY'); if (xt && !this.get(TICK_X_ARRAY)) { xy[0] = DDM._calcTicks(xy[0], lx, xt, r[LEFT], r[RIGHT]); } if (yt && !this.get(TICK_Y_ARRAY)) { xy[1] = DDM._calcTicks(xy[1], ly, yt, r[TOP], r[BOTTOM]); } if (this.get(TICK_X_ARRAY)) { xy[0] = DDM._calcTickArray(xy[0], this.get(TICK_X_ARRAY), r[LEFT], r[RIGHT]); } if (this.get(TICK_Y_ARRAY)) { xy[1] = DDM._calcTickArray(xy[1], this.get(TICK_Y_ARRAY), r[TOP], r[BOTTOM]); } return xy; }, /** * Fires when the actXY[0] reach a new value respecting the tickX gap. * @private * @method _tickAlignX */ _tickAlignX: function() { this.fire(EV_TICK_ALIGN_X); }, /** * Fires when the actXY[1] reach a new value respecting the tickY gap. * @private * @method _tickAlignY */ _tickAlignY: function() { this.fire(EV_TICK_ALIGN_Y); } }; Y.namespace('Plugin'); Y.extend(C, Y.Base, proto); Y.Plugin.DDConstrained = C; Y.mix(DDM, { /** * Helper method to calculate the tick offsets for a given position * @for DDM * @namespace DD * @private * @method _calcTicks * @param {Number} pos The current X or Y position * @param {Number} start The start X or Y position * @param {Number} tick The X or Y tick increment * @param {Number} off1 The min offset that we can't pass (region) * @param {Number} off2 The max offset that we can't pass (region) * @return {Number} The new position based on the tick calculation */ _calcTicks: function(pos, start, tick, off1, off2) { var ix = ((pos - start) / tick), min = Math.floor(ix), max = Math.ceil(ix); if ((min !== 0) || (max !== 0)) { if ((ix >= min) && (ix <= max)) { pos = (start + (tick * min)); if (off1 && off2) { if (pos < off1) { pos = (start + (tick * (min + 1))); } if (pos > off2) { pos = (start + (tick * (min - 1))); } } } } return pos; }, /** * This method is used with the tickXArray and tickYArray config options * @for DDM * @namespace DD * @private * @method _calcTickArray * @param {Number} pos The current X or Y position * @param {Number} ticks The array containing our custom tick positions. * @param {Number} off1 The min offset that we can't pass (region) * @param {Number} off2 The max offset that we can't pass (region) * @return The tick position */ _calcTickArray: function(pos, ticks, off1, off2) { var i = 0, len = ticks.length, next = 0, diff1, diff2, ret; if (!ticks || (ticks.length === 0)) { return pos; } if (ticks[0] >= pos) { return ticks[0]; } for (i = 0; i < len; i++) { next = (i + 1); if (ticks[next] && ticks[next] >= pos) { diff1 = pos - ticks[i]; diff2 = ticks[next] - pos; ret = (diff2 > diff1) ? ticks[i] : ticks[next]; if (off1 && off2) { if (ret > off2) { if (ticks[i]) { ret = ticks[i]; } else { ret = ticks[len - 1]; } } } return ret; } } return ticks[ticks.length - 1]; } }); }, '3.18.1', {"requires": ["dd-drag"]}); PK\߲'3.18.1/series-line/series-line-debug.jsnu[YUI.add('series-line', function (Y, NAME) { /** * Provides functionality for creating a line series. * * @module charts * @submodule series-line */ /** * The LineSeries class renders quantitative data on a graph by connecting relevant data points. * * @class LineSeries * @extends CartesianSeries * @uses Lines * @constructor * @param {Object} config (optional) Configuration parameters. * @submodule series-line */ Y.LineSeries = Y.Base.create("lineSeries", Y.CartesianSeries, [Y.Lines], { /** * @protected * * @method drawSeries */ drawSeries: function() { this.drawLines(); }, /** * @protected * * Method used by `styles` setter. Overrides base implementation. * * @method _setStyles * @param {Object} newStyles Hash of properties to update. * @return Object */ _setStyles: function(val) { if(!val.line) { val = {line:val}; } return Y.LineSeries.superclass._setStyles.apply(this, [val]); }, /** * @protected * * Gets the default value for the `styles` attribute. Overrides * base implementation. * * @method _getDefaultStyles * @return Object */ _getDefaultStyles: function() { var styles = this._mergeStyles({line:this._getLineDefaults()}, Y.LineSeries.superclass._getDefaultStyles()); return styles; } }, { ATTRS: { /** * Read-only attribute indicating the type of series. * * @attribute type * @type String * @default line */ type: { value:"line" } /** * Style properties used for drawing lines. This attribute is inherited from `Renderer`. Below are the * default values: *
*
color
The color of the line. The default value is determined by the order of the series * on the graph. The color will be retrieved from the following array: * `["#426ab3", "#d09b2c", "#000000", "#b82837", "#b384b5", "#ff7200", "#779de3", "#cbc8ba", "#7ed7a6", "#007a6c"]` *
weight
Number that indicates the width of the line. The default value is 6.
*
alpha
Number between 0 and 1 that indicates the opacity of the line. The default value is 1.
*
lineType
Indicates whether the line is solid or dashed. The default value is solid.
*
dashLength
When the `lineType` is dashed, indicates the length of the dash. The default * value is 10.
*
gapSpace
When the `lineType` is dashed, indicates the distance between dashes. The default * value is 10.
*
connectDiscontinuousPoints
Indicates whether or not to connect lines when there is a missing * or null value between points. The default value is true.
*
discontinuousType
Indicates whether the line between discontinuous points is solid or dashed. * The default value is solid.
*
discontinuousDashLength
When the `discontinuousType` is dashed, indicates the length of the * dash. The default value is 10.
*
discontinuousGapSpace
When the `discontinuousType` is dashed, indicates the distance between * dashes. The default value is 10.
*
* * @attribute styles * @type Object */ } }); }, '3.18.1', {"requires": ["series-cartesian", "series-line-util"]}); PK\߲!3.18.1/series-line/series-line.jsnu[YUI.add('series-line', function (Y, NAME) { /** * Provides functionality for creating a line series. * * @module charts * @submodule series-line */ /** * The LineSeries class renders quantitative data on a graph by connecting relevant data points. * * @class LineSeries * @extends CartesianSeries * @uses Lines * @constructor * @param {Object} config (optional) Configuration parameters. * @submodule series-line */ Y.LineSeries = Y.Base.create("lineSeries", Y.CartesianSeries, [Y.Lines], { /** * @protected * * @method drawSeries */ drawSeries: function() { this.drawLines(); }, /** * @protected * * Method used by `styles` setter. Overrides base implementation. * * @method _setStyles * @param {Object} newStyles Hash of properties to update. * @return Object */ _setStyles: function(val) { if(!val.line) { val = {line:val}; } return Y.LineSeries.superclass._setStyles.apply(this, [val]); }, /** * @protected * * Gets the default value for the `styles` attribute. Overrides * base implementation. * * @method _getDefaultStyles * @return Object */ _getDefaultStyles: function() { var styles = this._mergeStyles({line:this._getLineDefaults()}, Y.LineSeries.superclass._getDefaultStyles()); return styles; } }, { ATTRS: { /** * Read-only attribute indicating the type of series. * * @attribute type * @type String * @default line */ type: { value:"line" } /** * Style properties used for drawing lines. This attribute is inherited from `Renderer`. Below are the * default values: *
*
color
The color of the line. The default value is determined by the order of the series * on the graph. The color will be retrieved from the following array: * `["#426ab3", "#d09b2c", "#000000", "#b82837", "#b384b5", "#ff7200", "#779de3", "#cbc8ba", "#7ed7a6", "#007a6c"]` *
weight
Number that indicates the width of the line. The default value is 6.
*
alpha
Number between 0 and 1 that indicates the opacity of the line. The default value is 1.
*
lineType
Indicates whether the line is solid or dashed. The default value is solid.
*
dashLength
When the `lineType` is dashed, indicates the length of the dash. The default * value is 10.
*
gapSpace
When the `lineType` is dashed, indicates the distance between dashes. The default * value is 10.
*
connectDiscontinuousPoints
Indicates whether or not to connect lines when there is a missing * or null value between points. The default value is true.
*
discontinuousType
Indicates whether the line between discontinuous points is solid or dashed. * The default value is solid.
*
discontinuousDashLength
When the `discontinuousType` is dashed, indicates the length of the * dash. The default value is 10.
*
discontinuousGapSpace
When the `discontinuousType` is dashed, indicates the distance between * dashes. The default value is 10.
*
* * @attribute styles * @type Object */ } }); }, '3.18.1', {"requires": ["series-cartesian", "series-line-util"]}); PK\7%3.18.1/series-line/series-line-min.jsnu[YUI.add("series-line",function(e,t){e.LineSeries=e.Base.create("lineSeries",e.CartesianSeries,[e.Lines],{drawSeries:function(){this.drawLines()},_setStyles:function(t){return t.line||(t={line:t}),e.LineSeries.superclass._setStyles.apply(this,[t])},_getDefaultStyles:function(){var t=this._mergeStyles({line:this._getLineDefaults()},e.LineSeries.superclass._getDefaultStyles());return t}},{ATTRS:{type:{value:"line"}}})},"3.18.1",{requires:["series-cartesian","series-line-util"]}); PK\93.18.1/autocomplete-filters/autocomplete-filters-debug.jsnu[YUI.add('autocomplete-filters', function (Y, NAME) { /** Provides pre-built result matching filters for AutoComplete. @module autocomplete @submodule autocomplete-filters @class AutoCompleteFilters @static **/ var YArray = Y.Array, YObject = Y.Object, WordBreak = Y.Text.WordBreak, Filters = Y.mix(Y.namespace('AutoCompleteFilters'), { // -- Public Methods ------------------------------------------------------- /** Returns an array of results that contain all of the characters in the query, in any order (not necessarily consecutive). Case-insensitive. @method charMatch @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ charMatch: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // charMatchCase(). It's intentionally undocumented. if (!query) { return results; } var queryChars = YArray.unique((caseSensitive ? query : query.toLowerCase()).split('')); return YArray.filter(results, function (result) { result = result.text; if (!caseSensitive) { result = result.toLowerCase(); } return YArray.every(queryChars, function (chr) { return result.indexOf(chr) !== -1; }); }); }, /** Case-sensitive version of `charMatch()`. @method charMatchCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ charMatchCase: function (query, results) { return Filters.charMatch(query, results, true); }, /** Returns an array of results that contain the complete query as a phrase. Case-insensitive. @method phraseMatch @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ phraseMatch: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // phraseMatchCase(). It's intentionally undocumented. if (!query) { return results; } if (!caseSensitive) { query = query.toLowerCase(); } return YArray.filter(results, function (result) { return (caseSensitive ? result.text : result.text.toLowerCase()).indexOf(query) !== -1; }); }, /** Case-sensitive version of `phraseMatch()`. @method phraseMatchCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ phraseMatchCase: function (query, results) { return Filters.phraseMatch(query, results, true); }, /** Returns an array of results that start with the complete query as a phrase. Case-insensitive. @method startsWith @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ startsWith: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // startsWithCase(). It's intentionally undocumented. if (!query) { return results; } if (!caseSensitive) { query = query.toLowerCase(); } return YArray.filter(results, function (result) { return (caseSensitive ? result.text : result.text.toLowerCase()).indexOf(query) === 0; }); }, /** Case-sensitive version of `startsWith()`. @method startsWithCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ startsWithCase: function (query, results) { return Filters.startsWith(query, results, true); }, /** Returns an array of results in which all the words of the query match either whole words or parts of words in the result. Non-word characters like whitespace and certain punctuation are ignored. Case-insensitive. This is basically a combination of `wordMatch()` (by ignoring whitespace and word order) and `phraseMatch()` (by allowing partial matching instead of requiring the entire word to match). Example use case: Trying to find personal names independently of name order (Western or Eastern order) and supporting immediate feedback by allowing partial occurences. So queries like "J. Doe", "Doe, John", and "J. D." would all match "John Doe". @method subWordMatch @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ subWordMatch: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // subWordMatchCase(). It's intentionally undocumented. if (!query) { return results; } var queryWords = WordBreak.getUniqueWords(query, { ignoreCase: !caseSensitive }); return YArray.filter(results, function (result) { var resultText = caseSensitive ? result.text : result.text.toLowerCase(); return YArray.every(queryWords, function (queryWord) { return resultText.indexOf(queryWord) !== -1; }); }); }, /** Case-sensitive version of `subWordMatch()`. @method subWordMatchCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ subWordMatchCase: function (query, results) { return Filters.subWordMatch(query, results, true); }, /** Returns an array of results that contain all of the words in the query, in any order. Non-word characters like whitespace and certain punctuation are ignored. Case-insensitive. @method wordMatch @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ wordMatch: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // wordMatchCase(). It's intentionally undocumented. if (!query) { return results; } var options = {ignoreCase: !caseSensitive}, queryWords = WordBreak.getUniqueWords(query, options); return YArray.filter(results, function (result) { // Convert resultWords array to a hash for fast lookup. var resultWords = YArray.hash(WordBreak.getUniqueWords(result.text, options)); return YArray.every(queryWords, function (word) { return YObject.owns(resultWords, word); }); }); }, /** Case-sensitive version of `wordMatch()`. @method wordMatchCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ wordMatchCase: function (query, results) { return Filters.wordMatch(query, results, true); } }); }, '3.18.1', {"requires": ["array-extras", "text-wordbreak"]}); PK\33.18.1/autocomplete-filters/autocomplete-filters.jsnu[YUI.add('autocomplete-filters', function (Y, NAME) { /** Provides pre-built result matching filters for AutoComplete. @module autocomplete @submodule autocomplete-filters @class AutoCompleteFilters @static **/ var YArray = Y.Array, YObject = Y.Object, WordBreak = Y.Text.WordBreak, Filters = Y.mix(Y.namespace('AutoCompleteFilters'), { // -- Public Methods ------------------------------------------------------- /** Returns an array of results that contain all of the characters in the query, in any order (not necessarily consecutive). Case-insensitive. @method charMatch @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ charMatch: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // charMatchCase(). It's intentionally undocumented. if (!query) { return results; } var queryChars = YArray.unique((caseSensitive ? query : query.toLowerCase()).split('')); return YArray.filter(results, function (result) { result = result.text; if (!caseSensitive) { result = result.toLowerCase(); } return YArray.every(queryChars, function (chr) { return result.indexOf(chr) !== -1; }); }); }, /** Case-sensitive version of `charMatch()`. @method charMatchCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ charMatchCase: function (query, results) { return Filters.charMatch(query, results, true); }, /** Returns an array of results that contain the complete query as a phrase. Case-insensitive. @method phraseMatch @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ phraseMatch: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // phraseMatchCase(). It's intentionally undocumented. if (!query) { return results; } if (!caseSensitive) { query = query.toLowerCase(); } return YArray.filter(results, function (result) { return (caseSensitive ? result.text : result.text.toLowerCase()).indexOf(query) !== -1; }); }, /** Case-sensitive version of `phraseMatch()`. @method phraseMatchCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ phraseMatchCase: function (query, results) { return Filters.phraseMatch(query, results, true); }, /** Returns an array of results that start with the complete query as a phrase. Case-insensitive. @method startsWith @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ startsWith: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // startsWithCase(). It's intentionally undocumented. if (!query) { return results; } if (!caseSensitive) { query = query.toLowerCase(); } return YArray.filter(results, function (result) { return (caseSensitive ? result.text : result.text.toLowerCase()).indexOf(query) === 0; }); }, /** Case-sensitive version of `startsWith()`. @method startsWithCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ startsWithCase: function (query, results) { return Filters.startsWith(query, results, true); }, /** Returns an array of results in which all the words of the query match either whole words or parts of words in the result. Non-word characters like whitespace and certain punctuation are ignored. Case-insensitive. This is basically a combination of `wordMatch()` (by ignoring whitespace and word order) and `phraseMatch()` (by allowing partial matching instead of requiring the entire word to match). Example use case: Trying to find personal names independently of name order (Western or Eastern order) and supporting immediate feedback by allowing partial occurences. So queries like "J. Doe", "Doe, John", and "J. D." would all match "John Doe". @method subWordMatch @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ subWordMatch: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // subWordMatchCase(). It's intentionally undocumented. if (!query) { return results; } var queryWords = WordBreak.getUniqueWords(query, { ignoreCase: !caseSensitive }); return YArray.filter(results, function (result) { var resultText = caseSensitive ? result.text : result.text.toLowerCase(); return YArray.every(queryWords, function (queryWord) { return resultText.indexOf(queryWord) !== -1; }); }); }, /** Case-sensitive version of `subWordMatch()`. @method subWordMatchCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ subWordMatchCase: function (query, results) { return Filters.subWordMatch(query, results, true); }, /** Returns an array of results that contain all of the words in the query, in any order. Non-word characters like whitespace and certain punctuation are ignored. Case-insensitive. @method wordMatch @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ wordMatch: function (query, results, caseSensitive) { // The caseSensitive parameter is only intended for use by // wordMatchCase(). It's intentionally undocumented. if (!query) { return results; } var options = {ignoreCase: !caseSensitive}, queryWords = WordBreak.getUniqueWords(query, options); return YArray.filter(results, function (result) { // Convert resultWords array to a hash for fast lookup. var resultWords = YArray.hash(WordBreak.getUniqueWords(result.text, options)); return YArray.every(queryWords, function (word) { return YObject.owns(resultWords, word); }); }); }, /** Case-sensitive version of `wordMatch()`. @method wordMatchCase @param {String} query Query to match @param {Array} results Results to filter @return {Array} Filtered results @static **/ wordMatchCase: function (query, results) { return Filters.wordMatch(query, results, true); } }); }, '3.18.1', {"requires": ["array-extras", "text-wordbreak"]}); PK\\zz73.18.1/autocomplete-filters/autocomplete-filters-min.jsnu[YUI.add("autocomplete-filters",function(e,t){var n=e.Array,r=e.Object,i=e.Text.WordBreak,s=e.mix(e.namespace("AutoCompleteFilters"),{charMatch:function(e,t,r){if(!e)return t;var i=n.unique((r?e:e.toLowerCase()).split(""));return n.filter(t,function(e){return e=e.text,r||(e=e.toLowerCase()),n.every(i,function(t){return e.indexOf(t)!==-1})})},charMatchCase:function(e,t){return s.charMatch(e,t,!0)},phraseMatch:function(e,t,r){return e?(r||(e=e.toLowerCase()),n.filter(t,function(t){return(r?t.text:t.text.toLowerCase()).indexOf(e)!==-1})):t},phraseMatchCase:function(e,t){return s.phraseMatch(e,t,!0)},startsWith:function(e,t,r){return e?(r||(e=e.toLowerCase()),n.filter(t,function(t){return(r?t.text:t.text.toLowerCase()).indexOf(e)===0})):t},startsWithCase:function(e,t){return s.startsWith(e,t,!0)},subWordMatch:function(e,t,r){if(!e)return t;var s=i.getUniqueWords(e,{ignoreCase:!r});return n.filter(t,function(e){var t=r?e.text:e.text.toLowerCase();return n.every(s,function(e){return t.indexOf(e)!==-1})})},subWordMatchCase:function(e,t){return s.subWordMatch(e,t,!0)},wordMatch:function(e,t,s){if(!e)return t;var o={ignoreCase:!s},u=i.getUniqueWords(e,o);return n.filter(t,function(e){var t=n.hash(i.getUniqueWords(e.text,o));return n.every(u,function(e){return r.owns(t,e)})})},wordMatchCase:function(e,t){return s.wordMatch(e,t,!0)}})},"3.18.1",{requires:["array-extras","text-wordbreak"]}); PK\ %3.18.1/editor-bidi/editor-bidi-min.jsnu[YUI.add("editor-bidi",function(e,t){var n=function(){n.superclass.constructor.apply(this,arguments)},r="host",i="dir",s="nodeChange",o="bidiContextChange",u="style";e.extend(n,e.Base,{lastDirection:null,firstEvent:null,_checkForChange:function(){var e=this.get(r),t=e.getInstance(),i=new t.EditorSelection,s,u;i.isCollapsed?(s=n.blockParent(i.focusNode,!1,t.EditorSelection.ROOT),s&&(u=s.getStyle("direction"),u!==this.lastDirection&&(e.fire(o,{changedTo:u}),this.lastDirection=u))):(e.fire(o,{changedTo:"select"}),this.lastDirection=null)},_afterNodeChange:function(e){if(this.firstEvent||n.EVENTS[e.changedType])this._checkForChange(),this.firstEvent=!1},_afterMouseUp:function(){this._checkForChange(),this.firstEvent=!1},initializer:function(){var t=this.get(r);this.firstEvent=!0,t.after(s,e.bind(this._afterNodeChange,this)),t.after("dom:mouseup",e.bind(this._afterMouseUp,this))}},{EVENTS:{"backspace-up":!0,"pageup-up":!0,"pagedown-down":!0,"end-up":!0,"home-up":!0,"left-up":!0,"up-up":!0,"right-up":!0,"down-up":!0,"delete-up":!0},BLOCKS:e.EditorSelection.BLOCKS,DIV_WRAPPER:"
",blockParent:function(t,r,i){var s=t,o,u;return i=i||e.EditorSelection.ROOT,s||(s=i),s.test(n.BLOCKS)||(s=s.ancestor(n.BLOCKS)),r&&s.compareTo(i)&&(o=e.Node.create(n.DIV_WRAPPER),s.get("children").each(function(e,t){t===0?u=e:o.append(e)}),u.replace(o),o.prepend(u),s=o),s},_NODE_SELECTED:"bidiSelected",addParents:function(t,r){var i,s,o;tester=function(e){if(!e.getData(n._NODE_SELECTED))return o=!1,!0},r=r||e.EditorSelection.ROOT;for(i=0;i', /** * Returns a block parent for a given element * @static * @method blockParent */ blockParent: function(node, wrap, root) { var parent = node, divNode, firstChild; root = root || Y.EditorSelection.ROOT; if (!parent) { parent = root; } if (!parent.test(EditorBidi.BLOCKS)) { parent = parent.ancestor(EditorBidi.BLOCKS); } if (wrap && parent.compareTo(root)) { // This shouldn't happen if the RTE handles everything // according to spec: we should get to a P before ROOT. But // we don't want to set the direction of ROOT even if that // happens, so we wrap everything in a DIV. // The code is based on YUI3's Y.EditorSelection._wrapBlock function. divNode = Y.Node.create(EditorBidi.DIV_WRAPPER); parent.get('children').each(function(node, index) { if (index === 0) { firstChild = node; } else { divNode.append(node); } }); firstChild.replace(divNode); divNode.prepend(firstChild); parent = divNode; } return parent; }, /** * The data key to store on the node. * @static * @property _NODE_SELECTED */ _NODE_SELECTED: 'bidiSelected', /** * Generates a list of all the block parents of the current NodeList * @static * @method addParents */ addParents: function(nodeArray, root) { var i, parent, addParent; tester = function(sibling) { if (!sibling.getData(EditorBidi._NODE_SELECTED)) { addParent = false; return true; // stop more processing } }; root = root || Y.EditorSelection.ROOT; for (i = 0; i < nodeArray.length; i += 1) { nodeArray[i].setData(EditorBidi._NODE_SELECTED, true); } // This works automagically, since new parents added get processed // later themselves. So if there's a node early in the process that // we haven't discovered some of its siblings yet, thus resulting in // its parent not added, the parent will be added later, since those // siblings will be added to the array and then get processed. for (i = 0; i < nodeArray.length; i += 1) { parent = nodeArray[i].get('parentNode'); // Don't add the parent if the parent is the ROOT element. // We don't want to change the direction of ROOT. Also don't // do it if the parent is already in the list. if (!root.compareTo(parent) && !parent.getData(EditorBidi._NODE_SELECTED)) { addParent = true; parent.get('children').some(tester); if (addParent) { nodeArray.push(parent); parent.setData(EditorBidi._NODE_SELECTED, true); } } } for (i = 0; i < nodeArray.length; i += 1) { nodeArray[i].clearData(EditorBidi._NODE_SELECTED); } return nodeArray; }, /** * editorBidi * @static * @property NAME */ NAME: 'editorBidi', /** * editorBidi * @static * @property NS */ NS: 'editorBidi', ATTRS: { host: { value: false } }, /** * Regex for testing/removing text-align style from an element * @static * @property RE_TEXT_ALIGN */ RE_TEXT_ALIGN: /text-align:\s*\w*\s*;/, /** * Method to test a node's style attribute for text-align and removing it. * @static * @method removeTextAlign */ removeTextAlign: function(n) { if (n) { if (n.getAttribute(STYLE).match(EditorBidi.RE_TEXT_ALIGN)) { n.setAttribute(STYLE, n.getAttribute(STYLE).replace(EditorBidi.RE_TEXT_ALIGN, '')); } if (n.hasAttribute('align')) { n.removeAttribute('align'); } } return n; } }); Y.namespace('Plugin'); Y.Plugin.EditorBidi = EditorBidi; /** * bidi execCommand override for setting the text direction of a node. * This property is added to the `Y.Plugin.ExecCommands.COMMANDS` * collection. * * @for Plugin.ExecCommand * @property bidi */ //TODO -- This should not add this command unless the plugin is added to the instance.. Y.Plugin.ExecCommand.COMMANDS.bidi = function(cmd, direction) { var inst = this.getInstance(), sel = new inst.EditorSelection(), ns = this.get(HOST).get(HOST).editorBidi, returnValue, block, b, root = inst.EditorSelection.ROOT, selected, selectedBlocks, dir; if (!ns) { Y.error('bidi execCommand is not available without the EditorBiDi plugin.'); return; } inst.EditorSelection.filterBlocks(); if (sel.isCollapsed) { // No selection block = EditorBidi.blockParent(sel.anchorNode, false, root); if (!block) { block = root.one(inst.EditorSelection.BLOCKS); } //Remove text-align attribute if it exists block = EditorBidi.removeTextAlign(block); if (!direction) { //If no direction is set, auto-detect the proper setting to make it "toggle" dir = block.getAttribute(DIR); if (!dir || dir === 'ltr') { direction = 'rtl'; } else { direction = 'ltr'; } } block.setAttribute(DIR, direction); if (Y.UA.ie) { b = block.all('br.yui-cursor'); if (b.size() === 1 && block.get('childNodes').size() === 1) { b.remove(); } } returnValue = block; } else { // some text is selected selected = sel.getSelected(); selectedBlocks = []; selected.each(function(node) { selectedBlocks.push(EditorBidi.blockParent(node, false, root)); }); selectedBlocks = inst.all(EditorBidi.addParents(selectedBlocks, root)); selectedBlocks.each(function(n) { var d = direction; //Remove text-align attribute if it exists n = EditorBidi.removeTextAlign(n); if (!d) { dir = n.getAttribute(DIR); if (!dir || dir === 'ltr') { d = 'rtl'; } else { d = 'ltr'; } } n.setAttribute(DIR, d); }); returnValue = selectedBlocks; } ns._checkForChange(); return returnValue; }; }, '3.18.1', {"requires": ["editor-base"]}); PK\RL--!3.18.1/editor-bidi/editor-bidi.jsnu[YUI.add('editor-bidi', function (Y, NAME) { /** * Plugin for Editor to support BiDirectional (bidi) text operations. * @class Plugin.EditorBidi * @extends Base * @constructor * @module editor * @submodule editor-bidi */ var EditorBidi = function() { EditorBidi.superclass.constructor.apply(this, arguments); }, HOST = 'host', DIR = 'dir', NODE_CHANGE = 'nodeChange', B_C_CHANGE = 'bidiContextChange', STYLE = 'style'; Y.extend(EditorBidi, Y.Base, { /** * Place holder for the last direction when checking for a switch * @private * @property lastDirection */ lastDirection: null, /** * Tells us that an initial bidi check has already been performed * @private * @property firstEvent */ firstEvent: null, /** * Method checks to see if the direction of the text has changed based on a nodeChange event. * @private * @method _checkForChange */ _checkForChange: function() { var host = this.get(HOST), inst = host.getInstance(), sel = new inst.EditorSelection(), node, direction; if (sel.isCollapsed) { node = EditorBidi.blockParent(sel.focusNode, false, inst.EditorSelection.ROOT); if (node) { direction = node.getStyle('direction'); if (direction !== this.lastDirection) { host.fire(B_C_CHANGE, { changedTo: direction }); this.lastDirection = direction; } } } else { host.fire(B_C_CHANGE, { changedTo: 'select' }); this.lastDirection = null; } }, /** * Checked for a change after a specific nodeChange event has been fired. * @private * @method _afterNodeChange */ _afterNodeChange: function(e) { // If this is the first event ever, or an event that can result in a context change if (this.firstEvent || EditorBidi.EVENTS[e.changedType]) { this._checkForChange(); this.firstEvent = false; } }, /** * Checks for a direction change after a mouseup occurs. * @private * @method _afterMouseUp */ _afterMouseUp: function() { this._checkForChange(); this.firstEvent = false; }, initializer: function() { var host = this.get(HOST); this.firstEvent = true; host.after(NODE_CHANGE, Y.bind(this._afterNodeChange, this)); host.after('dom:mouseup', Y.bind(this._afterMouseUp, this)); } }, { /** * The events to check for a direction change on * @property EVENTS * @static */ EVENTS: { 'backspace-up': true, 'pageup-up': true, 'pagedown-down': true, 'end-up': true, 'home-up': true, 'left-up': true, 'up-up': true, 'right-up': true, 'down-up': true, 'delete-up': true }, /** * More elements may be needed. BODY *must* be in the list to take care of the special case. * * blockParent could be changed to use inst.EditorSelection.BLOCKS * instead, but that would make Y.Plugin.EditorBidi.blockParent * unusable in non-RTE contexts (it being usable is a nice * side-effect). * @property BLOCKS * @static */ //BLOCKS: Y.EditorSelection.BLOCKS+',LI,HR,' + BODY, BLOCKS: Y.EditorSelection.BLOCKS, /** * Template for creating a block element * @static * @property DIV_WRAPPER */ DIV_WRAPPER: '
', /** * Returns a block parent for a given element * @static * @method blockParent */ blockParent: function(node, wrap, root) { var parent = node, divNode, firstChild; root = root || Y.EditorSelection.ROOT; if (!parent) { parent = root; } if (!parent.test(EditorBidi.BLOCKS)) { parent = parent.ancestor(EditorBidi.BLOCKS); } if (wrap && parent.compareTo(root)) { // This shouldn't happen if the RTE handles everything // according to spec: we should get to a P before ROOT. But // we don't want to set the direction of ROOT even if that // happens, so we wrap everything in a DIV. // The code is based on YUI3's Y.EditorSelection._wrapBlock function. divNode = Y.Node.create(EditorBidi.DIV_WRAPPER); parent.get('children').each(function(node, index) { if (index === 0) { firstChild = node; } else { divNode.append(node); } }); firstChild.replace(divNode); divNode.prepend(firstChild); parent = divNode; } return parent; }, /** * The data key to store on the node. * @static * @property _NODE_SELECTED */ _NODE_SELECTED: 'bidiSelected', /** * Generates a list of all the block parents of the current NodeList * @static * @method addParents */ addParents: function(nodeArray, root) { var i, parent, addParent; tester = function(sibling) { if (!sibling.getData(EditorBidi._NODE_SELECTED)) { addParent = false; return true; // stop more processing } }; root = root || Y.EditorSelection.ROOT; for (i = 0; i < nodeArray.length; i += 1) { nodeArray[i].setData(EditorBidi._NODE_SELECTED, true); } // This works automagically, since new parents added get processed // later themselves. So if there's a node early in the process that // we haven't discovered some of its siblings yet, thus resulting in // its parent not added, the parent will be added later, since those // siblings will be added to the array and then get processed. for (i = 0; i < nodeArray.length; i += 1) { parent = nodeArray[i].get('parentNode'); // Don't add the parent if the parent is the ROOT element. // We don't want to change the direction of ROOT. Also don't // do it if the parent is already in the list. if (!root.compareTo(parent) && !parent.getData(EditorBidi._NODE_SELECTED)) { addParent = true; parent.get('children').some(tester); if (addParent) { nodeArray.push(parent); parent.setData(EditorBidi._NODE_SELECTED, true); } } } for (i = 0; i < nodeArray.length; i += 1) { nodeArray[i].clearData(EditorBidi._NODE_SELECTED); } return nodeArray; }, /** * editorBidi * @static * @property NAME */ NAME: 'editorBidi', /** * editorBidi * @static * @property NS */ NS: 'editorBidi', ATTRS: { host: { value: false } }, /** * Regex for testing/removing text-align style from an element * @static * @property RE_TEXT_ALIGN */ RE_TEXT_ALIGN: /text-align:\s*\w*\s*;/, /** * Method to test a node's style attribute for text-align and removing it. * @static * @method removeTextAlign */ removeTextAlign: function(n) { if (n) { if (n.getAttribute(STYLE).match(EditorBidi.RE_TEXT_ALIGN)) { n.setAttribute(STYLE, n.getAttribute(STYLE).replace(EditorBidi.RE_TEXT_ALIGN, '')); } if (n.hasAttribute('align')) { n.removeAttribute('align'); } } return n; } }); Y.namespace('Plugin'); Y.Plugin.EditorBidi = EditorBidi; /** * bidi execCommand override for setting the text direction of a node. * This property is added to the `Y.Plugin.ExecCommands.COMMANDS` * collection. * * @for Plugin.ExecCommand * @property bidi */ //TODO -- This should not add this command unless the plugin is added to the instance.. Y.Plugin.ExecCommand.COMMANDS.bidi = function(cmd, direction) { var inst = this.getInstance(), sel = new inst.EditorSelection(), ns = this.get(HOST).get(HOST).editorBidi, returnValue, block, b, root = inst.EditorSelection.ROOT, selected, selectedBlocks, dir; if (!ns) { Y.error('bidi execCommand is not available without the EditorBiDi plugin.'); return; } inst.EditorSelection.filterBlocks(); if (sel.isCollapsed) { // No selection block = EditorBidi.blockParent(sel.anchorNode, false, root); if (!block) { block = root.one(inst.EditorSelection.BLOCKS); } //Remove text-align attribute if it exists block = EditorBidi.removeTextAlign(block); if (!direction) { //If no direction is set, auto-detect the proper setting to make it "toggle" dir = block.getAttribute(DIR); if (!dir || dir === 'ltr') { direction = 'rtl'; } else { direction = 'ltr'; } } block.setAttribute(DIR, direction); if (Y.UA.ie) { b = block.all('br.yui-cursor'); if (b.size() === 1 && block.get('childNodes').size() === 1) { b.remove(); } } returnValue = block; } else { // some text is selected selected = sel.getSelected(); selectedBlocks = []; selected.each(function(node) { selectedBlocks.push(EditorBidi.blockParent(node, false, root)); }); selectedBlocks = inst.all(EditorBidi.addParents(selectedBlocks, root)); selectedBlocks.each(function(n) { var d = direction; //Remove text-align attribute if it exists n = EditorBidi.removeTextAlign(n); if (!d) { dir = n.getAttribute(DIR); if (!dir || dir === 'ltr') { d = 'rtl'; } else { d = 'ltr'; } } n.setAttribute(DIR, d); }); returnValue = selectedBlocks; } ns._checkForChange(); return returnValue; }; }, '3.18.1', {"requires": ["editor-base"]}); PK\qノ 13.18.1/node-event-delegate/node-event-delegate.jsnu[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); }; }, '3.18.1', {"requires": ["node-base", "event-delegate"]}); PK\G  53.18.1/node-event-delegate/node-event-delegate-min.jsnu[YUI.add("node-event-delegate",function(e,t){e.Node.prototype.delegate=function(t){var n=e.Array(arguments,0,!0),r=e.Lang.isObject(t)&&!e.Lang.isArray(t)?1:2;return n.splice(r,0,this._node),e.delegate.apply(e,n)}},"3.18.1",{requires:["node-base","event-delegate"]}); PK\qノ 73.18.1/node-event-delegate/node-event-delegate-debug.jsnu[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); }; }, '3.18.1', {"requires": ["node-base", "event-delegate"]}); PK\ ȫWW%3.18.1/event-move/event-move-debug.jsnu[YUI.add('event-move', function (Y, NAME) { /** * Adds lower level support for "gesturemovestart", "gesturemove" and "gesturemoveend" events, which can be used to create drag/drop * interactions which work across touch and mouse input devices. They correspond to "touchstart", "touchmove" and "touchend" on a touch input * device, and "mousedown", "mousemove", "mouseup" on a mouse based input device. * *

Documentation for the gesturemove triplet of events can be found on the YUI global, * along with the other supported events.

@example YUI().use('event-move', function (Y) { Y.one('#myNode').on('gesturemovestart', function (e) { Y.log('gesturemovestart Fired.'); }); Y.one('#myNode').on('gesturemove', function (e) { Y.log('gesturemove Fired.'); }); Y.one('#myNode').on('gesturemoveend', function (e) { Y.log('gesturemoveend Fired.'); }); }); * @module event-gestures * @submodule event-move */ var GESTURE_MAP = Y.Event._GESTURE_MAP, EVENT = { start: GESTURE_MAP.start, end: GESTURE_MAP.end, move: GESTURE_MAP.move }, START = "start", MOVE = "move", END = "end", GESTURE_MOVE = "gesture" + MOVE, GESTURE_MOVE_END = GESTURE_MOVE + END, GESTURE_MOVE_START = GESTURE_MOVE + START, _MOVE_START_HANDLE = "_msh", _MOVE_HANDLE = "_mh", _MOVE_END_HANDLE = "_meh", _DEL_MOVE_START_HANDLE = "_dmsh", _DEL_MOVE_HANDLE = "_dmh", _DEL_MOVE_END_HANDLE = "_dmeh", _MOVE_START = "_ms", _MOVE = "_m", MIN_TIME = "minTime", MIN_DISTANCE = "minDistance", PREVENT_DEFAULT = "preventDefault", BUTTON = "button", OWNER_DOCUMENT = "ownerDocument", CURRENT_TARGET = "currentTarget", TARGET = "target", NODE_TYPE = "nodeType", _getTouchAction = function(win) { var touchAction; if(win) { if("PointerEvent" in win) { touchAction = "touchAction"; } else if("msPointerEnabled" in win.navigator) { touchAction = "msTouchAction"; } } return touchAction; }, TOUCH_ACTION = _getTouchAction(Y.config.win), SUPPORTS_POINTER = (TOUCH_ACTION === "msTouchAction" || TOUCH_ACTION === "touchAction"), MS_TOUCH_ACTION_COUNT = 'msTouchActionCount', MS_INIT_TOUCH_ACTION = 'msInitTouchAction', _defArgsProcessor = function(se, args, delegate) { var iConfig = (delegate) ? 4 : 3, config = (args.length > iConfig) ? Y.merge(args.splice(iConfig,1)[0]) : {}; if (!(PREVENT_DEFAULT in config)) { config[PREVENT_DEFAULT] = se.PREVENT_DEFAULT; } return config; }, _getRoot = function(node, subscriber) { return subscriber._extra.root || (node.get(NODE_TYPE) === 9) ? node : node.get(OWNER_DOCUMENT); }, //Checks to see if the node is the document, and if it is, returns the documentElement. _checkDocumentElem = function(node) { var elem = node.getDOMNode(); if (node.compareTo(Y.config.doc) && elem.documentElement) { return elem.documentElement; } else { return false; } }, _normTouchFacade = function(touchFacade, touch, params) { touchFacade.pageX = touch.pageX; touchFacade.pageY = touch.pageY; touchFacade.screenX = touch.screenX; touchFacade.screenY = touch.screenY; touchFacade.clientX = touch.clientX; touchFacade.clientY = touch.clientY; touchFacade[TARGET] = touchFacade[TARGET] || touch[TARGET]; touchFacade[CURRENT_TARGET] = touchFacade[CURRENT_TARGET] || touch[CURRENT_TARGET]; touchFacade[BUTTON] = (params && params[BUTTON]) || 1; // default to left (left as per vendors, not W3C which is 0) }, /* In IE10 touch mode, gestures will not work properly unless the -ms-touch-action CSS property is set to something other than 'auto'. Read http://msdn.microsoft.com/en-us/library/windows/apps/hh767313.aspx for more info. To get around this, we set -ms-touch-action: none which is the same as e.preventDefault() on touch environments. This tells the browser to fire DOM events for all touch events, and not perform any default behavior. The user can over-ride this by setting a more lenient -ms-touch-action property on a node (such as pan-x, pan-y, etc.) via CSS when subscribing to the 'gesturemovestart' event. */ _setTouchActions = function (node) { var elem = node.getDOMNode(), num = node.getData(MS_TOUCH_ACTION_COUNT); //Checks to see if msTouchAction is supported. if (SUPPORTS_POINTER) { if (!num) { num = 0; node.setData(MS_INIT_TOUCH_ACTION, elem.style[TOUCH_ACTION]); } elem.style[TOUCH_ACTION] = Y.Event._DEFAULT_TOUCH_ACTION; num++; node.setData(MS_TOUCH_ACTION_COUNT, num); } }, /* Resets the element's -ms-touch-action property back to the original value, This is called on detach() and detachDelegate(). */ _unsetTouchActions = function (node) { var elem = node.getDOMNode(), num = node.getData(MS_TOUCH_ACTION_COUNT), initTouchAction = node.getData(MS_INIT_TOUCH_ACTION); if (SUPPORTS_POINTER) { num--; node.setData(MS_TOUCH_ACTION_COUNT, num); if (num === 0 && elem.style[TOUCH_ACTION] !== initTouchAction) { elem.style[TOUCH_ACTION] = initTouchAction; } } }, _prevent = function(e, preventDefault) { if (preventDefault) { // preventDefault is a boolean or a function if (!preventDefault.call || preventDefault(e)) { e.preventDefault(); } } }, define = Y.Event.define; Y.Event._DEFAULT_TOUCH_ACTION = 'none'; /** * Sets up a "gesturemovestart" event, that is fired on touch devices in response to a single finger "touchstart", * and on mouse based devices in response to a "mousedown". The subscriber can specify the minimum time * and distance thresholds which should be crossed before the "gesturemovestart" is fired and for the mouse, * which button should initiate a "gesturemovestart". This event can also be listened for using node.delegate(). * *

It is recommended that you use Y.bind to set up context and additional arguments for your event handler, * however if you want to pass the context and arguments as additional signature arguments to on/delegate, * you need to provide a null value for the configuration object, e.g: node.on("gesturemovestart", fn, null, context, arg1, arg2, arg3)

* * @event gesturemovestart * @for YUI * @param type {string} "gesturemovestart" * @param fn {function} The method the event invokes. It receives the event facade of the underlying DOM event (mousedown or touchstart.touches[0]) which contains position co-ordinates. * @param cfg {Object} Optional. An object which specifies: * *
*
minDistance (defaults to 0)
*
The minimum distance threshold which should be crossed before the gesturemovestart is fired
*
minTime (defaults to 0)
*
The minimum time threshold for which the finger/mouse should be help down before the gesturemovestart is fired
*
button (no default)
*
In the case of a mouse input device, if the event should only be fired for a specific mouse button.
*
preventDefault (defaults to false)
*
Can be set to true/false to prevent default behavior as soon as the touchstart or mousedown is received (that is before minTime or minDistance thresholds are crossed, and so before the gesturemovestart listener is notified) so that things like text selection and context popups (on touch devices) can be * prevented. This property can also be set to a function, which returns true or false, based on the event facade passed to it (for example, DragDrop can determine if the target is a valid handle or not before preventing default).
*
* * @return {EventHandle} the detach handle */ define(GESTURE_MOVE_START, { on: function (node, subscriber, ce) { //Set -ms-touch-action on IE10 and set preventDefault to true if (!_checkDocumentElem(node)) { _setTouchActions(node); } subscriber[_MOVE_START_HANDLE] = node.on(EVENT[START], this._onStart, this, node, subscriber, ce); }, delegate : function(node, subscriber, ce, filter) { var se = this; subscriber[_DEL_MOVE_START_HANDLE] = node.delegate(EVENT[START], function(e) { se._onStart(e, node, subscriber, ce, true); }, filter); }, detachDelegate : function(node, subscriber, ce, filter) { var handle = subscriber[_DEL_MOVE_START_HANDLE]; if (handle) { handle.detach(); subscriber[_DEL_MOVE_START_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, detach: function (node, subscriber, ce) { var startHandle = subscriber[_MOVE_START_HANDLE]; if (startHandle) { startHandle.detach(); subscriber[_MOVE_START_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, processArgs : function(args, delegate) { var params = _defArgsProcessor(this, args, delegate); if (!(MIN_TIME in params)) { params[MIN_TIME] = this.MIN_TIME; } if (!(MIN_DISTANCE in params)) { params[MIN_DISTANCE] = this.MIN_DISTANCE; } return params; }, _onStart : function(e, node, subscriber, ce, delegate) { if (delegate) { node = e[CURRENT_TARGET]; } var params = subscriber._extra, fireStart = true, minTime = params[MIN_TIME], minDistance = params[MIN_DISTANCE], button = params.button, preventDefault = params[PREVENT_DEFAULT], root = _getRoot(node, subscriber), startXY; if (e.touches) { if (e.touches.length === 1) { _normTouchFacade(e, e.touches[0], params); } else { fireStart = false; } } else { fireStart = (button === undefined) || (button === e.button); } Y.log("gesturemovestart: params = button:" + button + ", minTime = " + minTime + ", minDistance = " + minDistance, "event-gestures"); if (fireStart) { _prevent(e, preventDefault); if (minTime === 0 || minDistance === 0) { Y.log("gesturemovestart: No minTime or minDistance. Firing immediately", "event-gestures"); this._start(e, node, ce, params); } else { startXY = [e.pageX, e.pageY]; if (minTime > 0) { Y.log("gesturemovestart: minTime specified. Setup timer.", "event-gestures"); Y.log("gesturemovestart: initialTime for minTime = " + new Date().getTime(), "event-gestures"); params._ht = Y.later(minTime, this, this._start, [e, node, ce, params]); params._hme = root.on(EVENT[END], Y.bind(function() { this._cancel(params); }, this)); } if (minDistance > 0) { Y.log("gesturemovestart: minDistance specified. Setup native mouse/touchmove listener to measure distance.", "event-gestures"); Y.log("gesturemovestart: initialXY for minDistance = " + startXY, "event-gestures"); params._hm = root.on(EVENT[MOVE], Y.bind(function(em) { if (Math.abs(em.pageX - startXY[0]) > minDistance || Math.abs(em.pageY - startXY[1]) > minDistance) { Y.log("gesturemovestart: minDistance hit.", "event-gestures"); this._start(e, node, ce, params); } }, this)); } } } }, _cancel : function(params) { if (params._ht) { params._ht.cancel(); params._ht = null; } if (params._hme) { params._hme.detach(); params._hme = null; } if (params._hm) { params._hm.detach(); params._hm = null; } }, _start : function(e, node, ce, params) { if (params) { this._cancel(params); } e.type = GESTURE_MOVE_START; Y.log("gesturemovestart: Firing start: " + new Date().getTime(), "event-gestures"); node.setData(_MOVE_START, e); ce.fire(e); }, MIN_TIME : 0, MIN_DISTANCE : 0, PREVENT_DEFAULT : false }); /** * Sets up a "gesturemove" event, that is fired on touch devices in response to a single finger "touchmove", * and on mouse based devices in response to a "mousemove". * *

By default this event is only fired when the same node * has received a "gesturemovestart" event. The subscriber can set standAlone to true, in the configuration properties, * if they want to listen for this event without an initial "gesturemovestart".

* *

By default this event sets up it's internal "touchmove" and "mousemove" DOM listeners on the document element. The subscriber * can set the root configuration property, to specify which node to attach DOM listeners to, if different from the document.

* *

This event can also be listened for using node.delegate().

* *

It is recommended that you use Y.bind to set up context and additional arguments for your event handler, * however if you want to pass the context and arguments as additional signature arguments to on/delegate, * you need to provide a null value for the configuration object, e.g: node.on("gesturemove", fn, null, context, arg1, arg2, arg3)

* * @event gesturemove * @for YUI * @param type {string} "gesturemove" * @param fn {function} The method the event invokes. It receives the event facade of the underlying DOM event (mousemove or touchmove.touches[0]) which contains position co-ordinates. * @param cfg {Object} Optional. An object which specifies: *
*
standAlone (defaults to false)
*
true, if the subscriber should be notified even if a "gesturemovestart" has not occured on the same node.
*
root (defaults to document)
*
The node to which the internal DOM listeners should be attached.
*
preventDefault (defaults to false)
*
Can be set to true/false to prevent default behavior as soon as the touchmove or mousemove is received. As with gesturemovestart, can also be set to function which returns true/false based on the event facade passed to it.
*
* * @return {EventHandle} the detach handle */ define(GESTURE_MOVE, { on : function (node, subscriber, ce) { var moveHandle, root; // if the passed node is NOT the document itself, modify the ms-pointer // behavior to prevent scrolling, highlighting, etc. if (!_checkDocumentElem(node)) { _setTouchActions(node); } root = _getRoot(node, subscriber, EVENT[MOVE]); moveHandle = root.on(EVENT[MOVE], this._onMove, this, node, subscriber, ce); subscriber[_MOVE_HANDLE] = moveHandle; }, delegate : function(node, subscriber, ce, filter) { var se = this; subscriber[_DEL_MOVE_HANDLE] = node.delegate(EVENT[MOVE], function(e) { se._onMove(e, node, subscriber, ce, true); }, filter); }, detach : function (node, subscriber, ce) { var moveHandle = subscriber[_MOVE_HANDLE]; if (moveHandle) { moveHandle.detach(); subscriber[_MOVE_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, detachDelegate : function(node, subscriber, ce, filter) { var handle = subscriber[_DEL_MOVE_HANDLE]; if (handle) { handle.detach(); subscriber[_DEL_MOVE_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, processArgs : function(args, delegate) { return _defArgsProcessor(this, args, delegate); }, _onMove : function(e, node, subscriber, ce, delegate) { if (delegate) { node = e[CURRENT_TARGET]; } var fireMove = subscriber._extra.standAlone || node.getData(_MOVE_START), preventDefault = subscriber._extra.preventDefault; Y.log("onMove initial fireMove check:" + fireMove,"event-gestures"); if (fireMove) { if (e.touches) { if (e.touches.length === 1) { _normTouchFacade(e, e.touches[0]); } else { fireMove = false; } } if (fireMove) { _prevent(e, preventDefault); Y.log("onMove second fireMove check:" + fireMove,"event-gestures"); e.type = GESTURE_MOVE; ce.fire(e); } } }, PREVENT_DEFAULT : false }); /** * Sets up a "gesturemoveend" event, that is fired on touch devices in response to a single finger "touchend", * and on mouse based devices in response to a "mouseup". * *

By default this event is only fired when the same node * has received a "gesturemove" or "gesturemovestart" event. The subscriber can set standAlone to true, in the configuration properties, * if they want to listen for this event without a preceding "gesturemovestart" or "gesturemove".

* *

By default this event sets up it's internal "touchend" and "mouseup" DOM listeners on the document element. The subscriber * can set the root configuration property, to specify which node to attach DOM listeners to, if different from the document.

* *

This event can also be listened for using node.delegate().

* *

It is recommended that you use Y.bind to set up context and additional arguments for your event handler, * however if you want to pass the context and arguments as additional signature arguments to on/delegate, * you need to provide a null value for the configuration object, e.g: node.on("gesturemoveend", fn, null, context, arg1, arg2, arg3)

* * * @event gesturemoveend * @for YUI * @param type {string} "gesturemoveend" * @param fn {function} The method the event invokes. It receives the event facade of the underlying DOM event (mouseup or touchend.changedTouches[0]). * @param cfg {Object} Optional. An object which specifies: *
*
standAlone (defaults to false)
*
true, if the subscriber should be notified even if a "gesturemovestart" or "gesturemove" has not occured on the same node.
*
root (defaults to document)
*
The node to which the internal DOM listeners should be attached.
*
preventDefault (defaults to false)
*
Can be set to true/false to prevent default behavior as soon as the touchend or mouseup is received. As with gesturemovestart, can also be set to function which returns true/false based on the event facade passed to it.
*
* * @return {EventHandle} the detach handle */ define(GESTURE_MOVE_END, { on : function (node, subscriber, ce) { var endHandle, root; if (!_checkDocumentElem(node)) { _setTouchActions(node); } root = _getRoot(node, subscriber); endHandle = root.on(EVENT[END], this._onEnd, this, node, subscriber, ce); subscriber[_MOVE_END_HANDLE] = endHandle; }, delegate : function(node, subscriber, ce, filter) { var se = this; subscriber[_DEL_MOVE_END_HANDLE] = node.delegate(EVENT[END], function(e) { se._onEnd(e, node, subscriber, ce, true); }, filter); }, detachDelegate : function(node, subscriber, ce, filter) { var handle = subscriber[_DEL_MOVE_END_HANDLE]; if (handle) { handle.detach(); subscriber[_DEL_MOVE_END_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, detach : function (node, subscriber, ce) { var endHandle = subscriber[_MOVE_END_HANDLE]; if (endHandle) { endHandle.detach(); subscriber[_MOVE_END_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, processArgs : function(args, delegate) { return _defArgsProcessor(this, args, delegate); }, _onEnd : function(e, node, subscriber, ce, delegate) { if (delegate) { node = e[CURRENT_TARGET]; } var fireMoveEnd = subscriber._extra.standAlone || node.getData(_MOVE) || node.getData(_MOVE_START), preventDefault = subscriber._extra.preventDefault; if (fireMoveEnd) { if (e.changedTouches) { if (e.changedTouches.length === 1) { _normTouchFacade(e, e.changedTouches[0]); } else { fireMoveEnd = false; } } if (fireMoveEnd) { _prevent(e, preventDefault); e.type = GESTURE_MOVE_END; ce.fire(e); node.clearData(_MOVE_START); node.clearData(_MOVE); } } }, PREVENT_DEFAULT : false }); }, '3.18.1', {"requires": ["node-base", "event-touch", "event-synthetic"]}); PK\_ASS3.18.1/event-move/event-move.jsnu[YUI.add('event-move', function (Y, NAME) { /** * Adds lower level support for "gesturemovestart", "gesturemove" and "gesturemoveend" events, which can be used to create drag/drop * interactions which work across touch and mouse input devices. They correspond to "touchstart", "touchmove" and "touchend" on a touch input * device, and "mousedown", "mousemove", "mouseup" on a mouse based input device. * *

Documentation for the gesturemove triplet of events can be found on the YUI global, * along with the other supported events.

@example YUI().use('event-move', function (Y) { Y.one('#myNode').on('gesturemovestart', function (e) { }); Y.one('#myNode').on('gesturemove', function (e) { }); Y.one('#myNode').on('gesturemoveend', function (e) { }); }); * @module event-gestures * @submodule event-move */ var GESTURE_MAP = Y.Event._GESTURE_MAP, EVENT = { start: GESTURE_MAP.start, end: GESTURE_MAP.end, move: GESTURE_MAP.move }, START = "start", MOVE = "move", END = "end", GESTURE_MOVE = "gesture" + MOVE, GESTURE_MOVE_END = GESTURE_MOVE + END, GESTURE_MOVE_START = GESTURE_MOVE + START, _MOVE_START_HANDLE = "_msh", _MOVE_HANDLE = "_mh", _MOVE_END_HANDLE = "_meh", _DEL_MOVE_START_HANDLE = "_dmsh", _DEL_MOVE_HANDLE = "_dmh", _DEL_MOVE_END_HANDLE = "_dmeh", _MOVE_START = "_ms", _MOVE = "_m", MIN_TIME = "minTime", MIN_DISTANCE = "minDistance", PREVENT_DEFAULT = "preventDefault", BUTTON = "button", OWNER_DOCUMENT = "ownerDocument", CURRENT_TARGET = "currentTarget", TARGET = "target", NODE_TYPE = "nodeType", _getTouchAction = function(win) { var touchAction; if(win) { if("PointerEvent" in win) { touchAction = "touchAction"; } else if("msPointerEnabled" in win.navigator) { touchAction = "msTouchAction"; } } return touchAction; }, TOUCH_ACTION = _getTouchAction(Y.config.win), SUPPORTS_POINTER = (TOUCH_ACTION === "msTouchAction" || TOUCH_ACTION === "touchAction"), MS_TOUCH_ACTION_COUNT = 'msTouchActionCount', MS_INIT_TOUCH_ACTION = 'msInitTouchAction', _defArgsProcessor = function(se, args, delegate) { var iConfig = (delegate) ? 4 : 3, config = (args.length > iConfig) ? Y.merge(args.splice(iConfig,1)[0]) : {}; if (!(PREVENT_DEFAULT in config)) { config[PREVENT_DEFAULT] = se.PREVENT_DEFAULT; } return config; }, _getRoot = function(node, subscriber) { return subscriber._extra.root || (node.get(NODE_TYPE) === 9) ? node : node.get(OWNER_DOCUMENT); }, //Checks to see if the node is the document, and if it is, returns the documentElement. _checkDocumentElem = function(node) { var elem = node.getDOMNode(); if (node.compareTo(Y.config.doc) && elem.documentElement) { return elem.documentElement; } else { return false; } }, _normTouchFacade = function(touchFacade, touch, params) { touchFacade.pageX = touch.pageX; touchFacade.pageY = touch.pageY; touchFacade.screenX = touch.screenX; touchFacade.screenY = touch.screenY; touchFacade.clientX = touch.clientX; touchFacade.clientY = touch.clientY; touchFacade[TARGET] = touchFacade[TARGET] || touch[TARGET]; touchFacade[CURRENT_TARGET] = touchFacade[CURRENT_TARGET] || touch[CURRENT_TARGET]; touchFacade[BUTTON] = (params && params[BUTTON]) || 1; // default to left (left as per vendors, not W3C which is 0) }, /* In IE10 touch mode, gestures will not work properly unless the -ms-touch-action CSS property is set to something other than 'auto'. Read http://msdn.microsoft.com/en-us/library/windows/apps/hh767313.aspx for more info. To get around this, we set -ms-touch-action: none which is the same as e.preventDefault() on touch environments. This tells the browser to fire DOM events for all touch events, and not perform any default behavior. The user can over-ride this by setting a more lenient -ms-touch-action property on a node (such as pan-x, pan-y, etc.) via CSS when subscribing to the 'gesturemovestart' event. */ _setTouchActions = function (node) { var elem = node.getDOMNode(), num = node.getData(MS_TOUCH_ACTION_COUNT); //Checks to see if msTouchAction is supported. if (SUPPORTS_POINTER) { if (!num) { num = 0; node.setData(MS_INIT_TOUCH_ACTION, elem.style[TOUCH_ACTION]); } elem.style[TOUCH_ACTION] = Y.Event._DEFAULT_TOUCH_ACTION; num++; node.setData(MS_TOUCH_ACTION_COUNT, num); } }, /* Resets the element's -ms-touch-action property back to the original value, This is called on detach() and detachDelegate(). */ _unsetTouchActions = function (node) { var elem = node.getDOMNode(), num = node.getData(MS_TOUCH_ACTION_COUNT), initTouchAction = node.getData(MS_INIT_TOUCH_ACTION); if (SUPPORTS_POINTER) { num--; node.setData(MS_TOUCH_ACTION_COUNT, num); if (num === 0 && elem.style[TOUCH_ACTION] !== initTouchAction) { elem.style[TOUCH_ACTION] = initTouchAction; } } }, _prevent = function(e, preventDefault) { if (preventDefault) { // preventDefault is a boolean or a function if (!preventDefault.call || preventDefault(e)) { e.preventDefault(); } } }, define = Y.Event.define; Y.Event._DEFAULT_TOUCH_ACTION = 'none'; /** * Sets up a "gesturemovestart" event, that is fired on touch devices in response to a single finger "touchstart", * and on mouse based devices in response to a "mousedown". The subscriber can specify the minimum time * and distance thresholds which should be crossed before the "gesturemovestart" is fired and for the mouse, * which button should initiate a "gesturemovestart". This event can also be listened for using node.delegate(). * *

It is recommended that you use Y.bind to set up context and additional arguments for your event handler, * however if you want to pass the context and arguments as additional signature arguments to on/delegate, * you need to provide a null value for the configuration object, e.g: node.on("gesturemovestart", fn, null, context, arg1, arg2, arg3)

* * @event gesturemovestart * @for YUI * @param type {string} "gesturemovestart" * @param fn {function} The method the event invokes. It receives the event facade of the underlying DOM event (mousedown or touchstart.touches[0]) which contains position co-ordinates. * @param cfg {Object} Optional. An object which specifies: * *
*
minDistance (defaults to 0)
*
The minimum distance threshold which should be crossed before the gesturemovestart is fired
*
minTime (defaults to 0)
*
The minimum time threshold for which the finger/mouse should be help down before the gesturemovestart is fired
*
button (no default)
*
In the case of a mouse input device, if the event should only be fired for a specific mouse button.
*
preventDefault (defaults to false)
*
Can be set to true/false to prevent default behavior as soon as the touchstart or mousedown is received (that is before minTime or minDistance thresholds are crossed, and so before the gesturemovestart listener is notified) so that things like text selection and context popups (on touch devices) can be * prevented. This property can also be set to a function, which returns true or false, based on the event facade passed to it (for example, DragDrop can determine if the target is a valid handle or not before preventing default).
*
* * @return {EventHandle} the detach handle */ define(GESTURE_MOVE_START, { on: function (node, subscriber, ce) { //Set -ms-touch-action on IE10 and set preventDefault to true if (!_checkDocumentElem(node)) { _setTouchActions(node); } subscriber[_MOVE_START_HANDLE] = node.on(EVENT[START], this._onStart, this, node, subscriber, ce); }, delegate : function(node, subscriber, ce, filter) { var se = this; subscriber[_DEL_MOVE_START_HANDLE] = node.delegate(EVENT[START], function(e) { se._onStart(e, node, subscriber, ce, true); }, filter); }, detachDelegate : function(node, subscriber, ce, filter) { var handle = subscriber[_DEL_MOVE_START_HANDLE]; if (handle) { handle.detach(); subscriber[_DEL_MOVE_START_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, detach: function (node, subscriber, ce) { var startHandle = subscriber[_MOVE_START_HANDLE]; if (startHandle) { startHandle.detach(); subscriber[_MOVE_START_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, processArgs : function(args, delegate) { var params = _defArgsProcessor(this, args, delegate); if (!(MIN_TIME in params)) { params[MIN_TIME] = this.MIN_TIME; } if (!(MIN_DISTANCE in params)) { params[MIN_DISTANCE] = this.MIN_DISTANCE; } return params; }, _onStart : function(e, node, subscriber, ce, delegate) { if (delegate) { node = e[CURRENT_TARGET]; } var params = subscriber._extra, fireStart = true, minTime = params[MIN_TIME], minDistance = params[MIN_DISTANCE], button = params.button, preventDefault = params[PREVENT_DEFAULT], root = _getRoot(node, subscriber), startXY; if (e.touches) { if (e.touches.length === 1) { _normTouchFacade(e, e.touches[0], params); } else { fireStart = false; } } else { fireStart = (button === undefined) || (button === e.button); } if (fireStart) { _prevent(e, preventDefault); if (minTime === 0 || minDistance === 0) { this._start(e, node, ce, params); } else { startXY = [e.pageX, e.pageY]; if (minTime > 0) { params._ht = Y.later(minTime, this, this._start, [e, node, ce, params]); params._hme = root.on(EVENT[END], Y.bind(function() { this._cancel(params); }, this)); } if (minDistance > 0) { params._hm = root.on(EVENT[MOVE], Y.bind(function(em) { if (Math.abs(em.pageX - startXY[0]) > minDistance || Math.abs(em.pageY - startXY[1]) > minDistance) { this._start(e, node, ce, params); } }, this)); } } } }, _cancel : function(params) { if (params._ht) { params._ht.cancel(); params._ht = null; } if (params._hme) { params._hme.detach(); params._hme = null; } if (params._hm) { params._hm.detach(); params._hm = null; } }, _start : function(e, node, ce, params) { if (params) { this._cancel(params); } e.type = GESTURE_MOVE_START; node.setData(_MOVE_START, e); ce.fire(e); }, MIN_TIME : 0, MIN_DISTANCE : 0, PREVENT_DEFAULT : false }); /** * Sets up a "gesturemove" event, that is fired on touch devices in response to a single finger "touchmove", * and on mouse based devices in response to a "mousemove". * *

By default this event is only fired when the same node * has received a "gesturemovestart" event. The subscriber can set standAlone to true, in the configuration properties, * if they want to listen for this event without an initial "gesturemovestart".

* *

By default this event sets up it's internal "touchmove" and "mousemove" DOM listeners on the document element. The subscriber * can set the root configuration property, to specify which node to attach DOM listeners to, if different from the document.

* *

This event can also be listened for using node.delegate().

* *

It is recommended that you use Y.bind to set up context and additional arguments for your event handler, * however if you want to pass the context and arguments as additional signature arguments to on/delegate, * you need to provide a null value for the configuration object, e.g: node.on("gesturemove", fn, null, context, arg1, arg2, arg3)

* * @event gesturemove * @for YUI * @param type {string} "gesturemove" * @param fn {function} The method the event invokes. It receives the event facade of the underlying DOM event (mousemove or touchmove.touches[0]) which contains position co-ordinates. * @param cfg {Object} Optional. An object which specifies: *
*
standAlone (defaults to false)
*
true, if the subscriber should be notified even if a "gesturemovestart" has not occured on the same node.
*
root (defaults to document)
*
The node to which the internal DOM listeners should be attached.
*
preventDefault (defaults to false)
*
Can be set to true/false to prevent default behavior as soon as the touchmove or mousemove is received. As with gesturemovestart, can also be set to function which returns true/false based on the event facade passed to it.
*
* * @return {EventHandle} the detach handle */ define(GESTURE_MOVE, { on : function (node, subscriber, ce) { var moveHandle, root; // if the passed node is NOT the document itself, modify the ms-pointer // behavior to prevent scrolling, highlighting, etc. if (!_checkDocumentElem(node)) { _setTouchActions(node); } root = _getRoot(node, subscriber, EVENT[MOVE]); moveHandle = root.on(EVENT[MOVE], this._onMove, this, node, subscriber, ce); subscriber[_MOVE_HANDLE] = moveHandle; }, delegate : function(node, subscriber, ce, filter) { var se = this; subscriber[_DEL_MOVE_HANDLE] = node.delegate(EVENT[MOVE], function(e) { se._onMove(e, node, subscriber, ce, true); }, filter); }, detach : function (node, subscriber, ce) { var moveHandle = subscriber[_MOVE_HANDLE]; if (moveHandle) { moveHandle.detach(); subscriber[_MOVE_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, detachDelegate : function(node, subscriber, ce, filter) { var handle = subscriber[_DEL_MOVE_HANDLE]; if (handle) { handle.detach(); subscriber[_DEL_MOVE_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, processArgs : function(args, delegate) { return _defArgsProcessor(this, args, delegate); }, _onMove : function(e, node, subscriber, ce, delegate) { if (delegate) { node = e[CURRENT_TARGET]; } var fireMove = subscriber._extra.standAlone || node.getData(_MOVE_START), preventDefault = subscriber._extra.preventDefault; if (fireMove) { if (e.touches) { if (e.touches.length === 1) { _normTouchFacade(e, e.touches[0]); } else { fireMove = false; } } if (fireMove) { _prevent(e, preventDefault); e.type = GESTURE_MOVE; ce.fire(e); } } }, PREVENT_DEFAULT : false }); /** * Sets up a "gesturemoveend" event, that is fired on touch devices in response to a single finger "touchend", * and on mouse based devices in response to a "mouseup". * *

By default this event is only fired when the same node * has received a "gesturemove" or "gesturemovestart" event. The subscriber can set standAlone to true, in the configuration properties, * if they want to listen for this event without a preceding "gesturemovestart" or "gesturemove".

* *

By default this event sets up it's internal "touchend" and "mouseup" DOM listeners on the document element. The subscriber * can set the root configuration property, to specify which node to attach DOM listeners to, if different from the document.

* *

This event can also be listened for using node.delegate().

* *

It is recommended that you use Y.bind to set up context and additional arguments for your event handler, * however if you want to pass the context and arguments as additional signature arguments to on/delegate, * you need to provide a null value for the configuration object, e.g: node.on("gesturemoveend", fn, null, context, arg1, arg2, arg3)

* * * @event gesturemoveend * @for YUI * @param type {string} "gesturemoveend" * @param fn {function} The method the event invokes. It receives the event facade of the underlying DOM event (mouseup or touchend.changedTouches[0]). * @param cfg {Object} Optional. An object which specifies: *
*
standAlone (defaults to false)
*
true, if the subscriber should be notified even if a "gesturemovestart" or "gesturemove" has not occured on the same node.
*
root (defaults to document)
*
The node to which the internal DOM listeners should be attached.
*
preventDefault (defaults to false)
*
Can be set to true/false to prevent default behavior as soon as the touchend or mouseup is received. As with gesturemovestart, can also be set to function which returns true/false based on the event facade passed to it.
*
* * @return {EventHandle} the detach handle */ define(GESTURE_MOVE_END, { on : function (node, subscriber, ce) { var endHandle, root; if (!_checkDocumentElem(node)) { _setTouchActions(node); } root = _getRoot(node, subscriber); endHandle = root.on(EVENT[END], this._onEnd, this, node, subscriber, ce); subscriber[_MOVE_END_HANDLE] = endHandle; }, delegate : function(node, subscriber, ce, filter) { var se = this; subscriber[_DEL_MOVE_END_HANDLE] = node.delegate(EVENT[END], function(e) { se._onEnd(e, node, subscriber, ce, true); }, filter); }, detachDelegate : function(node, subscriber, ce, filter) { var handle = subscriber[_DEL_MOVE_END_HANDLE]; if (handle) { handle.detach(); subscriber[_DEL_MOVE_END_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, detach : function (node, subscriber, ce) { var endHandle = subscriber[_MOVE_END_HANDLE]; if (endHandle) { endHandle.detach(); subscriber[_MOVE_END_HANDLE] = null; } if (!_checkDocumentElem(node)) { _unsetTouchActions(node); } }, processArgs : function(args, delegate) { return _defArgsProcessor(this, args, delegate); }, _onEnd : function(e, node, subscriber, ce, delegate) { if (delegate) { node = e[CURRENT_TARGET]; } var fireMoveEnd = subscriber._extra.standAlone || node.getData(_MOVE) || node.getData(_MOVE_START), preventDefault = subscriber._extra.preventDefault; if (fireMoveEnd) { if (e.changedTouches) { if (e.changedTouches.length === 1) { _normTouchFacade(e, e.changedTouches[0]); } else { fireMoveEnd = false; } } if (fireMoveEnd) { _prevent(e, preventDefault); e.type = GESTURE_MOVE_END; ce.fire(e); node.clearData(_MOVE_START); node.clearData(_MOVE); } } }, PREVENT_DEFAULT : false }); }, '3.18.1', {"requires": ["node-base", "event-touch", "event-synthetic"]}); PK\]=ۨ#3.18.1/event-move/event-move-min.jsnu[YUI.add("event-move",function(e,t){var n=e.Event._GESTURE_MAP,r={start:n.start,end:n.end,move:n.move},i="start",s="move",o="end",u="gesture"+s,a=u+o,f=u+i,l="_msh",c="_mh",h="_meh",p="_dmsh",d="_dmh",v="_dmeh",m="_ms",g="_m",y="minTime",b="minDistance",w="preventDefault",E="button",S="ownerDocument",x="currentTarget",T="target",N="nodeType",C=function(e){var t;return e&&("PointerEvent"in e?t="touchAction":"msPointerEnabled"in e.navigator&&(t="msTouchAction")),t},k=C(e.config.win),L=k==="msTouchAction"||k==="touchAction",A="msTouchActionCount",O="msInitTouchAction",M=function(t,n,r){var i=r?4:3,s=n.length>i?e.merge(n.splice(i,1)[0]):{};return w in s||(s[w]=t.PREVENT_DEFAULT),s},_=function(e,t){return t._extra.root||e.get(N)===9?e:e.get(S)},D=function(t){var n=t.getDOMNode();return t.compareTo(e.config.doc)&&n.documentElement?n.documentElement:!1},P=function(e,t,n){e.pageX=t.pageX,e.pageY=t.pageY,e.screenX=t.screenX,e.screenY=t.screenY,e.clientX=t.clientX,e.clientY=t.clientY,e[T]=e[T]||t[T],e[x]=e[x]||t[x],e[E]=n&&n[E]||1},H=function(t){var n=t.getDOMNode(),r=t.getData(A);L&&(r||(r=0,t.setData(O,n.style[k])),n.style[k]=e.Event._DEFAULT_TOUCH_ACTION,r++,t.setData(A,r))},B=function(e){var t=e.getDOMNode(),n=e.getData(A),r=e.getData(O);L&&(n--,e.setData(A,n),n===0&&t.style[k]!==r&&(t.style[k]=r))},j=function(e,t){t&&(!t.call||t(e))&&e.preventDefault()},F=e.Event.define;e.Event._DEFAULT_TOUCH_ACTION="none",F(f,{on:function(e,t,n){D(e)||H(e),t[l]=e.on(r[i],this._onStart,this,e,t,n)},delegate:function(e,t,n,s){var o=this;t[p]=e.delegate(r[i],function(r){o._onStart(r,e,t,n,!0)},s)},detachDelegate:function(e,t,n,r){var i=t[p];i&&(i.detach(),t[p]=null),D(e)||B(e)},detach:function(e,t,n){var r=t[l];r&&(r.detach(),t[l]=null),D(e)||B(e)},processArgs:function(e,t){var n=M(this,e,t);return y in n||(n[y]=this.MIN_TIME),b in n||(n[b]=this.MIN_DISTANCE),n},_onStart:function(t,n,i,u,a){a&&(n=t[x]);var f=i._extra,l=!0,c=f[y],h=f[b],p=f.button,d=f[w],v=_(n,i),m;t.touches?t.touches.length===1?P(t,t.touches[0],f):l=!1:l=p===undefined||p===t.button,l&&(j(t,d),c===0||h===0?this._start(t,n,u,f):(m=[t.pageX,t.pageY],c>0&&(f._ht=e.later(c,this,this._start,[t,n,u,f]),f._hme=v.on(r[o],e.bind(function(){this._cancel(f)},this))),h>0&&(f._hm=v.on(r[s],e.bind(function(e){(Math.abs(e.pageX-m[0])>h||Math.abs(e.pageY-m[1])>h)&&this._start(t,n,u,f)},this)))))},_cancel:function(e){e._ht&&(e._ht.cancel(),e._ht=null),e._hme&&(e._hme.detach(),e._hme=null),e._hm&&(e._hm.detach(),e._hm=null)},_start:function(e,t,n,r){r&&this._cancel(r),e.type=f,t.setData(m,e),n.fire(e)},MIN_TIME:0,MIN_DISTANCE:0,PREVENT_DEFAULT:!1}),F(u,{on:function(e,t,n){var i,o;D(e)||H(e),o=_(e,t,r[s]),i=o.on(r[s],this._onMove,this,e,t,n),t[c]=i},delegate:function(e,t,n,i){var o=this;t[d]=e.delegate(r[s],function(r){o._onMove(r,e,t,n,!0)},i)},detach:function(e,t,n){var r=t[c];r&&(r.detach(),t[c]=null),D(e)||B(e)},detachDelegate:function(e,t,n,r){var i=t[d];i&&(i.detach(),t[d]=null),D(e)||B(e)},processArgs:function(e,t){return M(this,e,t)},_onMove:function(e,t,n,r,i){i&&(t=e[x]);var s=n._extra.standAlone||t.getData(m),o=n._extra.preventDefault;s&&(e.touches&&(e.touches.length===1?P(e,e.touches[0]):s=!1),s&&(j(e,o),e.type=u,r.fire(e)))},PREVENT_DEFAULT:!1}),F(a,{on:function(e,t,n){var i,s;D(e)||H(e),s=_(e,t),i=s.on(r[o],this._onEnd,this,e,t,n),t[h]=i},delegate:function(e,t,n,i){var s=this;t[v]=e.delegate(r[o],function(r){s._onEnd(r,e,t,n,!0)},i)},detachDelegate:function(e,t,n,r){var i=t[v];i&&(i.detach(),t[v]=null),D(e)||B(e)},detach:function(e,t,n){var r=t[h];r&&(r.detach(),t[h]=null),D(e)||B(e)},processArgs:function(e,t){return M(this,e,t)},_onEnd:function(e,t,n,r,i){i&&(t=e[x]);var s=n._extra.standAlone||t.getData(g)||t.getData(m),o=n._extra.preventDefault;s&&(e.changedTouches&&(e.changedTouches.length===1?P(e,e.changedTouches[0]):s=!1),s&&(j(e,o),e.type=a,r.fire(e),t.clearData(m),t.clearData(g)))},PREVENT_DEFAULT:!1})},"3.18.1",{requires:["node-base","event-touch","event-synthetic"]}); PK\}i ,3.18.1/cssgrids-units/cssgrids-units-min.cssnu[/*! Pure v0.4.2 Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. https://github.com/yui/pure/blob/master/LICENSE.md */.yui3-u-1,.yui3-u-1-1,.yui3-u-1-2,.yui3-u-1-3,.yui3-u-2-3,.yui3-u-1-4,.yui3-u-3-4,.yui3-u-1-5,.yui3-u-2-5,.yui3-u-3-5,.yui3-u-4-5,.yui3-u-5-5,.yui3-u-1-6,.yui3-u-5-6,.yui3-u-1-8,.yui3-u-3-8,.yui3-u-5-8,.yui3-u-7-8,.yui3-u-1-12,.yui3-u-5-12,.yui3-u-7-12,.yui3-u-11-12,.yui3-u-1-24,.yui3-u-2-24,.yui3-u-3-24,.yui3-u-4-24,.yui3-u-5-24,.yui3-u-6-24,.yui3-u-7-24,.yui3-u-8-24,.yui3-u-9-24,.yui3-u-10-24,.yui3-u-11-24,.yui3-u-12-24,.yui3-u-13-24,.yui3-u-14-24,.yui3-u-15-24,.yui3-u-16-24,.yui3-u-17-24,.yui3-u-18-24,.yui3-u-19-24,.yui3-u-20-24,.yui3-u-21-24,.yui3-u-22-24,.yui3-u-23-24,.yui3-u-24-24{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.yui3-u-1-24{width:4.1667%;*width:4.1357%}.yui3-u-1-12,.yui3-u-2-24{width:8.3333%;*width:8.3023%}.yui3-u-1-8,.yui3-u-3-24{width:12.5000%;*width:12.4690%}.yui3-u-1-6,.yui3-u-4-24{width:16.6667%;*width:16.6357%}.yui3-u-1-5{width:20%;*width:19.9690%}.yui3-u-5-24{width:20.8333%;*width:20.8023%}.yui3-u-1-4,.yui3-u-6-24{width:25%;*width:24.9690%}.yui3-u-7-24{width:29.1667%;*width:29.1357%}.yui3-u-1-3,.yui3-u-8-24{width:33.3333%;*width:33.3023%}.yui3-u-3-8,.yui3-u-9-24{width:37.5000%;*width:37.4690%}.yui3-u-2-5{width:40%;*width:39.9690%}.yui3-u-5-12,.yui3-u-10-24{width:41.6667%;*width:41.6357%}.yui3-u-11-24{width:45.8333%;*width:45.8023%}.yui3-u-1-2,.yui3-u-12-24{width:50%;*width:49.9690%}.yui3-u-13-24{width:54.1667%;*width:54.1357%}.yui3-u-7-12,.yui3-u-14-24{width:58.3333%;*width:58.3023%}.yui3-u-3-5{width:60%;*width:59.9690%}.yui3-u-5-8,.yui3-u-15-24{width:62.5000%;*width:62.4690%}.yui3-u-2-3,.yui3-u-16-24{width:66.6667%;*width:66.6357%}.yui3-u-17-24{width:70.8333%;*width:70.8023%}.yui3-u-3-4,.yui3-u-18-24{width:75%;*width:74.9690%}.yui3-u-19-24{width:79.1667%;*width:79.1357%}.yui3-u-4-5{width:80%;*width:79.9690%}.yui3-u-5-6,.yui3-u-20-24{width:83.3333%;*width:83.3023%}.yui3-u-7-8,.yui3-u-21-24{width:87.5000%;*width:87.4690%}.yui3-u-11-12,.yui3-u-22-24{width:91.6667%;*width:91.6357%}.yui3-u-23-24{width:95.8333%;*width:95.8023%}.yui3-u-1,.yui3-u-1-1,.yui3-u-5-5,.yui3-u-24-24{width:100%}#yui3-css-stamp.cssgrids-units{display:none} PK\u u (3.18.1/cssgrids-units/cssgrids-units.cssnu[/*! Pure v0.4.2 Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. https://github.com/yui/pure/blob/master/LICENSE.md */ .yui3-u-1, .yui3-u-1-1, .yui3-u-1-2, .yui3-u-1-3, .yui3-u-2-3, .yui3-u-1-4, .yui3-u-3-4, .yui3-u-1-5, .yui3-u-2-5, .yui3-u-3-5, .yui3-u-4-5, .yui3-u-5-5, .yui3-u-1-6, .yui3-u-5-6, .yui3-u-1-8, .yui3-u-3-8, .yui3-u-5-8, .yui3-u-7-8, .yui3-u-1-12, .yui3-u-5-12, .yui3-u-7-12, .yui3-u-11-12, .yui3-u-1-24, .yui3-u-2-24, .yui3-u-3-24, .yui3-u-4-24, .yui3-u-5-24, .yui3-u-6-24, .yui3-u-7-24, .yui3-u-8-24, .yui3-u-9-24, .yui3-u-10-24, .yui3-u-11-24, .yui3-u-12-24, .yui3-u-13-24, .yui3-u-14-24, .yui3-u-15-24, .yui3-u-16-24, .yui3-u-17-24, .yui3-u-18-24, .yui3-u-19-24, .yui3-u-20-24, .yui3-u-21-24, .yui3-u-22-24, .yui3-u-23-24, .yui3-u-24-24 { display: inline-block; *display: inline; zoom: 1; letter-spacing: normal; word-spacing: normal; vertical-align: top; text-rendering: auto; } .yui3-u-1-24 { width: 4.1667%; *width: 4.1357%; } .yui3-u-1-12, .yui3-u-2-24 { width: 8.3333%; *width: 8.3023%; } .yui3-u-1-8, .yui3-u-3-24 { width: 12.5000%; *width: 12.4690%; } .yui3-u-1-6, .yui3-u-4-24 { width: 16.6667%; *width: 16.6357%; } .yui3-u-1-5 { width: 20%; *width: 19.9690%; } .yui3-u-5-24 { width: 20.8333%; *width: 20.8023%; } .yui3-u-1-4, .yui3-u-6-24 { width: 25%; *width: 24.9690%; } .yui3-u-7-24 { width: 29.1667%; *width: 29.1357%; } .yui3-u-1-3, .yui3-u-8-24 { width: 33.3333%; *width: 33.3023%; } .yui3-u-3-8, .yui3-u-9-24 { width: 37.5000%; *width: 37.4690%; } .yui3-u-2-5 { width: 40%; *width: 39.9690%; } .yui3-u-5-12, .yui3-u-10-24 { width: 41.6667%; *width: 41.6357%; } .yui3-u-11-24 { width: 45.8333%; *width: 45.8023%; } .yui3-u-1-2, .yui3-u-12-24 { width: 50%; *width: 49.9690%; } .yui3-u-13-24 { width: 54.1667%; *width: 54.1357%; } .yui3-u-7-12, .yui3-u-14-24 { width: 58.3333%; *width: 58.3023%; } .yui3-u-3-5 { width: 60%; *width: 59.9690%; } .yui3-u-5-8, .yui3-u-15-24 { width: 62.5000%; *width: 62.4690%; } .yui3-u-2-3, .yui3-u-16-24 { width: 66.6667%; *width: 66.6357%; } .yui3-u-17-24 { width: 70.8333%; *width: 70.8023%; } .yui3-u-3-4, .yui3-u-18-24 { width: 75%; *width: 74.9690%; } .yui3-u-19-24 { width: 79.1667%; *width: 79.1357%; } .yui3-u-4-5 { width: 80%; *width: 79.9690%; } .yui3-u-5-6, .yui3-u-20-24 { width: 83.3333%; *width: 83.3023%; } .yui3-u-7-8, .yui3-u-21-24 { width: 87.5000%; *width: 87.4690%; } .yui3-u-11-12, .yui3-u-22-24 { width: 91.6667%; *width: 91.6357%; } .yui3-u-23-24 { width: 95.8333%; *width: 95.8023%; } .yui3-u-1, .yui3-u-1-1, .yui3-u-5-5, .yui3-u-24-24 { width: 100%; } /* YUI CSS Detection Stamp */ #yui3-css-stamp.cssgrids-units { display: none; } PK\w :;;3.18.1/dd-proxy/dd-proxy.jsnu[YUI.add('dd-proxy', function (Y, NAME) { /** * Plugin for dd-drag for creating a proxy drag node, instead of dragging the original node. * @module dd * @submodule dd-proxy */ /** * Plugin for dd-drag for creating a proxy drag node, instead of dragging the original node. * @class DDProxy * @extends Base * @constructor * @namespace Plugin */ var DDM = Y.DD.DDM, NODE = 'node', DRAG_NODE = 'dragNode', HOST = 'host', TRUE = true, proto, P = function() { P.superclass.constructor.apply(this, arguments); }; P.NAME = 'DDProxy'; /** * The Proxy instance will be placed on the Drag instance under the proxy namespace. * @property NS * @default con * @readonly * @protected * @static * @type {String} */ P.NS = 'proxy'; P.ATTRS = { host: { }, /** * Move the original node at the end of the drag. Default: true * @attribute moveOnEnd * @type Boolean */ moveOnEnd: { value: TRUE }, /** * Hide the drag node at the end of the drag. Default: true * @attribute hideOnEnd * @type Boolean */ hideOnEnd: { value: TRUE }, /** * Make the Proxy node assume the size of the original node. Default: true * @attribute resizeFrame * @type Boolean */ resizeFrame: { value: TRUE }, /** * Make the Proxy node appear in the same place as the original node. Default: true * @attribute positionProxy * @type Boolean */ positionProxy: { value: TRUE }, /** * The default border style for the border of the proxy. Default: 1px solid #808080 * @attribute borderStyle * @type Boolean */ borderStyle: { value: '1px solid #808080' }, /** * Should the node be cloned into the proxy for you. Default: false * @attribute cloneNode * @type Boolean */ cloneNode: { value: false } }; proto = { /** * Holds the event handles for setting the proxy * @private * @property _hands */ _hands: null, /** * Handler for the proxy config attribute * @private * @method _init */ _init: function() { if (!DDM._proxy) { DDM._createFrame(); Y.on('domready', Y.bind(this._init, this)); return; } if (!this._hands) { this._hands = []; } var h, h1, host = this.get(HOST), dnode = host.get(DRAG_NODE); if (dnode.compareTo(host.get(NODE))) { if (DDM._proxy) { host.set(DRAG_NODE, DDM._proxy); } } Y.Array.each(this._hands, function(v) { v.detach(); }); h = DDM.on('ddm:start', Y.bind(function() { if (DDM.activeDrag === host) { DDM._setFrame(host); } }, this)); h1 = DDM.on('ddm:end', Y.bind(function() { if (host.get('dragging')) { if (this.get('moveOnEnd')) { host.get(NODE).setXY(host.lastXY); } if (this.get('hideOnEnd')) { host.get(DRAG_NODE).setStyle('display', 'none'); } if (this.get('cloneNode')) { host.get(DRAG_NODE).remove(); host.set(DRAG_NODE, DDM._proxy); } } }, this)); this._hands = [h, h1]; }, initializer: function() { this._init(); }, destructor: function() { var host = this.get(HOST); Y.Array.each(this._hands, function(v) { v.detach(); }); host.set(DRAG_NODE, host.get(NODE)); }, clone: function() { var host = this.get(HOST), n = host.get(NODE), c = n.cloneNode(true); c.all('input[type="radio"]').removeAttribute('name'); delete c._yuid; c.setAttribute('id', Y.guid()); c.setStyle('position', 'absolute'); n.get('parentNode').appendChild(c); host.set(DRAG_NODE, c); return c; } }; Y.namespace('Plugin'); Y.extend(P, Y.Base, proto); Y.Plugin.DDProxy = P; //Add a couple of methods to the DDM Y.mix(DDM, { /** * Create the proxy element if it doesn't already exist and set the DD.DDM._proxy value * @private * @for DDM * @namespace DD * @method _createFrame */ _createFrame: function() { if (!DDM._proxy) { DDM._proxy = TRUE; var p = Y.Node.create('
'), b = Y.one('body'); p.setStyles({ position: 'absolute', display: 'none', zIndex: '999', top: '-999px', left: '-999px' }); b.prepend(p); p.set('id', Y.guid()); p.addClass(DDM.CSS_PREFIX + '-proxy'); DDM._proxy = p; } }, /** * If resizeProxy is set to true (default) it will resize the proxy element to match the size of the Drag Element. * If positionProxy is set to true (default) it will position the proxy element in the same location as the Drag Element. * @private * @for DDM * @namespace DD * @method _setFrame */ _setFrame: function(drag) { var n = drag.get(NODE), d = drag.get(DRAG_NODE), ah, cur = 'auto'; ah = DDM.activeDrag.get('activeHandle'); if (ah) { cur = ah.getStyle('cursor'); } if (cur === 'auto') { cur = DDM.get('dragCursor'); } d.setStyles({ visibility: 'hidden', display: 'block', cursor: cur, border: drag.proxy.get('borderStyle') }); if (drag.proxy.get('cloneNode')) { d = drag.proxy.clone(); } if (drag.proxy.get('resizeFrame')) { d.setStyles({ height: n.get('offsetHeight') + 'px', width: n.get('offsetWidth') + 'px' }); } if (drag.proxy.get('positionProxy')) { d.setXY(drag.nodeXY); } d.setStyle('visibility', 'visible'); } }); //Create the frame when DOM is ready //Y.on('domready', Y.bind(DDM._createFrame, DDM)); }, '3.18.1', {"requires": ["dd-drag"]}); PK\w :;;!3.18.1/dd-proxy/dd-proxy-debug.jsnu[YUI.add('dd-proxy', function (Y, NAME) { /** * Plugin for dd-drag for creating a proxy drag node, instead of dragging the original node. * @module dd * @submodule dd-proxy */ /** * Plugin for dd-drag for creating a proxy drag node, instead of dragging the original node. * @class DDProxy * @extends Base * @constructor * @namespace Plugin */ var DDM = Y.DD.DDM, NODE = 'node', DRAG_NODE = 'dragNode', HOST = 'host', TRUE = true, proto, P = function() { P.superclass.constructor.apply(this, arguments); }; P.NAME = 'DDProxy'; /** * The Proxy instance will be placed on the Drag instance under the proxy namespace. * @property NS * @default con * @readonly * @protected * @static * @type {String} */ P.NS = 'proxy'; P.ATTRS = { host: { }, /** * Move the original node at the end of the drag. Default: true * @attribute moveOnEnd * @type Boolean */ moveOnEnd: { value: TRUE }, /** * Hide the drag node at the end of the drag. Default: true * @attribute hideOnEnd * @type Boolean */ hideOnEnd: { value: TRUE }, /** * Make the Proxy node assume the size of the original node. Default: true * @attribute resizeFrame * @type Boolean */ resizeFrame: { value: TRUE }, /** * Make the Proxy node appear in the same place as the original node. Default: true * @attribute positionProxy * @type Boolean */ positionProxy: { value: TRUE }, /** * The default border style for the border of the proxy. Default: 1px solid #808080 * @attribute borderStyle * @type Boolean */ borderStyle: { value: '1px solid #808080' }, /** * Should the node be cloned into the proxy for you. Default: false * @attribute cloneNode * @type Boolean */ cloneNode: { value: false } }; proto = { /** * Holds the event handles for setting the proxy * @private * @property _hands */ _hands: null, /** * Handler for the proxy config attribute * @private * @method _init */ _init: function() { if (!DDM._proxy) { DDM._createFrame(); Y.on('domready', Y.bind(this._init, this)); return; } if (!this._hands) { this._hands = []; } var h, h1, host = this.get(HOST), dnode = host.get(DRAG_NODE); if (dnode.compareTo(host.get(NODE))) { if (DDM._proxy) { host.set(DRAG_NODE, DDM._proxy); } } Y.Array.each(this._hands, function(v) { v.detach(); }); h = DDM.on('ddm:start', Y.bind(function() { if (DDM.activeDrag === host) { DDM._setFrame(host); } }, this)); h1 = DDM.on('ddm:end', Y.bind(function() { if (host.get('dragging')) { if (this.get('moveOnEnd')) { host.get(NODE).setXY(host.lastXY); } if (this.get('hideOnEnd')) { host.get(DRAG_NODE).setStyle('display', 'none'); } if (this.get('cloneNode')) { host.get(DRAG_NODE).remove(); host.set(DRAG_NODE, DDM._proxy); } } }, this)); this._hands = [h, h1]; }, initializer: function() { this._init(); }, destructor: function() { var host = this.get(HOST); Y.Array.each(this._hands, function(v) { v.detach(); }); host.set(DRAG_NODE, host.get(NODE)); }, clone: function() { var host = this.get(HOST), n = host.get(NODE), c = n.cloneNode(true); c.all('input[type="radio"]').removeAttribute('name'); delete c._yuid; c.setAttribute('id', Y.guid()); c.setStyle('position', 'absolute'); n.get('parentNode').appendChild(c); host.set(DRAG_NODE, c); return c; } }; Y.namespace('Plugin'); Y.extend(P, Y.Base, proto); Y.Plugin.DDProxy = P; //Add a couple of methods to the DDM Y.mix(DDM, { /** * Create the proxy element if it doesn't already exist and set the DD.DDM._proxy value * @private * @for DDM * @namespace DD * @method _createFrame */ _createFrame: function() { if (!DDM._proxy) { DDM._proxy = TRUE; var p = Y.Node.create('
'), b = Y.one('body'); p.setStyles({ position: 'absolute', display: 'none', zIndex: '999', top: '-999px', left: '-999px' }); b.prepend(p); p.set('id', Y.guid()); p.addClass(DDM.CSS_PREFIX + '-proxy'); DDM._proxy = p; } }, /** * If resizeProxy is set to true (default) it will resize the proxy element to match the size of the Drag Element. * If positionProxy is set to true (default) it will position the proxy element in the same location as the Drag Element. * @private * @for DDM * @namespace DD * @method _setFrame */ _setFrame: function(drag) { var n = drag.get(NODE), d = drag.get(DRAG_NODE), ah, cur = 'auto'; ah = DDM.activeDrag.get('activeHandle'); if (ah) { cur = ah.getStyle('cursor'); } if (cur === 'auto') { cur = DDM.get('dragCursor'); } d.setStyles({ visibility: 'hidden', display: 'block', cursor: cur, border: drag.proxy.get('borderStyle') }); if (drag.proxy.get('cloneNode')) { d = drag.proxy.clone(); } if (drag.proxy.get('resizeFrame')) { d.setStyles({ height: n.get('offsetHeight') + 'px', width: n.get('offsetWidth') + 'px' }); } if (drag.proxy.get('positionProxy')) { d.setXY(drag.nodeXY); } d.setStyle('visibility', 'visible'); } }); //Create the frame when DOM is ready //Y.on('domready', Y.bind(DDM._createFrame, DDM)); }, '3.18.1', {"requires": ["dd-drag"]}); PK\Pj3.18.1/dd-proxy/dd-proxy-min.jsnu[YUI.add("dd-proxy",function(e,t){var n=e.DD.DDM,r="node",i="dragNode",s="host",o=!0,u,a=function(){a.superclass.constructor.apply(this,arguments)};a.NAME="DDProxy",a.NS="proxy",a.ATTRS={host:{},moveOnEnd:{value:o},hideOnEnd:{value:o},resizeFrame:{value:o},positionProxy:{value:o},borderStyle:{value:"1px solid #808080"},cloneNode:{value:!1}},u={_hands:null,_init:function(){if(!n._proxy){n._createFrame(),e.on("domready",e.bind(this._init,this));return}this._hands||(this._hands=[]);var t,o,u=this.get(s),a=u.get(i);a.compareTo(u.get(r))&&n._proxy&&u.set(i,n._proxy),e.Array.each(this._hands,function(e){e.detach()}),t=n.on("ddm:start",e.bind(function(){n.activeDrag===u&&n._setFrame(u)},this)),o=n.on("ddm:end",e.bind(function(){u.get("dragging")&&(this.get("moveOnEnd")&&u.get(r).setXY(u.lastXY),this.get("hideOnEnd")&&u.get(i).setStyle("display","none"),this.get("cloneNode")&&(u.get(i).remove(),u.set(i,n._proxy)))},this)),this._hands=[t,o]},initializer:function(){this._init()},destructor:function(){var t=this.get(s);e.Array.each(this._hands,function(e){e.detach()}),t.set(i,t.get(r))},clone:function(){var t=this.get(s),n=t.get(r),o=n.cloneNode(!0);return o.all('input[type="radio"]').removeAttribute("name"),delete o._yuid,o.setAttribute("id",e.guid()),o.setStyle("position","absolute"),n.get("parentNode").appendChild(o),t.set(i,o),o}},e.namespace("Plugin"),e.extend(a,e.Base,u),e.Plugin.DDProxy=a,e.mix(n,{_createFrame:function(){if(!n._proxy){n._proxy=o;var t=e.Node.create("
"),r=e.one("body");t.setStyles({position:"absolute",display:"none",zIndex:"999",top:"-999px",left:"-999px"}),r.prepend(t),t.set("id",e.guid()),t.addClass(n.CSS_PREFIX+"-proxy"),n._proxy=t}},_setFrame:function(e){var t=e.get(r),s=e.get(i),o,u="auto";o=n.activeDrag.get("activeHandle"),o&&(u=o.getStyle("cursor")),u==="auto"&&(u=n.get("dragCursor")),s.setStyles({visibility:"hidden",display:"block",cursor:u,border:e.proxy.get("borderStyle")}),e.proxy.get("cloneNode")&&(s=e.proxy.clone()),e.proxy.get("resizeFrame")&&s.setStyles({height:t.get("offsetHeight")+"px",width:t.get("offsetWidth")+"px"}),e.proxy.get("positionProxy")&&s.setXY(e.nodeXY),s.setStyle("visibility","visible")}})},"3.18.1",{requires:["dd-drag"]}); PK\36+3.18.1/tabview-plugin/tabview-plugin-min.jsnu[YUI.add("tabview-plugin",function(e,t){function n(){n.superclass.constructor.apply(this,arguments)}n.NAME="tabviewPlugin",n.NS="tabs",e.extend(n,e.TabviewBase),e.namespace("Plugin"),e.Plugin.Tabview=n},"3.18.1",{requires:["tabview-base"]}); PK\x@:cc'3.18.1/tabview-plugin/tabview-plugin.jsnu[YUI.add('tabview-plugin', function (Y, NAME) { function TabviewPlugin() { TabviewPlugin.superclass.constructor.apply(this, arguments); } TabviewPlugin.NAME = 'tabviewPlugin'; TabviewPlugin.NS = 'tabs'; Y.extend(TabviewPlugin, Y.TabviewBase); Y.namespace('Plugin'); Y.Plugin.Tabview = TabviewPlugin; }, '3.18.1', {"requires": ["tabview-base"]}); PK\x@:cc-3.18.1/tabview-plugin/tabview-plugin-debug.jsnu[YUI.add('tabview-plugin', function (Y, NAME) { function TabviewPlugin() { TabviewPlugin.superclass.constructor.apply(this, arguments); } TabviewPlugin.NAME = 'tabviewPlugin'; TabviewPlugin.NS = 'tabs'; Y.extend(TabviewPlugin, Y.TabviewBase); Y.namespace('Plugin'); Y.Plugin.Tabview = TabviewPlugin; }, '3.18.1', {"requires": ["tabview-base"]}); PK\!=݇#3.18.1/series-bar/series-bar-min.jsnu[YUI.add("series-bar",function(e,t){e.BarSeries=e.Base.create("barSeries",e.MarkerSeries,[e.Histogram],{_getMarkerDimensions:function(e,t,n,r){var i={top:t+r};return e>=this._leftOrigin?(i.left=this._leftOrigin,i.calculatedSize=e-i.left):(i.left=e,i.calculatedSize=this._leftOrigin-e),i},updateMarkerState:function(e,t){if(this._markers&&this._markers[t]){var n=this._copyObject(this.get("styles").marker),r,i=this._getState(e),s=this.get("xcoords"),o=this.get("ycoords"),u=this._markers[t],a,f=this.get("seriesTypeCollection"),l=f?f.length:0,c,h=0,p=0,d,v=0,m=[],g=this.get("order"),y;r=i==="off"||!n[i]?n:n[i],r.fill.color=this._getItemColor(r.fill.color,t),r.border.color=this._getItemColor(r.border.color,t),y=this._getMarkerDimensions(s[t],o[t],n.height,p),r.width=y.calculatedSize,r.height=Math.min(this._maxSize,r.height),u.set(r);for(;vv&&(p=h),p-=h/2;for(v=0;v= this._leftOrigin) { config.left = this._leftOrigin; config.calculatedSize = xcoord - config.left; } else { config.left = xcoord; config.calculatedSize = this._leftOrigin - xcoord; } return config; }, /** * Resizes and positions markers based on a mouse interaction. * * @method updateMarkerState * @param {String} type state of the marker * @param {Number} i index of the marker * @protected */ updateMarkerState: function(type, i) { if(this._markers && this._markers[i]) { var styles = this._copyObject(this.get("styles").marker), markerStyles, state = this._getState(type), xcoords = this.get("xcoords"), ycoords = this.get("ycoords"), marker = this._markers[i], markers, seriesCollection = this.get("seriesTypeCollection"), seriesLen = seriesCollection ? seriesCollection.length : 0, seriesStyles, seriesSize = 0, offset = 0, renderer, n = 0, ys = [], order = this.get("order"), config; markerStyles = state === "off" || !styles[state] ? styles : styles[state]; markerStyles.fill.color = this._getItemColor(markerStyles.fill.color, i); markerStyles.border.color = this._getItemColor(markerStyles.border.color, i); config = this._getMarkerDimensions(xcoords[i], ycoords[i], styles.height, offset); markerStyles.width = config.calculatedSize; markerStyles.height = Math.min(this._maxSize, markerStyles.height); marker.set(markerStyles); for(; n < seriesLen; ++n) { ys[n] = ycoords[i] + seriesSize; seriesStyles = seriesCollection[n].get("styles").marker; seriesSize += Math.min(this._maxSize, seriesStyles.height); if(order > n) { offset = seriesSize; } offset -= seriesSize/2; } for(n = 0; n < seriesLen; ++n) { markers = seriesCollection[n].get("markers"); if(markers) { renderer = markers[i]; if(renderer && renderer !== undefined) { renderer.set("y", (ys[n] - seriesSize/2)); } } } } } }, { ATTRS: { /** * Read-only attribute indicating the type of series. * * @attribute type * @type String * @default bar */ type: { value: "bar" }, /** * Indicates the direction of the category axis that the bars are plotted against. * * @attribute direction * @type String */ direction: { value: "vertical" } /** * Style properties used for drawing markers. This attribute is inherited from `MarkerSeries`. Below are the default values: *
*
fill
A hash containing the following values: *
*
color
Color of the fill. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:
* `["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"]` *
*
alpha
Number from 0 to 1 indicating the opacity of the marker fill. The default value is 1.
*
*
*
border
A hash containing the following values: *
*
color
Color of the border. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:
* `["#205096", "#b38206", "#000000", "#94001e", "#9d6fa0", "#e55b00", "#5e85c9", "#adab9e", "#6ac291", "#006457"]` *
alpha
Number from 0 to 1 indicating the opacity of the marker border. The default value is 1.
*
weight
Number indicating the width of the border. The default value is 1.
*
*
*
height
indicates the width of the marker. The default value is 12.
*
over
hash containing styles for markers when highlighted by a `mouseover` event. The default * values for each style is null. When an over style is not set, the non-over value will be used. For example, * the default value for `marker.over.fill.color` is equivalent to `marker.fill.color`.
*
* * @attribute styles * @type Object */ } }); }, '3.18.1', {"requires": ["series-marker", "series-histogram-base"]}); PK\JP Eee%3.18.1/series-bar/series-bar-debug.jsnu[YUI.add('series-bar', function (Y, NAME) { /** * Provides functionality for creating a bar series. * * @module charts * @submodule series-bar */ /** * The BarSeries class renders bars positioned vertically along a category or time axis. The bars' * lengths are proportional to the values they represent along a horizontal axis. * and the relevant data points. * * @class BarSeries * @extends MarkerSeries * @uses Histogram * @constructor * @param {Object} config (optional) Configuration parameters. * @submodule series-bar */ Y.BarSeries = Y.Base.create("barSeries", Y.MarkerSeries, [Y.Histogram], { /** * Helper method for calculating the size of markers. * * @method _getMarkerDimensions * @param {Number} xcoord The x-coordinate representing the data point for the marker. * @param {Number} ycoord The y-coordinate representing the data point for the marker. * @param {Number} calculatedSize The calculated size for the marker. For a `BarSeries` is it the width. For a `ColumnSeries` it is the height. * @param {Number} offset Distance of position offset dictated by other marker series in the same graph. * @return Object * @private */ _getMarkerDimensions: function(xcoord, ycoord, calculatedSize, offset) { var config = { top: ycoord + offset }; if(xcoord >= this._leftOrigin) { config.left = this._leftOrigin; config.calculatedSize = xcoord - config.left; } else { config.left = xcoord; config.calculatedSize = this._leftOrigin - xcoord; } return config; }, /** * Resizes and positions markers based on a mouse interaction. * * @method updateMarkerState * @param {String} type state of the marker * @param {Number} i index of the marker * @protected */ updateMarkerState: function(type, i) { if(this._markers && this._markers[i]) { var styles = this._copyObject(this.get("styles").marker), markerStyles, state = this._getState(type), xcoords = this.get("xcoords"), ycoords = this.get("ycoords"), marker = this._markers[i], markers, seriesCollection = this.get("seriesTypeCollection"), seriesLen = seriesCollection ? seriesCollection.length : 0, seriesStyles, seriesSize = 0, offset = 0, renderer, n = 0, ys = [], order = this.get("order"), config; markerStyles = state === "off" || !styles[state] ? styles : styles[state]; markerStyles.fill.color = this._getItemColor(markerStyles.fill.color, i); markerStyles.border.color = this._getItemColor(markerStyles.border.color, i); config = this._getMarkerDimensions(xcoords[i], ycoords[i], styles.height, offset); markerStyles.width = config.calculatedSize; markerStyles.height = Math.min(this._maxSize, markerStyles.height); marker.set(markerStyles); for(; n < seriesLen; ++n) { ys[n] = ycoords[i] + seriesSize; seriesStyles = seriesCollection[n].get("styles").marker; seriesSize += Math.min(this._maxSize, seriesStyles.height); if(order > n) { offset = seriesSize; } offset -= seriesSize/2; } for(n = 0; n < seriesLen; ++n) { markers = seriesCollection[n].get("markers"); if(markers) { renderer = markers[i]; if(renderer && renderer !== undefined) { renderer.set("y", (ys[n] - seriesSize/2)); } } } } } }, { ATTRS: { /** * Read-only attribute indicating the type of series. * * @attribute type * @type String * @default bar */ type: { value: "bar" }, /** * Indicates the direction of the category axis that the bars are plotted against. * * @attribute direction * @type String */ direction: { value: "vertical" } /** * Style properties used for drawing markers. This attribute is inherited from `MarkerSeries`. Below are the default values: *
*
fill
A hash containing the following values: *
*
color
Color of the fill. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:
* `["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"]` *
*
alpha
Number from 0 to 1 indicating the opacity of the marker fill. The default value is 1.
*
*
*
border
A hash containing the following values: *
*
color
Color of the border. The default value is determined by the order of the series on the graph. The color * will be retrieved from the below array:
* `["#205096", "#b38206", "#000000", "#94001e", "#9d6fa0", "#e55b00", "#5e85c9", "#adab9e", "#6ac291", "#006457"]` *
alpha
Number from 0 to 1 indicating the opacity of the marker border. The default value is 1.
*
weight
Number indicating the width of the border. The default value is 1.
*
*
*
height
indicates the width of the marker. The default value is 12.
*
over
hash containing styles for markers when highlighted by a `mouseover` event. The default * values for each style is null. When an over style is not set, the non-over value will be used. For example, * the default value for `marker.over.fill.color` is equivalent to `marker.fill.color`.
*
* * @attribute styles * @type Object */ } }); }, '3.18.1', {"requires": ["series-marker", "series-histogram-base"]}); PK\pQu,,!3.18.1/dd-ddm-base/dd-ddm-base.jsnu[YUI.add('dd-ddm-base', function (Y, NAME) { /** * Provides the base Drag Drop Manager required for making a Node draggable. * @module dd * @submodule dd-ddm-base */ /** * Provides the base Drag Drop Manager required for making a Node draggable. * @class DDM * @extends Base * @constructor * @namespace DD */ var DDMBase = function() { DDMBase.superclass.constructor.apply(this, arguments); }; DDMBase.NAME = 'ddm'; DDMBase.ATTRS = { /** * The cursor to apply when dragging, if shimmed the shim will get the cursor. * @attribute dragCursor * @type String */ dragCursor: { value: 'move' }, /** * The number of pixels to move to start a drag operation, default is 3. * @attribute clickPixelThresh * @type Number */ clickPixelThresh: { value: 3 }, /** * The number of milliseconds a mousedown has to pass to start a drag operation, default is 1000. * @attribute clickTimeThresh * @type Number */ clickTimeThresh: { value: 1000 }, /** * The number of milliseconds to throttle the mousemove event. Default: 150 * @attribute throttleTime * @type Number */ throttleTime: { //value: 150 value: -1 }, /** * This attribute only works if the dd-drop module is active. It will set the dragMode (point, intersect, strict) of all future Drag instances. * @attribute dragMode * @type String */ dragMode: { value: 'point', setter: function(mode) { this._setDragMode(mode); return mode; } } }; Y.extend(DDMBase, Y.Base, { _createPG: function() {}, /** * flag set when we activate our first drag, so DDM can start listening for events. * @property _active * @type {Boolean} */ _active: null, /** * Handler for dragMode attribute setter. * @private * @method _setDragMode * @param {String|Number} mode The Number value or the String for the DragMode to default all future drag instances to. * @return Number The Mode to be set */ _setDragMode: function(mode) { if (mode === null) { mode = Y.DD.DDM.get('dragMode'); } switch (mode) { case 1: case 'intersect': return 1; case 2: case 'strict': return 2; case 0: case 'point': return 0; } return 0; }, /** * The PREFIX to attach to all DD CSS class names * @property CSS_PREFIX * @type {String} */ CSS_PREFIX: Y.ClassNameManager.getClassName('dd'), _activateTargets: function() {}, /** * Holder for all registered drag elements. * @private * @property _drags * @type {Array} */ _drags: [], /** * A reference to the currently active draggable object. * @property activeDrag * @type {Drag} */ activeDrag: false, /** * Adds a reference to the drag object to the DDM._drags array, called in the constructor of Drag. * @private * @method _regDrag * @param {Drag} d The Drag object */ _regDrag: function(d) { if (this.getDrag(d.get('node'))) { return false; } if (!this._active) { this._setupListeners(); } this._drags.push(d); return true; }, /** * Remove this drag object from the DDM._drags array. * @private * @method _unregDrag * @param {Drag} d The drag object. */ _unregDrag: function(d) { var tmp = []; Y.Array.each(this._drags, function(n) { if (n !== d) { tmp[tmp.length] = n; } }); this._drags = tmp; }, /** * Add the document listeners. * @private * @method _setupListeners */ _setupListeners: function() { this._createPG(); this._active = true; var doc = Y.one(Y.config.doc); doc.on('mousemove', Y.throttle(Y.bind(this._docMove, this), this.get('throttleTime'))); doc.on('mouseup', Y.bind(this._end, this)); }, /** * Internal method used by Drag to signal the start of a drag operation * @private * @method _start */ _start: function() { this.fire('ddm:start'); this._startDrag(); }, /** * Factory method to be overwritten by other DDM's * @private * @method _startDrag * @param {Number} x The x position of the drag element * @param {Number} y The y position of the drag element * @param {Number} w The width of the drag element * @param {Number} h The height of the drag element */ _startDrag: function() {}, /** * Factory method to be overwritten by other DDM's * @private * @method _endDrag */ _endDrag: function() {}, _dropMove: function() {}, /** * Internal method used by Drag to signal the end of a drag operation * @private * @method _end */ _end: function() { if (this.activeDrag) { this._shimming = false; this._endDrag(); this.fire('ddm:end'); this.activeDrag.end.call(this.activeDrag); this.activeDrag = null; } }, /** * Method will forcefully stop a drag operation. For example calling this from inside an ESC keypress handler will stop this drag. * @method stopDrag * @chainable */ stopDrag: function() { if (this.activeDrag) { this._end(); } return this; }, /** * Set to true when drag starts and useShim is true. Used in pairing with _docMove * @private * @property _shimming * @see _docMove * @type {Boolean} */ _shimming: false, /** * Internal listener for the mousemove on Document. Checks if the shim is in place to only call _move once per mouse move * @private * @method _docMove * @param {EventFacade} ev The Dom mousemove Event */ _docMove: function(ev) { if (!this._shimming) { this._move(ev); } }, /** * Internal listener for the mousemove DOM event to pass to the Drag's move method. * @private * @method _move * @param {EventFacade} ev The Dom mousemove Event */ _move: function(ev) { if (this.activeDrag) { this.activeDrag._move.call(this.activeDrag, ev); this._dropMove(); } }, /** * //TODO Private, rename??... * Helper method to use to set the gutter from the attribute setter. * CSS style string for gutter: '5 0' (sets top and bottom to 5px, left and right to 0px), '1 2 3 4' (top 1px, right 2px, bottom 3px, left 4px) * @private * @method cssSizestoObject * @param {String} gutter CSS style string for gutter * @return {Object} The gutter Object Literal. */ cssSizestoObject: function(gutter) { var x = gutter.split(' '); switch (x.length) { case 1: x[1] = x[2] = x[3] = x[0]; break; case 2: x[2] = x[0]; x[3] = x[1]; break; case 3: x[3] = x[1]; break; } return { top : parseInt(x[0],10), right : parseInt(x[1],10), bottom: parseInt(x[2],10), left : parseInt(x[3],10) }; }, /** * Get a valid Drag instance back from a Node or a selector string, false otherwise * @method getDrag * @param {String/Object} node The Node instance or Selector string to check for a valid Drag Object * @return {Object} */ getDrag: function(node) { var drag = false, n = Y.one(node); if (n instanceof Y.Node) { Y.Array.each(this._drags, function(v) { if (n.compareTo(v.get('node'))) { drag = v; } }); } return drag; }, /** * Swap the position of 2 nodes based on their CSS positioning. * @method swapPosition * @param {Node} n1 The first node to swap * @param {Node} n2 The first node to swap * @return {Node} */ swapPosition: function(n1, n2) { n1 = Y.DD.DDM.getNode(n1); n2 = Y.DD.DDM.getNode(n2); var xy1 = n1.getXY(), xy2 = n2.getXY(); n1.setXY(xy2); n2.setXY(xy1); return n1; }, /** * Return a node instance from the given node, selector string or Y.Base extended object. * @method getNode * @param {Node/Object/String} n The node to resolve. * @return {Node} */ getNode: function(n) { if (n instanceof Y.Node) { return n; } if (n && n.get) { if (Y.Widget && (n instanceof Y.Widget)) { n = n.get('boundingBox'); } else { n = n.get('node'); } } else { n = Y.one(n); } return n; }, /** * Swap the position of 2 nodes based on their DOM location. * @method swapNode * @param {Node} n1 The first node to swap * @param {Node} n2 The first node to swap * @return {Node} */ swapNode: function(n1, n2) { n1 = Y.DD.DDM.getNode(n1); n2 = Y.DD.DDM.getNode(n2); var p = n2.get('parentNode'), s = n2.get('nextSibling'); if (s === n1) { p.insertBefore(n1, n2); } else if (n2 === n1.get('nextSibling')) { p.insertBefore(n2, n1); } else { n1.get('parentNode').replaceChild(n2, n1); p.insertBefore(n1, s); } return n1; } }); Y.namespace('DD'); Y.DD.DDM = new DDMBase(); /** * Fires from the DDM before all drag events fire. * @event ddm:start * @type {CustomEvent} */ /** * Fires from the DDM after the DDM finishes, before the drag end events. * @event ddm:end * @type {CustomEvent} */ }, '3.18.1', {"requires": ["node", "base", "yui-throttle", "classnamemanager"]}); PK\pQu,,'3.18.1/dd-ddm-base/dd-ddm-base-debug.jsnu[YUI.add('dd-ddm-base', function (Y, NAME) { /** * Provides the base Drag Drop Manager required for making a Node draggable. * @module dd * @submodule dd-ddm-base */ /** * Provides the base Drag Drop Manager required for making a Node draggable. * @class DDM * @extends Base * @constructor * @namespace DD */ var DDMBase = function() { DDMBase.superclass.constructor.apply(this, arguments); }; DDMBase.NAME = 'ddm'; DDMBase.ATTRS = { /** * The cursor to apply when dragging, if shimmed the shim will get the cursor. * @attribute dragCursor * @type String */ dragCursor: { value: 'move' }, /** * The number of pixels to move to start a drag operation, default is 3. * @attribute clickPixelThresh * @type Number */ clickPixelThresh: { value: 3 }, /** * The number of milliseconds a mousedown has to pass to start a drag operation, default is 1000. * @attribute clickTimeThresh * @type Number */ clickTimeThresh: { value: 1000 }, /** * The number of milliseconds to throttle the mousemove event. Default: 150 * @attribute throttleTime * @type Number */ throttleTime: { //value: 150 value: -1 }, /** * This attribute only works if the dd-drop module is active. It will set the dragMode (point, intersect, strict) of all future Drag instances. * @attribute dragMode * @type String */ dragMode: { value: 'point', setter: function(mode) { this._setDragMode(mode); return mode; } } }; Y.extend(DDMBase, Y.Base, { _createPG: function() {}, /** * flag set when we activate our first drag, so DDM can start listening for events. * @property _active * @type {Boolean} */ _active: null, /** * Handler for dragMode attribute setter. * @private * @method _setDragMode * @param {String|Number} mode The Number value or the String for the DragMode to default all future drag instances to. * @return Number The Mode to be set */ _setDragMode: function(mode) { if (mode === null) { mode = Y.DD.DDM.get('dragMode'); } switch (mode) { case 1: case 'intersect': return 1; case 2: case 'strict': return 2; case 0: case 'point': return 0; } return 0; }, /** * The PREFIX to attach to all DD CSS class names * @property CSS_PREFIX * @type {String} */ CSS_PREFIX: Y.ClassNameManager.getClassName('dd'), _activateTargets: function() {}, /** * Holder for all registered drag elements. * @private * @property _drags * @type {Array} */ _drags: [], /** * A reference to the currently active draggable object. * @property activeDrag * @type {Drag} */ activeDrag: false, /** * Adds a reference to the drag object to the DDM._drags array, called in the constructor of Drag. * @private * @method _regDrag * @param {Drag} d The Drag object */ _regDrag: function(d) { if (this.getDrag(d.get('node'))) { return false; } if (!this._active) { this._setupListeners(); } this._drags.push(d); return true; }, /** * Remove this drag object from the DDM._drags array. * @private * @method _unregDrag * @param {Drag} d The drag object. */ _unregDrag: function(d) { var tmp = []; Y.Array.each(this._drags, function(n) { if (n !== d) { tmp[tmp.length] = n; } }); this._drags = tmp; }, /** * Add the document listeners. * @private * @method _setupListeners */ _setupListeners: function() { this._createPG(); this._active = true; var doc = Y.one(Y.config.doc); doc.on('mousemove', Y.throttle(Y.bind(this._docMove, this), this.get('throttleTime'))); doc.on('mouseup', Y.bind(this._end, this)); }, /** * Internal method used by Drag to signal the start of a drag operation * @private * @method _start */ _start: function() { this.fire('ddm:start'); this._startDrag(); }, /** * Factory method to be overwritten by other DDM's * @private * @method _startDrag * @param {Number} x The x position of the drag element * @param {Number} y The y position of the drag element * @param {Number} w The width of the drag element * @param {Number} h The height of the drag element */ _startDrag: function() {}, /** * Factory method to be overwritten by other DDM's * @private * @method _endDrag */ _endDrag: function() {}, _dropMove: function() {}, /** * Internal method used by Drag to signal the end of a drag operation * @private * @method _end */ _end: function() { if (this.activeDrag) { this._shimming = false; this._endDrag(); this.fire('ddm:end'); this.activeDrag.end.call(this.activeDrag); this.activeDrag = null; } }, /** * Method will forcefully stop a drag operation. For example calling this from inside an ESC keypress handler will stop this drag. * @method stopDrag * @chainable */ stopDrag: function() { if (this.activeDrag) { this._end(); } return this; }, /** * Set to true when drag starts and useShim is true. Used in pairing with _docMove * @private * @property _shimming * @see _docMove * @type {Boolean} */ _shimming: false, /** * Internal listener for the mousemove on Document. Checks if the shim is in place to only call _move once per mouse move * @private * @method _docMove * @param {EventFacade} ev The Dom mousemove Event */ _docMove: function(ev) { if (!this._shimming) { this._move(ev); } }, /** * Internal listener for the mousemove DOM event to pass to the Drag's move method. * @private * @method _move * @param {EventFacade} ev The Dom mousemove Event */ _move: function(ev) { if (this.activeDrag) { this.activeDrag._move.call(this.activeDrag, ev); this._dropMove(); } }, /** * //TODO Private, rename??... * Helper method to use to set the gutter from the attribute setter. * CSS style string for gutter: '5 0' (sets top and bottom to 5px, left and right to 0px), '1 2 3 4' (top 1px, right 2px, bottom 3px, left 4px) * @private * @method cssSizestoObject * @param {String} gutter CSS style string for gutter * @return {Object} The gutter Object Literal. */ cssSizestoObject: function(gutter) { var x = gutter.split(' '); switch (x.length) { case 1: x[1] = x[2] = x[3] = x[0]; break; case 2: x[2] = x[0]; x[3] = x[1]; break; case 3: x[3] = x[1]; break; } return { top : parseInt(x[0],10), right : parseInt(x[1],10), bottom: parseInt(x[2],10), left : parseInt(x[3],10) }; }, /** * Get a valid Drag instance back from a Node or a selector string, false otherwise * @method getDrag * @param {String/Object} node The Node instance or Selector string to check for a valid Drag Object * @return {Object} */ getDrag: function(node) { var drag = false, n = Y.one(node); if (n instanceof Y.Node) { Y.Array.each(this._drags, function(v) { if (n.compareTo(v.get('node'))) { drag = v; } }); } return drag; }, /** * Swap the position of 2 nodes based on their CSS positioning. * @method swapPosition * @param {Node} n1 The first node to swap * @param {Node} n2 The first node to swap * @return {Node} */ swapPosition: function(n1, n2) { n1 = Y.DD.DDM.getNode(n1); n2 = Y.DD.DDM.getNode(n2); var xy1 = n1.getXY(), xy2 = n2.getXY(); n1.setXY(xy2); n2.setXY(xy1); return n1; }, /** * Return a node instance from the given node, selector string or Y.Base extended object. * @method getNode * @param {Node/Object/String} n The node to resolve. * @return {Node} */ getNode: function(n) { if (n instanceof Y.Node) { return n; } if (n && n.get) { if (Y.Widget && (n instanceof Y.Widget)) { n = n.get('boundingBox'); } else { n = n.get('node'); } } else { n = Y.one(n); } return n; }, /** * Swap the position of 2 nodes based on their DOM location. * @method swapNode * @param {Node} n1 The first node to swap * @param {Node} n2 The first node to swap * @return {Node} */ swapNode: function(n1, n2) { n1 = Y.DD.DDM.getNode(n1); n2 = Y.DD.DDM.getNode(n2); var p = n2.get('parentNode'), s = n2.get('nextSibling'); if (s === n1) { p.insertBefore(n1, n2); } else if (n2 === n1.get('nextSibling')) { p.insertBefore(n2, n1); } else { n1.get('parentNode').replaceChild(n2, n1); p.insertBefore(n1, s); } return n1; } }); Y.namespace('DD'); Y.DD.DDM = new DDMBase(); /** * Fires from the DDM before all drag events fire. * @event ddm:start * @type {CustomEvent} */ /** * Fires from the DDM after the DDM finishes, before the drag end events. * @event ddm:end * @type {CustomEvent} */ }, '3.18.1', {"requires": ["node", "base", "yui-throttle", "classnamemanager"]}); PK\v@*= = %3.18.1/dd-ddm-base/dd-ddm-base-min.jsnu[YUI.add("dd-ddm-base",function(e,t){var n=function(){n.superclass.constructor.apply(this,arguments)};n.NAME="ddm",n.ATTRS={dragCursor:{value:"move"},clickPixelThresh:{value:3},clickTimeThresh:{value:1e3},throttleTime:{value:-1},dragMode:{value:"point",setter:function(e){return this._setDragMode(e),e}}},e.extend(n,e.Base,{_createPG:function(){},_active:null,_setDragMode:function(t){t===null&&(t=e.DD.DDM.get("dragMode"));switch(t){case 1:case"intersect":return 1;case 2:case"strict":return 2;case 0:case"point":return 0}return 0},CSS_PREFIX:e.ClassNameManager.getClassName("dd"),_activateTargets:function(){},_drags:[],activeDrag:!1,_regDrag:function(e){return this.getDrag(e.get("node"))?!1:(this._active||this._setupListeners(),this._drags.push(e),!0)},_unregDrag:function(t){var n=[];e.Array.each(this._drags,function(e){e!==t&&(n[n.length]=e)}),this._drags=n},_setupListeners:function(){this._createPG(),this._active=!0;var t=e.one(e.config.doc);t.on("mousemove",e.throttle(e.bind(this._docMove,this),this.get("throttleTime"))),t.on("mouseup",e.bind(this._end,this))},_start:function(){this.fire("ddm:start"),this._startDrag()},_startDrag:function(){},_endDrag:function(){},_dropMove:function(){},_end:function(){this.activeDrag&&(this._shimming=!1,this._endDrag(),this.fire("ddm:end"),this.activeDrag.end.call(this.activeDrag),this.activeDrag=null)},stopDrag:function(){return this.activeDrag&&this._end(),this},_shimming:!1,_docMove:function(e){this._shimming||this._move(e)},_move:function(e){this.activeDrag&&(this.activeDrag._move.call(this.activeDrag,e),this._dropMove())},cssSizestoObject:function(e){var t=e.split(" ");switch(t.length){case 1:t[1]=t[2]=t[3]=t[0];break;case 2:t[2]=t[0],t[3]=t[1];break;case 3:t[3]=t[1]}return{top:parseInt(t[0],10),right:parseInt(t[1],10),bottom:parseInt(t[2],10),left:parseInt(t[3],10)}},getDrag:function(t){var n=!1,r=e.one(t);return r instanceof e.Node&&e.Array.each(this._drags,function(e){r.compareTo(e.get("node"))&&(n=e)}),n},swapPosition:function(t,n){t=e.DD.DDM.getNode(t),n=e.DD.DDM.getNode(n);var r=t.getXY(),i=n.getXY();return t.setXY(i),n.setXY(r),t},getNode:function(t){return t instanceof e.Node?t:(t&&t.get?e.Widget&&t instanceof e.Widget?t=t.get("boundingBox"):t=t.get("node"):t=e.one(t),t)},swapNode:function(t,n){t=e.DD.DDM.getNode(t),n=e.DD.DDM.getNode(n);var r=n.get("parentNode"),i=n.get("nextSibling");return i===t?r.insertBefore(t,n):n===t.get("nextSibling")?r.insertBefore(n,t):(t.get("parentNode").replaceChild(n,t),r.insertBefore(t,i)),t}}),e.namespace("DD"),e.DD.DDM=new n},"3.18.1",{requires:["node","base","yui-throttle","classnamemanager"]}); PK\8S)3.18.1/tabview-base/tabview-base-debug.jsnu[YUI.add('tabview-base', function (Y, NAME) { var getClassName = Y.ClassNameManager.getClassName, TABVIEW = 'tabview', TAB = 'tab', PANEL = 'panel', SELECTED = 'selected', EMPTY_OBJ = {}, DOT = '.', TabviewBase = function() { this.init.apply(this, arguments); }; TabviewBase.NAME = 'tabviewBase'; TabviewBase._classNames = { tabview: getClassName(TABVIEW), tabviewPanel: getClassName(TABVIEW, PANEL), tabviewList: getClassName(TABVIEW, 'list'), tab: getClassName(TAB), tabLabel: getClassName(TAB, 'label'), tabPanel: getClassName(TAB, PANEL), selectedTab: getClassName(TAB, SELECTED), selectedPanel: getClassName(TAB, PANEL, SELECTED) }; TabviewBase._queries = { tabview: DOT + TabviewBase._classNames.tabview, tabviewList: '> ul', tab: '> ul > li', tabLabel: '> ul > li > a', tabviewPanel: '> div', tabPanel: '> div > div', selectedTab: '> ul > ' + DOT + TabviewBase._classNames.selectedTab, selectedPanel: '> div ' + DOT + TabviewBase._classNames.selectedPanel }; Y.mix(TabviewBase.prototype, { init: function(config) { config = config || EMPTY_OBJ; this._node = config.host || Y.one(config.node); this.refresh(); }, initClassNames: function(index) { var _classNames = Y.TabviewBase._classNames; Y.Object.each(Y.TabviewBase._queries, function(query, name) { // this === tabview._node if (_classNames[name]) { var result = this.all(query); if (index !== undefined) { result = result.item(index); } if (result) { result.addClass(_classNames[name]); } } }, this._node); this._node.addClass(_classNames.tabview); }, _select: function(index) { var _classNames = Y.TabviewBase._classNames, _queries = Y.TabviewBase._queries, node = this._node, oldItem = node.one(_queries.selectedTab), oldContent = node.one(_queries.selectedPanel), newItem = node.all(_queries.tab).item(index), newContent = node.all(_queries.tabPanel).item(index); if (oldItem) { oldItem.removeClass(_classNames.selectedTab); } if (oldContent) { oldContent.removeClass(_classNames.selectedPanel); } if (newItem) { newItem.addClass(_classNames.selectedTab); } if (newContent) { newContent.addClass(_classNames.selectedPanel); } }, initState: function() { var _queries = Y.TabviewBase._queries, node = this._node, activeNode = node.one(_queries.selectedTab), activeIndex = activeNode ? node.all(_queries.tab).indexOf(activeNode) : 0; this._select(activeIndex); }, // collapse extra space between list-items _scrubTextNodes: function() { this._node.one(Y.TabviewBase._queries.tabviewList).get('childNodes').each(function(node) { if (node.get('nodeType') === 3) { // text node node.remove(); } }); }, // base renderer only enlivens existing markup refresh: function() { this._scrubTextNodes(); this.initClassNames(); this.initState(); this.initEvents(); }, tabEventName: 'click', initEvents: function() { // TODO: detach prefix for delegate? // this._node.delegate('tabview|' + this.tabEventName), this._node.delegate(this.tabEventName, this.onTabEvent, Y.TabviewBase._queries.tab, this ); }, onTabEvent: function(e) { e.preventDefault(); this._select(this._node.all(Y.TabviewBase._queries.tab).indexOf(e.currentTarget)); }, destroy: function() { this._node.detach(this.tabEventName); } }); Y.TabviewBase = TabviewBase; }, '3.18.1', {"requires": ["node-event-delegate", "classnamemanager"]}); PK\ '3.18.1/tabview-base/tabview-base-min.jsnu[YUI.add("tabview-base",function(e,t){var n=e.ClassNameManager.getClassName,r="tabview",i="tab",s="panel",o="selected",u={},a=".",f=function(){this.init.apply(this,arguments)};f.NAME="tabviewBase",f._classNames={tabview:n(r),tabviewPanel:n(r,s),tabviewList:n(r,"list"),tab:n(i),tabLabel:n(i,"label"),tabPanel:n(i,s),selectedTab:n(i,o),selectedPanel:n(i,s,o)},f._queries={tabview:a+f._classNames.tabview,tabviewList:"> ul",tab:"> ul > li",tabLabel:"> ul > li > a",tabviewPanel:"> div",tabPanel:"> div > div",selectedTab:"> ul > "+a+f._classNames.selectedTab,selectedPanel:"> div "+a+f._classNames.selectedPanel},e.mix(f.prototype,{init:function(t){t=t||u,this._node=t.host||e.one(t.node),this.refresh()},initClassNames:function(t){var n=e.TabviewBase._classNames;e.Object.each(e.TabviewBase._queries,function(e,r){if(n[r]){var i=this.all(e);t!==undefined&&(i=i.item(t)),i&&i.addClass(n[r])}},this._node),this._node.addClass(n.tabview)},_select:function(t){var n=e.TabviewBase._classNames,r=e.TabviewBase._queries,i=this._node,s=i.one(r.selectedTab),o=i.one(r.selectedPanel),u=i.all(r.tab).item(t),a=i.all(r.tabPanel).item(t);s&&s.removeClass(n.selectedTab),o&&o.removeClass(n.selectedPanel),u&&u.addClass(n.selectedTab),a&&a.addClass(n.selectedPanel)},initState:function(){var t=e.TabviewBase._queries,n=this._node,r=n.one(t.selectedTab),i=r?n.all(t.tab).indexOf(r):0;this._select(i)},_scrubTextNodes:function(){this._node.one(e.TabviewBase._queries.tabviewList).get("childNodes").each(function(e){e.get("nodeType")===3&&e.remove()})},refresh:function(){this._scrubTextNodes(),this.initClassNames(),this.initState(),this.initEvents()},tabEventName:"click",initEvents:function(){this._node.delegate(this.tabEventName,this.onTabEvent,e.TabviewBase._queries.tab,this)},onTabEvent:function(t){t.preventDefault(),this._select(this._node.all(e.TabviewBase._queries.tab).indexOf(t.currentTarget))},destroy:function(){this._node.detach(this.tabEventName)}}),e.TabviewBase=f},"3.18.1",{requires:["node-event-delegate","classnamemanager"]}); PK\8S#3.18.1/tabview-base/tabview-base.jsnu[YUI.add('tabview-base', function (Y, NAME) { var getClassName = Y.ClassNameManager.getClassName, TABVIEW = 'tabview', TAB = 'tab', PANEL = 'panel', SELECTED = 'selected', EMPTY_OBJ = {}, DOT = '.', TabviewBase = function() { this.init.apply(this, arguments); }; TabviewBase.NAME = 'tabviewBase'; TabviewBase._classNames = { tabview: getClassName(TABVIEW), tabviewPanel: getClassName(TABVIEW, PANEL), tabviewList: getClassName(TABVIEW, 'list'), tab: getClassName(TAB), tabLabel: getClassName(TAB, 'label'), tabPanel: getClassName(TAB, PANEL), selectedTab: getClassName(TAB, SELECTED), selectedPanel: getClassName(TAB, PANEL, SELECTED) }; TabviewBase._queries = { tabview: DOT + TabviewBase._classNames.tabview, tabviewList: '> ul', tab: '> ul > li', tabLabel: '> ul > li > a', tabviewPanel: '> div', tabPanel: '> div > div', selectedTab: '> ul > ' + DOT + TabviewBase._classNames.selectedTab, selectedPanel: '> div ' + DOT + TabviewBase._classNames.selectedPanel }; Y.mix(TabviewBase.prototype, { init: function(config) { config = config || EMPTY_OBJ; this._node = config.host || Y.one(config.node); this.refresh(); }, initClassNames: function(index) { var _classNames = Y.TabviewBase._classNames; Y.Object.each(Y.TabviewBase._queries, function(query, name) { // this === tabview._node if (_classNames[name]) { var result = this.all(query); if (index !== undefined) { result = result.item(index); } if (result) { result.addClass(_classNames[name]); } } }, this._node); this._node.addClass(_classNames.tabview); }, _select: function(index) { var _classNames = Y.TabviewBase._classNames, _queries = Y.TabviewBase._queries, node = this._node, oldItem = node.one(_queries.selectedTab), oldContent = node.one(_queries.selectedPanel), newItem = node.all(_queries.tab).item(index), newContent = node.all(_queries.tabPanel).item(index); if (oldItem) { oldItem.removeClass(_classNames.selectedTab); } if (oldContent) { oldContent.removeClass(_classNames.selectedPanel); } if (newItem) { newItem.addClass(_classNames.selectedTab); } if (newContent) { newContent.addClass(_classNames.selectedPanel); } }, initState: function() { var _queries = Y.TabviewBase._queries, node = this._node, activeNode = node.one(_queries.selectedTab), activeIndex = activeNode ? node.all(_queries.tab).indexOf(activeNode) : 0; this._select(activeIndex); }, // collapse extra space between list-items _scrubTextNodes: function() { this._node.one(Y.TabviewBase._queries.tabviewList).get('childNodes').each(function(node) { if (node.get('nodeType') === 3) { // text node node.remove(); } }); }, // base renderer only enlivens existing markup refresh: function() { this._scrubTextNodes(); this.initClassNames(); this.initState(); this.initEvents(); }, tabEventName: 'click', initEvents: function() { // TODO: detach prefix for delegate? // this._node.delegate('tabview|' + this.tabEventName), this._node.delegate(this.tabEventName, this.onTabEvent, Y.TabviewBase._queries.tab, this ); }, onTabEvent: function(e) { e.preventDefault(); this._select(this._node.all(Y.TabviewBase._queries.tab).indexOf(e.currentTarget)); }, destroy: function() { this._node.detach(this.tabEventName); } }); Y.TabviewBase = TabviewBase; }, '3.18.1', {"requires": ["node-event-delegate", "classnamemanager"]}); PK\+==23.18.1/cssgrids-responsive/cssgrids-responsive.cssnu[/*! Pure v0.4.2 Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. https://github.com/yui/pure/blob/master/LICENSE.md */ /*csslint regex-selectors:false, known-properties:false, duplicate-properties:false*/ .yui3-g { letter-spacing: -0.31em; /* Webkit: collapse white-space between units */ *letter-spacing: normal; /* reset IE < 8 */ *word-spacing: -0.43em; /* IE < 8: collapse white-space between units */ text-rendering: optimizespeed; /* Webkit: fixes text-rendering: optimizeLegibility */ /* Sets the font stack to fonts known to work properly with the above letter and word spacings. See: https://github.com/yui/pure/issues/41/ The following font stack makes Pure Grids work on all known environments. * FreeSans: Ships with many Linux distros, including Ubuntu * Arimo: Ships with Chrome OS. Arimo has to be defined before Helvetica and Arial to get picked up by the browser, even though neither is available in Chrome OS. * Droid Sans: Ships with all versions of Android. * Helvetica, Arial, sans-serif: Common font stack on OS X and Windows. */ font-family: FreeSans, Arimo, "Droid Sans", Helvetica, Arial, sans-serif; /* Use flexbox when possible to avoid `letter-spacing` side-effects. NOTE: Firefox (as of 25) does not currently support flex-wrap, so the `-moz-` prefix version is omitted. */ display: -webkit-flex; -webkit-flex-flow: row wrap; /* IE10 uses display: flexbox */ display: -ms-flexbox; -ms-flex-flow: row wrap; } /* Opera as of 12 on Windows needs word-spacing. The ".opera-only" selector is used to prevent actual prefocus styling and is not required in markup. */ .opera-only :-o-prefocus, .yui3-g { word-spacing: -0.43em; } .yui3-u { display: inline-block; *display: inline; /* IE < 8: fake inline-block */ zoom: 1; letter-spacing: normal; word-spacing: normal; vertical-align: top; text-rendering: auto; } /* Resets the font family back to the OS/browser's default sans-serif font, this the same font stack that Normalize.css sets for the `body`. */ .yui3-g [class *= "yui3-u"] { font-family: sans-serif; } .yui3-u-1, .yui3-u-1-1, .yui3-u-1-2, .yui3-u-1-3, .yui3-u-2-3, .yui3-u-1-4, .yui3-u-3-4, .yui3-u-1-5, .yui3-u-2-5, .yui3-u-3-5, .yui3-u-4-5, .yui3-u-5-5, .yui3-u-1-6, .yui3-u-5-6, .yui3-u-1-8, .yui3-u-3-8, .yui3-u-5-8, .yui3-u-7-8, .yui3-u-1-12, .yui3-u-5-12, .yui3-u-7-12, .yui3-u-11-12, .yui3-u-1-24, .yui3-u-2-24, .yui3-u-3-24, .yui3-u-4-24, .yui3-u-5-24, .yui3-u-6-24, .yui3-u-7-24, .yui3-u-8-24, .yui3-u-9-24, .yui3-u-10-24, .yui3-u-11-24, .yui3-u-12-24, .yui3-u-13-24, .yui3-u-14-24, .yui3-u-15-24, .yui3-u-16-24, .yui3-u-17-24, .yui3-u-18-24, .yui3-u-19-24, .yui3-u-20-24, .yui3-u-21-24, .yui3-u-22-24, .yui3-u-23-24, .yui3-u-24-24 { display: inline-block; *display: inline; zoom: 1; letter-spacing: normal; word-spacing: normal; vertical-align: top; text-rendering: auto; } .yui3-u-1-24 { width: 4.1667%; *width: 4.1357%; } .yui3-u-1-12, .yui3-u-2-24 { width: 8.3333%; *width: 8.3023%; } .yui3-u-1-8, .yui3-u-3-24 { width: 12.5000%; *width: 12.4690%; } .yui3-u-1-6, .yui3-u-4-24 { width: 16.6667%; *width: 16.6357%; } .yui3-u-1-5 { width: 20%; *width: 19.9690%; } .yui3-u-5-24 { width: 20.8333%; *width: 20.8023%; } .yui3-u-1-4, .yui3-u-6-24 { width: 25%; *width: 24.9690%; } .yui3-u-7-24 { width: 29.1667%; *width: 29.1357%; } .yui3-u-1-3, .yui3-u-8-24 { width: 33.3333%; *width: 33.3023%; } .yui3-u-3-8, .yui3-u-9-24 { width: 37.5000%; *width: 37.4690%; } .yui3-u-2-5 { width: 40%; *width: 39.9690%; } .yui3-u-5-12, .yui3-u-10-24 { width: 41.6667%; *width: 41.6357%; } .yui3-u-11-24 { width: 45.8333%; *width: 45.8023%; } .yui3-u-1-2, .yui3-u-12-24 { width: 50%; *width: 49.9690%; } .yui3-u-13-24 { width: 54.1667%; *width: 54.1357%; } .yui3-u-7-12, .yui3-u-14-24 { width: 58.3333%; *width: 58.3023%; } .yui3-u-3-5 { width: 60%; *width: 59.9690%; } .yui3-u-5-8, .yui3-u-15-24 { width: 62.5000%; *width: 62.4690%; } .yui3-u-2-3, .yui3-u-16-24 { width: 66.6667%; *width: 66.6357%; } .yui3-u-17-24 { width: 70.8333%; *width: 70.8023%; } .yui3-u-3-4, .yui3-u-18-24 { width: 75%; *width: 74.9690%; } .yui3-u-19-24 { width: 79.1667%; *width: 79.1357%; } .yui3-u-4-5 { width: 80%; *width: 79.9690%; } .yui3-u-5-6, .yui3-u-20-24 { width: 83.3333%; *width: 83.3023%; } .yui3-u-7-8, .yui3-u-21-24 { width: 87.5000%; *width: 87.4690%; } .yui3-u-11-12, .yui3-u-22-24 { width: 91.6667%; *width: 91.6357%; } .yui3-u-23-24 { width: 95.8333%; *width: 95.8023%; } .yui3-u-1, .yui3-u-1-1, .yui3-u-5-5, .yui3-u-24-24 { width: 100%; } /*csslint regex-selectors:false, known-properties:false, duplicate-properties:false*/ .yui3-g-r { letter-spacing: -0.31em; *letter-spacing: normal; *word-spacing: -0.43em; /* Sets the font stack to fonts known to work properly with the above letter and word spacings. See: https://github.com/yui/pure/issues/41/ The following font stack makes Pure Grids work on all known environments. * FreeSans: Ships with many Linux distros, including Ubuntu * Arimo: Ships with Chrome OS. Arimo has to be defined before Helvetica and Arial to get picked up by the browser, even though neither is available in Chrome OS. * Droid Sans: Ships with all versions of Android. * Helvetica, Arial, sans-serif: Common font stack on OS X and Windows. */ font-family: FreeSans, Arimo, "Droid Sans", Helvetica, Arial, sans-serif; /* Use flexbox when possible to avoid `letter-spacing` side-effects. NOTE: Firefox (as of 25) does not currently support flex-wrap, so the `-moz-` prefix version is omitted. */ display: -webkit-flex; -webkit-flex-flow: row wrap; /* IE10 uses display: flexbox */ display: -ms-flexbox; -ms-flex-flow: row wrap; } /* Opera as of 12 on Windows needs word-spacing. The ".opera-only" selector is used to prevent actual prefocus styling and is not required in markup. */ .opera-only :-o-prefocus, .yui3-g-r { word-spacing: -0.43em; } /* Resets the font family back to the OS/browser's default sans-serif font, this the same font stack that Normalize.css sets for the `body`. */ .yui3-g-r [class *= "yui3-u"] { font-family: sans-serif; } .yui3-g-r img { max-width: 100%; height: auto; } @media (min-width: 980px) { .yui3-visible-phone { display: none; } .yui3-visible-tablet { display: none; } .yui3-hidden-desktop { display: none; } } @media (max-width: 480px) { .yui3-g-r > .yui3-u, .yui3-g-r > [class *= "yui3-u-"] { width: 100%; } } @media (max-width: 767px) { .yui3-g-r > .yui3-u, .yui3-g-r > [class *= "yui3-u-"] { width: 100%; } .yui3-hidden-phone { display: none; } .yui3-visible-desktop { display: none; } } @media (min-width: 768px) and (max-width: 979px) { .yui3-hidden-tablet { display: none; } .yui3-visible-desktop { display: none; } } /* YUI CSS Detection Stamp */ #yui3-css-stamp.cssgrids-responsive { display: none; } PK\; ff63.18.1/cssgrids-responsive/cssgrids-responsive-min.cssnu[/*! Pure v0.4.2 Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. https://github.com/yui/pure/blob/master/LICENSE.md */.yui3-g{letter-spacing:-0.31em;*letter-spacing:normal;*word-spacing:-0.43em;text-rendering:optimizespeed;font-family:FreeSans,Arimo,"Droid Sans",Helvetica,Arial,sans-serif;display:-webkit-flex;-webkit-flex-flow:row wrap;display:-ms-flexbox;-ms-flex-flow:row wrap}.opera-only :-o-prefocus,.yui3-g{word-spacing:-0.43em}.yui3-u{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.yui3-g [class *= "yui3-u"]{font-family:sans-serif}.yui3-u-1,.yui3-u-1-1,.yui3-u-1-2,.yui3-u-1-3,.yui3-u-2-3,.yui3-u-1-4,.yui3-u-3-4,.yui3-u-1-5,.yui3-u-2-5,.yui3-u-3-5,.yui3-u-4-5,.yui3-u-5-5,.yui3-u-1-6,.yui3-u-5-6,.yui3-u-1-8,.yui3-u-3-8,.yui3-u-5-8,.yui3-u-7-8,.yui3-u-1-12,.yui3-u-5-12,.yui3-u-7-12,.yui3-u-11-12,.yui3-u-1-24,.yui3-u-2-24,.yui3-u-3-24,.yui3-u-4-24,.yui3-u-5-24,.yui3-u-6-24,.yui3-u-7-24,.yui3-u-8-24,.yui3-u-9-24,.yui3-u-10-24,.yui3-u-11-24,.yui3-u-12-24,.yui3-u-13-24,.yui3-u-14-24,.yui3-u-15-24,.yui3-u-16-24,.yui3-u-17-24,.yui3-u-18-24,.yui3-u-19-24,.yui3-u-20-24,.yui3-u-21-24,.yui3-u-22-24,.yui3-u-23-24,.yui3-u-24-24{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.yui3-u-1-24{width:4.1667%;*width:4.1357%}.yui3-u-1-12,.yui3-u-2-24{width:8.3333%;*width:8.3023%}.yui3-u-1-8,.yui3-u-3-24{width:12.5000%;*width:12.4690%}.yui3-u-1-6,.yui3-u-4-24{width:16.6667%;*width:16.6357%}.yui3-u-1-5{width:20%;*width:19.9690%}.yui3-u-5-24{width:20.8333%;*width:20.8023%}.yui3-u-1-4,.yui3-u-6-24{width:25%;*width:24.9690%}.yui3-u-7-24{width:29.1667%;*width:29.1357%}.yui3-u-1-3,.yui3-u-8-24{width:33.3333%;*width:33.3023%}.yui3-u-3-8,.yui3-u-9-24{width:37.5000%;*width:37.4690%}.yui3-u-2-5{width:40%;*width:39.9690%}.yui3-u-5-12,.yui3-u-10-24{width:41.6667%;*width:41.6357%}.yui3-u-11-24{width:45.8333%;*width:45.8023%}.yui3-u-1-2,.yui3-u-12-24{width:50%;*width:49.9690%}.yui3-u-13-24{width:54.1667%;*width:54.1357%}.yui3-u-7-12,.yui3-u-14-24{width:58.3333%;*width:58.3023%}.yui3-u-3-5{width:60%;*width:59.9690%}.yui3-u-5-8,.yui3-u-15-24{width:62.5000%;*width:62.4690%}.yui3-u-2-3,.yui3-u-16-24{width:66.6667%;*width:66.6357%}.yui3-u-17-24{width:70.8333%;*width:70.8023%}.yui3-u-3-4,.yui3-u-18-24{width:75%;*width:74.9690%}.yui3-u-19-24{width:79.1667%;*width:79.1357%}.yui3-u-4-5{width:80%;*width:79.9690%}.yui3-u-5-6,.yui3-u-20-24{width:83.3333%;*width:83.3023%}.yui3-u-7-8,.yui3-u-21-24{width:87.5000%;*width:87.4690%}.yui3-u-11-12,.yui3-u-22-24{width:91.6667%;*width:91.6357%}.yui3-u-23-24{width:95.8333%;*width:95.8023%}.yui3-u-1,.yui3-u-1-1,.yui3-u-5-5,.yui3-u-24-24{width:100%}.yui3-g-r{letter-spacing:-0.31em;*letter-spacing:normal;*word-spacing:-0.43em;font-family:FreeSans,Arimo,"Droid Sans",Helvetica,Arial,sans-serif;display:-webkit-flex;-webkit-flex-flow:row wrap;display:-ms-flexbox;-ms-flex-flow:row wrap}.opera-only :-o-prefocus,.yui3-g-r{word-spacing:-0.43em}.yui3-g-r [class *= "yui3-u"]{font-family:sans-serif}.yui3-g-r img{max-width:100%;height:auto}@media(min-width:980px){.yui3-visible-phone{display:none}.yui3-visible-tablet{display:none}.yui3-hidden-desktop{display:none}}@media(max-width:480px){.yui3-g-r>.yui3-u,.yui3-g-r>[class *= "yui3-u-"]{width:100%}}@media(max-width:767px){.yui3-g-r>.yui3-u,.yui3-g-r>[class *= "yui3-u-"]{width:100%}.yui3-hidden-phone{display:none}.yui3-visible-desktop{display:none}}@media(min-width:768px) and (max-width:979px){.yui3-hidden-tablet{display:none}.yui3-visible-desktop{display:none}}#yui3-css-stamp.cssgrids-responsive{display:none} PK\ktkt%3.18.1/widget-stdmod/widget-stdmod.jsnu[YUI.add('widget-stdmod', function (Y, NAME) { /** * Provides standard module support for Widgets through an extension. * * @module widget-stdmod */ var L = Y.Lang, Node = Y.Node, UA = Y.UA, Widget = Y.Widget, EMPTY = "", HD = "hd", BD = "bd", FT = "ft", HEADER = "header", BODY = "body", FOOTER = "footer", FILL_HEIGHT = "fillHeight", STDMOD = "stdmod", NODE_SUFFIX = "Node", CONTENT_SUFFIX = "Content", FIRST_CHILD = "firstChild", CHILD_NODES = "childNodes", OWNER_DOCUMENT = "ownerDocument", CONTENT_BOX = "contentBox", HEIGHT = "height", OFFSET_HEIGHT = "offsetHeight", AUTO = "auto", HeaderChange = "headerContentChange", BodyChange = "bodyContentChange", FooterChange = "footerContentChange", FillHeightChange = "fillHeightChange", HeightChange = "heightChange", ContentUpdate = "contentUpdate", RENDERUI = "renderUI", BINDUI = "bindUI", SYNCUI = "syncUI", APPLY_PARSED_CONFIG = "_applyParsedConfig", UI = Y.Widget.UI_SRC; /** * Widget extension, which can be used to add Standard Module support to the * base Widget class, through the Base.build * method. *

* The extension adds header, body and footer sections to the Widget's content box and * provides the corresponding methods and attributes to modify the contents of these sections. *

* @class WidgetStdMod * @param {Object} The user configuration object */ function StdMod(config) {} /** * Constant used to refer the the standard module header, in methods which expect a section specifier * * @property HEADER * @static * @type String */ StdMod.HEADER = HEADER; /** * Constant used to refer the the standard module body, in methods which expect a section specifier * * @property BODY * @static * @type String */ StdMod.BODY = BODY; /** * Constant used to refer the the standard module footer, in methods which expect a section specifier * * @property FOOTER * @static * @type String */ StdMod.FOOTER = FOOTER; /** * Constant used to specify insertion position, when adding content to sections of the standard module in * methods which expect a "where" argument. *

* Inserts new content before the sections existing content. *

* @property AFTER * @static * @type String */ StdMod.AFTER = "after"; /** * Constant used to specify insertion position, when adding content to sections of the standard module in * methods which expect a "where" argument. *

* Inserts new content before the sections existing content. *

* @property BEFORE * @static * @type String */ StdMod.BEFORE = "before"; /** * Constant used to specify insertion position, when adding content to sections of the standard module in * methods which expect a "where" argument. *

* Replaces the sections existing content, with new content. *

* @property REPLACE * @static * @type String */ StdMod.REPLACE = "replace"; var STD_HEADER = StdMod.HEADER, STD_BODY = StdMod.BODY, STD_FOOTER = StdMod.FOOTER, HEADER_CONTENT = STD_HEADER + CONTENT_SUFFIX, FOOTER_CONTENT = STD_FOOTER + CONTENT_SUFFIX, BODY_CONTENT = STD_BODY + CONTENT_SUFFIX; /** * Static property used to define the default attribute * configuration introduced by WidgetStdMod. * * @property ATTRS * @type Object * @static */ StdMod.ATTRS = { /** * @attribute headerContent * @type HTML * @default undefined * @description The content to be added to the header section. This will replace any existing content * in the header. If you want to append, or insert new content, use the setStdModContent method. */ headerContent: { value:null }, /** * @attribute footerContent * @type HTML * @default undefined * @description The content to be added to the footer section. This will replace any existing content * in the footer. If you want to append, or insert new content, use the setStdModContent method. */ footerContent: { value:null }, /** * @attribute bodyContent * @type HTML * @default undefined * @description The content to be added to the body section. This will replace any existing content * in the body. If you want to append, or insert new content, use the setStdModContent method. */ bodyContent: { value:null }, /** * @attribute fillHeight * @type {String} * @default WidgetStdMod.BODY * @description The section (WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER) which should be resized to fill the height of the standard module, when a * height is set on the Widget. If a height is not set on the widget, then all sections are sized based on * their content. */ fillHeight: { value: StdMod.BODY, validator: function(val) { return this._validateFillHeight(val); } } }; /** * The HTML parsing rules for the WidgetStdMod class. * * @property HTML_PARSER * @static * @type Object */ StdMod.HTML_PARSER = { headerContent: function(contentBox) { return this._parseStdModHTML(STD_HEADER); }, bodyContent: function(contentBox) { return this._parseStdModHTML(STD_BODY); }, footerContent : function(contentBox) { return this._parseStdModHTML(STD_FOOTER); } }; /** * Static hash of default class names used for the header, * body and footer sections of the standard module, keyed by * the section identifier (WidgetStdMod.STD_HEADER, WidgetStdMod.STD_BODY, WidgetStdMod.STD_FOOTER) * * @property SECTION_CLASS_NAMES * @static * @type Object */ StdMod.SECTION_CLASS_NAMES = { header: Widget.getClassName(HD), body: Widget.getClassName(BD), footer: Widget.getClassName(FT) }; /** * The template HTML strings for each of the standard module sections. Section entries are keyed by the section constants, * WidgetStdMod.HEADER, WidgetStdMod.BODY, WidgetStdMod.FOOTER, and contain the HTML to be added for each section. * e.g. *
     *    {
     *       header : '<div class="yui-widget-hd"></div>',
     *       body : '<div class="yui-widget-bd"></div>',
     *       footer : '<div class="yui-widget-ft"></div>'
     *    }
     * 
* @property TEMPLATES * @type Object * @static */ StdMod.TEMPLATES = { header : '
', body : '
', footer : '
' }; StdMod.prototype = { initializer : function() { this._stdModNode = this.get(CONTENT_BOX); Y.before(this._renderUIStdMod, this, RENDERUI); Y.before(this._bindUIStdMod, this, BINDUI); Y.before(this._syncUIStdMod, this, SYNCUI); }, /** * Synchronizes the UI to match the Widgets standard module state. *

* This method is invoked after syncUI is invoked for the Widget class * using YUI's aop infrastructure. *

* @method _syncUIStdMod * @protected */ _syncUIStdMod : function() { var stdModParsed = this._stdModParsed; if (!stdModParsed || !stdModParsed[HEADER_CONTENT]) { this._uiSetStdMod(STD_HEADER, this.get(HEADER_CONTENT)); } if (!stdModParsed || !stdModParsed[BODY_CONTENT]) { this._uiSetStdMod(STD_BODY, this.get(BODY_CONTENT)); } if (!stdModParsed || !stdModParsed[FOOTER_CONTENT]) { this._uiSetStdMod(STD_FOOTER, this.get(FOOTER_CONTENT)); } this._uiSetFillHeight(this.get(FILL_HEIGHT)); }, /** * Creates/Initializes the DOM for standard module support. *

* This method is invoked after renderUI is invoked for the Widget class * using YUI's aop infrastructure. *

* @method _renderUIStdMod * @protected */ _renderUIStdMod : function() { this._stdModNode.addClass(Widget.getClassName(STDMOD)); this._renderStdModSections(); //This normally goes in bindUI but in order to allow setStdModContent() to work before renderUI //stage, these listeners should be set up at the earliest possible time. this.after(HeaderChange, this._afterHeaderChange); this.after(BodyChange, this._afterBodyChange); this.after(FooterChange, this._afterFooterChange); }, _renderStdModSections : function() { if (L.isValue(this.get(HEADER_CONTENT))) { this._renderStdMod(STD_HEADER); } if (L.isValue(this.get(BODY_CONTENT))) { this._renderStdMod(STD_BODY); } if (L.isValue(this.get(FOOTER_CONTENT))) { this._renderStdMod(STD_FOOTER); } }, /** * Binds event listeners responsible for updating the UI state in response to * Widget standard module related state changes. *

* This method is invoked after bindUI is invoked for the Widget class * using YUI's aop infrastructure. *

* @method _bindUIStdMod * @protected */ _bindUIStdMod : function() { // this.after(HeaderChange, this._afterHeaderChange); // this.after(BodyChange, this._afterBodyChange); // this.after(FooterChange, this._afterFooterChange); this.after(FillHeightChange, this._afterFillHeightChange); this.after(HeightChange, this._fillHeight); this.after(ContentUpdate, this._fillHeight); }, /** * Default attribute change listener for the headerContent attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterHeaderChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterHeaderChange : function(e) { if (e.src !== UI) { this._uiSetStdMod(STD_HEADER, e.newVal, e.stdModPosition); } }, /** * Default attribute change listener for the bodyContent attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterBodyChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterBodyChange : function(e) { if (e.src !== UI) { this._uiSetStdMod(STD_BODY, e.newVal, e.stdModPosition); } }, /** * Default attribute change listener for the footerContent attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterFooterChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterFooterChange : function(e) { if (e.src !== UI) { this._uiSetStdMod(STD_FOOTER, e.newVal, e.stdModPosition); } }, /** * Default attribute change listener for the fillHeight attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterFillHeightChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterFillHeightChange: function (e) { this._uiSetFillHeight(e.newVal); }, /** * Default validator for the fillHeight attribute. Verifies that the * value set is a valid section specifier - one of WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER, * or a falsey value if fillHeight is to be disabled. * * @method _validateFillHeight * @protected * @param {String} val The section which should be setup to fill height, or false/null to disable fillHeight * @return true if valid, false if not */ _validateFillHeight : function(val) { return !val || val == StdMod.BODY || val == StdMod.HEADER || val == StdMod.FOOTER; }, /** * Updates the rendered UI, to resize the provided section so that the standard module fills out * the specified widget height. Note: This method does not check whether or not a height is set * on the Widget. * * @method _uiSetFillHeight * @protected * @param {String} fillSection A valid section specifier - one of WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER */ _uiSetFillHeight : function(fillSection) { var fillNode = this.getStdModNode(fillSection); var currNode = this._currFillNode; if (currNode && fillNode !== currNode){ currNode.setStyle(HEIGHT, EMPTY); } if (fillNode) { this._currFillNode = fillNode; } this._fillHeight(); }, /** * Updates the rendered UI, to resize the current section specified by the fillHeight attribute, so * that the standard module fills out the Widget height. If a height has not been set on Widget, * the section is not resized (height is set to "auto"). * * @method _fillHeight * @private */ _fillHeight : function() { if (this.get(FILL_HEIGHT)) { var height = this.get(HEIGHT); if (height != EMPTY && height != AUTO) { this.fillHeight(this.getStdModNode(this.get(FILL_HEIGHT))); } } }, /** * Updates the rendered UI, adding the provided content (either an HTML string, or node reference), * to the specified section. The content is either added before, after or replaces existing content * in the section, based on the value of the where argument. * * @method _uiSetStdMod * @protected * * @param {String} section The section to be updated. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @param {String | Node} content The new content (either as an HTML string, or Node reference) to add to the section * @param {String} where Optional. Either WidgetStdMod.AFTER, WidgetStdMod.BEFORE or WidgetStdMod.REPLACE. * If not provided, the content will replace existing content in the section. */ _uiSetStdMod : function(section, content, where) { // Using isValue, so that "" is valid content if (L.isValue(content)) { var node = this.getStdModNode(section, true); this._addStdModContent(node, content, where); this.set(section + CONTENT_SUFFIX, this._getStdModContent(section), {src:UI}); } else { this._eraseStdMod(section); } this.fire(ContentUpdate); }, /** * Creates the DOM node for the given section, and inserts it into the correct location in the contentBox. * * @method _renderStdMod * @protected * @param {String} section The section to create/render. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @return {Node} A reference to the added section node */ _renderStdMod : function(section) { var contentBox = this.get(CONTENT_BOX), sectionNode = this._findStdModSection(section); if (!sectionNode) { sectionNode = this._getStdModTemplate(section); } this._insertStdModSection(contentBox, section, sectionNode); this[section + NODE_SUFFIX] = sectionNode; return this[section + NODE_SUFFIX]; }, /** * Removes the DOM node for the given section. * * @method _eraseStdMod * @protected * @param {String} section The section to remove. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. */ _eraseStdMod : function(section) { var sectionNode = this.getStdModNode(section); if (sectionNode) { sectionNode.remove(true); delete this[section + NODE_SUFFIX]; } }, /** * Helper method to insert the Node for the given section into the correct location in the contentBox. * * @method _insertStdModSection * @private * @param {Node} contentBox A reference to the Widgets content box. * @param {String} section The section to create/render. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @param {Node} sectionNode The Node for the section. */ _insertStdModSection : function(contentBox, section, sectionNode) { var fc = contentBox.get(FIRST_CHILD); if (section === STD_FOOTER || !fc) { contentBox.appendChild(sectionNode); } else { if (section === STD_HEADER) { contentBox.insertBefore(sectionNode, fc); } else { var footer = this[STD_FOOTER + NODE_SUFFIX]; if (footer) { contentBox.insertBefore(sectionNode, footer); } else { contentBox.appendChild(sectionNode); } } } }, /** * Gets a new Node reference for the given standard module section, by cloning * the stored template node. * * @method _getStdModTemplate * @protected * @param {String} section The section to create a new node for. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @return {Node} The new Node instance for the section */ _getStdModTemplate : function(section) { return Node.create(StdMod.TEMPLATES[section], this._stdModNode.get(OWNER_DOCUMENT)); }, /** * Helper method to add content to a StdMod section node. * The content is added either before, after or replaces the existing node content * based on the value of the where argument. * * @method _addStdModContent * @private * * @param {Node} node The section Node to be updated. * @param {Node|NodeList|String} children The new content Node, NodeList or String to be added to section Node provided. * @param {String} where Optional. Either WidgetStdMod.AFTER, WidgetStdMod.BEFORE or WidgetStdMod.REPLACE. * If not provided, the content will replace existing content in the Node. */ _addStdModContent : function(node, children, where) { // StdMod where to Node where switch (where) { case StdMod.BEFORE: // 0 is before fistChild where = 0; break; case StdMod.AFTER: // undefined is appendChild where = undefined; break; default: // replace is replace, not specified is replace where = StdMod.REPLACE; } node.insert(children, where); }, /** * Helper method to obtain the precise height of the node provided, including padding and border. * The height could be a sub-pixel value for certain browsers, such as Firefox 3. * * @method _getPreciseHeight * @private * @param {Node} node The node for which the precise height is required. * @return {Number} The height of the Node including borders and padding, possibly a float. */ _getPreciseHeight : function(node) { var height = (node) ? node.get(OFFSET_HEIGHT) : 0, getBCR = "getBoundingClientRect"; if (node && node.hasMethod(getBCR)) { var preciseRegion = node.invoke(getBCR); if (preciseRegion) { height = preciseRegion.bottom - preciseRegion.top; } } return height; }, /** * Helper method to to find the rendered node for the given section, * if it exists. * * @method _findStdModSection * @private * @param {String} section The section for which the render Node is to be found. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @return {Node} The rendered node for the given section, or null if not found. */ _findStdModSection: function(section) { return this.get(CONTENT_BOX).one("> ." + StdMod.SECTION_CLASS_NAMES[section]); }, /** * Utility method, used by WidgetStdMods HTML_PARSER implementation * to extract data for each section from markup. * * @method _parseStdModHTML * @private * @param {String} section * @return {String} Inner HTML string with the contents of the section */ _parseStdModHTML : function(section) { var node = this._findStdModSection(section); if (node) { if (!this._stdModParsed) { this._stdModParsed = {}; Y.before(this._applyStdModParsedConfig, this, APPLY_PARSED_CONFIG); } this._stdModParsed[section + CONTENT_SUFFIX] = 1; return node.get("innerHTML"); } return null; }, /** * This method is injected before the _applyParsedConfig step in * the application of HTML_PARSER, and sets up the state to * identify whether or not we should remove the current DOM content * or not, based on whether or not the current content attribute value * was extracted from the DOM, or provided by the user configuration * * @method _applyStdModParsedConfig * @private */ _applyStdModParsedConfig : function(node, cfg, parsedCfg) { var parsed = this._stdModParsed; if (parsed) { parsed[HEADER_CONTENT] = !(HEADER_CONTENT in cfg) && (HEADER_CONTENT in parsed); parsed[BODY_CONTENT] = !(BODY_CONTENT in cfg) && (BODY_CONTENT in parsed); parsed[FOOTER_CONTENT] = !(FOOTER_CONTENT in cfg) && (FOOTER_CONTENT in parsed); } }, /** * Retrieves the child nodes (content) of a standard module section * * @method _getStdModContent * @private * @param {String} section The standard module section whose child nodes are to be retrieved. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @return {Node} The child node collection of the standard module section. */ _getStdModContent : function(section) { return (this[section + NODE_SUFFIX]) ? this[section + NODE_SUFFIX].get(CHILD_NODES) : null; }, /** * Updates the body section of the standard module with the content provided (either an HTML string, or node reference). *

* This method can be used instead of the corresponding section content attribute if you'd like to retain the current content of the section, * and insert content before or after it, by specifying the where argument. *

* @method setStdModContent * @param {String} section The standard module section whose content is to be updated. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @param {String | Node} content The content to be added, either an HTML string or a Node reference. * @param {String} where Optional. Either WidgetStdMod.AFTER, WidgetStdMod.BEFORE or WidgetStdMod.REPLACE. * If not provided, the content will replace existing content in the section. */ setStdModContent : function(section, content, where) { //var node = this.getStdModNode(section) || this._renderStdMod(section); this.set(section + CONTENT_SUFFIX, content, {stdModPosition:where}); //this._addStdModContent(node, content, where); }, /** Returns the node reference for the specified `section`. **Note:** The DOM is not queried for the node reference. The reference stored by the widget instance is returned if it was set. Passing a truthy for `forceCreate` will create the section node if it does not already exist. @method getStdModNode @param {String} section The section whose node reference is required. Either `WidgetStdMod.HEADER`, `WidgetStdMod.BODY`, or `WidgetStdMod.FOOTER`. @param {Boolean} forceCreate Whether the section node should be created if it does not already exist. @return {Node} The node reference for the `section`, or null if not set. **/ getStdModNode : function(section, forceCreate) { var node = this[section + NODE_SUFFIX] || null; if (!node && forceCreate) { node = this._renderStdMod(section); } return node; }, /** * Sets the height on the provided header, body or footer element to * fill out the height of the Widget. It determines the height of the * widgets bounding box, based on it's configured height value, and * sets the height of the provided section to fill out any * space remaining after the other standard module section heights * have been accounted for. * *

NOTE: This method is not designed to work if an explicit * height has not been set on the Widget, since for an "auto" height Widget, * the heights of the header/body/footer will drive the height of the Widget.

* * @method fillHeight * @param {Node} node The node which should be resized to fill out the height * of the Widget bounding box. Should be a standard module section node which belongs * to the widget. */ fillHeight : function(node) { if (node) { var contentBox = this.get(CONTENT_BOX), stdModNodes = [this.headerNode, this.bodyNode, this.footerNode], stdModNode, cbContentHeight, filled = 0, remaining = 0, validNode = false; for (var i = 0, l = stdModNodes.length; i < l; i++) { stdModNode = stdModNodes[i]; if (stdModNode) { if (stdModNode !== node) { filled += this._getPreciseHeight(stdModNode); } else { validNode = true; } } } if (validNode) { if (UA.ie || UA.opera) { // Need to set height to 0, to allow height to be reduced node.set(OFFSET_HEIGHT, 0); } cbContentHeight = contentBox.get(OFFSET_HEIGHT) - parseInt(contentBox.getComputedStyle("paddingTop"), 10) - parseInt(contentBox.getComputedStyle("paddingBottom"), 10) - parseInt(contentBox.getComputedStyle("borderBottomWidth"), 10) - parseInt(contentBox.getComputedStyle("borderTopWidth"), 10); if (L.isNumber(cbContentHeight)) { remaining = cbContentHeight - filled; if (remaining >= 0) { node.set(OFFSET_HEIGHT, remaining); } } } } } }; Y.WidgetStdMod = StdMod; }, '3.18.1', {"requires": ["base-build", "widget"]}); PK\ktkt+3.18.1/widget-stdmod/widget-stdmod-debug.jsnu[YUI.add('widget-stdmod', function (Y, NAME) { /** * Provides standard module support for Widgets through an extension. * * @module widget-stdmod */ var L = Y.Lang, Node = Y.Node, UA = Y.UA, Widget = Y.Widget, EMPTY = "", HD = "hd", BD = "bd", FT = "ft", HEADER = "header", BODY = "body", FOOTER = "footer", FILL_HEIGHT = "fillHeight", STDMOD = "stdmod", NODE_SUFFIX = "Node", CONTENT_SUFFIX = "Content", FIRST_CHILD = "firstChild", CHILD_NODES = "childNodes", OWNER_DOCUMENT = "ownerDocument", CONTENT_BOX = "contentBox", HEIGHT = "height", OFFSET_HEIGHT = "offsetHeight", AUTO = "auto", HeaderChange = "headerContentChange", BodyChange = "bodyContentChange", FooterChange = "footerContentChange", FillHeightChange = "fillHeightChange", HeightChange = "heightChange", ContentUpdate = "contentUpdate", RENDERUI = "renderUI", BINDUI = "bindUI", SYNCUI = "syncUI", APPLY_PARSED_CONFIG = "_applyParsedConfig", UI = Y.Widget.UI_SRC; /** * Widget extension, which can be used to add Standard Module support to the * base Widget class, through the Base.build * method. *

* The extension adds header, body and footer sections to the Widget's content box and * provides the corresponding methods and attributes to modify the contents of these sections. *

* @class WidgetStdMod * @param {Object} The user configuration object */ function StdMod(config) {} /** * Constant used to refer the the standard module header, in methods which expect a section specifier * * @property HEADER * @static * @type String */ StdMod.HEADER = HEADER; /** * Constant used to refer the the standard module body, in methods which expect a section specifier * * @property BODY * @static * @type String */ StdMod.BODY = BODY; /** * Constant used to refer the the standard module footer, in methods which expect a section specifier * * @property FOOTER * @static * @type String */ StdMod.FOOTER = FOOTER; /** * Constant used to specify insertion position, when adding content to sections of the standard module in * methods which expect a "where" argument. *

* Inserts new content before the sections existing content. *

* @property AFTER * @static * @type String */ StdMod.AFTER = "after"; /** * Constant used to specify insertion position, when adding content to sections of the standard module in * methods which expect a "where" argument. *

* Inserts new content before the sections existing content. *

* @property BEFORE * @static * @type String */ StdMod.BEFORE = "before"; /** * Constant used to specify insertion position, when adding content to sections of the standard module in * methods which expect a "where" argument. *

* Replaces the sections existing content, with new content. *

* @property REPLACE * @static * @type String */ StdMod.REPLACE = "replace"; var STD_HEADER = StdMod.HEADER, STD_BODY = StdMod.BODY, STD_FOOTER = StdMod.FOOTER, HEADER_CONTENT = STD_HEADER + CONTENT_SUFFIX, FOOTER_CONTENT = STD_FOOTER + CONTENT_SUFFIX, BODY_CONTENT = STD_BODY + CONTENT_SUFFIX; /** * Static property used to define the default attribute * configuration introduced by WidgetStdMod. * * @property ATTRS * @type Object * @static */ StdMod.ATTRS = { /** * @attribute headerContent * @type HTML * @default undefined * @description The content to be added to the header section. This will replace any existing content * in the header. If you want to append, or insert new content, use the setStdModContent method. */ headerContent: { value:null }, /** * @attribute footerContent * @type HTML * @default undefined * @description The content to be added to the footer section. This will replace any existing content * in the footer. If you want to append, or insert new content, use the setStdModContent method. */ footerContent: { value:null }, /** * @attribute bodyContent * @type HTML * @default undefined * @description The content to be added to the body section. This will replace any existing content * in the body. If you want to append, or insert new content, use the setStdModContent method. */ bodyContent: { value:null }, /** * @attribute fillHeight * @type {String} * @default WidgetStdMod.BODY * @description The section (WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER) which should be resized to fill the height of the standard module, when a * height is set on the Widget. If a height is not set on the widget, then all sections are sized based on * their content. */ fillHeight: { value: StdMod.BODY, validator: function(val) { return this._validateFillHeight(val); } } }; /** * The HTML parsing rules for the WidgetStdMod class. * * @property HTML_PARSER * @static * @type Object */ StdMod.HTML_PARSER = { headerContent: function(contentBox) { return this._parseStdModHTML(STD_HEADER); }, bodyContent: function(contentBox) { return this._parseStdModHTML(STD_BODY); }, footerContent : function(contentBox) { return this._parseStdModHTML(STD_FOOTER); } }; /** * Static hash of default class names used for the header, * body and footer sections of the standard module, keyed by * the section identifier (WidgetStdMod.STD_HEADER, WidgetStdMod.STD_BODY, WidgetStdMod.STD_FOOTER) * * @property SECTION_CLASS_NAMES * @static * @type Object */ StdMod.SECTION_CLASS_NAMES = { header: Widget.getClassName(HD), body: Widget.getClassName(BD), footer: Widget.getClassName(FT) }; /** * The template HTML strings for each of the standard module sections. Section entries are keyed by the section constants, * WidgetStdMod.HEADER, WidgetStdMod.BODY, WidgetStdMod.FOOTER, and contain the HTML to be added for each section. * e.g. *
     *    {
     *       header : '<div class="yui-widget-hd"></div>',
     *       body : '<div class="yui-widget-bd"></div>',
     *       footer : '<div class="yui-widget-ft"></div>'
     *    }
     * 
* @property TEMPLATES * @type Object * @static */ StdMod.TEMPLATES = { header : '
', body : '
', footer : '
' }; StdMod.prototype = { initializer : function() { this._stdModNode = this.get(CONTENT_BOX); Y.before(this._renderUIStdMod, this, RENDERUI); Y.before(this._bindUIStdMod, this, BINDUI); Y.before(this._syncUIStdMod, this, SYNCUI); }, /** * Synchronizes the UI to match the Widgets standard module state. *

* This method is invoked after syncUI is invoked for the Widget class * using YUI's aop infrastructure. *

* @method _syncUIStdMod * @protected */ _syncUIStdMod : function() { var stdModParsed = this._stdModParsed; if (!stdModParsed || !stdModParsed[HEADER_CONTENT]) { this._uiSetStdMod(STD_HEADER, this.get(HEADER_CONTENT)); } if (!stdModParsed || !stdModParsed[BODY_CONTENT]) { this._uiSetStdMod(STD_BODY, this.get(BODY_CONTENT)); } if (!stdModParsed || !stdModParsed[FOOTER_CONTENT]) { this._uiSetStdMod(STD_FOOTER, this.get(FOOTER_CONTENT)); } this._uiSetFillHeight(this.get(FILL_HEIGHT)); }, /** * Creates/Initializes the DOM for standard module support. *

* This method is invoked after renderUI is invoked for the Widget class * using YUI's aop infrastructure. *

* @method _renderUIStdMod * @protected */ _renderUIStdMod : function() { this._stdModNode.addClass(Widget.getClassName(STDMOD)); this._renderStdModSections(); //This normally goes in bindUI but in order to allow setStdModContent() to work before renderUI //stage, these listeners should be set up at the earliest possible time. this.after(HeaderChange, this._afterHeaderChange); this.after(BodyChange, this._afterBodyChange); this.after(FooterChange, this._afterFooterChange); }, _renderStdModSections : function() { if (L.isValue(this.get(HEADER_CONTENT))) { this._renderStdMod(STD_HEADER); } if (L.isValue(this.get(BODY_CONTENT))) { this._renderStdMod(STD_BODY); } if (L.isValue(this.get(FOOTER_CONTENT))) { this._renderStdMod(STD_FOOTER); } }, /** * Binds event listeners responsible for updating the UI state in response to * Widget standard module related state changes. *

* This method is invoked after bindUI is invoked for the Widget class * using YUI's aop infrastructure. *

* @method _bindUIStdMod * @protected */ _bindUIStdMod : function() { // this.after(HeaderChange, this._afterHeaderChange); // this.after(BodyChange, this._afterBodyChange); // this.after(FooterChange, this._afterFooterChange); this.after(FillHeightChange, this._afterFillHeightChange); this.after(HeightChange, this._fillHeight); this.after(ContentUpdate, this._fillHeight); }, /** * Default attribute change listener for the headerContent attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterHeaderChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterHeaderChange : function(e) { if (e.src !== UI) { this._uiSetStdMod(STD_HEADER, e.newVal, e.stdModPosition); } }, /** * Default attribute change listener for the bodyContent attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterBodyChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterBodyChange : function(e) { if (e.src !== UI) { this._uiSetStdMod(STD_BODY, e.newVal, e.stdModPosition); } }, /** * Default attribute change listener for the footerContent attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterFooterChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterFooterChange : function(e) { if (e.src !== UI) { this._uiSetStdMod(STD_FOOTER, e.newVal, e.stdModPosition); } }, /** * Default attribute change listener for the fillHeight attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterFillHeightChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterFillHeightChange: function (e) { this._uiSetFillHeight(e.newVal); }, /** * Default validator for the fillHeight attribute. Verifies that the * value set is a valid section specifier - one of WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER, * or a falsey value if fillHeight is to be disabled. * * @method _validateFillHeight * @protected * @param {String} val The section which should be setup to fill height, or false/null to disable fillHeight * @return true if valid, false if not */ _validateFillHeight : function(val) { return !val || val == StdMod.BODY || val == StdMod.HEADER || val == StdMod.FOOTER; }, /** * Updates the rendered UI, to resize the provided section so that the standard module fills out * the specified widget height. Note: This method does not check whether or not a height is set * on the Widget. * * @method _uiSetFillHeight * @protected * @param {String} fillSection A valid section specifier - one of WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER */ _uiSetFillHeight : function(fillSection) { var fillNode = this.getStdModNode(fillSection); var currNode = this._currFillNode; if (currNode && fillNode !== currNode){ currNode.setStyle(HEIGHT, EMPTY); } if (fillNode) { this._currFillNode = fillNode; } this._fillHeight(); }, /** * Updates the rendered UI, to resize the current section specified by the fillHeight attribute, so * that the standard module fills out the Widget height. If a height has not been set on Widget, * the section is not resized (height is set to "auto"). * * @method _fillHeight * @private */ _fillHeight : function() { if (this.get(FILL_HEIGHT)) { var height = this.get(HEIGHT); if (height != EMPTY && height != AUTO) { this.fillHeight(this.getStdModNode(this.get(FILL_HEIGHT))); } } }, /** * Updates the rendered UI, adding the provided content (either an HTML string, or node reference), * to the specified section. The content is either added before, after or replaces existing content * in the section, based on the value of the where argument. * * @method _uiSetStdMod * @protected * * @param {String} section The section to be updated. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @param {String | Node} content The new content (either as an HTML string, or Node reference) to add to the section * @param {String} where Optional. Either WidgetStdMod.AFTER, WidgetStdMod.BEFORE or WidgetStdMod.REPLACE. * If not provided, the content will replace existing content in the section. */ _uiSetStdMod : function(section, content, where) { // Using isValue, so that "" is valid content if (L.isValue(content)) { var node = this.getStdModNode(section, true); this._addStdModContent(node, content, where); this.set(section + CONTENT_SUFFIX, this._getStdModContent(section), {src:UI}); } else { this._eraseStdMod(section); } this.fire(ContentUpdate); }, /** * Creates the DOM node for the given section, and inserts it into the correct location in the contentBox. * * @method _renderStdMod * @protected * @param {String} section The section to create/render. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @return {Node} A reference to the added section node */ _renderStdMod : function(section) { var contentBox = this.get(CONTENT_BOX), sectionNode = this._findStdModSection(section); if (!sectionNode) { sectionNode = this._getStdModTemplate(section); } this._insertStdModSection(contentBox, section, sectionNode); this[section + NODE_SUFFIX] = sectionNode; return this[section + NODE_SUFFIX]; }, /** * Removes the DOM node for the given section. * * @method _eraseStdMod * @protected * @param {String} section The section to remove. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. */ _eraseStdMod : function(section) { var sectionNode = this.getStdModNode(section); if (sectionNode) { sectionNode.remove(true); delete this[section + NODE_SUFFIX]; } }, /** * Helper method to insert the Node for the given section into the correct location in the contentBox. * * @method _insertStdModSection * @private * @param {Node} contentBox A reference to the Widgets content box. * @param {String} section The section to create/render. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @param {Node} sectionNode The Node for the section. */ _insertStdModSection : function(contentBox, section, sectionNode) { var fc = contentBox.get(FIRST_CHILD); if (section === STD_FOOTER || !fc) { contentBox.appendChild(sectionNode); } else { if (section === STD_HEADER) { contentBox.insertBefore(sectionNode, fc); } else { var footer = this[STD_FOOTER + NODE_SUFFIX]; if (footer) { contentBox.insertBefore(sectionNode, footer); } else { contentBox.appendChild(sectionNode); } } } }, /** * Gets a new Node reference for the given standard module section, by cloning * the stored template node. * * @method _getStdModTemplate * @protected * @param {String} section The section to create a new node for. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @return {Node} The new Node instance for the section */ _getStdModTemplate : function(section) { return Node.create(StdMod.TEMPLATES[section], this._stdModNode.get(OWNER_DOCUMENT)); }, /** * Helper method to add content to a StdMod section node. * The content is added either before, after or replaces the existing node content * based on the value of the where argument. * * @method _addStdModContent * @private * * @param {Node} node The section Node to be updated. * @param {Node|NodeList|String} children The new content Node, NodeList or String to be added to section Node provided. * @param {String} where Optional. Either WidgetStdMod.AFTER, WidgetStdMod.BEFORE or WidgetStdMod.REPLACE. * If not provided, the content will replace existing content in the Node. */ _addStdModContent : function(node, children, where) { // StdMod where to Node where switch (where) { case StdMod.BEFORE: // 0 is before fistChild where = 0; break; case StdMod.AFTER: // undefined is appendChild where = undefined; break; default: // replace is replace, not specified is replace where = StdMod.REPLACE; } node.insert(children, where); }, /** * Helper method to obtain the precise height of the node provided, including padding and border. * The height could be a sub-pixel value for certain browsers, such as Firefox 3. * * @method _getPreciseHeight * @private * @param {Node} node The node for which the precise height is required. * @return {Number} The height of the Node including borders and padding, possibly a float. */ _getPreciseHeight : function(node) { var height = (node) ? node.get(OFFSET_HEIGHT) : 0, getBCR = "getBoundingClientRect"; if (node && node.hasMethod(getBCR)) { var preciseRegion = node.invoke(getBCR); if (preciseRegion) { height = preciseRegion.bottom - preciseRegion.top; } } return height; }, /** * Helper method to to find the rendered node for the given section, * if it exists. * * @method _findStdModSection * @private * @param {String} section The section for which the render Node is to be found. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @return {Node} The rendered node for the given section, or null if not found. */ _findStdModSection: function(section) { return this.get(CONTENT_BOX).one("> ." + StdMod.SECTION_CLASS_NAMES[section]); }, /** * Utility method, used by WidgetStdMods HTML_PARSER implementation * to extract data for each section from markup. * * @method _parseStdModHTML * @private * @param {String} section * @return {String} Inner HTML string with the contents of the section */ _parseStdModHTML : function(section) { var node = this._findStdModSection(section); if (node) { if (!this._stdModParsed) { this._stdModParsed = {}; Y.before(this._applyStdModParsedConfig, this, APPLY_PARSED_CONFIG); } this._stdModParsed[section + CONTENT_SUFFIX] = 1; return node.get("innerHTML"); } return null; }, /** * This method is injected before the _applyParsedConfig step in * the application of HTML_PARSER, and sets up the state to * identify whether or not we should remove the current DOM content * or not, based on whether or not the current content attribute value * was extracted from the DOM, or provided by the user configuration * * @method _applyStdModParsedConfig * @private */ _applyStdModParsedConfig : function(node, cfg, parsedCfg) { var parsed = this._stdModParsed; if (parsed) { parsed[HEADER_CONTENT] = !(HEADER_CONTENT in cfg) && (HEADER_CONTENT in parsed); parsed[BODY_CONTENT] = !(BODY_CONTENT in cfg) && (BODY_CONTENT in parsed); parsed[FOOTER_CONTENT] = !(FOOTER_CONTENT in cfg) && (FOOTER_CONTENT in parsed); } }, /** * Retrieves the child nodes (content) of a standard module section * * @method _getStdModContent * @private * @param {String} section The standard module section whose child nodes are to be retrieved. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @return {Node} The child node collection of the standard module section. */ _getStdModContent : function(section) { return (this[section + NODE_SUFFIX]) ? this[section + NODE_SUFFIX].get(CHILD_NODES) : null; }, /** * Updates the body section of the standard module with the content provided (either an HTML string, or node reference). *

* This method can be used instead of the corresponding section content attribute if you'd like to retain the current content of the section, * and insert content before or after it, by specifying the where argument. *

* @method setStdModContent * @param {String} section The standard module section whose content is to be updated. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER. * @param {String | Node} content The content to be added, either an HTML string or a Node reference. * @param {String} where Optional. Either WidgetStdMod.AFTER, WidgetStdMod.BEFORE or WidgetStdMod.REPLACE. * If not provided, the content will replace existing content in the section. */ setStdModContent : function(section, content, where) { //var node = this.getStdModNode(section) || this._renderStdMod(section); this.set(section + CONTENT_SUFFIX, content, {stdModPosition:where}); //this._addStdModContent(node, content, where); }, /** Returns the node reference for the specified `section`. **Note:** The DOM is not queried for the node reference. The reference stored by the widget instance is returned if it was set. Passing a truthy for `forceCreate` will create the section node if it does not already exist. @method getStdModNode @param {String} section The section whose node reference is required. Either `WidgetStdMod.HEADER`, `WidgetStdMod.BODY`, or `WidgetStdMod.FOOTER`. @param {Boolean} forceCreate Whether the section node should be created if it does not already exist. @return {Node} The node reference for the `section`, or null if not set. **/ getStdModNode : function(section, forceCreate) { var node = this[section + NODE_SUFFIX] || null; if (!node && forceCreate) { node = this._renderStdMod(section); } return node; }, /** * Sets the height on the provided header, body or footer element to * fill out the height of the Widget. It determines the height of the * widgets bounding box, based on it's configured height value, and * sets the height of the provided section to fill out any * space remaining after the other standard module section heights * have been accounted for. * *

NOTE: This method is not designed to work if an explicit * height has not been set on the Widget, since for an "auto" height Widget, * the heights of the header/body/footer will drive the height of the Widget.

* * @method fillHeight * @param {Node} node The node which should be resized to fill out the height * of the Widget bounding box. Should be a standard module section node which belongs * to the widget. */ fillHeight : function(node) { if (node) { var contentBox = this.get(CONTENT_BOX), stdModNodes = [this.headerNode, this.bodyNode, this.footerNode], stdModNode, cbContentHeight, filled = 0, remaining = 0, validNode = false; for (var i = 0, l = stdModNodes.length; i < l; i++) { stdModNode = stdModNodes[i]; if (stdModNode) { if (stdModNode !== node) { filled += this._getPreciseHeight(stdModNode); } else { validNode = true; } } } if (validNode) { if (UA.ie || UA.opera) { // Need to set height to 0, to allow height to be reduced node.set(OFFSET_HEIGHT, 0); } cbContentHeight = contentBox.get(OFFSET_HEIGHT) - parseInt(contentBox.getComputedStyle("paddingTop"), 10) - parseInt(contentBox.getComputedStyle("paddingBottom"), 10) - parseInt(contentBox.getComputedStyle("borderBottomWidth"), 10) - parseInt(contentBox.getComputedStyle("borderTopWidth"), 10); if (L.isNumber(cbContentHeight)) { remaining = cbContentHeight - filled; if (remaining >= 0) { node.set(OFFSET_HEIGHT, remaining); } } } } } }; Y.WidgetStdMod = StdMod; }, '3.18.1', {"requires": ["base-build", "widget"]}); PK\.d)3.18.1/widget-stdmod/widget-stdmod-min.jsnu[YUI.add("widget-stdmod",function(e,t){function H(e){}var n=e.Lang,r=e.Node,i=e.UA,s=e.Widget,o="",u="hd",a="bd",f="ft",l="header",c="body",h="footer",p="fillHeight",d="stdmod",v="Node",m="Content",g="firstChild",y="childNodes",b="ownerDocument",w="contentBox",E="height",S="offsetHeight",x="auto",T="headerContentChange",N="bodyContentChange",C="footerContentChange",k="fillHeightChange",L="heightChange",A="contentUpdate",O="renderUI",M="bindUI",_="syncUI",D="_applyParsedConfig",P=e.Widget.UI_SRC;H.HEADER=l,H.BODY=c,H.FOOTER=h,H.AFTER="after",H.BEFORE="before",H.REPLACE="replace";var B=H.HEADER,j=H.BODY,F=H.FOOTER,I=B+m,q=F+m,R=j+m;H.ATTRS={headerContent:{value:null},footerContent:{value:null},bodyContent:{value:null},fillHeight:{value:H.BODY,validator:function(e){return this._validateFillHeight(e)}}},H.HTML_PARSER={headerContent:function(e){return this._parseStdModHTML(B)},bodyContent:function(e){return this._parseStdModHTML(j)},footerContent:function(e){return this._parseStdModHTML(F)}},H.SECTION_CLASS_NAMES={header:s.getClassName(u),body:s.getClassName(a),footer:s.getClassName(f)},H.TEMPLATES={header:'
',body:'
',footer:'
'},H.prototype={initializer:function(){this._stdModNode=this.get(w),e.before(this._renderUIStdMod,this,O),e.before(this._bindUIStdMod,this,M),e.before(this._syncUIStdMod,this,_)},_syncUIStdMod:function(){var e=this._stdModParsed;(!e||!e[I])&&this._uiSetStdMod(B,this.get(I)),(!e||!e[R])&&this._uiSetStdMod(j,this.get(R)),(!e||!e[q])&&this._uiSetStdMod(F,this.get(q)),this._uiSetFillHeight(this.get(p))},_renderUIStdMod:function(){this._stdModNode.addClass(s.getClassName(d)),this._renderStdModSections(),this.after(T,this._afterHeaderChange),this.after(N,this._afterBodyChange),this.after(C,this._afterFooterChange)},_renderStdModSections:function(){n.isValue(this.get(I))&&this._renderStdMod(B),n.isValue(this.get(R))&&this._renderStdMod(j),n.isValue(this.get(q))&&this._renderStdMod(F)},_bindUIStdMod:function(){this.after(k,this._afterFillHeightChange),this.after(L,this._fillHeight),this.after(A,this._fillHeight)},_afterHeaderChange:function(e){e.src!==P&&this._uiSetStdMod(B,e.newVal,e.stdModPosition)},_afterBodyChange:function(e){e.src!==P&&this._uiSetStdMod(j,e.newVal,e.stdModPosition)},_afterFooterChange:function(e){e.src!==P&&this._uiSetStdMod(F,e.newVal,e.stdModPosition)},_afterFillHeightChange:function(e){this._uiSetFillHeight(e.newVal)},_validateFillHeight:function(e){return!e||e==H.BODY||e==H.HEADER||e==H.FOOTER},_uiSetFillHeight:function(e){var t=this.getStdModNode(e),n=this._currFillNode;n&&t!==n&&n.setStyle(E,o),t&&(this._currFillNode=t),this._fillHeight()},_fillHeight:function(){if(this.get(p)){var e=this.get(E);e!=o&&e!=x&&this.fillHeight(this.getStdModNode(this.get(p)))}},_uiSetStdMod:function(e,t,r){if(n.isValue(t)){var i=this.getStdModNode(e,!0);this._addStdModContent(i,t,r),this.set(e+m,this._getStdModContent(e),{src:P})}else this._eraseStdMod(e);this.fire(A)},_renderStdMod:function(e){var t=this.get(w),n=this._findStdModSection(e);return n||(n=this._getStdModTemplate(e)),this._insertStdModSection(t,e,n),this[e+v]=n,this[e+v]},_eraseStdMod:function(e){var t=this.getStdModNode(e);t&&(t.remove(!0),delete this[e+v])},_insertStdModSection:function(e,t,n){var r=e.get(g);if(t===F||!r)e.appendChild(n);else if(t===B)e.insertBefore(n,r);else{var i=this[F+v];i?e.insertBefore(n,i):e.appendChild(n)}},_getStdModTemplate:function(e){return r.create(H.TEMPLATES[e],this._stdModNode.get(b))},_addStdModContent:function(e,t,n){switch(n){case H.BEFORE:n=0;break;case H.AFTER:n=undefined;break;default:n=H.REPLACE}e.insert(t,n)},_getPreciseHeight:function(e){var t=e?e.get(S):0,n="getBoundingClientRect";if(e&&e.hasMethod(n)){var r=e.invoke(n);r&&(t=r.bottom-r.top)}return t},_findStdModSection:function(e){return this.get(w).one("> ."+H.SECTION_CLASS_NAMES[e])},_parseStdModHTML:function(t){var n=this._findStdModSection(t);return n?(this._stdModParsed||(this._stdModParsed={},e.before(this._applyStdModParsedConfig,this,D)),this._stdModParsed[t+m]=1,n.get("innerHTML")):null},_applyStdModParsedConfig:function(e,t,n){var r=this._stdModParsed;r&&(r[I]=!(I in t)&&I in r,r[R]=!(R in t)&&R in r,r[q]=!(q in t)&&q in r)},_getStdModContent:function(e){return this[e+v]?this[e+v].get(y):null},setStdModContent:function(e,t,n){this.set(e+m,t,{stdModPosition:n})},getStdModNode:function(e,t){var n=this[e+v]||null;return!n&&t&&(n=this._renderStdMod(e)),n},fillHeight:function(e){if(e){var t=this.get(w),r=[this.headerNode,this.bodyNode,this.footerNode],s,o,u=0,a=0,f=!1;for(var l=0,c=r.length;l=0&&e.set(S,a)))}}},e.WidgetStdMod=H},"3.18.1",{requires:["base-build","widget"]}); PK\883.18.1/view/view-debug.jsnu[YUI.add('view', function (Y, NAME) { /** Represents a logical piece of an application's user interface, and provides a lightweight, overridable API for rendering content and handling delegated DOM events on a container element. @module app @submodule view @since 3.4.0 **/ /** Represents a logical piece of an application's user interface, and provides a lightweight, overridable API for rendering content and handling delegated DOM events on a container element. The View class imposes little structure and provides only minimal functionality of its own: it's basically just an overridable API interface that helps you implement custom views. As of YUI 3.5.0, View allows ad-hoc attributes to be specified at instantiation time, so you don't need to subclass `Y.View` to add custom attributes. Just pass them to the constructor: var view = new Y.View({foo: 'bar'}); view.get('foo'); // => "bar" @class View @constructor @extends Base @since 3.4.0 **/ function View() { View.superclass.constructor.apply(this, arguments); } Y.View = Y.extend(View, Y.Base, { // -- Public Properties ---------------------------------------------------- /** Template for this view's container. @property containerTemplate @type String @default "
" @since 3.5.0 **/ containerTemplate: '
', /** Hash of CSS selectors mapped to events to delegate to elements matching those selectors. CSS selectors are relative to the `container` element. Events are attached to the container, and delegation is used so that subscribers are only notified of events that occur on elements inside the container that match the specified selectors. This allows the container's contents to be re- rendered as needed without losing event subscriptions. Event handlers can be specified either as functions or as strings that map to function names on this view instance or its prototype. The `this` object in event handlers will refer to this view instance. If you'd prefer `this` to be something else, use `Y.bind()` to bind a custom `this` object. @example var view = new Y.View({ events: { // Call `this.toggle()` whenever the element with the id // "toggle-button" is clicked. '#toggle-button': {click: 'toggle'}, // Call `this.hoverOn()` when the mouse moves over any element // with the "hoverable" class, and `this.hoverOff()` when the // mouse moves out of any element with the "hoverable" class. '.hoverable': { mouseover: 'hoverOn', mouseout : 'hoverOff' } } }); @property events @type Object @default {} **/ events: {}, /** Template for this view's contents. This is a convenience property that has no default behavior of its own. It's only provided as a convention to allow you to store whatever you consider to be a template, whether that's an HTML string, a `Y.Node` instance, a Mustache template, or anything else your little heart desires. How this template gets used is entirely up to you and your custom `render()` method. @property template @type mixed @default '' **/ template: '', // -- Protected Properties ------------------------------------------------- /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to View's constructor. This makes it possible to instantiate a view and set a bunch of attributes without having to subclass `Y.View` and declare all those attributes first. @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.5.0 **/ _allowAdHocAttrs: true, // -- Lifecycle Methods ---------------------------------------------------- initializer: function (config) { config || (config = {}); // Set instance properties specified in the config. config.containerTemplate && (this.containerTemplate = config.containerTemplate); config.template && (this.template = config.template); // Merge events from the config into events in `this.events`. this.events = config.events ? Y.merge(this.events, config.events) : this.events; // When the container node changes (or when it's set for the first // time), we'll attach events to it, but not until then. This allows the // container to be created lazily the first time it's accessed rather // than always on init. this.after('containerChange', this._afterContainerChange); }, /** Destroys this View, detaching any DOM events and optionally also destroying its container node. By default, the container node will not be destroyed. Pass an _options_ object with a truthy `remove` property to destroy the container as well. @method destroy @param {Object} [options] Options. @param {Boolean} [options.remove=false] If `true`, this View's container will be removed from the DOM and destroyed as well. @chainable */ destroy: function (options) { // We also accept `delete` as a synonym for `remove`. if (options && (options.remove || options['delete'])) { // Attaching an event handler here because the `destroy` event is // preventable. If we destroyed the container before calling the // superclass's `destroy()` method and the event was prevented, the // class would end up in a broken state. this.onceAfter('destroy', function () { this._destroyContainer(); }); } return View.superclass.destroy.call(this); }, destructor: function () { this.detachEvents(); delete this._container; }, // -- Public Methods ------------------------------------------------------- /** Attaches delegated event handlers to this view's container element. This method is called internally to subscribe to events configured in the `events` attribute when the view is initialized. You may override this method to customize the event attaching logic. @method attachEvents @param {Object} [events] Hash of events to attach. See the docs for the `events` attribute for details on the format. If not specified, this view's `events` property will be used. @chainable @see detachEvents **/ attachEvents: function (events) { var container = this.get('container'), owns = Y.Object.owns, handler, handlers, name, selector; this.detachEvents(); events || (events = this.events); for (selector in events) { if (!owns(events, selector)) { continue; } handlers = events[selector]; for (name in handlers) { if (!owns(handlers, name)) { continue; } handler = handlers[name]; // TODO: Make this more robust by using lazy-binding: // `handler = Y.bind(handler, this);` if (typeof handler === 'string') { handler = this[handler]; } if (!handler) { Y.log('Missing handler for ' + selector + ' ' + name + ' event.', 'warn', 'View'); continue; } this._attachedViewEvents.push( container.delegate(name, handler, selector, this)); } } return this; }, /** Creates and returns a container node for this view. By default, the container is created from the HTML template specified in the `containerTemplate` property, and is _not_ added to the DOM automatically. You may override this method to customize how the container node is created (such as by rendering it from a custom template format). Your method must return a `Y.Node` instance. @method create @param {HTMLElement|Node|String} [container] Selector string, `Y.Node` instance, or DOM element to use at the container node. @return {Node} Node instance of the created container node. **/ create: function (container) { return container ? Y.one(container) : Y.Node.create(this.containerTemplate); }, /** Detaches DOM events that have previously been attached to the container by `attachEvents()`. @method detachEvents @chainable @see attachEvents **/ detachEvents: function () { Y.Array.each(this._attachedViewEvents, function (handle) { if (handle) { handle.detach(); } }); this._attachedViewEvents = []; return this; }, /** Removes this view's container element from the DOM (if it's in the DOM), but doesn't destroy it or any event listeners attached to it. @method remove @chainable **/ remove: function () { var container = this.get('container'); container && container.remove(); return this; }, /** Renders this view. This method is a noop by default. Override it to provide a custom implementation that renders this view's content and appends it to the container element. Ideally your `render` method should also return `this` as the end to allow chaining, but that's up to you. Since there's no default renderer, you're free to render your view however you see fit, whether that means manipulating the DOM directly, dumping strings into `innerHTML`, or using a template language of some kind. For basic templating needs, `Y.Node.create()` and `Y.Lang.sub()` may suffice, but there are no restrictions on what tools or techniques you can use to render your view. All you need to do is append something to the container element at some point, and optionally append the container to the DOM if it's not there already. @method render @chainable **/ render: function () { return this; }, // -- Protected Methods ---------------------------------------------------- /** Removes the `container` from the DOM and purges all its event listeners. @method _destroyContainer @protected **/ _destroyContainer: function () { var container = this.get('container'); container && container.remove(true); }, /** Getter for the `container` attribute. @method _getContainer @param {Node|null} value Current attribute value. @return {Node} Container node. @protected @since 3.5.0 **/ _getContainer: function (value) { // This wackiness is necessary to enable fully lazy creation of the // container node both when no container is specified and when one is // specified via a valueFn. if (!this._container) { if (value) { // Attach events to the container when it's specified via a // valueFn, which won't fire the containerChange event. this._container = value; this.attachEvents(); } else { // Create a default container and set that as the new attribute // value. The `this._container` property prevents infinite // recursion. value = this._container = this.create(); this._set('container', value); } } return value; }, // -- Protected Event Handlers --------------------------------------------- /** Handles `containerChange` events. Detaches event handlers from the old container (if any) and attaches them to the new container. Right now the `container` attr is initOnly so this event should only ever fire the first time the container is created, but in the future (once Y.App can handle it) we may allow runtime container changes. @method _afterContainerChange @protected @since 3.5.0 **/ _afterContainerChange: function () { this.attachEvents(this.events); } }, { NAME: 'view', ATTRS: { /** Container node into which this view's content will be rendered. The container node serves as the host for all DOM events attached by the view. Delegation is used to handle events on children of the container, allowing the container's contents to be re-rendered at any time without losing event subscriptions. The default container is a `
` Node, but you can override this in a subclass, or by passing in a custom `container` config value at instantiation time. If you override the default container in a subclass using `ATTRS`, you must use the `valueFn` property. The view's constructor will ignore any assignments using `value`. When `container` is overridden by a subclass or passed as a config option at instantiation time, you can provide it as a selector string, a DOM element, a `Y.Node` instance, or (if you are subclassing and modifying the attribute), a `valueFn` function that returns a `Y.Node` instance. The value will be converted into a `Y.Node` instance if it isn't one already. The container is not added to the page automatically. This allows you to have full control over how and when your view is actually rendered to the page. @attribute container @type HTMLElement|Node|String @default Y.Node.create(this.containerTemplate) @writeOnce **/ container: { getter : '_getContainer', setter : Y.one, writeOnce: true } }, /** Properties that shouldn't be turned into ad-hoc attributes when passed to View's constructor. @property _NON_ATTRS_CFG @type Array @static @protected @since 3.5.0 **/ _NON_ATTRS_CFG: [ 'containerTemplate', 'events', 'template' ] }); }, '3.18.1', {"requires": ["base-build", "node-event-delegate"]}); PK\X773.18.1/view/view.jsnu[YUI.add('view', function (Y, NAME) { /** Represents a logical piece of an application's user interface, and provides a lightweight, overridable API for rendering content and handling delegated DOM events on a container element. @module app @submodule view @since 3.4.0 **/ /** Represents a logical piece of an application's user interface, and provides a lightweight, overridable API for rendering content and handling delegated DOM events on a container element. The View class imposes little structure and provides only minimal functionality of its own: it's basically just an overridable API interface that helps you implement custom views. As of YUI 3.5.0, View allows ad-hoc attributes to be specified at instantiation time, so you don't need to subclass `Y.View` to add custom attributes. Just pass them to the constructor: var view = new Y.View({foo: 'bar'}); view.get('foo'); // => "bar" @class View @constructor @extends Base @since 3.4.0 **/ function View() { View.superclass.constructor.apply(this, arguments); } Y.View = Y.extend(View, Y.Base, { // -- Public Properties ---------------------------------------------------- /** Template for this view's container. @property containerTemplate @type String @default "
" @since 3.5.0 **/ containerTemplate: '
', /** Hash of CSS selectors mapped to events to delegate to elements matching those selectors. CSS selectors are relative to the `container` element. Events are attached to the container, and delegation is used so that subscribers are only notified of events that occur on elements inside the container that match the specified selectors. This allows the container's contents to be re- rendered as needed without losing event subscriptions. Event handlers can be specified either as functions or as strings that map to function names on this view instance or its prototype. The `this` object in event handlers will refer to this view instance. If you'd prefer `this` to be something else, use `Y.bind()` to bind a custom `this` object. @example var view = new Y.View({ events: { // Call `this.toggle()` whenever the element with the id // "toggle-button" is clicked. '#toggle-button': {click: 'toggle'}, // Call `this.hoverOn()` when the mouse moves over any element // with the "hoverable" class, and `this.hoverOff()` when the // mouse moves out of any element with the "hoverable" class. '.hoverable': { mouseover: 'hoverOn', mouseout : 'hoverOff' } } }); @property events @type Object @default {} **/ events: {}, /** Template for this view's contents. This is a convenience property that has no default behavior of its own. It's only provided as a convention to allow you to store whatever you consider to be a template, whether that's an HTML string, a `Y.Node` instance, a Mustache template, or anything else your little heart desires. How this template gets used is entirely up to you and your custom `render()` method. @property template @type mixed @default '' **/ template: '', // -- Protected Properties ------------------------------------------------- /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to View's constructor. This makes it possible to instantiate a view and set a bunch of attributes without having to subclass `Y.View` and declare all those attributes first. @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.5.0 **/ _allowAdHocAttrs: true, // -- Lifecycle Methods ---------------------------------------------------- initializer: function (config) { config || (config = {}); // Set instance properties specified in the config. config.containerTemplate && (this.containerTemplate = config.containerTemplate); config.template && (this.template = config.template); // Merge events from the config into events in `this.events`. this.events = config.events ? Y.merge(this.events, config.events) : this.events; // When the container node changes (or when it's set for the first // time), we'll attach events to it, but not until then. This allows the // container to be created lazily the first time it's accessed rather // than always on init. this.after('containerChange', this._afterContainerChange); }, /** Destroys this View, detaching any DOM events and optionally also destroying its container node. By default, the container node will not be destroyed. Pass an _options_ object with a truthy `remove` property to destroy the container as well. @method destroy @param {Object} [options] Options. @param {Boolean} [options.remove=false] If `true`, this View's container will be removed from the DOM and destroyed as well. @chainable */ destroy: function (options) { // We also accept `delete` as a synonym for `remove`. if (options && (options.remove || options['delete'])) { // Attaching an event handler here because the `destroy` event is // preventable. If we destroyed the container before calling the // superclass's `destroy()` method and the event was prevented, the // class would end up in a broken state. this.onceAfter('destroy', function () { this._destroyContainer(); }); } return View.superclass.destroy.call(this); }, destructor: function () { this.detachEvents(); delete this._container; }, // -- Public Methods ------------------------------------------------------- /** Attaches delegated event handlers to this view's container element. This method is called internally to subscribe to events configured in the `events` attribute when the view is initialized. You may override this method to customize the event attaching logic. @method attachEvents @param {Object} [events] Hash of events to attach. See the docs for the `events` attribute for details on the format. If not specified, this view's `events` property will be used. @chainable @see detachEvents **/ attachEvents: function (events) { var container = this.get('container'), owns = Y.Object.owns, handler, handlers, name, selector; this.detachEvents(); events || (events = this.events); for (selector in events) { if (!owns(events, selector)) { continue; } handlers = events[selector]; for (name in handlers) { if (!owns(handlers, name)) { continue; } handler = handlers[name]; // TODO: Make this more robust by using lazy-binding: // `handler = Y.bind(handler, this);` if (typeof handler === 'string') { handler = this[handler]; } if (!handler) { continue; } this._attachedViewEvents.push( container.delegate(name, handler, selector, this)); } } return this; }, /** Creates and returns a container node for this view. By default, the container is created from the HTML template specified in the `containerTemplate` property, and is _not_ added to the DOM automatically. You may override this method to customize how the container node is created (such as by rendering it from a custom template format). Your method must return a `Y.Node` instance. @method create @param {HTMLElement|Node|String} [container] Selector string, `Y.Node` instance, or DOM element to use at the container node. @return {Node} Node instance of the created container node. **/ create: function (container) { return container ? Y.one(container) : Y.Node.create(this.containerTemplate); }, /** Detaches DOM events that have previously been attached to the container by `attachEvents()`. @method detachEvents @chainable @see attachEvents **/ detachEvents: function () { Y.Array.each(this._attachedViewEvents, function (handle) { if (handle) { handle.detach(); } }); this._attachedViewEvents = []; return this; }, /** Removes this view's container element from the DOM (if it's in the DOM), but doesn't destroy it or any event listeners attached to it. @method remove @chainable **/ remove: function () { var container = this.get('container'); container && container.remove(); return this; }, /** Renders this view. This method is a noop by default. Override it to provide a custom implementation that renders this view's content and appends it to the container element. Ideally your `render` method should also return `this` as the end to allow chaining, but that's up to you. Since there's no default renderer, you're free to render your view however you see fit, whether that means manipulating the DOM directly, dumping strings into `innerHTML`, or using a template language of some kind. For basic templating needs, `Y.Node.create()` and `Y.Lang.sub()` may suffice, but there are no restrictions on what tools or techniques you can use to render your view. All you need to do is append something to the container element at some point, and optionally append the container to the DOM if it's not there already. @method render @chainable **/ render: function () { return this; }, // -- Protected Methods ---------------------------------------------------- /** Removes the `container` from the DOM and purges all its event listeners. @method _destroyContainer @protected **/ _destroyContainer: function () { var container = this.get('container'); container && container.remove(true); }, /** Getter for the `container` attribute. @method _getContainer @param {Node|null} value Current attribute value. @return {Node} Container node. @protected @since 3.5.0 **/ _getContainer: function (value) { // This wackiness is necessary to enable fully lazy creation of the // container node both when no container is specified and when one is // specified via a valueFn. if (!this._container) { if (value) { // Attach events to the container when it's specified via a // valueFn, which won't fire the containerChange event. this._container = value; this.attachEvents(); } else { // Create a default container and set that as the new attribute // value. The `this._container` property prevents infinite // recursion. value = this._container = this.create(); this._set('container', value); } } return value; }, // -- Protected Event Handlers --------------------------------------------- /** Handles `containerChange` events. Detaches event handlers from the old container (if any) and attaches them to the new container. Right now the `container` attr is initOnly so this event should only ever fire the first time the container is created, but in the future (once Y.App can handle it) we may allow runtime container changes. @method _afterContainerChange @protected @since 3.5.0 **/ _afterContainerChange: function () { this.attachEvents(this.events); } }, { NAME: 'view', ATTRS: { /** Container node into which this view's content will be rendered. The container node serves as the host for all DOM events attached by the view. Delegation is used to handle events on children of the container, allowing the container's contents to be re-rendered at any time without losing event subscriptions. The default container is a `
` Node, but you can override this in a subclass, or by passing in a custom `container` config value at instantiation time. If you override the default container in a subclass using `ATTRS`, you must use the `valueFn` property. The view's constructor will ignore any assignments using `value`. When `container` is overridden by a subclass or passed as a config option at instantiation time, you can provide it as a selector string, a DOM element, a `Y.Node` instance, or (if you are subclassing and modifying the attribute), a `valueFn` function that returns a `Y.Node` instance. The value will be converted into a `Y.Node` instance if it isn't one already. The container is not added to the page automatically. This allows you to have full control over how and when your view is actually rendered to the page. @attribute container @type HTMLElement|Node|String @default Y.Node.create(this.containerTemplate) @writeOnce **/ container: { getter : '_getContainer', setter : Y.one, writeOnce: true } }, /** Properties that shouldn't be turned into ad-hoc attributes when passed to View's constructor. @property _NON_ATTRS_CFG @type Array @static @protected @since 3.5.0 **/ _NON_ATTRS_CFG: [ 'containerTemplate', 'events', 'template' ] }); }, '3.18.1', {"requires": ["base-build", "node-event-delegate"]}); PK\j3.18.1/view/view-min.jsnu[YUI.add("view",function(e,t){function n(){n.superclass.constructor.apply(this,arguments)}e.View=e.extend(n,e.Base,{containerTemplate:"
",events:{},template:"",_allowAdHocAttrs:!0,initializer:function(t){t||(t={}),t.containerTemplate&&(this.containerTemplate=t.containerTemplate),t.template&&(this.template=t.template),this.events=t.events?e.merge(this.events,t.events):this.events,this.after("containerChange",this._afterContainerChange)},destroy:function(e){return e&&(e.remove||e["delete"])&&this.onceAfter("destroy",function(){this._destroyContainer()}),n.superclass.destroy.call(this)},destructor:function(){this.detachEvents(),delete this._container},attachEvents:function(t){var n=this.get("container"),r=e.Object.owns,i,s,o,u;this.detachEvents(),t||(t=this.events);for(u in t){if(!r(t,u))continue;s=t[u];for(o in s){if(!r(s,o))continue;i=s[o],typeof i=="string"&&(i=this[i]);if(!i)continue;this._attachedViewEvents.push(n.delegate(o,i,u,this))}}return this},create:function(t){return t?e.one(t):e.Node.create(this.containerTemplate)},detachEvents:function(){return e.Array.each(this._attachedViewEvents,function(e){e&&e.detach()}),this._attachedViewEvents=[],this},remove:function(){var e=this.get("container");return e&&e.remove(),this},render:function(){return this},_destroyContainer:function(){var e=this.get("container");e&&e.remove(!0)},_getContainer:function(e){return this._container||(e?(this._container=e,this.attachEvents()):(e=this._container=this.create(),this._set("container",e))),e},_afterContainerChange:function(){this.attachEvents(this.events)}},{NAME:"view",ATTRS:{container:{getter:"_getContainer",setter:e.one,writeOnce:!0}},_NON_ATTRS_CFG:["containerTemplate","events","template"]})},"3.18.1",{requires:["base-build","node-event-delegate"]}); PK\47^7^3.18.1/yui-core/yui-core-min.jsnu[typeof YUI!="undefined"&&(YUI._YUI=YUI);var YUI=function(){var e=0,t=this,n=arguments,r=n.length,i=function(e,t){return e&&e.hasOwnProperty&&e instanceof t},s=typeof YUI_config!="undefined"&&YUI_config;i(t,YUI)?(t._init(),YUI.GlobalConfig&&t.applyConfig(YUI.GlobalConfig),s&&t.applyConfig(s),r||(t._afterConfig(),t._setup())):t=new YUI;if(r){for(;e-1&&(n="3.5.0"),e={applyConfig:function(e){e=e||u;var t,n,r=this.config,i=r.modules,s=r.groups,o=r.aliases,a=this.Env._loader;for(n in e)e.hasOwnProperty(n)&&(t=e[n],i&&n=="modules"?S(i,t):o&&n=="aliases"?S(o,t):s&&n=="groups"?S(s,t):n=="win"?(r[n]=t&&t.contentWindow||t,r.doc=r[n]?r[n].document:null):n!="_yuid"&&(r[n]=t));a&&a._config(e)},_config:function(e){this.applyConfig(e)},_init:function(){var e,t,r=this,s=YUI.Env,u=r.Env,a;r.version=n;if(!u){r.Env={core:["intl-base"],loaderExtras:["loader-rollup","loader-yui3"],mods:{},versions:{},base:i,cdn:i+n+"/",_idx:0,_used:{},_attached:{},_exported:{},_missed:[],_yidx:0,_uidx:0,_guidp:"y",_loaded:{},_BASE_RE:/(?:\?(?:[^&]*&)*([^&]*))?\b(yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/,parseBasePath:function(e,t){var n=e.match(t),r,i;return n&&(r=RegExp.leftContext||e.slice(0,e.indexOf(n[0])),i=n[3],n[1]&&(r+="?"+n[1]),r={filter:i,path:r}),r},getBase:s&&s.getBase||function(t){var n=h&&h.getElementsByTagName("script")||[],i=u.cdn,s,o,a,f;for(o=0,a=n.length;o
',YUI.Env.cssStampEl=t.firstChild,h.body?h.body.appendChild(YUI.Env.cssStampEl):p.insertBefore(YUI.Env.cssStampEl,p.firstChild)):h&&h.getElementById(o)&&!YUI.Env.cssStampEl&&(YUI.Env.cssStampEl=h.getElementById(o)),r.config.lang=r.config.lang||"en-US",r.config.base=YUI.config.base||YUI.config.defaultBase&&YUI.config.root&&YUI.config.defaultBase+YUI.config.root||r.Env.getBase(r.Env._BASE_RE);if(!e||!"mindebug".indexOf(e))e="min";e=e?"-"+e:e,r.config.loaderPath=YUI.config.loaderPath||"loader/loader"+e+".js"},_afterConfig:function(){var e=this;e.config.hasOwnProperty("global")||(e.config.global=Function("return this")())},_setup:function(){var e,t=this,n=[],r=YUI.Env.mods,i=t.config.extendedCore||[],s=t.config.core||[].concat(YUI.Env.core).concat(i);for(e=0;e-1){s=o.split(r);for(i=s[0]=="YAHOO"?1:0;i-1?n(t,r):t[r];return typeof i=="undefined"?e:i}):e},n.trim=n._isNative(r.trim)&&!u.trim()?function(e){return e&&e.trim?e.trim():e}:function(e){try{return e.replace(c,"")}catch(t){return e}},n.trimLeft=n._isNative(r.trimLeft)&&!u.trimLeft()?function(e){return e.trimLeft()}:function(e){return e.replace(f,"")},n.trimRight=n._isNative(r.trimRight)&&!u.trimRight()?function(e){return e.trimRight()}:function(e){return e.replace(l,"")},n.type=function(e){return s[typeof e]||s[i.call(e)]||(e?"object":"null")};var p=e.Lang,d=Array.prototype,v=Object.prototype.hasOwnProperty;e.Array=m,m.dedupe=p._isNative(Object.create)?function(e){var t=Object.create(null),n=[],r,i,s;for(r=0,s=e.length;ri&&i in t?t[i]:!0);return n},m.indexOf=p._isNative(d.indexOf)?function(e,t,n){return d.indexOf.call(e,t,n)}:function(e,t,n){var r=e.length;n=+n||0,n=(n>0||-1)*Math.floor(Math.abs(n)),n<0&&(n+=r,n<0&&(n=0));for(;n1?Array.prototype.join.call(arguments,y):String(r);if(!(i in t)||n&&t[i]==n)t[i]=e.apply(e,arguments);return t[i]}},e.getLocation=function(){var t=e.config.win;return t&&t.location},e.merge=function(){var e=0,t=arguments.length,n={},r,i;for(;e-1},E.each=function(t,n,r,i){var s;for(s in t)(i||N(t,s))&&n.call(r||e,t[s],s,t);return e},E.some=function(t,n,r,i){var s;for(s in t)if(i||N(t,s))if(n.call(r||e,t[s],s,t))return!0;return!1},E.getValue=function(t,n){if(!p.isObject(t))return w;var r,i=e.Array(n),s=i.length;for(r=0;t!==w&&r=0){for(i=0;u!==w&&i0),t||(typeof process=="object"&&process.versions&&process.versions.node&&(s.os=process.platform,s.nodejs=n(process.versions.node)),YUI.Env.UA=s),s},e.UA=YUI.Env.UA||YUI.Env.parseUA(),e.UA.compareVersions=function(e,t){var n,r,i,s,o,u;if(e===t)return 0;r=(e+"").split("."),s=(t+"").split(".");for(o=0,u=Math.max(r.length,s.length);oi)return 1}return 0},YUI.Env.aliases={anim:["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"],"anim-shape-transform":["anim-shape"],app:["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","model-sync-local","router","view","view-node-map"],attribute:["attribute-base","attribute-complex"],"attribute-events":["attribute-observable"],autocomplete:["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"],axes:["axis-numeric","axis-category","axis-time","axis-stacked"],"axes-base":["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"],base:["base-base","base-pluginhost","base-build"],cache:["cache-base","cache-offline","cache-plugin"],charts:["charts-base"],collection:["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"],color:["color-base","color-hsl","color-harmony"],controller:["router"],dataschema:["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"],datasource:["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"],datatable:["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"],datatype:["datatype-date","datatype-number","datatype-xml"],"datatype-date":["datatype-date-parse","datatype-date-format","datatype-date-math"],"datatype-number":["datatype-number-parse","datatype-number-format"],"datatype-xml":["datatype-xml-parse","datatype-xml-format"],dd:["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"],dom:["dom-base","dom-screen","dom-style","selector-native","selector"],editor:["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"],event:["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"],"event-custom":["event-custom-base","event-custom-complex"],"event-gestures":["event-flick","event-move"],handlebars:["handlebars-compiler"],highlight:["highlight-base","highlight-accentfold"],history:["history-base","history-hash","history-html5"],io:["io-base","io-xdr","io-form","io-upload-iframe","io-queue"],json:["json-parse","json-stringify"],loader:["loader-base","loader-rollup","loader-yui3"],"loader-pathogen-encoder":["loader-base","loader-rollup","loader-yui3","loader-pathogen-combohandler"],node:["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"],pluginhost:["pluginhost-base","pluginhost-config"],querystring:["querystring-parse","querystring-stringify"],recordset:["recordset-base","recordset-sort","recordset-filter","recordset-indexer"],resize:["resize-base","resize-proxy","resize-constrain"],slider:["slider-base","slider-value-range","clickable-rail","range-slider"],template:["template-base","template-micro"],text:["text-accentfold" ,"text-wordbreak"],widget:["widget-base","widget-htmlparser","widget-skin","widget-uievents"]}},"3.18.1"); PK\?}jj3.18.1/yui-core/yui-core.jsnu[/** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @main yui @submodule yui-base **/ /*jshint eqeqeq: false*/ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. This is the constructor for all YUI instances. This is a self-instantiable factory function, meaning you don't need to precede it with the `new` operator. You can invoke it directly like this: YUI().use('*', function (Y) { // Y is a new YUI instance. }); But it also works like this: var Y = YUI(); The `YUI` constructor accepts an optional config object, like this: YUI({ debug: true, combine: false }).use('node', function (Y) { // Y.Node is ready to use. }); See the API docs for the Config class for the complete list of supported configuration properties accepted by the YUI constuctor. If a global `YUI` object is already defined, the existing YUI object will not be overwritten, to ensure that defined namespaces are preserved. Each YUI instance has full custom event support, but only if the event system is available. @class YUI @uses EventTarget @constructor @global @param {Object} [config]* Zero or more optional configuration objects. Config values are stored in the `Y.config` property. See the Config docs for the list of supported properties. **/ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts. @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} GlobalConfig @global @static **/ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** Page-level config applied to all YUI instances created on the current page. This is applied after `YUI.GlobalConfig` and before any instance-level configuration. @example // Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} YUI_config @global **/ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._afterConfig(); Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._afterConfig(); Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '3.18.1', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleReady = function() { YUI.Env.DOMReady = true; if (hasWin) { remove(doc, 'DOMContentLoaded', handleReady); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.5.0'; // dev time hack for cdn test } proto = { /** Applies a new configuration object to the config of this YUI instance. This will merge new group/module definitions, and will also update the loader cache if necessary. Updating `Y.config` directly will not update the cache. @method applyConfig @param {Object} o the configuration object. @since 3.2.0 **/ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** Old way to apply a config to this instance (calls `applyConfig` under the hood). @private @method _config @param {Object} o The config to apply **/ _config: function(o) { this.applyConfig(o); }, /** Initializes this YUI instance. @private @method _init **/ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** The version number of this YUI instance. This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree. @property {String} version **/ Y.version = VERSION; if (!Env) { Y.Env = { core: ['intl-base'], loaderExtras: ['loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _exported: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(yui). // 1. Look in the test string for "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_yui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js". // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b( after a word break find either the string // yui(?:-\w+)? "yui" optionally followed by a -, then more characters // ) and store the yui-* string in \2 // \/\2 then comes a / followed by the yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path }; } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '
'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) { YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || (YUI.config.defaultBase && YUI.config.root && YUI.config.defaultBase + YUI.config.root) || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** This method is called after all other configuration has been applied to the YUI instance. @method _afterConfig @private **/ _afterConfig: function () { var Y = this; // We need to set up Y.config.global after the rest of the configuration // so that setting it in user configuration prevents the library from // using eval(). This is critical for Content Security Policy enabled // sites and other environments like Chrome extensions if (!Y.config.hasOwnProperty('global')) { Y.config.global = Function('return this')(); } }, /** Finishes the instance setup. Attaches whatever YUI modules were defined at the time that this instance was created. @method _setup @private **/ _setup: function() { var i, Y = this, core = [], mods = YUI.Env.mods, extendedCore = Y.config.extendedCore || [], extras = Y.config.core || [].concat(YUI.Env.core).concat(extendedCore); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** Executes the named method on the specified YUI instance if that method is whitelisted. @method applyTo @param {String} id YUI instance id. @param {String} method Name of the method to execute. For example: 'Object.keys'. @param {Array} args Arguments to apply to the method. @return {Mixed} Return value from the applied method, or `null` if the specified instance was not found or the method was not whitelisted. **/ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a YUI module and makes it available for use in a `YUI().use()` call or as a dependency for other modules. The easiest way to create a first-class YUI module is to use Shifter, the YUI component build tool. Shifter will automatically wrap your module code in a `YUI.add()` call along with any configuration info required for the module. @example YUI.add('davglass', function (Y) { Y.davglass = function () { }; }, '3.4.0', { requires: ['harley-davidson', 'mt-dew'] }); @method add @param {String} name Module name. @param {Function} fn Function containing module code. This function will be executed whenever the module is attached to a specific YUI instance. @param {YUI} fn.Y The YUI instance to which this module is attached. @param {String} fn.name Name of the module @param {String} version Module version number. This is currently used only for informational purposes, and is not used internally by YUI. @param {Object} [details] Module config. @param {Array} [details.requires] Array of other module names that must be attached before this module can be attached. @param {Array} [details.optional] Array of optional module names that should be attached before this module is attached if they've already been loaded. If the `loadOptional` YUI option is `true`, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. @param {Array} [details.use] Array of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules. @return {YUI} This YUI instance. **/ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, modInfo, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { modInfo = loader.getModuleInfo(name); if (!modInfo || modInfo.temp) { loader.addModule(details, name); } } } } } return this; }, /** Executes the callback function associated with each required module, attaching the module to this YUI instance. @method _attach @param {Array} r The array of modules to attach @param {Boolean} [moot=false] If `true`, don't throw a warning if the module is not attached. @private **/ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, exported = Y.Env._exported, len = r.length, loader, def, go, c = [], modArgs, esCompat, reqlen, modInfo, condition, __exports__, __imports__; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { modInfo = loader && loader.getModuleInfo(name); if (modInfo) { mod = modInfo; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } // Optional dependencies normally work by modifying the // dependency list of a module. If the dependency's test // passes it is added to the list. If not, it's not loaded. // This following check ensures that optional dependencies // are not attached when they were already loaded into the // page (when bundling for example) if (loader && !loader._canBeAttached(name)) { return true; } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; modInfo = loader.getModuleInfo(name); for (j in modInfo.expanded_map) { if (modInfo.expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; esCompat = details.es; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } if (req) { reqlen = req.length; for (j = 0; j < reqlen; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { modArgs = [Y, name]; if (esCompat) { __imports__ = {}; __exports__ = {}; // passing `exports` and `imports` onto the module function modArgs.push(__imports__, __exports__); if (req) { reqlen = req.length; for (j = 0; j < reqlen; j++) { __imports__[req[j]] = exported.hasOwnProperty(req[j]) ? exported[req[j]] : Y; } } } if (Y.config.throwFail) { __exports__ = mod.fn.apply(esCompat ? undefined : mod, modArgs); } else { try { __exports__ = mod.fn.apply(esCompat ? undefined : mod, modArgs); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (esCompat) { // store the `exports` in case others `es` modules requires it exported[name] = __exports__; // If an ES module is conditionally loaded and set // to be used "instead" another module, replace the // trigger module's content with the conditionally // loaded one so the values returned by require() // still makes sense condition = mod.details.condition; if (condition && condition.when === 'instead') { exported[condition.trigger] = __exports__; } } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** Delays the `use` callback until another event has taken place such as `window.onload`, `domready`, `contentready`, or `available`. @private @method _delayCallback @param {Function} cb The original `use` callback. @param {String|Object} until Either an event name ('load', 'domready', etc.) or an object containing event/args keys for contentready/available. @return {Function} **/ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } return function() { var args = arguments; Y._use(mod, function() { Y.on(until.event, function() { args[1].delayUntil = until.event; cb.apply(Y, args); }, until.args); }); }; }, /** Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen: * All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the `use()` callback will be executed synchronously after the modules are attached. * One or more modules have not yet been loaded, or the Get utility is not available, or the `bootstrap` config option is `false`. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and the `use()` callback will be executed synchronously. * One or more modules are missing and the Loader is not available but the Get utility is, and `bootstrap` is not `false`. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state: * One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the `use()` callback will be executed asynchronously. @example // Loads and attaches dd and its dependencies. YUI().use('dd', function (Y) { // ... }); // Loads and attaches dd and node as well as all of their dependencies. YUI().use(['dd', 'node'], function (Y) { // ... }); // Attaches all modules that have already been loaded. YUI().use('*', function (Y) { // ... }); // Attaches a gallery module. YUI().use('gallery-yql', function (Y) { // ... }); // Attaches a YUI 2in3 module. YUI().use('yui2-datatable', function (Y) { // ... }); @method use @param {String|Array} modules* One or more module names to attach. @param {Function} [callback] Callback function to be executed once all specified modules and their dependencies have been attached. @param {YUI} callback.Y The YUI instance created for this sandbox. @param {Object} callback.status Object containing `success`, `msg` and `data` properties. @chainable **/ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** Sugar for loading both legacy and ES6-based YUI modules. @method require @param {String} [modules*] List of module names to import or a single module name. @param {Function} callback Callback that gets called once all the modules were loaded. Each parameter of the callback is the export value of the corresponding module in the list. If the module is a legacy YUI module, the YUI instance is used instead of the module exports. @example ``` YUI().require(['es6-set'], function (Y, imports) { var Set = imports.Set, set = new Set(); }); ``` **/ require: function () { var args = SLICE.call(arguments), callback; if (typeof args[args.length - 1] === 'function') { callback = args.pop(); // only add the callback if one was provided // YUI().require('foo'); is valid args.push(function (Y) { var i, length = args.length, exported = Y.Env._exported, __imports__ = {}; // Get only the imports requested as arguments for (i = 0; i < length; i++) { if (exported.hasOwnProperty(args[i])) { __imports__[args[i]] = exported[args[i]]; } } // Using `undefined` because: // - Using `Y.config.global` would force the value of `this` to be // the global object even in strict mode // - Using `Y` goes against the goal of moving away from a shared // object and start thinking in terms of imported and exported // objects callback.call(undefined, Y, __imports__); }); } // Do not return the Y object. This makes it hard to follow this // traditional pattern: // var Y = YUI().use(...); // This is a good idea in the light of ES6 modules, to avoid working // in the global scope. // This also leaves the door open for returning a promise, once the // YUI loader is based on the ES6 loader which uses // loader.import(...).then(...) this.use.apply(this, args); }, /** Handles Loader notifications about attachment/load errors. @method _notify @param {Function} callback Callback to pass to `Y.config.loadErrorFn`. @param {Object} response Response returned from Loader. @param {Array} args Arguments passed from Loader. @private **/ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** Called from the `use` method queue to ensure that only one set of loading logic is performed at a time. @method _use @param {String} args* One or more modules to attach. @param {Function} [callback] Function to call once all required modules have been attached. @private **/ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } } }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance. When called statically, a namespace will be created on the YUI global object: // Create `YUI.your.namespace.here` as nested objects, preserving any // objects that already exist instead of overwriting them. YUI.namespace('your.namespace.here'); When called as a method on a YUI instance, a namespace will be created on that instance: // Creates `Y.property.package`. Y.namespace('property.package'); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place and will not be overwritten. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace('really.long.nested.namespace'); Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function. @method namespace @param {String} namespace* One or more namespaces to create. @return {Object} Reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** Reports an error. The reporting mechanism is controlled by the `throwFail` configuration attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is truthy, a JS exception is thrown. If an `errorFn` is specified in the config it must return `true` to indicate that the exception was handled and keep it from being thrown. @method error @param {String} msg Error message. @param {Error|String} [e] JavaScript error object or an error string. @param {String} [src] Source of the error (such as the name of the module in which the error occurred). @chainable **/ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** Generates an id string that is unique among all YUI instances in this execution context. @method guid @param {String} [pre] Prefix. @return {String} Unique id. **/ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** Returns a unique id associated with the given object and (if *readOnly* is falsy) stamps the object with that id so it can be identified in the future. Stamping an object involves adding a `_yuid` property to it that contains the object's id. One exception to this is that in Internet Explorer, DOM nodes have a `uniqueID` property that contains a browser-generated unique id, which will be used instead of a YUI-generated id when available. @method stamp @param {Object} o Object to stamp. @param {Boolean} readOnly If truthy and the given object has not already been stamped, the object will not be modified and `null` will be returned. @return {String} Object's unique id, or `null` if *readOnly* was truthy and the given object was not already stamped. **/ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** Destroys this YUI instance. @method destroy @since 3.3.0 **/ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** Safe `instanceof` wrapper that works around a memory leak in IE when the object being tested is `window` or `document`. Unless you are testing objects that may be `window` or `document`, you should use the native `instanceof` operator instead of this method. @method instanceOf @param {Object} o Object to check. @param {Object} type Class to check against. @since 3.3.0 **/ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Applies a configuration to all YUI instances in this execution context. The main use case for this method is in "mashups" where several third-party scripts need to write to a global YUI config, but cannot share a single centrally-managed config object. This way they can all call `YUI.applyConfig({})` instead of overwriting the single global config. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function (Y) { // Module davglass will be available here. }); @method applyConfig @param {Object} o Configuration object to apply. @static @since 3.5.0 **/ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { add(doc, 'DOMContentLoaded', handleReady); // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleReady(); handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; /** * Set a method to be called when `Get.script` is called in Node.js * `Get` will open the file, then pass it's content and it's path * to this method before attaching it. Commonly used for code coverage * instrumentation. Calling this multiple times will only * attach the last hook method. This method is only * available in Node.js. * @method setLoadHook * @static * @param {Function} fn The function to set * @param {String} fn.data The content of the file * @param {String} fn.path The file path of the file */ YUI.setLoadHook = function(fn) { YUI._getLoadHook = fn; }; /** * Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook` * @method _getLoadHook * @private * @param {String} data The content of the file * @param {String} path The file path of the file */ YUI._getLoadHook = null; } YUI.Env[VERSION] = {}; }()); /** Config object that contains all of the configuration options for this `YUI` instance. This object is supplied by the implementer when instantiating YUI. Some properties have default values if they are not supplied by the implementer. This object should not be updated directly because some values are cached. Use `applyConfig()` to update the config object on a YUI instance that has already been configured. @class config @static **/ /** If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata if they're needed to load additional dependencies and aren't already available. Setting this to `false` will prevent YUI from automatically loading the Loader and module metadata, so you will need to manually ensure that they're available or handle dependency resolution yourself. @property {Boolean} bootstrap @default true **/ /** @property {Object} filters **/ /** If `true`, YUI will use a combo handler to load multiple modules in as few requests as possible. The YUI CDN (which YUI uses by default) supports combo handling, but other servers may not. If the server from which you're loading YUI does not support combo handling, set this to `false`. Providing a value for the `base` config property will cause `combine` to default to `false` instead of `true`. @property {Boolean} combine @default true */ /** Array of module names that should never be dynamically loaded. @property {String[]} ignore **/ /** Array of module names that should always be loaded when required, even if already present on the page. @property {String[]} force **/ /** DOM element or id that should be used as the insertion point for dynamically added ` @module test-console @namespace Test @class Console @extends Console @constructor @param {Object} [config] Config attributes. @param {Object} [config.filters] Category filter configuration. @since 3.5.0 **/ function TestConsole() { TestConsole.superclass.constructor.apply(this, arguments); } Y.namespace('Test').Console = Y.extend(TestConsole, Y.Console, { initializer: function (config) { this.on('entry', this._onEntry); this.plug(Y.Plugin.ConsoleFilters, { category: Y.merge({ info : true, pass : false, fail : true, status: false }, (config && config.filters) || {}), defaultVisibility: false, source: { TestRunner: true } }); Y.Test.Runner.on('complete', Y.bind(this._parseCoverage, this)); }, // -- Protected Coverage Parser --------------------------------------------- /** * Scans the coverage data to determine if it's an Istanbul coverage object. * @method _isIstanbul * @param {Object} json The coverage data to scan * @return {Boolean} True if this is Istanbul Coverage */ _isIstanbul: function(json) { var first = Y.Object.keys(json)[0], ret = false; if (json[first].s !== undefined && json[first].fnMap !== undefined) { ret = true; } if (json.s !== undefined && json.fnMap !== undefined) { ret = true; } return ret; }, /** * Parses and logs a summary of YUITest coverage data. * @method parseYUITest * @param {Object} coverage The YUITest Coverage JSON data */ parseYUITestCoverage: function (coverage) { var cov = { lines: { hit: 0, miss: 0, total: 0, percent: 0 }, functions: { hit: 0, miss: 0, total: 0, percent: 0 } }, coverageLog; Y.Object.each(coverage, function(info) { cov.lines.total += info.coveredLines; cov.lines.hit += info.calledLines; cov.lines.miss += (info.coveredLines - info.calledLines); cov.lines.percent = Math.floor((cov.lines.hit / cov.lines.total) * 100); cov.functions.total += info.coveredFunctions; cov.functions.hit += info.calledFunctions; cov.functions.miss += (info.coveredFunctions - info.calledFunctions); cov.functions.percent = Math.floor((cov.functions.hit / cov.functions.total) * 100); }); coverageLog = 'Lines: Hit:' + cov.lines.hit + ' Missed:' + cov.lines.miss + ' Total:' + cov.lines.total + ' Percent:' + cov.lines.percent + '%\n'; coverageLog += 'Functions: Hit:' + cov.functions.hit + ' Missed:' + cov.functions.miss + ' Total:' + cov.functions.total + ' Percent:' + cov.functions.percent + '%'; this.log('Coverage: ' + coverageLog, 'info', 'TestRunner'); }, /** * Generates a generic summary object used for Istanbul conversions. * @method _blankSummary * @return {Object} Generic summary object */ _blankSummary: function () { return { lines: { total: 0, covered: 0, pct: 'Unknown' }, statements: { total: 0, covered: 0, pct: 'Unknown' }, functions: { total: 0, covered: 0, pct: 'Unknown' }, branches: { total: 0, covered: 0, pct: 'Unknown' } }; }, /** * Calculates line numbers from statement coverage * @method _addDerivedInfoForFile * @private * @param {Object} fileCoverage JSON coverage data */ _addDerivedInfoForFile: function (fileCoverage) { var statementMap = fileCoverage.statementMap, statements = fileCoverage.s, lineMap; if (!fileCoverage.l) { fileCoverage.l = lineMap = {}; Y.Object.each(statements, function (value, st) { var line = statementMap[st].start.line, count = statements[st], prevVal = lineMap[line]; if (typeof prevVal === 'undefined' || prevVal < count) { lineMap[line] = count; } }); } }, /** * Generic percent calculator * @method _percent * @param {Number} covered The covered amount * @param {Number} total The total * @private */ _percent: function (covered, total) { var tmp, pct = 100.00; if (total > 0) { tmp = 1000 * 100 * covered / total + 5; pct = Math.floor(tmp / 10) / 100; } return pct; }, /** * Summarize simple properties in the coverage data * @method _computSimpleTotals * @private * @param {Object} fileCoverage JSON coverage data * @param {String} property The property to summarize */ _computeSimpleTotals: function (fileCoverage, property) { var stats = fileCoverage[property], ret = { total: 0, covered: 0 }; Y.Object.each(stats, function(val) { ret.total += 1; if (val) { ret.covered += 1; } }); ret.pct = this._percent(ret.covered, ret.total); return ret; }, /** * Noramlizes branch data from Istanbul * @method _computeBranchTotals * @private * @param {Object} fileCoverage JSON coverage data */ _computeBranchTotals: function (fileCoverage) { var stats = fileCoverage.b, ret = { total: 0, covered: 0 }; Y.Object.each(stats, function (branches) { var covered = Y.Array.filter(branches, function (num) { return num > 0; }); ret.total += branches.length; ret.covered += covered.length; }); ret.pct = this._percent(ret.covered, ret.total); return ret; }, /** * Takes an Istanbul coverage object, normalizes it and prints a log with a summary * @method parseInstanbul * @param {Object} coverage The coverage object to normalize and log */ parseIstanbul: function (coverage) { var self = this, str = 'Coverage Report:\n'; Y.Object.each(coverage, function(fileCoverage, file) { var ret = self._blankSummary(); self._addDerivedInfoForFile(fileCoverage); ret.lines = self._computeSimpleTotals(fileCoverage, 'l'); ret.functions = self._computeSimpleTotals(fileCoverage, 'f'); ret.statements = self._computeSimpleTotals(fileCoverage, 's'); ret.branches = self._computeBranchTotals(fileCoverage); str += file + ':\n'; Y.Array.each(['lines','functions','statements','branches'], function(key) { str += ' ' + key +': ' + ret[key].covered + '/' + ret[key].total + ' : ' + ret[key].pct + '%\n'; }); }); this.log(str, 'info', 'TestRunner'); }, /** * Parses YUITest or Istanbul coverage results if they are available and logs them. * @method _parseCoverage * @private */ _parseCoverage: function() { var coverage = Y.Test.Runner.getCoverage(); if (!coverage) { return; } if (this._isIstanbul(coverage)) { this.parseIstanbul(coverage); } else { this.parseYUITestCoverage(coverage); } }, // -- Protected Event Handlers --------------------------------------------- _onEntry: function (e) { var msg = e.message; if (msg.category === 'info' && /\s(?:case|suite)\s|yuitests\d+|began/.test(msg.message)) { msg.category = 'status'; } else if (msg.category === 'fail') { this.printBuffer(); } } }, { NAME: 'testConsole', ATTRS: { entryTemplate: { value: '
' + '
{message}
' + '
' }, height: { value: '350px' }, newestOnTop: { value: false }, style: { value: 'block' }, width: { value: Y.UA.ie && Y.UA.ie < 9 ? '100%' : 'inherit' } } }); }, '3.18.1', {"requires": ["console-filters", "test", "array-extras"], "skinnable": true}); PK\mږk$k$#3.18.1/test-console/test-console.jsnu[YUI.add('test-console', function (Y, NAME) { /** Provides a specialized log console widget that's pre-configured to display YUI Test output with no extra configuration. @example
@module test-console @namespace Test @class Console @extends Console @constructor @param {Object} [config] Config attributes. @param {Object} [config.filters] Category filter configuration. @since 3.5.0 **/ function TestConsole() { TestConsole.superclass.constructor.apply(this, arguments); } Y.namespace('Test').Console = Y.extend(TestConsole, Y.Console, { initializer: function (config) { this.on('entry', this._onEntry); this.plug(Y.Plugin.ConsoleFilters, { category: Y.merge({ info : true, pass : false, fail : true, status: false }, (config && config.filters) || {}), defaultVisibility: false, source: { TestRunner: true } }); Y.Test.Runner.on('complete', Y.bind(this._parseCoverage, this)); }, // -- Protected Coverage Parser --------------------------------------------- /** * Scans the coverage data to determine if it's an Istanbul coverage object. * @method _isIstanbul * @param {Object} json The coverage data to scan * @return {Boolean} True if this is Istanbul Coverage */ _isIstanbul: function(json) { var first = Y.Object.keys(json)[0], ret = false; if (json[first].s !== undefined && json[first].fnMap !== undefined) { ret = true; } if (json.s !== undefined && json.fnMap !== undefined) { ret = true; } return ret; }, /** * Parses and logs a summary of YUITest coverage data. * @method parseYUITest * @param {Object} coverage The YUITest Coverage JSON data */ parseYUITestCoverage: function (coverage) { var cov = { lines: { hit: 0, miss: 0, total: 0, percent: 0 }, functions: { hit: 0, miss: 0, total: 0, percent: 0 } }, coverageLog; Y.Object.each(coverage, function(info) { cov.lines.total += info.coveredLines; cov.lines.hit += info.calledLines; cov.lines.miss += (info.coveredLines - info.calledLines); cov.lines.percent = Math.floor((cov.lines.hit / cov.lines.total) * 100); cov.functions.total += info.coveredFunctions; cov.functions.hit += info.calledFunctions; cov.functions.miss += (info.coveredFunctions - info.calledFunctions); cov.functions.percent = Math.floor((cov.functions.hit / cov.functions.total) * 100); }); coverageLog = 'Lines: Hit:' + cov.lines.hit + ' Missed:' + cov.lines.miss + ' Total:' + cov.lines.total + ' Percent:' + cov.lines.percent + '%\n'; coverageLog += 'Functions: Hit:' + cov.functions.hit + ' Missed:' + cov.functions.miss + ' Total:' + cov.functions.total + ' Percent:' + cov.functions.percent + '%'; this.log('Coverage: ' + coverageLog, 'info', 'TestRunner'); }, /** * Generates a generic summary object used for Istanbul conversions. * @method _blankSummary * @return {Object} Generic summary object */ _blankSummary: function () { return { lines: { total: 0, covered: 0, pct: 'Unknown' }, statements: { total: 0, covered: 0, pct: 'Unknown' }, functions: { total: 0, covered: 0, pct: 'Unknown' }, branches: { total: 0, covered: 0, pct: 'Unknown' } }; }, /** * Calculates line numbers from statement coverage * @method _addDerivedInfoForFile * @private * @param {Object} fileCoverage JSON coverage data */ _addDerivedInfoForFile: function (fileCoverage) { var statementMap = fileCoverage.statementMap, statements = fileCoverage.s, lineMap; if (!fileCoverage.l) { fileCoverage.l = lineMap = {}; Y.Object.each(statements, function (value, st) { var line = statementMap[st].start.line, count = statements[st], prevVal = lineMap[line]; if (typeof prevVal === 'undefined' || prevVal < count) { lineMap[line] = count; } }); } }, /** * Generic percent calculator * @method _percent * @param {Number} covered The covered amount * @param {Number} total The total * @private */ _percent: function (covered, total) { var tmp, pct = 100.00; if (total > 0) { tmp = 1000 * 100 * covered / total + 5; pct = Math.floor(tmp / 10) / 100; } return pct; }, /** * Summarize simple properties in the coverage data * @method _computSimpleTotals * @private * @param {Object} fileCoverage JSON coverage data * @param {String} property The property to summarize */ _computeSimpleTotals: function (fileCoverage, property) { var stats = fileCoverage[property], ret = { total: 0, covered: 0 }; Y.Object.each(stats, function(val) { ret.total += 1; if (val) { ret.covered += 1; } }); ret.pct = this._percent(ret.covered, ret.total); return ret; }, /** * Noramlizes branch data from Istanbul * @method _computeBranchTotals * @private * @param {Object} fileCoverage JSON coverage data */ _computeBranchTotals: function (fileCoverage) { var stats = fileCoverage.b, ret = { total: 0, covered: 0 }; Y.Object.each(stats, function (branches) { var covered = Y.Array.filter(branches, function (num) { return num > 0; }); ret.total += branches.length; ret.covered += covered.length; }); ret.pct = this._percent(ret.covered, ret.total); return ret; }, /** * Takes an Istanbul coverage object, normalizes it and prints a log with a summary * @method parseInstanbul * @param {Object} coverage The coverage object to normalize and log */ parseIstanbul: function (coverage) { var self = this, str = 'Coverage Report:\n'; Y.Object.each(coverage, function(fileCoverage, file) { var ret = self._blankSummary(); self._addDerivedInfoForFile(fileCoverage); ret.lines = self._computeSimpleTotals(fileCoverage, 'l'); ret.functions = self._computeSimpleTotals(fileCoverage, 'f'); ret.statements = self._computeSimpleTotals(fileCoverage, 's'); ret.branches = self._computeBranchTotals(fileCoverage); str += file + ':\n'; Y.Array.each(['lines','functions','statements','branches'], function(key) { str += ' ' + key +': ' + ret[key].covered + '/' + ret[key].total + ' : ' + ret[key].pct + '%\n'; }); }); this.log(str, 'info', 'TestRunner'); }, /** * Parses YUITest or Istanbul coverage results if they are available and logs them. * @method _parseCoverage * @private */ _parseCoverage: function() { var coverage = Y.Test.Runner.getCoverage(); if (!coverage) { return; } if (this._isIstanbul(coverage)) { this.parseIstanbul(coverage); } else { this.parseYUITestCoverage(coverage); } }, // -- Protected Event Handlers --------------------------------------------- _onEntry: function (e) { var msg = e.message; if (msg.category === 'info' && /\s(?:case|suite)\s|yuitests\d+|began/.test(msg.message)) { msg.category = 'status'; } else if (msg.category === 'fail') { this.printBuffer(); } } }, { NAME: 'testConsole', ATTRS: { entryTemplate: { value: '
' + '
{message}
' + '
' }, height: { value: '350px' }, newestOnTop: { value: false }, style: { value: 'block' }, width: { value: Y.UA.ie && Y.UA.ie < 9 ? '100%' : 'inherit' } } }); }, '3.18.1', {"requires": ["console-filters", "test", "array-extras"], "skinnable": true}); PK\*` ` '3.18.1/test-console/test-console-min.jsnu[YUI.add("test-console",function(e,t){function n(){n.superclass.constructor.apply(this,arguments)}e.namespace("Test").Console=e.extend(n,e.Console,{initializer:function(t){this.on("entry",this._onEntry),this.plug(e.Plugin.ConsoleFilters,{category:e.merge({info:!0,pass:!1,fail:!0,status:!1},t&&t.filters||{}),defaultVisibility:!1,source:{TestRunner:!0}}),e.Test.Runner.on("complete",e.bind(this._parseCoverage,this))},_isIstanbul:function(t){var n=e.Object.keys(t)[0],r=!1;return t[n].s!==undefined&&t[n].fnMap!==undefined&&(r=!0),t.s!==undefined&&t.fnMap!==undefined&&(r=!0),r},parseYUITestCoverage:function(t){var n={lines:{hit:0,miss:0,total:0,percent:0},functions:{hit:0,miss:0,total:0,percent:0}},r;e.Object.each(t,function(e){n.lines.total+=e.coveredLines,n.lines.hit+=e.calledLines,n.lines.miss+=e.coveredLines-e.calledLines,n.lines.percent=Math.floor(n.lines.hit/n.lines.total*100),n.functions.total+=e.coveredFunctions,n.functions.hit+=e.calledFunctions,n.functions.miss+=e.coveredFunctions-e.calledFunctions,n.functions.percent=Math.floor(n.functions.hit/n.functions.total*100)}),r="Lines: Hit:"+n.lines.hit+" Missed:"+n.lines.miss+" Total:"+n.lines.total+" Percent:"+n.lines.percent+"%\n",r+="Functions: Hit:"+n.functions.hit+" Missed:"+n.functions.miss+" Total:"+n.functions.total+" Percent:"+n.functions.percent+"%",this.log("Coverage: "+r,"info","TestRunner")},_blankSummary:function(){return{lines:{total:0,covered:0,pct:"Unknown"},statements:{total:0,covered:0,pct:"Unknown"},functions:{total:0,covered:0,pct:"Unknown"},branches:{total:0,covered:0,pct:"Unknown"}}},_addDerivedInfoForFile:function(t){var n=t.statementMap,r=t.s,i;t.l||(t.l=i={},e.Object.each(r,function(e,t){var s=n[t].start.line,o=r[t],u=i[s];if(typeof u=="undefined"||u0&&(n=1e5*e/t+5,r=Math.floor(n/10)/100),r},_computeSimpleTotals:function(t,n){var r=t[n],i={total:0,covered:0};return e.Object.each(r,function(e){i.total+=1,e&&(i.covered+=1)}),i.pct=this._percent(i.covered,i.total),i},_computeBranchTotals:function(t){var n=t.b,r={total:0,covered:0};return e.Object.each(n,function(t){var n=e.Array.filter(t,function(e){return e>0});r.total+=t.length,r.covered+=n.length}),r.pct=this._percent(r.covered,r.total),r},parseIstanbul:function(t){var n=this,r="Coverage Report:\n";e.Object.each(t,function(t,i){var s=n._blankSummary();n._addDerivedInfoForFile(t),s.lines=n._computeSimpleTotals(t,"l"),s.functions=n._computeSimpleTotals(t,"f"),s.statements=n._computeSimpleTotals(t,"s"),s.branches=n._computeBranchTotals(t),r+=i+":\n",e.Array.each(["lines","functions","statements","branches"],function(e){r+=" "+e+": "+s[e].covered+"/"+s[e].total+" : "+s[e].pct+"%\n"})}),this.log(r,"info","TestRunner")},_parseCoverage:function(){var t=e.Test.Runner.getCoverage();if(!t)return;this._isIstanbul(t)?this.parseIstanbul(t):this.parseYUITestCoverage(t)},_onEntry:function(e){var t=e.message;t.category==="info"&&/\s(?:case|suite)\s|yuitests\d+|began/.test(t.message)?t.category="status":t.category==="fail"&&this.printBuffer()}},{NAME:"testConsole",ATTRS:{entryTemplate:{value:'
{message}
'},height:{value:"350px"},newestOnTop:{value:!1},style:{value:"block"},width:{value:e.UA.ie&&e.UA.ie<9?"100%":"inherit"}}})},"3.18.1",{requires:["console-filters","test","array-extras"],skinnable:!0}); PK\Yp p #3.18.1/intl-base/intl-base-debug.jsnu[YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '3.18.1', {"requires": ["yui-base"]}); PK\Yp p 3.18.1/intl-base/intl-base.jsnu[YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '3.18.1', {"requires": ["yui-base"]}); PK\B3!3.18.1/intl-base/intl-base-min.jsnu[YUI.add("intl-base",function(e,t){var n=/[, ]/;e.mix(e.namespace("Intl"),{lookupBestLang:function(t,r){function a(e){var t;for(t=0;t0){o=a(s);if(o)return o;u=s.lastIndexOf("-");if(!(u>=0))break;s=s.substring(0,u),u>=2&&s.charAt(u-2)==="-"&&(s=s.substring(0,u-2))}}return""}})},"3.18.1",{requires:["yui-base"]}); PK\FeYY-3.18.1/widget-base-ie/widget-base-ie-debug.jsnu[YUI.add('widget-base-ie', function (Y, NAME) { /** * IE specific support for the widget-base module. * * @module widget-base-ie */ var BOUNDING_BOX = "boundingBox", CONTENT_BOX = "contentBox", HEIGHT = "height", OFFSET_HEIGHT = "offsetHeight", EMPTY_STR = "", IE = Y.UA.ie, heightReallyMinHeight = IE < 7, bbTempExpanding = Y.Widget.getClassName("tmp", "forcesize"), contentExpanded = Y.Widget.getClassName("content", "expanded"); // TODO: Ideally we want to re-use the base _uiSizeCB impl Y.Widget.prototype._uiSizeCB = function(expand) { var bb = this.get(BOUNDING_BOX), cb = this.get(CONTENT_BOX), borderBoxSupported = this._bbs; if (borderBoxSupported === undefined) { this._bbs = borderBoxSupported = !(IE && IE < 8 && bb.get("ownerDocument").get("compatMode") != "BackCompat"); } if (borderBoxSupported) { cb.toggleClass(contentExpanded, expand); } else { if (expand) { if (heightReallyMinHeight) { bb.addClass(bbTempExpanding); } cb.set(OFFSET_HEIGHT, bb.get(OFFSET_HEIGHT)); if (heightReallyMinHeight) { bb.removeClass(bbTempExpanding); } } else { cb.setStyle(HEIGHT, EMPTY_STR); } } }; }, '3.18.1', {"requires": ["widget-base"]}); PK\FeYY'3.18.1/widget-base-ie/widget-base-ie.jsnu[YUI.add('widget-base-ie', function (Y, NAME) { /** * IE specific support for the widget-base module. * * @module widget-base-ie */ var BOUNDING_BOX = "boundingBox", CONTENT_BOX = "contentBox", HEIGHT = "height", OFFSET_HEIGHT = "offsetHeight", EMPTY_STR = "", IE = Y.UA.ie, heightReallyMinHeight = IE < 7, bbTempExpanding = Y.Widget.getClassName("tmp", "forcesize"), contentExpanded = Y.Widget.getClassName("content", "expanded"); // TODO: Ideally we want to re-use the base _uiSizeCB impl Y.Widget.prototype._uiSizeCB = function(expand) { var bb = this.get(BOUNDING_BOX), cb = this.get(CONTENT_BOX), borderBoxSupported = this._bbs; if (borderBoxSupported === undefined) { this._bbs = borderBoxSupported = !(IE && IE < 8 && bb.get("ownerDocument").get("compatMode") != "BackCompat"); } if (borderBoxSupported) { cb.toggleClass(contentExpanded, expand); } else { if (expand) { if (heightReallyMinHeight) { bb.addClass(bbTempExpanding); } cb.set(OFFSET_HEIGHT, bb.get(OFFSET_HEIGHT)); if (heightReallyMinHeight) { bb.removeClass(bbTempExpanding); } } else { cb.setStyle(HEIGHT, EMPTY_STR); } } }; }, '3.18.1', {"requires": ["widget-base"]}); PK\MKn+3.18.1/widget-base-ie/widget-base-ie-min.jsnu[YUI.add("widget-base-ie",function(e,t){var n="boundingBox",r="contentBox",i="height",s="offsetHeight",o="",u=e.UA.ie,a=u<7,f=e.Widget.getClassName("tmp","forcesize"),l=e.Widget.getClassName("content","expanded");e.Widget.prototype._uiSizeCB=function(e){var t=this.get(n),c=this.get(r),h=this._bbs;h===undefined&&(this._bbs=h=!(u&&u<8&&t.get("ownerDocument").get("compatMode")!="BackCompat")),h?c.toggleClass(l,e):e?(a&&t.addClass(f),c.set(s,t.get(s)),a&&t.removeClass(f)):c.setStyle(i,o)}},"3.18.1",{requires:["widget-base"]}); PK\}[}[13.18.1/content-editable/content-editable-debug.jsnu[YUI.add('content-editable', function (Y, NAME) { /*jshint maxlen: 500 */ /** * Creates a component to work with an elemment. * @class ContentEditable * @for ContentEditable * @extends Y.Plugin.Base * @constructor * @module editor * @submodule content-editable */ var Lang = Y.Lang, YNode = Y.Node, EVENT_CONTENT_READY = 'contentready', EVENT_READY = 'ready', TAG_PARAGRAPH = 'p', BLUR = 'blur', CONTAINER = 'container', CONTENT_EDITABLE = 'contentEditable', EMPTY = '', FOCUS = 'focus', HOST = 'host', INNER_HTML = 'innerHTML', KEY = 'key', PARENT_NODE = 'parentNode', PASTE = 'paste', TEXT = 'Text', USE = 'use', ContentEditable = function() { ContentEditable.superclass.constructor.apply(this, arguments); }; Y.extend(ContentEditable, Y.Plugin.Base, { /** * Internal reference set when render is called. * @private * @property _rendered * @type Boolean */ _rendered: null, /** * Internal reference to the YUI instance bound to the element * @private * @property _instance * @type YUI */ _instance: null, /** * Initializes the ContentEditable instance * @protected * @method initializer */ initializer: function() { var host = this.get(HOST); if (host) { host.frame = this; } this._eventHandles = []; this.publish(EVENT_READY, { emitFacade: true, defaultFn: this._defReadyFn }); }, /** * Destroys the instance. * @protected * @method destructor */ destructor: function() { new Y.EventHandle(this._eventHandles).detach(); this._container.removeAttribute(CONTENT_EDITABLE); }, /** * Generic handler for all DOM events fired by the Editor container. This handler * takes the current EventFacade and augments it to fire on the ContentEditable host. It adds two new properties * to the EventFacade called frameX and frameY which adds the scroll and xy position of the ContentEditable element * to the original pageX and pageY of the event so external nodes can be positioned over the element. * In case of ContentEditable element these will be equal to pageX and pageY of the container. * @private * @method _onDomEvent * @param {EventFacade} e */ _onDomEvent: function(e) { var xy; e.frameX = e.frameY = 0; if (e.pageX > 0 || e.pageY > 0) { if (e.type.substring(0, 3) !== KEY) { xy = this._container.getXY(); e.frameX = xy[0]; e.frameY = xy[1]; } } e.frameTarget = e.target; e.frameCurrentTarget = e.currentTarget; e.frameEvent = e; this.fire('dom:' + e.type, e); }, /** * Simple pass thru handler for the paste event so we can do content cleanup * @private * @method _DOMPaste * @param {EventFacade} e */ _DOMPaste: function(e) { var inst = this.getInstance(), data = EMPTY, win = inst.config.win; if (e._event.originalTarget) { data = e._event.originalTarget; } if (e._event.clipboardData) { data = e._event.clipboardData.getData(TEXT); } if (win.clipboardData) { data = win.clipboardData.getData(TEXT); if (data === EMPTY) { // Could be empty, or failed // Verify failure if (!win.clipboardData.setData(TEXT, data)) { data = null; } } } e.frameTarget = e.target; e.frameCurrentTarget = e.currentTarget; e.frameEvent = e; if (data) { e.clipboardData = { data: data, getData: function() { return data; } }; } else { Y.log('Failed to collect clipboard data', 'warn', 'contenteditable'); e.clipboardData = null; } this.fire('dom:paste', e); }, /** * Binds DOM events and fires the ready event * @private * @method _defReadyFn */ _defReadyFn: function() { var inst = this.getInstance(), container = this.get(CONTAINER); Y.each( ContentEditable.DOM_EVENTS, function(value, key) { var fn = Y.bind(this._onDomEvent, this), kfn = ((Y.UA.ie && ContentEditable.THROTTLE_TIME > 0) ? Y.throttle(fn, ContentEditable.THROTTLE_TIME) : fn); if (!inst.Node.DOM_EVENTS[key]) { inst.Node.DOM_EVENTS[key] = 1; } if (value === 1) { if (key !== FOCUS && key !== BLUR && key !== PASTE) { if (key.substring(0, 3) === KEY) { //Throttle key events in IE this._eventHandles.push(container.on(key, kfn, container)); } else { this._eventHandles.push(container.on(key, fn, container)); } } } }, this ); inst.Node.DOM_EVENTS.paste = 1; this._eventHandles.push( container.on(PASTE, Y.bind(this._DOMPaste, this), container), container.on(FOCUS, Y.bind(this._onDomEvent, this), container), container.on(BLUR, Y.bind(this._onDomEvent, this), container) ); inst.__use = inst.use; inst.use = Y.bind(this.use, this); }, /** * Called once the content is available in the ContentEditable element and calls the final use call * @private * @method _onContentReady * on the internal instance so that the modules are loaded properly. */ _onContentReady: function(event) { if (!this._ready) { this._ready = true; var inst = this.getInstance(), args = Y.clone(this.get(USE)); this.fire(EVENT_CONTENT_READY); Y.log('On content available', 'info', 'contenteditable'); if (event) { inst.config.doc = YNode.getDOMNode(event.target); } args.push(Y.bind(function() { Y.log('Callback from final internal use call', 'info', 'contenteditable'); if (inst.EditorSelection) { inst.EditorSelection.DEFAULT_BLOCK_TAG = this.get('defaultblock'); inst.EditorSelection.ROOT = this.get(CONTAINER); } this.fire(EVENT_READY); }, this)); Y.log('Calling use on internal instance: ' + args, 'info', 'contentEditable'); inst.use.apply(inst, args); } }, /** * Retrieves defaultblock value from host attribute * @private * @method _getDefaultBlock * @return {String} */ _getDefaultBlock: function() { return this._getHostValue('defaultblock'); }, /** * Retrieves dir value from host attribute * @private * @method _getDir * @return {String} */ _getDir: function() { return this._getHostValue('dir'); }, /** * Retrieves extracss value from host attribute * @private * @method _getExtraCSS * @return {String} */ _getExtraCSS: function() { return this._getHostValue('extracss'); }, /** * Get the content from the container * @private * @method _getHTML * @param {String} html The raw HTML from the container. * @return {String} */ _getHTML: function() { var html, container; if (this._ready) { container = this.get(CONTAINER); html = container.get(INNER_HTML); } return html; }, /** * Retrieves a value from host attribute * @private * @method _getHostValue * @param {attr} The attribute which value should be returned from the host * @return {String|Object} */ _getHostValue: function(attr) { var host = this.get(HOST); if (host) { return host.get(attr); } }, /** * Set the content of the container * @private * @method _setHTML * @param {String} html The raw HTML to set to the container. * @return {String} */ _setHTML: function(html) { if (this._ready) { var container = this.get(CONTAINER); container.set(INNER_HTML, html); } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setHTML, this, html)); } return html; }, /** * Sets the linked CSS on the instance. * @private * @method _setLinkedCSS * @param {String} css The linkedcss value * @return {String} */ _setLinkedCSS: function(css) { if (this._ready) { var inst = this.getInstance(); inst.Get.css(css); } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setLinkedCSS, this, css)); } return css; }, /** * Sets the dir (language direction) attribute on the container. * @private * @method _setDir * @param {String} value The language direction * @return {String} */ _setDir: function(value) { var container; if (this._ready) { container = this.get(CONTAINER); container.setAttribute('dir', value); } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setDir, this, value)); } return value; }, /** * Set's the extra CSS on the instance. * @private * @method _setExtraCSS * @param {String} css The CSS style to be set as extra css * @return {String} */ _setExtraCSS: function(css) { if (this._ready) { if (css) { var inst = this.getInstance(), head = inst.one('head'); if (this._extraCSSNode) { this._extraCSSNode.remove(); } this._extraCSSNode = YNode.create(''); head.append(this._extraCSSNode); } } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setExtraCSS, this, css)); } return css; }, /** * Sets the language value on the instance. * @private * @method _setLang * @param {String} value The language to be set * @return {String} */ _setLang: function(value) { var container; if (this._ready) { container = this.get(CONTAINER); container.setAttribute('lang', value); } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setLang, this, value)); } return value; }, /** * Called from the first YUI instance that sets up the internal instance. * This loads the content into the ContentEditable element and attaches the contentready event. * @private * @method _instanceLoaded * @param {YUI} inst The internal YUI instance bound to the ContentEditable element */ _instanceLoaded: function(inst) { this._instance = inst; this._onContentReady(); var doc = this._instance.config.doc; if (!Y.UA.ie) { try { //Force other browsers into non CSS styling doc.execCommand('styleWithCSS', false, false); doc.execCommand('insertbronreturn', false, false); } catch (err) {} } }, /** * Validates linkedcss property * * @method _validateLinkedCSS * @private */ _validateLinkedCSS: function(value) { return Lang.isString(value) || Lang.isArray(value); }, //BEGIN PUBLIC METHODS /** * This is a scoped version of the normal YUI.use method & is bound to the ContentEditable element * At setup, the inst.use method is mapped to this method. * @method use */ use: function() { Y.log('Calling augmented use after ready', 'info', 'contenteditable'); var inst = this.getInstance(), args = Y.Array(arguments), callback = false; if (Lang.isFunction(args[args.length - 1])) { callback = args.pop(); } if (callback) { args.push(function() { Y.log('Internal callback from augmented use', 'info', 'contenteditable'); callback.apply(inst, arguments); }); } return inst.__use.apply(inst, args); }, /** * A delegate method passed to the instance's delegate method * @method delegate * @param {String} type The type of event to listen for * @param {Function} fn The method to attach * @param {String, Node} cont The container to act as a delegate, if no "sel" passed, the container is assumed. * @param {String} sel The selector to match in the event (optional) * @return {EventHandle} The Event handle returned from Y.delegate */ delegate: function(type, fn, cont, sel) { var inst = this.getInstance(); if (!inst) { Y.log('Delegate events can not be attached until after the ready event has fired.', 'error', 'contenteditable'); return false; } if (!sel) { sel = cont; cont = this.get(CONTAINER); } return inst.delegate(type, fn, cont, sel); }, /** * Get a reference to the internal YUI instance. * @method getInstance * @return {YUI} The internal YUI instance */ getInstance: function() { return this._instance; }, /** * @method render * @param {String/HTMLElement/Node} node The node to render to * @return {ContentEditable} * @chainable */ render: function(node) { var args, inst, fn; if (this._rendered) { Y.log('Container already rendered.', 'warn', 'contentEditable'); return this; } if (node) { this.set(CONTAINER, node); } container = this.get(CONTAINER); if (!container) { container = YNode.create(ContentEditable.HTML); Y.one('body').prepend(container); this.set(CONTAINER, container); } this._rendered = true; this._container.setAttribute(CONTENT_EDITABLE, true); args = Y.clone(this.get(USE)); fn = Y.bind(function() { inst = YUI(); inst.host = this.get(HOST); //Cross reference to Editor inst.log = Y.log; //Dump the instance logs to the parent instance. Y.log('Creating new internal instance with node-base only', 'info', 'contenteditable'); inst.use('node-base', Y.bind(this._instanceLoaded, this)); }, this); args.push(fn); Y.log('Adding new modules to main instance: ' + args, 'info', 'contenteditable'); Y.use.apply(Y, args); return this; }, /** * Set the focus to the container * @method focus * @param {Function} fn Callback function to execute after focus happens * @return {ContentEditable} * @chainable */ focus: function() { this._container.focus(); return this; }, /** * Show the iframe instance * @method show * @return {ContentEditable} * @chainable */ show: function() { this._container.show(); this.focus(); return this; }, /** * Hide the iframe instance * @method hide * @return {ContentEditable} * @chainable */ hide: function() { this._container.hide(); return this; } }, { /** * The throttle time for key events in IE * @static * @property THROTTLE_TIME * @type Number * @default 100 */ THROTTLE_TIME: 100, /** * The DomEvents that the frame automatically attaches and bubbles * @static * @property DOM_EVENTS * @type Object */ DOM_EVENTS: { click: 1, dblclick: 1, focusin: 1, focusout: 1, keydown: 1, keypress: 1, keyup: 1, mousedown: 1, mouseup: 1, paste: 1 }, /** * The template string used to create the ContentEditable element * @static * @property HTML * @type String */ HTML: '
', /** * The name of the class (contentEditable) * @static * @property NAME * @type String */ NAME: 'contentEditable', /** * The namespace on which ContentEditable plugin will reside. * * @property NS * @type String * @default 'contentEditable' * @static */ NS: CONTENT_EDITABLE, ATTRS: { /** * The default text direction for this ContentEditable element. Default: ltr * @attribute dir * @type String */ dir: { lazyAdd: false, validator: Lang.isString, setter: '_setDir', valueFn: '_getDir' }, /** * The container to set contentEditable=true or to create on render. * @attribute container * @type String/HTMLElement/Node */ container: { setter: function(n) { this._container = Y.one(n); return this._container; } }, /** * The string to inject as Editor content. Default '
' * @attribute content * @type String */ content: { getter: '_getHTML', lazyAdd: false, setter: '_setHTML', validator: Lang.isString, value: '
' }, /** * The default tag to use for block level items, defaults to: p * @attribute defaultblock * @type String */ defaultblock: { validator: Lang.isString, value: TAG_PARAGRAPH, valueFn: '_getDefaultBlock' }, /** * A string of CSS to add to the Head of the Editor * @attribute extracss * @type String */ extracss: { lazyAdd: false, setter: '_setExtraCSS', validator: Lang.isString, valueFn: '_getExtraCSS' }, /** * Set the id of the new Node. (optional) * @attribute id * @type String * @writeonce */ id: { writeOnce: true, getter: function(id) { if (!id) { id = 'inlineedit-' + Y.guid(); } return id; } }, /** * The default language. Default: en-US * @attribute lang * @type String */ lang: { validator: Lang.isString, setter: '_setLang', lazyAdd: false, value: 'en-US' }, /** * An array of url's to external linked style sheets * @attribute linkedcss * @type String|Array */ linkedcss: { setter: '_setLinkedCSS', validator: '_validateLinkedCSS' //value: '' }, /** * The Node instance of the container. * @attribute node * @type Node */ node: { readOnly: true, value: null, getter: function() { return this._container; } }, /** * Array of modules to include in the scoped YUI instance at render time. Default: ['node-base', 'editor-selection', 'stylesheet'] * @attribute use * @writeonce * @type Array */ use: { validator: Lang.isArray, writeOnce: true, value: ['node-base', 'editor-selection', 'stylesheet'] } } }); Y.namespace('Plugin'); Y.Plugin.ContentEditable = ContentEditable; }, '3.18.1', {"requires": ["node-base", "editor-selection", "stylesheet", "plugin"]}); PK\xxWW+3.18.1/content-editable/content-editable.jsnu[YUI.add('content-editable', function (Y, NAME) { /*jshint maxlen: 500 */ /** * Creates a component to work with an elemment. * @class ContentEditable * @for ContentEditable * @extends Y.Plugin.Base * @constructor * @module editor * @submodule content-editable */ var Lang = Y.Lang, YNode = Y.Node, EVENT_CONTENT_READY = 'contentready', EVENT_READY = 'ready', TAG_PARAGRAPH = 'p', BLUR = 'blur', CONTAINER = 'container', CONTENT_EDITABLE = 'contentEditable', EMPTY = '', FOCUS = 'focus', HOST = 'host', INNER_HTML = 'innerHTML', KEY = 'key', PARENT_NODE = 'parentNode', PASTE = 'paste', TEXT = 'Text', USE = 'use', ContentEditable = function() { ContentEditable.superclass.constructor.apply(this, arguments); }; Y.extend(ContentEditable, Y.Plugin.Base, { /** * Internal reference set when render is called. * @private * @property _rendered * @type Boolean */ _rendered: null, /** * Internal reference to the YUI instance bound to the element * @private * @property _instance * @type YUI */ _instance: null, /** * Initializes the ContentEditable instance * @protected * @method initializer */ initializer: function() { var host = this.get(HOST); if (host) { host.frame = this; } this._eventHandles = []; this.publish(EVENT_READY, { emitFacade: true, defaultFn: this._defReadyFn }); }, /** * Destroys the instance. * @protected * @method destructor */ destructor: function() { new Y.EventHandle(this._eventHandles).detach(); this._container.removeAttribute(CONTENT_EDITABLE); }, /** * Generic handler for all DOM events fired by the Editor container. This handler * takes the current EventFacade and augments it to fire on the ContentEditable host. It adds two new properties * to the EventFacade called frameX and frameY which adds the scroll and xy position of the ContentEditable element * to the original pageX and pageY of the event so external nodes can be positioned over the element. * In case of ContentEditable element these will be equal to pageX and pageY of the container. * @private * @method _onDomEvent * @param {EventFacade} e */ _onDomEvent: function(e) { var xy; e.frameX = e.frameY = 0; if (e.pageX > 0 || e.pageY > 0) { if (e.type.substring(0, 3) !== KEY) { xy = this._container.getXY(); e.frameX = xy[0]; e.frameY = xy[1]; } } e.frameTarget = e.target; e.frameCurrentTarget = e.currentTarget; e.frameEvent = e; this.fire('dom:' + e.type, e); }, /** * Simple pass thru handler for the paste event so we can do content cleanup * @private * @method _DOMPaste * @param {EventFacade} e */ _DOMPaste: function(e) { var inst = this.getInstance(), data = EMPTY, win = inst.config.win; if (e._event.originalTarget) { data = e._event.originalTarget; } if (e._event.clipboardData) { data = e._event.clipboardData.getData(TEXT); } if (win.clipboardData) { data = win.clipboardData.getData(TEXT); if (data === EMPTY) { // Could be empty, or failed // Verify failure if (!win.clipboardData.setData(TEXT, data)) { data = null; } } } e.frameTarget = e.target; e.frameCurrentTarget = e.currentTarget; e.frameEvent = e; if (data) { e.clipboardData = { data: data, getData: function() { return data; } }; } else { e.clipboardData = null; } this.fire('dom:paste', e); }, /** * Binds DOM events and fires the ready event * @private * @method _defReadyFn */ _defReadyFn: function() { var inst = this.getInstance(), container = this.get(CONTAINER); Y.each( ContentEditable.DOM_EVENTS, function(value, key) { var fn = Y.bind(this._onDomEvent, this), kfn = ((Y.UA.ie && ContentEditable.THROTTLE_TIME > 0) ? Y.throttle(fn, ContentEditable.THROTTLE_TIME) : fn); if (!inst.Node.DOM_EVENTS[key]) { inst.Node.DOM_EVENTS[key] = 1; } if (value === 1) { if (key !== FOCUS && key !== BLUR && key !== PASTE) { if (key.substring(0, 3) === KEY) { //Throttle key events in IE this._eventHandles.push(container.on(key, kfn, container)); } else { this._eventHandles.push(container.on(key, fn, container)); } } } }, this ); inst.Node.DOM_EVENTS.paste = 1; this._eventHandles.push( container.on(PASTE, Y.bind(this._DOMPaste, this), container), container.on(FOCUS, Y.bind(this._onDomEvent, this), container), container.on(BLUR, Y.bind(this._onDomEvent, this), container) ); inst.__use = inst.use; inst.use = Y.bind(this.use, this); }, /** * Called once the content is available in the ContentEditable element and calls the final use call * @private * @method _onContentReady * on the internal instance so that the modules are loaded properly. */ _onContentReady: function(event) { if (!this._ready) { this._ready = true; var inst = this.getInstance(), args = Y.clone(this.get(USE)); this.fire(EVENT_CONTENT_READY); if (event) { inst.config.doc = YNode.getDOMNode(event.target); } args.push(Y.bind(function() { if (inst.EditorSelection) { inst.EditorSelection.DEFAULT_BLOCK_TAG = this.get('defaultblock'); inst.EditorSelection.ROOT = this.get(CONTAINER); } this.fire(EVENT_READY); }, this)); inst.use.apply(inst, args); } }, /** * Retrieves defaultblock value from host attribute * @private * @method _getDefaultBlock * @return {String} */ _getDefaultBlock: function() { return this._getHostValue('defaultblock'); }, /** * Retrieves dir value from host attribute * @private * @method _getDir * @return {String} */ _getDir: function() { return this._getHostValue('dir'); }, /** * Retrieves extracss value from host attribute * @private * @method _getExtraCSS * @return {String} */ _getExtraCSS: function() { return this._getHostValue('extracss'); }, /** * Get the content from the container * @private * @method _getHTML * @param {String} html The raw HTML from the container. * @return {String} */ _getHTML: function() { var html, container; if (this._ready) { container = this.get(CONTAINER); html = container.get(INNER_HTML); } return html; }, /** * Retrieves a value from host attribute * @private * @method _getHostValue * @param {attr} The attribute which value should be returned from the host * @return {String|Object} */ _getHostValue: function(attr) { var host = this.get(HOST); if (host) { return host.get(attr); } }, /** * Set the content of the container * @private * @method _setHTML * @param {String} html The raw HTML to set to the container. * @return {String} */ _setHTML: function(html) { if (this._ready) { var container = this.get(CONTAINER); container.set(INNER_HTML, html); } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setHTML, this, html)); } return html; }, /** * Sets the linked CSS on the instance. * @private * @method _setLinkedCSS * @param {String} css The linkedcss value * @return {String} */ _setLinkedCSS: function(css) { if (this._ready) { var inst = this.getInstance(); inst.Get.css(css); } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setLinkedCSS, this, css)); } return css; }, /** * Sets the dir (language direction) attribute on the container. * @private * @method _setDir * @param {String} value The language direction * @return {String} */ _setDir: function(value) { var container; if (this._ready) { container = this.get(CONTAINER); container.setAttribute('dir', value); } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setDir, this, value)); } return value; }, /** * Set's the extra CSS on the instance. * @private * @method _setExtraCSS * @param {String} css The CSS style to be set as extra css * @return {String} */ _setExtraCSS: function(css) { if (this._ready) { if (css) { var inst = this.getInstance(), head = inst.one('head'); if (this._extraCSSNode) { this._extraCSSNode.remove(); } this._extraCSSNode = YNode.create(''); head.append(this._extraCSSNode); } } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setExtraCSS, this, css)); } return css; }, /** * Sets the language value on the instance. * @private * @method _setLang * @param {String} value The language to be set * @return {String} */ _setLang: function(value) { var container; if (this._ready) { container = this.get(CONTAINER); container.setAttribute('lang', value); } else { //This needs to be wrapped in a contentready callback for the !_ready state this.once(EVENT_CONTENT_READY, Y.bind(this._setLang, this, value)); } return value; }, /** * Called from the first YUI instance that sets up the internal instance. * This loads the content into the ContentEditable element and attaches the contentready event. * @private * @method _instanceLoaded * @param {YUI} inst The internal YUI instance bound to the ContentEditable element */ _instanceLoaded: function(inst) { this._instance = inst; this._onContentReady(); var doc = this._instance.config.doc; if (!Y.UA.ie) { try { //Force other browsers into non CSS styling doc.execCommand('styleWithCSS', false, false); doc.execCommand('insertbronreturn', false, false); } catch (err) {} } }, /** * Validates linkedcss property * * @method _validateLinkedCSS * @private */ _validateLinkedCSS: function(value) { return Lang.isString(value) || Lang.isArray(value); }, //BEGIN PUBLIC METHODS /** * This is a scoped version of the normal YUI.use method & is bound to the ContentEditable element * At setup, the inst.use method is mapped to this method. * @method use */ use: function() { var inst = this.getInstance(), args = Y.Array(arguments), callback = false; if (Lang.isFunction(args[args.length - 1])) { callback = args.pop(); } if (callback) { args.push(function() { callback.apply(inst, arguments); }); } return inst.__use.apply(inst, args); }, /** * A delegate method passed to the instance's delegate method * @method delegate * @param {String} type The type of event to listen for * @param {Function} fn The method to attach * @param {String, Node} cont The container to act as a delegate, if no "sel" passed, the container is assumed. * @param {String} sel The selector to match in the event (optional) * @return {EventHandle} The Event handle returned from Y.delegate */ delegate: function(type, fn, cont, sel) { var inst = this.getInstance(); if (!inst) { return false; } if (!sel) { sel = cont; cont = this.get(CONTAINER); } return inst.delegate(type, fn, cont, sel); }, /** * Get a reference to the internal YUI instance. * @method getInstance * @return {YUI} The internal YUI instance */ getInstance: function() { return this._instance; }, /** * @method render * @param {String/HTMLElement/Node} node The node to render to * @return {ContentEditable} * @chainable */ render: function(node) { var args, inst, fn; if (this._rendered) { return this; } if (node) { this.set(CONTAINER, node); } container = this.get(CONTAINER); if (!container) { container = YNode.create(ContentEditable.HTML); Y.one('body').prepend(container); this.set(CONTAINER, container); } this._rendered = true; this._container.setAttribute(CONTENT_EDITABLE, true); args = Y.clone(this.get(USE)); fn = Y.bind(function() { inst = YUI(); inst.host = this.get(HOST); //Cross reference to Editor inst.use('node-base', Y.bind(this._instanceLoaded, this)); }, this); args.push(fn); Y.use.apply(Y, args); return this; }, /** * Set the focus to the container * @method focus * @param {Function} fn Callback function to execute after focus happens * @return {ContentEditable} * @chainable */ focus: function() { this._container.focus(); return this; }, /** * Show the iframe instance * @method show * @return {ContentEditable} * @chainable */ show: function() { this._container.show(); this.focus(); return this; }, /** * Hide the iframe instance * @method hide * @return {ContentEditable} * @chainable */ hide: function() { this._container.hide(); return this; } }, { /** * The throttle time for key events in IE * @static * @property THROTTLE_TIME * @type Number * @default 100 */ THROTTLE_TIME: 100, /** * The DomEvents that the frame automatically attaches and bubbles * @static * @property DOM_EVENTS * @type Object */ DOM_EVENTS: { click: 1, dblclick: 1, focusin: 1, focusout: 1, keydown: 1, keypress: 1, keyup: 1, mousedown: 1, mouseup: 1, paste: 1 }, /** * The template string used to create the ContentEditable element * @static * @property HTML * @type String */ HTML: '
', /** * The name of the class (contentEditable) * @static * @property NAME * @type String */ NAME: 'contentEditable', /** * The namespace on which ContentEditable plugin will reside. * * @property NS * @type String * @default 'contentEditable' * @static */ NS: CONTENT_EDITABLE, ATTRS: { /** * The default text direction for this ContentEditable element. Default: ltr * @attribute dir * @type String */ dir: { lazyAdd: false, validator: Lang.isString, setter: '_setDir', valueFn: '_getDir' }, /** * The container to set contentEditable=true or to create on render. * @attribute container * @type String/HTMLElement/Node */ container: { setter: function(n) { this._container = Y.one(n); return this._container; } }, /** * The string to inject as Editor content. Default '
' * @attribute content * @type String */ content: { getter: '_getHTML', lazyAdd: false, setter: '_setHTML', validator: Lang.isString, value: '
' }, /** * The default tag to use for block level items, defaults to: p * @attribute defaultblock * @type String */ defaultblock: { validator: Lang.isString, value: TAG_PARAGRAPH, valueFn: '_getDefaultBlock' }, /** * A string of CSS to add to the Head of the Editor * @attribute extracss * @type String */ extracss: { lazyAdd: false, setter: '_setExtraCSS', validator: Lang.isString, valueFn: '_getExtraCSS' }, /** * Set the id of the new Node. (optional) * @attribute id * @type String * @writeonce */ id: { writeOnce: true, getter: function(id) { if (!id) { id = 'inlineedit-' + Y.guid(); } return id; } }, /** * The default language. Default: en-US * @attribute lang * @type String */ lang: { validator: Lang.isString, setter: '_setLang', lazyAdd: false, value: 'en-US' }, /** * An array of url's to external linked style sheets * @attribute linkedcss * @type String|Array */ linkedcss: { setter: '_setLinkedCSS', validator: '_validateLinkedCSS' //value: '' }, /** * The Node instance of the container. * @attribute node * @type Node */ node: { readOnly: true, value: null, getter: function() { return this._container; } }, /** * Array of modules to include in the scoped YUI instance at render time. Default: ['node-base', 'editor-selection', 'stylesheet'] * @attribute use * @writeonce * @type Array */ use: { validator: Lang.isArray, writeOnce: true, value: ['node-base', 'editor-selection', 'stylesheet'] } } }); Y.namespace('Plugin'); Y.Plugin.ContentEditable = ContentEditable; }, '3.18.1', {"requires": ["node-base", "editor-selection", "stylesheet", "plugin"]}); PK\/3.18.1/content-editable/content-editable-min.jsnu[YUI.add("content-editable",function(e,t){var n=e.Lang,r=e.Node,i="contentready",s="ready",o="p",u="blur",a="container",f="contentEditable",l="",c="focus",h="host",p="innerHTML",d="key",v="parentNode",m="paste",g="Text",y="use",b=function(){b.superclass.constructor.apply(this,arguments)};e.extend(b,e.Plugin.Base,{_rendered:null,_instance:null,initializer:function(){var e=this.get(h);e&&(e.frame=this),this._eventHandles=[],this.publish(s,{emitFacade:!0,defaultFn:this._defReadyFn})},destructor:function(){(new e.EventHandle(this._eventHandles)).detach(),this._container.removeAttribute(f)},_onDomEvent:function(e){var t;e.frameX=e.frameY=0,(e.pageX>0||e.pageY>0)&&e.type.substring(0,3)!==d&&(t=this._container.getXY(),e.frameX=t[0],e.frameY=t[1]),e.frameTarget=e.target,e.frameCurrentTarget=e.currentTarget,e.frameEvent=e,this.fire("dom:"+e.type,e)},_DOMPaste:function(e){var t=this.getInstance(),n=l,r=t.config.win;e._event.originalTarget&&(n=e._event.originalTarget),e._event.clipboardData&&(n=e._event.clipboardData.getData(g)),r.clipboardData&&(n=r.clipboardData.getData(g),n===l&&(r.clipboardData.setData(g,n)||(n=null))),e.frameTarget=e.target,e.frameCurrentTarget=e.currentTarget,e.frameEvent=e,n?e.clipboardData={data:n,getData:function(){return n}}:e.clipboardData=null,this.fire("dom:paste",e)},_defReadyFn:function(){var t=this.getInstance(),n=this.get(a);e.each(b.DOM_EVENTS,function(r,i){var s=e.bind(this._onDomEvent,this),o=e.UA.ie&&b.THROTTLE_TIME>0?e.throttle(s,b.THROTTLE_TIME):s;t.Node.DOM_EVENTS[i]||(t.Node.DOM_EVENTS[i]=1),r===1&&i!==c&&i!==u&&i!==m&&(i.substring(0,3)===d?this._eventHandles.push(n.on(i,o,n)):this._eventHandles.push(n.on(i,s,n)))},this),t.Node.DOM_EVENTS.paste=1,this._eventHandles.push(n.on(m,e.bind(this._DOMPaste,this),n),n.on(c,e.bind(this._onDomEvent,this),n),n.on(u,e.bind(this._onDomEvent,this),n)),t.__use=t.use,t.use=e.bind(this.use,this)},_onContentReady:function(t){if(!this._ready){this._ready=!0;var n=this.getInstance(),o=e.clone(this.get(y));this.fire(i),t&&(n.config.doc=r.getDOMNode(t.target)),o.push(e.bind(function(){n.EditorSelection&&(n.EditorSelection.DEFAULT_BLOCK_TAG=this.get("defaultblock"),n.EditorSelection.ROOT=this.get(a)),this.fire(s)},this)),n.use.apply(n,o)}},_getDefaultBlock:function(){return this._getHostValue("defaultblock")},_getDir:function(){return this._getHostValue("dir")},_getExtraCSS:function(){return this._getHostValue("extracss")},_getHTML:function(){var e,t;return this._ready&&(t=this.get(a),e=t.get(p)),e},_getHostValue:function(e){var t=this.get(h);if(t)return t.get(e)},_setHTML:function(t){if(this._ready){var n=this.get(a);n.set(p,t)}else this.once(i,e.bind(this._setHTML,this,t));return t},_setLinkedCSS:function(t){if(this._ready){var n=this.getInstance();n.Get.css(t)}else this.once(i,e.bind(this._setLinkedCSS,this,t));return t},_setDir:function(t){var n;return this._ready?(n=this.get(a),n.setAttribute("dir",t)):this.once(i,e.bind(this._setDir,this,t)),t},_setExtraCSS:function(t){if(this._ready){if(t){var n=this.getInstance(),s=n.one("head");this._extraCSSNode&&this._extraCSSNode.remove(),this._extraCSSNode=r.create(""),s.append(this._extraCSSNode)}}else this.once(i,e.bind(this._setExtraCSS,this,t));return t},_setLang:function(t){var n;return this._ready?(n=this.get(a),n.setAttribute("lang",t)):this.once(i,e.bind(this._setLang,this,t)),t},_instanceLoaded:function(t){this._instance=t,this._onContentReady();var n=this._instance.config.doc;if(!e.UA.ie)try{n.execCommand("styleWithCSS",!1,!1),n.execCommand("insertbronreturn",!1,!1)}catch(r){}},_validateLinkedCSS:function(e){return n.isString(e)||n.isArray(e)},use:function(){var t=this.getInstance(),r=e.Array(arguments),i=!1;return n.isFunction(r[r.length-1])&&(i=r.pop()),i&&r.push(function(){i.apply(t,arguments)}),t.__use.apply(t,r)},delegate:function(e,t,n,r){var i=this.getInstance();return i?(r||(r=n,n=this.get(a)),i.delegate(e,t,n,r)):!1},getInstance:function(){return this._instance},render:function(t){var n,i,s;return this._rendered?this:(t&&this.set(a,t),container=this.get(a),container||(container=r.create(b.HTML),e.one("body").prepend(container),this.set(a,container)),this._rendered=!0,this._container.setAttribute(f,!0),n=e.clone(this.get(y)),s=e.bind(function(){i=YUI(),i.host=this.get(h),i.use("node-base",e.bind(this._instanceLoaded,this))},this),n.push(s),e.use.apply(e,n),this)},focus:function(){return this._container.focus(),this},show:function(){return this._container.show(),this.focus(),this},hide:function(){return this._container.hide(),this}},{THROTTLE_TIME:100,DOM_EVENTS:{click:1,dblclick:1,focusin:1,focusout:1,keydown:1,keypress:1,keyup:1,mousedown:1,mouseup:1,paste:1},HTML:"
",NAME:"contentEditable",NS:f,ATTRS:{dir:{lazyAdd:!1,validator:n.isString,setter:"_setDir",valueFn:"_getDir"},container:{setter:function(t){return this._container=e.one(t),this._container}},content:{getter:"_getHTML",lazyAdd:!1,setter:"_setHTML",validator:n.isString,value:"
"},defaultblock:{validator:n.isString,value:o,valueFn:"_getDefaultBlock"},extracss:{lazyAdd:!1,setter:"_setExtraCSS",validator:n.isString,valueFn:"_getExtraCSS"},id:{writeOnce:!0,getter:function(t){return t||(t="inlineedit-"+e.guid()),t}},lang:{validator:n.isString,setter:"_setLang",lazyAdd:!1,value:"en-US"},linkedcss:{setter:"_setLinkedCSS",validator:"_validateLinkedCSS"},node:{readOnly:!0,value:null,getter:function(){return this._container}},use:{validator:n.isArray,writeOnce:!0,value:["node-base","editor-selection","stylesheet"]}}}),e.namespace("Plugin"),e.Plugin.ContentEditable=b},"3.18.1",{requires:["node-base","editor-selection","stylesheet","plugin"]}); PK\7sDD%3.18.1/selector-css2/selector-css2.jsnu[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 = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], visited, tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName, isUniversal; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() visited = []; child = root.firstChild; isUniversal = tagName === "*"; while (child) { while (child) { // IE 6-7 considers comment nodes as element nodes, and gives them the tagName "!". // We can filter them out by checking if its tagName is > "@". // This also avoids a superflous nodeType === 1 check. if (child.tagName > "@" && (isUniversal || child.tagName === tagName)) { nodes.push(child); } // We may need to traverse back up the tree to find more unvisited subtrees. visited.push(child); child = child.firstChild; } // Find the most recently visited node who has a next sibling. while (visited.length > 0 && !child) { child = visited.pop().nextSibling; } } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '3.18.1', {"requires": ["selector-native"]}); PK\)xx)3.18.1/selector-css2/selector-css2-min.jsnu[YUI.add("selector-css2",function(e,t){var n="parentNode",r="tagName",i="attributes",s="combinator",o="pseudos",u=e.Selector,a={_reRegExpTokens:/([\^\$\?\[\]\*\+\-\.\(\)\|\\])/,SORT_RESULTS:!0,_isXML:function(){var t=e.config.doc.createElement("div").tagName!=="DIV";return t}(),shorthand:{"\\#(-?[_a-z0-9]+[-\\w\\uE000]*)":"[id=$1]","\\.(-?[_a-z]+[-\\w\\uE000]*)":"[className~=$1]"},operators:{"":function(t,n){return e.DOM.getAttribute(t,n)!==""},"~=":"(?:^|\\s+){val}(?:\\s+|$)","|=":"^{val}-?"},pseudos:{"first-child":function(t){return e.DOM._children(t[n])[0]===t}},_bruteQuery:function(t,n,r){var i=[],s=[],o,a=u._tokenize(t),f=a[a.length-1],l=e.DOM._getDoc(n),c,h,p,d,v;if(f){h=f.id,p=f.className,d=f.tagName||"*";if(n.getElementsByTagName)h&&(n.all||n.nodeType===9||e.DOM.inDoc(n))?s=e.DOM.allById(h,n):p?s=n.getElementsByClassName(p):s=n.getElementsByTagName(d);else{o=[],c=n.firstChild,v=d==="*";while(c){while(c)c.tagName>"@"&&(v||c.tagName===d)&&s.push(c),o.push(c),c=c.firstChild;while(o.length>0&&!c)c=o.pop().nextSibling}}s.length&&(i=u._filterNodes(s,a,r))}return i},_filterNodes:function(t,n,r){var i=0,s,o=n.length,a=o-1,f=[],l=t[0],c=l,h=e.Selector.getters,p,d,v,m,g,y,b,w;for(i=0;c=l=t[i++];){a=o-1,m=null;e:while(c&&c.tagName){v=n[a],b=v.tests,s=b.length;if(s&&!g)while(w=b[--s]){p=w[1],h[w[0]]?y=h[w[0]](c,w[0]):(y=c[w[0]],w[0]==="tagName"&&!u._isXML&&(y=y.toUpperCase()),typeof y!="string"&&y!==undefined&&y.toString?y=y.toString():y===undefined&&c.getAttribute&&(y=c.getAttribute(w[0],2)));if(p==="="&&y!==w[2]||typeof p!="string"&&p.test&&!p.test(y)||!p.test&&typeof p=="function"&&!p(c,w[0],w[2])){if(c=c[m])while(c&&(!c.tagName||v.tagName&&v.tagName!==c.tagName))c=c[m];continue e}}a--;if(!!g||!(d=v.combinator)){f.push(l);if(r)return f;break}m=d.axis,c=c[m];while(c&&!c.tagName)c=c[m];d.direct&&(m=null)}}return l=c=null,f},combinators:{" ":{axis:"parentNode"},">":{axis:"parentNode",direct:!0},"+":{axis:"previousSibling",direct:!0}},_parsers:[{name:i,re:/^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i,fn:function(t,n){var r=t[2]||"",i=u.operators,s=t[3]?t[3].replace(/\\/g,""):"",o;if(t[1]==="id"&&r==="="||t[1]==="className"&&e.config.doc.documentElement.getElementsByClassName&&(r==="~="||r==="="))n.prefilter=t[1],t[3]=s,n[t[1]]=t[1]==="id"?t[3]:s;r in i&&(o=i[r],typeof o=="string"&&(t[3]=s.replace(u._reRegExpTokens,"\\$1"),o=new RegExp(o.replace("{val}",t[3]))),t[2]=o);if(!n.last||n.prefilter!==t[1])return t.slice(1)}},{name:r,re:/^((?:-?[_a-z]+[\w-]*)|\*)/i,fn:function(e,t){var n=e[1];u._isXML||(n=n.toUpperCase()),t.tagName=n;if(n!=="*"&&(!t.last||t.prefilter))return[r,"=",n];t.prefilter||(t.prefilter="tagName")}},{name:s,re:/^\s*([>+~]|\s)\s*/,fn:function(e,t){}},{name:o,re:/^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i,fn:function(e,t){var n=u[o][e[1]];return n?(e[2]&&(e[2]=e[2].replace(/\\/g,"")),[e[2],n]):!1}}],_getToken:function(e){return{tagName:null,id:null,className:null,attributes:{},combinator:null,tests:[]}},_tokenize:function(t){t=t||"",t=u._parseSelector(e.Lang.trim(t));var n=u._getToken(),r=t,i=[],o=!1,a,f,l,c;e:do{o=!1;for(l=0;c=u._parsers[l++];)if(a=c.re.exec(t)){c.name!==s&&(n.selector=t),t=t.replace(a[0],""),t.length||(n.last=!0),u._attrFilters[a[1]]&&(a[1]=u._attrFilters[a[1]]),f=c.fn(a,n);if(f===!1){o=!1;break e}f&&n.tests.push(f);if(!t.length||c.name===s)i.push(n),n=u._getToken(n),c.name===s&&(n.combinator=e.Selector.combinators[a[1]]);o=!0}}while(o&&t.length);if(!o||t.length)i=[];return i},_replaceMarkers:function(e){return e=e.replace(/\[/g,"\ue003"),e=e.replace(/\]/g,"\ue004"),e=e.replace(/\(/g,"\ue005"),e=e.replace(/\)/g,"\ue006"),e},_replaceShorthand:function(t){var n=e.Selector.shorthand,r;for(r in n)n.hasOwnProperty(r)&&(t=t.replace(new RegExp(r,"gi"),n[r]));return t},_parseSelector:function(t){var n=e.Selector._replaceSelector(t),t=n.selector;return t=e.Selector._replaceShorthand(t),t=e.Selector._restore("attr",t,n.attrs),t=e.Selector._restore("pseudo",t,n.pseudos),t=e.Selector._replaceMarkers(t),t=e.Selector._restore("esc",t,n.esc),t},_attrFilters:{"class":"className","for":"htmlFor"},getters:{href:function(t,n){return e.DOM.getAttribute(t,n)},id:function(t,n){return e.DOM.getId(t)}}};e.mix(e.Selector,a,!0),e.Selector.getters.src=e.Selector.getters.rel=e.Selector.getters.href,e.Selector.useNative&&e.config.doc.querySelector&&(e.Selector.shorthand["\\.(-?[_a-z]+[-\\w]*)"]="[class~=$1]")},"3.18.1",{requires:["selector-native"]}); PK\SDD+3.18.1/selector-css2/selector-css2-debug.jsnu[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 = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], visited, tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName, isUniversal; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() visited = []; child = root.firstChild; isUniversal = tagName === "*"; while (child) { while (child) { // IE 6-7 considers comment nodes as element nodes, and gives them the tagName "!". // We can filter them out by checking if its tagName is > "@". // This also avoids a superflous nodeType === 1 check. if (child.tagName > "@" && (isUniversal || child.tagName === tagName)) { nodes.push(child); } // We may need to traverse back up the tree to find more unvisited subtrees. visited.push(child); child = child.firstChild; } // Find the most recently visited node who has a next sibling. while (visited.length > 0 && !child) { child = visited.pop().nextSibling; } } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed Y.log('query: ' + query + ' contains unsupported token in: ' + selector, 'warn', 'Selector'); tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '3.18.1', {"requires": ["selector-native"]}); PK\B#3.18.1/dom-style/dom-style-debug.jsnu[YUI.add('dom-style', function (Y, NAME) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', DOCUMENT = Y.config.doc, Y_DOM = Y.DOM, TRANSFORM, TRANSFORMORIGIN, VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform', 'transform' ], re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} node The HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. * @param {Object} [style] The style node. Defaults to `node.style`. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} node The HTMLElement to get the style from. * @param {String} att The style property to get. * @param {Object} [style] The style node. Defaults to `node.style`. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node The HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} node The HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== undefined) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== undefined) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; if (TRANSFORM) { Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; } }, '3.18.1', {"requires": ["dom-base"]}); PK\ZZ!3.18.1/dom-style/dom-style-min.jsnu[YUI.add("dom-style",function(e,t){var n="documentElement",r="defaultView",i="ownerDocument",s="style",o="float",u="cssFloat",a="styleFloat",f="transparent",l="getComputedStyle",c="getBoundingClientRect",h=e.config.doc,p=e.DOM,d,v,m=["WebkitTransform","MozTransform","OTransform","msTransform","transform"],g=/width|height|top|left|right|bottom|margin|padding/i;e.Array.each(m,function(e){e in h[n].style&&(d=e,v=e+"Origin")}),e.mix(p,{DEFAULT_UNIT:"px",CUSTOM_STYLES:{},setStyle:function(e,t,n,r){r=r||e.style;var i=p.CUSTOM_STYLES;if(r){n===null||n===""?n="":!isNaN(Number(n))&&g.test(t)&&(n+=p.DEFAULT_UNIT);if(t in i){if(i[t].set){i[t].set(e,n,r);return}typeof i[t]=="string"&&(t=i[t])}else t===""&&(t="cssText",n="");r[t]=n}},getStyle:function(e,t,n){n=n||e.style;var r=p.CUSTOM_STYLES,i="";if(n){if(t in r){if(r[t].get)return r[t].get(e,t,n);typeof r[t]=="string"&&(t=r[t])}i=n[t],i===""&&(i=p[l](e,t))}return i},setStyles:function(t,n){var r=t.style;e.each(n,function(e,n){p.setStyle(t,n,e,r)},p)},getComputedStyle:function(e,t){var n="",o=e[i],u;return e[s]&&o[r]&&o[r][l]&&(u=o[r][l](e,null),u&&(n=u[t])),n}}),h[n][s][u]!==undefined?p.CUSTOM_STYLES[o]=u:h[n][s][a]!==undefined&&(p.CUSTOM_STYLES[o]=a),e.UA.webkit&&(p[l]=function(e,t){var n=e[i][r],s=n[l](e,"")[t];return s==="rgba(0, 0, 0, 0)"&&(s=f),s}),e.DOM._getAttrOffset=function(t,n){var r=e.DOM[l](t,n),i=t.offsetParent,s,o,u;return r==="auto"&&(s=e.DOM.getStyle(t,"position"),s==="static"||s==="relative"?r=0:i&&i[c]&&(o=i[c]()[n],u=t[c]()[n],n==="left"||n==="top"?r=u-o:r=o-t[c]()[n])),r},e.DOM._getOffset=function(e){var t,n=null;return e&&(t=p.getStyle(e,"position"),n=[parseInt(p[l](e,"left"),10),parseInt(p[l](e,"top"),10)],isNaN(n[0])&&(n[0]=parseInt(p.getStyle(e,"left"),10),isNaN(n[0])&&(n[0]=t==="relative"?0:e.offsetLeft||0)),isNaN(n[1])&&(n[1]=parseInt(p.getStyle(e,"top"),10),isNaN(n[1])&&(n[1]=t==="relative"?0:e.offsetTop||0))),n},d&&(p.CUSTOM_STYLES.transform={set:function(e,t,n){n[d]=t},get:function(e){return p[l](e,d)}},p.CUSTOM_STYLES.transformOrigin={set:function(e,t,n){n[v]=t},get:function(e){return p[l](e,v)}})},"3.18.1",{requires:["dom-base"]}); PK\B3.18.1/dom-style/dom-style.jsnu[YUI.add('dom-style', function (Y, NAME) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', DOCUMENT = Y.config.doc, Y_DOM = Y.DOM, TRANSFORM, TRANSFORMORIGIN, VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform', 'transform' ], re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} node The HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. * @param {Object} [style] The style node. Defaults to `node.style`. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} node The HTMLElement to get the style from. * @param {String} att The style property to get. * @param {Object} [style] The style node. Defaults to `node.style`. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node The HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} node The HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== undefined) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== undefined) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; if (TRANSFORM) { Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; } }, '3.18.1', {"requires": ["dom-base"]}); PK\ű+3.18.1/queue-promote/queue-promote-debug.jsnu[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); } } }); }, '3.18.1', {"requires": ["yui-base"]}); PK\ű%3.18.1/queue-promote/queue-promote.jsnu[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); } } }); }, '3.18.1', {"requires": ["yui-base"]}); PK\H,=599)3.18.1/queue-promote/queue-promote-min.jsnu[YUI.add("queue-promote",function(e,t){e.mix(e.Queue.prototype,{indexOf:function(t){return e.Array.indexOf(this._q,t)},promote:function(e){var t=this.indexOf(e);t>-1&&this._q.unshift(this._q.splice(t,1)[0])},remove:function(e){var t=this.indexOf(e);t>-1&&this._q.splice(t,1)}})},"3.18.1",{requires:["yui-base"]}); PK\ʃoMM'3.18.1/imageloader/imageloader-debug.jsnu[YUI.add('imageloader', function (Y, NAME) { /** * The ImageLoader Utility is a framework to dynamically load images according to certain triggers, * enabling faster load times and a more responsive UI. * * @module imageloader */ /** * A group for images. A group can have one time limit and a series of triggers. Thus the images belonging to this group must share these constraints. * @class ImgLoadGroup * @extends Base * @constructor */ Y.ImgLoadGroup = function() { // call init first, because it sets up local vars for storing attribute-related info this._init(); Y.ImgLoadGroup.superclass.constructor.apply(this, arguments); }; Y.ImgLoadGroup.NAME = 'imgLoadGroup'; Y.ImgLoadGroup.ATTRS = { /** * Name for the group. Only used to identify the group in logging statements. * @attribute name * @type String */ name: { value: '' }, /** * Time limit, in seconds, after which images are fetched regardless of trigger events. * @attribute timeLimit * @type Number */ timeLimit: { value: null }, /** * Distance below the fold for which images are loaded. Images are not loaded until they are at most this distance away from (or above) the fold. * This check is performed at page load (domready) and after any window scroll or window resize event (until all images are loaded). * @attribute foldDistance * @type Number */ foldDistance: { validator: Y.Lang.isNumber, setter: function(val) { this._setFoldTriggers(); return val; }, lazyAdd: false }, /** * Class name that will identify images belonging to the group. This class name will be removed from each element in order to fetch images. * This class should have, in its CSS style definition, "background:none !important;". * @attribute className * @type String */ className: { value: null, setter: function(name) { this._className = name; return name; }, lazyAdd: false }, /** * Determines how to act when className is used as the way to delay load images. The "default" action is to just * remove the class name. The "enhanced" action is to remove the class name and also set the src attribute if * the element is an img. * @attribute classNameAction * @type String */ classNameAction: { value: "default" } }; var groupProto = { /** * Initialize all private members needed for the group. * @method _init * @private */ _init: function() { /** * Collection of triggers for this group. * Keeps track of each trigger's event handle, as returned from Y.on. * @property _triggers * @private * @type Array */ this._triggers = []; /** * Collection of images (Y.ImgLoadImgObj objects) registered with this group, keyed by DOM id. * @property _imgObjs * @private * @type Object */ this._imgObjs = {}; /** * Timeout object to keep a handle on the time limit. * @property _timeout * @private * @type Object */ this._timeout = null; /** * DOM elements having the class name that is associated with this group. * Elements are stored during the _foldCheck function and reused later during any subsequent _foldCheck calls - gives a slight performance improvement when the page fold is repeatedly checked. * @property _classImageEls * @private * @type Array */ this._classImageEls = null; /** * Keep the CSS class name in a member variable for ease and speed. * @property _className * @private * @type String */ this._className = null; /** * Boolean tracking whether the window scroll and window resize triggers have been set if this is a fold group. * @property _areFoldTriggersSet * @private * @type Boolean */ this._areFoldTriggersSet = false; /** * The maximum pixel height of the document that has been made visible. * During fold checks, if the user scrolls up then there's no need to check for newly exposed images. * @property _maxKnownHLimit * @private * @type Int */ this._maxKnownHLimit = 0; // add a listener to domready that will start the time limit Y.on('domready', this._onloadTasks, this); }, /** * Adds a trigger to the group. Arguments are passed to Y.on. * @method addTrigger * @chainable * @param {Object} obj The DOM object to attach the trigger event to * @param {String} type The event type */ addTrigger: function(obj, type) { if (! obj || ! type) { return this; } Y.log('adding trigger to group: ' + this.get('name'), 'info', 'imageloader'); /* Need to wrap the fetch function. Event Util can't distinguish prototyped functions of different instantiations. * Leads to this scenario: groupA and groupZ both have window-scroll triggers. groupZ also has a 2-sec timeout (groupA has no timeout). * groupZ's timeout fires; we remove the triggers. The detach call finds the first window-scroll event with Y.ILG.p.fetch, which is groupA's. * groupA's trigger is removed and never fires, leaving images unfetched. */ var wrappedFetch = function() { this.fetch(); }; this._triggers.push( Y.on(type, wrappedFetch, obj, this) ); return this; }, /** * Adds a custom event trigger to the group. * @method addCustomTrigger * @chainable * @param {String} name The name of the event * @param {Object} obj The object on which to attach the event. obj is optional - by default the event is attached to the Y instance */ addCustomTrigger: function(name, obj) { if (! name) { return this; } Y.log('adding custom trigger to group: ' + this.get('name'), 'info', 'imageloader'); // see comment in addTrigger() var wrappedFetch = function() { this.fetch(); }; if (Y.Lang.isUndefined(obj)) { this._triggers.push( Y.on(name, wrappedFetch, this) ); } else { this._triggers.push( obj.on(name, wrappedFetch, this) ); } return this; }, /** * Sets the window scroll and window resize triggers for any group that is fold-conditional (i.e., has a fold distance set). * @method _setFoldTriggers * @private */ _setFoldTriggers: function() { if (this._areFoldTriggersSet) { return; } Y.log('setting window scroll and resize events for group: ' + this.get('name'), 'info', 'imageloader'); var wrappedFoldCheck = function() { this._foldCheck(); }; this._triggers.push( Y.on('scroll', wrappedFoldCheck, window, this) ); this._triggers.push( Y.on('resize', wrappedFoldCheck, window, this) ); this._areFoldTriggersSet = true; }, /** * Performs necessary setup at domready time. * Initiates time limit for group; executes the fold check for the images. * @method _onloadTasks * @private */ _onloadTasks: function() { var timeLim = this.get('timeLimit'); if (timeLim && timeLim > 0) { Y.log('setting time limit of ' + timeLim + ' seconds for group: ' + this.get('name'), 'info', 'imageloader'); this._timeout = setTimeout(this._getFetchTimeout(), timeLim * 1000); } if (! Y.Lang.isUndefined(this.get('foldDistance'))) { this._foldCheck(); } }, /** * Returns the group's fetch method, with the proper closure, for use with setTimeout. * @method _getFetchTimeout * @return {Function} group's fetch method * @private */ _getFetchTimeout: function() { var self = this; return function() { self.fetch(); }; }, /** * Registers an image with the group. * Arguments are passed through to a Y.ImgLoadImgObj constructor; see that class' attribute documentation for detailed information. "domId" is a required attribute. * @method registerImage * @param {Object} config A configuration object literal with attribute name/value pairs (passed through to a Y.ImgLoadImgObj constructor) * @return {Object} Y.ImgLoadImgObj that was registered */ registerImage: function() { var domId = arguments[0].domId; if (! domId) { return null; } Y.log('adding image with id: ' + domId + ' to group: ' + this.get('name'), 'info', 'imageloader'); this._imgObjs[domId] = new Y.ImgLoadImgObj(arguments[0]); return this._imgObjs[domId]; }, /** * Displays the images in the group. * This method is called when a trigger fires or the time limit expires; it shouldn't be called externally, but is not private in the rare event that it needs to be called immediately. * @method fetch */ fetch: function() { Y.log('Fetching images in group: "' + this.get('name') + '".', 'info', 'imageloader'); // done with the triggers this._clearTriggers(); // fetch whatever we need to by className this._fetchByClass(); // fetch registered images for (var id in this._imgObjs) { if (this._imgObjs.hasOwnProperty(id)) { this._imgObjs[id].fetch(); } } }, /** * Clears the timeout and all triggers associated with the group. * @method _clearTriggers * @private */ _clearTriggers: function() { clearTimeout(this._timeout); // detach all listeners for (var i=0, len = this._triggers.length; i < len; i++) { this._triggers[i].detach(); } }, /** * Checks the position of each image in the group. If any part of the image is within the specified distance (foldDistance) of the client viewport, the image is fetched immediately. * @method _foldCheck * @private */ _foldCheck: function() { Y.log('Checking for images above the fold in group: "' + this.get('name') + '"', 'info', 'imageloader'); var allFetched = true, viewReg = Y.DOM.viewportRegion(), hLimit = viewReg.bottom + this.get('foldDistance'), id, imgFetched, els, i, len; // unless we've uncovered new frontiers, there's no need to continue if (hLimit <= this._maxKnownHLimit) { return; } this._maxKnownHLimit = hLimit; for (id in this._imgObjs) { if (this._imgObjs.hasOwnProperty(id)) { imgFetched = this._imgObjs[id].fetch(hLimit); allFetched = allFetched && imgFetched; } } // and by class if (this._className) { if (this._classImageEls === null) { // get all the relevant elements and store them this._classImageEls = []; els = Y.all('.' + this._className); els.each( function(node) { this._classImageEls.push( { el: node, y: node.getY(), fetched: false } ); }, this); } els = this._classImageEls; for (i=0, len = els.length; i < len; i++) { if (els[i].fetched) { continue; } if (els[i].y && els[i].y <= hLimit) { //els[i].el.removeClass(this._className); this._updateNodeClassName(els[i].el); els[i].fetched = true; Y.log('Image with id "' + els[i].el.get('id') + '" is within distance of the fold. Fetching image. (Image registered by class name with the group - may not have an id.)', 'info', 'imageloader'); } else { allFetched = false; } } } // if allFetched, remove listeners if (allFetched) { Y.log('All images fetched; removing listeners for group: "' + this.get('name') + '"', 'info', 'imageloader'); this._clearTriggers(); } }, /** * Updates a given node, removing the ImageLoader class name. If the * node is an img and the classNameAction is "enhanced", then node * class name is removed and also the src attribute is set to the * image URL as well as clearing the style background image. * @method _updateNodeClassName * @param node {Node} The node to act on. * @private */ _updateNodeClassName: function(node){ var url; if (this.get("classNameAction") == "enhanced"){ if (node.get("tagName").toLowerCase() == "img"){ url = node.getStyle("backgroundImage"); /url\(["']?(.*?)["']?\)/.test(url); url = RegExp.$1; node.set("src", url); node.setStyle("backgroundImage", ""); } } node.removeClass(this._className); }, /** * Finds all elements in the DOM with the class name specified in the group. Removes the class from the element in order to let the style definitions trigger the image fetching. * @method _fetchByClass * @private */ _fetchByClass: function() { if (! this._className) { return; } Y.log('Fetching all images with class "' + this._className + '" in group "' + this.get('name') + '".', 'info', 'imageloader'); Y.all('.' + this._className).each(Y.bind(this._updateNodeClassName, this)); } }; Y.extend(Y.ImgLoadGroup, Y.Base, groupProto); //------------------------------------------------ /** * Image objects to be registered with the groups * @class ImgLoadImgObj * @extends Base * @constructor */ Y.ImgLoadImgObj = function() { Y.ImgLoadImgObj.superclass.constructor.apply(this, arguments); this._init(); }; Y.ImgLoadImgObj.NAME = 'imgLoadImgObj'; Y.ImgLoadImgObj.ATTRS = { /** * HTML DOM id of the image element. * @attribute domId * @type String */ domId: { value: null, writeOnce: true }, /** * Background URL for the image. * For an image whose URL is specified by "background-image" in the element's style. * @attribute bgUrl * @type String */ bgUrl: { value: null }, /** * Source URL for the image. * For an image whose URL is specified by a "src" attribute in the DOM element. * @attribute srcUrl * @type String */ srcUrl: { value: null }, /** * Pixel width of the image. Will be set as a width attribute on the DOM element after the image is fetched. * Defaults to the natural width of the image (no width attribute will be set). * Usually only used with src images. * @attribute width * @type Int */ width: { value: null }, /** * Pixel height of the image. Will be set as a height attribute on the DOM element after the image is fetched. * Defaults to the natural height of the image (no height attribute will be set). * Usually only used with src images. * @attribute height * @type Int */ height: { value: null }, /** * Whether the image's style.visibility should be set to visible after the image is fetched. * Used when setting images as visibility:hidden prior to image fetching. * @attribute setVisible * @type Boolean */ setVisible: { value: false }, /** * Whether the image is a PNG. * PNG images get special treatment in that the URL is specified through AlphaImageLoader for IE, versions 6 and earlier. * Only used with background images. * @attribute isPng * @type Boolean */ isPng: { value: false }, /** * AlphaImageLoader sizingMethod property to be set for the image. * Only set if isPng value for this image is set to true. * Defaults to scale. * @attribute sizingMethod * @type String */ sizingMethod: { value: 'scale' }, /** * AlphaImageLoader enabled property to be set for the image. * Only set if isPng value for this image is set to true. * Defaults to true. * @attribute enabled * @type String */ enabled: { value: 'true' } }; var imgProto = { /** * Initialize all private members needed for the group. * @method _init * @private */ _init: function() { /** * Whether this image has already been fetched. * In the case of fold-conditional groups, images won't be fetched twice. * @property _fetched * @private * @type Boolean */ this._fetched = false; /** * The Node object returned from Y.one, to avoid repeat calls to access the DOM. * @property _imgEl * @private * @type Object */ this._imgEl = null; /** * The vertical position returned from getY, to avoid repeat calls to access the DOM. * The Y position is checked only for images registered with fold-conditional groups. The position is checked first at page load (domready) * and this caching enhancement assumes that the image's vertical position won't change after that first check. * @property _yPos * @private * @type Int */ this._yPos = null; }, /** * Displays the image; puts the URL into the DOM. * This method shouldn't be called externally, but is not private in the rare event that it needs to be called immediately. * @method fetch * @param {Number} withinY The pixel distance from the top of the page, for which if the image lies within, it will be fetched. Undefined indicates that no check should be made, and the image should always be fetched * @return {Boolean} Whether the image has been fetched (either during this execution or previously) */ fetch: function(withinY) { if (this._fetched) { return true; } var el = this._getImgEl(), yPos; if (! el) { return false; } if (withinY) { // need a distance check yPos = this._getYPos(); if (! yPos || yPos > withinY) { return false; } Y.log('Image with id "' + this.get('domId') + '" is within distance of the fold. Fetching image.', 'info', 'imageloader'); } Y.log('Fetching image with id "' + this.get('domId') + '".', 'info', 'imageloader'); // apply url if (this.get('bgUrl') !== null) { // bg url if (this.get('isPng') && Y.UA.ie && Y.UA.ie <= 6) { // png for which to apply AlphaImageLoader el.setStyle('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + this.get('bgUrl') + '", sizingMethod="' + this.get('sizingMethod') + '", enabled="' + this.get('enabled') + '")'); } else { // regular bg image el.setStyle('backgroundImage', "url('" + this.get('bgUrl') + "')"); } } else if (this.get('srcUrl') !== null) { // regular src image el.setAttribute('src', this.get('srcUrl')); } // apply attributes if (this.get('setVisible')) { el.setStyle('visibility', 'visible'); } if (this.get('width')) { el.setAttribute('width', this.get('width')); } if (this.get('height')) { el.setAttribute('height', this.get('height')); } this._fetched = true; return true; }, /** * Gets the object (as a Y.Node) of the DOM element indicated by "domId". * @method _getImgEl * @return {Object} DOM element of the image as a Y.Node object * @private */ _getImgEl: function() { if (this._imgEl === null) { this._imgEl = Y.one('#' + this.get('domId')); } return this._imgEl; }, /** * Gets the Y position of the node in page coordinates. * Expects that the page-coordinate position of the image won't change. * @method _getYPos * @return {Object} The Y position of the image * @private */ _getYPos: function() { if (this._yPos === null) { this._yPos = this._getImgEl().getY(); } return this._yPos; } }; Y.extend(Y.ImgLoadImgObj, Y.Base, imgProto); }, '3.18.1', {"requires": ["base-base", "node-style", "node-screen"]}); PK\*GG!3.18.1/imageloader/imageloader.jsnu[YUI.add('imageloader', function (Y, NAME) { /** * The ImageLoader Utility is a framework to dynamically load images according to certain triggers, * enabling faster load times and a more responsive UI. * * @module imageloader */ /** * A group for images. A group can have one time limit and a series of triggers. Thus the images belonging to this group must share these constraints. * @class ImgLoadGroup * @extends Base * @constructor */ Y.ImgLoadGroup = function() { // call init first, because it sets up local vars for storing attribute-related info this._init(); Y.ImgLoadGroup.superclass.constructor.apply(this, arguments); }; Y.ImgLoadGroup.NAME = 'imgLoadGroup'; Y.ImgLoadGroup.ATTRS = { /** * Name for the group. Only used to identify the group in logging statements. * @attribute name * @type String */ name: { value: '' }, /** * Time limit, in seconds, after which images are fetched regardless of trigger events. * @attribute timeLimit * @type Number */ timeLimit: { value: null }, /** * Distance below the fold for which images are loaded. Images are not loaded until they are at most this distance away from (or above) the fold. * This check is performed at page load (domready) and after any window scroll or window resize event (until all images are loaded). * @attribute foldDistance * @type Number */ foldDistance: { validator: Y.Lang.isNumber, setter: function(val) { this._setFoldTriggers(); return val; }, lazyAdd: false }, /** * Class name that will identify images belonging to the group. This class name will be removed from each element in order to fetch images. * This class should have, in its CSS style definition, "background:none !important;". * @attribute className * @type String */ className: { value: null, setter: function(name) { this._className = name; return name; }, lazyAdd: false }, /** * Determines how to act when className is used as the way to delay load images. The "default" action is to just * remove the class name. The "enhanced" action is to remove the class name and also set the src attribute if * the element is an img. * @attribute classNameAction * @type String */ classNameAction: { value: "default" } }; var groupProto = { /** * Initialize all private members needed for the group. * @method _init * @private */ _init: function() { /** * Collection of triggers for this group. * Keeps track of each trigger's event handle, as returned from Y.on. * @property _triggers * @private * @type Array */ this._triggers = []; /** * Collection of images (Y.ImgLoadImgObj objects) registered with this group, keyed by DOM id. * @property _imgObjs * @private * @type Object */ this._imgObjs = {}; /** * Timeout object to keep a handle on the time limit. * @property _timeout * @private * @type Object */ this._timeout = null; /** * DOM elements having the class name that is associated with this group. * Elements are stored during the _foldCheck function and reused later during any subsequent _foldCheck calls - gives a slight performance improvement when the page fold is repeatedly checked. * @property _classImageEls * @private * @type Array */ this._classImageEls = null; /** * Keep the CSS class name in a member variable for ease and speed. * @property _className * @private * @type String */ this._className = null; /** * Boolean tracking whether the window scroll and window resize triggers have been set if this is a fold group. * @property _areFoldTriggersSet * @private * @type Boolean */ this._areFoldTriggersSet = false; /** * The maximum pixel height of the document that has been made visible. * During fold checks, if the user scrolls up then there's no need to check for newly exposed images. * @property _maxKnownHLimit * @private * @type Int */ this._maxKnownHLimit = 0; // add a listener to domready that will start the time limit Y.on('domready', this._onloadTasks, this); }, /** * Adds a trigger to the group. Arguments are passed to Y.on. * @method addTrigger * @chainable * @param {Object} obj The DOM object to attach the trigger event to * @param {String} type The event type */ addTrigger: function(obj, type) { if (! obj || ! type) { return this; } /* Need to wrap the fetch function. Event Util can't distinguish prototyped functions of different instantiations. * Leads to this scenario: groupA and groupZ both have window-scroll triggers. groupZ also has a 2-sec timeout (groupA has no timeout). * groupZ's timeout fires; we remove the triggers. The detach call finds the first window-scroll event with Y.ILG.p.fetch, which is groupA's. * groupA's trigger is removed and never fires, leaving images unfetched. */ var wrappedFetch = function() { this.fetch(); }; this._triggers.push( Y.on(type, wrappedFetch, obj, this) ); return this; }, /** * Adds a custom event trigger to the group. * @method addCustomTrigger * @chainable * @param {String} name The name of the event * @param {Object} obj The object on which to attach the event. obj is optional - by default the event is attached to the Y instance */ addCustomTrigger: function(name, obj) { if (! name) { return this; } // see comment in addTrigger() var wrappedFetch = function() { this.fetch(); }; if (Y.Lang.isUndefined(obj)) { this._triggers.push( Y.on(name, wrappedFetch, this) ); } else { this._triggers.push( obj.on(name, wrappedFetch, this) ); } return this; }, /** * Sets the window scroll and window resize triggers for any group that is fold-conditional (i.e., has a fold distance set). * @method _setFoldTriggers * @private */ _setFoldTriggers: function() { if (this._areFoldTriggersSet) { return; } var wrappedFoldCheck = function() { this._foldCheck(); }; this._triggers.push( Y.on('scroll', wrappedFoldCheck, window, this) ); this._triggers.push( Y.on('resize', wrappedFoldCheck, window, this) ); this._areFoldTriggersSet = true; }, /** * Performs necessary setup at domready time. * Initiates time limit for group; executes the fold check for the images. * @method _onloadTasks * @private */ _onloadTasks: function() { var timeLim = this.get('timeLimit'); if (timeLim && timeLim > 0) { this._timeout = setTimeout(this._getFetchTimeout(), timeLim * 1000); } if (! Y.Lang.isUndefined(this.get('foldDistance'))) { this._foldCheck(); } }, /** * Returns the group's fetch method, with the proper closure, for use with setTimeout. * @method _getFetchTimeout * @return {Function} group's fetch method * @private */ _getFetchTimeout: function() { var self = this; return function() { self.fetch(); }; }, /** * Registers an image with the group. * Arguments are passed through to a Y.ImgLoadImgObj constructor; see that class' attribute documentation for detailed information. "domId" is a required attribute. * @method registerImage * @param {Object} config A configuration object literal with attribute name/value pairs (passed through to a Y.ImgLoadImgObj constructor) * @return {Object} Y.ImgLoadImgObj that was registered */ registerImage: function() { var domId = arguments[0].domId; if (! domId) { return null; } this._imgObjs[domId] = new Y.ImgLoadImgObj(arguments[0]); return this._imgObjs[domId]; }, /** * Displays the images in the group. * This method is called when a trigger fires or the time limit expires; it shouldn't be called externally, but is not private in the rare event that it needs to be called immediately. * @method fetch */ fetch: function() { // done with the triggers this._clearTriggers(); // fetch whatever we need to by className this._fetchByClass(); // fetch registered images for (var id in this._imgObjs) { if (this._imgObjs.hasOwnProperty(id)) { this._imgObjs[id].fetch(); } } }, /** * Clears the timeout and all triggers associated with the group. * @method _clearTriggers * @private */ _clearTriggers: function() { clearTimeout(this._timeout); // detach all listeners for (var i=0, len = this._triggers.length; i < len; i++) { this._triggers[i].detach(); } }, /** * Checks the position of each image in the group. If any part of the image is within the specified distance (foldDistance) of the client viewport, the image is fetched immediately. * @method _foldCheck * @private */ _foldCheck: function() { var allFetched = true, viewReg = Y.DOM.viewportRegion(), hLimit = viewReg.bottom + this.get('foldDistance'), id, imgFetched, els, i, len; // unless we've uncovered new frontiers, there's no need to continue if (hLimit <= this._maxKnownHLimit) { return; } this._maxKnownHLimit = hLimit; for (id in this._imgObjs) { if (this._imgObjs.hasOwnProperty(id)) { imgFetched = this._imgObjs[id].fetch(hLimit); allFetched = allFetched && imgFetched; } } // and by class if (this._className) { if (this._classImageEls === null) { // get all the relevant elements and store them this._classImageEls = []; els = Y.all('.' + this._className); els.each( function(node) { this._classImageEls.push( { el: node, y: node.getY(), fetched: false } ); }, this); } els = this._classImageEls; for (i=0, len = els.length; i < len; i++) { if (els[i].fetched) { continue; } if (els[i].y && els[i].y <= hLimit) { //els[i].el.removeClass(this._className); this._updateNodeClassName(els[i].el); els[i].fetched = true; } else { allFetched = false; } } } // if allFetched, remove listeners if (allFetched) { this._clearTriggers(); } }, /** * Updates a given node, removing the ImageLoader class name. If the * node is an img and the classNameAction is "enhanced", then node * class name is removed and also the src attribute is set to the * image URL as well as clearing the style background image. * @method _updateNodeClassName * @param node {Node} The node to act on. * @private */ _updateNodeClassName: function(node){ var url; if (this.get("classNameAction") == "enhanced"){ if (node.get("tagName").toLowerCase() == "img"){ url = node.getStyle("backgroundImage"); /url\(["']?(.*?)["']?\)/.test(url); url = RegExp.$1; node.set("src", url); node.setStyle("backgroundImage", ""); } } node.removeClass(this._className); }, /** * Finds all elements in the DOM with the class name specified in the group. Removes the class from the element in order to let the style definitions trigger the image fetching. * @method _fetchByClass * @private */ _fetchByClass: function() { if (! this._className) { return; } Y.all('.' + this._className).each(Y.bind(this._updateNodeClassName, this)); } }; Y.extend(Y.ImgLoadGroup, Y.Base, groupProto); //------------------------------------------------ /** * Image objects to be registered with the groups * @class ImgLoadImgObj * @extends Base * @constructor */ Y.ImgLoadImgObj = function() { Y.ImgLoadImgObj.superclass.constructor.apply(this, arguments); this._init(); }; Y.ImgLoadImgObj.NAME = 'imgLoadImgObj'; Y.ImgLoadImgObj.ATTRS = { /** * HTML DOM id of the image element. * @attribute domId * @type String */ domId: { value: null, writeOnce: true }, /** * Background URL for the image. * For an image whose URL is specified by "background-image" in the element's style. * @attribute bgUrl * @type String */ bgUrl: { value: null }, /** * Source URL for the image. * For an image whose URL is specified by a "src" attribute in the DOM element. * @attribute srcUrl * @type String */ srcUrl: { value: null }, /** * Pixel width of the image. Will be set as a width attribute on the DOM element after the image is fetched. * Defaults to the natural width of the image (no width attribute will be set). * Usually only used with src images. * @attribute width * @type Int */ width: { value: null }, /** * Pixel height of the image. Will be set as a height attribute on the DOM element after the image is fetched. * Defaults to the natural height of the image (no height attribute will be set). * Usually only used with src images. * @attribute height * @type Int */ height: { value: null }, /** * Whether the image's style.visibility should be set to visible after the image is fetched. * Used when setting images as visibility:hidden prior to image fetching. * @attribute setVisible * @type Boolean */ setVisible: { value: false }, /** * Whether the image is a PNG. * PNG images get special treatment in that the URL is specified through AlphaImageLoader for IE, versions 6 and earlier. * Only used with background images. * @attribute isPng * @type Boolean */ isPng: { value: false }, /** * AlphaImageLoader sizingMethod property to be set for the image. * Only set if isPng value for this image is set to true. * Defaults to scale. * @attribute sizingMethod * @type String */ sizingMethod: { value: 'scale' }, /** * AlphaImageLoader enabled property to be set for the image. * Only set if isPng value for this image is set to true. * Defaults to true. * @attribute enabled * @type String */ enabled: { value: 'true' } }; var imgProto = { /** * Initialize all private members needed for the group. * @method _init * @private */ _init: function() { /** * Whether this image has already been fetched. * In the case of fold-conditional groups, images won't be fetched twice. * @property _fetched * @private * @type Boolean */ this._fetched = false; /** * The Node object returned from Y.one, to avoid repeat calls to access the DOM. * @property _imgEl * @private * @type Object */ this._imgEl = null; /** * The vertical position returned from getY, to avoid repeat calls to access the DOM. * The Y position is checked only for images registered with fold-conditional groups. The position is checked first at page load (domready) * and this caching enhancement assumes that the image's vertical position won't change after that first check. * @property _yPos * @private * @type Int */ this._yPos = null; }, /** * Displays the image; puts the URL into the DOM. * This method shouldn't be called externally, but is not private in the rare event that it needs to be called immediately. * @method fetch * @param {Number} withinY The pixel distance from the top of the page, for which if the image lies within, it will be fetched. Undefined indicates that no check should be made, and the image should always be fetched * @return {Boolean} Whether the image has been fetched (either during this execution or previously) */ fetch: function(withinY) { if (this._fetched) { return true; } var el = this._getImgEl(), yPos; if (! el) { return false; } if (withinY) { // need a distance check yPos = this._getYPos(); if (! yPos || yPos > withinY) { return false; } } // apply url if (this.get('bgUrl') !== null) { // bg url if (this.get('isPng') && Y.UA.ie && Y.UA.ie <= 6) { // png for which to apply AlphaImageLoader el.setStyle('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + this.get('bgUrl') + '", sizingMethod="' + this.get('sizingMethod') + '", enabled="' + this.get('enabled') + '")'); } else { // regular bg image el.setStyle('backgroundImage', "url('" + this.get('bgUrl') + "')"); } } else if (this.get('srcUrl') !== null) { // regular src image el.setAttribute('src', this.get('srcUrl')); } // apply attributes if (this.get('setVisible')) { el.setStyle('visibility', 'visible'); } if (this.get('width')) { el.setAttribute('width', this.get('width')); } if (this.get('height')) { el.setAttribute('height', this.get('height')); } this._fetched = true; return true; }, /** * Gets the object (as a Y.Node) of the DOM element indicated by "domId". * @method _getImgEl * @return {Object} DOM element of the image as a Y.Node object * @private */ _getImgEl: function() { if (this._imgEl === null) { this._imgEl = Y.one('#' + this.get('domId')); } return this._imgEl; }, /** * Gets the Y position of the node in page coordinates. * Expects that the page-coordinate position of the image won't change. * @method _getYPos * @return {Object} The Y position of the image * @private */ _getYPos: function() { if (this._yPos === null) { this._yPos = this._getImgEl().getY(); } return this._yPos; } }; Y.extend(Y.ImgLoadImgObj, Y.Base, imgProto); }, '3.18.1', {"requires": ["base-base", "node-style", "node-screen"]}); PK\:?&%3.18.1/imageloader/imageloader-min.jsnu[YUI.add("imageloader",function(e,t){e.ImgLoadGroup=function(){this._init(),e.ImgLoadGroup.superclass.constructor.apply(this,arguments)},e.ImgLoadGroup.NAME="imgLoadGroup",e.ImgLoadGroup.ATTRS={name:{value:""},timeLimit:{value:null},foldDistance:{validator:e.Lang.isNumber,setter:function(e){return this._setFoldTriggers(),e},lazyAdd:!1},className:{value:null,setter:function(e){return this._className=e,e},lazyAdd:!1},classNameAction:{value:"default"}};var n={_init:function(){this._triggers=[],this._imgObjs={},this._timeout=null,this._classImageEls=null,this._className=null,this._areFoldTriggersSet=!1,this._maxKnownHLimit=0,e.on("domready",this._onloadTasks,this)},addTrigger:function(t,n){if(!t||!n)return this;var r=function(){this.fetch()};return this._triggers.push(e.on(n,r,t,this)),this},addCustomTrigger:function(t,n){if(!t)return this;var r=function(){this.fetch()};return e.Lang.isUndefined(n)?this._triggers.push(e.on(t,r,this)):this._triggers.push(n.on(t,r,this)),this},_setFoldTriggers:function(){if(this._areFoldTriggersSet)return;var t=function(){this._foldCheck()};this._triggers.push(e.on("scroll",t,window,this)),this._triggers.push(e.on("resize",t,window,this)),this._areFoldTriggersSet=!0},_onloadTasks:function(){var t=this.get("timeLimit");t&&t>0&&(this._timeout=setTimeout(this._getFetchTimeout(),t*1e3)),e.Lang.isUndefined(this.get("foldDistance"))||this._foldCheck()},_getFetchTimeout:function(){var e=this;return function(){e.fetch()}},registerImage:function(){var t=arguments[0].domId;return t?(this._imgObjs[t]=new e.ImgLoadImgObj(arguments[0]),this._imgObjs[t]):null},fetch:function(){this._clearTriggers(),this._fetchByClass();for(var e in this._imgObjs)this._imgObjs.hasOwnProperty(e)&&this._imgObjs[e].fetch()},_clearTriggers:function(){clearTimeout(this._timeout);for(var e=0,t=this._triggers.length;et)return!1}return this.get("bgUrl")!==null?this.get("isPng")&&e.UA.ie&&e.UA.ie<=6?n.setStyle("filter",'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+this.get("bgUrl")+'", sizingMethod="'+this.get("sizingMethod")+'", enabled="'+this.get("enabled")+'")'):n.setStyle("backgroundImage","url('"+this.get("bgUrl")+"')"):this.get("srcUrl")!==null&&n.setAttribute("src",this.get("srcUrl")),this.get("setVisible")&&n.setStyle("visibility","visible"),this.get("width")&&n.setAttribute("width",this.get("width")),this.get("height")&&n.setAttribute("height",this.get("height")),this._fetched=!0,!0},_getImgEl:function(){return this._imgEl===null&&(this._imgEl=e.one("#"+this.get("domId"))),this._imgEl},_getYPos:function(){return this._yPos===null&&(this._yPos=this._getImgEl().getY()),this._yPos}};e.extend(e.ImgLoadImgObj,e.Base,r)},"3.18.1",{requires:["base-base","node-style","node-screen"]}); PK\DLL'3.18.1/recordset-base/recordset-base.jsnu[YUI.add('recordset-base', function (Y, NAME) { /** * Provides a wrapper around a standard javascript object. Can be inserted into a Recordset instance. * * @class Record */ var Record = Y.Base.create('record', Y.Base, [], { _setId: function() { return Y.guid(); }, initializer: function() { }, destructor: function() { }, /** * Retrieve a particular (or all) values from the object * * @param field {string} (optional) The key to retrieve the value from. If not supplied, the entire object is returned. * @method getValue * @public */ getValue: function(field) { if (field === undefined) { return this.get("data"); } else { return this.get("data")[field]; } return null; } }, { ATTRS: { /** * @description Unique ID of the record instance * @attribute id * @type string */ id: { valueFn: "_setId" }, /** * @description The object stored within the record instance * @attribute data * @type object */ data: { value: null } } }); Y.Record = Record; /** The Recordset utility provides a standard way for dealing with a collection of similar objects. @module recordset @main recordset @submodule recordset-base **/ var ArrayList = Y.ArrayList, Lang = Y.Lang, /** The Recordset utility provides a standard way for dealing with a collection of similar objects. Provides the base Recordset implementation, which can be extended to add additional functionality, such as custom indexing. sorting, and filtering. @class Recordset @extends Base @uses ArrayList @param config {Object} Configuration object with initial attribute values @constructor **/ Recordset = Y.Base.create('recordset', Y.Base, [], { /** * Publish default functions for events. Create the initial hash table. * * @method initializer * @protected */ initializer: function() { // The reason the conditional is needed is because of two scenarios: // 1. Instantiating new Y.Recordset() will not go into the setter of "records", and so it is necessary to create this._items in the initializer. // 2. Instantiating new Y.Recordset({records: [{...}]}) will call the setter of "records" and create this._items. In this case, we don't want that to be overwritten by []. if (!this._items) { this._items = []; } //set up event listener to fire events when recordset is modified in anyway this.publish({ /** *

At least one record is being added. Additional properties of * the event are:

*
*
added
*
Array of new records to be added
*
index
*
The insertion index in the Recordset's internal * array
*
* *

Preventing this event will cause the new records NOT to be * added to the Recordset's internal collection.

* * @event add * @preventable _defAddFn */ add: { defaultFn: this._defAddFn }, /** *

At least one record is being removed. Additional properties of * the event are:

*
*
removed
*
Array of records to be removed
*
range
*
Number of records to be removed
*
index
*
The starting index in the Recordset's internal * array from which to remove records
*
* *

Preventing this event will cause the records NOT to be * removed from the Recordset's internal collection.

* * @event remove * @preventable _defRemoveFn */ remove: { defaultFn: this._defRemoveFn }, /** * The Recordset is being flushed of all records. * * @event empty * @preventable _defEmptyFn */ empty: { defaultFn: this._defEmptyFn }, /** *

At least one record is being updated. Additional properties of * the event are:

*
*
updated
*
Array of records with updated values
*
overwritten
*
Array of current records that will be replaced
*
index
*
The starting index in the Recordset's internal * array from which to update will apply
*
* *

Preventing this event will cause the records NOT to be * updated in the Recordset's internal collection.

* * @event update * @preventable _defUpdateFn */ update: { defaultFn: this._defUpdateFn } }); this._buildHashTable(this.get('key')); this.after([ 'recordsChange', 'add', 'remove', 'update', 'empty'], this._updateHash); }, /** * Returns the record with particular ID or index * * @method getRecord * @param i {String, Number} The ID of the record if a string, or the index if a number. * @return {Record} A Y.Record instance */ getRecord: function(i) { if (Lang.isString(i)) { return this.get('table')[i]; } else if (Lang.isNumber(i)) { return this._items[i]; } return null; }, /** * Returns the record at a particular index * * @method getRecordByIndex * @param i {Number} Index at which the required record resides * @return {Record} A Y.Record instance */ getRecordByIndex: function(i) { return this._items[i]; }, /** * Returns a range of records beginning at particular index * * @method getRecordsByIndex * @param index {Number} Index at which the required record resides * @param range {Number} (Optional) Number of records to retrieve. The default is 1 * @return {Array} An array of Y.Record instances */ getRecordsByIndex: function(index, range) { var i = 0, returnedRecords = []; //Range cannot take on negative values range = (Lang.isNumber(range) && (range > 0)) ? range: 1; for (; i < range; i++) { returnedRecords.push(this._items[index + i]); } return returnedRecords; }, /** * Returns the length of the recordset * * @method getLength * @return {Number} Number of records in the recordset */ getLength: function() { return this.size(); }, /** Gets an array of values for a data _key_ in the set's records. If no _key_ is supplied, the returned array will contain the full data object for each record. @method getValuesByKey @param {String} [key] Data property to get from all records @return {Array} An array of values for the given _key_ if supplied. Otherwise, an array of each record's data hash. **/ getValuesByKey: function(key) { var i = 0, len = this._items.length, retVals = []; for (; i < len; i++) { retVals.push(this._items[i].getValue(key)); } return retVals; }, /** * Adds one or more Records to the RecordSet at the given index. If index is null, then adds the Records to the end of the RecordSet. * * @method add * @param {Record|Object|Array} oData A Y.Record instance, An object literal of data or an array of object literals * @param [index] {Number} [index] Index at which to add the record(s) * @return {Recordset} The updated recordset instance */ add: function(oData, index) { var newRecords = [], idx, i = 0; idx = (Lang.isNumber(index) && (index > -1)) ? index: this._items.length; //Passing in array of object literals for oData if (Lang.isArray(oData)) { for (; i < oData.length; i++) { newRecords[i] = this._changeToRecord(oData[i]); } } else if (Lang.isObject(oData)) { newRecords[0] = this._changeToRecord(oData); } this.fire('add', { added: newRecords, index: idx }); return this; }, /** Removes one or more Records to the RecordSet at the given index. If index is null, then removes a single Record from the end of the RecordSet. @method remove @param {Number} [index] Index at which to remove the record(s) from @param {Number} [range] Number of records to remove (including the one at the index) @return {Recordset} The updated recordset instance **/ remove: function(index, range) { var remRecords = []; //Default is to only remove the last record - the length is always 1 greater than the last index index = (index > -1) ? index: (this._items.length - 1); range = (range > 0) ? range: 1; remRecords = this._items.slice(index, (index + range)); this.fire('remove', { removed: remRecords, range: range, index: index }); //this._recordRemoved(remRecords, index); //return ({data: remRecords, index:index}); return this; }, /** * Empties the recordset * * @method empty * @return {Recordset} The updated recordset instance */ empty: function() { this.fire('empty', {}); return this; }, /** Updates the recordset with the new records passed in. Overwrites existing records when updating the index with the new records. @method update @param {Record|Object|Array} data A Y.Record instance, An object literal of data or an array of object literals @param {Number} [index] The index to start updating from. @return {Recordset} The updated recordset instance **/ update: function(data, index) { var rec, arr, i = 0; // Whatever is passed in, we are changing it to an array so that it can // be easily iterated in the _defUpdateFn method arr = (!(Lang.isArray(data))) ? [data] : data; rec = this._items.slice(index, index + arr.length); for (; i < arr.length; i++) { arr[i] = this._changeToRecord(arr[i]); } this.fire('update', { updated: arr, overwritten: rec, index: index }); return this; }, /** * Default behavior for the "add" event. Adds Record instances starting from * the index specified in `e.index`. * * @method _defAddFn * @param {EventFacade} e The add event * @private */ _defAddFn: function(e) { this._items.splice.apply(this._items, [e.index, 0].concat(e.added)); }, /** * Default behavior for the "remove" event. Removes Records from the * internal array starting from `e.index`. By default, it will remove one * Record. But if `e.range` is set, it will remove that many Records. * * @method _defRemoveFn * @param {EventFacade} e The remove event * @private */ _defRemoveFn: function(e) { this._items.splice(e.index, e.range || 1); }, /** * Default behavior for the "update" event. Sets Record instances for each * item in `e.updated` at indexes starting from `e.index`. * * @method _defUpdateFn * @param {EventFacade} e The update event * @private */ _defUpdateFn: function(e) { for (var i = 0; i < e.updated.length; i++) { this._items[e.index + i] = this._changeToRecord(e.updated[i]); } }, /** * Default behavior for the "empty" event. Clears the internal array of * Records. * * @method _defEmptyFn * @param {EventFacade} e The empty event * @private */ _defEmptyFn: function(e) { this._items = []; }, /** Updates the internal hash table. @method _defUpdateHash @param {EventFacade} e Event triggering the hash table update @private **/ _updateHash: function (e) { var handler = "_hash", type = e.type.replace(/.*:/,''), newHash; // _hashAdd, _hashRemove, _hashEmpty, etc // Not a switch or else if setup to allow for external expansion. handler += type.charAt(0).toUpperCase() + type.slice(1); newHash = this[handler] && this[handler](this.get('table'), this.get('key'), e); if (newHash) { this.set('table', newHash); } }, /** Regenerates the hash table from the current internal array of Records. @method _hashRecordsChange @param {Object} hash The hash map before replacement @param {String} key The key by which to add items to the hash @param {Object} e The event or object containing the items to be added. Items are expected to be stored in an array assigned to the `added` property. @return {Object} The updated hash map @private **/ _hashRecordsChange: function (hash, key, e) { return this._buildHashTable(key); }, /** Builds a hash table from the current internal array of Records. @method _buildHashTable @param {String} key The Record key to hash the items by @return {Object} A new hash map of Records keyed by each Records' key @private **/ _buildHashTable: function (key) { return this._hashAdd({}, key, { added: this._items }); }, /** Adds items to the hash table. Items are the values, and the keys are the values of the item's attribute named in the `key` parameter. @method _hashAdd @param {Object} hash The hash map before adding items @param {String} key The key by which to add the items to the hash @param {Object} e The event or object containing the items to be added. Items are expected to be stored in an array assigned to the `added` property. @return {Object} The updated hash map @private **/ _hashAdd: function(hash, key, e) { var items = e.added, i, len; for (i = 0, len = e.added.length; i < len; ++i) { hash[items[i].get(key)] = items[i]; } return hash; }, /** Removes items from the hash table. @method _hashRemove @param {Object} hash The hash map before removing items @param {String} key The key by which to remove the items from the hash @param {Object} e The event or object containing the items to be removed. Items are expected to be stored in an array assigned to the `removed` property. @return {Object} The updated hash map @private **/ _hashRemove: function(hash, key, e) { for (var i = e.removed.length - 1; i >= 0; --i) { delete hash[e.removed[i].get(key)]; } return hash; }, /** Updates items in the hash table. @method _hashUpdate @param {Object} hash The hash map before updating items @param {String} key The key by which to update the items to the hash @param {Object} e The event or object containing the items to be updated. Items are expected to be stored in an array assigned to the `updated` property. Optionally, items can be identified for being overwritten by including them in an array assigned to the `overwritten` property. @return {Object} The updated hash map @private **/ _hashUpdate: function (hash, key, e) { if (e.overwritten && e.overwritten.length) { hash = this._hashRemove(hash, key, { removed: e.overwritten }); } return this._hashAdd(hash, key, { added: e.updated }); }, /** Clears the hash table. @method _hashEmpty @param {Object} hash The hash map before adding items @param {String} key The key by which to remove the items from the hash @param {Object} e The event or object containing the items to be removed. Items are expected to be stored in an array assigned to the `removed` property. @return {Object} An empty hash @private **/ _hashEmpty: function() { return {}; }, /** * Sets up the hashtable with all the records currently in the recordset * * @method _initHashTable * @private */ _initHashTable: function() { return this._hashAdd({}, this.get('key'), { added: this._items || [] }); }, /** * Helper method - it takes an object bag and converts it to a Y.Record * * @method _changeToRecord * @param obj {Object|Record} Any objet literal or Y.Record instance * @return {Record} A Record instance. * @private */ _changeToRecord: function(obj) { return (obj instanceof Y.Record) ? obj : new Y.Record({ data: obj }); }, /** Ensures the value being set is an array of Record instances. If array items are raw object data, they are turned into Records. @method _setRecords @param {Record[]|Object[]} items The Records or data Objects to store as Records. @return {Record[]} **/ _setRecords: function (items) { if (!Y.Lang.isArray(items)) { return Y.Attribute.INVALID_VALUE; } var records = [], i, len; // FIXME: This should use the flyweight pattern if possible for (i = 0, len = items.length; i < len; ++i) { records[i] = this._changeToRecord(items[i]); } return (this._items = records); } }, { ATTRS: { /** * An array of Records that the Recordset is storing. Passing an array * of raw record data is also accepted. The data for each item will be * wrapped in a Record instance. * * @attribute records * @type {Record[]} */ records: { // TODO: necessary? valueFn? lazyAdd: false, getter: function() { // give them a copy, not the internal object return Y.Array(this._items); }, setter: "_setRecords" }, /** A hash table where the ID of the record is the key, and the record instance is the value. @attribute table @type object **/ table: { valueFn: '_initHashTable' }, /** The ID to use as the key in the hash table. @attribute key @type string **/ key: { value: 'id', readOnly: true } } }); Y.augment(Recordset, ArrayList); Y.Recordset = Recordset; }, '3.18.1', {"requires": ["base", "arraylist"]}); PK\HO[ [ +3.18.1/recordset-base/recordset-base-min.jsnu[YUI.add("recordset-base",function(e,t){var n=e.Base.create("record",e.Base,[],{_setId:function(){return e.guid()},initializer:function(){},destructor:function(){},getValue:function(e){return e===undefined?this.get("data"):this.get("data")[e]}},{ATTRS:{id:{valueFn:"_setId"},data:{value:null}}});e.Record=n;var r=e.ArrayList,i=e.Lang,s=e.Base.create("recordset",e.Base,[],{initializer:function(){this._items||(this._items=[]),this.publish({add:{defaultFn:this._defAddFn},remove:{defaultFn:this._defRemoveFn},empty:{defaultFn:this._defEmptyFn},update:{defaultFn:this._defUpdateFn}}),this._buildHashTable(this.get("key")),this.after(["recordsChange","add","remove","update","empty"],this._updateHash)},getRecord:function(e){return i.isString(e)?this.get("table")[e]:i.isNumber(e)?this._items[e]:null},getRecordByIndex:function(e){return this._items[e]},getRecordsByIndex:function(e,t){var n=0,r=[];t=i.isNumber(t)&&t>0?t:1;for(;n-1?t:this._items.length;if(i.isArray(e))for(;s-1?e:this._items.length-1,t=t>0?t:1,n=this._items.slice(e,e+t),this.fire("remove",{removed:n,range:t,index:e}),this},empty:function(){return this.fire("empty",{}),this},update:function(e,t){var n,r,s=0;r=i.isArray(e)?e:[e],n=this._items.slice(t,t+r.length);for(;s=0;--r)delete e[n.removed[r].get(t)];return e},_hashUpdate:function(e,t,n){return n.overwritten&&n.overwritten.length&&(e=this._hashRemove(e,t,{removed:n.overwritten})),this._hashAdd(e,t,{added:n.updated})},_hashEmpty:function(){return{}},_initHashTable:function(){return this._hashAdd({},this.get("key"),{added:this._items||[]})},_changeToRecord:function(t){return t instanceof e.Record?t:new e.Record({data:t})},_setRecords:function(t){if(!e.Lang.isArray(t))return e.Attribute.INVALID_VALUE;var n=[],r,i;for(r=0,i=t.length;rAt least one record is being added. Additional properties of * the event are:

*
*
added
*
Array of new records to be added
*
index
*
The insertion index in the Recordset's internal * array
*
* *

Preventing this event will cause the new records NOT to be * added to the Recordset's internal collection.

* * @event add * @preventable _defAddFn */ add: { defaultFn: this._defAddFn }, /** *

At least one record is being removed. Additional properties of * the event are:

*
*
removed
*
Array of records to be removed
*
range
*
Number of records to be removed
*
index
*
The starting index in the Recordset's internal * array from which to remove records
*
* *

Preventing this event will cause the records NOT to be * removed from the Recordset's internal collection.

* * @event remove * @preventable _defRemoveFn */ remove: { defaultFn: this._defRemoveFn }, /** * The Recordset is being flushed of all records. * * @event empty * @preventable _defEmptyFn */ empty: { defaultFn: this._defEmptyFn }, /** *

At least one record is being updated. Additional properties of * the event are:

*
*
updated
*
Array of records with updated values
*
overwritten
*
Array of current records that will be replaced
*
index
*
The starting index in the Recordset's internal * array from which to update will apply
*
* *

Preventing this event will cause the records NOT to be * updated in the Recordset's internal collection.

* * @event update * @preventable _defUpdateFn */ update: { defaultFn: this._defUpdateFn } }); this._buildHashTable(this.get('key')); this.after([ 'recordsChange', 'add', 'remove', 'update', 'empty'], this._updateHash); }, /** * Returns the record with particular ID or index * * @method getRecord * @param i {String, Number} The ID of the record if a string, or the index if a number. * @return {Record} A Y.Record instance */ getRecord: function(i) { if (Lang.isString(i)) { return this.get('table')[i]; } else if (Lang.isNumber(i)) { return this._items[i]; } return null; }, /** * Returns the record at a particular index * * @method getRecordByIndex * @param i {Number} Index at which the required record resides * @return {Record} A Y.Record instance */ getRecordByIndex: function(i) { return this._items[i]; }, /** * Returns a range of records beginning at particular index * * @method getRecordsByIndex * @param index {Number} Index at which the required record resides * @param range {Number} (Optional) Number of records to retrieve. The default is 1 * @return {Array} An array of Y.Record instances */ getRecordsByIndex: function(index, range) { var i = 0, returnedRecords = []; //Range cannot take on negative values range = (Lang.isNumber(range) && (range > 0)) ? range: 1; for (; i < range; i++) { returnedRecords.push(this._items[index + i]); } return returnedRecords; }, /** * Returns the length of the recordset * * @method getLength * @return {Number} Number of records in the recordset */ getLength: function() { return this.size(); }, /** Gets an array of values for a data _key_ in the set's records. If no _key_ is supplied, the returned array will contain the full data object for each record. @method getValuesByKey @param {String} [key] Data property to get from all records @return {Array} An array of values for the given _key_ if supplied. Otherwise, an array of each record's data hash. **/ getValuesByKey: function(key) { var i = 0, len = this._items.length, retVals = []; for (; i < len; i++) { retVals.push(this._items[i].getValue(key)); } return retVals; }, /** * Adds one or more Records to the RecordSet at the given index. If index is null, then adds the Records to the end of the RecordSet. * * @method add * @param {Record|Object|Array} oData A Y.Record instance, An object literal of data or an array of object literals * @param [index] {Number} [index] Index at which to add the record(s) * @return {Recordset} The updated recordset instance */ add: function(oData, index) { var newRecords = [], idx, i = 0; idx = (Lang.isNumber(index) && (index > -1)) ? index: this._items.length; //Passing in array of object literals for oData if (Lang.isArray(oData)) { for (; i < oData.length; i++) { newRecords[i] = this._changeToRecord(oData[i]); } } else if (Lang.isObject(oData)) { newRecords[0] = this._changeToRecord(oData); } this.fire('add', { added: newRecords, index: idx }); return this; }, /** Removes one or more Records to the RecordSet at the given index. If index is null, then removes a single Record from the end of the RecordSet. @method remove @param {Number} [index] Index at which to remove the record(s) from @param {Number} [range] Number of records to remove (including the one at the index) @return {Recordset} The updated recordset instance **/ remove: function(index, range) { var remRecords = []; //Default is to only remove the last record - the length is always 1 greater than the last index index = (index > -1) ? index: (this._items.length - 1); range = (range > 0) ? range: 1; remRecords = this._items.slice(index, (index + range)); this.fire('remove', { removed: remRecords, range: range, index: index }); //this._recordRemoved(remRecords, index); //return ({data: remRecords, index:index}); return this; }, /** * Empties the recordset * * @method empty * @return {Recordset} The updated recordset instance */ empty: function() { this.fire('empty', {}); return this; }, /** Updates the recordset with the new records passed in. Overwrites existing records when updating the index with the new records. @method update @param {Record|Object|Array} data A Y.Record instance, An object literal of data or an array of object literals @param {Number} [index] The index to start updating from. @return {Recordset} The updated recordset instance **/ update: function(data, index) { var rec, arr, i = 0; // Whatever is passed in, we are changing it to an array so that it can // be easily iterated in the _defUpdateFn method arr = (!(Lang.isArray(data))) ? [data] : data; rec = this._items.slice(index, index + arr.length); for (; i < arr.length; i++) { arr[i] = this._changeToRecord(arr[i]); } this.fire('update', { updated: arr, overwritten: rec, index: index }); return this; }, /** * Default behavior for the "add" event. Adds Record instances starting from * the index specified in `e.index`. * * @method _defAddFn * @param {EventFacade} e The add event * @private */ _defAddFn: function(e) { this._items.splice.apply(this._items, [e.index, 0].concat(e.added)); }, /** * Default behavior for the "remove" event. Removes Records from the * internal array starting from `e.index`. By default, it will remove one * Record. But if `e.range` is set, it will remove that many Records. * * @method _defRemoveFn * @param {EventFacade} e The remove event * @private */ _defRemoveFn: function(e) { this._items.splice(e.index, e.range || 1); }, /** * Default behavior for the "update" event. Sets Record instances for each * item in `e.updated` at indexes starting from `e.index`. * * @method _defUpdateFn * @param {EventFacade} e The update event * @private */ _defUpdateFn: function(e) { for (var i = 0; i < e.updated.length; i++) { this._items[e.index + i] = this._changeToRecord(e.updated[i]); } }, /** * Default behavior for the "empty" event. Clears the internal array of * Records. * * @method _defEmptyFn * @param {EventFacade} e The empty event * @private */ _defEmptyFn: function(e) { this._items = []; Y.log('empty fired'); }, /** Updates the internal hash table. @method _defUpdateHash @param {EventFacade} e Event triggering the hash table update @private **/ _updateHash: function (e) { var handler = "_hash", type = e.type.replace(/.*:/,''), newHash; // _hashAdd, _hashRemove, _hashEmpty, etc // Not a switch or else if setup to allow for external expansion. handler += type.charAt(0).toUpperCase() + type.slice(1); newHash = this[handler] && this[handler](this.get('table'), this.get('key'), e); if (newHash) { this.set('table', newHash); } }, /** Regenerates the hash table from the current internal array of Records. @method _hashRecordsChange @param {Object} hash The hash map before replacement @param {String} key The key by which to add items to the hash @param {Object} e The event or object containing the items to be added. Items are expected to be stored in an array assigned to the `added` property. @return {Object} The updated hash map @private **/ _hashRecordsChange: function (hash, key, e) { return this._buildHashTable(key); }, /** Builds a hash table from the current internal array of Records. @method _buildHashTable @param {String} key The Record key to hash the items by @return {Object} A new hash map of Records keyed by each Records' key @private **/ _buildHashTable: function (key) { return this._hashAdd({}, key, { added: this._items }); }, /** Adds items to the hash table. Items are the values, and the keys are the values of the item's attribute named in the `key` parameter. @method _hashAdd @param {Object} hash The hash map before adding items @param {String} key The key by which to add the items to the hash @param {Object} e The event or object containing the items to be added. Items are expected to be stored in an array assigned to the `added` property. @return {Object} The updated hash map @private **/ _hashAdd: function(hash, key, e) { var items = e.added, i, len; for (i = 0, len = e.added.length; i < len; ++i) { hash[items[i].get(key)] = items[i]; } return hash; }, /** Removes items from the hash table. @method _hashRemove @param {Object} hash The hash map before removing items @param {String} key The key by which to remove the items from the hash @param {Object} e The event or object containing the items to be removed. Items are expected to be stored in an array assigned to the `removed` property. @return {Object} The updated hash map @private **/ _hashRemove: function(hash, key, e) { for (var i = e.removed.length - 1; i >= 0; --i) { delete hash[e.removed[i].get(key)]; } return hash; }, /** Updates items in the hash table. @method _hashUpdate @param {Object} hash The hash map before updating items @param {String} key The key by which to update the items to the hash @param {Object} e The event or object containing the items to be updated. Items are expected to be stored in an array assigned to the `updated` property. Optionally, items can be identified for being overwritten by including them in an array assigned to the `overwritten` property. @return {Object} The updated hash map @private **/ _hashUpdate: function (hash, key, e) { if (e.overwritten && e.overwritten.length) { hash = this._hashRemove(hash, key, { removed: e.overwritten }); } return this._hashAdd(hash, key, { added: e.updated }); }, /** Clears the hash table. @method _hashEmpty @param {Object} hash The hash map before adding items @param {String} key The key by which to remove the items from the hash @param {Object} e The event or object containing the items to be removed. Items are expected to be stored in an array assigned to the `removed` property. @return {Object} An empty hash @private **/ _hashEmpty: function() { return {}; }, /** * Sets up the hashtable with all the records currently in the recordset * * @method _initHashTable * @private */ _initHashTable: function() { return this._hashAdd({}, this.get('key'), { added: this._items || [] }); }, /** * Helper method - it takes an object bag and converts it to a Y.Record * * @method _changeToRecord * @param obj {Object|Record} Any objet literal or Y.Record instance * @return {Record} A Record instance. * @private */ _changeToRecord: function(obj) { return (obj instanceof Y.Record) ? obj : new Y.Record({ data: obj }); }, /** Ensures the value being set is an array of Record instances. If array items are raw object data, they are turned into Records. @method _setRecords @param {Record[]|Object[]} items The Records or data Objects to store as Records. @return {Record[]} **/ _setRecords: function (items) { if (!Y.Lang.isArray(items)) { return Y.Attribute.INVALID_VALUE; } var records = [], i, len; // FIXME: This should use the flyweight pattern if possible for (i = 0, len = items.length; i < len; ++i) { records[i] = this._changeToRecord(items[i]); } return (this._items = records); } }, { ATTRS: { /** * An array of Records that the Recordset is storing. Passing an array * of raw record data is also accepted. The data for each item will be * wrapped in a Record instance. * * @attribute records * @type {Record[]} */ records: { // TODO: necessary? valueFn? lazyAdd: false, getter: function() { // give them a copy, not the internal object return Y.Array(this._items); }, setter: "_setRecords" }, /** A hash table where the ID of the record is the key, and the record instance is the value. @attribute table @type object **/ table: { valueFn: '_initHashTable' }, /** The ID to use as the key in the hash table. @attribute key @type string **/ key: { value: 'id', readOnly: true } } }); Y.augment(Recordset, ArrayList); Y.Recordset = Recordset; }, '3.18.1', {"requires": ["base", "arraylist"]}); PK\, = r.right) { scroll = true; nl = xy[0] + ((ws) ? b : 0); sl = sLeft + b; } } if (this.get('vertical')) { if (bottom >= r.bottom) { scroll = true; nt = xy[1] + ((ws) ? b : 0); st = sTop + b; } if (top <= r.top) { scroll = true; nt = xy[1] - ((ws) ? b : 0); st = sTop - b; } } if (st < 0) { st = 0; nt = xy[1]; } if (sl < 0) { sl = 0; nl = xy[0]; } if (nt < 0) { nt = xy[1]; } if (nl < 0) { nl = xy[0]; } if (move) { ho.actXY = [nl, nt]; ho._alignNode([nl, nt], true); //We are srolling.. xy = ho.actXY; ho.actXY = [nl, nt]; ho._moveNode({ node: win, top: st, left: sl}); if (!st && !sl) { this._cancelScroll(); } } else { if (scroll) { this._initScroll(); } else { this._cancelScroll(); } } }, /** * Cancel a previous scroll timer and init a new one. * @private * @method _initScroll */ _initScroll: function() { this._cancelScroll(); this._scrollTimer = Y.Lang.later(this.get('scrollDelay'), this, this._checkWinScroll, [true], true); }, /** * Cancel a currently running scroll timer. * @private * @method _cancelScroll */ _cancelScroll: function() { this._scrolling = false; if (this._scrollTimer) { this._scrollTimer.cancel(); delete this._scrollTimer; } }, /** * Called from the drag:align event to determine if we need to scroll. * @method align */ align: function(e) { if (this._scrolling) { this._cancelScroll(); e.preventDefault(); } if (!this._scrolling) { this._checkWinScroll(); } }, /** * Set the cache of the dragNode dims. * @private * @method _setDimCache */ _setDimCache: function() { var node = this.get(HOST).get('dragNode'); this._dimCache = { h: node.get(OFFSET_HEIGHT), w: node.get(OFFSET_WIDTH) }; }, /** * Called from the drag:start event * @method start */ start: function() { this._setDimCache(); }, /** * Called from the drag:end event * @method end */ end: function() { this._dimCache = null; this._cancelScroll(); } }); Y.namespace('Plugin'); /** * Extends the Scroll class to make the window scroll while dragging. * @class DDWindowScroll * @extends Scroll * @namespace Plugin * @constructor */ WS = function() { WS.superclass.constructor.apply(this, arguments); }; WS.ATTRS = Y.merge(S.ATTRS, { /** * Turn on window scroll support, default: true * @attribute windowScroll * @type Boolean */ windowScroll: { value: true, setter: function(scroll) { if (scroll) { this.set(PARENT_SCROLL, Y.one('win')); } return scroll; } } }); Y.extend(WS, S, { //Shouldn't have to do this.. initializer: function() { this.set('windowScroll', this.get('windowScroll')); } }); /** * The Scroll instance will be placed on the Drag instance under the winscroll namespace. * @property NS * @default winscroll * @readonly * @protected * @static * @type {String} */ WS.NAME = WS.NS = 'winscroll'; Y.Plugin.DDWinScroll = WS; /** * Extends the Scroll class to make a parent node scroll while dragging. * @class DDNodeScroll * @extends Scroll * @namespace Plugin * @constructor */ NS = function() { NS.superclass.constructor.apply(this, arguments); }; NS.ATTRS = Y.merge(S.ATTRS, { /** * The node we want to scroll. Used to set the internal parentScroll attribute. * @attribute node * @type Node */ node: { value: false, setter: function(node) { var n = Y.one(node); if (!n) { if (node !== false) { Y.error('DDNodeScroll: Invalid Node Given: ' + node); } } else { this.set(PARENT_SCROLL, n); } return n; } } }); Y.extend(NS, S, { //Shouldn't have to do this.. initializer: function() { this.set('node', this.get('node')); } }); /** * The NodeScroll instance will be placed on the Drag instance under the nodescroll namespace. * @property NS * @default nodescroll * @readonly * @protected * @static * @type {String} */ NS.NAME = NS.NS = 'nodescroll'; Y.Plugin.DDNodeScroll = NS; Y.DD.Scroll = S; }, '3.18.1', {"requires": ["dd-drag"]}); PK\Q ..3.18.1/dd-scroll/dd-scroll.jsnu[YUI.add('dd-scroll', function (Y, NAME) { /** * Base scroller class used to create the Plugin.DDNodeScroll and Plugin.DDWinScroll. * This class should not be called on it's own, it's designed to be a plugin. * @module dd * @submodule dd-scroll */ /** * Base scroller class used to create the Plugin.DDNodeScroll and Plugin.DDWinScroll. * This class should not be called on it's own, it's designed to be a plugin. * @class Scroll * @extends Base * @namespace DD * @constructor */ var S = function() { S.superclass.constructor.apply(this, arguments); }, WS, NS, HOST = 'host', BUFFER = 'buffer', PARENT_SCROLL = 'parentScroll', WINDOW_SCROLL = 'windowScroll', SCROLL_TOP = 'scrollTop', SCROLL_LEFT = 'scrollLeft', OFFSET_WIDTH = 'offsetWidth', OFFSET_HEIGHT = 'offsetHeight'; S.ATTRS = { /** * Internal config option to hold the node that we are scrolling. Should not be set by the developer. * @attribute parentScroll * @protected * @type Node */ parentScroll: { value: false, setter: function(node) { if (node) { return node; } return false; } }, /** * The number of pixels from the edge of the screen to turn on scrolling. Default: 30 * @attribute buffer * @type Number */ buffer: { value: 30, validator: Y.Lang.isNumber }, /** * The number of milliseconds delay to pass to the auto scroller. Default: 235 * @attribute scrollDelay * @type Number */ scrollDelay: { value: 235, validator: Y.Lang.isNumber }, /** * The host we are plugged into. * @attribute host * @type Object */ host: { value: null }, /** * Turn on window scroll support, default: false * @attribute windowScroll * @type Boolean */ windowScroll: { value: false, validator: Y.Lang.isBoolean }, /** * Allow vertical scrolling, default: true. * @attribute vertical * @type Boolean */ vertical: { value: true, validator: Y.Lang.isBoolean }, /** * Allow horizontal scrolling, default: true. * @attribute horizontal * @type Boolean */ horizontal: { value: true, validator: Y.Lang.isBoolean } }; Y.extend(S, Y.Base, { /** * Tells if we are actively scrolling or not. * @private * @property _scrolling * @type Boolean */ _scrolling: null, /** * Cache of the Viewport dims. * @private * @property _vpRegionCache * @type Object */ _vpRegionCache: null, /** * Cache of the dragNode dims. * @private * @property _dimCache * @type Object */ _dimCache: null, /** * Holder for the Timer object returned from Y.later. * @private * @property _scrollTimer * @type {Y.later} */ _scrollTimer: null, /** * Sets the _vpRegionCache property with an Object containing the dims from the viewport. * @private * @method _getVPRegion */ _getVPRegion: function() { var r = {}, n = this.get(PARENT_SCROLL), b = this.get(BUFFER), ws = this.get(WINDOW_SCROLL), xy = ((ws) ? [] : n.getXY()), w = ((ws) ? 'winWidth' : OFFSET_WIDTH), h = ((ws) ? 'winHeight' : OFFSET_HEIGHT), t = ((ws) ? n.get(SCROLL_TOP) : xy[1]), l = ((ws) ? n.get(SCROLL_LEFT) : xy[0]); r = { top: t + b, right: (n.get(w) + l) - b, bottom: (n.get(h) + t) - b, left: l + b }; this._vpRegionCache = r; return r; }, initializer: function() { var h = this.get(HOST); h.after('drag:start', Y.bind(this.start, this)); h.after('drag:end', Y.bind(this.end, this)); h.on('drag:align', Y.bind(this.align, this)); //TODO - This doesn't work yet?? Y.one('win').on('scroll', Y.bind(function() { this._vpRegionCache = null; }, this)); }, /** * Check to see if we need to fire the scroll timer. If scroll timer is running this will scroll the window. * @private * @method _checkWinScroll * @param {Boolean} move Should we move the window. From Y.later */ _checkWinScroll: function(move) { var r = this._getVPRegion(), ho = this.get(HOST), ws = this.get(WINDOW_SCROLL), xy = ho.lastXY, scroll = false, b = this.get(BUFFER), win = this.get(PARENT_SCROLL), sTop = win.get(SCROLL_TOP), sLeft = win.get(SCROLL_LEFT), w = this._dimCache.w, h = this._dimCache.h, bottom = xy[1] + h, top = xy[1], right = xy[0] + w, left = xy[0], nt = top, nl = left, st = sTop, sl = sLeft; if (this.get('horizontal')) { if (left <= r.left) { scroll = true; nl = xy[0] - ((ws) ? b : 0); sl = sLeft - b; } if (right >= r.right) { scroll = true; nl = xy[0] + ((ws) ? b : 0); sl = sLeft + b; } } if (this.get('vertical')) { if (bottom >= r.bottom) { scroll = true; nt = xy[1] + ((ws) ? b : 0); st = sTop + b; } if (top <= r.top) { scroll = true; nt = xy[1] - ((ws) ? b : 0); st = sTop - b; } } if (st < 0) { st = 0; nt = xy[1]; } if (sl < 0) { sl = 0; nl = xy[0]; } if (nt < 0) { nt = xy[1]; } if (nl < 0) { nl = xy[0]; } if (move) { ho.actXY = [nl, nt]; ho._alignNode([nl, nt], true); //We are srolling.. xy = ho.actXY; ho.actXY = [nl, nt]; ho._moveNode({ node: win, top: st, left: sl}); if (!st && !sl) { this._cancelScroll(); } } else { if (scroll) { this._initScroll(); } else { this._cancelScroll(); } } }, /** * Cancel a previous scroll timer and init a new one. * @private * @method _initScroll */ _initScroll: function() { this._cancelScroll(); this._scrollTimer = Y.Lang.later(this.get('scrollDelay'), this, this._checkWinScroll, [true], true); }, /** * Cancel a currently running scroll timer. * @private * @method _cancelScroll */ _cancelScroll: function() { this._scrolling = false; if (this._scrollTimer) { this._scrollTimer.cancel(); delete this._scrollTimer; } }, /** * Called from the drag:align event to determine if we need to scroll. * @method align */ align: function(e) { if (this._scrolling) { this._cancelScroll(); e.preventDefault(); } if (!this._scrolling) { this._checkWinScroll(); } }, /** * Set the cache of the dragNode dims. * @private * @method _setDimCache */ _setDimCache: function() { var node = this.get(HOST).get('dragNode'); this._dimCache = { h: node.get(OFFSET_HEIGHT), w: node.get(OFFSET_WIDTH) }; }, /** * Called from the drag:start event * @method start */ start: function() { this._setDimCache(); }, /** * Called from the drag:end event * @method end */ end: function() { this._dimCache = null; this._cancelScroll(); } }); Y.namespace('Plugin'); /** * Extends the Scroll class to make the window scroll while dragging. * @class DDWindowScroll * @extends Scroll * @namespace Plugin * @constructor */ WS = function() { WS.superclass.constructor.apply(this, arguments); }; WS.ATTRS = Y.merge(S.ATTRS, { /** * Turn on window scroll support, default: true * @attribute windowScroll * @type Boolean */ windowScroll: { value: true, setter: function(scroll) { if (scroll) { this.set(PARENT_SCROLL, Y.one('win')); } return scroll; } } }); Y.extend(WS, S, { //Shouldn't have to do this.. initializer: function() { this.set('windowScroll', this.get('windowScroll')); } }); /** * The Scroll instance will be placed on the Drag instance under the winscroll namespace. * @property NS * @default winscroll * @readonly * @protected * @static * @type {String} */ WS.NAME = WS.NS = 'winscroll'; Y.Plugin.DDWinScroll = WS; /** * Extends the Scroll class to make a parent node scroll while dragging. * @class DDNodeScroll * @extends Scroll * @namespace Plugin * @constructor */ NS = function() { NS.superclass.constructor.apply(this, arguments); }; NS.ATTRS = Y.merge(S.ATTRS, { /** * The node we want to scroll. Used to set the internal parentScroll attribute. * @attribute node * @type Node */ node: { value: false, setter: function(node) { var n = Y.one(node); if (!n) { if (node !== false) { Y.error('DDNodeScroll: Invalid Node Given: ' + node); } } else { this.set(PARENT_SCROLL, n); } return n; } } }); Y.extend(NS, S, { //Shouldn't have to do this.. initializer: function() { this.set('node', this.get('node')); } }); /** * The NodeScroll instance will be placed on the Drag instance under the nodescroll namespace. * @property NS * @default nodescroll * @readonly * @protected * @static * @type {String} */ NS.NAME = NS.NS = 'nodescroll'; Y.Plugin.DDNodeScroll = NS; Y.DD.Scroll = S; }, '3.18.1', {"requires": ["dd-drag"]}); PK\N  !3.18.1/dd-scroll/dd-scroll-min.jsnu[YUI.add("dd-scroll",function(e,t){var n=function(){n.superclass.constructor.apply(this,arguments)},r,i,s="host",o="buffer",u="parentScroll",a="windowScroll",f="scrollTop",l="scrollLeft",c="offsetWidth",h="offsetHeight";n.ATTRS={parentScroll:{value:!1,setter:function(e){return e?e:!1}},buffer:{value:30,validator:e.Lang.isNumber},scrollDelay:{value:235,validator:e.Lang.isNumber},host:{value:null},windowScroll:{value:!1,validator:e.Lang.isBoolean},vertical:{value:!0,validator:e.Lang.isBoolean},horizontal:{value:!0,validator:e.Lang.isBoolean}},e.extend(n,e.Base,{_scrolling:null,_vpRegionCache:null,_dimCache:null,_scrollTimer:null,_getVPRegion:function(){var e={},t=this.get(u),n=this.get(o),r=this.get(a),i=r?[]:t.getXY(),s=r?"winWidth":c,p=r?"winHeight":h,d=r?t.get(f):i[1],v=r?t.get(l):i[0];return e={top:d+n,right:t.get(s)+v-n,bottom:t.get(p)+d-n,left:v+n},this._vpRegionCache=e,e},initializer:function(){var t=this.get(s);t.after("drag:start",e.bind(this.start,this)),t.after("drag:end",e.bind(this.end,this)),t.on("drag:align",e.bind(this.align,this)),e.one("win").on("scroll",e.bind(function(){this._vpRegionCache=null},this))},_checkWinScroll:function(e){var t=this._getVPRegion(),n=this.get(s),r=this.get(a),i=n.lastXY,c=!1,h=this.get(o),p=this.get(u),d=p.get(f),v=p.get(l),m=this._dimCache.w,g=this._dimCache.h,y=i[1]+g,b=i[1],w=i[0]+m,E=i[0],S=b,x=E,T=d,N=v;this.get("horizontal")&&(E<=t.left&&(c=!0,x=i[0]-(r?h:0),N=v-h),w>=t.right&&(c=!0,x=i[0]+(r?h:0),N=v+h)),this.get("vertical")&&(y>=t.bottom&&(c=!0,S=i[1]+(r?h:0),T=d+h),b<=t.top&&(c=!0,S=i[1]-(r?h:0),T=d-h)),T<0&&(T=0,S=i[1]),N<0&&(N=0,x=i[0]),S<0&&(S=i[1]),x<0&&(x=i[0]),e?(n.actXY=[x,S],n._alignNode([x,S],!0),i=n.actXY,n.actXY=[x,S],n._moveNode({node:p,top:T,left:N}),!T&&!N&&this._cancelScroll()):c?this._initScroll():this._cancelScroll()},_initScroll:function(){this._cancelScroll(),this._scrollTimer=e.Lang.later(this.get("scrollDelay"),this,this._checkWinScroll,[!0],!0)},_cancelScroll:function(){this._scrolling=!1,this._scrollTimer&&(this._scrollTimer.cancel(),delete this._scrollTimer)},align:function(e){this._scrolling&&(this._cancelScroll(),e.preventDefault()),this._scrolling||this._checkWinScroll()},_setDimCache:function(){var e=this.get(s).get("dragNode");this._dimCache={h:e.get(h),w:e.get(c)}},start:function(){this._setDimCache()},end:function(){this._dimCache=null,this._cancelScroll()}}),e.namespace("Plugin"),r=function(){r.superclass.constructor.apply(this,arguments)},r.ATTRS=e.merge(n.ATTRS,{windowScroll:{value:!0,setter:function(t){return t&&this.set(u,e.one("win")),t}}}),e.extend(r,n,{initializer:function(){this.set("windowScroll",this.get("windowScroll"))}}),r.NAME=r.NS="winscroll",e.Plugin.DDWinScroll=r,i=function(){i.superclass.constructor.apply(this,arguments)},i.ATTRS=e.merge(n.ATTRS,{node:{value:!1,setter:function(t){var n=e.one(t);return n?this.set(u,n):t!==!1&&e.error("DDNodeScroll: Invalid Node Given: "+t),n}}}),e.extend(i,n,{initializer:function(){this.set("node",this.get("node"))}}),i.NAME=i.NS="nodescroll",e.Plugin.DDNodeScroll=i,e.DD.Scroll=n},"3.18.1",{requires:["dd-drag"]}); PK\痐!3.18.1/anim-base/anim-base-min.jsnu[YUI.add("anim-base",function(e,t){var n="running",r="startTime",i="elapsedTime",s="start",o="tween",u="end",a="node",f="paused",l="reverse",c="iterationCount",h=Number,p={},d;e.Anim=function(){e.Anim.superclass.constructor.apply(this,arguments),e.Anim._instances[e.stamp(this)]=this},e.Anim.NAME="anim",e.Anim._instances={},e.Anim.RE_DEFAULT_UNIT=/^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i,e.Anim.DEFAULT_UNIT="px",e.Anim.DEFAULT_EASING=function(e,t,n,r){return n*e/r+t},e.Anim._intervalTime=20,e.Anim.behaviors={left:{get:function(e,t){return e._getOffset(t)}}},e.Anim.behaviors.top=e.Anim.behaviors.left,e.Anim.DEFAULT_SETTER=function(t,n,r,i,s,o,u,a){var f=t._node,l=f._node,c=u(s,h(r),h(i)-h(r),o);l?"style"in l&&(n in l.style||n in e.DOM.CUSTOM_STYLES)?(a=a||"",f.setStyle(n,c+a)):"attributes"in l&&n in l.attributes?f.setAttribute(n,c):n in l&&(l[n]=c):f.set?f.set(n,c):n in f&&(f[n]=c)},e.Anim.DEFAULT_GETTER=function(t,n){var r=t._node,i=r._node,s="";return i?"style"in i&&(n in i.style||n in e.DOM.CUSTOM_STYLES)?s=r.getComputedStyle(n):"attributes"in i&&n in i.attributes?s=r.getAttribute(n):n in i&&(s=i[n]):r.get?s=r.get(n):n in r&&(s=r[n]),s},e.Anim.ATTRS={node:{setter:function(t){return t&&(typeof t=="string"||t.nodeType)&&(t=e.one(t)),this._node=t,!t,t}},duration:{value:1},easing:{value:e.Anim.DEFAULT_EASING,setter:function(t){if(typeof t=="string"&&e.Easing)return e.Easing[t]}},from:{},to:{},startTime:{value:0,readOnly:!0},elapsedTime:{value:0,readOnly:!0},running:{getter:function(){return!!p[e.stamp(this)]},value:!1,readOnly:!0},iterations:{value:1},iterationCount:{value:0,readOnly:!0},direction:{value:"normal"},paused:{readOnly:!0,value:!1},reverse:{value:!1}},e.Anim.run=function(){var t=e.Anim._instances,n;for(n in t)t[n].run&&t[n].run()},e.Anim.pause=function(){for(var t in p)p[t].pause&&p[t].pause();e.Anim._stopTimer()},e.Anim.stop=function(){for(var t in p)p[t].stop&&p[t].stop();e.Anim._stopTimer()},e.Anim._startTimer=function(){d||(d=setInterval(e.Anim._runFrame,e.Anim._intervalTime))},e.Anim._stopTimer=function(){clearInterval(d),d=0},e.Anim._runFrame=function(){var t=!0,n;for(n in p)p[n]._runFrame&&(t=!1,p[n]._runFrame());t&&e.Anim._stopTimer()},e.Anim.RE_UNITS=/^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/;var v={run:function(){return this.get(f)?this._resume():this.get(n)||this._start(),this},pause:function(){return this.get(n)&&this._pause(),this},stop:function(e){return(this.get(n)||this.get(f))&&this._end(e),this},_added:!1,_start:function(){this._set(r,new Date-this.get(i)),this._actualFrames=0,this.get(f)||this._initAnimAttr(),p[e.stamp(this)]=this,e.Anim._startTimer(),this.fire(s)},_pause:function(){this._set(r,null),this._set(f,!0),delete p[e.stamp(this)],this.fire("pause")},_resume:function(){this._set(f,!1),p[e.stamp(this)]=this,this._set(r,new Date-this.get(i)),e.Anim._startTimer(),this.fire("resume")},_end:function(t){var n=this.get("duration")*1e3;t&&this._runAttrs(n,n,this.get(l)),this._set(r,null),this._set(i,0),this._set(f,!1),delete p[e.stamp(this)],this.fire(u,{elapsed:this.get(i)})},_runFrame:function(){var e=this._runtimeAttr.duration,t=new Date-this.get(r),n=this.get(l),s=t>=e;this._runAttrs(t,e,n),this._actualFrames+=1,this._set(i,t),this.fire(o),s&&this._lastFrame()},_runAttrs:function(t,n,r){var i=this._runtimeAttr,s=e.Anim.behaviors,o=i.easing,u=n,a=!1,f,l,c;t>=n&&(a=!0),r&&(t=n-t,u=0);for(c in i)i[c].to&&(f=i[c],l=c in s&&"set"in s[c]?s[c].set:e.Anim.DEFAULT_SETTER,a?l(this,c,f.from,f.to,u,n,o,f.unit):l(this,c,f.from,f.to,t,n,o,f.unit))},_lastFrame:function(){var e=this.get("iterations"),t=this.get(c);t+=1,e==="infinite"||t= d); this._runAttrs(t, d, reverse); this._actualFrames += 1; this._set(ELAPSED_TIME, t); this.fire(TWEEN); if (done) { this._lastFrame(); } }, _runAttrs: function(t, d, reverse) { var attr = this._runtimeAttr, customAttr = Y.Anim.behaviors, easing = attr.easing, lastFrame = d, done = false, attribute, setter, i; if (t >= d) { done = true; } if (reverse) { t = d - t; lastFrame = 0; } for (i in attr) { if (attr[i].to) { attribute = attr[i]; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Y.Anim.DEFAULT_SETTER; if (!done) { setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit); } else { setter(this, i, attribute.from, attribute.to, lastFrame, d, easing, attribute.unit); } } } }, _lastFrame: function() { var iter = this.get('iterations'), iterCount = this.get(ITERATION_COUNT); iterCount += 1; if (iter === 'infinite' || iterCount < iter) { if (this.get('direction') === 'alternate') { this.set(REVERSE, !this.get(REVERSE)); // flip it } /** * @event iteration * @description fires when an animation begins an iteration. * @param {Event} ev The iteration event. * @type Event.Custom */ this.fire('iteration'); } else { iterCount = 0; this._end(); } this._set(START_TIME, new Date()); this._set(ITERATION_COUNT, iterCount); }, _initAnimAttr: function() { var from = this.get('from') || {}, to = this.get('to') || {}, attr = { duration: this.get('duration') * 1000, easing: this.get('easing') }, customAttr = Y.Anim.behaviors, node = this.get(NODE), // implicit attr init unit, begin, end; Y.each(to, function(val, name) { if (typeof val === 'function') { val = val.call(this, node); } begin = from[name]; if (begin === undefined) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(this, name) : Y.Anim.DEFAULT_GETTER(this, name); } else if (typeof begin === 'function') { begin = begin.call(this, node); } var mFrom = Y.Anim.RE_UNITS.exec(begin), mTo = Y.Anim.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Y.Anim.RE_DEFAULT_UNIT.test(name)) { unit = Y.Anim.DEFAULT_UNIT; } if (!begin || !end) { Y.error('invalid "from" or "to" for "' + name + '"', 'Anim'); return; } attr[name] = { from: Y.Lang.isObject(begin) ? Y.clone(begin) : begin, to: end, unit: unit }; }, this); this._runtimeAttr = attr; }, // TODO: move to computedStyle? (browsers dont agree on default computed offsets) _getOffset: function(attr) { var node = this._node, val = node.getComputedStyle(attr), get = (attr === 'left') ? 'getX': 'getY', set = (attr === 'left') ? 'setX': 'setY', position; if (val === 'auto') { position = node.getStyle('position'); if (position === 'absolute' || position === 'fixed') { val = node[get](); node[set](val); } else { val = 0; } } return val; }, destructor: function() { delete Y.Anim._instances[Y.stamp(this)]; } }; Y.extend(Y.Anim, Y.Base, proto); }, '3.18.1', {"requires": ["base-base", "node-style", "color-base"]}); PK\)VLJLJ#3.18.1/anim-base/anim-base-debug.jsnu[YUI.add('anim-base', function (Y, NAME) { /** * The Animation Utility provides an API for creating advanced transitions. * @module anim */ /** * Provides the base Anim class, for animating numeric properties. * * @module anim * @submodule anim-base */ /** * A class for constructing animation instances. * @class Anim * @for Anim * @constructor * @extends Base */ var RUNNING = 'running', START_TIME = 'startTime', ELAPSED_TIME = 'elapsedTime', /** * @for Anim * @event start * @description fires when an animation begins. * @param {Event} ev The start event. * @type Event.Custom */ START = 'start', /** * @event tween * @description fires every frame of the animation. * @param {Event} ev The tween event. * @type Event.Custom */ TWEEN = 'tween', /** * @event end * @description fires after the animation completes. * @param {Event} ev The end event. * @type Event.Custom */ END = 'end', NODE = 'node', PAUSED = 'paused', REVERSE = 'reverse', // TODO: cleanup ITERATION_COUNT = 'iterationCount', NUM = Number; var _running = {}, _timer; Y.Anim = function() { Y.Anim.superclass.constructor.apply(this, arguments); Y.Anim._instances[Y.stamp(this)] = this; }; Y.Anim.NAME = 'anim'; Y.Anim._instances = {}; /** * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ Y.Anim.RE_DEFAULT_UNIT = /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i; /** * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ Y.Anim.DEFAULT_UNIT = 'px'; Y.Anim.DEFAULT_EASING = function (t, b, c, d) { return c * t / d + b; // linear easing }; /** * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ Y.Anim._intervalTime = 20; /** * Bucket for custom getters and setters * * @property behaviors * @static */ Y.Anim.behaviors = { left: { get: function(anim, attr) { return anim._getOffset(attr); } } }; Y.Anim.behaviors.top = Y.Anim.behaviors.left; /** * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ Y.Anim.DEFAULT_SETTER = function(anim, att, from, to, elapsed, duration, fn, unit) { var node = anim._node, domNode = node._node, val = fn(elapsed, NUM(from), NUM(to) - NUM(from), duration); if (domNode) { if ('style' in domNode && (att in domNode.style || att in Y.DOM.CUSTOM_STYLES)) { unit = unit || ''; node.setStyle(att, val + unit); } else if ('attributes' in domNode && att in domNode.attributes) { node.setAttribute(att, val); } else if (att in domNode) { domNode[att] = val; } } else if (node.set) { node.set(att, val); } else if (att in node) { node[att] = val; } }; /** * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ Y.Anim.DEFAULT_GETTER = function(anim, att) { var node = anim._node, domNode = node._node, val = ''; if (domNode) { if ('style' in domNode && (att in domNode.style || att in Y.DOM.CUSTOM_STYLES)) { val = node.getComputedStyle(att); } else if ('attributes' in domNode && att in domNode.attributes) { val = node.getAttribute(att); } else if (att in domNode) { val = domNode[att]; } } else if (node.get) { val = node.get(att); } else if (att in node) { val = node[att]; } return val; }; Y.Anim.ATTRS = { /** * The object to be animated. * @attribute node * @type Node */ node: { setter: function(node) { if (node) { if (typeof node === 'string' || node.nodeType) { node = Y.one(node); } } this._node = node; if (!node) { Y.log(node + ' is not a valid node', 'warn', 'Anim'); } return node; } }, /** * The length of the animation. Defaults to "1" (second). * @attribute duration * @type NUM */ duration: { value: 1 }, /** * The method that will provide values to the attribute(s) during the animation. * Defaults to "Easing.easeNone". * @attribute easing * @type Function */ easing: { value: Y.Anim.DEFAULT_EASING, setter: function(val) { if (typeof val === 'string' && Y.Easing) { return Y.Easing[val]; } } }, /** * The starting values for the animated properties. * * Fields may be strings, numbers, or functions. * If a function is used, the return value becomes the from value. * If no from value is specified, the DEFAULT_GETTER will be used. * Supports any unit, provided it matches the "to" (or default) * unit (e.g. `{width: '10em', color: 'rgb(0, 0, 0)', borderColor: '#ccc'}`). * * If using the default ('px' for length-based units), the unit may be omitted * (e.g. `{width: 100}, borderColor: 'ccc'}`, which defaults to pixels * and hex, respectively). * * @attribute from * @type Object */ from: {}, /** * The ending values for the animated properties. * * Fields may be strings, numbers, or functions. * Supports any unit, provided it matches the "from" (or default) * unit (e.g. `{width: '50%', color: 'red', borderColor: '#ccc'}`). * * If using the default ('px' for length-based units), the unit may be omitted * (e.g. `{width: 100, borderColor: 'ccc'}`, which defaults to pixels * and hex, respectively). * * @attribute to * @type Object */ to: {}, /** * Date stamp for the first frame of the animation. * @attribute startTime * @type Int * @default 0 * @readOnly */ startTime: { value: 0, readOnly: true }, /** * Current time the animation has been running. * @attribute elapsedTime * @type Int * @default 0 * @readOnly */ elapsedTime: { value: 0, readOnly: true }, /** * Whether or not the animation is currently running. * @attribute running * @type Boolean * @default false * @readOnly */ running: { getter: function() { return !!_running[Y.stamp(this)]; }, value: false, readOnly: true }, /** * The number of times the animation should run * @attribute iterations * @type Int * @default 1 */ iterations: { value: 1 }, /** * The number of iterations that have occurred. * Resets when an animation ends (reaches iteration count or stop() called). * @attribute iterationCount * @type Int * @default 0 * @readOnly */ iterationCount: { value: 0, readOnly: true }, /** * How iterations of the animation should behave. * Possible values are "normal" and "alternate". * Normal will repeat the animation, alternate will reverse on every other pass. * * @attribute direction * @type String * @default "normal" */ direction: { value: 'normal' // | alternate (fwd on odd, rev on even per spec) }, /** * Whether or not the animation is currently paused. * @attribute paused * @type Boolean * @default false * @readOnly */ paused: { readOnly: true, value: false }, /** * If true, the `from` and `to` attributes are swapped, * and the animation is then run starting from `from`. * @attribute reverse * @type Boolean * @default false */ reverse: { value: false } }; /** * Runs all animation instances. * @method run * @static */ Y.Anim.run = function() { var instances = Y.Anim._instances, i; for (i in instances) { if (instances[i].run) { instances[i].run(); } } }; /** * Pauses all animation instances. * @method pause * @static */ Y.Anim.pause = function() { for (var i in _running) { // stop timer if nothing running if (_running[i].pause) { _running[i].pause(); } } Y.Anim._stopTimer(); }; /** * Stops all animation instances. * @method stop * @static */ Y.Anim.stop = function() { for (var i in _running) { // stop timer if nothing running if (_running[i].stop) { _running[i].stop(); } } Y.Anim._stopTimer(); }; Y.Anim._startTimer = function() { if (!_timer) { _timer = setInterval(Y.Anim._runFrame, Y.Anim._intervalTime); } }; Y.Anim._stopTimer = function() { clearInterval(_timer); _timer = 0; }; /** * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ Y.Anim._runFrame = function() { var done = true, anim; for (anim in _running) { if (_running[anim]._runFrame) { done = false; _running[anim]._runFrame(); } } if (done) { Y.Anim._stopTimer(); } }; Y.Anim.RE_UNITS = /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/; var proto = { /** * Starts or resumes an animation. * @method run * @chainable */ run: function() { if (this.get(PAUSED)) { this._resume(); } else if (!this.get(RUNNING)) { this._start(); } return this; }, /** * Pauses the animation and * freezes it in its current state and time. * Calling run() will continue where it left off. * @method pause * @chainable */ pause: function() { if (this.get(RUNNING)) { this._pause(); } return this; }, /** * Stops the animation and resets its time. * @method stop * @param {Boolean} finish If true, the animation will move to the last frame * @chainable */ stop: function(finish) { if (this.get(RUNNING) || this.get(PAUSED)) { this._end(finish); } return this; }, _added: false, _start: function() { this._set(START_TIME, new Date() - this.get(ELAPSED_TIME)); this._actualFrames = 0; if (!this.get(PAUSED)) { this._initAnimAttr(); } _running[Y.stamp(this)] = this; Y.Anim._startTimer(); this.fire(START); }, _pause: function() { this._set(START_TIME, null); this._set(PAUSED, true); delete _running[Y.stamp(this)]; /** * @event pause * @description fires when an animation is paused. * @param {Event} ev The pause event. * @type Event.Custom */ this.fire('pause'); }, _resume: function() { this._set(PAUSED, false); _running[Y.stamp(this)] = this; this._set(START_TIME, new Date() - this.get(ELAPSED_TIME)); Y.Anim._startTimer(); /** * @event resume * @description fires when an animation is resumed (run from pause). * @param {Event} ev The pause event. * @type Event.Custom */ this.fire('resume'); }, _end: function(finish) { var duration = this.get('duration') * 1000; if (finish) { // jump to last frame this._runAttrs(duration, duration, this.get(REVERSE)); } this._set(START_TIME, null); this._set(ELAPSED_TIME, 0); this._set(PAUSED, false); delete _running[Y.stamp(this)]; this.fire(END, {elapsed: this.get(ELAPSED_TIME)}); }, _runFrame: function() { var d = this._runtimeAttr.duration, t = new Date() - this.get(START_TIME), reverse = this.get(REVERSE), done = (t >= d); this._runAttrs(t, d, reverse); this._actualFrames += 1; this._set(ELAPSED_TIME, t); this.fire(TWEEN); if (done) { this._lastFrame(); } }, _runAttrs: function(t, d, reverse) { var attr = this._runtimeAttr, customAttr = Y.Anim.behaviors, easing = attr.easing, lastFrame = d, done = false, attribute, setter, i; if (t >= d) { done = true; } if (reverse) { t = d - t; lastFrame = 0; } for (i in attr) { if (attr[i].to) { attribute = attr[i]; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Y.Anim.DEFAULT_SETTER; if (!done) { setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit); } else { setter(this, i, attribute.from, attribute.to, lastFrame, d, easing, attribute.unit); } } } }, _lastFrame: function() { var iter = this.get('iterations'), iterCount = this.get(ITERATION_COUNT); iterCount += 1; if (iter === 'infinite' || iterCount < iter) { if (this.get('direction') === 'alternate') { this.set(REVERSE, !this.get(REVERSE)); // flip it } /** * @event iteration * @description fires when an animation begins an iteration. * @param {Event} ev The iteration event. * @type Event.Custom */ this.fire('iteration'); } else { iterCount = 0; this._end(); } this._set(START_TIME, new Date()); this._set(ITERATION_COUNT, iterCount); }, _initAnimAttr: function() { var from = this.get('from') || {}, to = this.get('to') || {}, attr = { duration: this.get('duration') * 1000, easing: this.get('easing') }, customAttr = Y.Anim.behaviors, node = this.get(NODE), // implicit attr init unit, begin, end; Y.each(to, function(val, name) { if (typeof val === 'function') { val = val.call(this, node); } begin = from[name]; if (begin === undefined) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(this, name) : Y.Anim.DEFAULT_GETTER(this, name); } else if (typeof begin === 'function') { begin = begin.call(this, node); } var mFrom = Y.Anim.RE_UNITS.exec(begin), mTo = Y.Anim.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Y.Anim.RE_DEFAULT_UNIT.test(name)) { unit = Y.Anim.DEFAULT_UNIT; } if (!begin || !end) { Y.error('invalid "from" or "to" for "' + name + '"', 'Anim'); return; } attr[name] = { from: Y.Lang.isObject(begin) ? Y.clone(begin) : begin, to: end, unit: unit }; }, this); this._runtimeAttr = attr; }, // TODO: move to computedStyle? (browsers dont agree on default computed offsets) _getOffset: function(attr) { var node = this._node, val = node.getComputedStyle(attr), get = (attr === 'left') ? 'getX': 'getY', set = (attr === 'left') ? 'setX': 'setY', position; if (val === 'auto') { position = node.getStyle('position'); if (position === 'absolute' || position === 'fixed') { val = node[get](); node[set](val); } else { val = 0; } } return val; }, destructor: function() { delete Y.Anim._instances[Y.stamp(this)]; } }; Y.extend(Y.Anim, Y.Base, proto); }, '3.18.1', {"requires": ["base-base", "node-style", "color-base"]}); PK\{ ! !73.18.1/text-data-wordbreak/text-data-wordbreak-debug.jsnu[YUI.add('text-data-wordbreak', function (Y, NAME) { Y.namespace('Text.Data').WordBreak = { // The UnicodeSet utility is helpful for enumerating the specific code // points covered by each of these regular expressions: // http://unicode.org/cldr/utility/list-unicodeset.jsp // // The code sets from which these regexes were derived can be generated // by the UnicodeSet utility using the links here: // http://unicode.org/cldr/utility/properties.jsp?a=Word_Break#Word_Break aletter : '[A-Za-z\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F3\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u10A0-\u10C5\u10D0-\u10FA\u10FC\u1100-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1A00-\u1A16\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BC0-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u24B6-\u24E9\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2D00-\u2D25\u2D30-\u2D65\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u303B\u303C\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790\uA791\uA7A0-\uA7A9\uA7FA-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFFA0-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]', midnumlet : "['\\.\u2018\u2019\u2024\uFE52\uFF07\uFF0E]", midletter : '[:\u00B7\u00B7\u05F4\u2027\uFE13\uFE55\uFF1A]', midnum : '[,;;\u0589\u060C\u060D\u066C\u07F8\u2044\uFE10\uFE14\uFE50\uFE54\uFF0C\uFF1B]', numeric : '[0-9\u0660-\u0669\u066B\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9]', cr : '\\r', lf : '\\n', newline : '[\u000B\u000C\u0085\u2028\u2029]', extend : '[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0900-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C82\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D02\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B6-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAA\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2\u1DC0-\u1DE6\u1DFC-\u1DFF\u200C\u200D\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA67C\uA67D\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE26\uFF9E\uFF9F]', format : '[\u00AD\u0600-\u0603\u06DD\u070F\u17B4\u17B5\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\uFEFF\uFFF9-\uFFFB]', katakana : '[\u3031-\u3035\u309B\u309C\u30A0-\u30FA\u30FC-\u30FF\u31F0-\u31FF\u32D0-\u32FE\u3300-\u3357\uFF66-\uFF9D]', extendnumlet: '[_\u203F\u2040\u2054\uFE33\uFE34\uFE4D-\uFE4F\uFF3F]', punctuation : '[!-#%-*,-\\/:;?@\\[-\\]_{}\u00A1\u00AB\u00B7\u00BB\u00BF;\u00B7\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1361-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u3008\u3009\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30\u2E31\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]' }; }, '3.18.1', {"requires": ["yui-base"]}); PK\{ ! !13.18.1/text-data-wordbreak/text-data-wordbreak.jsnu[YUI.add('text-data-wordbreak', function (Y, NAME) { Y.namespace('Text.Data').WordBreak = { // The UnicodeSet utility is helpful for enumerating the specific code // points covered by each of these regular expressions: // http://unicode.org/cldr/utility/list-unicodeset.jsp // // The code sets from which these regexes were derived can be generated // by the UnicodeSet utility using the links here: // http://unicode.org/cldr/utility/properties.jsp?a=Word_Break#Word_Break aletter : '[A-Za-z\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F3\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u10A0-\u10C5\u10D0-\u10FA\u10FC\u1100-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1A00-\u1A16\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BC0-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u24B6-\u24E9\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2D00-\u2D25\u2D30-\u2D65\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u303B\u303C\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790\uA791\uA7A0-\uA7A9\uA7FA-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFFA0-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]', midnumlet : "['\\.\u2018\u2019\u2024\uFE52\uFF07\uFF0E]", midletter : '[:\u00B7\u00B7\u05F4\u2027\uFE13\uFE55\uFF1A]', midnum : '[,;;\u0589\u060C\u060D\u066C\u07F8\u2044\uFE10\uFE14\uFE50\uFE54\uFF0C\uFF1B]', numeric : '[0-9\u0660-\u0669\u066B\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9]', cr : '\\r', lf : '\\n', newline : '[\u000B\u000C\u0085\u2028\u2029]', extend : '[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0900-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C82\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D02\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B6-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAA\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2\u1DC0-\u1DE6\u1DFC-\u1DFF\u200C\u200D\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA67C\uA67D\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE26\uFF9E\uFF9F]', format : '[\u00AD\u0600-\u0603\u06DD\u070F\u17B4\u17B5\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\uFEFF\uFFF9-\uFFFB]', katakana : '[\u3031-\u3035\u309B\u309C\u30A0-\u30FA\u30FC-\u30FF\u31F0-\u31FF\u32D0-\u32FE\u3300-\u3357\uFF66-\uFF9D]', extendnumlet: '[_\u203F\u2040\u2054\uFE33\uFE34\uFE4D-\uFE4F\uFF3F]', punctuation : '[!-#%-*,-\\/:;?@\\[-\\]_{}\u00A1\u00AB\u00B7\u00BB\u00BF;\u00B7\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1361-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u3008\u3009\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30\u2E31\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]' }; }, '3.18.1', {"requires": ["yui-base"]}); PK\o53.18.1/text-data-wordbreak/text-data-wordbreak-min.jsnu[YUI.add("text-data-wordbreak",function(e,t){e.namespace("Text.Data").WordBreak={aletter:"[A-Za-z\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f3\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u10a0-\u10c5\u10d0-\u10fa\u10fc\u1100-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1a00-\u1a16\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bc0-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u24b6-\u24e9\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2d00-\u2d25\u2d30-\u2d65\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005\u303b\u303c\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790\ua791\ua7a0-\ua7a9\ua7fa-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uffa0-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]",midnumlet:"['\\.\u2018\u2019\u2024\ufe52\uff07\uff0e]",midletter:"[:\u00b7\u00b7\u05f4\u2027\ufe13\ufe55\uff1a]",midnum:"[,;;\u0589\u060c\u060d\u066c\u07f8\u2044\ufe10\ufe14\ufe50\ufe54\uff0c\uff1b]",numeric:"[0-9\u0660-\u0669\u066b\u06f0-\u06f9\u07c0-\u07c9\u0966-\u096f\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be6-\u0bef\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29\u1040-\u1049\u1090-\u1099\u17e0-\u17e9\u1810-\u1819\u1946-\u194f\u19d0-\u19d9\u1a80-\u1a89\u1a90-\u1a99\u1b50-\u1b59\u1bb0-\u1bb9\u1c40-\u1c49\u1c50-\u1c59\ua620-\ua629\ua8d0-\ua8d9\ua900-\ua909\ua9d0-\ua9d9\uaa50-\uaa59\uabf0-\uabf9]",cr:"\\r",lf:"\\n",newline:"[ \f\u0085\u2028\u2029]",extend:"[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f\u109a-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b6-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u192b\u1930-\u193b\u19b0-\u19c0\u19c8\u19c9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f\u1b00-\u1b04\u1b34-\u1b44\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1baa\u1be6-\u1bf3\u1c24-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe3-\uabea\uabec\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]" ,format:"[\u00ad\u0600-\u0603\u06dd\u070f\u17b4\u17b5\u200e\u200f\u202a-\u202e\u2060-\u2064\u206a-\u206f\ufeff\ufff9-\ufffb]",katakana:"[\u3031-\u3035\u309b\u309c\u30a0-\u30fa\u30fc-\u30ff\u31f0-\u31ff\u32d0-\u32fe\u3300-\u3357\uff66-\uff9d]",extendnumlet:"[_\u203f\u2040\u2054\ufe33\ufe34\ufe4d-\ufe4f\uff3f]",punctuation:"[!-#%-*,-\\/:;?@\\[-\\]_{}\u00a1\u00ab\u00b7\u00bb\u00bf;\u00b7\u055a-\u055f\u0589\u058a\u05be\u05c0\u05c3\u05c6\u05f3\u05f4\u0609\u060a\u060c\u060d\u061b\u061e\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964\u0965\u0970\u0df4\u0e4f\u0e5a\u0e5b\u0f04-\u0f12\u0f3a-\u0f3d\u0f85\u0fd0-\u0fd4\u0fd9\u0fda\u104a-\u104f\u10fb\u1361-\u1368\u1400\u166d\u166e\u169b\u169c\u16eb-\u16ed\u1735\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u180a\u1944\u1945\u1a1e\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e\u1c7f\u1cd3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205e\u207d\u207e\u208d\u208e\u3008\u3009\u2768-\u2775\u27c5\u27c6\u27e6-\u27ef\u2983-\u2998\u29d8-\u29db\u29fc\u29fd\u2cf9-\u2cfc\u2cfe\u2cff\u2d70\u2e00-\u2e2e\u2e30\u2e31\u3001-\u3003\u3008-\u3011\u3014-\u301f\u3030\u303d\u30a0\u30fb\ua4fe\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce\ua8cf\ua8f8-\ua8fa\ua92e\ua92f\ua95f\ua9c1-\ua9cd\ua9de\ua9df\uaa5c-\uaa5f\uaade\uaadf\uabeb\ufd3e\ufd3f\ufe10-\ufe19\ufe30-\ufe52\ufe54-\ufe61\ufe63\ufe68\ufe6a\ufe6b\uff01-\uff03\uff05-\uff0a\uff0c-\uff0f\uff1a\uff1b\uff1f\uff20\uff3b-\uff3d\uff3f\uff5b\uff5d\uff5f-\uff65]"}},"3.18.1",{requires:["yui-base"]}); PK\cW $$+3.18.1/model-sync-local/model-sync-local.jsnu[YUI.add('model-sync-local', function (Y, NAME) { /* An extension which provides a sync implementation through locally stored key value pairs, either through the HTML localStorage API or falling back onto an in-memory cache, that can be mixed into a Model or ModelList subclass. @module app @submodule model-sync-local @since 3.13.0 **/ /** An extension which provides a sync implementation through locally stored key value pairs, either through the HTML localStorage API or falling back onto an in-memory cache, that can be mixed into a Model or ModelList subclass. A group of Models/ModelLists is serialized in localStorage by either its class name, or a specified 'root' that is provided. var User = Y.Base.create('user', Y.Model, [Y.ModelSync.Local], { root: 'user' }); var Users = Y.Base.create('users', Y.ModelList, [Y.ModelSync.Local], { model: User, }); @class ModelSync.Local @extensionfor Model @extensionfor ModelList @since 3.13.0 **/ function LocalSync() {} /** Properties that shouldn't be turned into ad-hoc attributes when passed to a Model or ModelList constructor. @property _NON_ATTRS_CFG @type Array @default ['root'] @static @protected @since 3.13.0 **/ LocalSync._NON_ATTRS_CFG = ['root']; /** Feature testing for `localStorage` availability. Will return falsey for browsers with `localStorage`, but that don't actually work, such as iOS Safari in private browsing mode. @property _hasLocalStorage @type Boolean @private **/ LocalSync._hasLocalStorage = (function () { var LS = Y.config.win.localStorage, test = Y.guid(); try { LS.setItem(test, test); LS.removeItem(test); return true; } catch (e) { return false; } })(), /** Object of key/value pairs to fall back on when localStorage is not available. @property _data @type Object @private **/ LocalSync._data = LocalSync._data || {}; /** Cache to quickly access a specific object with a given ID. @property _store @type Array @private **/ LocalSync._store = LocalSync._store || {}; LocalSync.prototype = { // -- Public Methods ------------------------------------------------------- /** Root used as the key inside of localStorage and/or the in-memory store. @property root @type String @default "" @since 3.13.0 **/ root: '', /** Shortcut for access to localStorage. @property storage @type Storage @default null @since 3.13.0 **/ storage: null, // -- Lifecycle Methods ----------------------------------------------------- initializer: function (config) { var store, data; config || (config = {}); if ('root' in config) { this.root = config.root || ''; } // This is checking to see if the sync layer is being applied to // a ModelList, and if so, is looking for a `root` property on its // Model's prototype instead. if (!this.root && this.model && this.model.prototype.root) { this.root = this.model.prototype.root; } if (LocalSync._hasLocalStorage) { this.storage = Y.config.win.localStorage; store = this.storage.getItem(this.root); } else { } // Pull in existing data from localStorage, if possible. // Otherwise, see if there's existing data on the local cache. if (store) { LocalSync._store[this.root] = store.split('|') || []; Y.Array.each(LocalSync._store[this.root], function (id) { LocalSync._data[id] = Y.JSON.parse(this.storage.getItem(id)); }, this); } else { LocalSync._store[this.root] || (LocalSync._store[this.root] = []); } }, // -- Public Methods ----------------------------------------------------------- /** Creates a synchronization layer with the localStorage API, if available. Otherwise, falls back to a in-memory data store. This method is called internally by load(), save(), and destroy(). @method sync @param {String} action Sync action to perform. May be one of the following: * **create**: Store a newly-created model for the first time. * **read** : Load an existing model. * **update**: Update an existing model. * **delete**: Delete an existing model. @param {Object} [options] Sync options @param {Function} [callback] Called when the sync operation finishes. @param {Error|null} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be falsey. @param {Any} [callback.response] The response from our sync. This value will be passed to the parse() method, which is expected to parse it and return an attribute hash. **/ sync: function (action, options, callback) { options || (options = {}); var response, errorInfo; try { switch (action) { case 'read': if (this._isYUIModelList) { response = this._index(options); } else { response = this._show(options); } break; case 'create': response = this._create(options); break; case 'update': response = this._update(options); break; case 'delete': response = this._destroy(options); break; } } catch (error) { errorInfo = error.message; } if (response) { callback(null, response); } else if (errorInfo) { callback(errorInfo); } else { callback("Data not found in LocalStorage"); } }, /** Generate a random GUID for our Models. This can be overriden if you have another method of generating different IDs. @method generateID @protected @param {String} pre Optional GUID prefix **/ generateID: function (pre) { return Y.guid(pre + '_'); }, // -- Protected Methods ---------------------------------------------------- /** Sync method correlating to the "read" operation, for a Model List @method _index @return {Object[]} Array of objects found for that root key @protected @since 3.13.0 **/ _index: function () { var store = LocalSync._store[this.root], data = Y.Array.map(store, function (id) { return LocalSync._data[id]; }); return data; }, /** Sync method correlating to the "read" operation, for a Model @method _show @return {Object} Object found for that root key and model ID @protected @since 3.13.0 **/ _show: function () { return LocalSync._data[this.get('id')] || null; }, /** Sync method correlating to the "create" operation @method _show @return {Object} The new object created. @protected @since 3.13.0 **/ _create: function () { var hash = this.toJSON(); hash.id = this.generateID(this.root); LocalSync._data[hash.id] = hash; if (this.storage) { this.storage.setItem(hash.id, Y.JSON.stringify(hash)); } LocalSync._store[this.root].push(hash.id); this._save(); return hash; }, /** Sync method correlating to the "update" operation @method _update @return {Object} The updated object. @protected @since 3.13.0 **/ _update: function () { var hash = this.toJSON(), id = this.get('id'); LocalSync._data[id] = hash; if (this.storage) { this.storage.setItem(id, hash); } if (Y.Array.indexOf(LocalSync._store[this.root], id) === -1) { LocalSync._store[this.root].push(id); } this._save(); return hash; }, /** Sync method correlating to the "delete" operation. Deletes the data from the in-memory object, and saves into localStorage if available. @method _destroy @protected @since 3.13.0 **/ _destroy: function () { var id = this.get('id'), storage = this.storage; if (!LocalSync._data[id]) { return; } delete LocalSync._data[id]; if (storage) { storage.removeItem(id); } LocalSync._store[this.root] = Y.Array.filter(LocalSync._store[this.root], function (item) { return item.id != id; }); this._save(); return this.toJSON(); }, /** Saves the current in-memory store into a localStorage key/value pair if localStorage is available; otherwise, does nothing. @method _save @protected @since 3.13.0 **/ _save: function () { if (LocalSync._hasLocalStorage && this.storage) { this.storage.setItem( this.root, LocalSync._store[this.root].join('|') ); } } }; // -- Namespace --------------------------------------------------------------- Y.namespace('ModelSync').Local = LocalSync; }, '3.18.1', {"requires": ["model", "json-stringify"]}); PK\,%%13.18.1/model-sync-local/model-sync-local-debug.jsnu[YUI.add('model-sync-local', function (Y, NAME) { /* An extension which provides a sync implementation through locally stored key value pairs, either through the HTML localStorage API or falling back onto an in-memory cache, that can be mixed into a Model or ModelList subclass. @module app @submodule model-sync-local @since 3.13.0 **/ /** An extension which provides a sync implementation through locally stored key value pairs, either through the HTML localStorage API or falling back onto an in-memory cache, that can be mixed into a Model or ModelList subclass. A group of Models/ModelLists is serialized in localStorage by either its class name, or a specified 'root' that is provided. var User = Y.Base.create('user', Y.Model, [Y.ModelSync.Local], { root: 'user' }); var Users = Y.Base.create('users', Y.ModelList, [Y.ModelSync.Local], { model: User, }); @class ModelSync.Local @extensionfor Model @extensionfor ModelList @since 3.13.0 **/ function LocalSync() {} /** Properties that shouldn't be turned into ad-hoc attributes when passed to a Model or ModelList constructor. @property _NON_ATTRS_CFG @type Array @default ['root'] @static @protected @since 3.13.0 **/ LocalSync._NON_ATTRS_CFG = ['root']; /** Feature testing for `localStorage` availability. Will return falsey for browsers with `localStorage`, but that don't actually work, such as iOS Safari in private browsing mode. @property _hasLocalStorage @type Boolean @private **/ LocalSync._hasLocalStorage = (function () { var LS = Y.config.win.localStorage, test = Y.guid(); try { LS.setItem(test, test); LS.removeItem(test); return true; } catch (e) { return false; } })(), /** Object of key/value pairs to fall back on when localStorage is not available. @property _data @type Object @private **/ LocalSync._data = LocalSync._data || {}; /** Cache to quickly access a specific object with a given ID. @property _store @type Array @private **/ LocalSync._store = LocalSync._store || {}; LocalSync.prototype = { // -- Public Methods ------------------------------------------------------- /** Root used as the key inside of localStorage and/or the in-memory store. @property root @type String @default "" @since 3.13.0 **/ root: '', /** Shortcut for access to localStorage. @property storage @type Storage @default null @since 3.13.0 **/ storage: null, // -- Lifecycle Methods ----------------------------------------------------- initializer: function (config) { var store, data; config || (config = {}); if ('root' in config) { this.root = config.root || ''; } // This is checking to see if the sync layer is being applied to // a ModelList, and if so, is looking for a `root` property on its // Model's prototype instead. if (!this.root && this.model && this.model.prototype.root) { this.root = this.model.prototype.root; } if (LocalSync._hasLocalStorage) { this.storage = Y.config.win.localStorage; store = this.storage.getItem(this.root); } else { Y.log("Could not access localStorage.", "warn"); } // Pull in existing data from localStorage, if possible. // Otherwise, see if there's existing data on the local cache. if (store) { LocalSync._store[this.root] = store.split('|') || []; Y.Array.each(LocalSync._store[this.root], function (id) { LocalSync._data[id] = Y.JSON.parse(this.storage.getItem(id)); }, this); } else { LocalSync._store[this.root] || (LocalSync._store[this.root] = []); } }, // -- Public Methods ----------------------------------------------------------- /** Creates a synchronization layer with the localStorage API, if available. Otherwise, falls back to a in-memory data store. This method is called internally by load(), save(), and destroy(). @method sync @param {String} action Sync action to perform. May be one of the following: * **create**: Store a newly-created model for the first time. * **read** : Load an existing model. * **update**: Update an existing model. * **delete**: Delete an existing model. @param {Object} [options] Sync options @param {Function} [callback] Called when the sync operation finishes. @param {Error|null} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be falsey. @param {Any} [callback.response] The response from our sync. This value will be passed to the parse() method, which is expected to parse it and return an attribute hash. **/ sync: function (action, options, callback) { options || (options = {}); var response, errorInfo; try { switch (action) { case 'read': if (this._isYUIModelList) { response = this._index(options); } else { response = this._show(options); } break; case 'create': response = this._create(options); break; case 'update': response = this._update(options); break; case 'delete': response = this._destroy(options); break; } } catch (error) { errorInfo = error.message; } if (response) { callback(null, response); } else if (errorInfo) { callback(errorInfo); } else { callback("Data not found in LocalStorage"); } }, /** Generate a random GUID for our Models. This can be overriden if you have another method of generating different IDs. @method generateID @protected @param {String} pre Optional GUID prefix **/ generateID: function (pre) { return Y.guid(pre + '_'); }, // -- Protected Methods ---------------------------------------------------- /** Sync method correlating to the "read" operation, for a Model List @method _index @return {Object[]} Array of objects found for that root key @protected @since 3.13.0 **/ _index: function () { var store = LocalSync._store[this.root], data = Y.Array.map(store, function (id) { return LocalSync._data[id]; }); return data; }, /** Sync method correlating to the "read" operation, for a Model @method _show @return {Object} Object found for that root key and model ID @protected @since 3.13.0 **/ _show: function () { return LocalSync._data[this.get('id')] || null; }, /** Sync method correlating to the "create" operation @method _show @return {Object} The new object created. @protected @since 3.13.0 **/ _create: function () { var hash = this.toJSON(); hash.id = this.generateID(this.root); LocalSync._data[hash.id] = hash; if (this.storage) { this.storage.setItem(hash.id, Y.JSON.stringify(hash)); } LocalSync._store[this.root].push(hash.id); this._save(); return hash; }, /** Sync method correlating to the "update" operation @method _update @return {Object} The updated object. @protected @since 3.13.0 **/ _update: function () { var hash = this.toJSON(), id = this.get('id'); LocalSync._data[id] = hash; if (this.storage) { this.storage.setItem(id, hash); } if (Y.Array.indexOf(LocalSync._store[this.root], id) === -1) { LocalSync._store[this.root].push(id); } this._save(); return hash; }, /** Sync method correlating to the "delete" operation. Deletes the data from the in-memory object, and saves into localStorage if available. @method _destroy @protected @since 3.13.0 **/ _destroy: function () { var id = this.get('id'), storage = this.storage; if (!LocalSync._data[id]) { return; } delete LocalSync._data[id]; if (storage) { storage.removeItem(id); } LocalSync._store[this.root] = Y.Array.filter(LocalSync._store[this.root], function (item) { return item.id != id; }); this._save(); return this.toJSON(); }, /** Saves the current in-memory store into a localStorage key/value pair if localStorage is available; otherwise, does nothing. @method _save @protected @since 3.13.0 **/ _save: function () { if (LocalSync._hasLocalStorage && this.storage) { this.storage.setItem( this.root, LocalSync._store[this.root].join('|') ); } } }; // -- Namespace --------------------------------------------------------------- Y.namespace('ModelSync').Local = LocalSync; }, '3.18.1', {"requires": ["model", "json-stringify"]}); PK\200/3.18.1/model-sync-local/model-sync-local-min.jsnu[YUI.add("model-sync-local",function(e,t){function n(){}n._NON_ATTRS_CFG=["root"],n._hasLocalStorage=function(){var t=e.config.win.localStorage,n=e.guid();try{return t.setItem(n,n),t.removeItem(n),!0}catch(r){return!1}}(),n._data=n._data||{},n._store=n._store||{},n.prototype={root:"",storage:null,initializer:function(t){var r,i;t||(t={}),"root"in t&&(this.root=t.root||""),!this.root&&this.model&&this.model.prototype.root&&(this.root=this.model.prototype.root),n._hasLocalStorage&&(this.storage=e.config.win.localStorage,r=this.storage.getItem(this.root)),r?(n._store[this.root]=r.split("|")||[],e.Array.each(n._store[this.root],function(t){n._data[t]=e.JSON.parse(this.storage.getItem(t))},this)):n._store[this.root]||(n._store[this.root]=[])},sync:function(e,t,n){t||(t={});var r,i;try{switch(e){case"read":this._isYUIModelList?r=this._index(t):r=this._show(t);break;case"create":r=this._create(t);break;case"update":r=this._update(t);break;case"delete":r=this._destroy(t)}}catch(s){i=s.message}r?n(null,r):i?n(i):n("Data not found in LocalStorage")},generateID:function(t){return e.guid(t+"_")},_index:function(){var t=n._store[this.root],r=e.Array.map(t,function(e){return n._data[e]});return r},_show:function(){return n._data[this.get("id")]||null},_create:function(){var t=this.toJSON();return t.id=this.generateID(this.root),n._data[t.id]=t,this.storage&&this.storage.setItem(t.id,e.JSON.stringify(t)),n._store[this.root].push(t.id),this._save(),t},_update:function(){var t=this.toJSON(),r=this.get("id");return n._data[r]=t,this.storage&&this.storage.setItem(r,t),e.Array.indexOf(n._store[this.root],r)===-1&&n._store[this.root].push(r),this._save(),t},_destroy:function(){var t=this.get("id"),r=this.storage;if(!n._data[t])return;return delete n._data[t],r&&r.removeItem(t),n._store[this.root]=e.Array.filter(n._store[this.root],function(e){return e.id!=t}),this._save(),this.toJSON()},_save:function(){n._hasLocalStorage&&this.storage&&this.storage.setItem(this.root,n._store[this.root].join("|"))}},e.namespace("ModelSync").Local=n},"3.18.1",{requires:["model","json-stringify"]}); PK\ 0P(P(33.18.1/event-custom-base/event-custom-base-debug.jsnu[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 {EventHandle} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); 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 {EventHandle} 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 {EventHandle} 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 {EventHandle} 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) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); 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 */ /** * Flag for the default function to execute only if the * firing event is the current target. This happens only * when using custom event delegation and setting the * flag to `true` mimics the behavior of event delegation * in the DOM. * * @property defaultTargetOnly * @type Boolean * @default false */ /** * 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) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } 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) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); 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 {Number} 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) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); 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) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * 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) { this.log('fireOnce event: ' + this.type + ' already 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) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); 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 {Number} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {Number} 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 {Number} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); 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 || !type || 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] The prefix. Defaults to this._yuievt.config.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. * * this.on("change", this._onChange, this); * * 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. * * this.on({ * "attrChange" : this._onAttrChange, * "change" : this._onChange * }); * * You can also pass an array of event names as the first argument to * subscribe to all listed events with the same callback. * * this.on([ "change", "attrChange" ], this._onChange); * * 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)); // Y.log("Node detected, redirecting with these args: " + args); 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) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); 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() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); 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() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); 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() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); 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: * @param [opts.broadcast=false] {Boolean} whether or not the YUI instance and YUI global * are notified when the event is fired. * @param [opts.bubbles=true] {Boolean} Whether or not this event bubbles. Events can * only bubble if `emitFacade` is true. * @param [opts.context=this] {Object} the default execution context for the listeners. * @param [opts.defaultFn] {Function} the default function to execute when this event * fires if preventDefault was not called. * @param [opts.emitFacade=false] {Boolean} whether or not this event emits a facade. * @param [opts.prefix] {String} the prefix for this targets events, e.g., 'menu' in 'menu:click'. * @param [opts.fireOnce=false] {Boolean} if an event is configured to fire once, * new subscribers after the fire will be notified immediately. * @param [opts.async=false] {Boolean} fireOnce event listeners will fire synchronously * if the event has already fired unless `async` is `true`. * @param [opts.preventable=true] {Boolean} whether or not `preventDefault()` has an effect. * @param [opts.preventedFn] {Function} a function that is executed when `preventDefault()` is called. * @param [opts.queuable=false] {Boolean} whether or not this event can be queued during bubbling. * @param [opts.silent] {Boolean} if silent is true, debug messages are not provided for this event. * @param [opts.stoppedFn] {Function} a function that is executed when stopPropagation is called. * @param [opts.monitored] {Boolean} specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * @param [opts.type] {String} 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 **/ }, '3.18.1', {"requires": ["oop"]}); PK\ //13.18.1/event-custom-base/event-custom-base-min.jsnu[YUI.add("event-custom-base",function(e,t){e.Env.evt={handles:{},plugins:{}};var n=0,r=1,i={objs:null,before:function(t,r,i,s){var o=t,u;return s&&(u=[t,s].concat(e.Array(arguments,4,!0)),o=e.rbind.apply(e,u)),this._inject(n,o,r,i)},after:function(t,n,i,s){var o=t,u;return s&&(u=[t,s].concat(e.Array(arguments,4,!0)),o=e.rbind.apply(e,u)),this._inject(r,o,n,i)},_inject:function(t,n,r,i){var s=e.stamp(r),o,u;return r._yuiaop||(r._yuiaop={}),o=r._yuiaop,o[i]||(o[i]=new e.Do.Method(r,i),r[i]=function(){return o[i].exec.apply(o[i],arguments)}),u=s+e.stamp(n)+i,o[i].register(u,n,t),new e.EventHandle(o[i],u)},detach:function(e){e.detach&&e.detach()}};e.Do=i,i.Method=function(e,t){this.obj=e,this.methodName=t,this.method=e[t],this.before={},this.after={}},i.Method.prototype.register=function(e,t,n){n?this.after[e]=t:this.before[e]=t},i.Method.prototype._delete=function(e){delete this.before[e],delete this.after[e]},i.Method.prototype.exec=function(){var t=e.Array(arguments,0,!0),n,r,s,o=this.before,u=this.after,a=!1;for(n in o)if(o.hasOwnProperty(n)){r=o[n].apply(this.obj,t);if(r)switch(r.constructor){case i.Halt:return r.retVal;case i.AlterArgs:t=r.newArgs;break;case i.Prevent:a=!0;break;default:}}a||(r=this.method.apply(this.obj,t)),i.originalRetVal=r,i.currentRetVal=r;for(n in u)if(u.hasOwnProperty(n)){s=u[n].apply(this.obj,t);if(s&&s.constructor===i.Halt)return s.retVal;s&&s.constructor===i.AlterReturn&&(r=s.newRetVal,i.currentRetVal=r)}return r},i.AlterArgs=function(e,t){this.msg=e,this.newArgs=t},i.AlterReturn=function(e,t){this.msg=e,this.newRetVal=t},i.Halt=function(e,t){this.msg=e,this.retVal=t},i.Prevent=function(e){this.msg=e},i.Error=i.Halt;var s=e.Array,o="after",u=["broadcast","monitored","bubbles","context","contextFn","currentTarget","defaultFn","defaultTargetOnly","details","emitFacade","fireOnce","async","host","preventable","preventedFn","queuable","silent","stoppedFn","target","type"],a=s.hash(u),f=Array.prototype.slice,l=9,c="yui:log",h=function(e,t,n){var r;for(r in t)a[r]&&(n||!(r in e))&&(e[r]=t[r]);return e};e.CustomEvent=function(t,n){this._kds=e.CustomEvent.keepDeprecatedSubs,this.id=e.guid(),this.type=t,this.silent=this.logSystem=t===c,this._kds&&(this.subscribers={},this.afters={}),n&&h(this,n,!0)},e.CustomEvent.keepDeprecatedSubs=!1,e.CustomEvent.mixConfigs=h,e.CustomEvent.prototype={constructor:e.CustomEvent,signature:l,context:e,preventable:!0,bubbles:!0,hasSubs:function(e){var t=0,n=0,r=this._subscribers,i=this._afters,s=this.sibling;return r&&(t=r.length),i&&(n=i.length),s&&(r=s._subscribers,i=s._afters,r&&(t+=r.length),i&&(n+=i.length)),e?e==="after"?n:t:t+n},monitor:function(e){this.monitored=!0;var t=this.id+"|"+this.type+"_"+e,n=f.call(arguments,0);return n[0]=t,this.host.on.apply(this.host,n)},getSubs:function(){var e=this.sibling,t=this._subscribers,n=this._afters,r,i;return e&&(r=e._subscribers,i=e._afters),r?t?t=t.concat(r):t=r.concat():t?t=t.concat():t=[],i?n?n=n.concat(i):n=i.concat():n?n=n.concat():n=[],[t,n]},applyConfig:function(e,t){h(this,e,t)},_on:function(t,n,r,i){var s=new e.Subscriber(t,n,r,i),u;return this.fireOnce&&this.fired&&(u=this.firedWith,this.emitFacade&&this._addFacadeToArgs&&this._addFacadeToArgs(u),this.async?setTimeout(e.bind(this._notify,this,s,u),0):this._notify(s,u)),i===o?(this._afters||(this._afters=[]),this._afters.push(s)):(this._subscribers||(this._subscribers=[]),this._subscribers.push(s)),this._kds&&(i===o?this.afters[s.id]=s:this.subscribers[s.id]=s),new e.EventHandle(this,s)},subscribe:function(e,t){var n=arguments.length>2?f.call(arguments,2):null;return this._on(e,t,n,!0)},on:function(e,t){var n=arguments.length>2?f.call(arguments,2):null;return this.monitored&&this.host&&this.host._monitor("attach",this,{args:arguments}),this._on(e,t,n,!0)},after:function(e,t){var n=arguments.length>2?f.call(arguments,2):null;return this._on(e,t,n,o)},detach:function(e,t){if(e&&e.detach)return e.detach();var n,r,i=0,s=this._subscribers,o=this._afters;if(s)for(n=s.length;n>=0;n--)r=s[n],r&&(!e||e===r.fn)&&(this._delete(r,s,n),i++);if(o)for(n=o.length;n>=0;n--)r=o[n],r&&(!e||e===r.fn)&&(this._delete(r,o,n),i++);return i},unsubscribe:function(){return this.detach.apply(this,arguments)},_notify:function(e,t,n){var r;return r=e.notify(t,this),!1===r||this.stopped>1?!1:!0},log:function(e,t){},fire:function(){var e=[];return e.push.apply(e,arguments),this._fire(e)},_fire:function(e){return this.fireOnce&&this.fired?!0:(this.fired=!0,this.fireOnce&&(this.firedWith=e),this.emitFacade?this.fireComplex(e):this.fireSimple(e))},fireSimple:function(e){this.stopped=0,this.prevented=0;if(this.hasSubs()){var t=this.getSubs();this._procSubs(t[0],e),this._procSubs(t[1],e)}return this.broadcast&&this._broadcast(e),this.stopped?!1:!0},fireComplex:function(e){return e[0]=e[0]||{},this.fireSimple(e)},_procSubs:function(e,t,n){var r,i,s;for(i=0,s=e.length;i-1?e:t+d+e},w=e.cached(function(e,t){var n=e,r,i,s;return p.isString(n)?(s=n.indexOf(m),s>-1&&(i=!0,n=n.substr(m.length)),s=n.indexOf(v),s>-1&&(r=n.substr(0,s),n=n.substr(s+1),n==="*"&&(n=null)),[r,t?b(n,t):n,i,n]):n}),E=function(t){var n=this._yuievt,r;n||(n=this._yuievt={events:{},targets:null,config:{host:this,context:this},chain:e.config.chain}),r=n.config,t&&(h(r,t,!0),t.chain!==undefined&&(n.chain=t.chain),t.prefix&&(r.prefix=t.prefix))};E.prototype={constructor:E,once:function(){var e=this.on.apply(this,arguments);return e.batch(function(e){e.sub&&(e.sub.once=!0)}),e},onceAfter:function(){var e=this.after.apply(this,arguments);return e.batch(function(e){e.sub&&(e.sub.once=!0)}),e},parseType:function(e,t){return w(e,t||this._yuievt.config.prefix)},on:function(t,n,r){var i=this._yuievt,s=w(t,i.config.prefix),o,u,a,l,c,h,d,v=e.Env.evt.handles,g,y,b,E=e.Node,S,x,T;this._monitor("attach",s[1],{args:arguments,category:s[0],after:s[2]});if(p.isObject(t))return p.isFunction(t)?e.Do.before.apply(e.Do,arguments):(o=n,u=r,a=f.call(arguments,0),l=[],p.isArray(t)&&(T=!0),g=t._after,delete t._after,e.each(t,function(e,t){p.isObject(e)&&(o=e.fn||(p.isFunction(e)?e:o),u=e.context||u);var n=g?m:"";a[0]=n+(T?e:t),a[1]=o,a[2]=u,l.push(this.on.apply(this,a))},this),i.chain?this:new e.EventHandle(l));h=s[0],g=s[2],b=s[3];if(E&&e.instanceOf(this,E)&&b in E.DOM_EVENTS)return a=f.call(arguments,0),a.splice(2,0,E.getDOMNode(this)),e.on.apply(e,a);t=s[1];if(e.instanceOf(this,YUI)){y=e.Env.evt.plugins[t],a=f.call(arguments,0),a[0]=b,E&&(S=a[2],e.instanceOf(S,e.NodeList)?S=e.NodeList.getDOMNodes(S):e.instanceOf(S,E)&&(S=E.getDOMNode(S)),x=b in E.DOM_EVENTS,x&&(a[2]=S));if(y)d=y.on.apply(e,a);else if(!t||x)d=e.Event._attach(a)}return d||(c=i.events[t]||this.publish(t),d=c._on(n,r,arguments.length>3?f.call(arguments,3):null,g?"after":!0),t.indexOf("*:")!==-1&&(this._hasSiblings=!0)),h&&(v[h]=v[h]||{},v[h][t]=v[h][t]||[],v[h][t].push(d)),i.chain?this:d},subscribe:function(){return this.on.apply(this,arguments)},detach:function(t,n,r){var i=this._yuievt.events,s,o=e.Node,u=o&&e.instanceOf(this,o);if(!t&&this!==e){for(s in i)i.hasOwnProperty(s)&&i[s].detach(n,r);return u&&e.Event.purgeElement(o.getDOMNode(this)),this}var a=w(t,this._yuievt.config.prefix),l=p.isArray(a)?a[0]:null,c=a?a[3]:null,h,d=e.Env.evt.handles,v,m,g,y,b=function(e,t,n){var r=e[t],i,s;if(r)for(s=r.length-1;s>=0;--s)i=r[s].evt,(i.host===n||i.el===n)&&r[s].detach()};if(l){m=d[l],t=a[1],v=u?e.Node.getDOMNode(this):this;if(m){if(t)b(m,t,v);else for(s in m)m.hasOwnProperty(s)&&b(m,s,v);return this}}else{if(p.isObject(t)&&t.detach)return t.detach(),this;if(u&&(!c||c in o.DOM_EVENTS))return g=f.call(arguments,0),g[2]=o.getDOMNode(this),e.detach.apply(e,g),this}h=e.Env.evt.plugins[c];if(e.instanceOf(this,YUI)){g=f.call(arguments,0);if(h&&h.detach)return h.detach.apply(e,g),this;if(!t||!h&&o&&t in o.DOM_EVENTS)return g[0]=t,e.Event.detach.apply(e.Event,g),this}return y=i[a[1]],y&&y.detach(n,r),this},unsubscribe:function(){return this.detach.apply(this,arguments)},detachAll:function(e){return this.detach(e)},unsubscribeAll:function(){return this.detachAll.apply(this,arguments)},publish:function(t,n){var r,i=this._yuievt,s=i.config,o=s.prefix;return typeof t=="string"?(o&&(t=b(t,o)),r=this._publish(t,s,n)):(r={},e.each(t,function(e,t){o&&(t=b(t,o)),r[t]=this._publish(t,s,e||n)},this)),r},_getFullType:function(e){var t=this._yuievt.config.prefix;return t?t+d+e:e},_publish:function(t,n,r){var i,s=this._yuievt,o=s.config,u=o.host,a=o.context,f=s.events;return i=f[t],(o.monitored&&!i||i&&i.monitored)&&this._monitor("publish",t,{args:arguments}),i||(i=f[t]=new e.CustomEvent(t,n),n||(i.host=u,i.context=a)),r&&h(i,r,!0),i},_monitor:function(e,t,n){var r,i,s;if(t){typeof t=="string"?(s=t,i=this.getEvent(t,!0)):(i=t,s=t.type);if(this._yuievt.config.monitored&&(!i||i.monitored)||i&&i.monitored)r=s+"_"+e,n.monitored=e,this.fire.call(this,r,n)}},fire:function(e){var t=typeof e=="string",n=arguments.length,r=e,i=this._yuievt,s=i.config,o=s.prefix,u,a,l,c;t&&n<=3?n===2?c=[arguments[1]]:n===3?c=[arguments[1],arguments[2]]:c=[]:c=f.call(arguments,t?1:0),t||(r=e&&e.type),o&&(r=b(r,o)),a=i.events[r],this._hasSiblings&&(l=this.getSibling(r,a),l&&!a&&(a=this.publish(r))),(s.monitored&&(!a||a.monitored)||a&&a.monitored)&&this._monitor("fire",a||r,{args:c});if(!a){if(i.hasTargets)return this.bubble({type:r},c,this);u=!0}else l&&(a.sibling=l),u=a._fire(c);return i.chain?this:u},getSibling:function(e,t){var n;return e.indexOf(d)>-1&&(e=y(e),n=this.getEvent(e,!0),n&&(n.applyConfig(t),n.bubbles=!1,n.broadcast=0)),n},getEvent:function(e,t){var n,r;return t||(n=this._yuievt.config.prefix,e=n?b(e,n):e),r=this._yuievt.events,r[e]||null},after:function(t,n){var r=f.call(arguments,0);switch(p.type(t)){case"function":return e.Do.after.apply(e.Do,arguments);case"array":case"object":r[0]._after=!0;break;default:r[0]=m+t}return this.on.apply(this,r)},before:function(){return this.on.apply (this,arguments)}},e.EventTarget=E,e.mix(e,E.prototype),E.call(e,{bubbles:!1}),YUI.Env.globalEvents=YUI.Env.globalEvents||new E,e.Global=YUI.Env.globalEvents},"3.18.1",{requires:["oop"]}); PK\g##-3.18.1/event-custom-base/event-custom-base.jsnu[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 {EventHandle} 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 {EventHandle} 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 {EventHandle} 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 {EventHandle} 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 */ /** * Flag for the default function to execute only if the * firing event is the current target. This happens only * when using custom event delegation and setting the * flag to `true` mimics the behavior of event delegation * in the DOM. * * @property defaultTargetOnly * @type Boolean * @default false */ /** * 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 {Number} 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 {Number} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {Number} 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 {Number} 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 || !type || 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] The prefix. Defaults to this._yuievt.config.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. * * this.on("change", this._onChange, this); * * 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. * * this.on({ * "attrChange" : this._onAttrChange, * "change" : this._onChange * }); * * You can also pass an array of event names as the first argument to * subscribe to all listed events with the same callback. * * this.on([ "change", "attrChange" ], this._onChange); * * 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: * @param [opts.broadcast=false] {Boolean} whether or not the YUI instance and YUI global * are notified when the event is fired. * @param [opts.bubbles=true] {Boolean} Whether or not this event bubbles. Events can * only bubble if `emitFacade` is true. * @param [opts.context=this] {Object} the default execution context for the listeners. * @param [opts.defaultFn] {Function} the default function to execute when this event * fires if preventDefault was not called. * @param [opts.emitFacade=false] {Boolean} whether or not this event emits a facade. * @param [opts.prefix] {String} the prefix for this targets events, e.g., 'menu' in 'menu:click'. * @param [opts.fireOnce=false] {Boolean} if an event is configured to fire once, * new subscribers after the fire will be notified immediately. * @param [opts.async=false] {Boolean} fireOnce event listeners will fire synchronously * if the event has already fired unless `async` is `true`. * @param [opts.preventable=true] {Boolean} whether or not `preventDefault()` has an effect. * @param [opts.preventedFn] {Function} a function that is executed when `preventDefault()` is called. * @param [opts.queuable=false] {Boolean} whether or not this event can be queued during bubbling. * @param [opts.silent] {Boolean} if silent is true, debug messages are not provided for this event. * @param [opts.stoppedFn] {Function} a function that is executed when stopPropagation is called. * @param [opts.monitored] {Boolean} specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * @param [opts.type] {String} 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 **/ }, '3.18.1', {"requires": ["oop"]}); PK\77%3.18.1/event-hover/event-hover-min.jsnu[YUI.add("event-hover",function(e,t){var n=e.Lang.isFunction,r=function(){},i={processArgs:function(e){var t=n(e[2])?2:3;return n(e[t])?e.splice(t,1)[0]:r},on:function(e,t,n,r){var i=t.args?t.args.slice():[];i.unshift(null),t._detach=e[r?"delegate":"on"]({mouseenter:function(e){e.phase="over",n.fire(e)},mouseleave:function(e){var n=t.context||this;i[0]=e,e.type="hover",e.phase="out",t._extra.apply(n,i)}},r)},detach:function(e,t,n){t._detach.detach()}};i.delegate=i.on,i.detachDelegate=i.detach,e.Event.define("hover",i)},"3.18.1",{requires:["event-mouseenter"]}); PK\D''3.18.1/event-hover/event-hover-debug.jsnu[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); }, '3.18.1', {"requires": ["event-mouseenter"]}); PK\D'!3.18.1/event-hover/event-hover.jsnu[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); }, '3.18.1', {"requires": ["event-mouseenter"]}); PK\xSS3.18.1/series-pie/series-pie.jsnu[YUI.add('series-pie', function (Y, NAME) { /** * Provides functionality for creating a pie series. * * @module charts * @submodule series-pie */ /** * PieSeries visualizes data as a circular chart divided into wedges which represent data as a * percentage of a whole. * * @class PieSeries * @constructor * @extends SeriesBase * @uses Plots * @param {Object} config (optional) Configuration parameters. * @submodule series-pie */ var CONFIG = Y.config, DOCUMENT = CONFIG.doc, _getClassName = Y.ClassNameManager.getClassName, SERIES_MARKER = _getClassName("seriesmarker"); Y.PieSeries = Y.Base.create("pieSeries", Y.SeriesBase, [Y.Plots], { /** * Image map used for interactivity when rendered with canvas. * * @property _map * @type HTMLElement * @private */ _map: null, /** * Image used for image map when rendered with canvas. * * @property _image * @type HTMLElement * @private */ _image: null, /** * Creates or updates the image map when rendered with canvas. * * @method _setMap * @private */ _setMap: function() { var id = "pieHotSpotMapi_" + Math.round(100000 * Math.random()), graph = this.get("graph"), graphic, cb, areaNode; if(graph) { cb = graph.get("contentBox"); } else { graphic = this.get("graphic"); cb = graphic.get("node"); } if(this._image) { cb.removeChild(this._image); while(this._areaNodes && this._areaNodes.length > 0) { areaNode = this._areaNodes.shift(); this._map.removeChild(areaNode); } cb.removeChild(this._map); } this._image = DOCUMENT.createElement("img"); this._image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAABCAYAAAD9yd/wAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSB" + "JbWFnZVJlYWR5ccllPAAAABJJREFUeNpiZGBgSGPAAgACDAAIkABoFyloZQAAAABJRU5ErkJggg=="; cb.appendChild(this._image); this._image.style.position = "absolute"; this._image.style.left = "0px"; this._image.style.top = "0px"; this._image.setAttribute("usemap", "#" + id); this._image.style.zIndex = 3; this._image.style.opacity = 0; this._image.setAttribute("alt", "imagemap"); this._map = DOCUMENT.createElement("map"); cb.appendChild(this._map); this._map.setAttribute("name", id); this._map.setAttribute("id", id); this._areaNodes = []; }, /** * Storage for `categoryDisplayName` attribute. * * @property _categoryDisplayName * @private */ _categoryDisplayName: null, /** * Storage for `valueDisplayName` attribute. * * @property _valueDisplayName * @private */ _valueDisplayName: null, /** * Adds event listeners. * * @method addListeners * @private */ addListeners: function() { var categoryAxis = this.get("categoryAxis"), valueAxis = this.get("valueAxis"); if(categoryAxis) { categoryAxis.after("dataReady", Y.bind(this._categoryDataChangeHandler, this)); categoryAxis.after("dataUpdate", Y.bind(this._categoryDataChangeHandler, this)); } if(valueAxis) { valueAxis.after("dataReady", Y.bind(this._valueDataChangeHandler, this)); valueAxis.after("dataUpdate", Y.bind(this._valueDataChangeHandler, this)); } this.after("categoryAxisChange", this.categoryAxisChangeHandler); this.after("valueAxisChange", this.valueAxisChangeHandler); this._stylesChangeHandle = this.after("stylesChange", this._updateHandler); this._visibleChangeHandle = this.after("visibleChange", this._handleVisibleChange); }, /** * Draws the series. * * @method validate * @private */ validate: function() { this.draw(); this._renderered = true; }, /** * Event handler for the categoryAxisChange event. * * @method _categoryAxisChangeHandler * @param {Object} e Event object. * @private */ _categoryAxisChangeHandler: function() { var categoryAxis = this.get("categoryAxis"); categoryAxis.after("dataReady", Y.bind(this._categoryDataChangeHandler, this)); categoryAxis.after("dataUpdate", Y.bind(this._categoryDataChangeHandler, this)); }, /** * Event handler for the valueAxisChange event. * * @method _valueAxisChangeHandler * @param {Object} e Event object. * @private */ _valueAxisChangeHandler: function() { var valueAxis = this.get("valueAxis"); valueAxis.after("dataReady", Y.bind(this._valueDataChangeHandler, this)); valueAxis.after("dataUpdate", Y.bind(this._valueDataChangeHandler, this)); }, /** * Constant used to generate unique id. * * @property GUID * @type String * @private */ GUID: "pieseries", /** * Event handler for categoryDataChange event. * * @method _categoryDataChangeHandler * @param {Object} event Event object. * @private */ _categoryDataChangeHandler: function() { if(this._rendered && this.get("categoryKey") && this.get("valueKey")) { this.draw(); } }, /** * Event handler for valueDataChange event. * * @method _valueDataChangeHandler * @param {Object} event Event object. * @private */ _valueDataChangeHandler: function() { if(this._rendered && this.get("categoryKey") && this.get("valueKey")) { this.draw(); } }, /** * Returns the sum of all values for the series. * * @method getTotalValues * @return Number */ getTotalValues: function() { var total = this.get("valueAxis").getTotalByKey(this.get("valueKey")); return total; }, /** * Draws the series. Overrides the base implementation. * * @method draw * @protected */ draw: function() { var w = this.get("width"), h = this.get("height"); if(isFinite(w) && isFinite(h) && w > 0 && h > 0) { this._rendered = true; if(this._drawing) { this._callLater = true; return; } this._drawing = true; this._callLater = false; this.drawSeries(); this._drawing = false; if(this._callLater) { this.draw(); } else { this.fire("drawingComplete"); } } }, /** * Draws the markers * * @method drawPlots * @protected */ drawPlots: function() { var values = this.get("valueAxis").getDataByKey(this.get("valueKey")).concat(), totalValue = 0, itemCount = values.length, styles = this.get("styles").marker, fillColors = styles.fill.colors, fillAlphas = styles.fill.alphas || ["1"], borderColors = styles.border.colors, borderWeights = [styles.border.weight], borderAlphas = [styles.border.alpha], tbw = borderWeights.concat(), tbc = borderColors.concat(), tba = borderAlphas.concat(), tfc, tfa, padding = styles.padding, graphic = this.get("graphic"), minDimension = Math.min(graphic.get("width"), graphic.get("height")), w = minDimension - (padding.left + padding.right), h = minDimension - (padding.top + padding.bottom), startAngle = -90, halfWidth = w / 2, halfHeight = h / 2, radius = Math.min(halfWidth, halfHeight), i = 0, value, angle = 0, lc, la, lw, wedgeStyle, marker, graphOrder = this.get("graphOrder") || 0, isCanvas = Y.Graphic.NAME === "canvasGraphic"; for(; i < itemCount; ++i) { value = parseFloat(values[i]); values.push(value); if(!isNaN(value)) { totalValue += value; } } tfc = fillColors ? fillColors.concat() : null; tfa = fillAlphas ? fillAlphas.concat() : null; this._createMarkerCache(); if(isCanvas) { this._setMap(); this._image.width = w; this._image.height = h; } for(i = 0; i < itemCount; i++) { value = values[i]; if(totalValue === 0) { angle = 360 / values.length; } else { angle = 360 * (value / totalValue); } if(tfc && tfc.length < 1) { tfc = fillColors.concat(); } if(tfa && tfa.length < 1) { tfa = fillAlphas.concat(); } if(tbw && tbw.length < 1) { tbw = borderWeights.concat(); } if(tbw && tbc.length < 1) { tbc = borderColors.concat(); } if(tba && tba.length < 1) { tba = borderAlphas.concat(); } lw = tbw ? tbw.shift() : null; lc = tbc ? tbc.shift() : null; la = tba ? tba.shift() : null; startAngle += angle; wedgeStyle = { border: { color:lc, weight:lw, alpha:la }, fill: { color:tfc ? tfc.shift() : this._getDefaultColor(i, "slice"), alpha:tfa ? tfa.shift() : null }, type: "pieslice", arc: angle, radius: radius, startAngle: startAngle, cx: halfWidth, cy: halfHeight, width: w, height: h }; marker = this.getMarker(wedgeStyle, graphOrder, i); if(isCanvas) { this._addHotspot(wedgeStyle, graphOrder, i); } } this._clearMarkerCache(); }, /** * @protected * * Method used by `styles` setter. Overrides base implementation. * * @method _setStyles * @param {Object} newStyles Hash of properties to update. * @return Object */ _setStyles: function(val) { if(!val.marker) { val = {marker:val}; } val = this._parseMarkerStyles(val); return Y.PieSeries.superclass._mergeStyles.apply(this, [val, this._getDefaultStyles()]); }, /** * Adds an interactive map when rendering in canvas. * * @method _addHotspot * @param {Object} cfg Object containing data used to draw the hotspot * @param {Number} seriesIndex Index of series in the `seriesCollection`. * @param {Number} index Index of the marker using the hotspot. * @private */ _addHotspot: function(cfg, seriesIndex, index) { var areaNode = DOCUMENT.createElement("area"), i = 1, x = cfg.cx, y = cfg.cy, arc = cfg.arc, startAngle = cfg.startAngle - arc, endAngle = cfg.startAngle, radius = cfg.radius, ax = x + Math.cos(startAngle / 180 * Math.PI) * radius, ay = y + Math.sin(startAngle / 180 * Math.PI) * radius, bx = x + Math.cos(endAngle / 180 * Math.PI) * radius, by = y + Math.sin(endAngle / 180 * Math.PI) * radius, numPoints = Math.floor(arc/10) - 1, divAngle = (arc/(Math.floor(arc/10)) / 180) * Math.PI, angleCoord = Math.atan((ay - y)/(ax - x)), pts = x + ", " + y + ", " + ax + ", " + ay, cosAng, sinAng, multDivAng; for(i = 1; i <= numPoints; ++i) { multDivAng = divAngle * i; cosAng = Math.cos(angleCoord + multDivAng); sinAng = Math.sin(angleCoord + multDivAng); if(startAngle <= 90) { pts += ", " + (x + (radius * Math.cos(angleCoord + (divAngle * i)))); pts += ", " + (y + (radius * Math.sin(angleCoord + (divAngle * i)))); } else { pts += ", " + (x - (radius * Math.cos(angleCoord + (divAngle * i)))); pts += ", " + (y - (radius * Math.sin(angleCoord + (divAngle * i)))); } } pts += ", " + bx + ", " + by; pts += ", " + x + ", " + y; this._map.appendChild(areaNode); areaNode.setAttribute("class", SERIES_MARKER); areaNode.setAttribute("id", "hotSpot_" + seriesIndex + "_" + index); areaNode.setAttribute("shape", "polygon"); areaNode.setAttribute("coords", pts); this._areaNodes.push(areaNode); }, /** * Resizes and positions markers based on a mouse interaction. * * @method updateMarkerState * @param {String} type state of the marker * @param {Number} i index of the marker * @protected */ updateMarkerState: function(type, i) { if(this._markers[i]) { var state = this._getState(type), markerStyles, indexStyles, marker = this._markers[i], styles = this.get("styles").marker; markerStyles = state === "off" || !styles[state] ? styles : styles[state]; indexStyles = this._mergeStyles(markerStyles, {}); indexStyles.fill.color = indexStyles.fill.colors[i % indexStyles.fill.colors.length]; indexStyles.fill.alpha = indexStyles.fill.alphas[i % indexStyles.fill.alphas.length]; marker.set(indexStyles); } }, /** * Creates a shape to be used as a marker. * * @method _createMarker * @param {Object} styles Hash of style properties. * @return Shape * @private */ _createMarker: function(styles) { var graphic = this.get("graphic"), marker, cfg = this._copyObject(styles); marker = graphic.addShape(cfg); marker.addClass(SERIES_MARKER); return marker; }, /** * Creates a cache of markers for reuse. * * @method _createMarkerCache * @private */ _clearMarkerCache: function() { var len = this._markerCache.length, i = 0, marker; for(; i < len; ++i) { marker = this._markerCache[i]; if(marker) { marker.destroy(); } } this._markerCache = []; }, /** * Gets the default style values for the markers. * * @method _getPlotDefaults * @return Object * @private */ _getPlotDefaults: function() { var defs = { padding:{ top: 0, left: 0, right: 0, bottom: 0 }, fill:{ alphas:["1"] }, border: { weight: 0, alpha: 1 } }; defs.fill.colors = this._defaultSliceColors; defs.border.colors = this._defaultBorderColors; return defs; } }, { ATTRS: { /** * Read-only attribute indicating the type of series. * * @attribute type * @type String * @default pie */ type: { value: "pie" }, /** * Order of this instance of this `type`. * * @attribute order * @type Number */ order: {}, /** * Reference to the `Graph` in which the series is drawn into. * * @attribute graph * @type Graph */ graph: {}, /** * Reference to the `Axis` instance used for assigning * category values to the graph. * * @attribute categoryAxis * @type Axis */ categoryAxis: { value: null, validator: function(value) { return value !== this.get("categoryAxis"); } }, /** * Reference to the `Axis` instance used for assigning * series values to the graph. * * @attribute categoryAxis * @type Axis */ valueAxis: { value: null, validator: function(value) { return value !== this.get("valueAxis"); } }, /** * Indicates which array to from the hash of value arrays in * the category `Axis` instance. * * @attribute categoryKey * @type String */ categoryKey: { value: null, validator: function(value) { return value !== this.get("categoryKey"); } }, /** * Indicates which array to from the hash of value arrays in * the value `Axis` instance. * * @attribute valueKey * @type String */ valueKey: { value: null, validator: function(value) { return value !== this.get("valueKey"); } }, /** * Name used for for displaying category data * * @attribute categoryDisplayName * @type String */ categoryDisplayName: { setter: function(val) { this._categoryDisplayName = val; return val; }, getter: function() { return this._categoryDisplayName || this.get("categoryKey"); } }, /** * Name used for for displaying value data * * @attribute valueDisplayName * @type String */ valueDisplayName: { setter: function(val) { this._valueDisplayName = val; return val; }, getter: function() { return this._valueDisplayName || this.get("valueKey"); } }, /** * @attribute slices * @type Array * @private */ slices: null /** * Style properties used for drawing markers. This attribute is inherited from `MarkerSeries`. Below are the default * values: *
*
fill
A hash containing the following values: *
*
colors
An array of colors to be used for the marker fills. The color for each marker is * retrieved from the array below:
* `["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"]` *
*
alphas
An array of alpha references (Number from 0 to 1) indicating the opacity of each marker * fill. The default value is [1].
*
*
*
border
A hash containing the following values: *
*
color
An array of colors to be used for the marker borders. The color for each marker is * retrieved from the array below:
* `["#205096", "#b38206", "#000000", "#94001e", "#9d6fa0", "#e55b00", "#5e85c9", "#adab9e", "#6ac291", "#006457"]` *
alpha
Number from 0 to 1 indicating the opacity of the marker border. The default value is 1.
*
weight
Number indicating the width of the border. The default value is 1.
*
*
*
over
hash containing styles for markers when highlighted by a `mouseover` event. The default * values for each style is null. When an over style is not set, the non-over value will be used. For example, * the default value for `marker.over.fill.color` is equivalent to `marker.fill.color`.
*
* * @attribute styles * @type Object */ } }); }, '3.18.1', {"requires": ["series-base", "series-plot-util"]}); PK\K#3.18.1/series-pie/series-pie-min.jsnu[YUI.add("series-pie",function(e,t){var n=e.config,r=n.doc,i=e.ClassNameManager.getClassName,s=i("seriesmarker");e.PieSeries=e.Base.create("pieSeries",e.SeriesBase,[e.Plots],{_map:null,_image:null,_setMap:function(){var e="pieHotSpotMapi_"+Math.round(1e5*Math.random()),t=this.get("graph"),n,i,s;t?i=t.get("contentBox"):(n=this.get("graphic"),i=n.get("node"));if(this._image){i.removeChild(this._image);while(this._areaNodes&&this._areaNodes.length>0)s=this._areaNodes.shift(),this._map.removeChild(s);i.removeChild(this._map)}this._image=r.createElement("img"),this._image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAABCAYAAAD9yd/wAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAABJJREFUeNpiZGBgSGPAAgACDAAIkABoFyloZQAAAABJRU5ErkJggg==",i.appendChild(this._image),this._image.style.position="absolute",this._image.style.left="0px",this._image.style.top="0px",this._image.setAttribute("usemap","#"+e),this._image.style.zIndex=3,this._image.style.opacity=0,this._image.setAttribute("alt","imagemap"),this._map=r.createElement("map"),i.appendChild(this._map),this._map.setAttribute("name",e),this._map.setAttribute("id",e),this._areaNodes=[]},_categoryDisplayName:null,_valueDisplayName:null,addListeners:function(){var t=this.get("categoryAxis"),n=this.get("valueAxis");t&&(t.after("dataReady",e.bind(this._categoryDataChangeHandler,this)),t.after("dataUpdate",e.bind(this._categoryDataChangeHandler,this))),n&&(n.after("dataReady",e.bind(this._valueDataChangeHandler,this)),n.after("dataUpdate",e.bind(this._valueDataChangeHandler,this))),this.after("categoryAxisChange",this.categoryAxisChangeHandler),this.after("valueAxisChange",this.valueAxisChangeHandler),this._stylesChangeHandle=this.after("stylesChange",this._updateHandler),this._visibleChangeHandle=this.after("visibleChange",this._handleVisibleChange)},validate:function(){this.draw(),this._renderered=!0},_categoryAxisChangeHandler:function(){var t=this.get("categoryAxis");t.after("dataReady",e.bind(this._categoryDataChangeHandler,this)),t.after("dataUpdate",e.bind(this._categoryDataChangeHandler,this))},_valueAxisChangeHandler:function(){var t=this.get("valueAxis");t.after("dataReady",e.bind(this._valueDataChangeHandler,this)),t.after("dataUpdate",e.bind(this._valueDataChangeHandler,this))},GUID:"pieseries",_categoryDataChangeHandler:function(){this._rendered&&this.get("categoryKey")&&this.get("valueKey")&&this.draw()},_valueDataChangeHandler:function(){this._rendered&&this.get("categoryKey")&&this.get("valueKey")&&this.draw()},getTotalValues:function(){var e=this.get("valueAxis").getTotalByKey(this.get("valueKey"));return e},draw:function(){var e=this.get("width"),t=this.get("height");if(isFinite(e)&&isFinite(t)&&e>0&&t>0){this._rendered=!0;if(this._drawing){this._callLater=!0;return}this._drawing=!0,this._callLater=!1,this.drawSeries(),this._drawing=!1,this._callLater?this.draw():this.fire("drawingComplete")}},drawPlots:function(){var t=this.get("valueAxis").getDataByKey(this.get("valueKey")).concat(),n=0,r=t.length,i=this.get("styles").marker,s=i.fill.colors,o=i.fill.alphas||["1"],u=i.border.colors,a=[i.border.weight],f=[i.border.alpha],l=a.concat(),c=u.concat(),h=f.concat(),p,d,v=i.padding,m=this.get("graphic"),g=Math.min(m.get("width"),m.get("height")),y=g-(v.left+v.right),b=g-(v.top+v.bottom),w=-90,E=y/2,S=b/2,x=Math.min(E,S),T=0,N,C=0,k,L,A,O,M,_=this.get("graphOrder")||0,D=e.Graphic.NAME==="canvasGraphic";for(;T 0) { areaNode = this._areaNodes.shift(); this._map.removeChild(areaNode); } cb.removeChild(this._map); } this._image = DOCUMENT.createElement("img"); this._image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAABCAYAAAD9yd/wAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSB" + "JbWFnZVJlYWR5ccllPAAAABJJREFUeNpiZGBgSGPAAgACDAAIkABoFyloZQAAAABJRU5ErkJggg=="; cb.appendChild(this._image); this._image.style.position = "absolute"; this._image.style.left = "0px"; this._image.style.top = "0px"; this._image.setAttribute("usemap", "#" + id); this._image.style.zIndex = 3; this._image.style.opacity = 0; this._image.setAttribute("alt", "imagemap"); this._map = DOCUMENT.createElement("map"); cb.appendChild(this._map); this._map.setAttribute("name", id); this._map.setAttribute("id", id); this._areaNodes = []; }, /** * Storage for `categoryDisplayName` attribute. * * @property _categoryDisplayName * @private */ _categoryDisplayName: null, /** * Storage for `valueDisplayName` attribute. * * @property _valueDisplayName * @private */ _valueDisplayName: null, /** * Adds event listeners. * * @method addListeners * @private */ addListeners: function() { var categoryAxis = this.get("categoryAxis"), valueAxis = this.get("valueAxis"); if(categoryAxis) { categoryAxis.after("dataReady", Y.bind(this._categoryDataChangeHandler, this)); categoryAxis.after("dataUpdate", Y.bind(this._categoryDataChangeHandler, this)); } if(valueAxis) { valueAxis.after("dataReady", Y.bind(this._valueDataChangeHandler, this)); valueAxis.after("dataUpdate", Y.bind(this._valueDataChangeHandler, this)); } this.after("categoryAxisChange", this.categoryAxisChangeHandler); this.after("valueAxisChange", this.valueAxisChangeHandler); this._stylesChangeHandle = this.after("stylesChange", this._updateHandler); this._visibleChangeHandle = this.after("visibleChange", this._handleVisibleChange); }, /** * Draws the series. * * @method validate * @private */ validate: function() { this.draw(); this._renderered = true; }, /** * Event handler for the categoryAxisChange event. * * @method _categoryAxisChangeHandler * @param {Object} e Event object. * @private */ _categoryAxisChangeHandler: function() { var categoryAxis = this.get("categoryAxis"); categoryAxis.after("dataReady", Y.bind(this._categoryDataChangeHandler, this)); categoryAxis.after("dataUpdate", Y.bind(this._categoryDataChangeHandler, this)); }, /** * Event handler for the valueAxisChange event. * * @method _valueAxisChangeHandler * @param {Object} e Event object. * @private */ _valueAxisChangeHandler: function() { var valueAxis = this.get("valueAxis"); valueAxis.after("dataReady", Y.bind(this._valueDataChangeHandler, this)); valueAxis.after("dataUpdate", Y.bind(this._valueDataChangeHandler, this)); }, /** * Constant used to generate unique id. * * @property GUID * @type String * @private */ GUID: "pieseries", /** * Event handler for categoryDataChange event. * * @method _categoryDataChangeHandler * @param {Object} event Event object. * @private */ _categoryDataChangeHandler: function() { if(this._rendered && this.get("categoryKey") && this.get("valueKey")) { this.draw(); } }, /** * Event handler for valueDataChange event. * * @method _valueDataChangeHandler * @param {Object} event Event object. * @private */ _valueDataChangeHandler: function() { if(this._rendered && this.get("categoryKey") && this.get("valueKey")) { this.draw(); } }, /** * Returns the sum of all values for the series. * * @method getTotalValues * @return Number */ getTotalValues: function() { var total = this.get("valueAxis").getTotalByKey(this.get("valueKey")); return total; }, /** * Draws the series. Overrides the base implementation. * * @method draw * @protected */ draw: function() { var w = this.get("width"), h = this.get("height"); if(isFinite(w) && isFinite(h) && w > 0 && h > 0) { this._rendered = true; if(this._drawing) { this._callLater = true; return; } this._drawing = true; this._callLater = false; this.drawSeries(); this._drawing = false; if(this._callLater) { this.draw(); } else { this.fire("drawingComplete"); } } }, /** * Draws the markers * * @method drawPlots * @protected */ drawPlots: function() { var values = this.get("valueAxis").getDataByKey(this.get("valueKey")).concat(), totalValue = 0, itemCount = values.length, styles = this.get("styles").marker, fillColors = styles.fill.colors, fillAlphas = styles.fill.alphas || ["1"], borderColors = styles.border.colors, borderWeights = [styles.border.weight], borderAlphas = [styles.border.alpha], tbw = borderWeights.concat(), tbc = borderColors.concat(), tba = borderAlphas.concat(), tfc, tfa, padding = styles.padding, graphic = this.get("graphic"), minDimension = Math.min(graphic.get("width"), graphic.get("height")), w = minDimension - (padding.left + padding.right), h = minDimension - (padding.top + padding.bottom), startAngle = -90, halfWidth = w / 2, halfHeight = h / 2, radius = Math.min(halfWidth, halfHeight), i = 0, value, angle = 0, lc, la, lw, wedgeStyle, marker, graphOrder = this.get("graphOrder") || 0, isCanvas = Y.Graphic.NAME === "canvasGraphic"; for(; i < itemCount; ++i) { value = parseFloat(values[i]); values.push(value); if(!isNaN(value)) { totalValue += value; } } tfc = fillColors ? fillColors.concat() : null; tfa = fillAlphas ? fillAlphas.concat() : null; this._createMarkerCache(); if(isCanvas) { this._setMap(); this._image.width = w; this._image.height = h; } for(i = 0; i < itemCount; i++) { value = values[i]; if(totalValue === 0) { angle = 360 / values.length; } else { angle = 360 * (value / totalValue); } if(tfc && tfc.length < 1) { tfc = fillColors.concat(); } if(tfa && tfa.length < 1) { tfa = fillAlphas.concat(); } if(tbw && tbw.length < 1) { tbw = borderWeights.concat(); } if(tbw && tbc.length < 1) { tbc = borderColors.concat(); } if(tba && tba.length < 1) { tba = borderAlphas.concat(); } lw = tbw ? tbw.shift() : null; lc = tbc ? tbc.shift() : null; la = tba ? tba.shift() : null; startAngle += angle; wedgeStyle = { border: { color:lc, weight:lw, alpha:la }, fill: { color:tfc ? tfc.shift() : this._getDefaultColor(i, "slice"), alpha:tfa ? tfa.shift() : null }, type: "pieslice", arc: angle, radius: radius, startAngle: startAngle, cx: halfWidth, cy: halfHeight, width: w, height: h }; marker = this.getMarker(wedgeStyle, graphOrder, i); if(isCanvas) { this._addHotspot(wedgeStyle, graphOrder, i); } } this._clearMarkerCache(); }, /** * @protected * * Method used by `styles` setter. Overrides base implementation. * * @method _setStyles * @param {Object} newStyles Hash of properties to update. * @return Object */ _setStyles: function(val) { if(!val.marker) { val = {marker:val}; } val = this._parseMarkerStyles(val); return Y.PieSeries.superclass._mergeStyles.apply(this, [val, this._getDefaultStyles()]); }, /** * Adds an interactive map when rendering in canvas. * * @method _addHotspot * @param {Object} cfg Object containing data used to draw the hotspot * @param {Number} seriesIndex Index of series in the `seriesCollection`. * @param {Number} index Index of the marker using the hotspot. * @private */ _addHotspot: function(cfg, seriesIndex, index) { var areaNode = DOCUMENT.createElement("area"), i = 1, x = cfg.cx, y = cfg.cy, arc = cfg.arc, startAngle = cfg.startAngle - arc, endAngle = cfg.startAngle, radius = cfg.radius, ax = x + Math.cos(startAngle / 180 * Math.PI) * radius, ay = y + Math.sin(startAngle / 180 * Math.PI) * radius, bx = x + Math.cos(endAngle / 180 * Math.PI) * radius, by = y + Math.sin(endAngle / 180 * Math.PI) * radius, numPoints = Math.floor(arc/10) - 1, divAngle = (arc/(Math.floor(arc/10)) / 180) * Math.PI, angleCoord = Math.atan((ay - y)/(ax - x)), pts = x + ", " + y + ", " + ax + ", " + ay, cosAng, sinAng, multDivAng; for(i = 1; i <= numPoints; ++i) { multDivAng = divAngle * i; cosAng = Math.cos(angleCoord + multDivAng); sinAng = Math.sin(angleCoord + multDivAng); if(startAngle <= 90) { pts += ", " + (x + (radius * Math.cos(angleCoord + (divAngle * i)))); pts += ", " + (y + (radius * Math.sin(angleCoord + (divAngle * i)))); } else { pts += ", " + (x - (radius * Math.cos(angleCoord + (divAngle * i)))); pts += ", " + (y - (radius * Math.sin(angleCoord + (divAngle * i)))); } } pts += ", " + bx + ", " + by; pts += ", " + x + ", " + y; this._map.appendChild(areaNode); areaNode.setAttribute("class", SERIES_MARKER); areaNode.setAttribute("id", "hotSpot_" + seriesIndex + "_" + index); areaNode.setAttribute("shape", "polygon"); areaNode.setAttribute("coords", pts); this._areaNodes.push(areaNode); }, /** * Resizes and positions markers based on a mouse interaction. * * @method updateMarkerState * @param {String} type state of the marker * @param {Number} i index of the marker * @protected */ updateMarkerState: function(type, i) { if(this._markers[i]) { var state = this._getState(type), markerStyles, indexStyles, marker = this._markers[i], styles = this.get("styles").marker; markerStyles = state === "off" || !styles[state] ? styles : styles[state]; indexStyles = this._mergeStyles(markerStyles, {}); indexStyles.fill.color = indexStyles.fill.colors[i % indexStyles.fill.colors.length]; indexStyles.fill.alpha = indexStyles.fill.alphas[i % indexStyles.fill.alphas.length]; marker.set(indexStyles); } }, /** * Creates a shape to be used as a marker. * * @method _createMarker * @param {Object} styles Hash of style properties. * @return Shape * @private */ _createMarker: function(styles) { var graphic = this.get("graphic"), marker, cfg = this._copyObject(styles); marker = graphic.addShape(cfg); marker.addClass(SERIES_MARKER); return marker; }, /** * Creates a cache of markers for reuse. * * @method _createMarkerCache * @private */ _clearMarkerCache: function() { var len = this._markerCache.length, i = 0, marker; for(; i < len; ++i) { marker = this._markerCache[i]; if(marker) { marker.destroy(); } } this._markerCache = []; }, /** * Gets the default style values for the markers. * * @method _getPlotDefaults * @return Object * @private */ _getPlotDefaults: function() { var defs = { padding:{ top: 0, left: 0, right: 0, bottom: 0 }, fill:{ alphas:["1"] }, border: { weight: 0, alpha: 1 } }; defs.fill.colors = this._defaultSliceColors; defs.border.colors = this._defaultBorderColors; return defs; } }, { ATTRS: { /** * Read-only attribute indicating the type of series. * * @attribute type * @type String * @default pie */ type: { value: "pie" }, /** * Order of this instance of this `type`. * * @attribute order * @type Number */ order: {}, /** * Reference to the `Graph` in which the series is drawn into. * * @attribute graph * @type Graph */ graph: {}, /** * Reference to the `Axis` instance used for assigning * category values to the graph. * * @attribute categoryAxis * @type Axis */ categoryAxis: { value: null, validator: function(value) { return value !== this.get("categoryAxis"); } }, /** * Reference to the `Axis` instance used for assigning * series values to the graph. * * @attribute categoryAxis * @type Axis */ valueAxis: { value: null, validator: function(value) { return value !== this.get("valueAxis"); } }, /** * Indicates which array to from the hash of value arrays in * the category `Axis` instance. * * @attribute categoryKey * @type String */ categoryKey: { value: null, validator: function(value) { return value !== this.get("categoryKey"); } }, /** * Indicates which array to from the hash of value arrays in * the value `Axis` instance. * * @attribute valueKey * @type String */ valueKey: { value: null, validator: function(value) { return value !== this.get("valueKey"); } }, /** * Name used for for displaying category data * * @attribute categoryDisplayName * @type String */ categoryDisplayName: { setter: function(val) { this._categoryDisplayName = val; return val; }, getter: function() { return this._categoryDisplayName || this.get("categoryKey"); } }, /** * Name used for for displaying value data * * @attribute valueDisplayName * @type String */ valueDisplayName: { setter: function(val) { this._valueDisplayName = val; return val; }, getter: function() { return this._valueDisplayName || this.get("valueKey"); } }, /** * @attribute slices * @type Array * @private */ slices: null /** * Style properties used for drawing markers. This attribute is inherited from `MarkerSeries`. Below are the default * values: *
*
fill
A hash containing the following values: *
*
colors
An array of colors to be used for the marker fills. The color for each marker is * retrieved from the array below:
* `["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"]` *
*
alphas
An array of alpha references (Number from 0 to 1) indicating the opacity of each marker * fill. The default value is [1].
*
*
*
border
A hash containing the following values: *
*
color
An array of colors to be used for the marker borders. The color for each marker is * retrieved from the array below:
* `["#205096", "#b38206", "#000000", "#94001e", "#9d6fa0", "#e55b00", "#5e85c9", "#adab9e", "#6ac291", "#006457"]` *
alpha
Number from 0 to 1 indicating the opacity of the marker border. The default value is 1.
*
weight
Number indicating the width of the border. The default value is 1.
*
*
*
over
hash containing styles for markers when highlighted by a `mouseover` event. The default * values for each style is null. When an over style is not set, the non-over value will be used. For example, * the default value for `marker.over.fill.color` is equivalent to `marker.fill.color`.
*
* * @attribute styles * @type Object */ } }); }, '3.18.1', {"requires": ["series-base", "series-plot-util"]}); PK\CC43.18.1/uploader-queue/assets/uploader-flash-core.cssnu[.yui3-uploader-selectfiles-button { width: 100%; height: 100%; } PK\8DaIaI'3.18.1/uploader-queue/uploader-queue.jsnu[YUI.add('uploader-queue', function (Y, NAME) { /** * The class manages a queue of files that should be uploaded to the server. * It initializes the required number of uploads, tracks them as they progress, * and automatically advances to the next upload when a preceding one has completed. * @module uploader-queue */ /** * This class manages a queue of files to be uploaded to the server. * @class Uploader.Queue * @extends Base * @constructor */ var UploaderQueue = function() { this.queuedFiles = []; this.uploadRetries = {}; this.numberOfUploads = 0; this.currentUploadedByteValues = {}; this.currentFiles = {}; this.totalBytesUploaded = 0; this.totalBytes = 0; UploaderQueue.superclass.constructor.apply(this, arguments); }; Y.extend(UploaderQueue, Y.Base, { /** * Stored value of the current queue state * @property _currentState * @type {String} * @protected * @default UploaderQueue.STOPPED */ _currentState: UploaderQueue.STOPPED, /** * Construction logic executed during UploaderQueue instantiation. * * @method initializer * @protected */ initializer : function () {}, /** * Handles and retransmits upload start event. * * @method _uploadStartHandler * @param event The event dispatched during the upload process. * @private */ _uploadStartHandler : function (event) { var updatedEvent = event; updatedEvent.file = event.target; updatedEvent.originEvent = event; this.fire("uploadstart", updatedEvent); }, /** * Handles and retransmits upload error event. * * @method _uploadErrorHandler * @param event The event dispatched during the upload process. * @private */ _uploadErrorHandler : function (event) { var errorAction = this.get("errorAction"), updatedEvent = event, fileid, retries; updatedEvent.file = event.target; updatedEvent.originEvent = event; this.numberOfUploads-=1; delete this.currentFiles[event.target.get("id")]; this._detachFileEvents(event.target); event.target.cancelUpload(); if (errorAction === UploaderQueue.STOP) { this.pauseUpload(); } else if (errorAction === UploaderQueue.RESTART_ASAP) { fileid = event.target.get("id"); retries = this.uploadRetries[fileid] || 0; if (retries < this.get("retryCount")) { this.uploadRetries[fileid] = retries + 1; this.addToQueueTop(event.target); } this._startNextFile(); } else if (errorAction === UploaderQueue.RESTART_AFTER) { fileid = event.target.get("id"); retries = this.uploadRetries[fileid] || 0; if (retries < this.get("retryCount")) { this.uploadRetries[fileid] = retries + 1; this.addToQueueBottom(event.target); } this._startNextFile(); } this.fire("uploaderror", updatedEvent); }, /** * Launches the upload of the next file in the queue. * * @method _startNextFile * @private */ _startNextFile : function () { if (this.queuedFiles.length > 0) { var currentFile = this.queuedFiles.shift(), fileId = currentFile.get("id"), parameters = this.get("perFileParameters"), fileParameters = parameters.hasOwnProperty(fileId) ? parameters[fileId] : parameters; this.currentUploadedByteValues[fileId] = 0; currentFile.on("uploadstart", this._uploadStartHandler, this); currentFile.on("uploadprogress", this._uploadProgressHandler, this); currentFile.on("uploadcomplete", this._uploadCompleteHandler, this); currentFile.on("uploaderror", this._uploadErrorHandler, this); currentFile.on("uploadcancel", this._uploadCancelHandler, this); currentFile.set("xhrHeaders", this.get("uploadHeaders")); currentFile.set("xhrWithCredentials", this.get("withCredentials")); currentFile.startUpload(this.get("uploadURL"), fileParameters, this.get("fileFieldName")); this._registerUpload(currentFile); } }, /** * Register a new upload process. * * @method _registerUpload * @private */ _registerUpload : function (file) { this.numberOfUploads += 1; this.currentFiles[file.get("id")] = file; }, /** * Unregisters a new upload process. * * @method _unregisterUpload * @private */ _unregisterUpload : function (file) { if (this.numberOfUploads > 0) { this.numberOfUploads -= 1; } delete this.currentFiles[file.get("id")]; delete this.uploadRetries[file.get("id")]; this._detachFileEvents(file); }, _detachFileEvents : function (file) { file.detach("uploadstart", this._uploadStartHandler); file.detach("uploadprogress", this._uploadProgressHandler); file.detach("uploadcomplete", this._uploadCompleteHandler); file.detach("uploaderror", this._uploadErrorHandler); file.detach("uploadcancel", this._uploadCancelHandler); }, /** * Handles and retransmits upload complete event. * * @method _uploadCompleteHandler * @param event The event dispatched during the upload process. * @private */ _uploadCompleteHandler : function (event) { this._unregisterUpload(event.target); this.totalBytesUploaded += event.target.get("size"); delete this.currentUploadedByteValues[event.target.get("id")]; if (this.queuedFiles.length > 0 && this._currentState === UploaderQueue.UPLOADING) { this._startNextFile(); } var updatedEvent = event, uploadedTotal = this.totalBytesUploaded, percentLoaded = Math.min(100, Math.round(10000*uploadedTotal/this.totalBytes) / 100); updatedEvent.file = event.target; updatedEvent.originEvent = event; Y.each(this.currentUploadedByteValues, function (value) { uploadedTotal += value; }); this.fire("totaluploadprogress", { bytesLoaded: uploadedTotal, bytesTotal: this.totalBytes, percentLoaded: percentLoaded }); this.fire("uploadcomplete", updatedEvent); if (this.queuedFiles.length === 0 && this.numberOfUploads <= 0) { this.fire("alluploadscomplete"); this._currentState = UploaderQueue.STOPPED; } }, /** * Handles and retransmits upload cancel event. * * @method _uploadCancelHandler * @param event The event dispatched during the upload process. * @private */ _uploadCancelHandler : function (event) { var updatedEvent = event; updatedEvent.originEvent = event; updatedEvent.file = event.target; this.fire("uploadcancel", updatedEvent); }, /** * Handles and retransmits upload progress event. * * @method _uploadProgressHandler * @param event The event dispatched during the upload process. * @private */ _uploadProgressHandler : function (event) { this.currentUploadedByteValues[event.target.get("id")] = event.bytesLoaded; var updatedEvent = event, uploadedTotal = this.totalBytesUploaded, percentLoaded = Math.min(100, Math.round(10000*uploadedTotal/this.totalBytes) / 100); updatedEvent.originEvent = event; updatedEvent.file = event.target; this.fire("uploadprogress", updatedEvent); Y.each(this.currentUploadedByteValues, function (value) { uploadedTotal += value; }); this.fire("totaluploadprogress", { bytesLoaded: uploadedTotal, bytesTotal: this.totalBytes, percentLoaded: percentLoaded }); }, /** * Starts uploading the queued up file list. * * @method startUpload */ startUpload: function() { this.queuedFiles = this.get("fileList").slice(0); this.numberOfUploads = 0; this.currentUploadedByteValues = {}; this.currentFiles = {}; this.totalBytesUploaded = 0; this._currentState = UploaderQueue.UPLOADING; while (this.numberOfUploads < this.get("simUploads") && this.queuedFiles.length > 0) { this._startNextFile(); } }, /** * Pauses the upload process. The ongoing file uploads * will complete after this method is called, but no * new ones will be launched. * * @method pauseUpload */ pauseUpload: function () { this._currentState = UploaderQueue.STOPPED; }, /** * Restarts a paused upload process. * * @method restartUpload */ restartUpload: function () { this._currentState = UploaderQueue.UPLOADING; while (this.numberOfUploads < this.get("simUploads")) { this._startNextFile(); } }, /** * If a particular file is stuck in an ongoing upload without * any progress events, this method allows to force its reupload * by cancelling its upload and immediately relaunching it. * * @method forceReupload * @param file {File} The file to force reupload on. */ forceReupload : function (file) { var id = file.get("id"); if (this.currentFiles.hasOwnProperty(id)) { file.cancelUpload(); this._unregisterUpload(file); this.addToQueueTop(file); this._startNextFile(); } }, /** * Add a new file to the top of the queue (the upload will be * launched as soon as the current number of uploading files * drops below the maximum permissible value). * * @method addToQueueTop * @param file {File} The file to add to the top of the queue. */ addToQueueTop: function (file) { this.queuedFiles.unshift(file); }, /** * Add a new file to the bottom of the queue (the upload will be * launched after all the other queued files are uploaded.) * * @method addToQueueBottom * @param file {File} The file to add to the bottom of the queue. */ addToQueueBottom: function (file) { this.queuedFiles.push(file); }, /** * Cancels a specific file's upload. If no argument is passed, * all ongoing uploads are cancelled and the upload process is * stopped. * * @method cancelUpload * @param file {File} An optional parameter - the file whose upload * should be cancelled. */ cancelUpload: function (file) { var id, i, fid; if (file) { id = file.get("id"); if (this.currentFiles[id]) { this.currentFiles[id].cancelUpload(); this._unregisterUpload(this.currentFiles[id]); if (this._currentState === UploaderQueue.UPLOADING) { this._startNextFile(); } } else { for (i = 0, len = this.queuedFiles.length; i < len; i++) { if (this.queuedFiles[i].get("id") === id) { this.queuedFiles.splice(i, 1); break; } } } } else { for (fid in this.currentFiles) { this.currentFiles[fid].cancelUpload(); this._unregisterUpload(this.currentFiles[fid]); } this.currentUploadedByteValues = {}; this.currentFiles = {}; this.totalBytesUploaded = 0; this.fire("alluploadscancelled"); this._currentState = UploaderQueue.STOPPED; } } }, { /** * Static constant for the value of the `errorAction` attribute: * prescribes the queue to continue uploading files in case of * an error. * @property CONTINUE * @readOnly * @type {String} * @static */ CONTINUE: "continue", /** * Static constant for the value of the `errorAction` attribute: * prescribes the queue to stop uploading files in case of * an error. * @property STOP * @readOnly * @type {String} * @static */ STOP: "stop", /** * Static constant for the value of the `errorAction` attribute: * prescribes the queue to restart a file upload immediately in case of * an error. * @property RESTART_ASAP * @readOnly * @type {String} * @static */ RESTART_ASAP: "restartasap", /** * Static constant for the value of the `errorAction` attribute: * prescribes the queue to restart an errored out file upload after * other files have finished uploading. * @property RESTART_AFTER * @readOnly * @type {String} * @static */ RESTART_AFTER: "restartafter", /** * Static constant for the value of the `_currentState` property: * implies that the queue is currently not uploading files. * @property STOPPED * @readOnly * @type {String} * @static */ STOPPED: "stopped", /** * Static constant for the value of the `_currentState` property: * implies that the queue is currently uploading files. * @property UPLOADING * @readOnly * @type {String} * @static */ UPLOADING: "uploading", /** * The identity of the class. * * @property NAME * @type String * @default 'uploaderqueue' * @readOnly * @protected * @static */ NAME: 'uploaderqueue', /** * Static property used to define the default attribute configuration of * the class. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * Maximum number of simultaneous uploads; must be in the * range between 1 and 5. The value of `2` is default. It * is recommended that this value does not exceed 3. * @attribute simUploads * @type Number * @default 2 */ simUploads: { value: 2, validator: function (val) { return (val >= 1 && val <= 5); } }, /** * The action to take in case of error. The valid values for this attribute are: * `Y.Uploader.Queue.CONTINUE` (the upload process should continue on other files, * ignoring the error), `Y.Uploader.Queue.STOP` (the upload process * should stop completely), `Y.Uploader.Queue.RESTART_ASAP` (the upload * should restart immediately on the errored out file and continue as planned), or * Y.Uploader.Queue.RESTART_AFTER (the upload of the errored out file should restart * after all other files have uploaded) * @attribute errorAction * @type String * @default Y.Uploader.Queue.CONTINUE */ errorAction: { value: "continue", validator: function (val) { return ( val === UploaderQueue.CONTINUE || val === UploaderQueue.STOP || val === UploaderQueue.RESTART_ASAP || val === UploaderQueue.RESTART_AFTER ); } }, /** * The total number of bytes that has been uploaded. * @attribute bytesUploaded * @type Number */ bytesUploaded: { readOnly: true, value: 0 }, /** * The total number of bytes in the queue. * @attribute bytesTotal * @type Number */ bytesTotal: { readOnly: true, value: 0 }, /** * The queue file list. This file list should only be modified * before the upload has been started; modifying it after starting * the upload has no effect, and `addToQueueTop` or `addToQueueBottom` methods * should be used instead. * @attribute fileList * @type Array */ fileList: { value: [], lazyAdd: false, setter: function (val) { var newValue = val; Y.Array.each(newValue, function (value) { this.totalBytes += value.get("size"); }, this); return val; } }, /** * A String specifying what should be the POST field name for the file * content in the upload request. * * @attribute fileFieldName * @type {String} * @default Filedata */ fileFieldName: { value: "Filedata" }, /** * The URL to POST the file upload requests to. * * @attribute uploadURL * @type {String} * @default "" */ uploadURL: { value: "" }, /** * Additional HTTP headers that should be included * in the upload request. Due to Flash Player security * restrictions, this attribute is only honored in the * HTML5 Uploader. * * @attribute uploadHeaders * @type {Object} * @default {} */ uploadHeaders: { value: {} }, /** * A Boolean that specifies whether the file should be * uploaded with the appropriate user credentials for the * domain. Due to Flash Player security restrictions, this * attribute is only honored in the HTML5 Uploader. * * @attribute withCredentials * @type {Boolean} * @default true */ withCredentials: { value: true }, /** * An object, keyed by `fileId`, containing sets of key-value pairs * that should be passed as POST variables along with each corresponding * file. * * @attribute perFileParameters * @type {Object} * @default {} */ perFileParameters: { value: {} }, /** * The number of times to try re-uploading a file that failed to upload before * cancelling its upload. * * @attribute retryCount * @type {Number} * @default 3 */ retryCount: { value: 3 } } }); Y.namespace('Uploader'); Y.Uploader.Queue = UploaderQueue; }, '3.18.1', {"requires": ["base"]}); PK\8DaIaI-3.18.1/uploader-queue/uploader-queue-debug.jsnu[YUI.add('uploader-queue', function (Y, NAME) { /** * The class manages a queue of files that should be uploaded to the server. * It initializes the required number of uploads, tracks them as they progress, * and automatically advances to the next upload when a preceding one has completed. * @module uploader-queue */ /** * This class manages a queue of files to be uploaded to the server. * @class Uploader.Queue * @extends Base * @constructor */ var UploaderQueue = function() { this.queuedFiles = []; this.uploadRetries = {}; this.numberOfUploads = 0; this.currentUploadedByteValues = {}; this.currentFiles = {}; this.totalBytesUploaded = 0; this.totalBytes = 0; UploaderQueue.superclass.constructor.apply(this, arguments); }; Y.extend(UploaderQueue, Y.Base, { /** * Stored value of the current queue state * @property _currentState * @type {String} * @protected * @default UploaderQueue.STOPPED */ _currentState: UploaderQueue.STOPPED, /** * Construction logic executed during UploaderQueue instantiation. * * @method initializer * @protected */ initializer : function () {}, /** * Handles and retransmits upload start event. * * @method _uploadStartHandler * @param event The event dispatched during the upload process. * @private */ _uploadStartHandler : function (event) { var updatedEvent = event; updatedEvent.file = event.target; updatedEvent.originEvent = event; this.fire("uploadstart", updatedEvent); }, /** * Handles and retransmits upload error event. * * @method _uploadErrorHandler * @param event The event dispatched during the upload process. * @private */ _uploadErrorHandler : function (event) { var errorAction = this.get("errorAction"), updatedEvent = event, fileid, retries; updatedEvent.file = event.target; updatedEvent.originEvent = event; this.numberOfUploads-=1; delete this.currentFiles[event.target.get("id")]; this._detachFileEvents(event.target); event.target.cancelUpload(); if (errorAction === UploaderQueue.STOP) { this.pauseUpload(); } else if (errorAction === UploaderQueue.RESTART_ASAP) { fileid = event.target.get("id"); retries = this.uploadRetries[fileid] || 0; if (retries < this.get("retryCount")) { this.uploadRetries[fileid] = retries + 1; this.addToQueueTop(event.target); } this._startNextFile(); } else if (errorAction === UploaderQueue.RESTART_AFTER) { fileid = event.target.get("id"); retries = this.uploadRetries[fileid] || 0; if (retries < this.get("retryCount")) { this.uploadRetries[fileid] = retries + 1; this.addToQueueBottom(event.target); } this._startNextFile(); } this.fire("uploaderror", updatedEvent); }, /** * Launches the upload of the next file in the queue. * * @method _startNextFile * @private */ _startNextFile : function () { if (this.queuedFiles.length > 0) { var currentFile = this.queuedFiles.shift(), fileId = currentFile.get("id"), parameters = this.get("perFileParameters"), fileParameters = parameters.hasOwnProperty(fileId) ? parameters[fileId] : parameters; this.currentUploadedByteValues[fileId] = 0; currentFile.on("uploadstart", this._uploadStartHandler, this); currentFile.on("uploadprogress", this._uploadProgressHandler, this); currentFile.on("uploadcomplete", this._uploadCompleteHandler, this); currentFile.on("uploaderror", this._uploadErrorHandler, this); currentFile.on("uploadcancel", this._uploadCancelHandler, this); currentFile.set("xhrHeaders", this.get("uploadHeaders")); currentFile.set("xhrWithCredentials", this.get("withCredentials")); currentFile.startUpload(this.get("uploadURL"), fileParameters, this.get("fileFieldName")); this._registerUpload(currentFile); } }, /** * Register a new upload process. * * @method _registerUpload * @private */ _registerUpload : function (file) { this.numberOfUploads += 1; this.currentFiles[file.get("id")] = file; }, /** * Unregisters a new upload process. * * @method _unregisterUpload * @private */ _unregisterUpload : function (file) { if (this.numberOfUploads > 0) { this.numberOfUploads -= 1; } delete this.currentFiles[file.get("id")]; delete this.uploadRetries[file.get("id")]; this._detachFileEvents(file); }, _detachFileEvents : function (file) { file.detach("uploadstart", this._uploadStartHandler); file.detach("uploadprogress", this._uploadProgressHandler); file.detach("uploadcomplete", this._uploadCompleteHandler); file.detach("uploaderror", this._uploadErrorHandler); file.detach("uploadcancel", this._uploadCancelHandler); }, /** * Handles and retransmits upload complete event. * * @method _uploadCompleteHandler * @param event The event dispatched during the upload process. * @private */ _uploadCompleteHandler : function (event) { this._unregisterUpload(event.target); this.totalBytesUploaded += event.target.get("size"); delete this.currentUploadedByteValues[event.target.get("id")]; if (this.queuedFiles.length > 0 && this._currentState === UploaderQueue.UPLOADING) { this._startNextFile(); } var updatedEvent = event, uploadedTotal = this.totalBytesUploaded, percentLoaded = Math.min(100, Math.round(10000*uploadedTotal/this.totalBytes) / 100); updatedEvent.file = event.target; updatedEvent.originEvent = event; Y.each(this.currentUploadedByteValues, function (value) { uploadedTotal += value; }); this.fire("totaluploadprogress", { bytesLoaded: uploadedTotal, bytesTotal: this.totalBytes, percentLoaded: percentLoaded }); this.fire("uploadcomplete", updatedEvent); if (this.queuedFiles.length === 0 && this.numberOfUploads <= 0) { this.fire("alluploadscomplete"); this._currentState = UploaderQueue.STOPPED; } }, /** * Handles and retransmits upload cancel event. * * @method _uploadCancelHandler * @param event The event dispatched during the upload process. * @private */ _uploadCancelHandler : function (event) { var updatedEvent = event; updatedEvent.originEvent = event; updatedEvent.file = event.target; this.fire("uploadcancel", updatedEvent); }, /** * Handles and retransmits upload progress event. * * @method _uploadProgressHandler * @param event The event dispatched during the upload process. * @private */ _uploadProgressHandler : function (event) { this.currentUploadedByteValues[event.target.get("id")] = event.bytesLoaded; var updatedEvent = event, uploadedTotal = this.totalBytesUploaded, percentLoaded = Math.min(100, Math.round(10000*uploadedTotal/this.totalBytes) / 100); updatedEvent.originEvent = event; updatedEvent.file = event.target; this.fire("uploadprogress", updatedEvent); Y.each(this.currentUploadedByteValues, function (value) { uploadedTotal += value; }); this.fire("totaluploadprogress", { bytesLoaded: uploadedTotal, bytesTotal: this.totalBytes, percentLoaded: percentLoaded }); }, /** * Starts uploading the queued up file list. * * @method startUpload */ startUpload: function() { this.queuedFiles = this.get("fileList").slice(0); this.numberOfUploads = 0; this.currentUploadedByteValues = {}; this.currentFiles = {}; this.totalBytesUploaded = 0; this._currentState = UploaderQueue.UPLOADING; while (this.numberOfUploads < this.get("simUploads") && this.queuedFiles.length > 0) { this._startNextFile(); } }, /** * Pauses the upload process. The ongoing file uploads * will complete after this method is called, but no * new ones will be launched. * * @method pauseUpload */ pauseUpload: function () { this._currentState = UploaderQueue.STOPPED; }, /** * Restarts a paused upload process. * * @method restartUpload */ restartUpload: function () { this._currentState = UploaderQueue.UPLOADING; while (this.numberOfUploads < this.get("simUploads")) { this._startNextFile(); } }, /** * If a particular file is stuck in an ongoing upload without * any progress events, this method allows to force its reupload * by cancelling its upload and immediately relaunching it. * * @method forceReupload * @param file {File} The file to force reupload on. */ forceReupload : function (file) { var id = file.get("id"); if (this.currentFiles.hasOwnProperty(id)) { file.cancelUpload(); this._unregisterUpload(file); this.addToQueueTop(file); this._startNextFile(); } }, /** * Add a new file to the top of the queue (the upload will be * launched as soon as the current number of uploading files * drops below the maximum permissible value). * * @method addToQueueTop * @param file {File} The file to add to the top of the queue. */ addToQueueTop: function (file) { this.queuedFiles.unshift(file); }, /** * Add a new file to the bottom of the queue (the upload will be * launched after all the other queued files are uploaded.) * * @method addToQueueBottom * @param file {File} The file to add to the bottom of the queue. */ addToQueueBottom: function (file) { this.queuedFiles.push(file); }, /** * Cancels a specific file's upload. If no argument is passed, * all ongoing uploads are cancelled and the upload process is * stopped. * * @method cancelUpload * @param file {File} An optional parameter - the file whose upload * should be cancelled. */ cancelUpload: function (file) { var id, i, fid; if (file) { id = file.get("id"); if (this.currentFiles[id]) { this.currentFiles[id].cancelUpload(); this._unregisterUpload(this.currentFiles[id]); if (this._currentState === UploaderQueue.UPLOADING) { this._startNextFile(); } } else { for (i = 0, len = this.queuedFiles.length; i < len; i++) { if (this.queuedFiles[i].get("id") === id) { this.queuedFiles.splice(i, 1); break; } } } } else { for (fid in this.currentFiles) { this.currentFiles[fid].cancelUpload(); this._unregisterUpload(this.currentFiles[fid]); } this.currentUploadedByteValues = {}; this.currentFiles = {}; this.totalBytesUploaded = 0; this.fire("alluploadscancelled"); this._currentState = UploaderQueue.STOPPED; } } }, { /** * Static constant for the value of the `errorAction` attribute: * prescribes the queue to continue uploading files in case of * an error. * @property CONTINUE * @readOnly * @type {String} * @static */ CONTINUE: "continue", /** * Static constant for the value of the `errorAction` attribute: * prescribes the queue to stop uploading files in case of * an error. * @property STOP * @readOnly * @type {String} * @static */ STOP: "stop", /** * Static constant for the value of the `errorAction` attribute: * prescribes the queue to restart a file upload immediately in case of * an error. * @property RESTART_ASAP * @readOnly * @type {String} * @static */ RESTART_ASAP: "restartasap", /** * Static constant for the value of the `errorAction` attribute: * prescribes the queue to restart an errored out file upload after * other files have finished uploading. * @property RESTART_AFTER * @readOnly * @type {String} * @static */ RESTART_AFTER: "restartafter", /** * Static constant for the value of the `_currentState` property: * implies that the queue is currently not uploading files. * @property STOPPED * @readOnly * @type {String} * @static */ STOPPED: "stopped", /** * Static constant for the value of the `_currentState` property: * implies that the queue is currently uploading files. * @property UPLOADING * @readOnly * @type {String} * @static */ UPLOADING: "uploading", /** * The identity of the class. * * @property NAME * @type String * @default 'uploaderqueue' * @readOnly * @protected * @static */ NAME: 'uploaderqueue', /** * Static property used to define the default attribute configuration of * the class. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * Maximum number of simultaneous uploads; must be in the * range between 1 and 5. The value of `2` is default. It * is recommended that this value does not exceed 3. * @attribute simUploads * @type Number * @default 2 */ simUploads: { value: 2, validator: function (val) { return (val >= 1 && val <= 5); } }, /** * The action to take in case of error. The valid values for this attribute are: * `Y.Uploader.Queue.CONTINUE` (the upload process should continue on other files, * ignoring the error), `Y.Uploader.Queue.STOP` (the upload process * should stop completely), `Y.Uploader.Queue.RESTART_ASAP` (the upload * should restart immediately on the errored out file and continue as planned), or * Y.Uploader.Queue.RESTART_AFTER (the upload of the errored out file should restart * after all other files have uploaded) * @attribute errorAction * @type String * @default Y.Uploader.Queue.CONTINUE */ errorAction: { value: "continue", validator: function (val) { return ( val === UploaderQueue.CONTINUE || val === UploaderQueue.STOP || val === UploaderQueue.RESTART_ASAP || val === UploaderQueue.RESTART_AFTER ); } }, /** * The total number of bytes that has been uploaded. * @attribute bytesUploaded * @type Number */ bytesUploaded: { readOnly: true, value: 0 }, /** * The total number of bytes in the queue. * @attribute bytesTotal * @type Number */ bytesTotal: { readOnly: true, value: 0 }, /** * The queue file list. This file list should only be modified * before the upload has been started; modifying it after starting * the upload has no effect, and `addToQueueTop` or `addToQueueBottom` methods * should be used instead. * @attribute fileList * @type Array */ fileList: { value: [], lazyAdd: false, setter: function (val) { var newValue = val; Y.Array.each(newValue, function (value) { this.totalBytes += value.get("size"); }, this); return val; } }, /** * A String specifying what should be the POST field name for the file * content in the upload request. * * @attribute fileFieldName * @type {String} * @default Filedata */ fileFieldName: { value: "Filedata" }, /** * The URL to POST the file upload requests to. * * @attribute uploadURL * @type {String} * @default "" */ uploadURL: { value: "" }, /** * Additional HTTP headers that should be included * in the upload request. Due to Flash Player security * restrictions, this attribute is only honored in the * HTML5 Uploader. * * @attribute uploadHeaders * @type {Object} * @default {} */ uploadHeaders: { value: {} }, /** * A Boolean that specifies whether the file should be * uploaded with the appropriate user credentials for the * domain. Due to Flash Player security restrictions, this * attribute is only honored in the HTML5 Uploader. * * @attribute withCredentials * @type {Boolean} * @default true */ withCredentials: { value: true }, /** * An object, keyed by `fileId`, containing sets of key-value pairs * that should be passed as POST variables along with each corresponding * file. * * @attribute perFileParameters * @type {Object} * @default {} */ perFileParameters: { value: {} }, /** * The number of times to try re-uploading a file that failed to upload before * cancelling its upload. * * @attribute retryCount * @type {Number} * @default 3 */ retryCount: { value: 3 } } }); Y.namespace('Uploader'); Y.Uploader.Queue = UploaderQueue; }, '3.18.1', {"requires": ["base"]}); PK\̑d+3.18.1/uploader-queue/uploader-queue-min.jsnu[YUI.add("uploader-queue",function(e,t){var n=function(){this.queuedFiles=[],this.uploadRetries={},this.numberOfUploads=0,this.currentUploadedByteValues={},this.currentFiles={},this.totalBytesUploaded=0,this.totalBytes=0,n.superclass.constructor.apply(this,arguments)};e.extend(n,e.Base,{_currentState:n.STOPPED,initializer:function(){},_uploadStartHandler:function(e){var t=e;t.file=e.target,t.originEvent=e,this.fire("uploadstart",t)},_uploadErrorHandler:function(e){var t=this.get("errorAction"),r=e,i,s;r.file=e.target,r.originEvent=e,this.numberOfUploads-=1,delete this.currentFiles[e.target.get("id")],this._detachFileEvents(e.target),e.target.cancelUpload(),t===n.STOP?this.pauseUpload():t===n.RESTART_ASAP?(i=e.target.get("id"),s=this.uploadRetries[i]||0,s0){var e=this.queuedFiles.shift(),t=e.get("id"),n=this.get("perFileParameters"),r=n.hasOwnProperty(t)?n[t]:n;this.currentUploadedByteValues[t]=0,e.on("uploadstart",this._uploadStartHandler,this),e.on("uploadprogress",this._uploadProgressHandler,this),e.on("uploadcomplete",this._uploadCompleteHandler,this),e.on("uploaderror",this._uploadErrorHandler,this),e.on("uploadcancel",this._uploadCancelHandler,this),e.set("xhrHeaders",this.get("uploadHeaders")),e.set("xhrWithCredentials",this.get("withCredentials")),e.startUpload(this.get("uploadURL"),r,this.get("fileFieldName")),this._registerUpload(e)}},_registerUpload:function(e){this.numberOfUploads+=1,this.currentFiles[e.get("id")]=e},_unregisterUpload:function(e){this.numberOfUploads>0&&(this.numberOfUploads-=1),delete this.currentFiles[e.get("id")],delete this.uploadRetries[e.get("id")],this._detachFileEvents(e)},_detachFileEvents:function(e){e.detach("uploadstart",this._uploadStartHandler),e.detach("uploadprogress",this._uploadProgressHandler),e.detach("uploadcomplete",this._uploadCompleteHandler),e.detach("uploaderror",this._uploadErrorHandler),e.detach("uploadcancel",this._uploadCancelHandler)},_uploadCompleteHandler:function(t){this._unregisterUpload(t.target),this.totalBytesUploaded+=t.target.get("size"),delete this.currentUploadedByteValues[t.target.get("id")],this.queuedFiles.length>0&&this._currentState===n.UPLOADING&&this._startNextFile();var r=t,i=this.totalBytesUploaded,s=Math.min(100,Math.round(1e4*i/this.totalBytes)/100);r.file=t.target,r.originEvent=t,e.each(this.currentUploadedByteValues,function(e){i+=e}),this.fire("totaluploadprogress",{bytesLoaded:i,bytesTotal:this.totalBytes,percentLoaded:s}),this.fire("uploadcomplete",r),this.queuedFiles.length===0&&this.numberOfUploads<=0&&(this.fire("alluploadscomplete"),this._currentState=n.STOPPED)},_uploadCancelHandler:function(e){var t=e;t.originEvent=e,t.file=e.target,this.fire("uploadcancel",t)},_uploadProgressHandler:function(t){this.currentUploadedByteValues[t.target.get("id")]=t.bytesLoaded;var n=t,r=this.totalBytesUploaded,i=Math.min(100,Math.round(1e4*r/this.totalBytes)/100);n.originEvent=t,n.file=t.target,this.fire("uploadprogress",n),e.each(this.currentUploadedByteValues,function(e){r+=e}),this.fire("totaluploadprogress",{bytesLoaded:r,bytesTotal:this.totalBytes,percentLoaded:i})},startUpload:function(){this.queuedFiles=this.get("fileList").slice(0),this.numberOfUploads=0,this.currentUploadedByteValues={},this.currentFiles={},this.totalBytesUploaded=0,this._currentState=n.UPLOADING;while(this.numberOfUploads0)this._startNextFile()},pauseUpload:function(){this._currentState=n.STOPPED},restartUpload:function(){this._currentState=n.UPLOADING;while(this.numberOfUploads=1&&e<=5}},errorAction:{value:"continue",validator:function(e){return e===n.CONTINUE||e===n.STOP||e===n.RESTART_ASAP||e===n.RESTART_AFTER}},bytesUploaded:{readOnly:!0,value:0},bytesTotal:{readOnly:!0,value:0},fileList:{value:[],lazyAdd:!1,setter:function(t){var n=t;return e.Array.each(n,function(e){this.totalBytes+=e.get("size")},this),t}},fileFieldName:{value:"Filedata"},uploadURL:{value:""},uploadHeaders:{value:{}},withCredentials:{value:!0},perFileParameters:{value:{}},retryCount:{value:3}}}),e.namespace("Uploader"),e.Uploader.Queue=n},"3.18.1",{requires:["base"]}); PK\~~-3.18.1/calendar/assets/skins/sam/calendar.cssnu[.yui3-calendar-column-hidden,.yui3-calendar-hidden{display:none}.yui3-calendar-day{cursor:pointer}.yui3-calendar-selection-disabled{cursor:default}.yui3-calendar-prevmonth-day{cursor:default}.yui3-calendar-nextmonth-day{cursor:default}.yui3-calendar-content:hover .yui3-calendar-day,.yui3-calendar-content:hover .yui3-calendar-prevmonth-day,.yui3-calendar-content:hover .yui3-calendar-nextmonth-day{-moz-user-select:none}.yui3-skin-sam .yui3-calendar-day-highlighted{background-color:#dcdef5}.yui3-skin-sam .yui3-calendar-day-selected.yui3-calendar-day-highlighted{background-color:#758fbb}#yui3-css-stamp.skin-sam-calendar{display:none} PK\c23.18.1/calendar/assets/skins/sam/calendar-skin.cssnu[.yui3-skin-sam .yui3-calendar-day-highlighted { background-color: #DCDEF5; } .yui3-skin-sam .yui3-calendar-day-selected.yui3-calendar-day-highlighted { background-color: #758FBB; } PK\8'~~/3.18.1/calendar/assets/skins/night/calendar.cssnu[.yui3-calendar-column-hidden,.yui3-calendar-hidden{display:none}.yui3-calendar-day{cursor:pointer}.yui3-calendar-selection-disabled{cursor:default}.yui3-calendar-prevmonth-day{cursor:default}.yui3-calendar-nextmonth-day{cursor:default}.yui3-calendar-content:hover .yui3-calendar-day,.yui3-calendar-content:hover .yui3-calendar-prevmonth-day,.yui3-calendar-content:hover .yui3-calendar-nextmonth-day{-moz-user-select:none}.yui3-skin-night .yui3-calendar-day-highlighted{background-color:#555}.yui3-skin-night .yui3-calendar-day-selected.yui3-calendar-day-highlighted{background-color:#777}#yui3-css-stamp.skin-night-calendar{display:none} PK\43.18.1/calendar/assets/skins/night/calendar-skin.cssnu[.yui3-skin-night .yui3-calendar-day-highlighted { background-color: #555555; } .yui3-skin-night .yui3-calendar-day-selected.yui3-calendar-day-highlighted { background-color: #777777; } PK\ 5(3.18.1/calendar/assets/calendar-core.cssnu[.yui3-calendar { } .yui3-calendar-content { } .yui3-calendar-column-hidden, .yui3-calendar-hidden { display:none; } .yui3-calendar-day { cursor: pointer; } .yui3-calendar-selection-disabled { cursor: default; } .yui3-calendar-prevmonth-day { cursor: default; } .yui3-calendar-nextmonth-day { cursor: default; } .yui3-calendar-content:hover .yui3-calendar-day, .yui3-calendar-content:hover .yui3-calendar-prevmonth-day, .yui3-calendar-content:hover .yui3-calendar-nextmonth-day { -moz-user-select: none; } PK\=|,3.18.1/calendar/calendar-min.jsnu[YUI.add("calendar",function(e,t){function b(){b.superclass.constructor.apply(this,arguments)}var n=e.ClassNameManager.getClassName,r="calendar",i=40,s=38,o=37,u=39,a=13,f=32,l=n(r,"day-selected"),c=n(r,"day-highlighted"),h=n(r,"day"),p=n(r,"prevmonth-day"),d=n(r,"nextmonth-day"),v=n(r,"grid"),m=e.DataType.Date,g=n(r,"pane"),y=e.UA.os;e.Calendar=e.extend(b,e.CalendarBase,{_keyEvents:[],_highlightedDateNode:null,_lastSelectedDate:null,initializer:function(){this.plug(e.Plugin.CalendarNavigator),this._keyEvents=[],this._highlightedDateNode=null,this._lastSelectedDate=null},_bindCalendarEvents:function(){var e=this.get("contentBox"),t=e.one("."+g);t.on("selectstart",this._preventSelectionStart),t.delegate("click",this._clickCalendar,"."+h+", ."+p+", ."+d,this),t.delegate("keydown",this._keydownCalendar,"."+v,this),t.delegate("focus",this._focusCalendarGrid,"."+v,this),t.delegate("focus",this._focusCalendarCell,"."+h,this),t.delegate("blur",this._blurCalendarGrid,"."+v+",."+h,this),this.after(["minimumDateChange","maximumDateChange"],this._afterCustomRendererChange)},_preventSelectionStart:function(e){e.preventDefault()},_highlightDateNode:function(e){this._unhighlightCurrentDateNode();var t=this._dateToNode(e);t.focus(),t.addClass(c)},_unhighlightCurrentDateNode:function(){var e=this.get("contentBox").all("."+c);e&&e.removeClass(c)},_getGridNumber:function(e){var t=e.get("id").split("_").reverse();return parseInt(t[0],10)},_blurCalendarGrid:function(){this._unhighlightCurrentDateNode()},_focusCalendarCell:function(e){this._highlightedDateNode=e.target,e.stopPropagation()},_focusCalendarGrid:function(){this._unhighlightCurrentDateNode(),this._highlightedDateNode=null},_keydownCalendar:function(e){var t=this._getGridNumber(e.target),n=this._highlightedDateNode?this._nodeToDate(this._highlightedDateNode):null,r=e.keyCode,c=0,h="",p,d,v,g,y;switch(r){case i:c=7,h="s";break;case s:c=-7,h="n";break;case o:c=-1,h="w";break;case u:c=1,h="e";break;case f:case a:e.preventDefault();if(this._highlightedDateNode){p=this.get("selectionMode");if(p==="single"&&!this._highlightedDateNode.hasClass(l))this._clearSelection(!0),this._addDateToSelection(n);else if(p==="multiple"||p==="multiple-sticky")this._highlightedDateNode.hasClass(l)?this._removeDateFromSelection(n):this._addDateToSelection(n)}}if(r===i||r===s||r===o||r===u)n||(n=m.addMonths(this.get("date"),t),c=0),e.preventDefault(),d=m.addDays(n,c),v=this.get("date"),g=m.addMonths(this.get("date"),this._paneNumber-1),y=new Date(g),g.setDate(m.daysInMonth(g)),m.isInRange(d,v,g)?this._highlightDateNode(d):m.isGreater(v,d)?m.isGreaterOrEqual(this.get("minimumDate"),v)||(this.set("date",m.addMonths(v,-1)),this._highlightDateNode(d)):m.isGreater(d,g)&&(m.isGreaterOrEqual(y,this.get("maximumDate"))||(this.set("date",m.addMonths(v,1)),this._highlightDateNode(d)))},_clickCalendar:function(e){var t=e.currentTarget,n=t.hasClass(h)&&!t.hasClass(p)&&!t.hasClass(d),r=t.hasClass(l),i;switch(this.get("selectionMode")){case"single":n&&(r||(this._clearSelection(!0),this._addDateToSelection(this._nodeToDate(t))));break;case"multiple-sticky":n&&(r?this._removeDateFromSelection(this._nodeToDate(t)):this._addDateToSelection(this._nodeToDate(t)));break;case"multiple":n&&(!e.metaKey&&!e.ctrlKey&&!e.shiftKey?(this._clearSelection(!0),this._lastSelectedDate=this._nodeToDate(t),this._addDateToSelection(this._lastSelectedDate)):(y==="macintosh"&&e.metaKey||y!=="macintosh"&&e.ctrlKey)&&!e.shiftKey?r?(this._removeDateFromSelection(this._nodeToDate(t)),this._lastSelectedDate=null):(this._lastSelectedDate=this._nodeToDate(t),this._addDateToSelection(this._lastSelectedDate)):(y==="macintosh"&&e.metaKey||y!=="macintosh"&&e.ctrlKey)&&e.shiftKey?this._lastSelectedDate?(i=this._nodeToDate(t),this._addDateRangeToSelection(i,this._lastSelectedDate),this._lastSelectedDate=i):(this._lastSelectedDate=this._nodeToDate(t),this._addDateToSelection(this._lastSelectedDate)):e.shiftKey&&(this._lastSelectedDate?(i=this._nodeToDate(t),this._clearSelection(!0),this._addDateRangeToSelection(i,this._lastSelectedDate),this._lastSelectedDate=i):(this._clearSelection(!0),this._lastSelectedDate=this._nodeToDate(t),this._addDateToSelection(this._lastSelectedDate))))}n?this.fire("dateClick",{cell:t,date:this._nodeToDate(t)}):t.hasClass(p)?this.fire("prevMonthClick"):t.hasClass(d)&&this.fire("nextMonthClick")},_canBeSelected:function(e){var t=this.get("minimumDate"),n=this.get("maximumDate");return t&&!m.isGreaterOrEqual(e,t)||n&&m.isGreater(e,n)?!1:b.superclass._canBeSelected.call(this,e)},_renderCustomRules:function(){b.superclass._renderCustomRules.call(this);var e=this.get("minimumDate"),t=this.get("maximumDate"),n=[],r,i,s,o;if(!e&&!t)return;for(o=0;o=0;r--){if(!m.isGreater(n[r],t))break;this._disableDate(n[r])}},subtractMonth:function(e){return this.set("date",m.addMonths(this.get("date"),-1)),e&&e.halt(),this},subtractYear:function(e){return this.set("date",m.addYears(this.get("date"),-1)),e&&e.halt(),this},addMonth:function(e){return this.set("date",m.addMonths(this.get("date"),1)),e&&e.halt(),this},addYear:function(e){return this.set("date",m.addYears(this.get("date"),1)),e&&e.halt(),this}},{NAME:"calendar",ATTRS:{selectionMode:{value:"single"},date:{value:new Date,lazyAdd:!1,setter:function(e){var t=this._normalizeDate(e),n=m.addMonths(t,this._paneNumber-1),r=this.get("minimumDate"),i=this.get("maximumDate");if((!r||m.isGreaterOrEqual(t,r))&&(!i||m.isGreaterOrEqual(i,n)))return t;if(r&&m.isGreater(r,t))return this._normalizeDate(r);if(i&&m.isGreater(n,i))return m.addMonths(this._normalizeDate(i),1-this._paneNumber)}},minimumDate:{value:null,setter:function(t){if(e.Lang.isDate(t)){var n=this.get("date"),r=this._normalizeTime(t);return n&&!m.isGreaterOrEqual(n,r)&&this.set("date",t),r}return null}}, maximumDate:{value:null,setter:function(t){if(e.Lang.isDate(t)){var n=this.get("date");return n&&!m.isGreaterOrEqual(t,m.addMonths(n,this._paneNumber-1))&&this.set("date",m.addMonths(this._normalizeDate(t),1-this._paneNumber)),this._normalizeTime(t)}return null}}}})},"3.18.1",{requires:["calendar-base","calendarnavigator"],skinnable:!0}); PK\8+QQ3.18.1/calendar/calendar.jsnu[YUI.add('calendar', function (Y, NAME) { /** * The Calendar component is a UI widget that allows users * to view dates in a two-dimensional month grid, as well as * to select one or more dates, or ranges of dates. Calendar * is generated dynamically and relies on the developer to * provide for a progressive enhancement alternative. * * * @module calendar */ var getCN = Y.ClassNameManager.getClassName, CALENDAR = 'calendar', KEY_DOWN = 40, KEY_UP = 38, KEY_LEFT = 37, KEY_RIGHT = 39, KEY_ENTER = 13, KEY_SPACE = 32, CAL_DAY_SELECTED = getCN(CALENDAR, 'day-selected'), CAL_DAY_HILITED = getCN(CALENDAR, 'day-highlighted'), CAL_DAY = getCN(CALENDAR, 'day'), CAL_PREVMONTH_DAY = getCN(CALENDAR, 'prevmonth-day'), CAL_NEXTMONTH_DAY = getCN(CALENDAR, 'nextmonth-day'), CAL_GRID = getCN(CALENDAR, 'grid'), ydate = Y.DataType.Date, CAL_PANE = getCN(CALENDAR, 'pane'), os = Y.UA.os; /** Create a calendar view to represent a single or multiple * month range of dates, rendered as a grid with date and * weekday labels. * * @class Calendar * @extends CalendarBase * @param config {Object} Configuration object (see Configuration attributes) * @constructor */ function Calendar() { Calendar.superclass.constructor.apply ( this, arguments ); } Y.Calendar = Y.extend(Calendar, Y.CalendarBase, { _keyEvents: [], _highlightedDateNode: null, /** * A property tracking the last selected date on the calendar, for the * purposes of multiple selection. * * @property _lastSelectedDate * @type Date * @default null * @private */ _lastSelectedDate: null, /** * Designated initializer. Activates the navigation plugin for the calendar. * * @method initializer */ initializer : function () { this.plug(Y.Plugin.CalendarNavigator); this._keyEvents = []; this._highlightedDateNode = null; this._lastSelectedDate = null; }, /** * Overrides the _bindCalendarEvents placeholder in CalendarBase * and binds calendar events during bindUI stage. * @method _bindCalendarEvents * @protected */ _bindCalendarEvents : function () { var contentBox = this.get('contentBox'), pane = contentBox.one("." + CAL_PANE); pane.on("selectstart", this._preventSelectionStart); pane.delegate("click", this._clickCalendar, "." + CAL_DAY + ", ." + CAL_PREVMONTH_DAY + ", ." + CAL_NEXTMONTH_DAY, this); pane.delegate("keydown", this._keydownCalendar, "." + CAL_GRID, this); pane.delegate("focus", this._focusCalendarGrid, "." + CAL_GRID, this); pane.delegate("focus", this._focusCalendarCell, "." + CAL_DAY, this); pane.delegate("blur", this._blurCalendarGrid, "." + CAL_GRID + ",." + CAL_DAY, this); this.after(['minimumDateChange', 'maximumDateChange'], this._afterCustomRendererChange); }, /** * Prevents text selection if it is started within the calendar pane * @method _preventSelectionStart * @param event {Event} The selectstart event * @protected */ _preventSelectionStart : function (event) { event.preventDefault(); }, /** * Highlights a specific date node with keyboard highlight class * @method _highlightDateNode * @param oDate {Date} Date corresponding the node to be highlighted * @protected */ _highlightDateNode : function (oDate) { this._unhighlightCurrentDateNode(); var newNode = this._dateToNode(oDate); newNode.focus(); newNode.addClass(CAL_DAY_HILITED); }, /** * Unhighlights a specific date node currently highlighted with keyboard highlight class * @method _unhighlightCurrentDateNode * @protected */ _unhighlightCurrentDateNode : function () { var allHilitedNodes = this.get("contentBox").all("." + CAL_DAY_HILITED); if (allHilitedNodes) { allHilitedNodes.removeClass(CAL_DAY_HILITED); } }, /** * Returns the grid number for a specific calendar grid (for multi-grid templates) * @method _getGridNumber * @param gridNode {Node} Node corresponding to a specific grid * @protected */ _getGridNumber : function (gridNode) { var idParts = gridNode.get("id").split("_").reverse(); return parseInt(idParts[0], 10); }, /** * Handler for loss of focus of calendar grid * @method _blurCalendarGrid * @protected */ _blurCalendarGrid : function () { this._unhighlightCurrentDateNode(); }, /** * Handler for gain of focus of calendar cell * @method _focusCalendarCell * @protected */ _focusCalendarCell : function (ev) { this._highlightedDateNode = ev.target; ev.stopPropagation(); }, /** * Handler for gain of focus of calendar grid * @method _focusCalendarGrid * @protected */ _focusCalendarGrid : function () { this._unhighlightCurrentDateNode(); this._highlightedDateNode = null; }, /** * Handler for keyboard press on a calendar grid * @method _keydownCalendar * @protected */ _keydownCalendar : function (ev) { var gridNum = this._getGridNumber(ev.target), curDate = !this._highlightedDateNode ? null : this._nodeToDate(this._highlightedDateNode), keyCode = ev.keyCode, dayNum = 0, dir = '', selMode, newDate, startDate, endDate, lastPaneDate; switch(keyCode) { case KEY_DOWN: dayNum = 7; dir = 's'; break; case KEY_UP: dayNum = -7; dir = 'n'; break; case KEY_LEFT: dayNum = -1; dir = 'w'; break; case KEY_RIGHT: dayNum = 1; dir = 'e'; break; case KEY_SPACE: case KEY_ENTER: ev.preventDefault(); if (this._highlightedDateNode) { selMode = this.get("selectionMode"); if (selMode === "single" && !this._highlightedDateNode.hasClass(CAL_DAY_SELECTED)) { this._clearSelection(true); this._addDateToSelection(curDate); } else if (selMode === "multiple" || selMode === "multiple-sticky") { if (this._highlightedDateNode.hasClass(CAL_DAY_SELECTED)) { this._removeDateFromSelection(curDate); } else { this._addDateToSelection(curDate); } } } break; } if (keyCode === KEY_DOWN || keyCode === KEY_UP || keyCode === KEY_LEFT || keyCode === KEY_RIGHT) { if (!curDate) { curDate = ydate.addMonths(this.get("date"), gridNum); dayNum = 0; } ev.preventDefault(); newDate = ydate.addDays(curDate, dayNum); startDate = this.get("date"); endDate = ydate.addMonths(this.get("date"), this._paneNumber - 1); lastPaneDate = new Date(endDate); endDate.setDate(ydate.daysInMonth(endDate)); if (ydate.isInRange(newDate, startDate, endDate)) { /* var paneShift = (newDate.getMonth() - curDate.getMonth()) % 10; if (paneShift != 0) { var newGridNum = gridNum + paneShift, contentBox = this.get('contentBox'), newPane = contentBox.one("#" + this._calendarId + "_pane_" + newGridNum); newPane.focus(); } */ this._highlightDateNode(newDate); } else if (ydate.isGreater(startDate, newDate)) { if (!ydate.isGreaterOrEqual(this.get("minimumDate"), startDate)) { this.set("date", ydate.addMonths(startDate, -1)); this._highlightDateNode(newDate); } } else if (ydate.isGreater(newDate, endDate)) { if (!ydate.isGreaterOrEqual(lastPaneDate, this.get("maximumDate"))) { this.set("date", ydate.addMonths(startDate, 1)); this._highlightDateNode(newDate); } } } }, /** * Handles the calendar clicks based on selection mode. * @method _clickCalendar * @param {Event} ev A click event * @private */ _clickCalendar : function (ev) { var clickedCell = ev.currentTarget, clickedCellIsDay = clickedCell.hasClass(CAL_DAY) && !clickedCell.hasClass(CAL_PREVMONTH_DAY) && !clickedCell.hasClass(CAL_NEXTMONTH_DAY), clickedCellIsSelected = clickedCell.hasClass(CAL_DAY_SELECTED), selectedDate; switch (this.get("selectionMode")) { case("single"): if (clickedCellIsDay) { if (!clickedCellIsSelected) { this._clearSelection(true); this._addDateToSelection(this._nodeToDate(clickedCell)); } } break; case("multiple-sticky"): if (clickedCellIsDay) { if (clickedCellIsSelected) { this._removeDateFromSelection(this._nodeToDate(clickedCell)); } else { this._addDateToSelection(this._nodeToDate(clickedCell)); } } break; case("multiple"): if (clickedCellIsDay) { if (!ev.metaKey && !ev.ctrlKey && !ev.shiftKey) { this._clearSelection(true); this._lastSelectedDate = this._nodeToDate(clickedCell); this._addDateToSelection(this._lastSelectedDate); } else if (((os === 'macintosh' && ev.metaKey) || (os !== 'macintosh' && ev.ctrlKey)) && !ev.shiftKey) { if (clickedCellIsSelected) { this._removeDateFromSelection(this._nodeToDate(clickedCell)); this._lastSelectedDate = null; } else { this._lastSelectedDate = this._nodeToDate(clickedCell); this._addDateToSelection(this._lastSelectedDate); } } else if (((os === 'macintosh' && ev.metaKey) || (os !== 'macintosh' && ev.ctrlKey)) && ev.shiftKey) { if (this._lastSelectedDate) { selectedDate = this._nodeToDate(clickedCell); this._addDateRangeToSelection(selectedDate, this._lastSelectedDate); this._lastSelectedDate = selectedDate; } else { this._lastSelectedDate = this._nodeToDate(clickedCell); this._addDateToSelection(this._lastSelectedDate); } } else if (ev.shiftKey) { if (this._lastSelectedDate) { selectedDate = this._nodeToDate(clickedCell); this._clearSelection(true); this._addDateRangeToSelection(selectedDate, this._lastSelectedDate); this._lastSelectedDate = selectedDate; } else { this._clearSelection(true); this._lastSelectedDate = this._nodeToDate(clickedCell); this._addDateToSelection(this._lastSelectedDate); } } } break; } if (clickedCellIsDay) { /** * Fired when a specific date cell in the calendar is clicked. The event carries a * payload which includes a `cell` property corresponding to the node of the actual * date cell, and a `date` property, with the `Date` that was clicked. * * @event dateClick */ this.fire("dateClick", {cell: clickedCell, date: this._nodeToDate(clickedCell)}); } else if (clickedCell.hasClass(CAL_PREVMONTH_DAY)) { /** * Fired when any of the previous month's days displayed before the calendar grid * are clicked. * * @event prevMonthClick */ this.fire("prevMonthClick"); } else if (clickedCell.hasClass(CAL_NEXTMONTH_DAY)) { /** * Fired when any of the next month's days displayed after the calendar grid * are clicked. * * @event nextMonthClick */ this.fire("nextMonthClick"); } }, /** * Overrides CalendarBase.prototype._canBeSelected to disable * nodes earlier than minimumDate and later than maximumDate * @method _canBeSelected * @private */ _canBeSelected : function (date) { var minDate = this.get('minimumDate'), maxDate = this.get('maximumDate'); if ((minDate && !ydate.isGreaterOrEqual(date, minDate)) || (maxDate && ydate.isGreater(date, maxDate))) { return false; } return Calendar.superclass._canBeSelected.call(this, date); }, /** * Overrides CalendarBase.prototype._renderCustomRules to disable * nodes earlier than minimumDate and later than maximumDate * @method _renderCustomRules * @private */ _renderCustomRules: function () { Calendar.superclass._renderCustomRules.call(this); var minDate = this.get('minimumDate'), maxDate = this.get('maximumDate'), dates = [], i, l, paneDate, paneNum; if (!minDate && !maxDate) { return; } for (paneNum = 0; paneNum < this._paneNumber; paneNum++) { paneDate = ydate.addMonths(this.get("date"), paneNum); dates = dates.concat(ydate.listOfDatesInMonth(paneDate)); } if (minDate) { for (i = 0, l = dates.length; i < l; i++) { if (!ydate.isGreaterOrEqual(dates[i], minDate)) { this._disableDate(dates[i]); } else { break; } } } if (maxDate) { for (i = dates.length - 1; i >= 0; i--) { if (ydate.isGreater(dates[i], maxDate)) { this._disableDate(dates[i]); } else { break; } } } }, /** * Subtracts one month from the current calendar view. * @method subtractMonth * @return {Calendar} A reference to this object * @chainable */ subtractMonth : function (e) { this.set("date", ydate.addMonths(this.get("date"), -1)); if (e) { e.halt(); } return this; }, /** * Subtracts one year from the current calendar view. * @method subtractYear * @return {Calendar} A reference to this object * @chainable */ subtractYear : function (e) { this.set("date", ydate.addYears(this.get("date"), -1)); if (e) { e.halt(); } return this; }, /** * Adds one month to the current calendar view. * @method addMonth * @return {Calendar} A reference to this object * @chainable */ addMonth : function (e) { this.set("date", ydate.addMonths(this.get("date"), 1)); if (e) { e.halt(); } return this; }, /** * Adds one year to the current calendar view. * @method addYear * @return {Calendar} A reference to this object * @chainable */ addYear : function (e) { this.set("date", ydate.addYears(this.get("date"), 1)); if (e) { e.halt(); } return this; } }, { /** * The identity of the widget. * * @property NAME * @type String * @default 'calendar' * @readOnly * @protected * @static */ NAME: "calendar", /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * A setting specifying the type of selection the calendar allows. * Possible values include: *
    *
  • `single` - One date at a time
  • *
  • `multiple-sticky` - Multiple dates, selected one at a time (the dates "stick"). This option * is appropriate for mobile devices, where function keys from the keyboard are not available.
  • *
  • `multiple` - Multiple dates, selected with Ctrl/Meta keys for additional single * dates, and Shift key for date ranges.
  • * * @attribute selectionMode * @type String * @default single */ selectionMode: { value: "single" }, /** * The date corresponding to the current calendar view. Always * normalized to the first of the month that contains the date * at assignment time. Used as the first date visible in the * calendar. * * @attribute date * @type Date * @default Today's date as set on the user's computer. */ date: { value: new Date(), lazyAdd: false, setter: function (val) { var newDate = this._normalizeDate(val), newEndDate = ydate.addMonths(newDate, this._paneNumber - 1), minDate = this.get("minimumDate"), maxDate = this.get("maximumDate"); if ((!minDate || ydate.isGreaterOrEqual(newDate, minDate)) && (!maxDate || ydate.isGreaterOrEqual(maxDate, newEndDate)) ) { return newDate; } else if (minDate && ydate.isGreater(minDate, newDate)) { return this._normalizeDate(minDate); } else if (maxDate && ydate.isGreater(newEndDate, maxDate)) { return ydate.addMonths(this._normalizeDate(maxDate), 1 - this._paneNumber); } } }, /** * Unless minimumDate is null, it will not be possible to display and select dates earlier than this one. * * @attribute minimumDate * @type Date * @default null */ minimumDate: { value: null, setter: function (val) { if (Y.Lang.isDate(val)) { var curDate = this.get('date'), newMin = this._normalizeTime(val); if (curDate && !ydate.isGreaterOrEqual(curDate, newMin)) { this.set('date', val); } return newMin; } else { return null; } } }, /** * Unless maximumDate is null, it will not be possible to display and select dates later than this one. * * @attribute maximumDate * @type Date * @default null */ maximumDate: { value: null, setter: function (val) { if (Y.Lang.isDate(val)) { var curDate = this.get('date'); if (curDate && !ydate.isGreaterOrEqual(val, ydate.addMonths(curDate, this._paneNumber - 1))) { this.set('date', ydate.addMonths(this._normalizeDate(val), 1 - this._paneNumber)); } return this._normalizeTime(val); } else { return null; } } } } }); }, '3.18.1', {"requires": ["calendar-base", "calendarnavigator"], "skinnable": true}); PK\8+QQ!3.18.1/calendar/calendar-debug.jsnu[YUI.add('calendar', function (Y, NAME) { /** * The Calendar component is a UI widget that allows users * to view dates in a two-dimensional month grid, as well as * to select one or more dates, or ranges of dates. Calendar * is generated dynamically and relies on the developer to * provide for a progressive enhancement alternative. * * * @module calendar */ var getCN = Y.ClassNameManager.getClassName, CALENDAR = 'calendar', KEY_DOWN = 40, KEY_UP = 38, KEY_LEFT = 37, KEY_RIGHT = 39, KEY_ENTER = 13, KEY_SPACE = 32, CAL_DAY_SELECTED = getCN(CALENDAR, 'day-selected'), CAL_DAY_HILITED = getCN(CALENDAR, 'day-highlighted'), CAL_DAY = getCN(CALENDAR, 'day'), CAL_PREVMONTH_DAY = getCN(CALENDAR, 'prevmonth-day'), CAL_NEXTMONTH_DAY = getCN(CALENDAR, 'nextmonth-day'), CAL_GRID = getCN(CALENDAR, 'grid'), ydate = Y.DataType.Date, CAL_PANE = getCN(CALENDAR, 'pane'), os = Y.UA.os; /** Create a calendar view to represent a single or multiple * month range of dates, rendered as a grid with date and * weekday labels. * * @class Calendar * @extends CalendarBase * @param config {Object} Configuration object (see Configuration attributes) * @constructor */ function Calendar() { Calendar.superclass.constructor.apply ( this, arguments ); } Y.Calendar = Y.extend(Calendar, Y.CalendarBase, { _keyEvents: [], _highlightedDateNode: null, /** * A property tracking the last selected date on the calendar, for the * purposes of multiple selection. * * @property _lastSelectedDate * @type Date * @default null * @private */ _lastSelectedDate: null, /** * Designated initializer. Activates the navigation plugin for the calendar. * * @method initializer */ initializer : function () { this.plug(Y.Plugin.CalendarNavigator); this._keyEvents = []; this._highlightedDateNode = null; this._lastSelectedDate = null; }, /** * Overrides the _bindCalendarEvents placeholder in CalendarBase * and binds calendar events during bindUI stage. * @method _bindCalendarEvents * @protected */ _bindCalendarEvents : function () { var contentBox = this.get('contentBox'), pane = contentBox.one("." + CAL_PANE); pane.on("selectstart", this._preventSelectionStart); pane.delegate("click", this._clickCalendar, "." + CAL_DAY + ", ." + CAL_PREVMONTH_DAY + ", ." + CAL_NEXTMONTH_DAY, this); pane.delegate("keydown", this._keydownCalendar, "." + CAL_GRID, this); pane.delegate("focus", this._focusCalendarGrid, "." + CAL_GRID, this); pane.delegate("focus", this._focusCalendarCell, "." + CAL_DAY, this); pane.delegate("blur", this._blurCalendarGrid, "." + CAL_GRID + ",." + CAL_DAY, this); this.after(['minimumDateChange', 'maximumDateChange'], this._afterCustomRendererChange); }, /** * Prevents text selection if it is started within the calendar pane * @method _preventSelectionStart * @param event {Event} The selectstart event * @protected */ _preventSelectionStart : function (event) { event.preventDefault(); }, /** * Highlights a specific date node with keyboard highlight class * @method _highlightDateNode * @param oDate {Date} Date corresponding the node to be highlighted * @protected */ _highlightDateNode : function (oDate) { this._unhighlightCurrentDateNode(); var newNode = this._dateToNode(oDate); newNode.focus(); newNode.addClass(CAL_DAY_HILITED); }, /** * Unhighlights a specific date node currently highlighted with keyboard highlight class * @method _unhighlightCurrentDateNode * @protected */ _unhighlightCurrentDateNode : function () { var allHilitedNodes = this.get("contentBox").all("." + CAL_DAY_HILITED); if (allHilitedNodes) { allHilitedNodes.removeClass(CAL_DAY_HILITED); } }, /** * Returns the grid number for a specific calendar grid (for multi-grid templates) * @method _getGridNumber * @param gridNode {Node} Node corresponding to a specific grid * @protected */ _getGridNumber : function (gridNode) { var idParts = gridNode.get("id").split("_").reverse(); return parseInt(idParts[0], 10); }, /** * Handler for loss of focus of calendar grid * @method _blurCalendarGrid * @protected */ _blurCalendarGrid : function () { this._unhighlightCurrentDateNode(); }, /** * Handler for gain of focus of calendar cell * @method _focusCalendarCell * @protected */ _focusCalendarCell : function (ev) { this._highlightedDateNode = ev.target; ev.stopPropagation(); }, /** * Handler for gain of focus of calendar grid * @method _focusCalendarGrid * @protected */ _focusCalendarGrid : function () { this._unhighlightCurrentDateNode(); this._highlightedDateNode = null; }, /** * Handler for keyboard press on a calendar grid * @method _keydownCalendar * @protected */ _keydownCalendar : function (ev) { var gridNum = this._getGridNumber(ev.target), curDate = !this._highlightedDateNode ? null : this._nodeToDate(this._highlightedDateNode), keyCode = ev.keyCode, dayNum = 0, dir = '', selMode, newDate, startDate, endDate, lastPaneDate; switch(keyCode) { case KEY_DOWN: dayNum = 7; dir = 's'; break; case KEY_UP: dayNum = -7; dir = 'n'; break; case KEY_LEFT: dayNum = -1; dir = 'w'; break; case KEY_RIGHT: dayNum = 1; dir = 'e'; break; case KEY_SPACE: case KEY_ENTER: ev.preventDefault(); if (this._highlightedDateNode) { selMode = this.get("selectionMode"); if (selMode === "single" && !this._highlightedDateNode.hasClass(CAL_DAY_SELECTED)) { this._clearSelection(true); this._addDateToSelection(curDate); } else if (selMode === "multiple" || selMode === "multiple-sticky") { if (this._highlightedDateNode.hasClass(CAL_DAY_SELECTED)) { this._removeDateFromSelection(curDate); } else { this._addDateToSelection(curDate); } } } break; } if (keyCode === KEY_DOWN || keyCode === KEY_UP || keyCode === KEY_LEFT || keyCode === KEY_RIGHT) { if (!curDate) { curDate = ydate.addMonths(this.get("date"), gridNum); dayNum = 0; } ev.preventDefault(); newDate = ydate.addDays(curDate, dayNum); startDate = this.get("date"); endDate = ydate.addMonths(this.get("date"), this._paneNumber - 1); lastPaneDate = new Date(endDate); endDate.setDate(ydate.daysInMonth(endDate)); if (ydate.isInRange(newDate, startDate, endDate)) { /* var paneShift = (newDate.getMonth() - curDate.getMonth()) % 10; if (paneShift != 0) { var newGridNum = gridNum + paneShift, contentBox = this.get('contentBox'), newPane = contentBox.one("#" + this._calendarId + "_pane_" + newGridNum); newPane.focus(); } */ this._highlightDateNode(newDate); } else if (ydate.isGreater(startDate, newDate)) { if (!ydate.isGreaterOrEqual(this.get("minimumDate"), startDate)) { this.set("date", ydate.addMonths(startDate, -1)); this._highlightDateNode(newDate); } } else if (ydate.isGreater(newDate, endDate)) { if (!ydate.isGreaterOrEqual(lastPaneDate, this.get("maximumDate"))) { this.set("date", ydate.addMonths(startDate, 1)); this._highlightDateNode(newDate); } } } }, /** * Handles the calendar clicks based on selection mode. * @method _clickCalendar * @param {Event} ev A click event * @private */ _clickCalendar : function (ev) { var clickedCell = ev.currentTarget, clickedCellIsDay = clickedCell.hasClass(CAL_DAY) && !clickedCell.hasClass(CAL_PREVMONTH_DAY) && !clickedCell.hasClass(CAL_NEXTMONTH_DAY), clickedCellIsSelected = clickedCell.hasClass(CAL_DAY_SELECTED), selectedDate; switch (this.get("selectionMode")) { case("single"): if (clickedCellIsDay) { if (!clickedCellIsSelected) { this._clearSelection(true); this._addDateToSelection(this._nodeToDate(clickedCell)); } } break; case("multiple-sticky"): if (clickedCellIsDay) { if (clickedCellIsSelected) { this._removeDateFromSelection(this._nodeToDate(clickedCell)); } else { this._addDateToSelection(this._nodeToDate(clickedCell)); } } break; case("multiple"): if (clickedCellIsDay) { if (!ev.metaKey && !ev.ctrlKey && !ev.shiftKey) { this._clearSelection(true); this._lastSelectedDate = this._nodeToDate(clickedCell); this._addDateToSelection(this._lastSelectedDate); } else if (((os === 'macintosh' && ev.metaKey) || (os !== 'macintosh' && ev.ctrlKey)) && !ev.shiftKey) { if (clickedCellIsSelected) { this._removeDateFromSelection(this._nodeToDate(clickedCell)); this._lastSelectedDate = null; } else { this._lastSelectedDate = this._nodeToDate(clickedCell); this._addDateToSelection(this._lastSelectedDate); } } else if (((os === 'macintosh' && ev.metaKey) || (os !== 'macintosh' && ev.ctrlKey)) && ev.shiftKey) { if (this._lastSelectedDate) { selectedDate = this._nodeToDate(clickedCell); this._addDateRangeToSelection(selectedDate, this._lastSelectedDate); this._lastSelectedDate = selectedDate; } else { this._lastSelectedDate = this._nodeToDate(clickedCell); this._addDateToSelection(this._lastSelectedDate); } } else if (ev.shiftKey) { if (this._lastSelectedDate) { selectedDate = this._nodeToDate(clickedCell); this._clearSelection(true); this._addDateRangeToSelection(selectedDate, this._lastSelectedDate); this._lastSelectedDate = selectedDate; } else { this._clearSelection(true); this._lastSelectedDate = this._nodeToDate(clickedCell); this._addDateToSelection(this._lastSelectedDate); } } } break; } if (clickedCellIsDay) { /** * Fired when a specific date cell in the calendar is clicked. The event carries a * payload which includes a `cell` property corresponding to the node of the actual * date cell, and a `date` property, with the `Date` that was clicked. * * @event dateClick */ this.fire("dateClick", {cell: clickedCell, date: this._nodeToDate(clickedCell)}); } else if (clickedCell.hasClass(CAL_PREVMONTH_DAY)) { /** * Fired when any of the previous month's days displayed before the calendar grid * are clicked. * * @event prevMonthClick */ this.fire("prevMonthClick"); } else if (clickedCell.hasClass(CAL_NEXTMONTH_DAY)) { /** * Fired when any of the next month's days displayed after the calendar grid * are clicked. * * @event nextMonthClick */ this.fire("nextMonthClick"); } }, /** * Overrides CalendarBase.prototype._canBeSelected to disable * nodes earlier than minimumDate and later than maximumDate * @method _canBeSelected * @private */ _canBeSelected : function (date) { var minDate = this.get('minimumDate'), maxDate = this.get('maximumDate'); if ((minDate && !ydate.isGreaterOrEqual(date, minDate)) || (maxDate && ydate.isGreater(date, maxDate))) { return false; } return Calendar.superclass._canBeSelected.call(this, date); }, /** * Overrides CalendarBase.prototype._renderCustomRules to disable * nodes earlier than minimumDate and later than maximumDate * @method _renderCustomRules * @private */ _renderCustomRules: function () { Calendar.superclass._renderCustomRules.call(this); var minDate = this.get('minimumDate'), maxDate = this.get('maximumDate'), dates = [], i, l, paneDate, paneNum; if (!minDate && !maxDate) { return; } for (paneNum = 0; paneNum < this._paneNumber; paneNum++) { paneDate = ydate.addMonths(this.get("date"), paneNum); dates = dates.concat(ydate.listOfDatesInMonth(paneDate)); } if (minDate) { for (i = 0, l = dates.length; i < l; i++) { if (!ydate.isGreaterOrEqual(dates[i], minDate)) { this._disableDate(dates[i]); } else { break; } } } if (maxDate) { for (i = dates.length - 1; i >= 0; i--) { if (ydate.isGreater(dates[i], maxDate)) { this._disableDate(dates[i]); } else { break; } } } }, /** * Subtracts one month from the current calendar view. * @method subtractMonth * @return {Calendar} A reference to this object * @chainable */ subtractMonth : function (e) { this.set("date", ydate.addMonths(this.get("date"), -1)); if (e) { e.halt(); } return this; }, /** * Subtracts one year from the current calendar view. * @method subtractYear * @return {Calendar} A reference to this object * @chainable */ subtractYear : function (e) { this.set("date", ydate.addYears(this.get("date"), -1)); if (e) { e.halt(); } return this; }, /** * Adds one month to the current calendar view. * @method addMonth * @return {Calendar} A reference to this object * @chainable */ addMonth : function (e) { this.set("date", ydate.addMonths(this.get("date"), 1)); if (e) { e.halt(); } return this; }, /** * Adds one year to the current calendar view. * @method addYear * @return {Calendar} A reference to this object * @chainable */ addYear : function (e) { this.set("date", ydate.addYears(this.get("date"), 1)); if (e) { e.halt(); } return this; } }, { /** * The identity of the widget. * * @property NAME * @type String * @default 'calendar' * @readOnly * @protected * @static */ NAME: "calendar", /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * A setting specifying the type of selection the calendar allows. * Possible values include: *
      *
    • `single` - One date at a time
    • *
    • `multiple-sticky` - Multiple dates, selected one at a time (the dates "stick"). This option * is appropriate for mobile devices, where function keys from the keyboard are not available.
    • *
    • `multiple` - Multiple dates, selected with Ctrl/Meta keys for additional single * dates, and Shift key for date ranges.
    • * * @attribute selectionMode * @type String * @default single */ selectionMode: { value: "single" }, /** * The date corresponding to the current calendar view. Always * normalized to the first of the month that contains the date * at assignment time. Used as the first date visible in the * calendar. * * @attribute date * @type Date * @default Today's date as set on the user's computer. */ date: { value: new Date(), lazyAdd: false, setter: function (val) { var newDate = this._normalizeDate(val), newEndDate = ydate.addMonths(newDate, this._paneNumber - 1), minDate = this.get("minimumDate"), maxDate = this.get("maximumDate"); if ((!minDate || ydate.isGreaterOrEqual(newDate, minDate)) && (!maxDate || ydate.isGreaterOrEqual(maxDate, newEndDate)) ) { return newDate; } else if (minDate && ydate.isGreater(minDate, newDate)) { return this._normalizeDate(minDate); } else if (maxDate && ydate.isGreater(newEndDate, maxDate)) { return ydate.addMonths(this._normalizeDate(maxDate), 1 - this._paneNumber); } } }, /** * Unless minimumDate is null, it will not be possible to display and select dates earlier than this one. * * @attribute minimumDate * @type Date * @default null */ minimumDate: { value: null, setter: function (val) { if (Y.Lang.isDate(val)) { var curDate = this.get('date'), newMin = this._normalizeTime(val); if (curDate && !ydate.isGreaterOrEqual(curDate, newMin)) { this.set('date', val); } return newMin; } else { return null; } } }, /** * Unless maximumDate is null, it will not be possible to display and select dates later than this one. * * @attribute maximumDate * @type Date * @default null */ maximumDate: { value: null, setter: function (val) { if (Y.Lang.isDate(val)) { var curDate = this.get('date'); if (curDate && !ydate.isGreaterOrEqual(val, ydate.addMonths(curDate, this._paneNumber - 1))) { this.set('date', ydate.addMonths(this._normalizeDate(val), 1 - this._paneNumber)); } return this._normalizeTime(val); } else { return null; } } } } }); }, '3.18.1', {"requires": ["calendar-base", "calendarnavigator"], "skinnable": true}); PK\DUU%3.18.1/anim-color/anim-color-debug.jsnu[YUI.add('anim-color', function (Y, NAME) { /** * Adds support for color properties in to * and from attributes. * @module anim * @submodule anim-color */ var NUM = Number; Y.Anim.getUpdatedColorValue = function(fromColor, toColor, elapsed, duration, fn) { fromColor = Y.Color.re_RGB.exec(Y.Color.toRGB(fromColor)); toColor = Y.Color.re_RGB.exec(Y.Color.toRGB(toColor)); if (!fromColor || fromColor.length < 3 || !toColor || toColor.length < 3) { Y.error('invalid from or to passed to color behavior'); } return 'rgb(' + [ Math.floor(fn(elapsed, NUM(fromColor[1]), NUM(toColor[1]) - NUM(fromColor[1]), duration)), Math.floor(fn(elapsed, NUM(fromColor[2]), NUM(toColor[2]) - NUM(fromColor[2]), duration)), Math.floor(fn(elapsed, NUM(fromColor[3]), NUM(toColor[3]) - NUM(fromColor[3]), duration)) ].join(', ') + ')'; }; Y.Anim.behaviors.color = { set: function(anim, att, from, to, elapsed, duration, fn) { anim._node.setStyle(att, Y.Anim.getUpdatedColorValue(from, to, elapsed, duration, fn)); }, // TODO: default bgcolor const get: function(anim, att) { var val = anim._node.getComputedStyle(att); val = (val === 'transparent') ? 'rgb(255, 255, 255)' : val; return val; } }; Y.each(['backgroundColor', 'borderColor', 'borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor'], function(v) { Y.Anim.behaviors[v] = Y.Anim.behaviors.color; } ); }, '3.18.1', {"requires": ["anim-base"]}); PK\DUU3.18.1/anim-color/anim-color.jsnu[YUI.add('anim-color', function (Y, NAME) { /** * Adds support for color properties in to * and from attributes. * @module anim * @submodule anim-color */ var NUM = Number; Y.Anim.getUpdatedColorValue = function(fromColor, toColor, elapsed, duration, fn) { fromColor = Y.Color.re_RGB.exec(Y.Color.toRGB(fromColor)); toColor = Y.Color.re_RGB.exec(Y.Color.toRGB(toColor)); if (!fromColor || fromColor.length < 3 || !toColor || toColor.length < 3) { Y.error('invalid from or to passed to color behavior'); } return 'rgb(' + [ Math.floor(fn(elapsed, NUM(fromColor[1]), NUM(toColor[1]) - NUM(fromColor[1]), duration)), Math.floor(fn(elapsed, NUM(fromColor[2]), NUM(toColor[2]) - NUM(fromColor[2]), duration)), Math.floor(fn(elapsed, NUM(fromColor[3]), NUM(toColor[3]) - NUM(fromColor[3]), duration)) ].join(', ') + ')'; }; Y.Anim.behaviors.color = { set: function(anim, att, from, to, elapsed, duration, fn) { anim._node.setStyle(att, Y.Anim.getUpdatedColorValue(from, to, elapsed, duration, fn)); }, // TODO: default bgcolor const get: function(anim, att) { var val = anim._node.getComputedStyle(att); val = (val === 'transparent') ? 'rgb(255, 255, 255)' : val; return val; } }; Y.each(['backgroundColor', 'borderColor', 'borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor'], function(v) { Y.Anim.behaviors[v] = Y.Anim.behaviors.color; } ); }, '3.18.1', {"requires": ["anim-base"]}); PK\6UU#3.18.1/anim-color/anim-color-min.jsnu[YUI.add("anim-color",function(e,t){var n=Number;e.Anim.getUpdatedColorValue=function(t,r,i,s,o){return t=e.Color.re_RGB.exec(e.Color.toRGB(t)),r=e.Color.re_RGB.exec(e.Color.toRGB(r)),(!t||t.length<3||!r||r.length<3)&&e.error("invalid from or to passed to color behavior"),"rgb("+[Math.floor(o(i,n(t[1]),n(r[1])-n(t[1]),s)),Math.floor(o(i,n(t[2]),n(r[2])-n(t[2]),s)),Math.floor(o(i,n(t[3]),n(r[3])-n(t[3]),s))].join(", ")+")"},e.Anim.behaviors.color={set:function(t,n,r,i,s,o,u){t._node.setStyle(n,e.Anim.getUpdatedColorValue(r,i,s,o,u))},get:function(e,t){var n=e._node.getComputedStyle(t);return n=n==="transparent"?"rgb(255, 255, 255)":n,n}},e.each(["backgroundColor","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"],function(t){e.Anim.behaviors[t]=e.Anim.behaviors.color})},"3.18.1",{requires:["anim-base"]}); PK\x2?3.18.1/loader-pathogen-encoder/loader-pathogen-encoder-debug.jsnu[YUI.add('loader-base', function (Y, NAME) { /** * The YUI loader core * @module loader * @submodule loader-base */ (function() { var VERSION = Y.version, BUILD = '/build/', ROOT = VERSION + '/', CDN_BASE = Y.Env.base, GALLERY_VERSION = 'gallery-2014.07.31-18-26', TNT = '2in3', TNT_VERSION = '4', YUI2_VERSION = '2.9.0', COMBO_BASE = CDN_BASE + 'combo?', META = { version: VERSION, root: ROOT, base: Y.Env.base, comboBase: COMBO_BASE, skin: { defaultSkin: 'sam', base: 'assets/skins/', path: 'skin.css', after: [ 'cssreset', 'cssfonts', 'cssgrids', 'cssbase', 'cssreset-context', 'cssfonts-context' ] }, groups: {}, patterns: {} }, groups = META.groups, yui2Update = function(tnt, yui2, config) { var root = TNT + '.' + (tnt || TNT_VERSION) + '/' + (yui2 || YUI2_VERSION) + BUILD, base = (config && config.base) ? config.base : CDN_BASE, combo = (config && config.comboBase) ? config.comboBase : COMBO_BASE; groups.yui2.base = base + root; groups.yui2.root = root; groups.yui2.comboBase = combo; }, galleryUpdate = function(tag, config) { var root = (tag || GALLERY_VERSION) + BUILD, base = (config && config.base) ? config.base : CDN_BASE, combo = (config && config.comboBase) ? config.comboBase : COMBO_BASE; groups.gallery.base = base + root; groups.gallery.root = root; groups.gallery.comboBase = combo; }; groups[VERSION] = {}; groups.gallery = { ext: false, combine: true, comboBase: COMBO_BASE, update: galleryUpdate, patterns: { 'gallery-': {}, 'lang/gallery-': {}, 'gallerycss-': { type: 'css' } } }; groups.yui2 = { combine: true, ext: false, comboBase: COMBO_BASE, update: yui2Update, patterns: { 'yui2-': { configFn: function(me) { if (/-skin|reset|fonts|grids|base/.test(me.name)) { me.type = 'css'; me.path = me.path.replace(/\.js/, '.css'); // this makes skins in builds earlier than // 2.6.0 work as long as combine is false me.path = me.path.replace(/\/yui2-skin/, '/assets/skins/sam/yui2-skin'); } } } } }; galleryUpdate(); yui2Update(); if (YUI.Env[VERSION]) { Y.mix(META, YUI.Env[VERSION], false, [ 'modules', 'groups', 'skin' ], 0, true); } YUI.Env[VERSION] = META; }()); /*jslint forin: true, maxlen: 350 */ /** * Loader dynamically loads script and css files. It includes the dependency * information for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It can also load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * @module loader * @main loader * @submodule loader-base */ var NOT_FOUND = {}, NO_REQUIREMENTS = [], MAX_URL_LENGTH = 1024, GLOBAL_ENV = YUI.Env, GLOBAL_LOADED = GLOBAL_ENV._loaded, CSS = 'css', JS = 'js', INTL = 'intl', DEFAULT_SKIN = 'sam', VERSION = Y.version, ROOT_LANG = '', YObject = Y.Object, oeach = YObject.each, yArray = Y.Array, _queue = GLOBAL_ENV._loaderQueue, META = GLOBAL_ENV[VERSION], SKIN_PREFIX = 'skin-', L = Y.Lang, ON_PAGE = GLOBAL_ENV.mods, modulekey, _path = function(dir, file, type, nomin) { var path = dir + '/' + file; if (!nomin) { path += '-min'; } path += '.' + (type || CSS); return path; }; if (!YUI.Env._cssLoaded) { YUI.Env._cssLoaded = {}; } /** * The component metadata is stored in Y.Env.meta. * Part of the loader module. * @property meta * @for YUI */ Y.Env.meta = META; /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. You can also specify an external, custom combo service to host * your modules as well. var Y = YUI(); var loader = new Y.Loader({ filter: 'debug', base: '../../', root: 'build/', combine: true, require: ['node', 'dd', 'console'] }); var out = loader.resolve(true); * If the Loader needs to be patched before it is used for the first time, it * should be done through the `doBeforeLoader` hook. Simply make the patch * available via configuration before YUI is loaded: YUI_config = YUI_config || {}; YUI_config.doBeforeLoader = function (config) { var resolve = this.context.Loader.prototype.resolve; this.context.Loader.prototype.resolve = function () { // do something here return resolve.apply(this, arguments); }; }; * @constructor * @class Loader * @param {Object} config an optional set of configuration options. * @param {String} config.base The base dir which to fetch this module from * @param {String} config.comboBase The Combo service base path. Ex: `http://yui.yahooapis.com/combo?` * @param {String} config.root The root path to prepend to module names for the combo service. Ex: `2.5.2/build/` * @param {String|Object} config.filter A filter to apply to result urls. See filter property * @param {Object} config.filters Per-component filter specification. If specified for a given component, this overrides the filter config. * @param {Boolean} config.combine Use a combo service to reduce the number of http connections required to load your dependencies * @param {Boolean} [config.async=true] Fetch files in async * @param {Array} config.ignore: A list of modules that should never be dynamically loaded * @param {Array} config.force A list of modules that should always be loaded when required, even if already present on the page * @param {HTMLElement|String} config.insertBefore Node or id for a node that should be used as the insertion point for new nodes * @param {Object} config.jsAttributes Object literal containing attributes to add to script nodes * @param {Object} config.cssAttributes Object literal containing attributes to add to link nodes * @param {Number} config.timeout The number of milliseconds before a timeout occurs when dynamically loading nodes. If not set, there is no timeout * @param {Object} config.context Execution context for all callbacks * @param {Function} config.onSuccess Callback for the 'success' event * @param {Function} config.onFailure Callback for the 'failure' event * @param {Function} config.onTimeout Callback for the 'timeout' event * @param {Function} config.onProgress Callback executed each time a script or css file is loaded * @param {Object} config.modules A list of module definitions. See Loader.addModule for the supported module metadata * @param {Object} config.groups A list of group definitions. Each group can contain specific definitions for `base`, `comboBase`, `combine`, and accepts a list of `modules`. * @param {String} config.2in3 The version of the YUI 2 in 3 wrapper to use. The intrinsic support for YUI 2 modules in YUI 3 relies on versions of the YUI 2 components inside YUI 3 module wrappers. These wrappers change over time to accomodate the issues that arise from running YUI 2 in a YUI 3 sandbox. * @param {String} config.yui2 When using the 2in3 project, you can select the version of YUI 2 to use. Valid values are `2.2.2`, `2.3.1`, `2.4.1`, `2.5.2`, `2.6.0`, `2.7.0`, `2.8.0`, `2.8.1` and `2.9.0` [default] -- plus all versions of YUI 2 going forward. * @param {Function} config.doBeforeLoader An optional hook that allows for the patching of the loader instance. The `Y` instance is available as `this.context` and the only argument to the function is the Loader configuration object. */ Y.Loader = function(o) { var self = this; //Catch no config passed. o = o || {}; modulekey = META.md5; /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ // self._internalCallback = null; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ // self.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ // self.onFailure = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ // self.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ // self.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ self.context = Y; // Hook that allows the patching of loader if (o.doBeforeLoader) { o.doBeforeLoader.apply(self, arguments); } /** * Data that is passed to all callbacks * @property data */ // self.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ // self.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @deprecated , use cssAttributes or jsAttributes. */ // self.charset = null; /** * An object literal containing attributes to add to link nodes * @property cssAttributes * @type object */ // self.cssAttributes = null; /** * An object literal containing attributes to add to script nodes * @property jsAttributes * @type object */ // self.jsAttributes = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ self.base = Y.Env.meta.base + Y.Env.meta.root; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ self.comboBase = Y.Env.meta.comboBase; /* * Base path for language packs. */ // self.langBase = Y.Env.meta.langBase; // self.lang = ""; /** * If configured, the loader will attempt to use the combo * service for YUI resources and configured external resources. * @property combine * @type boolean * @default true if a base dir isn't in the config */ self.combine = o.base && (o.base.indexOf(self.comboBase.substr(0, 20)) > -1); /** * The default seperator to use between files in a combo URL * @property comboSep * @type {String} * @default Ampersand */ self.comboSep = '&'; /** * Max url length for combo urls. The default is 1024. This is the URL * limit for the Yahoo! hosted combo servers. If consuming * a different combo service that has a different URL limit * it is possible to override this default by supplying * the maxURLLength config option. The config option will * only take effect if lower than the default. * * @property maxURLLength * @type int */ self.maxURLLength = MAX_URL_LENGTH; /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ self.ignoreRegistered = o.ignoreRegistered; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ self.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, self value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ self.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ // self.ignore = null; /** * A list of modules that should always be loaded, even * if they have already been inserted into the page. * @property force * @type string[] */ // self.force = null; self.forceMap = {}; /** * Should we allow rollups * @property allowRollup * @type boolean * @default false */ self.allowRollup = false; /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: *
      *
      DEBUG
      *
      Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget
      *
      RAW
      *
      Selects the non-minified version of the library (e.g., event.js). *
      *
      * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * @property filter * @type string| {searchExp: string, replaceStr: string} */ // self.filter = null; /** * per-component filter specification. If specified for a given * component, this overrides the filter config. * @property filters * @type object */ self.filters = {}; /** * The list of requested modules * @property required * @type {string: boolean} */ self.required = {}; /** * If a module name is predefined when requested, it is checked againsts * the patterns provided in this property. If there is a match, the * module is added with the default configuration. * * At the moment only supporting module prefixes, but anticipate * supporting at least regular expressions. * @property patterns * @type Object */ // self.patterns = Y.merge(Y.Env.meta.patterns); self.patterns = {}; /** * Internal loader instance metadata. Use accessor `getModuleInfo()` instead. */ self.moduleInfo = {}; self.groups = Y.merge(Y.Env.meta.groups); /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * skin: { * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * @property skin * @type {Object} */ self.skin = Y.merge(Y.Env.meta.skin); /* * Map of conditional modules * @since 3.2.0 */ self.conditions = {}; // map of modules with a hash of modules that meet the requirement // self.provides = {}; self.config = o; self._internal = true; self._populateConditionsCache(); /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by any instance on the page * with the version number specified in the metadata. * @property loaded * @type {string: boolean} */ self.loaded = GLOBAL_LOADED[VERSION]; /** * Should Loader fetch scripts in `async`, defaults to `true` * @property async */ self.async = true; self._inspectPage(); self._internal = false; self._config(o); self.forceMap = (self.force) ? Y.Array.hash(self.force) : {}; self.testresults = null; if (Y.config.tests) { self.testresults = Y.config.tests; } /** * List of rollup files found in the library metadata * @property rollups */ // self.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ // self.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ self.sorted = []; /* * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ // self.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ self.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ self.inserted = {}; /** * List of skipped modules during insert() because the module * was not defined * @property skipped */ self.skipped = {}; // Y.on('yui:load', self.loadNext, self); self.tested = {}; /* * Cached sorted calculate results * @property results * @since 3.2.0 */ //self.results = {}; if (self.ignoreRegistered) { //Clear inpage already processed modules. self._resetModules(); } }; Y.Loader.prototype = { /** * Gets the module info from the local moduleInfo hash, or from the * default metadata and populate the local moduleInfo hash. * @method getModuleInfo * @param {string} name of the module * @public */ getModuleInfo: function(name) { var m = this.moduleInfo[name], rawMetaModules, globalRenderedMods, internal, v; if (m) { return m; } rawMetaModules = META.modules; globalRenderedMods = GLOBAL_ENV._renderedMods; internal = this._internal; /* The logic here is: - if the `moduleInfo[name]` is avilable, then short circuit - otherwise, if the module is in the globalCache (cross Y instance), then port it from the global registry into `moduleInfo[name]` - otherwise, if the module has raw metadata (from meta modules) then add it to the global registry and to `moduleInfo[name]` */ if (globalRenderedMods && globalRenderedMods.hasOwnProperty(name) && !this.ignoreRegistered) { this.moduleInfo[name] = Y.merge(globalRenderedMods[name]); } else { if (rawMetaModules.hasOwnProperty(name)) { this._internal = true; // making sure that modules from raw data are marked as internal v = this.addModule(rawMetaModules[name], name); // Inspect the page for the CSS module and mark it as loaded. if (v && v.type === CSS) { if (this.isCSSLoaded(v.name, true)) { Y.log('Found CSS module on page: ' + v.name, 'info', 'loader'); this.loaded[v.name] = true; } } this._internal = internal; } } return this.moduleInfo[name]; }, /** * Expand the names that are aliases to other modules. * @method _expandAliases * @param {string[]} list a module name or a list of names to be expanded * @private * @return {array} */ _expandAliases: function(list) { var expanded = [], aliases = YUI.Env.aliases, i, name; list = Y.Array(list); for (i = 0; i < list.length; i += 1) { name = list[i]; expanded.push.apply(expanded, aliases[name] ? aliases[name] : [name]); } return expanded; }, /** * Populate the conditions cache from raw modules, this is necessary * because no other module will require a conditional module, instead * the condition has to be executed and then the module is analyzed * to be included in the final requirement list. Without this cache * conditional modules will be simply ignored. * @method _populateConditionsCache * @private */ _populateConditionsCache: function() { var rawMetaModules = META.modules, cache = GLOBAL_ENV._conditions, i, j, t, trigger; // if we have conditions in cache and cache is enabled // we should port them to this loader instance if (cache && !this.ignoreRegistered) { for (i in cache) { if (cache.hasOwnProperty(i)) { this.conditions[i] = Y.merge(cache[i]); } } } else { for (i in rawMetaModules) { if (rawMetaModules.hasOwnProperty(i) && rawMetaModules[i].condition) { t = this._expandAliases(rawMetaModules[i].condition.trigger); for (j = 0; j < t.length; j += 1) { trigger = t[j]; this.conditions[trigger] = this.conditions[trigger] || {}; this.conditions[trigger][rawMetaModules[i].name || i] = rawMetaModules[i].condition; } } } GLOBAL_ENV._conditions = this.conditions; } }, /** * Reset modules in the module cache to a pre-processed state so additional * computations with a different skin or language will work as expected. * @method _resetModules * @private */ _resetModules: function() { var self = this, i, o, mod, name, details; for (i in self.moduleInfo) { if (self.moduleInfo.hasOwnProperty(i) && self.moduleInfo[i]) { mod = self.moduleInfo[i]; name = mod.name; details = (YUI.Env.mods[name] ? YUI.Env.mods[name].details : null); if (details) { self.moduleInfo[name]._reset = true; self.moduleInfo[name].requires = details.requires || []; self.moduleInfo[name].optional = details.optional || []; self.moduleInfo[name].supersedes = details.supercedes || []; } if (mod.defaults) { for (o in mod.defaults) { if (mod.defaults.hasOwnProperty(o)) { if (mod[o]) { mod[o] = mod.defaults[o]; } } } } mod.langCache = undefined; mod.skinCache = undefined; if (mod.skinnable) { self._addSkin(self.skin.defaultSkin, mod.name); } } } }, /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** * Default filters for raw and debug * @property FILTER_DEFS * @type Object * @final * @protected */ FILTER_DEFS: { RAW: { 'searchExp': '-min\\.js', 'replaceStr': '.js' }, DEBUG: { 'searchExp': '-min\\.js', 'replaceStr': '-debug.js' }, COVERAGE: { 'searchExp': '-min\\.js', 'replaceStr': '-coverage.js' } }, /* * Check the pages meta-data and cache the result. * @method _inspectPage * @private */ _inspectPage: function() { var self = this, v, m, req, mr, i; for (i in ON_PAGE) { if (ON_PAGE.hasOwnProperty(i)) { v = ON_PAGE[i]; if (v.details) { m = self.getModuleInfo(v.name); req = v.details.requires; mr = m && m.requires; if (m) { if (!m._inspected && req && mr.length !== req.length) { // console.log('deleting ' + m.name); delete m.expanded; } } else { m = self.addModule(v.details, i); } m._inspected = true; } } } }, /* * returns true if b is not loaded, and is required directly or by means of modules it supersedes. * @private * @method _requires * @param {String} mod1 The first module to compare * @param {String} mod2 The second module to compare */ _requires: function(mod1, mod2) { var i, rm, after_map, s, m = this.getModuleInfo(mod1), other = this.getModuleInfo(mod2); if (!m || !other) { return false; } rm = m.expanded_map; after_map = m.after_map; // check if this module should be sorted after the other // do this first to short circut circular deps if (after_map && (mod2 in after_map)) { return true; } after_map = other.after_map; // and vis-versa if (after_map && (mod1 in after_map)) { return false; } // check if this module requires one the other supersedes s = other.supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod1, s[i])) { return true; } } } s = m.supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod2, s[i])) { return false; } } } // check if this module requires the other directly // if (r && yArray.indexOf(r, mod2) > -1) { if (rm && (mod2 in rm)) { return true; } // external css files should be sorted below yui css if (m.ext && m.type === CSS && !other.ext && other.type === CSS) { return true; } return false; }, /** * Apply a new config to the Loader instance * @method _config * @private * @param {Object} o The new configuration */ _config: function(o) { var i, j, val, a, f, group, groupName, self = this, mods = [], mod, modInfo; // apply config values if (o) { for (i in o) { if (o.hasOwnProperty(i)) { val = o[i]; //TODO This should be a case if (i === 'require') { self.require(val); } else if (i === 'skin') { //If the config.skin is a string, format to the expected object if (typeof val === 'string') { self.skin.defaultSkin = o.skin; val = { defaultSkin: val }; } Y.mix(self.skin, val, true); } else if (i === 'groups') { for (j in val) { if (val.hasOwnProperty(j)) { // Y.log('group: ' + j); groupName = j; group = val[j]; self.addGroup(group, groupName); if (group.aliases) { for (a in group.aliases) { if (group.aliases.hasOwnProperty(a)) { self.addAlias(group.aliases[a], a); } } } } } } else if (i === 'modules') { // add a hash of module definitions for (j in val) { if (val.hasOwnProperty(j)) { self.addModule(val[j], j); } } } else if (i === 'aliases') { for (j in val) { if (val.hasOwnProperty(j)) { self.addAlias(val[j], j); } } } else if (i === 'gallery') { if (this.groups.gallery.update) { this.groups.gallery.update(val, o); } } else if (i === 'yui2' || i === '2in3') { if (this.groups.yui2.update) { this.groups.yui2.update(o['2in3'], o.yui2, o); } } else { self[i] = val; } } } } // fix filter f = self.filter; if (L.isString(f)) { f = f.toUpperCase(); self.filterName = f; self.filter = self.FILTER_DEFS[f]; if (f === 'DEBUG') { self.require('yui-log', 'dump'); } } if (self.filterName && self.coverage) { if (self.filterName === 'COVERAGE' && L.isArray(self.coverage) && self.coverage.length) { for (i = 0; i < self.coverage.length; i++) { mod = self.coverage[i]; modInfo = self.getModuleInfo(mod); if (modInfo && modInfo.use) { mods = mods.concat(modInfo.use); } else { mods.push(mod); } } self.filters = self.filters || {}; Y.Array.each(mods, function(mod) { self.filters[mod] = self.FILTER_DEFS.COVERAGE; }); self.filterName = 'RAW'; self.filter = self.FILTER_DEFS[self.filterName]; } } }, /** * Returns the skin module name for the specified skin name. If a * module name is supplied, the returned skin module name is * specific to the module passed in. * @method formatSkin * @param {string} skin the name of the skin. * @param {string} mod optional: the name of a module to skin. * @return {string} the full skin module name. */ formatSkin: function(skin, mod) { var s = SKIN_PREFIX + skin; if (mod) { s = s + '-' + mod; } return s; }, /** * Adds the skin def to the module info * @method _addSkin * @param {string} skin the name of the skin. * @param {string} mod the name of the module. * @param {string} parent parent module if this is a skin of a * submodule or plugin. * @return {string} the module name for the skin. * @private */ _addSkin: function(skin, mod, parent) { var pkg, name, nmod, sinf = this.skin, mdef = mod && this.getModuleInfo(mod), ext = mdef && mdef.ext; // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!this.getModuleInfo(name)) { pkg = mdef.pkg || mod; nmod = { skin: true, name: name, group: mdef.group, type: 'css', after: sinf.after, path: (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', ext: ext }; if (mdef.base) { nmod.base = mdef.base; } if (mdef.configFn) { nmod.configFn = mdef.configFn; } this.addModule(nmod, name); Y.log('Adding skin (' + name + '), ' + parent + ', ' + pkg + ', ' + nmod.path, 'info', 'loader'); } } return name; }, /** * Adds an alias module to the system * @method addAlias * @param {Array} use An array of modules that makes up this alias * @param {String} name The name of the alias * @example * var loader = new Y.Loader({}); * loader.addAlias([ 'node', 'yql' ], 'davglass'); * loader.require(['davglass']); * var out = loader.resolve(true); * * //out.js will contain Node and YQL modules */ addAlias: function(use, name) { YUI.Env.aliases[name] = use; this.addModule({ name: name, use: use }); }, /** * Add a new module group * @method addGroup * @param {Object} config An object containing the group configuration data * @param {String} config.name required, the group name * @param {String} config.base The base directory for this module group * @param {String} config.root The root path to add to each combo resource path * @param {Boolean} config.combine Should the request be combined * @param {String} config.comboBase Combo service base path * @param {Object} config.modules The group of modules * @param {String} name the group name. * @example * var loader = new Y.Loader({}); * loader.addGroup({ * name: 'davglass', * combine: true, * comboBase: '/combo?', * root: '', * modules: { * //Module List here * } * }, 'davglass'); */ addGroup: function(o, name) { var mods = o.modules, self = this, defaultBase = o.defaultBase || Y.config.defaultBase, i, v; name = name || o.name; o.name = name; self.groups[name] = o; if (!o.base && defaultBase && o.root) { o.base = defaultBase + o.root; } if (o.patterns) { for (i in o.patterns) { if (o.patterns.hasOwnProperty(i)) { o.patterns[i].group = name; self.patterns[i] = o.patterns[i]; } } } if (mods) { for (i in mods) { if (mods.hasOwnProperty(i)) { v = mods[i]; if (typeof v === 'string') { v = { name: i, fullpath: v }; } v.group = name; self.addModule(v, i); } } } }, /** * Add a new module to the component metadata. * @method addModule * @param {Object} config An object containing the module data. * @param {String} config.name Required, the component name * @param {String} config.type Required, the component type (js or css) * @param {String} config.path Required, the path to the script from `base` * @param {Array} config.requires Array of modules required by this component * @param {Array} [config.optional] Array of optional modules for this component * @param {Array} [config.supersedes] Array of the modules this component replaces * @param {Array} [config.after] Array of modules the components which, if present, should be sorted above this one * @param {Object} [config.after_map] Faster alternative to 'after' -- supply a hash instead of an array * @param {Number} [config.rollup] The number of superseded modules required for automatic rollup * @param {String} [config.fullpath] If `fullpath` is specified, this is used instead of the configured `base + path` * @param {Boolean} [config.skinnable] Flag to determine if skin assets should automatically be pulled in * @param {Object} [config.submodules] Hash of submodules * @param {String} [config.group] The group the module belongs to -- this is set automatically when it is added as part of a group configuration. * @param {Array} [config.lang] Array of BCP 47 language tags of languages for which this module has localized resource bundles, e.g., `["en-GB", "zh-Hans-CN"]` * @param {Object} [config.condition] Specifies that the module should be loaded automatically if a condition is met. This is an object with up to four fields: * @param {String} [config.condition.trigger] The name of a module that can trigger the auto-load * @param {Function} [config.condition.test] A function that returns true when the module is to be loaded. * @param {String} [config.condition.ua] The UA name of Y.UA object that returns true when the module is to be loaded. e.g., `"ie"`, `"nodejs"`. * @param {String} [config.condition.when] Specifies the load order of the conditional module * with regard to the position of the trigger module. * This should be one of three values: `before`, `after`, or `instead`. The default is `after`. * @param {Object} [config.testresults] A hash of test results from `Y.Features.all()` * @param {Function} [config.configFn] A function to exectute when configuring this module * @param {Object} config.configFn.mod The module config, modifying this object will modify it's config. Returning false will delete the module's config. * @param {String[]} [config.optionalRequires] List of dependencies that may optionally be loaded by this loader. This is targeted mostly at polyfills, since they should not be in the list of requires because polyfills are assumed to be available in the global scope. * @param {Function} [config.test] Test to be called when this module is added as an optional dependency of another module. If the test function returns `false`, the module will be ignored and will not be attached to this YUI instance. * @param {String} [name] The module name, required if not in the module data. * @return {Object} the module definition or null if the object passed in did not provide all required attributes. */ addModule: function(o, name) { name = name || o.name; if (typeof o === 'string') { o = { name: name, fullpath: o }; } var subs, i, l, t, sup, s, smod, plugins, plug, j, langs, packName, supName, flatSup, flatLang, lang, ret, overrides, skinname, when, g, p, modInfo = this.moduleInfo[name], conditions = this.conditions, trigger; //Only merge this data if the temp flag is set //from an earlier pass from a pattern or else //an override module (YUI_config) can not be used to //replace a default module. if (modInfo && modInfo.temp) { //This catches temp modules loaded via a pattern // The module will be added twice, once from the pattern and // Once from the actual add call, this ensures that properties // that were added to the module the first time around (group: gallery) // are also added the second time around too. o = Y.merge(modInfo, o); } o.name = name; if (!o || !o.name) { return null; } if (!o.type) { //Always assume it's javascript unless the CSS pattern is matched. o.type = JS; p = o.path || o.fullpath; if (p && this.REGEX_CSS.test(p)) { Y.log('Auto determined module type as CSS', 'warn', 'loader'); o.type = CSS; } } if (!o.path && !o.fullpath) { o.path = _path(name, name, o.type); } o.supersedes = o.supersedes || o.use; o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; // Handle submodule logic subs = o.submodules; this.moduleInfo[name] = o; o.requires = o.requires || []; /* Only allowing the cascade of requires information, since optional and supersedes are far more fine grained than a blanket requires is. */ if (this.requires) { for (i = 0; i < this.requires.length; i++) { o.requires.push(this.requires[i]); } } if (o.group && this.groups && this.groups[o.group]) { g = this.groups[o.group]; if (g.requires) { for (i = 0; i < g.requires.length; i++) { o.requires.push(g.requires[i]); } } } if (!o.defaults) { o.defaults = { requires: o.requires ? [].concat(o.requires) : null, supersedes: o.supersedes ? [].concat(o.supersedes) : null, optional: o.optional ? [].concat(o.optional) : null }; } if (o.skinnable && o.ext && o.temp) { skinname = this._addSkin(this.skin.defaultSkin, name); o.requires.unshift(skinname); } if (o.requires.length) { o.requires = this.filterRequires(o.requires) || []; } if (!o.langPack && o.lang) { langs = yArray(o.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); smod = this.getModuleInfo(packName); if (!smod) { smod = this._addLangPack(lang, o, packName); } } } if (subs) { sup = o.supersedes || []; l = 0; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; s.path = s.path || _path(name, i, o.type); s.pkg = name; s.group = o.group; if (s.supersedes) { sup = sup.concat(s.supersedes); } smod = this.addModule(s, i); sup.push(i); if (smod.skinnable) { o.skinnable = true; overrides = this.skin.overrides; if (overrides && overrides[i]) { for (j = 0; j < overrides[i].length; j++) { skinname = this._addSkin(overrides[i][j], i, name); sup.push(skinname); } } skinname = this._addSkin(this.skin.defaultSkin, i, name); sup.push(skinname); } // looks like we are expected to work out the metadata // for the parent module language packs from what is // specified in the child modules. if (s.lang && s.lang.length) { langs = yArray(s.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); supName = this.getLangPackName(lang, i); smod = this.getModuleInfo(packName); if (!smod) { smod = this._addLangPack(lang, o, packName); } flatSup = flatSup || yArray.hash(smod.supersedes); if (!(supName in flatSup)) { smod.supersedes.push(supName); } o.lang = o.lang || []; flatLang = flatLang || yArray.hash(o.lang); if (!(lang in flatLang)) { o.lang.push(lang); } // Y.log('pack ' + packName + ' should supersede ' + supName); // Add rollup file, need to add to supersedes list too // default packages packName = this.getLangPackName(ROOT_LANG, name); supName = this.getLangPackName(ROOT_LANG, i); smod = this.getModuleInfo(packName); if (!smod) { smod = this._addLangPack(lang, o, packName); } if (!(supName in flatSup)) { smod.supersedes.push(supName); } // Y.log('pack ' + packName + ' should supersede ' + supName); // Add rollup file, need to add to supersedes list too } } l++; } } //o.supersedes = YObject.keys(yArray.hash(sup)); o.supersedes = yArray.dedupe(sup); if (this.allowRollup) { o.rollup = (l < 4) ? l : Math.min(l - 1, 4); } } plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { plug = plugins[i]; plug.pkg = name; plug.path = plug.path || _path(name, i, o.type); plug.requires = plug.requires || []; plug.group = o.group; this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } if (o.condition) { t = this._expandAliases(o.condition.trigger); for (i = 0; i < t.length; i++) { trigger = t[i]; when = o.condition.when; conditions[trigger] = conditions[trigger] || {}; conditions[trigger][name] = o.condition; // the 'when' attribute can be 'before', 'after', or 'instead' // the default is after. if (when && when !== 'after') { if (when === 'instead') { // replace the trigger o.supersedes = o.supersedes || []; o.supersedes.push(trigger); } // before the trigger // the trigger requires the conditional mod, // so it should appear before the conditional // mod if we do not intersede. } else { // after the trigger o.after = o.after || []; o.after.push(trigger); } } } if (o.supersedes) { o.supersedes = this.filterRequires(o.supersedes); } if (o.after) { o.after = this.filterRequires(o.after); o.after_map = yArray.hash(o.after); } // this.dirty = true; if (o.configFn) { ret = o.configFn(o); if (ret === false) { Y.log('Config function returned false for ' + name + ', skipping.', 'info', 'loader'); delete this.moduleInfo[name]; delete GLOBAL_ENV._renderedMods[name]; o = null; } } //Add to global cache if (o) { if (!GLOBAL_ENV._renderedMods) { GLOBAL_ENV._renderedMods = {}; } GLOBAL_ENV._renderedMods[name] = Y.mix(GLOBAL_ENV._renderedMods[name] || {}, o); GLOBAL_ENV._conditions = conditions; } return o; }, /** * Add a requirement for one or more module * @method require * @param {string[] | string*} what the modules to load. */ require: function(what) { var a = (typeof what === 'string') ? yArray(arguments) : what; this.dirty = true; this.required = Y.merge(this.required, yArray.hash(this.filterRequires(a))); this._explodeRollups(); }, /** * Grab all the items that were asked for, check to see if the Loader * meta-data contains a "use" array. If it doesm remove the asked item and replace it with * the content of the "use". * This will make asking for: "dd" * Actually ask for: "dd-ddm-base,dd-ddm,dd-ddm-drop,dd-drag,dd-proxy,dd-constrain,dd-drop,dd-scroll,dd-drop-plugin" * @private * @method _explodeRollups */ _explodeRollups: function() { var self = this, m, m2, i, a, v, len, len2, r = self.required; if (!self.allowRollup) { for (i in r) { if (r.hasOwnProperty(i)) { m = self.getModule(i); if (m && m.use) { len = m.use.length; for (a = 0; a < len; a++) { m2 = self.getModule(m.use[a]); if (m2 && m2.use) { len2 = m2.use.length; for (v = 0; v < len2; v++) { r[m2.use[v]] = true; } } else { r[m.use[a]] = true; } } } } } self.required = r; } }, /** * Explodes the required array to remove aliases and replace them with real modules * @method filterRequires * @param {Array} r The original requires array * @return {Array} The new array of exploded requirements */ filterRequires: function(r) { if (r) { if (!Y.Lang.isArray(r)) { r = [r]; } r = Y.Array(r); var c = [], i, mod, o, m; for (i = 0; i < r.length; i++) { mod = this.getModule(r[i]); if (mod && mod.use) { for (o = 0; o < mod.use.length; o++) { //Must walk the other modules in case a module is a rollup of rollups (datatype) m = this.getModule(mod.use[o]); if (m && m.use && (m.name !== mod.name)) { c = Y.Array.dedupe([].concat(c, this.filterRequires(m.use))); } else { c.push(mod.use[o]); } } } else { c.push(r[i]); } } r = c; } return r; }, /** Returns `true` if the module can be attached to the YUI instance. Runs the module's test if there is one and caches its result. @method _canBeAttached @param {String} module Name of the module to check. @return {Boolean} Result of the module's test if it has one, or `true`. **/ _canBeAttached: function (m) { m = this.getModule(m); if (m && m.test) { if (!m.hasOwnProperty('_testResult')) { m._testResult = m.test(Y); } return m._testResult; } // return `true` for modules not registered as Loader will know what // to do with them later on return true; }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param {object} mod The module definition from moduleInfo. * @return {array} the expanded requirement list. */ getRequires: function(mod) { if (!mod) { //console.log('returning no reqs for ' + mod.name); return NO_REQUIREMENTS; } if (mod._parsed) { //console.log('returning requires for ' + mod.name, mod.requires); return mod.expanded || NO_REQUIREMENTS; } //TODO add modue cache here out of scope.. var i, m, j, length, add, packName, lang, testresults = this.testresults, name = mod.name, cond, adddef = ON_PAGE[name] && ON_PAGE[name].details, optReqs = mod.optionalRequires, d, go, def, r, old_mod, o, skinmod, skindef, skinpar, skinname, intl = mod.lang || mod.intl, ftests = Y.Features && Y.Features.tests.load, hash, reparse; // console.log(name); // pattern match leaves module stub that needs to be filled out if (mod.temp && adddef) { old_mod = mod; mod = this.addModule(adddef, name); mod.group = old_mod.group; mod.pkg = old_mod.pkg; delete mod.expanded; } // console.log('cache: ' + mod.langCache + ' == ' + this.lang); //If a skin or a lang is different, reparse.. reparse = !((!this.lang || mod.langCache === this.lang) && (mod.skinCache === this.skin.defaultSkin)); if (mod.expanded && !reparse) { //Y.log('Already expanded ' + name + ', ' + mod.expanded); return mod.expanded; } // Optional dependencies are dependencies that may or may not be // available. // This feature was designed specifically to be used when transpiling // ES6 modules, in order to use polyfills and regular scripts that define // global variables without having to import them since they should be // available in the global scope. if (optReqs) { for (i = 0, length = optReqs.length; i < length; i++) { if (this._canBeAttached(optReqs[i])) { mod.requires.push(optReqs[i]); } } } d = []; hash = {}; r = this.filterRequires(mod.requires); if (mod.lang) { //If a module has a lang attribute, auto add the intl requirement. d.unshift('intl'); r.unshift('intl'); intl = true; } o = this.filterRequires(mod.optional); // Y.log("getRequires: " + name + " (dirty:" + this.dirty + // ", expanded:" + mod.expanded + ")"); mod._parsed = true; mod.langCache = this.lang; mod.skinCache = this.skin.defaultSkin; for (i = 0; i < r.length; i++) { //Y.log(name + ' requiring ' + r[i], 'info', 'loader'); if (!hash[r[i]]) { d.push(r[i]); hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } // get the requirements from superseded modules, if any r = this.filterRequires(mod.supersedes); if (r) { for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { // if this module has submodules, the requirements list is // expanded to include the submodules. This is so we can // prevent dups when a submodule is already loaded and the // parent is requested. if (mod.submodules) { d.push(r[i]); } hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } if (o && this.loadOptional) { for (i = 0; i < o.length; i++) { if (!hash[o[i]]) { d.push(o[i]); hash[o[i]] = true; m = this.getModuleInfo(o[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } cond = this.conditions[name]; if (cond) { //Set the module to not parsed since we have conditionals and this could change the dependency tree. mod._parsed = false; if (testresults && ftests) { oeach(testresults, function(result, id) { var condmod = ftests[id].name; if (!hash[condmod] && ftests[id].trigger === name) { if (result && ftests[id]) { hash[condmod] = true; d.push(condmod); } } }); } else { for (i in cond) { if (cond.hasOwnProperty(i)) { if (!hash[i]) { def = cond[i]; //first see if they've specfied a ua check //then see if they've got a test fn & if it returns true //otherwise just having a condition block is enough go = def && ((!def.ua && !def.test) || (def.ua && Y.UA[def.ua]) || (def.test && def.test(Y, r))); if (go) { hash[i] = true; d.push(i); m = this.getModule(i); if (m) { add = this.getRequires(m); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } } } } // Create skin modules if (mod.skinnable) { skindef = this.skin.overrides; for (i in YUI.Env.aliases) { if (YUI.Env.aliases.hasOwnProperty(i)) { if (Y.Array.indexOf(YUI.Env.aliases[i], name) > -1) { skinpar = i; } } } if (skindef && (skindef[name] || (skinpar && skindef[skinpar]))) { skinname = name; if (skindef[skinpar]) { skinname = skinpar; } for (i = 0; i < skindef[skinname].length; i++) { skinmod = this._addSkin(skindef[skinname][i], name); if (!this.isCSSLoaded(skinmod, this._boot)) { d.push(skinmod); } } } else { skinmod = this._addSkin(this.skin.defaultSkin, name); if (!this.isCSSLoaded(skinmod, this._boot)) { d.push(skinmod); } } } mod._parsed = false; if (intl) { if (mod.lang && !mod.langPack && Y.Intl) { lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang); //Y.log('Best lang: ' + lang + ', this.lang: ' + this.lang + ', mod.lang: ' + mod.lang); packName = this.getLangPackName(lang, name); if (packName) { d.unshift(packName); } } d.unshift(INTL); } mod.expanded_map = yArray.hash(d); mod.expanded = YObject.keys(mod.expanded_map); return mod.expanded; }, /** * Check to see if named css module is already loaded on the page * @method isCSSLoaded * @param {String} name The name of the css file * @param {Boolean} skip To skip the short-circuit for ignoreRegister * @return Boolean */ isCSSLoaded: function(name, skip) { //TODO - Make this call a batching call with name being an array if (!name || !YUI.Env.cssStampEl || (!skip && this.ignoreRegistered)) { Y.log('isCSSLoaded was skipped for ' + name, 'warn', 'loader'); return false; } var el = YUI.Env.cssStampEl, ret = false, mod = YUI.Env._cssLoaded[name], style = el.currentStyle; //IE if (mod !== undefined) { //Y.log('isCSSLoaded was cached for ' + name, 'warn', 'loader'); return mod; } //Add the classname to the element el.className = name; if (!style) { style = Y.config.doc.defaultView.getComputedStyle(el, null); } if (style && style.display === 'none') { ret = true; } Y.log('Has Skin? ' + name + ' : ' + ret, 'info', 'loader'); el.className = ''; //Reset the classname to '' YUI.Env._cssLoaded[name] = ret; return ret; }, /** * Returns a hash of module names the supplied module satisfies. * @method getProvides * @param {string} name The name of the module. * @return {object} what this module provides. */ getProvides: function(name) { var m = this.getModule(name), o, s; // supmap = this.provides; if (!m) { return NOT_FOUND; } if (m && !m.provides) { o = {}; s = m.supersedes; if (s) { yArray.each(s, function(v) { Y.mix(o, this.getProvides(v)); }, this); } o[name] = true; m.provides = o; } return m.provides; }, /** * Calculates the dependency tree, the result is stored in the sorted * property. * @method calculate * @param {object} o optional options object. * @param {string} type optional argument to prune modules. */ calculate: function(o, type) { if (o || type || this.dirty) { if (o) { this._config(o); } if (!this._init) { this._setup(); } this._explode(); if (this.allowRollup) { this._rollup(); } else { this._explodeRollups(); } this._reduce(); this._sort(); } }, /** * Creates a "psuedo" package for languages provided in the lang array * @method _addLangPack * @private * @param {String} lang The language to create * @param {Object} m The module definition to create the language pack around * @param {String} packName The name of the package (e.g: lang/datatype-date-en-US) * @return {Object} The module definition */ _addLangPack: function(lang, m, packName) { var name = m.name, packPath, conf, existing = this.getModuleInfo(packName); if (!existing) { packPath = _path((m.pkg || name), packName, JS, true); conf = { path: packPath, intl: true, langPack: true, ext: m.ext, group: m.group, supersedes: [] }; if (m.root) { conf.root = m.root; } if (m.base) { conf.base = m.base; } if (m.configFn) { conf.configFn = m.configFn; } this.addModule(conf, packName); if (lang) { Y.Env.lang = Y.Env.lang || {}; Y.Env.lang[lang] = Y.Env.lang[lang] || {}; Y.Env.lang[lang][name] = true; } } return this.getModuleInfo(packName); }, /** * Investigates the current YUI configuration on the page. By default, * modules already detected will not be loaded again unless a force * option is encountered. Called by calculate() * @method _setup * @private */ _setup: function() { var info = this.moduleInfo, name, i, j, m, l, packName; for (name in info) { if (info.hasOwnProperty(name)) { m = info[name]; if (m) { // remove dups //m.requires = YObject.keys(yArray.hash(m.requires)); m.requires = yArray.dedupe(m.requires); // Create lang pack modules //if (m.lang && m.lang.length) { if (m.lang) { // Setup root package if the module has lang defined, // it needs to provide a root language pack packName = this.getLangPackName(ROOT_LANG, name); this._addLangPack(null, m, packName); } } } } //l = Y.merge(this.inserted); l = {}; // available modules if (!this.ignoreRegistered) { Y.mix(l, GLOBAL_ENV.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { Y.mix(l, yArray.hash(this.ignore)); } // expand the list to include superseded modules for (j in l) { if (l.hasOwnProperty(j)) { Y.mix(l, this.getProvides(j)); } } // remove modules on the force list from the loaded list if (this.force) { for (i = 0; i < this.force.length; i++) { if (this.force[i] in l) { delete l[this.force[i]]; } } } Y.mix(this.loaded, l); this._init = true; }, /** * Builds a module name for a language pack * @method getLangPackName * @param {string} lang the language code. * @param {string} mname the module to build it for. * @return {string} the language pack module name. */ getLangPackName: function(lang, mname) { return ('lang/' + mname + ((lang) ? '_' + lang : '')); }, /** * Inspects the required modules list looking for additional * dependencies. Expands the required list to include all * required modules. Called by calculate() * @method _explode * @private */ _explode: function() { //TODO Move done out of scope var r = this.required, m, reqs, done = {}, self = this, name, expound; // the setup phase is over, all modules have been created self.dirty = false; self._explodeRollups(); r = self.required; for (name in r) { if (r.hasOwnProperty(name)) { if (!done[name]) { done[name] = true; m = self.getModule(name); if (m) { expound = m.expound; if (expound) { r[expound] = self.getModule(expound); reqs = self.getRequires(r[expound]); Y.mix(r, yArray.hash(reqs)); } reqs = self.getRequires(m); Y.mix(r, yArray.hash(reqs)); } } } } // Y.log('After explode: ' + YObject.keys(r)); }, /** * The default method used to test a module against a pattern * @method _patternTest * @private * @param {String} mname The module being tested * @param {String} pname The pattern to match */ _patternTest: function(mname, pname) { return (mname.indexOf(pname) > -1); }, /** * Get's the loader meta data for the requested module * @method getModule * @param {String} mname The module name to get * @return {Object} The module metadata */ getModule: function(mname) { //TODO: Remove name check - it's a quick hack to fix pattern WIP if (!mname) { return null; } var p, found, pname, m = this.getModuleInfo(mname), patterns = this.patterns; // check the patterns library to see if we should automatically add // the module with defaults if (!m || (m && m.ext)) { // Y.log('testing patterns ' + YObject.keys(patterns)); for (pname in patterns) { if (patterns.hasOwnProperty(pname)) { // Y.log('testing pattern ' + i); p = patterns[pname]; //There is no test method, create a default one that tests // the pattern against the mod name if (!p.test) { p.test = this._patternTest; } if (p.test(mname, pname)) { // use the metadata supplied for the pattern // as the module definition. found = p; break; } } } } if (!m) { if (found) { if (p.action) { // Y.log('executing pattern action: ' + pname); p.action.call(this, mname, pname); } else { Y.log('Undefined module: ' + mname + ', matched a pattern: ' + pname, 'info', 'loader'); // ext true or false? m = this.addModule(Y.merge(found, { test: void 0, temp: true }), mname); if (m && found.configFn) { m.configFn = found.configFn; } } } } else { if (found && m && found.configFn && !m.configFn) { m.configFn = found.configFn; m.configFn(m); } } return m; }, // impl in rollup submodule _rollup: function() { }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @return {object} the reduced dependency hash. * @private */ _reduce: function(r) { r = r || this.required; var i, j, s, m, type = this.loadType, ignore = this.ignore ? yArray.hash(this.ignore) : false; for (i in r) { if (r.hasOwnProperty(i)) { m = this.getModule(i); // remove if already loaded if (((this.loaded[i] || ON_PAGE[i]) && !this.forceMap[i] && !this.ignoreRegistered) || (type && m && m.type !== type)) { delete r[i]; } if (ignore && ignore[i]) { delete r[i]; } // remove anything this module supersedes s = m && m.supersedes; if (s) { for (j = 0; j < s.length; j++) { if (s[j] in r) { delete r[s[j]]; } } } } } return r; }, /** * Handles the queue when a module has been loaded for all cases * @method _finish * @private * @param {String} msg The message from Loader * @param {Boolean} success A boolean denoting success or failure */ _finish: function(msg, success) { Y.log('loader finishing: ' + msg + ', ' + Y.id + ', ' + this.data, 'info', 'loader'); _queue.running = false; var onEnd = this.onEnd; if (onEnd) { onEnd.call(this.context, { msg: msg, data: this.data, success: success }); } this._continue(); }, /** * The default Loader onSuccess handler, calls this.onSuccess with a payload * @method _onSuccess * @private */ _onSuccess: function() { var self = this, skipped = Y.merge(self.skipped), fn, failed = [], rreg = self.requireRegistration, success, msg, i, mod; for (i in skipped) { if (skipped.hasOwnProperty(i)) { delete self.inserted[i]; } } self.skipped = {}; for (i in self.inserted) { if (self.inserted.hasOwnProperty(i)) { mod = self.getModule(i); if (mod && rreg && mod.type === JS && !(i in YUI.Env.mods)) { failed.push(i); } else { Y.mix(self.loaded, self.getProvides(i)); } } } fn = self.onSuccess; msg = (failed.length) ? 'notregistered' : 'success'; success = !(failed.length); if (fn) { fn.call(self.context, { msg: msg, data: self.data, success: success, failed: failed, skipped: skipped }); } self._finish(msg, success); }, /** * The default Loader onProgress handler, calls this.onProgress with a payload * @method _onProgress * @private */ _onProgress: function(e) { var self = this, i; //set the internal cache to what just came in. if (e.data && e.data.length) { for (i = 0; i < e.data.length; i++) { e.data[i] = self.getModule(e.data[i].name); } } if (self.onProgress) { self.onProgress.call(self.context, { name: e.url, data: e.data }); } }, /** * The default Loader onFailure handler, calls this.onFailure with a payload * @method _onFailure * @private */ _onFailure: function(o) { var f = this.onFailure, msg = [], i = 0, len = o.errors.length; for (i; i < len; i++) { msg.push(o.errors[i].error); } msg = msg.join(','); Y.log('load error: ' + msg + ', ' + Y.id, 'error', 'loader'); if (f) { f.call(this.context, { msg: msg, data: this.data, success: false }); } this._finish(msg, false); }, /** * The default Loader onTimeout handler, calls this.onTimeout with a payload * @method _onTimeout * @param {Get.Transaction} transaction The Transaction object from `Y.Get` * @private */ _onTimeout: function(transaction) { Y.log('loader timeout: ' + Y.id, 'error', 'loader'); var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false, transaction: transaction }); } }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { var name, // Object containing module names. required = this.required, // Keep track of whether we've visited a module. visited = {}; // Will contain modules names, in the correct order, // according to dependencies. this.sorted = []; for (name in required) { if (!visited[name] && required.hasOwnProperty(name)) { this._visit(name, visited); } } }, /** * Recursively visits the dependencies of the module name * passed in, and appends each module name to the `sorted` property. * @param {String} name The name of a module. * @param {Object} visited Keeps track of whether a module was visited. * @method _visit * @private */ _visit: function (name, visited) { var required, condition, moduleInfo, dependency, dependencies, trigger, isAfter, i, l; visited[name] = true; required = this.required; moduleInfo = this.moduleInfo[name]; condition = this.conditions[name] || {}; if (moduleInfo) { // Recurse on each dependency of this module, // figuring out its dependencies, and so on. dependencies = moduleInfo.expanded || moduleInfo.requires; for (i = 0, l = dependencies.length; i < l; ++i) { dependency = dependencies[i]; trigger = condition[dependency]; // We cannot process this dependency yet if it must // appear after our current module. isAfter = trigger && (!trigger.when || trigger.when === "after"); // Is this module name in the required list of modules, // and have we not already visited it? if (required[dependency] && !visited[dependency] && !isAfter) { this._visit(dependency, visited); } } } this.sorted.push(name); }, /** * Handles the actual insertion of script/link tags * @method _insert * @private * @param {Object} source The YUI instance the request came from * @param {Object} o The metadata to include * @param {String} type JS or CSS * @param {Boolean} [skipcalc=false] Do a Loader.calculate on the meta */ _insert: function(source, o, type, skipcalc) { Y.log('private _insert() ' + (type || '') + ', ' + Y.id, "info", "loader"); // restore the state at the time of the request if (source) { this._config(source); } // build the dependency list // don't include type so we can process CSS and script in // one pass when the type is not specified. var modules = this.resolve(!skipcalc), self = this, comp = 0, actions = 0, mods = {}, deps, complete; self._refetch = []; if (type) { //Filter out the opposite type and reset the array so the checks later work modules[((type === JS) ? CSS : JS)] = []; } if (!self.fetchCSS) { modules.css = []; } if (modules.js.length) { comp++; } if (modules.css.length) { comp++; } //console.log('Resolved Modules: ', modules); complete = function(d) { actions++; var errs = {}, i = 0, o = 0, u = '', fn, modName, resMods; if (d && d.errors) { for (i = 0; i < d.errors.length; i++) { if (d.errors[i].request) { u = d.errors[i].request.url; } else { u = d.errors[i]; } errs[u] = u; } } if (d && d.data && d.data.length && (d.type === 'success')) { for (i = 0; i < d.data.length; i++) { self.inserted[d.data[i].name] = true; //If the external module has a skin or a lang, reprocess it if (d.data[i].lang || d.data[i].skinnable) { delete self.inserted[d.data[i].name]; self._refetch.push(d.data[i].name); } } } if (actions === comp) { self._loading = null; Y.log('Loader actions complete!', 'info', 'loader'); if (self._refetch.length) { //Get the deps for the new meta-data and reprocess Y.log('Found potential modules to refetch', 'info', 'loader'); for (i = 0; i < self._refetch.length; i++) { deps = self.getRequires(self.getModule(self._refetch[i])); for (o = 0; o < deps.length; o++) { if (!self.inserted[deps[o]]) { //We wouldn't be to this point without the module being here mods[deps[o]] = deps[o]; } } } mods = Y.Object.keys(mods); if (mods.length) { Y.log('Refetching modules with new meta-data', 'info', 'loader'); self.require(mods); resMods = self.resolve(true); if (resMods.cssMods.length) { for (i=0; i < resMods.cssMods.length; i++) { modName = resMods.cssMods[i].name; delete YUI.Env._cssLoaded[modName]; if (self.isCSSLoaded(modName)) { self.inserted[modName] = true; delete self.required[modName]; } } self.sorted = []; self._sort(); } d = null; //bail self._insert(); //insert the new deps } } if (d && d.fn) { Y.log('Firing final Loader callback!', 'info', 'loader'); fn = d.fn; delete d.fn; fn.call(self, d); } } }; this._loading = true; if (!modules.js.length && !modules.css.length) { Y.log('No modules resolved..', 'warn', 'loader'); actions = -1; complete({ fn: self._onSuccess }); return; } if (modules.css.length) { //Load CSS first Y.log('Loading CSS modules', 'info', 'loader'); Y.Get.css(modules.css, { data: modules.cssMods, attributes: self.cssAttributes, insertBefore: self.insertBefore, charset: self.charset, timeout: self.timeout, context: self, onProgress: function(e) { self._onProgress.call(self, e); }, onTimeout: function(d) { self._onTimeout.call(self, d); }, onSuccess: function(d) { d.type = 'success'; d.fn = self._onSuccess; complete.call(self, d); }, onFailure: function(d) { d.type = 'failure'; d.fn = self._onFailure; complete.call(self, d); } }); } if (modules.js.length) { Y.log('Loading JS modules', 'info', 'loader'); Y.Get.js(modules.js, { data: modules.jsMods, insertBefore: self.insertBefore, attributes: self.jsAttributes, charset: self.charset, timeout: self.timeout, autopurge: false, context: self, async: self.async, onProgress: function(e) { self._onProgress.call(self, e); }, onTimeout: function(d) { self._onTimeout.call(self, d); }, onSuccess: function(d) { d.type = 'success'; d.fn = self._onSuccess; complete.call(self, d); }, onFailure: function(d) { d.type = 'failure'; d.fn = self._onFailure; complete.call(self, d); } }); } }, /** * Once a loader operation is completely finished, process any additional queued items. * @method _continue * @private */ _continue: function() { if (!(_queue.running) && _queue.size() > 0) { _queue.running = true; _queue.next()(); } }, /** * inserts the requested modules and their dependencies. * type can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param {object} o optional options object. * @param {string} type the type of dependency to insert. */ insert: function(o, type, skipsort) { Y.log('public insert() ' + (type || '') + ', ' + Y.Object.keys(this.required), "info", "loader"); var self = this, copy = Y.merge(this); delete copy.require; delete copy.dirty; _queue.add(function() { self._insert(copy, o, type, skipsort); }); this._continue(); }, /** * Executed every time a module is loaded, and if we are in a load * cycle, we attempt to load the next script. Public so that it * is possible to call this if using a method other than * Y.register to determine when scripts are fully loaded * @method loadNext * @deprecated * @param {string} mname optional the name of the module that has * been loaded (which is usually why it is time to load the next * one). */ loadNext: function() { Y.log('loadNext was called..', 'error', 'loader'); return; }, /** * Apply filter defined for this instance to a url/path * @method _filter * @param {string} u the string to filter. * @param {string} name the name of the module, if we are processing * a single module as opposed to a combined url. * @return {string} the filtered string. * @private */ _filter: function(u, name, group) { var f = this.filter, hasFilter = name && (name in this.filters), modFilter = hasFilter && this.filters[name], groupName = group || (this.getModuleInfo(name) || {}).group || null; if (groupName && this.groups[groupName] && this.groups[groupName].filter) { modFilter = this.groups[groupName].filter; hasFilter = true; } if (u) { if (hasFilter) { f = (L.isString(modFilter)) ? this.FILTER_DEFS[modFilter.toUpperCase()] || null : modFilter; } if (f) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * @method _url * @param {string} path the path fragment. * @param {String} name The name of the module * @param {String} [base] The base url to use. Defaults to self.base * @return {string} the full url. * @private */ _url: function(path, name, base) { return this._filter((base || this.base || '') + path, name); }, /** * Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules. * @method resolve * @param {Boolean} [calc=false] Perform a loader.calculate() before anything else * @param {Array} [sorted=loader.sorted] An override for the loader.sorted array * @return {Object} Object hash (js and css) of two arrays of file lists * @example This method can be used as an off-line dep calculator * * var Y = YUI(); * var loader = new Y.Loader({ * filter: 'debug', * base: '../../', * root: 'build/', * combine: true, * require: ['node', 'dd', 'console'] * }); * var out = loader.resolve(true); * */ resolve: function(calc, sorted) { var self = this, resolved = { js: [], jsMods: [], css: [], cssMods: [] }, addSingle, usePathogen = Y.config.comboLoader && Y.config.customComboBase; if (self.skin.overrides || self.skin.defaultSkin !== DEFAULT_SKIN || self.ignoreRegistered) { self._resetModules(); } if (calc) { self.calculate(); } sorted = sorted || self.sorted; addSingle = function(mod) { if (mod) { var group = (mod.group && self.groups[mod.group]) || NOT_FOUND, url; //Always assume it's async if (group.async === false) { mod.async = group.async; } url = (mod.fullpath) ? self._filter(mod.fullpath, mod.name) : self._url(mod.path, mod.name, group.base || mod.base); if (mod.attributes || mod.async === false) { url = { url: url, async: mod.async }; if (mod.attributes) { url.attributes = mod.attributes; } } resolved[mod.type].push(url); resolved[mod.type + 'Mods'].push(mod); } else { Y.log('Undefined Module', 'warn', 'loader'); } }; /*jslint vars: true */ var inserted = (self.ignoreRegistered) ? {} : self.inserted, comboSources, maxURLLength, comboMeta, comboBase, comboSep, group, mod, len, i, hasComboModule = false; /*jslint vars: false */ for (i = 0, len = sorted.length; i < len; i++) { mod = self.getModule(sorted[i]); if (!mod || inserted[mod.name]) { continue; } group = self.groups[mod.group]; comboBase = self.comboBase; if (group) { if (!group.combine || mod.fullpath) { //This is not a combo module, skip it and load it singly later. addSingle(mod); continue; } mod.combine = true; if (typeof group.root === 'string') { mod.root = group.root; } comboBase = group.comboBase || comboBase; comboSep = group.comboSep; maxURLLength = group.maxURLLength; } else { if (!self.combine) { //This is not a combo module, skip it and load it singly later. addSingle(mod); continue; } } if (!mod.combine && mod.ext) { addSingle(mod); continue; } hasComboModule = true; comboSources = comboSources || {}; comboSources[comboBase] = comboSources[comboBase] || { js: [], jsMods: [], css: [], cssMods: [] }; comboMeta = comboSources[comboBase]; comboMeta.group = mod.group; comboMeta.comboSep = comboSep || self.comboSep; comboMeta.maxURLLength = maxURLLength || self.maxURLLength; comboMeta[mod.type + 'Mods'].push(mod); if (mod.type === JS || mod.type === CSS) { resolved[mod.type + 'Mods'].push(mod); } } //only encode if we have something to encode if (hasComboModule) { if (usePathogen) { resolved = this._pathogenEncodeComboSources(resolved); } else { resolved = this._encodeComboSources(resolved, comboSources); } } return resolved; }, /** * Encodes combo sources and appends them to an object hash of arrays from `loader.resolve`. * * @method _encodeComboSources * @param {Object} resolved The object hash of arrays in which to attach the encoded combo sources. * @param {Object} comboSources An object containing relevant data about modules. * @return Object * @private */ _encodeComboSources: function(resolved, comboSources) { var fragSubset, modules, tmpBase, baseLen, frags, frag, type, mod, maxURLLength, comboBase, comboMeta, comboSep, i, len, self = this; for (comboBase in comboSources) { if (comboSources.hasOwnProperty(comboBase)) { comboMeta = comboSources[comboBase]; comboSep = comboMeta.comboSep; maxURLLength = comboMeta.maxURLLength; Y.log('Using maxURLLength of ' + maxURLLength, 'info', 'loader'); for (type in comboMeta) { if (type === JS || type === CSS) { modules = comboMeta[type + 'Mods']; frags = []; for (i = 0, len = modules.length; i < len; i += 1) { mod = modules[i]; frag = ((typeof mod.root === 'string') ? mod.root : self.root) + (mod.path || mod.fullpath); frags.push( self._filter(frag, mod.name) ); } tmpBase = comboBase + frags.join(comboSep); baseLen = tmpBase.length; if (maxURLLength <= comboBase.length) { Y.log('maxURLLength (' + maxURLLength + ') is lower than the comboBase length (' + comboBase.length + '), resetting to default (' + MAX_URL_LENGTH + ')', 'error', 'loader'); maxURLLength = MAX_URL_LENGTH; } if (frags.length) { if (baseLen > maxURLLength) { Y.log('Exceeded maxURLLength (' + maxURLLength + ') for ' + type + ', splitting', 'info', 'loader'); fragSubset = []; for (i = 0, len = frags.length; i < len; i++) { fragSubset.push(frags[i]); tmpBase = comboBase + fragSubset.join(comboSep); if (tmpBase.length > maxURLLength) { frag = fragSubset.pop(); tmpBase = comboBase + fragSubset.join(comboSep); resolved[type].push(self._filter(tmpBase, null, comboMeta.group)); fragSubset = []; if (frag) { fragSubset.push(frag); } } } if (fragSubset.length) { tmpBase = comboBase + fragSubset.join(comboSep); resolved[type].push(self._filter(tmpBase, null, comboMeta.group)); } } else { resolved[type].push(self._filter(tmpBase, null, comboMeta.group)); } } } } } } return resolved; }, /** Shortcut to calculate, resolve and load all modules. var loader = new Y.Loader({ ignoreRegistered: true, modules: { mod: { path: 'mod.js' } }, requires: [ 'mod' ] }); loader.load(function() { console.log('All modules have loaded..'); }); @method load @param {Function} cb Executed after all load operations are complete */ load: function(cb) { if (!cb) { Y.log('No callback supplied to load()', 'error', 'loader'); return; } var self = this, out = self.resolve(true); self.data = out; self.onEnd = function() { cb.apply(self.context || self, arguments); }; self.insert(); } }; }, '3.18.1', {"requires": ["get", "features"]}); YUI.add('loader-rollup', function (Y, NAME) { /** * Optional automatic rollup logic for reducing http connections * when not using a combo service. * @module loader * @submodule rollup */ /** * Look for rollup packages to determine if all of the modules a * rollup supersedes are required. If so, include the rollup to * help reduce the total number of connections required. Called * by calculate(). This is an optional feature, and requires the * appropriate submodule to function. * @method _rollup * @for Loader * @private */ Y.Loader.prototype._rollup = function() { var i, j, m, s, r = this.required, roll, info = this.moduleInfo, rolled, c, smod; // find and cache rollup modules if (this.dirty || !this.rollups) { this.rollups = {}; for (i in info) { if (info.hasOwnProperty(i)) { m = this.getModule(i); // if (m && m.rollup && m.supersedes) { if (m && m.rollup) { this.rollups[i] = m; } } } } // make as many passes as needed to pick up rollup rollups for (;;) { rolled = false; // go through the rollup candidates for (i in this.rollups) { if (this.rollups.hasOwnProperty(i)) { // there can be only one, unless forced if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) { m = this.getModule(i); s = m.supersedes || []; roll = false; // @TODO remove continue if (!m.rollup) { continue; } c = 0; // check the threshold for (j = 0; j < s.length; j++) { smod = info[s[j]]; // if the superseded module is loaded, we can't // load the rollup unless it has been forced. if (this.loaded[s[j]] && !this.forceMap[s[j]]) { roll = false; break; // increment the counter if this module is required. // if we are beyond the rollup threshold, we will // use the rollup module } else if (r[s[j]] && m.type === smod.type) { c++; // Y.log("adding to thresh: " + c + ", " + s[j]); roll = (c >= m.rollup); if (roll) { // Y.log("over thresh " + c + ", " + s[j]); break; } } } if (roll) { // Y.log("adding rollup: " + i); // add the rollup r[i] = true; rolled = true; // expand the rollup's dependencies this.getRequires(m); } } } } // if we made it here w/o rolling up something, we are done if (!rolled) { break; } } }; }, '3.18.1', {"requires": ["loader-base"]}); YUI.add('loader-yui3', function (Y, NAME) { /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ /** * YUI 3 module metadata * @module loader * @submodule loader-yui3 */ YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || {}; Y.mix(YUI.Env[Y.version].modules, { "align-plugin": { "requires": [ "node-screen", "node-pluginhost" ] }, "anim": { "use": [ "anim-base", "anim-color", "anim-curve", "anim-easing", "anim-node-plugin", "anim-scroll", "anim-xy" ] }, "anim-base": { "requires": [ "base-base", "node-style", "color-base" ] }, "anim-color": { "requires": [ "anim-base" ] }, "anim-curve": { "requires": [ "anim-xy" ] }, "anim-easing": { "requires": [ "anim-base" ] }, "anim-node-plugin": { "requires": [ "node-pluginhost", "anim-base" ] }, "anim-scroll": { "requires": [ "anim-base" ] }, "anim-shape": { "requires": [ "anim-base", "anim-easing", "anim-color", "matrix" ] }, "anim-shape-transform": { "use": [ "anim-shape" ] }, "anim-xy": { "requires": [ "anim-base", "node-screen" ] }, "app": { "use": [ "app-base", "app-content", "app-transitions", "lazy-model-list", "model", "model-list", "model-sync-rest", "model-sync-local", "router", "view", "view-node-map" ] }, "app-base": { "requires": [ "classnamemanager", "pjax-base", "router", "view" ] }, "app-content": { "requires": [ "app-base", "pjax-content" ] }, "app-transitions": { "requires": [ "app-base" ] }, "app-transitions-css": { "type": "css" }, "app-transitions-native": { "condition": { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }, "requires": [ "app-transitions", "app-transitions-css", "parallel", "transition" ] }, "array-extras": { "requires": [ "yui-base" ] }, "array-invoke": { "requires": [ "yui-base" ] }, "arraylist": { "requires": [ "yui-base" ] }, "arraylist-add": { "requires": [ "arraylist" ] }, "arraylist-filter": { "requires": [ "arraylist" ] }, "arraysort": { "requires": [ "yui-base" ] }, "async-queue": { "requires": [ "event-custom" ] }, "attribute": { "use": [ "attribute-base", "attribute-complex" ] }, "attribute-base": { "requires": [ "attribute-core", "attribute-observable", "attribute-extras" ] }, "attribute-complex": { "requires": [ "attribute-base" ] }, "attribute-core": { "requires": [ "oop" ] }, "attribute-events": { "use": [ "attribute-observable" ] }, "attribute-extras": { "requires": [ "oop" ] }, "attribute-observable": { "requires": [ "event-custom" ] }, "autocomplete": { "use": [ "autocomplete-base", "autocomplete-sources", "autocomplete-list", "autocomplete-plugin" ] }, "autocomplete-base": { "optional": [ "autocomplete-sources" ], "requires": [ "array-extras", "base-build", "escape", "event-valuechange", "node-base" ] }, "autocomplete-filters": { "requires": [ "array-extras", "text-wordbreak" ] }, "autocomplete-filters-accentfold": { "requires": [ "array-extras", "text-accentfold", "text-wordbreak" ] }, "autocomplete-highlighters": { "requires": [ "array-extras", "highlight-base" ] }, "autocomplete-highlighters-accentfold": { "requires": [ "array-extras", "highlight-accentfold" ] }, "autocomplete-list": { "after": [ "autocomplete-sources" ], "lang": [ "en", "es", "hu", "it" ], "requires": [ "autocomplete-base", "event-resize", "node-screen", "selector-css3", "shim-plugin", "widget", "widget-position", "widget-position-align" ], "skinnable": true }, "autocomplete-list-keys": { "condition": { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }, "requires": [ "autocomplete-list", "base-build" ] }, "autocomplete-plugin": { "requires": [ "autocomplete-list", "node-pluginhost" ] }, "autocomplete-sources": { "optional": [ "io-base", "json-parse", "jsonp", "yql" ], "requires": [ "autocomplete-base" ] }, "axes": { "use": [ "axis-numeric", "axis-category", "axis-time", "axis-stacked" ] }, "axes-base": { "use": [ "axis-numeric-base", "axis-category-base", "axis-time-base", "axis-stacked-base" ] }, "axis": { "requires": [ "dom", "widget", "widget-position", "widget-stack", "graphics", "axis-base" ] }, "axis-base": { "requires": [ "classnamemanager", "datatype-number", "datatype-date", "base", "event-custom" ] }, "axis-category": { "requires": [ "axis", "axis-category-base" ] }, "axis-category-base": { "requires": [ "axis-base" ] }, "axis-numeric": { "requires": [ "axis", "axis-numeric-base" ] }, "axis-numeric-base": { "requires": [ "axis-base" ] }, "axis-stacked": { "requires": [ "axis-numeric", "axis-stacked-base" ] }, "axis-stacked-base": { "requires": [ "axis-numeric-base" ] }, "axis-time": { "requires": [ "axis", "axis-time-base" ] }, "axis-time-base": { "requires": [ "axis-base" ] }, "base": { "use": [ "base-base", "base-pluginhost", "base-build" ] }, "base-base": { "requires": [ "attribute-base", "base-core", "base-observable" ] }, "base-build": { "requires": [ "base-base" ] }, "base-core": { "requires": [ "attribute-core" ] }, "base-observable": { "requires": [ "attribute-observable", "base-core" ] }, "base-pluginhost": { "requires": [ "base-base", "pluginhost" ] }, "button": { "requires": [ "button-core", "cssbutton", "widget" ] }, "button-core": { "requires": [ "attribute-core", "classnamemanager", "node-base", "escape" ] }, "button-group": { "requires": [ "button-plugin", "cssbutton", "widget" ] }, "button-plugin": { "requires": [ "button-core", "cssbutton", "node-pluginhost" ] }, "cache": { "use": [ "cache-base", "cache-offline", "cache-plugin" ] }, "cache-base": { "requires": [ "base" ] }, "cache-offline": { "requires": [ "cache-base", "json" ] }, "cache-plugin": { "requires": [ "plugin", "cache-base" ] }, "calendar": { "requires": [ "calendar-base", "calendarnavigator" ], "skinnable": true }, "calendar-base": { "lang": [ "de", "en", "es", "es-AR", "fr", "hu", "it", "ja", "nb-NO", "nl", "pt-BR", "ru", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-HANT-TW" ], "requires": [ "widget", "datatype-date", "datatype-date-math", "cssgrids" ], "skinnable": true }, "calendarnavigator": { "requires": [ "plugin", "classnamemanager", "datatype-date", "node" ], "skinnable": true }, "charts": { "use": [ "charts-base" ] }, "charts-base": { "requires": [ "dom", "event-mouseenter", "event-touch", "graphics-group", "axes", "series-pie", "series-line", "series-marker", "series-area", "series-spline", "series-column", "series-bar", "series-areaspline", "series-combo", "series-combospline", "series-line-stacked", "series-marker-stacked", "series-area-stacked", "series-spline-stacked", "series-column-stacked", "series-bar-stacked", "series-areaspline-stacked", "series-combo-stacked", "series-combospline-stacked" ] }, "charts-legend": { "requires": [ "charts-base" ] }, "classnamemanager": { "requires": [ "yui-base" ] }, "clickable-rail": { "requires": [ "slider-base" ] }, "collection": { "use": [ "array-extras", "arraylist", "arraylist-add", "arraylist-filter", "array-invoke" ] }, "color": { "use": [ "color-base", "color-hsl", "color-harmony" ] }, "color-base": { "requires": [ "yui-base" ] }, "color-harmony": { "requires": [ "color-hsl" ] }, "color-hsl": { "requires": [ "color-base" ] }, "color-hsv": { "requires": [ "color-base" ] }, "console": { "lang": [ "en", "es", "hu", "it", "ja" ], "requires": [ "yui-log", "widget" ], "skinnable": true }, "console-filters": { "requires": [ "plugin", "console" ], "skinnable": true }, "content-editable": { "requires": [ "node-base", "editor-selection", "stylesheet", "plugin" ] }, "controller": { "use": [ "router" ] }, "cookie": { "requires": [ "yui-base" ] }, "createlink-base": { "requires": [ "editor-base" ] }, "cssbase": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssbase-context": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssbutton": { "type": "css" }, "cssfonts": { "type": "css" }, "cssfonts-context": { "type": "css" }, "cssgrids": { "optional": [ "cssnormalize" ], "type": "css" }, "cssgrids-base": { "optional": [ "cssnormalize" ], "type": "css" }, "cssgrids-responsive": { "optional": [ "cssnormalize" ], "requires": [ "cssgrids", "cssgrids-responsive-base" ], "type": "css" }, "cssgrids-units": { "optional": [ "cssnormalize" ], "requires": [ "cssgrids-base" ], "type": "css" }, "cssnormalize": { "type": "css" }, "cssnormalize-context": { "type": "css" }, "cssreset": { "type": "css" }, "cssreset-context": { "type": "css" }, "dataschema": { "use": [ "dataschema-base", "dataschema-json", "dataschema-xml", "dataschema-array", "dataschema-text" ] }, "dataschema-array": { "requires": [ "dataschema-base" ] }, "dataschema-base": { "requires": [ "base" ] }, "dataschema-json": { "requires": [ "dataschema-base", "json" ] }, "dataschema-text": { "requires": [ "dataschema-base" ] }, "dataschema-xml": { "requires": [ "dataschema-base" ] }, "datasource": { "use": [ "datasource-local", "datasource-io", "datasource-get", "datasource-function", "datasource-cache", "datasource-jsonschema", "datasource-xmlschema", "datasource-arrayschema", "datasource-textschema", "datasource-polling" ] }, "datasource-arrayschema": { "requires": [ "datasource-local", "plugin", "dataschema-array" ] }, "datasource-cache": { "requires": [ "datasource-local", "plugin", "cache-base" ] }, "datasource-function": { "requires": [ "datasource-local" ] }, "datasource-get": { "requires": [ "datasource-local", "get" ] }, "datasource-io": { "requires": [ "datasource-local", "io-base" ] }, "datasource-jsonschema": { "requires": [ "datasource-local", "plugin", "dataschema-json" ] }, "datasource-local": { "requires": [ "base" ] }, "datasource-polling": { "requires": [ "datasource-local" ] }, "datasource-textschema": { "requires": [ "datasource-local", "plugin", "dataschema-text" ] }, "datasource-xmlschema": { "requires": [ "datasource-local", "plugin", "datatype-xml", "dataschema-xml" ] }, "datatable": { "use": [ "datatable-core", "datatable-table", "datatable-head", "datatable-body", "datatable-base", "datatable-column-widths", "datatable-message", "datatable-mutable", "datatable-sort", "datatable-datasource" ] }, "datatable-base": { "requires": [ "datatable-core", "datatable-table", "datatable-head", "datatable-body", "base-build", "widget" ], "skinnable": true }, "datatable-body": { "requires": [ "datatable-core", "view", "classnamemanager" ] }, "datatable-column-widths": { "requires": [ "datatable-base" ] }, "datatable-core": { "requires": [ "escape", "model-list", "node-event-delegate" ] }, "datatable-datasource": { "requires": [ "datatable-base", "plugin", "datasource-local" ] }, "datatable-foot": { "requires": [ "datatable-core", "view" ] }, "datatable-formatters": { "requires": [ "datatable-body", "datatype-number-format", "datatype-date-format", "escape" ] }, "datatable-head": { "requires": [ "datatable-core", "view", "classnamemanager" ] }, "datatable-highlight": { "requires": [ "datatable-base", "event-hover" ], "skinnable": true }, "datatable-keynav": { "requires": [ "datatable-base" ] }, "datatable-message": { "lang": [ "en", "fr", "es", "hu", "it" ], "requires": [ "datatable-base" ], "skinnable": true }, "datatable-mutable": { "requires": [ "datatable-base" ] }, "datatable-paginator": { "lang": [ "en", "fr" ], "requires": [ "model", "view", "paginator-core", "datatable-foot", "datatable-paginator-templates" ], "skinnable": true }, "datatable-paginator-templates": { "requires": [ "template" ] }, "datatable-scroll": { "requires": [ "datatable-base", "datatable-column-widths", "dom-screen" ], "skinnable": true }, "datatable-sort": { "lang": [ "en", "fr", "es", "hu" ], "requires": [ "datatable-base" ], "skinnable": true }, "datatable-table": { "requires": [ "datatable-core", "datatable-head", "datatable-body", "view", "classnamemanager" ] }, "datatype": { "use": [ "datatype-date", "datatype-number", "datatype-xml" ] }, "datatype-date": { "use": [ "datatype-date-parse", "datatype-date-format", "datatype-date-math" ] }, "datatype-date-format": { "lang": [ "ar", "ar-JO", "ca", "ca-ES", "da", "da-DK", "de", "de-AT", "de-DE", "el", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-JO", "en-MY", "en-NZ", "en-PH", "en-SG", "en-US", "es", "es-AR", "es-BO", "es-CL", "es-CO", "es-EC", "es-ES", "es-MX", "es-PE", "es-PY", "es-US", "es-UY", "es-VE", "fi", "fi-FI", "fr", "fr-BE", "fr-CA", "fr-FR", "hi", "hi-IN", "hu", "id", "id-ID", "it", "it-IT", "ja", "ja-JP", "ko", "ko-KR", "ms", "ms-MY", "nb", "nb-NO", "nl", "nl-BE", "nl-NL", "pl", "pl-PL", "pt", "pt-BR", "ro", "ro-RO", "ru", "ru-RU", "sv", "sv-SE", "th", "th-TH", "tr", "tr-TR", "vi", "vi-VN", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-Hant-TW" ] }, "datatype-date-math": { "requires": [ "yui-base" ] }, "datatype-date-parse": {}, "datatype-number": { "use": [ "datatype-number-parse", "datatype-number-format" ] }, "datatype-number-format": {}, "datatype-number-parse": { "requires": [ "escape" ] }, "datatype-xml": { "use": [ "datatype-xml-parse", "datatype-xml-format" ] }, "datatype-xml-format": {}, "datatype-xml-parse": {}, "dd": { "use": [ "dd-ddm-base", "dd-ddm", "dd-ddm-drop", "dd-drag", "dd-proxy", "dd-constrain", "dd-drop", "dd-scroll", "dd-delegate" ] }, "dd-constrain": { "requires": [ "dd-drag" ] }, "dd-ddm": { "requires": [ "dd-ddm-base", "event-resize" ] }, "dd-ddm-base": { "requires": [ "node", "base", "yui-throttle", "classnamemanager" ] }, "dd-ddm-drop": { "requires": [ "dd-ddm" ] }, "dd-delegate": { "requires": [ "dd-drag", "dd-drop-plugin", "event-mouseenter" ] }, "dd-drag": { "requires": [ "dd-ddm-base", "selector-css2" ] }, "dd-drop": { "requires": [ "dd-drag", "dd-ddm-drop" ] }, "dd-drop-plugin": { "requires": [ "dd-drop" ] }, "dd-gestures": { "condition": { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }, "requires": [ "dd-drag", "event-synthetic", "event-gestures" ] }, "dd-plugin": { "optional": [ "dd-constrain", "dd-proxy" ], "requires": [ "dd-drag" ] }, "dd-proxy": { "requires": [ "dd-drag" ] }, "dd-scroll": { "requires": [ "dd-drag" ] }, "dial": { "lang": [ "en", "es", "hu" ], "requires": [ "widget", "dd-drag", "event-mouseenter", "event-move", "event-key", "transition", "intl" ], "skinnable": true }, "dom": { "use": [ "dom-base", "dom-screen", "dom-style", "selector-native", "selector" ] }, "dom-base": { "requires": [ "dom-core" ] }, "dom-core": { "requires": [ "oop", "features" ] }, "dom-screen": { "requires": [ "dom-base", "dom-style" ] }, "dom-style": { "requires": [ "dom-base" ] }, "dom-style-ie": { "condition": { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }, "requires": [ "dom-style", "color-base" ] }, "dump": { "requires": [ "yui-base" ] }, "editor": { "use": [ "frame", "editor-selection", "exec-command", "editor-base", "editor-para", "editor-br", "editor-bidi", "editor-tab", "createlink-base" ] }, "editor-base": { "requires": [ "base", "frame", "node", "exec-command", "editor-selection" ] }, "editor-bidi": { "requires": [ "editor-base" ] }, "editor-br": { "requires": [ "editor-base" ] }, "editor-inline": { "requires": [ "editor-base", "content-editable" ] }, "editor-lists": { "requires": [ "editor-base" ] }, "editor-para": { "requires": [ "editor-para-base" ] }, "editor-para-base": { "requires": [ "editor-base" ] }, "editor-para-ie": { "condition": { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }, "requires": [ "editor-para-base" ] }, "editor-selection": { "requires": [ "node" ] }, "editor-tab": { "requires": [ "editor-base" ] }, "escape": { "requires": [ "yui-base" ] }, "event": { "after": [ "node-base" ], "use": [ "event-base", "event-delegate", "event-synthetic", "event-mousewheel", "event-mouseenter", "event-key", "event-focus", "event-resize", "event-hover", "event-outside", "event-touch", "event-move", "event-flick", "event-valuechange", "event-tap" ] }, "event-base": { "after": [ "node-base" ], "requires": [ "event-custom-base" ] }, "event-base-ie": { "after": [ "event-base" ], "condition": { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }, "requires": [ "node-base" ] }, "event-contextmenu": { "requires": [ "event-synthetic", "dom-screen" ] }, "event-custom": { "use": [ "event-custom-base", "event-custom-complex" ] }, "event-custom-base": { "requires": [ "oop" ] }, "event-custom-complex": { "requires": [ "event-custom-base" ] }, "event-delegate": { "requires": [ "node-base" ] }, "event-flick": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-focus": { "requires": [ "event-synthetic" ] }, "event-gestures": { "use": [ "event-flick", "event-move" ] }, "event-hover": { "requires": [ "event-mouseenter" ] }, "event-key": { "requires": [ "event-synthetic" ] }, "event-mouseenter": { "requires": [ "event-synthetic" ] }, "event-mousewheel": { "requires": [ "node-base" ] }, "event-move": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-outside": { "requires": [ "event-synthetic" ] }, "event-resize": { "requires": [ "node-base", "event-synthetic" ] }, "event-simulate": { "requires": [ "event-base" ] }, "event-synthetic": { "requires": [ "node-base", "event-custom-complex" ] }, "event-tap": { "requires": [ "node-base", "event-base", "event-touch", "event-synthetic" ] }, "event-touch": { "requires": [ "node-base" ] }, "event-valuechange": { "requires": [ "event-focus", "event-synthetic" ] }, "exec-command": { "requires": [ "frame" ] }, "features": { "requires": [ "yui-base" ] }, "file": { "requires": [ "file-flash", "file-html5" ] }, "file-flash": { "requires": [ "base" ] }, "file-html5": { "requires": [ "base" ] }, "frame": { "requires": [ "base", "node", "plugin", "selector-css3", "yui-throttle" ] }, "gesture-simulate": { "requires": [ "async-queue", "event-simulate", "node-screen" ] }, "get": { "requires": [ "yui-base" ] }, "graphics": { "requires": [ "node", "event-custom", "pluginhost", "matrix", "classnamemanager" ] }, "graphics-canvas": { "condition": { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }, "requires": [ "graphics", "color-base" ] }, "graphics-canvas-default": { "condition": { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" } }, "graphics-group": { "requires": [ "graphics" ] }, "graphics-svg": { "condition": { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-svg-default": { "condition": { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" } }, "graphics-vml": { "condition": { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }, "requires": [ "graphics", "color-base" ] }, "graphics-vml-default": { "condition": { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" } }, "handlebars": { "use": [ "handlebars-compiler" ] }, "handlebars-base": { "requires": [] }, "handlebars-compiler": { "requires": [ "handlebars-base" ] }, "highlight": { "use": [ "highlight-base", "highlight-accentfold" ] }, "highlight-accentfold": { "requires": [ "highlight-base", "text-accentfold" ] }, "highlight-base": { "requires": [ "array-extras", "classnamemanager", "escape", "text-wordbreak" ] }, "history": { "use": [ "history-base", "history-hash", "history-html5" ] }, "history-base": { "requires": [ "event-custom-complex" ] }, "history-hash": { "after": [ "history-html5" ], "requires": [ "event-synthetic", "history-base", "yui-later" ] }, "history-hash-ie": { "condition": { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }, "requires": [ "history-hash", "node-base" ] }, "history-html5": { "optional": [ "json" ], "requires": [ "event-base", "history-base", "node-base" ] }, "imageloader": { "requires": [ "base-base", "node-style", "node-screen" ] }, "intl": { "requires": [ "intl-base", "event-custom" ] }, "intl-base": { "requires": [ "yui-base" ] }, "io": { "use": [ "io-base", "io-xdr", "io-form", "io-upload-iframe", "io-queue" ] }, "io-base": { "requires": [ "event-custom-base", "querystring-stringify-simple" ] }, "io-form": { "requires": [ "io-base", "node-base" ] }, "io-nodejs": { "condition": { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }, "requires": [ "io-base" ] }, "io-queue": { "requires": [ "io-base", "queue-promote" ] }, "io-upload-iframe": { "requires": [ "io-base", "node-base" ] }, "io-xdr": { "requires": [ "io-base", "datatype-xml-parse" ] }, "json": { "use": [ "json-parse", "json-stringify" ] }, "json-parse": { "requires": [ "yui-base" ] }, "json-parse-shim": { "condition": { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }, "requires": [ "json-parse" ] }, "json-stringify": { "requires": [ "yui-base" ] }, "json-stringify-shim": { "condition": { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }, "requires": [ "json-stringify" ] }, "jsonp": { "requires": [ "get", "oop" ] }, "jsonp-url": { "requires": [ "jsonp" ] }, "lazy-model-list": { "requires": [ "model-list" ] }, "loader": { "use": [ "loader-base", "loader-rollup", "loader-yui3" ] }, "loader-base": { "requires": [ "get", "features" ] }, "loader-pathogen-combohandler": {}, "loader-pathogen-encoder": { "use": [ "loader-base", "loader-rollup", "loader-yui3", "loader-pathogen-combohandler" ] }, "loader-rollup": { "requires": [ "loader-base" ] }, "loader-yui3": { "requires": [ "loader-base" ] }, "matrix": { "requires": [ "yui-base" ] }, "model": { "requires": [ "base-build", "escape", "json-parse" ] }, "model-list": { "requires": [ "array-extras", "array-invoke", "arraylist", "base-build", "escape", "json-parse", "model" ] }, "model-sync-local": { "requires": [ "model", "json-stringify" ] }, "model-sync-rest": { "requires": [ "model", "io-base", "json-stringify" ] }, "node": { "use": [ "node-base", "node-event-delegate", "node-pluginhost", "node-screen", "node-style" ] }, "node-base": { "requires": [ "event-base", "node-core", "dom-base", "dom-style" ] }, "node-core": { "requires": [ "dom-core", "selector" ] }, "node-event-delegate": { "requires": [ "node-base", "event-delegate" ] }, "node-event-html5": { "requires": [ "node-base" ] }, "node-event-simulate": { "requires": [ "node-base", "event-simulate", "gesture-simulate" ] }, "node-flick": { "requires": [ "classnamemanager", "transition", "event-flick", "plugin" ], "skinnable": true }, "node-focusmanager": { "requires": [ "attribute", "node", "plugin", "node-event-simulate", "event-key", "event-focus" ] }, "node-load": { "requires": [ "node-base", "io-base" ] }, "node-menunav": { "requires": [ "node", "classnamemanager", "plugin", "node-focusmanager" ], "skinnable": true }, "node-pluginhost": { "requires": [ "node-base", "pluginhost" ] }, "node-screen": { "requires": [ "dom-screen", "node-base" ] }, "node-scroll-info": { "requires": [ "array-extras", "base-build", "event-resize", "node-pluginhost", "plugin", "selector" ] }, "node-style": { "requires": [ "dom-style", "node-base" ] }, "oop": { "requires": [ "yui-base" ] }, "overlay": { "requires": [ "widget", "widget-stdmod", "widget-position", "widget-position-align", "widget-stack", "widget-position-constrain" ], "skinnable": true }, "paginator": { "requires": [ "paginator-core" ] }, "paginator-core": { "requires": [ "base" ] }, "paginator-url": { "requires": [ "paginator" ] }, "panel": { "requires": [ "widget", "widget-autohide", "widget-buttons", "widget-modality", "widget-position", "widget-position-align", "widget-position-constrain", "widget-stack", "widget-stdmod" ], "skinnable": true }, "parallel": { "requires": [ "yui-base" ] }, "pjax": { "requires": [ "pjax-base", "pjax-content" ] }, "pjax-base": { "requires": [ "classnamemanager", "node-event-delegate", "router" ] }, "pjax-content": { "requires": [ "io-base", "node-base", "router" ] }, "pjax-plugin": { "requires": [ "node-pluginhost", "pjax", "plugin" ] }, "plugin": { "requires": [ "base-base" ] }, "pluginhost": { "use": [ "pluginhost-base", "pluginhost-config" ] }, "pluginhost-base": { "requires": [ "yui-base" ] }, "pluginhost-config": { "requires": [ "pluginhost-base" ] }, "promise": { "requires": [ "timers" ] }, "querystring": { "use": [ "querystring-parse", "querystring-stringify" ] }, "querystring-parse": { "requires": [ "yui-base", "array-extras" ] }, "querystring-parse-simple": { "requires": [ "yui-base" ] }, "querystring-stringify": { "requires": [ "yui-base" ] }, "querystring-stringify-simple": { "requires": [ "yui-base" ] }, "queue-promote": { "requires": [ "yui-base" ] }, "range-slider": { "requires": [ "slider-base", "slider-value-range", "clickable-rail" ] }, "recordset": { "use": [ "recordset-base", "recordset-sort", "recordset-filter", "recordset-indexer" ] }, "recordset-base": { "requires": [ "base", "arraylist" ] }, "recordset-filter": { "requires": [ "recordset-base", "array-extras", "plugin" ] }, "recordset-indexer": { "requires": [ "recordset-base", "plugin" ] }, "recordset-sort": { "requires": [ "arraysort", "recordset-base", "plugin" ] }, "resize": { "use": [ "resize-base", "resize-proxy", "resize-constrain" ] }, "resize-base": { "requires": [ "base", "widget", "event", "oop", "dd-drag", "dd-delegate", "dd-drop" ], "skinnable": true }, "resize-constrain": { "requires": [ "plugin", "resize-base" ] }, "resize-plugin": { "optional": [ "resize-constrain" ], "requires": [ "resize-base", "plugin" ] }, "resize-proxy": { "requires": [ "plugin", "resize-base" ] }, "router": { "optional": [ "querystring-parse" ], "requires": [ "array-extras", "base-build", "history" ] }, "scrollview": { "requires": [ "scrollview-base", "scrollview-scrollbars" ] }, "scrollview-base": { "requires": [ "widget", "event-gestures", "event-mousewheel", "transition" ], "skinnable": true }, "scrollview-base-ie": { "condition": { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }, "requires": [ "scrollview-base" ] }, "scrollview-list": { "requires": [ "plugin", "classnamemanager" ], "skinnable": true }, "scrollview-paginator": { "requires": [ "plugin", "classnamemanager" ] }, "scrollview-scrollbars": { "requires": [ "classnamemanager", "transition", "plugin" ], "skinnable": true }, "selector": { "requires": [ "selector-native" ] }, "selector-css2": { "condition": { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }, "requires": [ "selector-native" ] }, "selector-css3": { "requires": [ "selector-native", "selector-css2" ] }, "selector-native": { "requires": [ "dom-base" ] }, "series-area": { "requires": [ "series-cartesian", "series-fill-util" ] }, "series-area-stacked": { "requires": [ "series-stacked", "series-area" ] }, "series-areaspline": { "requires": [ "series-area", "series-curve-util" ] }, "series-areaspline-stacked": { "requires": [ "series-stacked", "series-areaspline" ] }, "series-bar": { "requires": [ "series-marker", "series-histogram-base" ] }, "series-bar-stacked": { "requires": [ "series-stacked", "series-bar" ] }, "series-base": { "requires": [ "graphics", "axis-base" ] }, "series-candlestick": { "requires": [ "series-range" ] }, "series-cartesian": { "requires": [ "series-base" ] }, "series-column": { "requires": [ "series-marker", "series-histogram-base" ] }, "series-column-stacked": { "requires": [ "series-stacked", "series-column" ] }, "series-combo": { "requires": [ "series-cartesian", "series-line-util", "series-plot-util", "series-fill-util" ] }, "series-combo-stacked": { "requires": [ "series-stacked", "series-combo" ] }, "series-combospline": { "requires": [ "series-combo", "series-curve-util" ] }, "series-combospline-stacked": { "requires": [ "series-combo-stacked", "series-curve-util" ] }, "series-curve-util": {}, "series-fill-util": {}, "series-histogram-base": { "requires": [ "series-cartesian", "series-plot-util" ] }, "series-line": { "requires": [ "series-cartesian", "series-line-util" ] }, "series-line-stacked": { "requires": [ "series-stacked", "series-line" ] }, "series-line-util": {}, "series-marker": { "requires": [ "series-cartesian", "series-plot-util" ] }, "series-marker-stacked": { "requires": [ "series-stacked", "series-marker" ] }, "series-ohlc": { "requires": [ "series-range" ] }, "series-pie": { "requires": [ "series-base", "series-plot-util" ] }, "series-plot-util": {}, "series-range": { "requires": [ "series-cartesian" ] }, "series-spline": { "requires": [ "series-line", "series-curve-util" ] }, "series-spline-stacked": { "requires": [ "series-stacked", "series-spline" ] }, "series-stacked": { "requires": [ "axis-stacked" ] }, "shim-plugin": { "requires": [ "node-style", "node-pluginhost" ] }, "slider": { "use": [ "slider-base", "slider-value-range", "clickable-rail", "range-slider" ] }, "slider-base": { "requires": [ "widget", "dd-constrain", "event-key" ], "skinnable": true }, "slider-value-range": { "requires": [ "slider-base" ] }, "sortable": { "requires": [ "dd-delegate", "dd-drop-plugin", "dd-proxy" ] }, "sortable-scroll": { "requires": [ "dd-scroll", "sortable" ] }, "stylesheet": { "requires": [ "yui-base" ] }, "substitute": { "optional": [ "dump" ], "requires": [ "yui-base" ] }, "swf": { "requires": [ "event-custom", "node", "swfdetect", "escape" ] }, "swfdetect": { "requires": [ "yui-base" ] }, "tabview": { "requires": [ "widget", "widget-parent", "widget-child", "tabview-base", "node-pluginhost", "node-focusmanager" ], "skinnable": true }, "tabview-base": { "requires": [ "node-event-delegate", "classnamemanager" ] }, "tabview-plugin": { "requires": [ "tabview-base" ] }, "template": { "use": [ "template-base", "template-micro" ] }, "template-base": { "requires": [ "yui-base" ] }, "template-micro": { "requires": [ "escape" ] }, "test": { "requires": [ "event-simulate", "event-custom", "json-stringify" ] }, "test-console": { "requires": [ "console-filters", "test", "array-extras" ], "skinnable": true }, "text": { "use": [ "text-accentfold", "text-wordbreak" ] }, "text-accentfold": { "requires": [ "array-extras", "text-data-accentfold" ] }, "text-data-accentfold": { "requires": [ "yui-base" ] }, "text-data-wordbreak": { "requires": [ "yui-base" ] }, "text-wordbreak": { "requires": [ "array-extras", "text-data-wordbreak" ] }, "timers": { "requires": [ "yui-base" ] }, "transition": { "requires": [ "node-style" ] }, "transition-timer": { "condition": { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }, "requires": [ "transition" ] }, "tree": { "requires": [ "base-build", "tree-node" ] }, "tree-labelable": { "requires": [ "tree" ] }, "tree-lazy": { "requires": [ "base-pluginhost", "plugin", "tree" ] }, "tree-node": {}, "tree-openable": { "requires": [ "tree" ] }, "tree-selectable": { "requires": [ "tree" ] }, "tree-sortable": { "requires": [ "tree" ] }, "uploader": { "requires": [ "uploader-html5", "uploader-flash" ] }, "uploader-flash": { "requires": [ "swfdetect", "escape", "widget", "base", "cssbutton", "node", "event-custom", "uploader-queue" ] }, "uploader-html5": { "requires": [ "widget", "node-event-simulate", "file-html5", "uploader-queue" ] }, "uploader-queue": { "requires": [ "base" ] }, "view": { "requires": [ "base-build", "node-event-delegate" ] }, "view-node-map": { "requires": [ "view" ] }, "widget": { "use": [ "widget-base", "widget-htmlparser", "widget-skin", "widget-uievents" ] }, "widget-anim": { "requires": [ "anim-base", "plugin", "widget" ] }, "widget-autohide": { "requires": [ "base-build", "event-key", "event-outside", "widget" ] }, "widget-base": { "requires": [ "attribute", "base-base", "base-pluginhost", "classnamemanager", "event-focus", "node-base", "node-style" ], "skinnable": true }, "widget-base-ie": { "condition": { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }, "requires": [ "widget-base" ] }, "widget-buttons": { "requires": [ "button-plugin", "cssbutton", "widget-stdmod" ] }, "widget-child": { "requires": [ "base-build", "widget" ] }, "widget-htmlparser": { "requires": [ "widget-base" ] }, "widget-modality": { "requires": [ "base-build", "event-outside", "widget" ], "skinnable": true }, "widget-parent": { "requires": [ "arraylist", "base-build", "widget" ] }, "widget-position": { "requires": [ "base-build", "node-screen", "widget" ] }, "widget-position-align": { "requires": [ "widget-position" ] }, "widget-position-constrain": { "requires": [ "widget-position" ] }, "widget-skin": { "requires": [ "widget-base" ] }, "widget-stack": { "requires": [ "base-build", "widget" ], "skinnable": true }, "widget-stdmod": { "requires": [ "base-build", "widget" ] }, "widget-uievents": { "requires": [ "node-event-delegate", "widget-base" ] }, "yql": { "requires": [ "oop" ] }, "yql-jsonp": { "condition": { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql" }, "requires": [ "yql", "jsonp", "jsonp-url" ] }, "yql-nodejs": { "condition": { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs" }, "requires": [ "yql" ] }, "yql-winjs": { "condition": { "name": "yql-winjs", "trigger": "yql", "ua": "winjs" }, "requires": [ "yql" ] }, "yui": {}, "yui-base": {}, "yui-later": { "requires": [ "yui-base" ] }, "yui-log": { "requires": [ "yui-base" ] }, "yui-throttle": { "requires": [ "yui-base" ] } }); YUI.Env[Y.version].md5 = '2fd2be6b12ee9f999b4367499ae61aae'; }, '3.18.1', {"requires": ["loader-base"]}); YUI.add('loader-pathogen-combohandler', function (Y, NAME) { /*jslint vars: true */ var GROUP_DELIM = ';', SUB_GROUP_DELIM = '+', MODULE_DELIM = ',', FILTER_RE = /-(min|debug).js/, EXTENSION_RE = /\.(?:js|css)$/, galleryVersion, GALLERY_RE = /^(?:yui:)?gallery-([^\/]+)/, TYPES = { js: true, css: true }, customComboBase; Y.mix(Y.Loader.prototype, { /** * Encodes combo urls based on modules and appends them to an object hash of arrays from `loader.resolve`. * * @method _pathogenEncodeComboSources * @param {Object} resolved The object hash of arrays in which to attach the encoded combo sources. * @return Object * @private */ _pathogenEncodeComboSources: function (resolved) { var combine = this.combine, resolvedUrls, maxURLLength, resolvedMods, comboUrls, urlKey, modKey, group, type; // Check to see if anything needs to be combined. if (!combine) { for (group in this.groups) { if (this.groups.hasOwnProperty(group)) { if (!combine && group.combine) { combine = group.combine; break; } } } } // Add the pathogen namespace to the combo base. if (Y.config.customComboBase) { customComboBase = Y.config.customComboBase; } if (customComboBase && combine) { maxURLLength = this.maxURLLength; for (type in TYPES) { /*jslint forin: false*/ if (!TYPES.hasOwnProperty(type)) { /*jslint forin: true*/ continue; } urlKey = type; modKey = type + 'Mods'; resolved[urlKey] = resolvedUrls = resolved[urlKey] || []; resolved[modKey] = resolvedMods = resolved[modKey] || []; // Generate custom combo urls. comboUrls = this._customResolve(resolvedMods, type); Y.log('Default encoding resulted in ' + resolved[type].length + ' URLs', 'info', NAME); Y.log(Y.dump(resolved[type]), 'info', NAME); Y.log('Custom encoding resulted in ' + comboUrls.length + ' URLs', 'info', NAME); Y.log(Y.dump(comboUrls), 'info', NAME); resolved[type] = resolved[type].concat(comboUrls); } } return resolved; }, /** Build each combo url from the bottom up. There's probably room for optimization here, but let's keep it simple for now. @method _customResolve @param {Array} modules A list of module meta. @param {String} type Either `js` or `css`. @return {String} Combo url. @private */ _customResolve: function (modules, type) { var source = this._aggregateGroups(modules), groups = this._sortAggregatedGroups(source), comboUrls = [], comboTail, filter, match, url; // Determine the combo tail (e.g., '.debug.js'). Assumption: `filter` is // global to the resolve() and should match the filter on loader. if (!filter) { match = FILTER_RE.exec(Y.config.loaderPath); filter = match && match[1] || 'raw'; filter = (type === 'css' && filter === 'debug') ? 'raw' : 'min'; comboTail = filter === 'min' ? '' : '.' + filter; comboTail = comboTail + '.' + type; } url = this._buildCombo(groups, customComboBase, comboTail); while (url) { comboUrls.push(url); url = this._buildCombo(groups, customComboBase, comboTail); } return comboUrls; }, /** Aggregate modules into groups with unique keys. The key is "$name+$version" for core and gallery groups, and just "$root" for all other groups. @method _aggregateGroups @param {Array} modules A list of module meta. @return {Object} Aggregated groups of module meta. @private */ _aggregateGroups: function (modules) { var source = {}, galleryMatch, meta, name, mod, key, len, i; // Segment the modules for efficient combo encoding. for (i = 0, len = modules.length; i < len; i += 1) { mod = modules[i]; name = mod.name; // Skip modules that should be loaded singly. This is kind of confusing // because it mimics the behavior of the loader (also confusing): // https://github.com/ekashida/yui3/blob/632167a36d57da7a884aacf0f4488dd5b8619c7c/src/loader/js/loader.js#L2563 meta = this.groups && this.groups[mod.group]; if (meta) { if (!meta.combine || mod.fullpath) { continue; } } else if (!this.combine) { continue; } if (!mod.combine && mod.ext) { continue; } // YUI core modules => core group if (!mod.group) { key = 'c' + SUB_GROUP_DELIM + YUI.version; } // YUI gallery modules => gallery group else if (mod.group === 'gallery') { if (!galleryVersion) { galleryMatch = GALLERY_RE.exec(this.groups.gallery.root); galleryVersion = galleryMatch && galleryMatch[1]; } name = name.split('gallery-').pop(); // remove prefix key = 'g' + SUB_GROUP_DELIM + galleryVersion; } // If the module was built the YUI way, then we segment these modules // into the `root` group. else if (mod.path.indexOf(name + '/' + name) === 0) { key = meta.root; // Trim '/' from both ends. if (key.charAt(0) === '/') { key = key.slice(1); } if (key.charAt(key.length - 1) === '/') { key = key.slice(0, -1); } key = 'r' + SUB_GROUP_DELIM + key; } // If the path does not follow the YUI build convention, then we // add them to the prefix tree and subsequently segment these modules // into the `path` group. else { // remove file extension name = mod.path.split(EXTENSION_RE).shift(); if (meta && meta.root) { name = meta.root + name; } if (name.charAt(0) === '/') { name = name.slice(1); } // Tag this module as `path` so that we know to include the // full path in the combo url later on key = 'path' + SUB_GROUP_DELIM + name; } source[key] = source[key] || []; source[key].push(name); } return source; }, /** Build each combo url from the bottom up. There's probably room for optimization here, but let's keep it simple for now. @method _buildCombo @param {Array} groups Grouped module meta. @param {String} comboBase The base of the combo url. @param {String} comboTail The tail of the combo url (e.g. .debug.js). @return {String} A combo url. @private */ _buildCombo: function (groups, comboBase, comboTail) { var comboUrl = comboBase, currLen = comboBase.length + comboTail.length, currDelim, currKey, prepend, modules, token, group, len, i; for (i = 0, len = groups.length; i < len; i += 1) { group = groups[i]; currDelim = comboUrl === comboBase ? '' : GROUP_DELIM; currKey = group.key; modules = group.modules; while (modules.length) { prepend = currDelim + currKey; prepend = prepend ? prepend + SUB_GROUP_DELIM : MODULE_DELIM; // Since modules with custom paths are treated as their own // segment, we override the prepend value so that it is only ever // set to the group delimiter. TODO: refactor this while loop into // one with multiple if-statements to make it easier to read. if (group.key.indexOf('path') === 0) { prepend = currDelim; } token = prepend + modules[0]; if (currLen + token.length < this.maxURLLength) { comboUrl += token; currLen += token.length; modules.shift(); } else { return comboUrl + comboTail; } currDelim = currKey = ''; } } comboUrl += comboTail; // If no modules were encoded in the combo url. if (comboUrl.length === comboBase.length + comboTail.length) { comboUrl = null; } return comboUrl; }, /** Sort the aggregated groups, and the modules within them. Minimizes cache misses in Yahoo's infrastructure by encoding predictable combo urls across browsers since iterating over an object does not guarantee order. @method _sortAggregatedGroups @param {Object} groups Aggregated groups. @return {Array} Sorted groups. @private **/ _sortAggregatedGroups: function (groups) { var sorted = [], key, len, i; for (key in groups) { if (groups.hasOwnProperty(key)) { sorted.push({ key: key, modules: groups[key] }); } } // Sort the groups. sorted.sort(function (a, b) { if(a.key < b.key) { return -1; } else if (a.key > b.key) { return 1; } else { return 0; } }); // Sort the modules. for (i = 0, len = sorted.length; i < len; i += 1) { sorted[i].modules.sort(); } return sorted; } }, true); }, '3.18.1'); YUI.add('loader-pathogen-encoder', function (Y, NAME) {}, '3.18.1', {"use": ["loader-base", "loader-rollup", "loader-yui3", "loader-pathogen-combohandler"]}); PK\.=3.18.1/loader-pathogen-encoder/loader-pathogen-encoder-min.jsnu[YUI.add("loader-base",function(e,t){(function(){var t=e.version,n="/build/",r=t+"/",i=e.Env.base,s="gallery-2014.07.31-18-26",o="2in3",u="4",a="2.9.0",f=i+"combo?",l={version:t,root:r,base:e.Env.base,comboBase:f,skin:{defaultSkin:"sam",base:"assets/skins/",path:"skin.css",after:["cssreset","cssfonts","cssgrids","cssbase","cssreset-context","cssfonts-context"]},groups:{},patterns:{}},c=l.groups,h=function(e,t,r){var s=o+"."+(e||u)+"/"+(t||a)+n,l=r&&r.base?r.base:i,h=r&&r.comboBase?r.comboBase:f;c.yui2.base=l+s,c.yui2.root=s,c.yui2.comboBase=h},p=function(e,t){var r=(e||s)+n,o=t&&t.base?t.base:i,u=t&&t.comboBase?t.comboBase:f;c.gallery.base=o+r,c.gallery.root=r,c.gallery.comboBase=u};c[t]={},c.gallery={ext:!1,combine:!0,comboBase:f,update:p,patterns:{"gallery-":{},"lang/gallery-":{},"gallerycss-":{type:"css"}}},c.yui2={combine:!0,ext:!1,comboBase:f,update:h,patterns:{"yui2-":{configFn:function(e){/-skin|reset|fonts|grids|base/.test(e.name)&&(e.type="css",e.path=e.path.replace(/\.js/,".css"),e.path=e.path.replace(/\/yui2-skin/,"/assets/skins/sam/yui2-skin"))}}}},p(),h(),YUI.Env[t]&&e.mix(l,YUI.Env[t],!1,["modules","groups","skin"],0,!0),YUI.Env[t]=l})();var n={},r=[],i=1024,s=YUI.Env,o=s._loaded,u="css",a="js",f="intl",l="sam",c=e.version,h="",p=e.Object,d=p.each,v=e.Array,m=s._loaderQueue,g=s[c],y="skin-",b=e.Lang,w=s.mods,E,S=function(e,t,n,r){var i=e+"/"+t;return r||(i+="-min"),i+="."+(n||u),i};YUI.Env._cssLoaded||(YUI.Env._cssLoaded={}),e.Env.meta=g,e.Loader=function(t){var n=this;t=t||{},E=g.md5,n.context=e,t.doBeforeLoader&&t.doBeforeLoader.apply(n,arguments),n.base=e.Env.meta.base+e.Env.meta.root,n.comboBase=e.Env.meta.comboBase,n.combine=t.base&&t.base.indexOf(n.comboBase.substr(0,20))>-1,n.comboSep="&",n.maxURLLength=i,n.ignoreRegistered=t.ignoreRegistered,n.root=e.Env.meta.root,n.timeout=0,n.forceMap={},n.allowRollup=!1,n.filters={},n.required={},n.patterns={},n.moduleInfo={},n.groups=e.merge(e.Env.meta.groups),n.skin=e.merge(e.Env.meta.skin),n.conditions={},n.config=t,n._internal=!0,n._populateConditionsCache(),n.loaded=o[c],n.async=!0,n._inspectPage(),n._internal=!1,n._config(t),n.forceMap=n.force?e.Array.hash(n.force):{},n.testresults=null,e.config.tests&&(n.testresults=e.config.tests),n.sorted=[],n.dirty=!0,n.inserted={},n.skipped={},n.tested={},n.ignoreRegistered&&n._resetModules()},e.Loader.prototype={getModuleInfo:function(t){var n=this.moduleInfo[t],r,i,o,a;return n?n:(r=g.modules,i=s._renderedMods,o=this._internal,i&&i.hasOwnProperty(t)&&!this.ignoreRegistered?this.moduleInfo[t]=e.merge(i[t]):r.hasOwnProperty(t)&&(this._internal=!0,a=this.addModule(r[t],t),a&&a.type===u&&this.isCSSLoaded(a.name,!0)&&(this.loaded[a.name]=!0),this._internal=o),this.moduleInfo[t])},_expandAliases:function(t){var n=[],r=YUI.Env.aliases,i,s;t=e.Array(t);for(i=0;i-1&&(A=n);if(L&&(L[m]||A&&L[A])){O=m,L[A]&&(O=A);for(n=0;n-1},getModule:function(t){if(!t)return null;var n,r,i,s=this.getModuleInfo(t),o=this.patterns;if(!s||s&&s.ext)for(i in o)if(o.hasOwnProperty(i)){n=o[i],n.test||(n.test=this._patternTest);if(n.test(t,i)){r=n;break}}return s?r&&s&&r.configFn&&!s.configFn&&(s.configFn=r.configFn,s.configFn(s)):r&&(n.action?n.action.call(this,t,i):(s=this.addModule(e.merge(r,{test:void 0,temp:!0}),t),s&&r.configFn&&(s.configFn=r.configFn))),s},_rollup:function(){},_reduce:function(e){e=e||this.required;var t,n,r,i,s=this.loadType,o=this.ignore?v.hash(this.ignore):!1;for(t in e)if(e.hasOwnProperty(t)){i=this.getModule(t),((this.loaded[t]||w[t])&&!this.forceMap[t]&&!this.ignoreRegistered||s&&i&&i.type!==s)&&delete e[t],o&&o[t]&&delete e[t],r=i&&i.supersedes;if(r)for(n=0;n0&&(m.running=!0,m.next()())},insert:function(t,n,r){var i=this,s=e.merge(this);delete s.require,delete s.dirty,m.add(function(){i._insert(s,t,n,r)}),this._continue()},loadNext:function(){return},_filter:function(e,t,n){var r=this.filter,i=t&&t in this.filters,s=i&&this.filters[t],o=n||(this.getModuleInfo(t)||{}).group||null;return o&&this.groups[o]&&this.groups[o].filter&&(s=this.groups[o].filter,i=!0),e&&(i&&(r=b.isString(s)?this.FILTER_DEFS[s.toUpperCase()]||null:s),r&&(e=e.replace(new RegExp(r.searchExp,"g"),r.replaceStr))),e},_url:function(e,t,n){return this._filter((n||this.base||"")+e,t)},resolve:function(t,r){var i=this,s={js:[],jsMods:[],css:[],cssMods:[]},o,f=e.config.comboLoader&&e.config.customComboBase;(i.skin.overrides||i.skin.defaultSkin!==l||i.ignoreRegistered)&&i._resetModules(),t&&i.calculate(),r=r||i.sorted,o=function(e){if(e){var t=e.group&&i.groups[e.group]||n,r;t.async===!1&&(e.async=t.async),r=e.fullpath?i._filter(e.fullpath,e.name):i._url(e.path,e.name,t.base||e.base);if(e.attributes||e.async===!1)r={url:r,async:e.async},e.attributes&&(r.attributes=e.attributes);s[e.type].push(r),s[e.type+"Mods"].push(e)}};var c=i.ignoreRegistered?{}:i.inserted,h,p,d,v,m,g,y,b,w,E=!1;for(w=0,b=r.length;wp){n=[];for(g=0,y=f.length;gp&&(l=n.pop(),s=d+n.join(m),e[c].push(b._filter(s,null,v.group)),n=[],l&&n.push(l));n.length&&(s=d+n.join(m),e[c].push(b._filter(s,null,v.group)))}else e[c].push(b._filter(s,null,v.group))}}return e},load:function(e){if(!e)return;var t=this,n=t.resolve(!0);t.data=n,t.onEnd=function(){e.apply(t.context||t,arguments)},t.insert()}}},"3.18.1",{requires:["get","features"]}),YUI.add("loader-rollup",function(e,t){e.Loader.prototype._rollup=function(){var e,t,n,r,i=this.required,s,o=this.moduleInfo,u,a,f;if(this.dirty||!this.rollups){this.rollups={};for(e in o)o.hasOwnProperty(e)&&(n=this.getModule(e),n&&n.rollup&&(this.rollups[e]=n))}for(;;){u=!1;for(e in this.rollups)if(this.rollups.hasOwnProperty(e)&&!i[e]&&(!this.loaded[e]||this.forceMap[e])){n=this.getModule(e),r=n.supersedes||[],s=!1;if(!n.rollup)continue;a=0;for(t=0;t=n.rollup;if(s)break}}s&&(i[e]=!0,u=!0,this.getRequires(n))}if(!u)break}}},"3.18.1",{requires:["loader-base"]}),YUI.add("loader-yui3",function(e,t){YUI.Env[e.version].modules=YUI.Env[e.version].modules||{},e.mix(YUI.Env[e.version].modules,{"align-plugin":{requires:["node-screen","node-pluginhost"]},anim:{use:["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"]},"anim-base":{requires:["base-base","node-style","color-base"]},"anim-color":{requires:["anim-base"]},"anim-curve":{requires:["anim-xy"]},"anim-easing":{requires:["anim-base"]},"anim-node-plugin":{requires:["node-pluginhost","anim-base"]},"anim-scroll":{requires:["anim-base"]},"anim-shape":{requires:["anim-base","anim-easing","anim-color","matrix"]},"anim-shape-transform":{use:["anim-shape"]},"anim-xy":{requires:["anim-base","node-screen"]},app:{use:["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","model-sync-local","router","view","view-node-map"]},"app-base":{requires:["classnamemanager","pjax-base","router","view"]},"app-content":{requires:["app-base","pjax-content"]},"app-transitions":{requires:["app-base"]},"app-transitions-css":{type:"css"},"app-transitions-native":{condition:{name:"app-transitions-native",test:function(e){var t=e.config.doc,n=t?t.documentElement:null;return n&&n.style?"MozTransition"in n.style||"WebkitTransition"in n.style||"transition"in n.style:!1},trigger:"app-transitions"},requires:["app-transitions","app-transitions-css","parallel","transition" ]},"array-extras":{requires:["yui-base"]},"array-invoke":{requires:["yui-base"]},arraylist:{requires:["yui-base"]},"arraylist-add":{requires:["arraylist"]},"arraylist-filter":{requires:["arraylist"]},arraysort:{requires:["yui-base"]},"async-queue":{requires:["event-custom"]},attribute:{use:["attribute-base","attribute-complex"]},"attribute-base":{requires:["attribute-core","attribute-observable","attribute-extras"]},"attribute-complex":{requires:["attribute-base"]},"attribute-core":{requires:["oop"]},"attribute-events":{use:["attribute-observable"]},"attribute-extras":{requires:["oop"]},"attribute-observable":{requires:["event-custom"]},autocomplete:{use:["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"]},"autocomplete-base":{optional:["autocomplete-sources"],requires:["array-extras","base-build","escape","event-valuechange","node-base"]},"autocomplete-filters":{requires:["array-extras","text-wordbreak"]},"autocomplete-filters-accentfold":{requires:["array-extras","text-accentfold","text-wordbreak"]},"autocomplete-highlighters":{requires:["array-extras","highlight-base"]},"autocomplete-highlighters-accentfold":{requires:["array-extras","highlight-accentfold"]},"autocomplete-list":{after:["autocomplete-sources"],lang:["en","es","hu","it"],requires:["autocomplete-base","event-resize","node-screen","selector-css3","shim-plugin","widget","widget-position","widget-position-align"],skinnable:!0},"autocomplete-list-keys":{condition:{name:"autocomplete-list-keys",test:function(e){return!e.UA.ios&&!e.UA.android},trigger:"autocomplete-list"},requires:["autocomplete-list","base-build"]},"autocomplete-plugin":{requires:["autocomplete-list","node-pluginhost"]},"autocomplete-sources":{optional:["io-base","json-parse","jsonp","yql"],requires:["autocomplete-base"]},axes:{use:["axis-numeric","axis-category","axis-time","axis-stacked"]},"axes-base":{use:["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"]},axis:{requires:["dom","widget","widget-position","widget-stack","graphics","axis-base"]},"axis-base":{requires:["classnamemanager","datatype-number","datatype-date","base","event-custom"]},"axis-category":{requires:["axis","axis-category-base"]},"axis-category-base":{requires:["axis-base"]},"axis-numeric":{requires:["axis","axis-numeric-base"]},"axis-numeric-base":{requires:["axis-base"]},"axis-stacked":{requires:["axis-numeric","axis-stacked-base"]},"axis-stacked-base":{requires:["axis-numeric-base"]},"axis-time":{requires:["axis","axis-time-base"]},"axis-time-base":{requires:["axis-base"]},base:{use:["base-base","base-pluginhost","base-build"]},"base-base":{requires:["attribute-base","base-core","base-observable"]},"base-build":{requires:["base-base"]},"base-core":{requires:["attribute-core"]},"base-observable":{requires:["attribute-observable","base-core"]},"base-pluginhost":{requires:["base-base","pluginhost"]},button:{requires:["button-core","cssbutton","widget"]},"button-core":{requires:["attribute-core","classnamemanager","node-base","escape"]},"button-group":{requires:["button-plugin","cssbutton","widget"]},"button-plugin":{requires:["button-core","cssbutton","node-pluginhost"]},cache:{use:["cache-base","cache-offline","cache-plugin"]},"cache-base":{requires:["base"]},"cache-offline":{requires:["cache-base","json"]},"cache-plugin":{requires:["plugin","cache-base"]},calendar:{requires:["calendar-base","calendarnavigator"],skinnable:!0},"calendar-base":{lang:["de","en","es","es-AR","fr","hu","it","ja","nb-NO","nl","pt-BR","ru","zh-Hans","zh-Hans-CN","zh-Hant","zh-Hant-HK","zh-HANT-TW"],requires:["widget","datatype-date","datatype-date-math","cssgrids"],skinnable:!0},calendarnavigator:{requires:["plugin","classnamemanager","datatype-date","node"],skinnable:!0},charts:{use:["charts-base"]},"charts-base":{requires:["dom","event-mouseenter","event-touch","graphics-group","axes","series-pie","series-line","series-marker","series-area","series-spline","series-column","series-bar","series-areaspline","series-combo","series-combospline","series-line-stacked","series-marker-stacked","series-area-stacked","series-spline-stacked","series-column-stacked","series-bar-stacked","series-areaspline-stacked","series-combo-stacked","series-combospline-stacked"]},"charts-legend":{requires:["charts-base"]},classnamemanager:{requires:["yui-base"]},"clickable-rail":{requires:["slider-base"]},collection:{use:["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"]},color:{use:["color-base","color-hsl","color-harmony"]},"color-base":{requires:["yui-base"]},"color-harmony":{requires:["color-hsl"]},"color-hsl":{requires:["color-base"]},"color-hsv":{requires:["color-base"]},console:{lang:["en","es","hu","it","ja"],requires:["yui-log","widget"],skinnable:!0},"console-filters":{requires:["plugin","console"],skinnable:!0},"content-editable":{requires:["node-base","editor-selection","stylesheet","plugin"]},controller:{use:["router"]},cookie:{requires:["yui-base"]},"createlink-base":{requires:["editor-base"]},cssbase:{after:["cssreset","cssfonts","cssgrids","cssreset-context","cssfonts-context","cssgrids-context"],type:"css"},"cssbase-context":{after:["cssreset","cssfonts","cssgrids","cssreset-context","cssfonts-context","cssgrids-context"],type:"css"},cssbutton:{type:"css"},cssfonts:{type:"css"},"cssfonts-context":{type:"css"},cssgrids:{optional:["cssnormalize"],type:"css"},"cssgrids-base":{optional:["cssnormalize"],type:"css"},"cssgrids-responsive":{optional:["cssnormalize"],requires:["cssgrids","cssgrids-responsive-base"],type:"css"},"cssgrids-units":{optional:["cssnormalize"],requires:["cssgrids-base"],type:"css"},cssnormalize:{type:"css"},"cssnormalize-context":{type:"css"},cssreset:{type:"css"},"cssreset-context":{type:"css"},dataschema:{use:["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"]},"dataschema-array":{requires:["dataschema-base"]},"dataschema-base":{requires:["base"]},"dataschema-json":{requires :["dataschema-base","json"]},"dataschema-text":{requires:["dataschema-base"]},"dataschema-xml":{requires:["dataschema-base"]},datasource:{use:["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"]},"datasource-arrayschema":{requires:["datasource-local","plugin","dataschema-array"]},"datasource-cache":{requires:["datasource-local","plugin","cache-base"]},"datasource-function":{requires:["datasource-local"]},"datasource-get":{requires:["datasource-local","get"]},"datasource-io":{requires:["datasource-local","io-base"]},"datasource-jsonschema":{requires:["datasource-local","plugin","dataschema-json"]},"datasource-local":{requires:["base"]},"datasource-polling":{requires:["datasource-local"]},"datasource-textschema":{requires:["datasource-local","plugin","dataschema-text"]},"datasource-xmlschema":{requires:["datasource-local","plugin","datatype-xml","dataschema-xml"]},datatable:{use:["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"]},"datatable-base":{requires:["datatable-core","datatable-table","datatable-head","datatable-body","base-build","widget"],skinnable:!0},"datatable-body":{requires:["datatable-core","view","classnamemanager"]},"datatable-column-widths":{requires:["datatable-base"]},"datatable-core":{requires:["escape","model-list","node-event-delegate"]},"datatable-datasource":{requires:["datatable-base","plugin","datasource-local"]},"datatable-foot":{requires:["datatable-core","view"]},"datatable-formatters":{requires:["datatable-body","datatype-number-format","datatype-date-format","escape"]},"datatable-head":{requires:["datatable-core","view","classnamemanager"]},"datatable-highlight":{requires:["datatable-base","event-hover"],skinnable:!0},"datatable-keynav":{requires:["datatable-base"]},"datatable-message":{lang:["en","fr","es","hu","it"],requires:["datatable-base"],skinnable:!0},"datatable-mutable":{requires:["datatable-base"]},"datatable-paginator":{lang:["en","fr"],requires:["model","view","paginator-core","datatable-foot","datatable-paginator-templates"],skinnable:!0},"datatable-paginator-templates":{requires:["template"]},"datatable-scroll":{requires:["datatable-base","datatable-column-widths","dom-screen"],skinnable:!0},"datatable-sort":{lang:["en","fr","es","hu"],requires:["datatable-base"],skinnable:!0},"datatable-table":{requires:["datatable-core","datatable-head","datatable-body","view","classnamemanager"]},datatype:{use:["datatype-date","datatype-number","datatype-xml"]},"datatype-date":{use:["datatype-date-parse","datatype-date-format","datatype-date-math"]},"datatype-date-format":{lang:["ar","ar-JO","ca","ca-ES","da","da-DK","de","de-AT","de-DE","el","el-GR","en","en-AU","en-CA","en-GB","en-IE","en-IN","en-JO","en-MY","en-NZ","en-PH","en-SG","en-US","es","es-AR","es-BO","es-CL","es-CO","es-EC","es-ES","es-MX","es-PE","es-PY","es-US","es-UY","es-VE","fi","fi-FI","fr","fr-BE","fr-CA","fr-FR","hi","hi-IN","hu","id","id-ID","it","it-IT","ja","ja-JP","ko","ko-KR","ms","ms-MY","nb","nb-NO","nl","nl-BE","nl-NL","pl","pl-PL","pt","pt-BR","ro","ro-RO","ru","ru-RU","sv","sv-SE","th","th-TH","tr","tr-TR","vi","vi-VN","zh-Hans","zh-Hans-CN","zh-Hant","zh-Hant-HK","zh-Hant-TW"]},"datatype-date-math":{requires:["yui-base"]},"datatype-date-parse":{},"datatype-number":{use:["datatype-number-parse","datatype-number-format"]},"datatype-number-format":{},"datatype-number-parse":{requires:["escape"]},"datatype-xml":{use:["datatype-xml-parse","datatype-xml-format"]},"datatype-xml-format":{},"datatype-xml-parse":{},dd:{use:["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"]},"dd-constrain":{requires:["dd-drag"]},"dd-ddm":{requires:["dd-ddm-base","event-resize"]},"dd-ddm-base":{requires:["node","base","yui-throttle","classnamemanager"]},"dd-ddm-drop":{requires:["dd-ddm"]},"dd-delegate":{requires:["dd-drag","dd-drop-plugin","event-mouseenter"]},"dd-drag":{requires:["dd-ddm-base","selector-css2"]},"dd-drop":{requires:["dd-drag","dd-ddm-drop"]},"dd-drop-plugin":{requires:["dd-drop"]},"dd-gestures":{condition:{name:"dd-gestures",trigger:"dd-drag",ua:"touchEnabled"},requires:["dd-drag","event-synthetic","event-gestures"]},"dd-plugin":{optional:["dd-constrain","dd-proxy"],requires:["dd-drag"]},"dd-proxy":{requires:["dd-drag"]},"dd-scroll":{requires:["dd-drag"]},dial:{lang:["en","es","hu"],requires:["widget","dd-drag","event-mouseenter","event-move","event-key","transition","intl"],skinnable:!0},dom:{use:["dom-base","dom-screen","dom-style","selector-native","selector"]},"dom-base":{requires:["dom-core"]},"dom-core":{requires:["oop","features"]},"dom-screen":{requires:["dom-base","dom-style"]},"dom-style":{requires:["dom-base"]},"dom-style-ie":{condition:{name:"dom-style-ie",test:function(e){var t=e.Features.test,n=e.Features.add,r=e.config.win,i=e.config.doc,s="documentElement",o=!1;return n("style","computedStyle",{test:function(){return r&&"getComputedStyle"in r}}),n("style","opacity",{test:function(){return i&&"opacity"in i[s].style}}),o=!t("style","opacity")&&!t("style","computedStyle"),o},trigger:"dom-style"},requires:["dom-style","color-base"]},dump:{requires:["yui-base"]},editor:{use:["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"]},"editor-base":{requires:["base","frame","node","exec-command","editor-selection"]},"editor-bidi":{requires:["editor-base"]},"editor-br":{requires:["editor-base"]},"editor-inline":{requires:["editor-base","content-editable"]},"editor-lists":{requires:["editor-base"]},"editor-para":{requires:["editor-para-base"]},"editor-para-base":{requires:["editor-base"]},"editor-para-ie":{condition:{name:"editor-para-ie",trigger:"editor-para" ,ua:"ie",when:"instead"},requires:["editor-para-base"]},"editor-selection":{requires:["node"]},"editor-tab":{requires:["editor-base"]},escape:{requires:["yui-base"]},event:{after:["node-base"],use:["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"]},"event-base":{after:["node-base"],requires:["event-custom-base"]},"event-base-ie":{after:["event-base"],condition:{name:"event-base-ie",test:function(e){var t=e.config.doc&&e.config.doc.implementation;return t&&!t.hasFeature("Events","2.0")},trigger:"node-base"},requires:["node-base"]},"event-contextmenu":{requires:["event-synthetic","dom-screen"]},"event-custom":{use:["event-custom-base","event-custom-complex"]},"event-custom-base":{requires:["oop"]},"event-custom-complex":{requires:["event-custom-base"]},"event-delegate":{requires:["node-base"]},"event-flick":{requires:["node-base","event-touch","event-synthetic"]},"event-focus":{requires:["event-synthetic"]},"event-gestures":{use:["event-flick","event-move"]},"event-hover":{requires:["event-mouseenter"]},"event-key":{requires:["event-synthetic"]},"event-mouseenter":{requires:["event-synthetic"]},"event-mousewheel":{requires:["node-base"]},"event-move":{requires:["node-base","event-touch","event-synthetic"]},"event-outside":{requires:["event-synthetic"]},"event-resize":{requires:["node-base","event-synthetic"]},"event-simulate":{requires:["event-base"]},"event-synthetic":{requires:["node-base","event-custom-complex"]},"event-tap":{requires:["node-base","event-base","event-touch","event-synthetic"]},"event-touch":{requires:["node-base"]},"event-valuechange":{requires:["event-focus","event-synthetic"]},"exec-command":{requires:["frame"]},features:{requires:["yui-base"]},file:{requires:["file-flash","file-html5"]},"file-flash":{requires:["base"]},"file-html5":{requires:["base"]},frame:{requires:["base","node","plugin","selector-css3","yui-throttle"]},"gesture-simulate":{requires:["async-queue","event-simulate","node-screen"]},get:{requires:["yui-base"]},graphics:{requires:["node","event-custom","pluginhost","matrix","classnamemanager"]},"graphics-canvas":{condition:{name:"graphics-canvas",test:function(e){var t=e.config.doc,n=e.config.defaultGraphicEngine&&e.config.defaultGraphicEngine=="canvas",r=t&&t.createElement("canvas"),i=t&&t.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1");return(!i||n)&&r&&r.getContext&&r.getContext("2d")},trigger:"graphics"},requires:["graphics","color-base"]},"graphics-canvas-default":{condition:{name:"graphics-canvas-default",test:function(e){var t=e.config.doc,n=e.config.defaultGraphicEngine&&e.config.defaultGraphicEngine=="canvas",r=t&&t.createElement("canvas"),i=t&&t.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1");return(!i||n)&&r&&r.getContext&&r.getContext("2d")},trigger:"graphics"}},"graphics-group":{requires:["graphics"]},"graphics-svg":{condition:{name:"graphics-svg",test:function(e){var t=e.config.doc,n=!e.config.defaultGraphicEngine||e.config.defaultGraphicEngine!="canvas",r=t&&t.createElement("canvas"),i=t&&t.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1");return i&&(n||!r)},trigger:"graphics"},requires:["graphics"]},"graphics-svg-default":{condition:{name:"graphics-svg-default",test:function(e){var t=e.config.doc,n=!e.config.defaultGraphicEngine||e.config.defaultGraphicEngine!="canvas",r=t&&t.createElement("canvas"),i=t&&t.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1");return i&&(n||!r)},trigger:"graphics"}},"graphics-vml":{condition:{name:"graphics-vml",test:function(e){var t=e.config.doc,n=t&&t.createElement("canvas");return t&&!t.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")&&(!n||!n.getContext||!n.getContext("2d"))},trigger:"graphics"},requires:["graphics","color-base"]},"graphics-vml-default":{condition:{name:"graphics-vml-default",test:function(e){var t=e.config.doc,n=t&&t.createElement("canvas");return t&&!t.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")&&(!n||!n.getContext||!n.getContext("2d"))},trigger:"graphics"}},handlebars:{use:["handlebars-compiler"]},"handlebars-base":{requires:[]},"handlebars-compiler":{requires:["handlebars-base"]},highlight:{use:["highlight-base","highlight-accentfold"]},"highlight-accentfold":{requires:["highlight-base","text-accentfold"]},"highlight-base":{requires:["array-extras","classnamemanager","escape","text-wordbreak"]},history:{use:["history-base","history-hash","history-html5"]},"history-base":{requires:["event-custom-complex"]},"history-hash":{after:["history-html5"],requires:["event-synthetic","history-base","yui-later"]},"history-hash-ie":{condition:{name:"history-hash-ie",test:function(e){var t=e.config.doc&&e.config.doc.documentMode;return e.UA.ie&&(!("onhashchange"in e.config.win)||!t||t<8)},trigger:"history-hash"},requires:["history-hash","node-base"]},"history-html5":{optional:["json"],requires:["event-base","history-base","node-base"]},imageloader:{requires:["base-base","node-style","node-screen"]},intl:{requires:["intl-base","event-custom"]},"intl-base":{requires:["yui-base"]},io:{use:["io-base","io-xdr","io-form","io-upload-iframe","io-queue"]},"io-base":{requires:["event-custom-base","querystring-stringify-simple"]},"io-form":{requires:["io-base","node-base"]},"io-nodejs":{condition:{name:"io-nodejs",trigger:"io-base",ua:"nodejs"},requires:["io-base"]},"io-queue":{requires:["io-base","queue-promote"]},"io-upload-iframe":{requires:["io-base","node-base"]},"io-xdr":{requires:["io-base","datatype-xml-parse"]},json:{use:["json-parse","json-stringify"]},"json-parse":{requires:["yui-base"]},"json-parse-shim":{condition:{name:"json-parse-shim",test:function(e){function i(e,t){return e==="ok"?!0:t}var t=e.config .global.JSON,n=Object.prototype.toString.call(t)==="[object JSON]"&&t,r=e.config.useNativeJSONParse!==!1&&!!n;if(r)try{r=n.parse('{"ok":false}',i).ok}catch(s){r=!1}return!r},trigger:"json-parse"},requires:["json-parse"]},"json-stringify":{requires:["yui-base"]},"json-stringify-shim":{condition:{name:"json-stringify-shim",test:function(e){var t=e.config.global.JSON,n=Object.prototype.toString.call(t)==="[object JSON]"&&t,r=e.config.useNativeJSONStringify!==!1&&!!n;if(r)try{r="0"===n.stringify(0)}catch(i){r=!1}return!r},trigger:"json-stringify"},requires:["json-stringify"]},jsonp:{requires:["get","oop"]},"jsonp-url":{requires:["jsonp"]},"lazy-model-list":{requires:["model-list"]},loader:{use:["loader-base","loader-rollup","loader-yui3"]},"loader-base":{requires:["get","features"]},"loader-pathogen-combohandler":{},"loader-pathogen-encoder":{use:["loader-base","loader-rollup","loader-yui3","loader-pathogen-combohandler"]},"loader-rollup":{requires:["loader-base"]},"loader-yui3":{requires:["loader-base"]},matrix:{requires:["yui-base"]},model:{requires:["base-build","escape","json-parse"]},"model-list":{requires:["array-extras","array-invoke","arraylist","base-build","escape","json-parse","model"]},"model-sync-local":{requires:["model","json-stringify"]},"model-sync-rest":{requires:["model","io-base","json-stringify"]},node:{use:["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"]},"node-base":{requires:["event-base","node-core","dom-base","dom-style"]},"node-core":{requires:["dom-core","selector"]},"node-event-delegate":{requires:["node-base","event-delegate"]},"node-event-html5":{requires:["node-base"]},"node-event-simulate":{requires:["node-base","event-simulate","gesture-simulate"]},"node-flick":{requires:["classnamemanager","transition","event-flick","plugin"],skinnable:!0},"node-focusmanager":{requires:["attribute","node","plugin","node-event-simulate","event-key","event-focus"]},"node-load":{requires:["node-base","io-base"]},"node-menunav":{requires:["node","classnamemanager","plugin","node-focusmanager"],skinnable:!0},"node-pluginhost":{requires:["node-base","pluginhost"]},"node-screen":{requires:["dom-screen","node-base"]},"node-scroll-info":{requires:["array-extras","base-build","event-resize","node-pluginhost","plugin","selector"]},"node-style":{requires:["dom-style","node-base"]},oop:{requires:["yui-base"]},overlay:{requires:["widget","widget-stdmod","widget-position","widget-position-align","widget-stack","widget-position-constrain"],skinnable:!0},paginator:{requires:["paginator-core"]},"paginator-core":{requires:["base"]},"paginator-url":{requires:["paginator"]},panel:{requires:["widget","widget-autohide","widget-buttons","widget-modality","widget-position","widget-position-align","widget-position-constrain","widget-stack","widget-stdmod"],skinnable:!0},parallel:{requires:["yui-base"]},pjax:{requires:["pjax-base","pjax-content"]},"pjax-base":{requires:["classnamemanager","node-event-delegate","router"]},"pjax-content":{requires:["io-base","node-base","router"]},"pjax-plugin":{requires:["node-pluginhost","pjax","plugin"]},plugin:{requires:["base-base"]},pluginhost:{use:["pluginhost-base","pluginhost-config"]},"pluginhost-base":{requires:["yui-base"]},"pluginhost-config":{requires:["pluginhost-base"]},promise:{requires:["timers"]},querystring:{use:["querystring-parse","querystring-stringify"]},"querystring-parse":{requires:["yui-base","array-extras"]},"querystring-parse-simple":{requires:["yui-base"]},"querystring-stringify":{requires:["yui-base"]},"querystring-stringify-simple":{requires:["yui-base"]},"queue-promote":{requires:["yui-base"]},"range-slider":{requires:["slider-base","slider-value-range","clickable-rail"]},recordset:{use:["recordset-base","recordset-sort","recordset-filter","recordset-indexer"]},"recordset-base":{requires:["base","arraylist"]},"recordset-filter":{requires:["recordset-base","array-extras","plugin"]},"recordset-indexer":{requires:["recordset-base","plugin"]},"recordset-sort":{requires:["arraysort","recordset-base","plugin"]},resize:{use:["resize-base","resize-proxy","resize-constrain"]},"resize-base":{requires:["base","widget","event","oop","dd-drag","dd-delegate","dd-drop"],skinnable:!0},"resize-constrain":{requires:["plugin","resize-base"]},"resize-plugin":{optional:["resize-constrain"],requires:["resize-base","plugin"]},"resize-proxy":{requires:["plugin","resize-base"]},router:{optional:["querystring-parse"],requires:["array-extras","base-build","history"]},scrollview:{requires:["scrollview-base","scrollview-scrollbars"]},"scrollview-base":{requires:["widget","event-gestures","event-mousewheel","transition"],skinnable:!0},"scrollview-base-ie":{condition:{name:"scrollview-base-ie",trigger:"scrollview-base",ua:"ie"},requires:["scrollview-base"]},"scrollview-list":{requires:["plugin","classnamemanager"],skinnable:!0},"scrollview-paginator":{requires:["plugin","classnamemanager"]},"scrollview-scrollbars":{requires:["classnamemanager","transition","plugin"],skinnable:!0},selector:{requires:["selector-native"]},"selector-css2":{condition:{name:"selector-css2",test:function(e){var t=e.config.doc,n=t&&!("querySelectorAll"in t);return n},trigger:"selector"},requires:["selector-native"]},"selector-css3":{requires:["selector-native","selector-css2"]},"selector-native":{requires:["dom-base"]},"series-area":{requires:["series-cartesian","series-fill-util"]},"series-area-stacked":{requires:["series-stacked","series-area"]},"series-areaspline":{requires:["series-area","series-curve-util"]},"series-areaspline-stacked":{requires:["series-stacked","series-areaspline"]},"series-bar":{requires:["series-marker","series-histogram-base"]},"series-bar-stacked":{requires:["series-stacked","series-bar"]},"series-base":{requires:["graphics","axis-base"]},"series-candlestick":{requires:["series-range"]},"series-cartesian":{requires:["series-base"]},"series-column":{requires:["series-marker","series-histogram-base"]},"series-column-stacked":{requires: ["series-stacked","series-column"]},"series-combo":{requires:["series-cartesian","series-line-util","series-plot-util","series-fill-util"]},"series-combo-stacked":{requires:["series-stacked","series-combo"]},"series-combospline":{requires:["series-combo","series-curve-util"]},"series-combospline-stacked":{requires:["series-combo-stacked","series-curve-util"]},"series-curve-util":{},"series-fill-util":{},"series-histogram-base":{requires:["series-cartesian","series-plot-util"]},"series-line":{requires:["series-cartesian","series-line-util"]},"series-line-stacked":{requires:["series-stacked","series-line"]},"series-line-util":{},"series-marker":{requires:["series-cartesian","series-plot-util"]},"series-marker-stacked":{requires:["series-stacked","series-marker"]},"series-ohlc":{requires:["series-range"]},"series-pie":{requires:["series-base","series-plot-util"]},"series-plot-util":{},"series-range":{requires:["series-cartesian"]},"series-spline":{requires:["series-line","series-curve-util"]},"series-spline-stacked":{requires:["series-stacked","series-spline"]},"series-stacked":{requires:["axis-stacked"]},"shim-plugin":{requires:["node-style","node-pluginhost"]},slider:{use:["slider-base","slider-value-range","clickable-rail","range-slider"]},"slider-base":{requires:["widget","dd-constrain","event-key"],skinnable:!0},"slider-value-range":{requires:["slider-base"]},sortable:{requires:["dd-delegate","dd-drop-plugin","dd-proxy"]},"sortable-scroll":{requires:["dd-scroll","sortable"]},stylesheet:{requires:["yui-base"]},substitute:{optional:["dump"],requires:["yui-base"]},swf:{requires:["event-custom","node","swfdetect","escape"]},swfdetect:{requires:["yui-base"]},tabview:{requires:["widget","widget-parent","widget-child","tabview-base","node-pluginhost","node-focusmanager"],skinnable:!0},"tabview-base":{requires:["node-event-delegate","classnamemanager"]},"tabview-plugin":{requires:["tabview-base"]},template:{use:["template-base","template-micro"]},"template-base":{requires:["yui-base"]},"template-micro":{requires:["escape"]},test:{requires:["event-simulate","event-custom","json-stringify"]},"test-console":{requires:["console-filters","test","array-extras"],skinnable:!0},text:{use:["text-accentfold","text-wordbreak"]},"text-accentfold":{requires:["array-extras","text-data-accentfold"]},"text-data-accentfold":{requires:["yui-base"]},"text-data-wordbreak":{requires:["yui-base"]},"text-wordbreak":{requires:["array-extras","text-data-wordbreak"]},timers:{requires:["yui-base"]},transition:{requires:["node-style"]},"transition-timer":{condition:{name:"transition-timer",test:function(e){var t=e.config.doc,n=t?t.documentElement:null,r=!0;return n&&n.style&&(r=!("MozTransition"in n.style||"WebkitTransition"in n.style||"transition"in n.style)),r},trigger:"transition"},requires:["transition"]},tree:{requires:["base-build","tree-node"]},"tree-labelable":{requires:["tree"]},"tree-lazy":{requires:["base-pluginhost","plugin","tree"]},"tree-node":{},"tree-openable":{requires:["tree"]},"tree-selectable":{requires:["tree"]},"tree-sortable":{requires:["tree"]},uploader:{requires:["uploader-html5","uploader-flash"]},"uploader-flash":{requires:["swfdetect","escape","widget","base","cssbutton","node","event-custom","uploader-queue"]},"uploader-html5":{requires:["widget","node-event-simulate","file-html5","uploader-queue"]},"uploader-queue":{requires:["base"]},view:{requires:["base-build","node-event-delegate"]},"view-node-map":{requires:["view"]},widget:{use:["widget-base","widget-htmlparser","widget-skin","widget-uievents"]},"widget-anim":{requires:["anim-base","plugin","widget"]},"widget-autohide":{requires:["base-build","event-key","event-outside","widget"]},"widget-base":{requires:["attribute","base-base","base-pluginhost","classnamemanager","event-focus","node-base","node-style"],skinnable:!0},"widget-base-ie":{condition:{name:"widget-base-ie",trigger:"widget-base",ua:"ie"},requires:["widget-base"]},"widget-buttons":{requires:["button-plugin","cssbutton","widget-stdmod"]},"widget-child":{requires:["base-build","widget"]},"widget-htmlparser":{requires:["widget-base"]},"widget-modality":{requires:["base-build","event-outside","widget"],skinnable:!0},"widget-parent":{requires:["arraylist","base-build","widget"]},"widget-position":{requires:["base-build","node-screen","widget"]},"widget-position-align":{requires:["widget-position"]},"widget-position-constrain":{requires:["widget-position"]},"widget-skin":{requires:["widget-base"]},"widget-stack":{requires:["base-build","widget"],skinnable:!0},"widget-stdmod":{requires:["base-build","widget"]},"widget-uievents":{requires:["node-event-delegate","widget-base"]},yql:{requires:["oop"]},"yql-jsonp":{condition:{name:"yql-jsonp",test:function(e){return!e.UA.nodejs&&!e.UA.winjs},trigger:"yql"},requires:["yql","jsonp","jsonp-url"]},"yql-nodejs":{condition:{name:"yql-nodejs",trigger:"yql",ua:"nodejs"},requires:["yql"]},"yql-winjs":{condition:{name:"yql-winjs",trigger:"yql",ua:"winjs"},requires:["yql"]},yui:{},"yui-base":{},"yui-later":{requires:["yui-base"]},"yui-log":{requires:["yui-base"]},"yui-throttle":{requires:["yui-base"]}}),YUI.Env[e.version].md5="2fd2be6b12ee9f999b4367499ae61aae"},"3.18.1",{requires:["loader-base"]}),YUI.add("loader-pathogen-combohandler",function(e,t){var n=";",r="+",i=",",s=/-(min|debug).js/,o=/\.(?:js|css)$/,u,a=/^(?:yui:)?gallery-([^\/]+)/,f={js:!0,css:!0},l;e.mix(e.Loader.prototype,{_pathogenEncodeComboSources:function(t){var n=this.combine,r,i,s,o,u,a,c,h;if(!n)for(c in this.groups)if(this.groups.hasOwnProperty(c)&&!n&&c.combine){n=c.combine;break}e.config.customComboBase&&(l=e.config.customComboBase);if(l&&n){i=this.maxURLLength;for(h in f){if(!f.hasOwnProperty(h))continue;u=h,a=h+"Mods",t[u]=r=t[u]||[],t[a]=s=t[a]||[],o=this._customResolve(s,h),t[h]=t[h].concat(o)}}return t},_customResolve:function(t,n){var r=this._aggregateGroups(t),i=this._sortAggregatedGroups(r),o=[],u,a,f,c;a||(f=s.exec(e.config.loaderPath),a=f&&f[1]||"raw",a=n==="css"&& a==="debug"?"raw":"min",u=a==="min"?"":"."+a,u=u+"."+n),c=this._buildCombo(i,l,u);while(c)o.push(c),c=this._buildCombo(i,l,u);return o},_aggregateGroups:function(e){var t={},n,i,s,f,l,c,h;for(h=0,c=e.length;ht.key?1:0});for(i=0,r=t.length;iSee filter property * @param {Object} config.filters Per-component filter specification. If specified for a given component, this overrides the filter config. * @param {Boolean} config.combine Use a combo service to reduce the number of http connections required to load your dependencies * @param {Boolean} [config.async=true] Fetch files in async * @param {Array} config.ignore: A list of modules that should never be dynamically loaded * @param {Array} config.force A list of modules that should always be loaded when required, even if already present on the page * @param {HTMLElement|String} config.insertBefore Node or id for a node that should be used as the insertion point for new nodes * @param {Object} config.jsAttributes Object literal containing attributes to add to script nodes * @param {Object} config.cssAttributes Object literal containing attributes to add to link nodes * @param {Number} config.timeout The number of milliseconds before a timeout occurs when dynamically loading nodes. If not set, there is no timeout * @param {Object} config.context Execution context for all callbacks * @param {Function} config.onSuccess Callback for the 'success' event * @param {Function} config.onFailure Callback for the 'failure' event * @param {Function} config.onTimeout Callback for the 'timeout' event * @param {Function} config.onProgress Callback executed each time a script or css file is loaded * @param {Object} config.modules A list of module definitions. See Loader.addModule for the supported module metadata * @param {Object} config.groups A list of group definitions. Each group can contain specific definitions for `base`, `comboBase`, `combine`, and accepts a list of `modules`. * @param {String} config.2in3 The version of the YUI 2 in 3 wrapper to use. The intrinsic support for YUI 2 modules in YUI 3 relies on versions of the YUI 2 components inside YUI 3 module wrappers. These wrappers change over time to accomodate the issues that arise from running YUI 2 in a YUI 3 sandbox. * @param {String} config.yui2 When using the 2in3 project, you can select the version of YUI 2 to use. Valid values are `2.2.2`, `2.3.1`, `2.4.1`, `2.5.2`, `2.6.0`, `2.7.0`, `2.8.0`, `2.8.1` and `2.9.0` [default] -- plus all versions of YUI 2 going forward. * @param {Function} config.doBeforeLoader An optional hook that allows for the patching of the loader instance. The `Y` instance is available as `this.context` and the only argument to the function is the Loader configuration object. */ Y.Loader = function(o) { var self = this; //Catch no config passed. o = o || {}; modulekey = META.md5; /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ // self._internalCallback = null; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ // self.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ // self.onFailure = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ // self.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ // self.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ self.context = Y; // Hook that allows the patching of loader if (o.doBeforeLoader) { o.doBeforeLoader.apply(self, arguments); } /** * Data that is passed to all callbacks * @property data */ // self.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ // self.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @deprecated , use cssAttributes or jsAttributes. */ // self.charset = null; /** * An object literal containing attributes to add to link nodes * @property cssAttributes * @type object */ // self.cssAttributes = null; /** * An object literal containing attributes to add to script nodes * @property jsAttributes * @type object */ // self.jsAttributes = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ self.base = Y.Env.meta.base + Y.Env.meta.root; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ self.comboBase = Y.Env.meta.comboBase; /* * Base path for language packs. */ // self.langBase = Y.Env.meta.langBase; // self.lang = ""; /** * If configured, the loader will attempt to use the combo * service for YUI resources and configured external resources. * @property combine * @type boolean * @default true if a base dir isn't in the config */ self.combine = o.base && (o.base.indexOf(self.comboBase.substr(0, 20)) > -1); /** * The default seperator to use between files in a combo URL * @property comboSep * @type {String} * @default Ampersand */ self.comboSep = '&'; /** * Max url length for combo urls. The default is 1024. This is the URL * limit for the Yahoo! hosted combo servers. If consuming * a different combo service that has a different URL limit * it is possible to override this default by supplying * the maxURLLength config option. The config option will * only take effect if lower than the default. * * @property maxURLLength * @type int */ self.maxURLLength = MAX_URL_LENGTH; /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ self.ignoreRegistered = o.ignoreRegistered; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ self.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, self value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ self.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ // self.ignore = null; /** * A list of modules that should always be loaded, even * if they have already been inserted into the page. * @property force * @type string[] */ // self.force = null; self.forceMap = {}; /** * Should we allow rollups * @property allowRollup * @type boolean * @default false */ self.allowRollup = false; /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: *
      *
      DEBUG
      *
      Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget
      *
      RAW
      *
      Selects the non-minified version of the library (e.g., event.js). *
      *
      * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * @property filter * @type string| {searchExp: string, replaceStr: string} */ // self.filter = null; /** * per-component filter specification. If specified for a given * component, this overrides the filter config. * @property filters * @type object */ self.filters = {}; /** * The list of requested modules * @property required * @type {string: boolean} */ self.required = {}; /** * If a module name is predefined when requested, it is checked againsts * the patterns provided in this property. If there is a match, the * module is added with the default configuration. * * At the moment only supporting module prefixes, but anticipate * supporting at least regular expressions. * @property patterns * @type Object */ // self.patterns = Y.merge(Y.Env.meta.patterns); self.patterns = {}; /** * Internal loader instance metadata. Use accessor `getModuleInfo()` instead. */ self.moduleInfo = {}; self.groups = Y.merge(Y.Env.meta.groups); /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * skin: { * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * @property skin * @type {Object} */ self.skin = Y.merge(Y.Env.meta.skin); /* * Map of conditional modules * @since 3.2.0 */ self.conditions = {}; // map of modules with a hash of modules that meet the requirement // self.provides = {}; self.config = o; self._internal = true; self._populateConditionsCache(); /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by any instance on the page * with the version number specified in the metadata. * @property loaded * @type {string: boolean} */ self.loaded = GLOBAL_LOADED[VERSION]; /** * Should Loader fetch scripts in `async`, defaults to `true` * @property async */ self.async = true; self._inspectPage(); self._internal = false; self._config(o); self.forceMap = (self.force) ? Y.Array.hash(self.force) : {}; self.testresults = null; if (Y.config.tests) { self.testresults = Y.config.tests; } /** * List of rollup files found in the library metadata * @property rollups */ // self.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ // self.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ self.sorted = []; /* * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ // self.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ self.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ self.inserted = {}; /** * List of skipped modules during insert() because the module * was not defined * @property skipped */ self.skipped = {}; // Y.on('yui:load', self.loadNext, self); self.tested = {}; /* * Cached sorted calculate results * @property results * @since 3.2.0 */ //self.results = {}; if (self.ignoreRegistered) { //Clear inpage already processed modules. self._resetModules(); } }; Y.Loader.prototype = { /** * Gets the module info from the local moduleInfo hash, or from the * default metadata and populate the local moduleInfo hash. * @method getModuleInfo * @param {string} name of the module * @public */ getModuleInfo: function(name) { var m = this.moduleInfo[name], rawMetaModules, globalRenderedMods, internal, v; if (m) { return m; } rawMetaModules = META.modules; globalRenderedMods = GLOBAL_ENV._renderedMods; internal = this._internal; /* The logic here is: - if the `moduleInfo[name]` is avilable, then short circuit - otherwise, if the module is in the globalCache (cross Y instance), then port it from the global registry into `moduleInfo[name]` - otherwise, if the module has raw metadata (from meta modules) then add it to the global registry and to `moduleInfo[name]` */ if (globalRenderedMods && globalRenderedMods.hasOwnProperty(name) && !this.ignoreRegistered) { this.moduleInfo[name] = Y.merge(globalRenderedMods[name]); } else { if (rawMetaModules.hasOwnProperty(name)) { this._internal = true; // making sure that modules from raw data are marked as internal v = this.addModule(rawMetaModules[name], name); // Inspect the page for the CSS module and mark it as loaded. if (v && v.type === CSS) { if (this.isCSSLoaded(v.name, true)) { this.loaded[v.name] = true; } } this._internal = internal; } } return this.moduleInfo[name]; }, /** * Expand the names that are aliases to other modules. * @method _expandAliases * @param {string[]} list a module name or a list of names to be expanded * @private * @return {array} */ _expandAliases: function(list) { var expanded = [], aliases = YUI.Env.aliases, i, name; list = Y.Array(list); for (i = 0; i < list.length; i += 1) { name = list[i]; expanded.push.apply(expanded, aliases[name] ? aliases[name] : [name]); } return expanded; }, /** * Populate the conditions cache from raw modules, this is necessary * because no other module will require a conditional module, instead * the condition has to be executed and then the module is analyzed * to be included in the final requirement list. Without this cache * conditional modules will be simply ignored. * @method _populateConditionsCache * @private */ _populateConditionsCache: function() { var rawMetaModules = META.modules, cache = GLOBAL_ENV._conditions, i, j, t, trigger; // if we have conditions in cache and cache is enabled // we should port them to this loader instance if (cache && !this.ignoreRegistered) { for (i in cache) { if (cache.hasOwnProperty(i)) { this.conditions[i] = Y.merge(cache[i]); } } } else { for (i in rawMetaModules) { if (rawMetaModules.hasOwnProperty(i) && rawMetaModules[i].condition) { t = this._expandAliases(rawMetaModules[i].condition.trigger); for (j = 0; j < t.length; j += 1) { trigger = t[j]; this.conditions[trigger] = this.conditions[trigger] || {}; this.conditions[trigger][rawMetaModules[i].name || i] = rawMetaModules[i].condition; } } } GLOBAL_ENV._conditions = this.conditions; } }, /** * Reset modules in the module cache to a pre-processed state so additional * computations with a different skin or language will work as expected. * @method _resetModules * @private */ _resetModules: function() { var self = this, i, o, mod, name, details; for (i in self.moduleInfo) { if (self.moduleInfo.hasOwnProperty(i) && self.moduleInfo[i]) { mod = self.moduleInfo[i]; name = mod.name; details = (YUI.Env.mods[name] ? YUI.Env.mods[name].details : null); if (details) { self.moduleInfo[name]._reset = true; self.moduleInfo[name].requires = details.requires || []; self.moduleInfo[name].optional = details.optional || []; self.moduleInfo[name].supersedes = details.supercedes || []; } if (mod.defaults) { for (o in mod.defaults) { if (mod.defaults.hasOwnProperty(o)) { if (mod[o]) { mod[o] = mod.defaults[o]; } } } } mod.langCache = undefined; mod.skinCache = undefined; if (mod.skinnable) { self._addSkin(self.skin.defaultSkin, mod.name); } } } }, /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** * Default filters for raw and debug * @property FILTER_DEFS * @type Object * @final * @protected */ FILTER_DEFS: { RAW: { 'searchExp': '-min\\.js', 'replaceStr': '.js' }, DEBUG: { 'searchExp': '-min\\.js', 'replaceStr': '-debug.js' }, COVERAGE: { 'searchExp': '-min\\.js', 'replaceStr': '-coverage.js' } }, /* * Check the pages meta-data and cache the result. * @method _inspectPage * @private */ _inspectPage: function() { var self = this, v, m, req, mr, i; for (i in ON_PAGE) { if (ON_PAGE.hasOwnProperty(i)) { v = ON_PAGE[i]; if (v.details) { m = self.getModuleInfo(v.name); req = v.details.requires; mr = m && m.requires; if (m) { if (!m._inspected && req && mr.length !== req.length) { // console.log('deleting ' + m.name); delete m.expanded; } } else { m = self.addModule(v.details, i); } m._inspected = true; } } } }, /* * returns true if b is not loaded, and is required directly or by means of modules it supersedes. * @private * @method _requires * @param {String} mod1 The first module to compare * @param {String} mod2 The second module to compare */ _requires: function(mod1, mod2) { var i, rm, after_map, s, m = this.getModuleInfo(mod1), other = this.getModuleInfo(mod2); if (!m || !other) { return false; } rm = m.expanded_map; after_map = m.after_map; // check if this module should be sorted after the other // do this first to short circut circular deps if (after_map && (mod2 in after_map)) { return true; } after_map = other.after_map; // and vis-versa if (after_map && (mod1 in after_map)) { return false; } // check if this module requires one the other supersedes s = other.supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod1, s[i])) { return true; } } } s = m.supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod2, s[i])) { return false; } } } // check if this module requires the other directly // if (r && yArray.indexOf(r, mod2) > -1) { if (rm && (mod2 in rm)) { return true; } // external css files should be sorted below yui css if (m.ext && m.type === CSS && !other.ext && other.type === CSS) { return true; } return false; }, /** * Apply a new config to the Loader instance * @method _config * @private * @param {Object} o The new configuration */ _config: function(o) { var i, j, val, a, f, group, groupName, self = this, mods = [], mod, modInfo; // apply config values if (o) { for (i in o) { if (o.hasOwnProperty(i)) { val = o[i]; //TODO This should be a case if (i === 'require') { self.require(val); } else if (i === 'skin') { //If the config.skin is a string, format to the expected object if (typeof val === 'string') { self.skin.defaultSkin = o.skin; val = { defaultSkin: val }; } Y.mix(self.skin, val, true); } else if (i === 'groups') { for (j in val) { if (val.hasOwnProperty(j)) { groupName = j; group = val[j]; self.addGroup(group, groupName); if (group.aliases) { for (a in group.aliases) { if (group.aliases.hasOwnProperty(a)) { self.addAlias(group.aliases[a], a); } } } } } } else if (i === 'modules') { // add a hash of module definitions for (j in val) { if (val.hasOwnProperty(j)) { self.addModule(val[j], j); } } } else if (i === 'aliases') { for (j in val) { if (val.hasOwnProperty(j)) { self.addAlias(val[j], j); } } } else if (i === 'gallery') { if (this.groups.gallery.update) { this.groups.gallery.update(val, o); } } else if (i === 'yui2' || i === '2in3') { if (this.groups.yui2.update) { this.groups.yui2.update(o['2in3'], o.yui2, o); } } else { self[i] = val; } } } } // fix filter f = self.filter; if (L.isString(f)) { f = f.toUpperCase(); self.filterName = f; self.filter = self.FILTER_DEFS[f]; if (f === 'DEBUG') { self.require('yui-log', 'dump'); } } if (self.filterName && self.coverage) { if (self.filterName === 'COVERAGE' && L.isArray(self.coverage) && self.coverage.length) { for (i = 0; i < self.coverage.length; i++) { mod = self.coverage[i]; modInfo = self.getModuleInfo(mod); if (modInfo && modInfo.use) { mods = mods.concat(modInfo.use); } else { mods.push(mod); } } self.filters = self.filters || {}; Y.Array.each(mods, function(mod) { self.filters[mod] = self.FILTER_DEFS.COVERAGE; }); self.filterName = 'RAW'; self.filter = self.FILTER_DEFS[self.filterName]; } } }, /** * Returns the skin module name for the specified skin name. If a * module name is supplied, the returned skin module name is * specific to the module passed in. * @method formatSkin * @param {string} skin the name of the skin. * @param {string} mod optional: the name of a module to skin. * @return {string} the full skin module name. */ formatSkin: function(skin, mod) { var s = SKIN_PREFIX + skin; if (mod) { s = s + '-' + mod; } return s; }, /** * Adds the skin def to the module info * @method _addSkin * @param {string} skin the name of the skin. * @param {string} mod the name of the module. * @param {string} parent parent module if this is a skin of a * submodule or plugin. * @return {string} the module name for the skin. * @private */ _addSkin: function(skin, mod, parent) { var pkg, name, nmod, sinf = this.skin, mdef = mod && this.getModuleInfo(mod), ext = mdef && mdef.ext; // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!this.getModuleInfo(name)) { pkg = mdef.pkg || mod; nmod = { skin: true, name: name, group: mdef.group, type: 'css', after: sinf.after, path: (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', ext: ext }; if (mdef.base) { nmod.base = mdef.base; } if (mdef.configFn) { nmod.configFn = mdef.configFn; } this.addModule(nmod, name); } } return name; }, /** * Adds an alias module to the system * @method addAlias * @param {Array} use An array of modules that makes up this alias * @param {String} name The name of the alias * @example * var loader = new Y.Loader({}); * loader.addAlias([ 'node', 'yql' ], 'davglass'); * loader.require(['davglass']); * var out = loader.resolve(true); * * //out.js will contain Node and YQL modules */ addAlias: function(use, name) { YUI.Env.aliases[name] = use; this.addModule({ name: name, use: use }); }, /** * Add a new module group * @method addGroup * @param {Object} config An object containing the group configuration data * @param {String} config.name required, the group name * @param {String} config.base The base directory for this module group * @param {String} config.root The root path to add to each combo resource path * @param {Boolean} config.combine Should the request be combined * @param {String} config.comboBase Combo service base path * @param {Object} config.modules The group of modules * @param {String} name the group name. * @example * var loader = new Y.Loader({}); * loader.addGroup({ * name: 'davglass', * combine: true, * comboBase: '/combo?', * root: '', * modules: { * //Module List here * } * }, 'davglass'); */ addGroup: function(o, name) { var mods = o.modules, self = this, defaultBase = o.defaultBase || Y.config.defaultBase, i, v; name = name || o.name; o.name = name; self.groups[name] = o; if (!o.base && defaultBase && o.root) { o.base = defaultBase + o.root; } if (o.patterns) { for (i in o.patterns) { if (o.patterns.hasOwnProperty(i)) { o.patterns[i].group = name; self.patterns[i] = o.patterns[i]; } } } if (mods) { for (i in mods) { if (mods.hasOwnProperty(i)) { v = mods[i]; if (typeof v === 'string') { v = { name: i, fullpath: v }; } v.group = name; self.addModule(v, i); } } } }, /** * Add a new module to the component metadata. * @method addModule * @param {Object} config An object containing the module data. * @param {String} config.name Required, the component name * @param {String} config.type Required, the component type (js or css) * @param {String} config.path Required, the path to the script from `base` * @param {Array} config.requires Array of modules required by this component * @param {Array} [config.optional] Array of optional modules for this component * @param {Array} [config.supersedes] Array of the modules this component replaces * @param {Array} [config.after] Array of modules the components which, if present, should be sorted above this one * @param {Object} [config.after_map] Faster alternative to 'after' -- supply a hash instead of an array * @param {Number} [config.rollup] The number of superseded modules required for automatic rollup * @param {String} [config.fullpath] If `fullpath` is specified, this is used instead of the configured `base + path` * @param {Boolean} [config.skinnable] Flag to determine if skin assets should automatically be pulled in * @param {Object} [config.submodules] Hash of submodules * @param {String} [config.group] The group the module belongs to -- this is set automatically when it is added as part of a group configuration. * @param {Array} [config.lang] Array of BCP 47 language tags of languages for which this module has localized resource bundles, e.g., `["en-GB", "zh-Hans-CN"]` * @param {Object} [config.condition] Specifies that the module should be loaded automatically if a condition is met. This is an object with up to four fields: * @param {String} [config.condition.trigger] The name of a module that can trigger the auto-load * @param {Function} [config.condition.test] A function that returns true when the module is to be loaded. * @param {String} [config.condition.ua] The UA name of Y.UA object that returns true when the module is to be loaded. e.g., `"ie"`, `"nodejs"`. * @param {String} [config.condition.when] Specifies the load order of the conditional module * with regard to the position of the trigger module. * This should be one of three values: `before`, `after`, or `instead`. The default is `after`. * @param {Object} [config.testresults] A hash of test results from `Y.Features.all()` * @param {Function} [config.configFn] A function to exectute when configuring this module * @param {Object} config.configFn.mod The module config, modifying this object will modify it's config. Returning false will delete the module's config. * @param {String[]} [config.optionalRequires] List of dependencies that may optionally be loaded by this loader. This is targeted mostly at polyfills, since they should not be in the list of requires because polyfills are assumed to be available in the global scope. * @param {Function} [config.test] Test to be called when this module is added as an optional dependency of another module. If the test function returns `false`, the module will be ignored and will not be attached to this YUI instance. * @param {String} [name] The module name, required if not in the module data. * @return {Object} the module definition or null if the object passed in did not provide all required attributes. */ addModule: function(o, name) { name = name || o.name; if (typeof o === 'string') { o = { name: name, fullpath: o }; } var subs, i, l, t, sup, s, smod, plugins, plug, j, langs, packName, supName, flatSup, flatLang, lang, ret, overrides, skinname, when, g, p, modInfo = this.moduleInfo[name], conditions = this.conditions, trigger; //Only merge this data if the temp flag is set //from an earlier pass from a pattern or else //an override module (YUI_config) can not be used to //replace a default module. if (modInfo && modInfo.temp) { //This catches temp modules loaded via a pattern // The module will be added twice, once from the pattern and // Once from the actual add call, this ensures that properties // that were added to the module the first time around (group: gallery) // are also added the second time around too. o = Y.merge(modInfo, o); } o.name = name; if (!o || !o.name) { return null; } if (!o.type) { //Always assume it's javascript unless the CSS pattern is matched. o.type = JS; p = o.path || o.fullpath; if (p && this.REGEX_CSS.test(p)) { o.type = CSS; } } if (!o.path && !o.fullpath) { o.path = _path(name, name, o.type); } o.supersedes = o.supersedes || o.use; o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; // Handle submodule logic subs = o.submodules; this.moduleInfo[name] = o; o.requires = o.requires || []; /* Only allowing the cascade of requires information, since optional and supersedes are far more fine grained than a blanket requires is. */ if (this.requires) { for (i = 0; i < this.requires.length; i++) { o.requires.push(this.requires[i]); } } if (o.group && this.groups && this.groups[o.group]) { g = this.groups[o.group]; if (g.requires) { for (i = 0; i < g.requires.length; i++) { o.requires.push(g.requires[i]); } } } if (!o.defaults) { o.defaults = { requires: o.requires ? [].concat(o.requires) : null, supersedes: o.supersedes ? [].concat(o.supersedes) : null, optional: o.optional ? [].concat(o.optional) : null }; } if (o.skinnable && o.ext && o.temp) { skinname = this._addSkin(this.skin.defaultSkin, name); o.requires.unshift(skinname); } if (o.requires.length) { o.requires = this.filterRequires(o.requires) || []; } if (!o.langPack && o.lang) { langs = yArray(o.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); smod = this.getModuleInfo(packName); if (!smod) { smod = this._addLangPack(lang, o, packName); } } } if (subs) { sup = o.supersedes || []; l = 0; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; s.path = s.path || _path(name, i, o.type); s.pkg = name; s.group = o.group; if (s.supersedes) { sup = sup.concat(s.supersedes); } smod = this.addModule(s, i); sup.push(i); if (smod.skinnable) { o.skinnable = true; overrides = this.skin.overrides; if (overrides && overrides[i]) { for (j = 0; j < overrides[i].length; j++) { skinname = this._addSkin(overrides[i][j], i, name); sup.push(skinname); } } skinname = this._addSkin(this.skin.defaultSkin, i, name); sup.push(skinname); } // looks like we are expected to work out the metadata // for the parent module language packs from what is // specified in the child modules. if (s.lang && s.lang.length) { langs = yArray(s.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); supName = this.getLangPackName(lang, i); smod = this.getModuleInfo(packName); if (!smod) { smod = this._addLangPack(lang, o, packName); } flatSup = flatSup || yArray.hash(smod.supersedes); if (!(supName in flatSup)) { smod.supersedes.push(supName); } o.lang = o.lang || []; flatLang = flatLang || yArray.hash(o.lang); if (!(lang in flatLang)) { o.lang.push(lang); } // Add rollup file, need to add to supersedes list too // default packages packName = this.getLangPackName(ROOT_LANG, name); supName = this.getLangPackName(ROOT_LANG, i); smod = this.getModuleInfo(packName); if (!smod) { smod = this._addLangPack(lang, o, packName); } if (!(supName in flatSup)) { smod.supersedes.push(supName); } // Add rollup file, need to add to supersedes list too } } l++; } } //o.supersedes = YObject.keys(yArray.hash(sup)); o.supersedes = yArray.dedupe(sup); if (this.allowRollup) { o.rollup = (l < 4) ? l : Math.min(l - 1, 4); } } plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { plug = plugins[i]; plug.pkg = name; plug.path = plug.path || _path(name, i, o.type); plug.requires = plug.requires || []; plug.group = o.group; this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } if (o.condition) { t = this._expandAliases(o.condition.trigger); for (i = 0; i < t.length; i++) { trigger = t[i]; when = o.condition.when; conditions[trigger] = conditions[trigger] || {}; conditions[trigger][name] = o.condition; // the 'when' attribute can be 'before', 'after', or 'instead' // the default is after. if (when && when !== 'after') { if (when === 'instead') { // replace the trigger o.supersedes = o.supersedes || []; o.supersedes.push(trigger); } // before the trigger // the trigger requires the conditional mod, // so it should appear before the conditional // mod if we do not intersede. } else { // after the trigger o.after = o.after || []; o.after.push(trigger); } } } if (o.supersedes) { o.supersedes = this.filterRequires(o.supersedes); } if (o.after) { o.after = this.filterRequires(o.after); o.after_map = yArray.hash(o.after); } // this.dirty = true; if (o.configFn) { ret = o.configFn(o); if (ret === false) { delete this.moduleInfo[name]; delete GLOBAL_ENV._renderedMods[name]; o = null; } } //Add to global cache if (o) { if (!GLOBAL_ENV._renderedMods) { GLOBAL_ENV._renderedMods = {}; } GLOBAL_ENV._renderedMods[name] = Y.mix(GLOBAL_ENV._renderedMods[name] || {}, o); GLOBAL_ENV._conditions = conditions; } return o; }, /** * Add a requirement for one or more module * @method require * @param {string[] | string*} what the modules to load. */ require: function(what) { var a = (typeof what === 'string') ? yArray(arguments) : what; this.dirty = true; this.required = Y.merge(this.required, yArray.hash(this.filterRequires(a))); this._explodeRollups(); }, /** * Grab all the items that were asked for, check to see if the Loader * meta-data contains a "use" array. If it doesm remove the asked item and replace it with * the content of the "use". * This will make asking for: "dd" * Actually ask for: "dd-ddm-base,dd-ddm,dd-ddm-drop,dd-drag,dd-proxy,dd-constrain,dd-drop,dd-scroll,dd-drop-plugin" * @private * @method _explodeRollups */ _explodeRollups: function() { var self = this, m, m2, i, a, v, len, len2, r = self.required; if (!self.allowRollup) { for (i in r) { if (r.hasOwnProperty(i)) { m = self.getModule(i); if (m && m.use) { len = m.use.length; for (a = 0; a < len; a++) { m2 = self.getModule(m.use[a]); if (m2 && m2.use) { len2 = m2.use.length; for (v = 0; v < len2; v++) { r[m2.use[v]] = true; } } else { r[m.use[a]] = true; } } } } } self.required = r; } }, /** * Explodes the required array to remove aliases and replace them with real modules * @method filterRequires * @param {Array} r The original requires array * @return {Array} The new array of exploded requirements */ filterRequires: function(r) { if (r) { if (!Y.Lang.isArray(r)) { r = [r]; } r = Y.Array(r); var c = [], i, mod, o, m; for (i = 0; i < r.length; i++) { mod = this.getModule(r[i]); if (mod && mod.use) { for (o = 0; o < mod.use.length; o++) { //Must walk the other modules in case a module is a rollup of rollups (datatype) m = this.getModule(mod.use[o]); if (m && m.use && (m.name !== mod.name)) { c = Y.Array.dedupe([].concat(c, this.filterRequires(m.use))); } else { c.push(mod.use[o]); } } } else { c.push(r[i]); } } r = c; } return r; }, /** Returns `true` if the module can be attached to the YUI instance. Runs the module's test if there is one and caches its result. @method _canBeAttached @param {String} module Name of the module to check. @return {Boolean} Result of the module's test if it has one, or `true`. **/ _canBeAttached: function (m) { m = this.getModule(m); if (m && m.test) { if (!m.hasOwnProperty('_testResult')) { m._testResult = m.test(Y); } return m._testResult; } // return `true` for modules not registered as Loader will know what // to do with them later on return true; }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param {object} mod The module definition from moduleInfo. * @return {array} the expanded requirement list. */ getRequires: function(mod) { if (!mod) { //console.log('returning no reqs for ' + mod.name); return NO_REQUIREMENTS; } if (mod._parsed) { //console.log('returning requires for ' + mod.name, mod.requires); return mod.expanded || NO_REQUIREMENTS; } //TODO add modue cache here out of scope.. var i, m, j, length, add, packName, lang, testresults = this.testresults, name = mod.name, cond, adddef = ON_PAGE[name] && ON_PAGE[name].details, optReqs = mod.optionalRequires, d, go, def, r, old_mod, o, skinmod, skindef, skinpar, skinname, intl = mod.lang || mod.intl, ftests = Y.Features && Y.Features.tests.load, hash, reparse; // console.log(name); // pattern match leaves module stub that needs to be filled out if (mod.temp && adddef) { old_mod = mod; mod = this.addModule(adddef, name); mod.group = old_mod.group; mod.pkg = old_mod.pkg; delete mod.expanded; } // console.log('cache: ' + mod.langCache + ' == ' + this.lang); //If a skin or a lang is different, reparse.. reparse = !((!this.lang || mod.langCache === this.lang) && (mod.skinCache === this.skin.defaultSkin)); if (mod.expanded && !reparse) { return mod.expanded; } // Optional dependencies are dependencies that may or may not be // available. // This feature was designed specifically to be used when transpiling // ES6 modules, in order to use polyfills and regular scripts that define // global variables without having to import them since they should be // available in the global scope. if (optReqs) { for (i = 0, length = optReqs.length; i < length; i++) { if (this._canBeAttached(optReqs[i])) { mod.requires.push(optReqs[i]); } } } d = []; hash = {}; r = this.filterRequires(mod.requires); if (mod.lang) { //If a module has a lang attribute, auto add the intl requirement. d.unshift('intl'); r.unshift('intl'); intl = true; } o = this.filterRequires(mod.optional); mod._parsed = true; mod.langCache = this.lang; mod.skinCache = this.skin.defaultSkin; for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { d.push(r[i]); hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } // get the requirements from superseded modules, if any r = this.filterRequires(mod.supersedes); if (r) { for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { // if this module has submodules, the requirements list is // expanded to include the submodules. This is so we can // prevent dups when a submodule is already loaded and the // parent is requested. if (mod.submodules) { d.push(r[i]); } hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } if (o && this.loadOptional) { for (i = 0; i < o.length; i++) { if (!hash[o[i]]) { d.push(o[i]); hash[o[i]] = true; m = this.getModuleInfo(o[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } cond = this.conditions[name]; if (cond) { //Set the module to not parsed since we have conditionals and this could change the dependency tree. mod._parsed = false; if (testresults && ftests) { oeach(testresults, function(result, id) { var condmod = ftests[id].name; if (!hash[condmod] && ftests[id].trigger === name) { if (result && ftests[id]) { hash[condmod] = true; d.push(condmod); } } }); } else { for (i in cond) { if (cond.hasOwnProperty(i)) { if (!hash[i]) { def = cond[i]; //first see if they've specfied a ua check //then see if they've got a test fn & if it returns true //otherwise just having a condition block is enough go = def && ((!def.ua && !def.test) || (def.ua && Y.UA[def.ua]) || (def.test && def.test(Y, r))); if (go) { hash[i] = true; d.push(i); m = this.getModule(i); if (m) { add = this.getRequires(m); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } } } } // Create skin modules if (mod.skinnable) { skindef = this.skin.overrides; for (i in YUI.Env.aliases) { if (YUI.Env.aliases.hasOwnProperty(i)) { if (Y.Array.indexOf(YUI.Env.aliases[i], name) > -1) { skinpar = i; } } } if (skindef && (skindef[name] || (skinpar && skindef[skinpar]))) { skinname = name; if (skindef[skinpar]) { skinname = skinpar; } for (i = 0; i < skindef[skinname].length; i++) { skinmod = this._addSkin(skindef[skinname][i], name); if (!this.isCSSLoaded(skinmod, this._boot)) { d.push(skinmod); } } } else { skinmod = this._addSkin(this.skin.defaultSkin, name); if (!this.isCSSLoaded(skinmod, this._boot)) { d.push(skinmod); } } } mod._parsed = false; if (intl) { if (mod.lang && !mod.langPack && Y.Intl) { lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang); packName = this.getLangPackName(lang, name); if (packName) { d.unshift(packName); } } d.unshift(INTL); } mod.expanded_map = yArray.hash(d); mod.expanded = YObject.keys(mod.expanded_map); return mod.expanded; }, /** * Check to see if named css module is already loaded on the page * @method isCSSLoaded * @param {String} name The name of the css file * @param {Boolean} skip To skip the short-circuit for ignoreRegister * @return Boolean */ isCSSLoaded: function(name, skip) { //TODO - Make this call a batching call with name being an array if (!name || !YUI.Env.cssStampEl || (!skip && this.ignoreRegistered)) { return false; } var el = YUI.Env.cssStampEl, ret = false, mod = YUI.Env._cssLoaded[name], style = el.currentStyle; //IE if (mod !== undefined) { return mod; } //Add the classname to the element el.className = name; if (!style) { style = Y.config.doc.defaultView.getComputedStyle(el, null); } if (style && style.display === 'none') { ret = true; } el.className = ''; //Reset the classname to '' YUI.Env._cssLoaded[name] = ret; return ret; }, /** * Returns a hash of module names the supplied module satisfies. * @method getProvides * @param {string} name The name of the module. * @return {object} what this module provides. */ getProvides: function(name) { var m = this.getModule(name), o, s; // supmap = this.provides; if (!m) { return NOT_FOUND; } if (m && !m.provides) { o = {}; s = m.supersedes; if (s) { yArray.each(s, function(v) { Y.mix(o, this.getProvides(v)); }, this); } o[name] = true; m.provides = o; } return m.provides; }, /** * Calculates the dependency tree, the result is stored in the sorted * property. * @method calculate * @param {object} o optional options object. * @param {string} type optional argument to prune modules. */ calculate: function(o, type) { if (o || type || this.dirty) { if (o) { this._config(o); } if (!this._init) { this._setup(); } this._explode(); if (this.allowRollup) { this._rollup(); } else { this._explodeRollups(); } this._reduce(); this._sort(); } }, /** * Creates a "psuedo" package for languages provided in the lang array * @method _addLangPack * @private * @param {String} lang The language to create * @param {Object} m The module definition to create the language pack around * @param {String} packName The name of the package (e.g: lang/datatype-date-en-US) * @return {Object} The module definition */ _addLangPack: function(lang, m, packName) { var name = m.name, packPath, conf, existing = this.getModuleInfo(packName); if (!existing) { packPath = _path((m.pkg || name), packName, JS, true); conf = { path: packPath, intl: true, langPack: true, ext: m.ext, group: m.group, supersedes: [] }; if (m.root) { conf.root = m.root; } if (m.base) { conf.base = m.base; } if (m.configFn) { conf.configFn = m.configFn; } this.addModule(conf, packName); if (lang) { Y.Env.lang = Y.Env.lang || {}; Y.Env.lang[lang] = Y.Env.lang[lang] || {}; Y.Env.lang[lang][name] = true; } } return this.getModuleInfo(packName); }, /** * Investigates the current YUI configuration on the page. By default, * modules already detected will not be loaded again unless a force * option is encountered. Called by calculate() * @method _setup * @private */ _setup: function() { var info = this.moduleInfo, name, i, j, m, l, packName; for (name in info) { if (info.hasOwnProperty(name)) { m = info[name]; if (m) { // remove dups //m.requires = YObject.keys(yArray.hash(m.requires)); m.requires = yArray.dedupe(m.requires); // Create lang pack modules //if (m.lang && m.lang.length) { if (m.lang) { // Setup root package if the module has lang defined, // it needs to provide a root language pack packName = this.getLangPackName(ROOT_LANG, name); this._addLangPack(null, m, packName); } } } } //l = Y.merge(this.inserted); l = {}; // available modules if (!this.ignoreRegistered) { Y.mix(l, GLOBAL_ENV.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { Y.mix(l, yArray.hash(this.ignore)); } // expand the list to include superseded modules for (j in l) { if (l.hasOwnProperty(j)) { Y.mix(l, this.getProvides(j)); } } // remove modules on the force list from the loaded list if (this.force) { for (i = 0; i < this.force.length; i++) { if (this.force[i] in l) { delete l[this.force[i]]; } } } Y.mix(this.loaded, l); this._init = true; }, /** * Builds a module name for a language pack * @method getLangPackName * @param {string} lang the language code. * @param {string} mname the module to build it for. * @return {string} the language pack module name. */ getLangPackName: function(lang, mname) { return ('lang/' + mname + ((lang) ? '_' + lang : '')); }, /** * Inspects the required modules list looking for additional * dependencies. Expands the required list to include all * required modules. Called by calculate() * @method _explode * @private */ _explode: function() { //TODO Move done out of scope var r = this.required, m, reqs, done = {}, self = this, name, expound; // the setup phase is over, all modules have been created self.dirty = false; self._explodeRollups(); r = self.required; for (name in r) { if (r.hasOwnProperty(name)) { if (!done[name]) { done[name] = true; m = self.getModule(name); if (m) { expound = m.expound; if (expound) { r[expound] = self.getModule(expound); reqs = self.getRequires(r[expound]); Y.mix(r, yArray.hash(reqs)); } reqs = self.getRequires(m); Y.mix(r, yArray.hash(reqs)); } } } } }, /** * The default method used to test a module against a pattern * @method _patternTest * @private * @param {String} mname The module being tested * @param {String} pname The pattern to match */ _patternTest: function(mname, pname) { return (mname.indexOf(pname) > -1); }, /** * Get's the loader meta data for the requested module * @method getModule * @param {String} mname The module name to get * @return {Object} The module metadata */ getModule: function(mname) { //TODO: Remove name check - it's a quick hack to fix pattern WIP if (!mname) { return null; } var p, found, pname, m = this.getModuleInfo(mname), patterns = this.patterns; // check the patterns library to see if we should automatically add // the module with defaults if (!m || (m && m.ext)) { for (pname in patterns) { if (patterns.hasOwnProperty(pname)) { p = patterns[pname]; //There is no test method, create a default one that tests // the pattern against the mod name if (!p.test) { p.test = this._patternTest; } if (p.test(mname, pname)) { // use the metadata supplied for the pattern // as the module definition. found = p; break; } } } } if (!m) { if (found) { if (p.action) { p.action.call(this, mname, pname); } else { // ext true or false? m = this.addModule(Y.merge(found, { test: void 0, temp: true }), mname); if (m && found.configFn) { m.configFn = found.configFn; } } } } else { if (found && m && found.configFn && !m.configFn) { m.configFn = found.configFn; m.configFn(m); } } return m; }, // impl in rollup submodule _rollup: function() { }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @return {object} the reduced dependency hash. * @private */ _reduce: function(r) { r = r || this.required; var i, j, s, m, type = this.loadType, ignore = this.ignore ? yArray.hash(this.ignore) : false; for (i in r) { if (r.hasOwnProperty(i)) { m = this.getModule(i); // remove if already loaded if (((this.loaded[i] || ON_PAGE[i]) && !this.forceMap[i] && !this.ignoreRegistered) || (type && m && m.type !== type)) { delete r[i]; } if (ignore && ignore[i]) { delete r[i]; } // remove anything this module supersedes s = m && m.supersedes; if (s) { for (j = 0; j < s.length; j++) { if (s[j] in r) { delete r[s[j]]; } } } } } return r; }, /** * Handles the queue when a module has been loaded for all cases * @method _finish * @private * @param {String} msg The message from Loader * @param {Boolean} success A boolean denoting success or failure */ _finish: function(msg, success) { _queue.running = false; var onEnd = this.onEnd; if (onEnd) { onEnd.call(this.context, { msg: msg, data: this.data, success: success }); } this._continue(); }, /** * The default Loader onSuccess handler, calls this.onSuccess with a payload * @method _onSuccess * @private */ _onSuccess: function() { var self = this, skipped = Y.merge(self.skipped), fn, failed = [], rreg = self.requireRegistration, success, msg, i, mod; for (i in skipped) { if (skipped.hasOwnProperty(i)) { delete self.inserted[i]; } } self.skipped = {}; for (i in self.inserted) { if (self.inserted.hasOwnProperty(i)) { mod = self.getModule(i); if (mod && rreg && mod.type === JS && !(i in YUI.Env.mods)) { failed.push(i); } else { Y.mix(self.loaded, self.getProvides(i)); } } } fn = self.onSuccess; msg = (failed.length) ? 'notregistered' : 'success'; success = !(failed.length); if (fn) { fn.call(self.context, { msg: msg, data: self.data, success: success, failed: failed, skipped: skipped }); } self._finish(msg, success); }, /** * The default Loader onProgress handler, calls this.onProgress with a payload * @method _onProgress * @private */ _onProgress: function(e) { var self = this, i; //set the internal cache to what just came in. if (e.data && e.data.length) { for (i = 0; i < e.data.length; i++) { e.data[i] = self.getModule(e.data[i].name); } } if (self.onProgress) { self.onProgress.call(self.context, { name: e.url, data: e.data }); } }, /** * The default Loader onFailure handler, calls this.onFailure with a payload * @method _onFailure * @private */ _onFailure: function(o) { var f = this.onFailure, msg = [], i = 0, len = o.errors.length; for (i; i < len; i++) { msg.push(o.errors[i].error); } msg = msg.join(','); if (f) { f.call(this.context, { msg: msg, data: this.data, success: false }); } this._finish(msg, false); }, /** * The default Loader onTimeout handler, calls this.onTimeout with a payload * @method _onTimeout * @param {Get.Transaction} transaction The Transaction object from `Y.Get` * @private */ _onTimeout: function(transaction) { var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false, transaction: transaction }); } }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { var name, // Object containing module names. required = this.required, // Keep track of whether we've visited a module. visited = {}; // Will contain modules names, in the correct order, // according to dependencies. this.sorted = []; for (name in required) { if (!visited[name] && required.hasOwnProperty(name)) { this._visit(name, visited); } } }, /** * Recursively visits the dependencies of the module name * passed in, and appends each module name to the `sorted` property. * @param {String} name The name of a module. * @param {Object} visited Keeps track of whether a module was visited. * @method _visit * @private */ _visit: function (name, visited) { var required, condition, moduleInfo, dependency, dependencies, trigger, isAfter, i, l; visited[name] = true; required = this.required; moduleInfo = this.moduleInfo[name]; condition = this.conditions[name] || {}; if (moduleInfo) { // Recurse on each dependency of this module, // figuring out its dependencies, and so on. dependencies = moduleInfo.expanded || moduleInfo.requires; for (i = 0, l = dependencies.length; i < l; ++i) { dependency = dependencies[i]; trigger = condition[dependency]; // We cannot process this dependency yet if it must // appear after our current module. isAfter = trigger && (!trigger.when || trigger.when === "after"); // Is this module name in the required list of modules, // and have we not already visited it? if (required[dependency] && !visited[dependency] && !isAfter) { this._visit(dependency, visited); } } } this.sorted.push(name); }, /** * Handles the actual insertion of script/link tags * @method _insert * @private * @param {Object} source The YUI instance the request came from * @param {Object} o The metadata to include * @param {String} type JS or CSS * @param {Boolean} [skipcalc=false] Do a Loader.calculate on the meta */ _insert: function(source, o, type, skipcalc) { // restore the state at the time of the request if (source) { this._config(source); } // build the dependency list // don't include type so we can process CSS and script in // one pass when the type is not specified. var modules = this.resolve(!skipcalc), self = this, comp = 0, actions = 0, mods = {}, deps, complete; self._refetch = []; if (type) { //Filter out the opposite type and reset the array so the checks later work modules[((type === JS) ? CSS : JS)] = []; } if (!self.fetchCSS) { modules.css = []; } if (modules.js.length) { comp++; } if (modules.css.length) { comp++; } //console.log('Resolved Modules: ', modules); complete = function(d) { actions++; var errs = {}, i = 0, o = 0, u = '', fn, modName, resMods; if (d && d.errors) { for (i = 0; i < d.errors.length; i++) { if (d.errors[i].request) { u = d.errors[i].request.url; } else { u = d.errors[i]; } errs[u] = u; } } if (d && d.data && d.data.length && (d.type === 'success')) { for (i = 0; i < d.data.length; i++) { self.inserted[d.data[i].name] = true; //If the external module has a skin or a lang, reprocess it if (d.data[i].lang || d.data[i].skinnable) { delete self.inserted[d.data[i].name]; self._refetch.push(d.data[i].name); } } } if (actions === comp) { self._loading = null; if (self._refetch.length) { //Get the deps for the new meta-data and reprocess for (i = 0; i < self._refetch.length; i++) { deps = self.getRequires(self.getModule(self._refetch[i])); for (o = 0; o < deps.length; o++) { if (!self.inserted[deps[o]]) { //We wouldn't be to this point without the module being here mods[deps[o]] = deps[o]; } } } mods = Y.Object.keys(mods); if (mods.length) { self.require(mods); resMods = self.resolve(true); if (resMods.cssMods.length) { for (i=0; i < resMods.cssMods.length; i++) { modName = resMods.cssMods[i].name; delete YUI.Env._cssLoaded[modName]; if (self.isCSSLoaded(modName)) { self.inserted[modName] = true; delete self.required[modName]; } } self.sorted = []; self._sort(); } d = null; //bail self._insert(); //insert the new deps } } if (d && d.fn) { fn = d.fn; delete d.fn; fn.call(self, d); } } }; this._loading = true; if (!modules.js.length && !modules.css.length) { actions = -1; complete({ fn: self._onSuccess }); return; } if (modules.css.length) { //Load CSS first Y.Get.css(modules.css, { data: modules.cssMods, attributes: self.cssAttributes, insertBefore: self.insertBefore, charset: self.charset, timeout: self.timeout, context: self, onProgress: function(e) { self._onProgress.call(self, e); }, onTimeout: function(d) { self._onTimeout.call(self, d); }, onSuccess: function(d) { d.type = 'success'; d.fn = self._onSuccess; complete.call(self, d); }, onFailure: function(d) { d.type = 'failure'; d.fn = self._onFailure; complete.call(self, d); } }); } if (modules.js.length) { Y.Get.js(modules.js, { data: modules.jsMods, insertBefore: self.insertBefore, attributes: self.jsAttributes, charset: self.charset, timeout: self.timeout, autopurge: false, context: self, async: self.async, onProgress: function(e) { self._onProgress.call(self, e); }, onTimeout: function(d) { self._onTimeout.call(self, d); }, onSuccess: function(d) { d.type = 'success'; d.fn = self._onSuccess; complete.call(self, d); }, onFailure: function(d) { d.type = 'failure'; d.fn = self._onFailure; complete.call(self, d); } }); } }, /** * Once a loader operation is completely finished, process any additional queued items. * @method _continue * @private */ _continue: function() { if (!(_queue.running) && _queue.size() > 0) { _queue.running = true; _queue.next()(); } }, /** * inserts the requested modules and their dependencies. * type can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param {object} o optional options object. * @param {string} type the type of dependency to insert. */ insert: function(o, type, skipsort) { var self = this, copy = Y.merge(this); delete copy.require; delete copy.dirty; _queue.add(function() { self._insert(copy, o, type, skipsort); }); this._continue(); }, /** * Executed every time a module is loaded, and if we are in a load * cycle, we attempt to load the next script. Public so that it * is possible to call this if using a method other than * Y.register to determine when scripts are fully loaded * @method loadNext * @deprecated * @param {string} mname optional the name of the module that has * been loaded (which is usually why it is time to load the next * one). */ loadNext: function() { return; }, /** * Apply filter defined for this instance to a url/path * @method _filter * @param {string} u the string to filter. * @param {string} name the name of the module, if we are processing * a single module as opposed to a combined url. * @return {string} the filtered string. * @private */ _filter: function(u, name, group) { var f = this.filter, hasFilter = name && (name in this.filters), modFilter = hasFilter && this.filters[name], groupName = group || (this.getModuleInfo(name) || {}).group || null; if (groupName && this.groups[groupName] && this.groups[groupName].filter) { modFilter = this.groups[groupName].filter; hasFilter = true; } if (u) { if (hasFilter) { f = (L.isString(modFilter)) ? this.FILTER_DEFS[modFilter.toUpperCase()] || null : modFilter; } if (f) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * @method _url * @param {string} path the path fragment. * @param {String} name The name of the module * @param {String} [base] The base url to use. Defaults to self.base * @return {string} the full url. * @private */ _url: function(path, name, base) { return this._filter((base || this.base || '') + path, name); }, /** * Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules. * @method resolve * @param {Boolean} [calc=false] Perform a loader.calculate() before anything else * @param {Array} [sorted=loader.sorted] An override for the loader.sorted array * @return {Object} Object hash (js and css) of two arrays of file lists * @example This method can be used as an off-line dep calculator * * var Y = YUI(); * var loader = new Y.Loader({ * filter: 'debug', * base: '../../', * root: 'build/', * combine: true, * require: ['node', 'dd', 'console'] * }); * var out = loader.resolve(true); * */ resolve: function(calc, sorted) { var self = this, resolved = { js: [], jsMods: [], css: [], cssMods: [] }, addSingle, usePathogen = Y.config.comboLoader && Y.config.customComboBase; if (self.skin.overrides || self.skin.defaultSkin !== DEFAULT_SKIN || self.ignoreRegistered) { self._resetModules(); } if (calc) { self.calculate(); } sorted = sorted || self.sorted; addSingle = function(mod) { if (mod) { var group = (mod.group && self.groups[mod.group]) || NOT_FOUND, url; //Always assume it's async if (group.async === false) { mod.async = group.async; } url = (mod.fullpath) ? self._filter(mod.fullpath, mod.name) : self._url(mod.path, mod.name, group.base || mod.base); if (mod.attributes || mod.async === false) { url = { url: url, async: mod.async }; if (mod.attributes) { url.attributes = mod.attributes; } } resolved[mod.type].push(url); resolved[mod.type + 'Mods'].push(mod); } else { } }; /*jslint vars: true */ var inserted = (self.ignoreRegistered) ? {} : self.inserted, comboSources, maxURLLength, comboMeta, comboBase, comboSep, group, mod, len, i, hasComboModule = false; /*jslint vars: false */ for (i = 0, len = sorted.length; i < len; i++) { mod = self.getModule(sorted[i]); if (!mod || inserted[mod.name]) { continue; } group = self.groups[mod.group]; comboBase = self.comboBase; if (group) { if (!group.combine || mod.fullpath) { //This is not a combo module, skip it and load it singly later. addSingle(mod); continue; } mod.combine = true; if (typeof group.root === 'string') { mod.root = group.root; } comboBase = group.comboBase || comboBase; comboSep = group.comboSep; maxURLLength = group.maxURLLength; } else { if (!self.combine) { //This is not a combo module, skip it and load it singly later. addSingle(mod); continue; } } if (!mod.combine && mod.ext) { addSingle(mod); continue; } hasComboModule = true; comboSources = comboSources || {}; comboSources[comboBase] = comboSources[comboBase] || { js: [], jsMods: [], css: [], cssMods: [] }; comboMeta = comboSources[comboBase]; comboMeta.group = mod.group; comboMeta.comboSep = comboSep || self.comboSep; comboMeta.maxURLLength = maxURLLength || self.maxURLLength; comboMeta[mod.type + 'Mods'].push(mod); if (mod.type === JS || mod.type === CSS) { resolved[mod.type + 'Mods'].push(mod); } } //only encode if we have something to encode if (hasComboModule) { if (usePathogen) { resolved = this._pathogenEncodeComboSources(resolved); } else { resolved = this._encodeComboSources(resolved, comboSources); } } return resolved; }, /** * Encodes combo sources and appends them to an object hash of arrays from `loader.resolve`. * * @method _encodeComboSources * @param {Object} resolved The object hash of arrays in which to attach the encoded combo sources. * @param {Object} comboSources An object containing relevant data about modules. * @return Object * @private */ _encodeComboSources: function(resolved, comboSources) { var fragSubset, modules, tmpBase, baseLen, frags, frag, type, mod, maxURLLength, comboBase, comboMeta, comboSep, i, len, self = this; for (comboBase in comboSources) { if (comboSources.hasOwnProperty(comboBase)) { comboMeta = comboSources[comboBase]; comboSep = comboMeta.comboSep; maxURLLength = comboMeta.maxURLLength; for (type in comboMeta) { if (type === JS || type === CSS) { modules = comboMeta[type + 'Mods']; frags = []; for (i = 0, len = modules.length; i < len; i += 1) { mod = modules[i]; frag = ((typeof mod.root === 'string') ? mod.root : self.root) + (mod.path || mod.fullpath); frags.push( self._filter(frag, mod.name) ); } tmpBase = comboBase + frags.join(comboSep); baseLen = tmpBase.length; if (maxURLLength <= comboBase.length) { maxURLLength = MAX_URL_LENGTH; } if (frags.length) { if (baseLen > maxURLLength) { fragSubset = []; for (i = 0, len = frags.length; i < len; i++) { fragSubset.push(frags[i]); tmpBase = comboBase + fragSubset.join(comboSep); if (tmpBase.length > maxURLLength) { frag = fragSubset.pop(); tmpBase = comboBase + fragSubset.join(comboSep); resolved[type].push(self._filter(tmpBase, null, comboMeta.group)); fragSubset = []; if (frag) { fragSubset.push(frag); } } } if (fragSubset.length) { tmpBase = comboBase + fragSubset.join(comboSep); resolved[type].push(self._filter(tmpBase, null, comboMeta.group)); } } else { resolved[type].push(self._filter(tmpBase, null, comboMeta.group)); } } } } } } return resolved; }, /** Shortcut to calculate, resolve and load all modules. var loader = new Y.Loader({ ignoreRegistered: true, modules: { mod: { path: 'mod.js' } }, requires: [ 'mod' ] }); loader.load(function() { console.log('All modules have loaded..'); }); @method load @param {Function} cb Executed after all load operations are complete */ load: function(cb) { if (!cb) { return; } var self = this, out = self.resolve(true); self.data = out; self.onEnd = function() { cb.apply(self.context || self, arguments); }; self.insert(); } }; }, '3.18.1', {"requires": ["get", "features"]}); YUI.add('loader-rollup', function (Y, NAME) { /** * Optional automatic rollup logic for reducing http connections * when not using a combo service. * @module loader * @submodule rollup */ /** * Look for rollup packages to determine if all of the modules a * rollup supersedes are required. If so, include the rollup to * help reduce the total number of connections required. Called * by calculate(). This is an optional feature, and requires the * appropriate submodule to function. * @method _rollup * @for Loader * @private */ Y.Loader.prototype._rollup = function() { var i, j, m, s, r = this.required, roll, info = this.moduleInfo, rolled, c, smod; // find and cache rollup modules if (this.dirty || !this.rollups) { this.rollups = {}; for (i in info) { if (info.hasOwnProperty(i)) { m = this.getModule(i); // if (m && m.rollup && m.supersedes) { if (m && m.rollup) { this.rollups[i] = m; } } } } // make as many passes as needed to pick up rollup rollups for (;;) { rolled = false; // go through the rollup candidates for (i in this.rollups) { if (this.rollups.hasOwnProperty(i)) { // there can be only one, unless forced if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) { m = this.getModule(i); s = m.supersedes || []; roll = false; // @TODO remove continue if (!m.rollup) { continue; } c = 0; // check the threshold for (j = 0; j < s.length; j++) { smod = info[s[j]]; // if the superseded module is loaded, we can't // load the rollup unless it has been forced. if (this.loaded[s[j]] && !this.forceMap[s[j]]) { roll = false; break; // increment the counter if this module is required. // if we are beyond the rollup threshold, we will // use the rollup module } else if (r[s[j]] && m.type === smod.type) { c++; roll = (c >= m.rollup); if (roll) { break; } } } if (roll) { // add the rollup r[i] = true; rolled = true; // expand the rollup's dependencies this.getRequires(m); } } } } // if we made it here w/o rolling up something, we are done if (!rolled) { break; } } }; }, '3.18.1', {"requires": ["loader-base"]}); YUI.add('loader-yui3', function (Y, NAME) { /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ /** * YUI 3 module metadata * @module loader * @submodule loader-yui3 */ YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || {}; Y.mix(YUI.Env[Y.version].modules, { "align-plugin": { "requires": [ "node-screen", "node-pluginhost" ] }, "anim": { "use": [ "anim-base", "anim-color", "anim-curve", "anim-easing", "anim-node-plugin", "anim-scroll", "anim-xy" ] }, "anim-base": { "requires": [ "base-base", "node-style", "color-base" ] }, "anim-color": { "requires": [ "anim-base" ] }, "anim-curve": { "requires": [ "anim-xy" ] }, "anim-easing": { "requires": [ "anim-base" ] }, "anim-node-plugin": { "requires": [ "node-pluginhost", "anim-base" ] }, "anim-scroll": { "requires": [ "anim-base" ] }, "anim-shape": { "requires": [ "anim-base", "anim-easing", "anim-color", "matrix" ] }, "anim-shape-transform": { "use": [ "anim-shape" ] }, "anim-xy": { "requires": [ "anim-base", "node-screen" ] }, "app": { "use": [ "app-base", "app-content", "app-transitions", "lazy-model-list", "model", "model-list", "model-sync-rest", "model-sync-local", "router", "view", "view-node-map" ] }, "app-base": { "requires": [ "classnamemanager", "pjax-base", "router", "view" ] }, "app-content": { "requires": [ "app-base", "pjax-content" ] }, "app-transitions": { "requires": [ "app-base" ] }, "app-transitions-css": { "type": "css" }, "app-transitions-native": { "condition": { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }, "requires": [ "app-transitions", "app-transitions-css", "parallel", "transition" ] }, "array-extras": { "requires": [ "yui-base" ] }, "array-invoke": { "requires": [ "yui-base" ] }, "arraylist": { "requires": [ "yui-base" ] }, "arraylist-add": { "requires": [ "arraylist" ] }, "arraylist-filter": { "requires": [ "arraylist" ] }, "arraysort": { "requires": [ "yui-base" ] }, "async-queue": { "requires": [ "event-custom" ] }, "attribute": { "use": [ "attribute-base", "attribute-complex" ] }, "attribute-base": { "requires": [ "attribute-core", "attribute-observable", "attribute-extras" ] }, "attribute-complex": { "requires": [ "attribute-base" ] }, "attribute-core": { "requires": [ "oop" ] }, "attribute-events": { "use": [ "attribute-observable" ] }, "attribute-extras": { "requires": [ "oop" ] }, "attribute-observable": { "requires": [ "event-custom" ] }, "autocomplete": { "use": [ "autocomplete-base", "autocomplete-sources", "autocomplete-list", "autocomplete-plugin" ] }, "autocomplete-base": { "optional": [ "autocomplete-sources" ], "requires": [ "array-extras", "base-build", "escape", "event-valuechange", "node-base" ] }, "autocomplete-filters": { "requires": [ "array-extras", "text-wordbreak" ] }, "autocomplete-filters-accentfold": { "requires": [ "array-extras", "text-accentfold", "text-wordbreak" ] }, "autocomplete-highlighters": { "requires": [ "array-extras", "highlight-base" ] }, "autocomplete-highlighters-accentfold": { "requires": [ "array-extras", "highlight-accentfold" ] }, "autocomplete-list": { "after": [ "autocomplete-sources" ], "lang": [ "en", "es", "hu", "it" ], "requires": [ "autocomplete-base", "event-resize", "node-screen", "selector-css3", "shim-plugin", "widget", "widget-position", "widget-position-align" ], "skinnable": true }, "autocomplete-list-keys": { "condition": { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }, "requires": [ "autocomplete-list", "base-build" ] }, "autocomplete-plugin": { "requires": [ "autocomplete-list", "node-pluginhost" ] }, "autocomplete-sources": { "optional": [ "io-base", "json-parse", "jsonp", "yql" ], "requires": [ "autocomplete-base" ] }, "axes": { "use": [ "axis-numeric", "axis-category", "axis-time", "axis-stacked" ] }, "axes-base": { "use": [ "axis-numeric-base", "axis-category-base", "axis-time-base", "axis-stacked-base" ] }, "axis": { "requires": [ "dom", "widget", "widget-position", "widget-stack", "graphics", "axis-base" ] }, "axis-base": { "requires": [ "classnamemanager", "datatype-number", "datatype-date", "base", "event-custom" ] }, "axis-category": { "requires": [ "axis", "axis-category-base" ] }, "axis-category-base": { "requires": [ "axis-base" ] }, "axis-numeric": { "requires": [ "axis", "axis-numeric-base" ] }, "axis-numeric-base": { "requires": [ "axis-base" ] }, "axis-stacked": { "requires": [ "axis-numeric", "axis-stacked-base" ] }, "axis-stacked-base": { "requires": [ "axis-numeric-base" ] }, "axis-time": { "requires": [ "axis", "axis-time-base" ] }, "axis-time-base": { "requires": [ "axis-base" ] }, "base": { "use": [ "base-base", "base-pluginhost", "base-build" ] }, "base-base": { "requires": [ "attribute-base", "base-core", "base-observable" ] }, "base-build": { "requires": [ "base-base" ] }, "base-core": { "requires": [ "attribute-core" ] }, "base-observable": { "requires": [ "attribute-observable", "base-core" ] }, "base-pluginhost": { "requires": [ "base-base", "pluginhost" ] }, "button": { "requires": [ "button-core", "cssbutton", "widget" ] }, "button-core": { "requires": [ "attribute-core", "classnamemanager", "node-base", "escape" ] }, "button-group": { "requires": [ "button-plugin", "cssbutton", "widget" ] }, "button-plugin": { "requires": [ "button-core", "cssbutton", "node-pluginhost" ] }, "cache": { "use": [ "cache-base", "cache-offline", "cache-plugin" ] }, "cache-base": { "requires": [ "base" ] }, "cache-offline": { "requires": [ "cache-base", "json" ] }, "cache-plugin": { "requires": [ "plugin", "cache-base" ] }, "calendar": { "requires": [ "calendar-base", "calendarnavigator" ], "skinnable": true }, "calendar-base": { "lang": [ "de", "en", "es", "es-AR", "fr", "hu", "it", "ja", "nb-NO", "nl", "pt-BR", "ru", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-HANT-TW" ], "requires": [ "widget", "datatype-date", "datatype-date-math", "cssgrids" ], "skinnable": true }, "calendarnavigator": { "requires": [ "plugin", "classnamemanager", "datatype-date", "node" ], "skinnable": true }, "charts": { "use": [ "charts-base" ] }, "charts-base": { "requires": [ "dom", "event-mouseenter", "event-touch", "graphics-group", "axes", "series-pie", "series-line", "series-marker", "series-area", "series-spline", "series-column", "series-bar", "series-areaspline", "series-combo", "series-combospline", "series-line-stacked", "series-marker-stacked", "series-area-stacked", "series-spline-stacked", "series-column-stacked", "series-bar-stacked", "series-areaspline-stacked", "series-combo-stacked", "series-combospline-stacked" ] }, "charts-legend": { "requires": [ "charts-base" ] }, "classnamemanager": { "requires": [ "yui-base" ] }, "clickable-rail": { "requires": [ "slider-base" ] }, "collection": { "use": [ "array-extras", "arraylist", "arraylist-add", "arraylist-filter", "array-invoke" ] }, "color": { "use": [ "color-base", "color-hsl", "color-harmony" ] }, "color-base": { "requires": [ "yui-base" ] }, "color-harmony": { "requires": [ "color-hsl" ] }, "color-hsl": { "requires": [ "color-base" ] }, "color-hsv": { "requires": [ "color-base" ] }, "console": { "lang": [ "en", "es", "hu", "it", "ja" ], "requires": [ "yui-log", "widget" ], "skinnable": true }, "console-filters": { "requires": [ "plugin", "console" ], "skinnable": true }, "content-editable": { "requires": [ "node-base", "editor-selection", "stylesheet", "plugin" ] }, "controller": { "use": [ "router" ] }, "cookie": { "requires": [ "yui-base" ] }, "createlink-base": { "requires": [ "editor-base" ] }, "cssbase": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssbase-context": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssbutton": { "type": "css" }, "cssfonts": { "type": "css" }, "cssfonts-context": { "type": "css" }, "cssgrids": { "optional": [ "cssnormalize" ], "type": "css" }, "cssgrids-base": { "optional": [ "cssnormalize" ], "type": "css" }, "cssgrids-responsive": { "optional": [ "cssnormalize" ], "requires": [ "cssgrids", "cssgrids-responsive-base" ], "type": "css" }, "cssgrids-units": { "optional": [ "cssnormalize" ], "requires": [ "cssgrids-base" ], "type": "css" }, "cssnormalize": { "type": "css" }, "cssnormalize-context": { "type": "css" }, "cssreset": { "type": "css" }, "cssreset-context": { "type": "css" }, "dataschema": { "use": [ "dataschema-base", "dataschema-json", "dataschema-xml", "dataschema-array", "dataschema-text" ] }, "dataschema-array": { "requires": [ "dataschema-base" ] }, "dataschema-base": { "requires": [ "base" ] }, "dataschema-json": { "requires": [ "dataschema-base", "json" ] }, "dataschema-text": { "requires": [ "dataschema-base" ] }, "dataschema-xml": { "requires": [ "dataschema-base" ] }, "datasource": { "use": [ "datasource-local", "datasource-io", "datasource-get", "datasource-function", "datasource-cache", "datasource-jsonschema", "datasource-xmlschema", "datasource-arrayschema", "datasource-textschema", "datasource-polling" ] }, "datasource-arrayschema": { "requires": [ "datasource-local", "plugin", "dataschema-array" ] }, "datasource-cache": { "requires": [ "datasource-local", "plugin", "cache-base" ] }, "datasource-function": { "requires": [ "datasource-local" ] }, "datasource-get": { "requires": [ "datasource-local", "get" ] }, "datasource-io": { "requires": [ "datasource-local", "io-base" ] }, "datasource-jsonschema": { "requires": [ "datasource-local", "plugin", "dataschema-json" ] }, "datasource-local": { "requires": [ "base" ] }, "datasource-polling": { "requires": [ "datasource-local" ] }, "datasource-textschema": { "requires": [ "datasource-local", "plugin", "dataschema-text" ] }, "datasource-xmlschema": { "requires": [ "datasource-local", "plugin", "datatype-xml", "dataschema-xml" ] }, "datatable": { "use": [ "datatable-core", "datatable-table", "datatable-head", "datatable-body", "datatable-base", "datatable-column-widths", "datatable-message", "datatable-mutable", "datatable-sort", "datatable-datasource" ] }, "datatable-base": { "requires": [ "datatable-core", "datatable-table", "datatable-head", "datatable-body", "base-build", "widget" ], "skinnable": true }, "datatable-body": { "requires": [ "datatable-core", "view", "classnamemanager" ] }, "datatable-column-widths": { "requires": [ "datatable-base" ] }, "datatable-core": { "requires": [ "escape", "model-list", "node-event-delegate" ] }, "datatable-datasource": { "requires": [ "datatable-base", "plugin", "datasource-local" ] }, "datatable-foot": { "requires": [ "datatable-core", "view" ] }, "datatable-formatters": { "requires": [ "datatable-body", "datatype-number-format", "datatype-date-format", "escape" ] }, "datatable-head": { "requires": [ "datatable-core", "view", "classnamemanager" ] }, "datatable-highlight": { "requires": [ "datatable-base", "event-hover" ], "skinnable": true }, "datatable-keynav": { "requires": [ "datatable-base" ] }, "datatable-message": { "lang": [ "en", "fr", "es", "hu", "it" ], "requires": [ "datatable-base" ], "skinnable": true }, "datatable-mutable": { "requires": [ "datatable-base" ] }, "datatable-paginator": { "lang": [ "en", "fr" ], "requires": [ "model", "view", "paginator-core", "datatable-foot", "datatable-paginator-templates" ], "skinnable": true }, "datatable-paginator-templates": { "requires": [ "template" ] }, "datatable-scroll": { "requires": [ "datatable-base", "datatable-column-widths", "dom-screen" ], "skinnable": true }, "datatable-sort": { "lang": [ "en", "fr", "es", "hu" ], "requires": [ "datatable-base" ], "skinnable": true }, "datatable-table": { "requires": [ "datatable-core", "datatable-head", "datatable-body", "view", "classnamemanager" ] }, "datatype": { "use": [ "datatype-date", "datatype-number", "datatype-xml" ] }, "datatype-date": { "use": [ "datatype-date-parse", "datatype-date-format", "datatype-date-math" ] }, "datatype-date-format": { "lang": [ "ar", "ar-JO", "ca", "ca-ES", "da", "da-DK", "de", "de-AT", "de-DE", "el", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-JO", "en-MY", "en-NZ", "en-PH", "en-SG", "en-US", "es", "es-AR", "es-BO", "es-CL", "es-CO", "es-EC", "es-ES", "es-MX", "es-PE", "es-PY", "es-US", "es-UY", "es-VE", "fi", "fi-FI", "fr", "fr-BE", "fr-CA", "fr-FR", "hi", "hi-IN", "hu", "id", "id-ID", "it", "it-IT", "ja", "ja-JP", "ko", "ko-KR", "ms", "ms-MY", "nb", "nb-NO", "nl", "nl-BE", "nl-NL", "pl", "pl-PL", "pt", "pt-BR", "ro", "ro-RO", "ru", "ru-RU", "sv", "sv-SE", "th", "th-TH", "tr", "tr-TR", "vi", "vi-VN", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-Hant-TW" ] }, "datatype-date-math": { "requires": [ "yui-base" ] }, "datatype-date-parse": {}, "datatype-number": { "use": [ "datatype-number-parse", "datatype-number-format" ] }, "datatype-number-format": {}, "datatype-number-parse": { "requires": [ "escape" ] }, "datatype-xml": { "use": [ "datatype-xml-parse", "datatype-xml-format" ] }, "datatype-xml-format": {}, "datatype-xml-parse": {}, "dd": { "use": [ "dd-ddm-base", "dd-ddm", "dd-ddm-drop", "dd-drag", "dd-proxy", "dd-constrain", "dd-drop", "dd-scroll", "dd-delegate" ] }, "dd-constrain": { "requires": [ "dd-drag" ] }, "dd-ddm": { "requires": [ "dd-ddm-base", "event-resize" ] }, "dd-ddm-base": { "requires": [ "node", "base", "yui-throttle", "classnamemanager" ] }, "dd-ddm-drop": { "requires": [ "dd-ddm" ] }, "dd-delegate": { "requires": [ "dd-drag", "dd-drop-plugin", "event-mouseenter" ] }, "dd-drag": { "requires": [ "dd-ddm-base", "selector-css2" ] }, "dd-drop": { "requires": [ "dd-drag", "dd-ddm-drop" ] }, "dd-drop-plugin": { "requires": [ "dd-drop" ] }, "dd-gestures": { "condition": { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }, "requires": [ "dd-drag", "event-synthetic", "event-gestures" ] }, "dd-plugin": { "optional": [ "dd-constrain", "dd-proxy" ], "requires": [ "dd-drag" ] }, "dd-proxy": { "requires": [ "dd-drag" ] }, "dd-scroll": { "requires": [ "dd-drag" ] }, "dial": { "lang": [ "en", "es", "hu" ], "requires": [ "widget", "dd-drag", "event-mouseenter", "event-move", "event-key", "transition", "intl" ], "skinnable": true }, "dom": { "use": [ "dom-base", "dom-screen", "dom-style", "selector-native", "selector" ] }, "dom-base": { "requires": [ "dom-core" ] }, "dom-core": { "requires": [ "oop", "features" ] }, "dom-screen": { "requires": [ "dom-base", "dom-style" ] }, "dom-style": { "requires": [ "dom-base" ] }, "dom-style-ie": { "condition": { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }, "requires": [ "dom-style", "color-base" ] }, "dump": { "requires": [ "yui-base" ] }, "editor": { "use": [ "frame", "editor-selection", "exec-command", "editor-base", "editor-para", "editor-br", "editor-bidi", "editor-tab", "createlink-base" ] }, "editor-base": { "requires": [ "base", "frame", "node", "exec-command", "editor-selection" ] }, "editor-bidi": { "requires": [ "editor-base" ] }, "editor-br": { "requires": [ "editor-base" ] }, "editor-inline": { "requires": [ "editor-base", "content-editable" ] }, "editor-lists": { "requires": [ "editor-base" ] }, "editor-para": { "requires": [ "editor-para-base" ] }, "editor-para-base": { "requires": [ "editor-base" ] }, "editor-para-ie": { "condition": { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }, "requires": [ "editor-para-base" ] }, "editor-selection": { "requires": [ "node" ] }, "editor-tab": { "requires": [ "editor-base" ] }, "escape": { "requires": [ "yui-base" ] }, "event": { "after": [ "node-base" ], "use": [ "event-base", "event-delegate", "event-synthetic", "event-mousewheel", "event-mouseenter", "event-key", "event-focus", "event-resize", "event-hover", "event-outside", "event-touch", "event-move", "event-flick", "event-valuechange", "event-tap" ] }, "event-base": { "after": [ "node-base" ], "requires": [ "event-custom-base" ] }, "event-base-ie": { "after": [ "event-base" ], "condition": { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }, "requires": [ "node-base" ] }, "event-contextmenu": { "requires": [ "event-synthetic", "dom-screen" ] }, "event-custom": { "use": [ "event-custom-base", "event-custom-complex" ] }, "event-custom-base": { "requires": [ "oop" ] }, "event-custom-complex": { "requires": [ "event-custom-base" ] }, "event-delegate": { "requires": [ "node-base" ] }, "event-flick": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-focus": { "requires": [ "event-synthetic" ] }, "event-gestures": { "use": [ "event-flick", "event-move" ] }, "event-hover": { "requires": [ "event-mouseenter" ] }, "event-key": { "requires": [ "event-synthetic" ] }, "event-mouseenter": { "requires": [ "event-synthetic" ] }, "event-mousewheel": { "requires": [ "node-base" ] }, "event-move": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-outside": { "requires": [ "event-synthetic" ] }, "event-resize": { "requires": [ "node-base", "event-synthetic" ] }, "event-simulate": { "requires": [ "event-base" ] }, "event-synthetic": { "requires": [ "node-base", "event-custom-complex" ] }, "event-tap": { "requires": [ "node-base", "event-base", "event-touch", "event-synthetic" ] }, "event-touch": { "requires": [ "node-base" ] }, "event-valuechange": { "requires": [ "event-focus", "event-synthetic" ] }, "exec-command": { "requires": [ "frame" ] }, "features": { "requires": [ "yui-base" ] }, "file": { "requires": [ "file-flash", "file-html5" ] }, "file-flash": { "requires": [ "base" ] }, "file-html5": { "requires": [ "base" ] }, "frame": { "requires": [ "base", "node", "plugin", "selector-css3", "yui-throttle" ] }, "gesture-simulate": { "requires": [ "async-queue", "event-simulate", "node-screen" ] }, "get": { "requires": [ "yui-base" ] }, "graphics": { "requires": [ "node", "event-custom", "pluginhost", "matrix", "classnamemanager" ] }, "graphics-canvas": { "condition": { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }, "requires": [ "graphics", "color-base" ] }, "graphics-canvas-default": { "condition": { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" } }, "graphics-group": { "requires": [ "graphics" ] }, "graphics-svg": { "condition": { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-svg-default": { "condition": { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" } }, "graphics-vml": { "condition": { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }, "requires": [ "graphics", "color-base" ] }, "graphics-vml-default": { "condition": { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" } }, "handlebars": { "use": [ "handlebars-compiler" ] }, "handlebars-base": { "requires": [] }, "handlebars-compiler": { "requires": [ "handlebars-base" ] }, "highlight": { "use": [ "highlight-base", "highlight-accentfold" ] }, "highlight-accentfold": { "requires": [ "highlight-base", "text-accentfold" ] }, "highlight-base": { "requires": [ "array-extras", "classnamemanager", "escape", "text-wordbreak" ] }, "history": { "use": [ "history-base", "history-hash", "history-html5" ] }, "history-base": { "requires": [ "event-custom-complex" ] }, "history-hash": { "after": [ "history-html5" ], "requires": [ "event-synthetic", "history-base", "yui-later" ] }, "history-hash-ie": { "condition": { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }, "requires": [ "history-hash", "node-base" ] }, "history-html5": { "optional": [ "json" ], "requires": [ "event-base", "history-base", "node-base" ] }, "imageloader": { "requires": [ "base-base", "node-style", "node-screen" ] }, "intl": { "requires": [ "intl-base", "event-custom" ] }, "intl-base": { "requires": [ "yui-base" ] }, "io": { "use": [ "io-base", "io-xdr", "io-form", "io-upload-iframe", "io-queue" ] }, "io-base": { "requires": [ "event-custom-base", "querystring-stringify-simple" ] }, "io-form": { "requires": [ "io-base", "node-base" ] }, "io-nodejs": { "condition": { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }, "requires": [ "io-base" ] }, "io-queue": { "requires": [ "io-base", "queue-promote" ] }, "io-upload-iframe": { "requires": [ "io-base", "node-base" ] }, "io-xdr": { "requires": [ "io-base", "datatype-xml-parse" ] }, "json": { "use": [ "json-parse", "json-stringify" ] }, "json-parse": { "requires": [ "yui-base" ] }, "json-parse-shim": { "condition": { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }, "requires": [ "json-parse" ] }, "json-stringify": { "requires": [ "yui-base" ] }, "json-stringify-shim": { "condition": { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }, "requires": [ "json-stringify" ] }, "jsonp": { "requires": [ "get", "oop" ] }, "jsonp-url": { "requires": [ "jsonp" ] }, "lazy-model-list": { "requires": [ "model-list" ] }, "loader": { "use": [ "loader-base", "loader-rollup", "loader-yui3" ] }, "loader-base": { "requires": [ "get", "features" ] }, "loader-pathogen-combohandler": {}, "loader-pathogen-encoder": { "use": [ "loader-base", "loader-rollup", "loader-yui3", "loader-pathogen-combohandler" ] }, "loader-rollup": { "requires": [ "loader-base" ] }, "loader-yui3": { "requires": [ "loader-base" ] }, "matrix": { "requires": [ "yui-base" ] }, "model": { "requires": [ "base-build", "escape", "json-parse" ] }, "model-list": { "requires": [ "array-extras", "array-invoke", "arraylist", "base-build", "escape", "json-parse", "model" ] }, "model-sync-local": { "requires": [ "model", "json-stringify" ] }, "model-sync-rest": { "requires": [ "model", "io-base", "json-stringify" ] }, "node": { "use": [ "node-base", "node-event-delegate", "node-pluginhost", "node-screen", "node-style" ] }, "node-base": { "requires": [ "event-base", "node-core", "dom-base", "dom-style" ] }, "node-core": { "requires": [ "dom-core", "selector" ] }, "node-event-delegate": { "requires": [ "node-base", "event-delegate" ] }, "node-event-html5": { "requires": [ "node-base" ] }, "node-event-simulate": { "requires": [ "node-base", "event-simulate", "gesture-simulate" ] }, "node-flick": { "requires": [ "classnamemanager", "transition", "event-flick", "plugin" ], "skinnable": true }, "node-focusmanager": { "requires": [ "attribute", "node", "plugin", "node-event-simulate", "event-key", "event-focus" ] }, "node-load": { "requires": [ "node-base", "io-base" ] }, "node-menunav": { "requires": [ "node", "classnamemanager", "plugin", "node-focusmanager" ], "skinnable": true }, "node-pluginhost": { "requires": [ "node-base", "pluginhost" ] }, "node-screen": { "requires": [ "dom-screen", "node-base" ] }, "node-scroll-info": { "requires": [ "array-extras", "base-build", "event-resize", "node-pluginhost", "plugin", "selector" ] }, "node-style": { "requires": [ "dom-style", "node-base" ] }, "oop": { "requires": [ "yui-base" ] }, "overlay": { "requires": [ "widget", "widget-stdmod", "widget-position", "widget-position-align", "widget-stack", "widget-position-constrain" ], "skinnable": true }, "paginator": { "requires": [ "paginator-core" ] }, "paginator-core": { "requires": [ "base" ] }, "paginator-url": { "requires": [ "paginator" ] }, "panel": { "requires": [ "widget", "widget-autohide", "widget-buttons", "widget-modality", "widget-position", "widget-position-align", "widget-position-constrain", "widget-stack", "widget-stdmod" ], "skinnable": true }, "parallel": { "requires": [ "yui-base" ] }, "pjax": { "requires": [ "pjax-base", "pjax-content" ] }, "pjax-base": { "requires": [ "classnamemanager", "node-event-delegate", "router" ] }, "pjax-content": { "requires": [ "io-base", "node-base", "router" ] }, "pjax-plugin": { "requires": [ "node-pluginhost", "pjax", "plugin" ] }, "plugin": { "requires": [ "base-base" ] }, "pluginhost": { "use": [ "pluginhost-base", "pluginhost-config" ] }, "pluginhost-base": { "requires": [ "yui-base" ] }, "pluginhost-config": { "requires": [ "pluginhost-base" ] }, "promise": { "requires": [ "timers" ] }, "querystring": { "use": [ "querystring-parse", "querystring-stringify" ] }, "querystring-parse": { "requires": [ "yui-base", "array-extras" ] }, "querystring-parse-simple": { "requires": [ "yui-base" ] }, "querystring-stringify": { "requires": [ "yui-base" ] }, "querystring-stringify-simple": { "requires": [ "yui-base" ] }, "queue-promote": { "requires": [ "yui-base" ] }, "range-slider": { "requires": [ "slider-base", "slider-value-range", "clickable-rail" ] }, "recordset": { "use": [ "recordset-base", "recordset-sort", "recordset-filter", "recordset-indexer" ] }, "recordset-base": { "requires": [ "base", "arraylist" ] }, "recordset-filter": { "requires": [ "recordset-base", "array-extras", "plugin" ] }, "recordset-indexer": { "requires": [ "recordset-base", "plugin" ] }, "recordset-sort": { "requires": [ "arraysort", "recordset-base", "plugin" ] }, "resize": { "use": [ "resize-base", "resize-proxy", "resize-constrain" ] }, "resize-base": { "requires": [ "base", "widget", "event", "oop", "dd-drag", "dd-delegate", "dd-drop" ], "skinnable": true }, "resize-constrain": { "requires": [ "plugin", "resize-base" ] }, "resize-plugin": { "optional": [ "resize-constrain" ], "requires": [ "resize-base", "plugin" ] }, "resize-proxy": { "requires": [ "plugin", "resize-base" ] }, "router": { "optional": [ "querystring-parse" ], "requires": [ "array-extras", "base-build", "history" ] }, "scrollview": { "requires": [ "scrollview-base", "scrollview-scrollbars" ] }, "scrollview-base": { "requires": [ "widget", "event-gestures", "event-mousewheel", "transition" ], "skinnable": true }, "scrollview-base-ie": { "condition": { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }, "requires": [ "scrollview-base" ] }, "scrollview-list": { "requires": [ "plugin", "classnamemanager" ], "skinnable": true }, "scrollview-paginator": { "requires": [ "plugin", "classnamemanager" ] }, "scrollview-scrollbars": { "requires": [ "classnamemanager", "transition", "plugin" ], "skinnable": true }, "selector": { "requires": [ "selector-native" ] }, "selector-css2": { "condition": { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }, "requires": [ "selector-native" ] }, "selector-css3": { "requires": [ "selector-native", "selector-css2" ] }, "selector-native": { "requires": [ "dom-base" ] }, "series-area": { "requires": [ "series-cartesian", "series-fill-util" ] }, "series-area-stacked": { "requires": [ "series-stacked", "series-area" ] }, "series-areaspline": { "requires": [ "series-area", "series-curve-util" ] }, "series-areaspline-stacked": { "requires": [ "series-stacked", "series-areaspline" ] }, "series-bar": { "requires": [ "series-marker", "series-histogram-base" ] }, "series-bar-stacked": { "requires": [ "series-stacked", "series-bar" ] }, "series-base": { "requires": [ "graphics", "axis-base" ] }, "series-candlestick": { "requires": [ "series-range" ] }, "series-cartesian": { "requires": [ "series-base" ] }, "series-column": { "requires": [ "series-marker", "series-histogram-base" ] }, "series-column-stacked": { "requires": [ "series-stacked", "series-column" ] }, "series-combo": { "requires": [ "series-cartesian", "series-line-util", "series-plot-util", "series-fill-util" ] }, "series-combo-stacked": { "requires": [ "series-stacked", "series-combo" ] }, "series-combospline": { "requires": [ "series-combo", "series-curve-util" ] }, "series-combospline-stacked": { "requires": [ "series-combo-stacked", "series-curve-util" ] }, "series-curve-util": {}, "series-fill-util": {}, "series-histogram-base": { "requires": [ "series-cartesian", "series-plot-util" ] }, "series-line": { "requires": [ "series-cartesian", "series-line-util" ] }, "series-line-stacked": { "requires": [ "series-stacked", "series-line" ] }, "series-line-util": {}, "series-marker": { "requires": [ "series-cartesian", "series-plot-util" ] }, "series-marker-stacked": { "requires": [ "series-stacked", "series-marker" ] }, "series-ohlc": { "requires": [ "series-range" ] }, "series-pie": { "requires": [ "series-base", "series-plot-util" ] }, "series-plot-util": {}, "series-range": { "requires": [ "series-cartesian" ] }, "series-spline": { "requires": [ "series-line", "series-curve-util" ] }, "series-spline-stacked": { "requires": [ "series-stacked", "series-spline" ] }, "series-stacked": { "requires": [ "axis-stacked" ] }, "shim-plugin": { "requires": [ "node-style", "node-pluginhost" ] }, "slider": { "use": [ "slider-base", "slider-value-range", "clickable-rail", "range-slider" ] }, "slider-base": { "requires": [ "widget", "dd-constrain", "event-key" ], "skinnable": true }, "slider-value-range": { "requires": [ "slider-base" ] }, "sortable": { "requires": [ "dd-delegate", "dd-drop-plugin", "dd-proxy" ] }, "sortable-scroll": { "requires": [ "dd-scroll", "sortable" ] }, "stylesheet": { "requires": [ "yui-base" ] }, "substitute": { "optional": [ "dump" ], "requires": [ "yui-base" ] }, "swf": { "requires": [ "event-custom", "node", "swfdetect", "escape" ] }, "swfdetect": { "requires": [ "yui-base" ] }, "tabview": { "requires": [ "widget", "widget-parent", "widget-child", "tabview-base", "node-pluginhost", "node-focusmanager" ], "skinnable": true }, "tabview-base": { "requires": [ "node-event-delegate", "classnamemanager" ] }, "tabview-plugin": { "requires": [ "tabview-base" ] }, "template": { "use": [ "template-base", "template-micro" ] }, "template-base": { "requires": [ "yui-base" ] }, "template-micro": { "requires": [ "escape" ] }, "test": { "requires": [ "event-simulate", "event-custom", "json-stringify" ] }, "test-console": { "requires": [ "console-filters", "test", "array-extras" ], "skinnable": true }, "text": { "use": [ "text-accentfold", "text-wordbreak" ] }, "text-accentfold": { "requires": [ "array-extras", "text-data-accentfold" ] }, "text-data-accentfold": { "requires": [ "yui-base" ] }, "text-data-wordbreak": { "requires": [ "yui-base" ] }, "text-wordbreak": { "requires": [ "array-extras", "text-data-wordbreak" ] }, "timers": { "requires": [ "yui-base" ] }, "transition": { "requires": [ "node-style" ] }, "transition-timer": { "condition": { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }, "requires": [ "transition" ] }, "tree": { "requires": [ "base-build", "tree-node" ] }, "tree-labelable": { "requires": [ "tree" ] }, "tree-lazy": { "requires": [ "base-pluginhost", "plugin", "tree" ] }, "tree-node": {}, "tree-openable": { "requires": [ "tree" ] }, "tree-selectable": { "requires": [ "tree" ] }, "tree-sortable": { "requires": [ "tree" ] }, "uploader": { "requires": [ "uploader-html5", "uploader-flash" ] }, "uploader-flash": { "requires": [ "swfdetect", "escape", "widget", "base", "cssbutton", "node", "event-custom", "uploader-queue" ] }, "uploader-html5": { "requires": [ "widget", "node-event-simulate", "file-html5", "uploader-queue" ] }, "uploader-queue": { "requires": [ "base" ] }, "view": { "requires": [ "base-build", "node-event-delegate" ] }, "view-node-map": { "requires": [ "view" ] }, "widget": { "use": [ "widget-base", "widget-htmlparser", "widget-skin", "widget-uievents" ] }, "widget-anim": { "requires": [ "anim-base", "plugin", "widget" ] }, "widget-autohide": { "requires": [ "base-build", "event-key", "event-outside", "widget" ] }, "widget-base": { "requires": [ "attribute", "base-base", "base-pluginhost", "classnamemanager", "event-focus", "node-base", "node-style" ], "skinnable": true }, "widget-base-ie": { "condition": { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }, "requires": [ "widget-base" ] }, "widget-buttons": { "requires": [ "button-plugin", "cssbutton", "widget-stdmod" ] }, "widget-child": { "requires": [ "base-build", "widget" ] }, "widget-htmlparser": { "requires": [ "widget-base" ] }, "widget-modality": { "requires": [ "base-build", "event-outside", "widget" ], "skinnable": true }, "widget-parent": { "requires": [ "arraylist", "base-build", "widget" ] }, "widget-position": { "requires": [ "base-build", "node-screen", "widget" ] }, "widget-position-align": { "requires": [ "widget-position" ] }, "widget-position-constrain": { "requires": [ "widget-position" ] }, "widget-skin": { "requires": [ "widget-base" ] }, "widget-stack": { "requires": [ "base-build", "widget" ], "skinnable": true }, "widget-stdmod": { "requires": [ "base-build", "widget" ] }, "widget-uievents": { "requires": [ "node-event-delegate", "widget-base" ] }, "yql": { "requires": [ "oop" ] }, "yql-jsonp": { "condition": { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql" }, "requires": [ "yql", "jsonp", "jsonp-url" ] }, "yql-nodejs": { "condition": { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs" }, "requires": [ "yql" ] }, "yql-winjs": { "condition": { "name": "yql-winjs", "trigger": "yql", "ua": "winjs" }, "requires": [ "yql" ] }, "yui": {}, "yui-base": {}, "yui-later": { "requires": [ "yui-base" ] }, "yui-log": { "requires": [ "yui-base" ] }, "yui-throttle": { "requires": [ "yui-base" ] } }); YUI.Env[Y.version].md5 = '2fd2be6b12ee9f999b4367499ae61aae'; }, '3.18.1', {"requires": ["loader-base"]}); YUI.add('loader-pathogen-combohandler', function (Y, NAME) { /*jslint vars: true */ var GROUP_DELIM = ';', SUB_GROUP_DELIM = '+', MODULE_DELIM = ',', FILTER_RE = /-(min|debug).js/, EXTENSION_RE = /\.(?:js|css)$/, galleryVersion, GALLERY_RE = /^(?:yui:)?gallery-([^\/]+)/, TYPES = { js: true, css: true }, customComboBase; Y.mix(Y.Loader.prototype, { /** * Encodes combo urls based on modules and appends them to an object hash of arrays from `loader.resolve`. * * @method _pathogenEncodeComboSources * @param {Object} resolved The object hash of arrays in which to attach the encoded combo sources. * @return Object * @private */ _pathogenEncodeComboSources: function (resolved) { var combine = this.combine, resolvedUrls, maxURLLength, resolvedMods, comboUrls, urlKey, modKey, group, type; // Check to see if anything needs to be combined. if (!combine) { for (group in this.groups) { if (this.groups.hasOwnProperty(group)) { if (!combine && group.combine) { combine = group.combine; break; } } } } // Add the pathogen namespace to the combo base. if (Y.config.customComboBase) { customComboBase = Y.config.customComboBase; } if (customComboBase && combine) { maxURLLength = this.maxURLLength; for (type in TYPES) { /*jslint forin: false*/ if (!TYPES.hasOwnProperty(type)) { /*jslint forin: true*/ continue; } urlKey = type; modKey = type + 'Mods'; resolved[urlKey] = resolvedUrls = resolved[urlKey] || []; resolved[modKey] = resolvedMods = resolved[modKey] || []; // Generate custom combo urls. comboUrls = this._customResolve(resolvedMods, type); resolved[type] = resolved[type].concat(comboUrls); } } return resolved; }, /** Build each combo url from the bottom up. There's probably room for optimization here, but let's keep it simple for now. @method _customResolve @param {Array} modules A list of module meta. @param {String} type Either `js` or `css`. @return {String} Combo url. @private */ _customResolve: function (modules, type) { var source = this._aggregateGroups(modules), groups = this._sortAggregatedGroups(source), comboUrls = [], comboTail, filter, match, url; // Determine the combo tail (e.g., '.debug.js'). Assumption: `filter` is // global to the resolve() and should match the filter on loader. if (!filter) { match = FILTER_RE.exec(Y.config.loaderPath); filter = match && match[1] || 'raw'; filter = (type === 'css' && filter === 'debug') ? 'raw' : 'min'; comboTail = filter === 'min' ? '' : '.' + filter; comboTail = comboTail + '.' + type; } url = this._buildCombo(groups, customComboBase, comboTail); while (url) { comboUrls.push(url); url = this._buildCombo(groups, customComboBase, comboTail); } return comboUrls; }, /** Aggregate modules into groups with unique keys. The key is "$name+$version" for core and gallery groups, and just "$root" for all other groups. @method _aggregateGroups @param {Array} modules A list of module meta. @return {Object} Aggregated groups of module meta. @private */ _aggregateGroups: function (modules) { var source = {}, galleryMatch, meta, name, mod, key, len, i; // Segment the modules for efficient combo encoding. for (i = 0, len = modules.length; i < len; i += 1) { mod = modules[i]; name = mod.name; // Skip modules that should be loaded singly. This is kind of confusing // because it mimics the behavior of the loader (also confusing): // https://github.com/ekashida/yui3/blob/632167a36d57da7a884aacf0f4488dd5b8619c7c/src/loader/js/loader.js#L2563 meta = this.groups && this.groups[mod.group]; if (meta) { if (!meta.combine || mod.fullpath) { continue; } } else if (!this.combine) { continue; } if (!mod.combine && mod.ext) { continue; } // YUI core modules => core group if (!mod.group) { key = 'c' + SUB_GROUP_DELIM + YUI.version; } // YUI gallery modules => gallery group else if (mod.group === 'gallery') { if (!galleryVersion) { galleryMatch = GALLERY_RE.exec(this.groups.gallery.root); galleryVersion = galleryMatch && galleryMatch[1]; } name = name.split('gallery-').pop(); // remove prefix key = 'g' + SUB_GROUP_DELIM + galleryVersion; } // If the module was built the YUI way, then we segment these modules // into the `root` group. else if (mod.path.indexOf(name + '/' + name) === 0) { key = meta.root; // Trim '/' from both ends. if (key.charAt(0) === '/') { key = key.slice(1); } if (key.charAt(key.length - 1) === '/') { key = key.slice(0, -1); } key = 'r' + SUB_GROUP_DELIM + key; } // If the path does not follow the YUI build convention, then we // add them to the prefix tree and subsequently segment these modules // into the `path` group. else { // remove file extension name = mod.path.split(EXTENSION_RE).shift(); if (meta && meta.root) { name = meta.root + name; } if (name.charAt(0) === '/') { name = name.slice(1); } // Tag this module as `path` so that we know to include the // full path in the combo url later on key = 'path' + SUB_GROUP_DELIM + name; } source[key] = source[key] || []; source[key].push(name); } return source; }, /** Build each combo url from the bottom up. There's probably room for optimization here, but let's keep it simple for now. @method _buildCombo @param {Array} groups Grouped module meta. @param {String} comboBase The base of the combo url. @param {String} comboTail The tail of the combo url (e.g. .debug.js). @return {String} A combo url. @private */ _buildCombo: function (groups, comboBase, comboTail) { var comboUrl = comboBase, currLen = comboBase.length + comboTail.length, currDelim, currKey, prepend, modules, token, group, len, i; for (i = 0, len = groups.length; i < len; i += 1) { group = groups[i]; currDelim = comboUrl === comboBase ? '' : GROUP_DELIM; currKey = group.key; modules = group.modules; while (modules.length) { prepend = currDelim + currKey; prepend = prepend ? prepend + SUB_GROUP_DELIM : MODULE_DELIM; // Since modules with custom paths are treated as their own // segment, we override the prepend value so that it is only ever // set to the group delimiter. TODO: refactor this while loop into // one with multiple if-statements to make it easier to read. if (group.key.indexOf('path') === 0) { prepend = currDelim; } token = prepend + modules[0]; if (currLen + token.length < this.maxURLLength) { comboUrl += token; currLen += token.length; modules.shift(); } else { return comboUrl + comboTail; } currDelim = currKey = ''; } } comboUrl += comboTail; // If no modules were encoded in the combo url. if (comboUrl.length === comboBase.length + comboTail.length) { comboUrl = null; } return comboUrl; }, /** Sort the aggregated groups, and the modules within them. Minimizes cache misses in Yahoo's infrastructure by encoding predictable combo urls across browsers since iterating over an object does not guarantee order. @method _sortAggregatedGroups @param {Object} groups Aggregated groups. @return {Array} Sorted groups. @private **/ _sortAggregatedGroups: function (groups) { var sorted = [], key, len, i; for (key in groups) { if (groups.hasOwnProperty(key)) { sorted.push({ key: key, modules: groups[key] }); } } // Sort the groups. sorted.sort(function (a, b) { if(a.key < b.key) { return -1; } else if (a.key > b.key) { return 1; } else { return 0; } }); // Sort the modules. for (i = 0, len = sorted.length; i < len; i += 1) { sorted[i].modules.sort(); } return sorted; } }, true); }, '3.18.1'); YUI.add('loader-pathogen-encoder', function (Y, NAME) {}, '3.18.1', {"use": ["loader-base", "loader-rollup", "loader-yui3", "loader-pathogen-combohandler"]}); PK\qc53.18.1/datasource-function/datasource-function-min.jsnu[YUI.add("datasource-function",function(e,t){var n=e.Lang,r=function(){r.superclass.constructor.apply(this,arguments)};e.mix(r,{NAME:"dataSourceFunction",ATTRS:{source:{validator:n.isFunction}}}),e.extend(r,e.DataSource.Local,{_defRequestFn:function(e){var t=this.get("source"),n=e.details[0];if(t)try{n.data=t(e.request,this,e)}catch(r){n.error=r}else n.error=new Error("Function data failure");return this.fire("data",n),e.tId}}),e.DataSource.Function=r},"3.18.1",{requires:["datasource-local"]}); PK\lO  73.18.1/datasource-function/datasource-function-debug.jsnu[YUI.add('datasource-function', function (Y, NAME) { /** * Provides a DataSource implementation which can be used to retrieve data from * a custom function. * * @module datasource * @submodule datasource-function */ /** * Function subclass for the DataSource Utility. * @class DataSource.Function * @extends DataSource.Local * @constructor */ var LANG = Y.Lang, DSFn = function() { DSFn.superclass.constructor.apply(this, arguments); }; ///////////////////////////////////////////////////////////////////////////// // // DataSource.Function static properties // ///////////////////////////////////////////////////////////////////////////// Y.mix(DSFn, { /** * Class name. * * @property NAME * @type String * @static * @final * @value "dataSourceFunction" */ NAME: "dataSourceFunction", ///////////////////////////////////////////////////////////////////////////// // // DataSource.Function Attributes // ///////////////////////////////////////////////////////////////////////////// ATTRS: { /** * Stores the function that will serve the response data. * * @attribute source * @type {Any} * @default null */ source: { validator: LANG.isFunction } } }); Y.extend(DSFn, Y.DataSource.Local, { /** * Passes query data to the source function. Fires response * event with the function results (synchronously). * * @method _defRequestFn * @param e {EventFacade} Event Facade with the following properties: *
      *
      tId (Number)
      Unique transaction ID.
      *
      request (Object)
      The request.
      *
      callback (Object)
      The callback object with the following * properties: *
      *
      success (Function)
      Success handler.
      *
      failure (Function)
      Failure handler.
      *
      *
      *
      cfg (Object)
      Configuration object.
      *
      * @protected */ _defRequestFn: function(e) { var fn = this.get("source"), payload = e.details[0]; if (fn) { try { payload.data = fn(e.request, this, e); } catch (ex) { Y.log("Function execution failure", "error", "datasource-function"); payload.error = ex; } } else { Y.log("Function data failure", "error", "datasource-function"); payload.error = new Error("Function data failure"); } this.fire("data", payload); return e.tId; } }); Y.DataSource.Function = DSFn; }, '3.18.1', {"requires": ["datasource-local"]}); PK\:y y 13.18.1/datasource-function/datasource-function.jsnu[YUI.add('datasource-function', function (Y, NAME) { /** * Provides a DataSource implementation which can be used to retrieve data from * a custom function. * * @module datasource * @submodule datasource-function */ /** * Function subclass for the DataSource Utility. * @class DataSource.Function * @extends DataSource.Local * @constructor */ var LANG = Y.Lang, DSFn = function() { DSFn.superclass.constructor.apply(this, arguments); }; ///////////////////////////////////////////////////////////////////////////// // // DataSource.Function static properties // ///////////////////////////////////////////////////////////////////////////// Y.mix(DSFn, { /** * Class name. * * @property NAME * @type String * @static * @final * @value "dataSourceFunction" */ NAME: "dataSourceFunction", ///////////////////////////////////////////////////////////////////////////// // // DataSource.Function Attributes // ///////////////////////////////////////////////////////////////////////////// ATTRS: { /** * Stores the function that will serve the response data. * * @attribute source * @type {Any} * @default null */ source: { validator: LANG.isFunction } } }); Y.extend(DSFn, Y.DataSource.Local, { /** * Passes query data to the source function. Fires response * event with the function results (synchronously). * * @method _defRequestFn * @param e {EventFacade} Event Facade with the following properties: *
      *
      tId (Number)
      Unique transaction ID.
      *
      request (Object)
      The request.
      *
      callback (Object)
      The callback object with the following * properties: *
      *
      success (Function)
      Success handler.
      *
      failure (Function)
      Failure handler.
      *
      *
      *
      cfg (Object)
      Configuration object.
      *
      * @protected */ _defRequestFn: function(e) { var fn = this.get("source"), payload = e.details[0]; if (fn) { try { payload.data = fn(e.request, this, e); } catch (ex) { payload.error = ex; } } else { payload.error = new Error("Function data failure"); } this.fire("data", payload); return e.tId; } }); Y.DataSource.Function = DSFn; }, '3.18.1', {"requires": ["datasource-local"]}); PK\: #3.18.1/file-html5/file-html5-min.jsnu[YUI.add("file-html5",function(e,t){var n=e.Lang,r=e.bind,i=e.config.win,s=function(e){var t=null;s.isValidFile(e)?t=e:s.isValidFile(e.file)?t=e.file:t=!1,s.superclass.constructor.apply(this,arguments),t&&s.canUpload()&&(this.get("file")||this._set("file",t),this.get("name")||this._set("name",t.name||t.fileName),this.get("size")!=(t.size||t.fileSize)&&this._set("size",t.size||t.fileSize),this.get("type")||this._set("type",t.type),t.hasOwnProperty("lastModifiedDate")&&!this.get("dateModified")&&this._set("dateModified",t.lastModifiedDate))};e.extend(s,e.Base,{initializer:function(t){this.get("id")||this._set("id",e.guid("file"))},_uploadEventHandler:function(e){var t=this.get("xhr");switch(e.type){case"progress":this.fire("uploadprogress",{originEvent:e,bytesLoaded:e.loaded,bytesTotal:this.get("size"),percentLoaded:Math.min(100,Math.round(1e4*e.loaded/this.get("size"))/100)}),this._set("bytesUploaded",e.loaded);break;case"load":if(t.status>=200&&t.status<=299){this.fire("uploadcomplete",{originEvent:e,data:e.target.responseText});var n=t.upload,r=this.get("boundEventHandler");n.removeEventListener("progress",r),n.removeEventListener("error",r),n.removeEventListener("abort",r),t.removeEventListener("load",r),t.removeEventListener("error",r),t.removeEventListener("readystatechange",r),this._set("xhr",null)}else this.fire("uploaderror",{originEvent:e,data:t.responseText,status:t.status,statusText:t.statusText,source:"http"});break;case"error":this.fire("uploaderror",{originEvent:e,data:t.responseText,status:t.status,statusText:t.statusText,source:"io"});break;case"abort":this.fire("uploadcancel",{originEvent:e});break;case"readystatechange":this.fire("readystatechange",{readyState:e.target.readyState,originEvent:e})}},startUpload:function(t,n,i){this._set("bytesUploaded",0),this._set("xhr",new XMLHttpRequest),this._set("boundEventHandler",r(this._uploadEventHandler,this));var s=new FormData,o=i||"Filedata",u=this.get("xhr"),a=this.get("xhr").upload,f=this.get("boundEventHandler");e.each(n,function(e,t){s.append(t,e)}),s.append(o,this.get("file")),u.addEventListener("loadstart",f,!1),a.addEventListener("progress",f,!1),u.addEventListener("load",f,!1),u.addEventListener("error",f,!1),a.addEventListener("error",f,!1),a.addEventListener("abort",f,!1),u.addEventListener("abort",f,!1),u.addEventListener("loadend",f,!1),u.addEventListener("readystatechange",f,!1),u.open("POST",t,!0),u.withCredentials=this.get("xhrWithCredentials"),e.each(this.get("xhrHeaders"),function(e,t){u.setRequestHeader(t,e)}),u.send(s),this.fire("uploadstart",{xhr:u})},cancelUpload:function(){var e=this.get("xhr");e&&e.abort()}},{NAME:"file",TYPE:"html5",ATTRS:{id:{writeOnce:"initOnly",value:null},size:{writeOnce:"initOnly",value:0},name:{writeOnce:"initOnly",value:null},dateCreated:{writeOnce:"initOnly",value:null},dateModified:{writeOnce:"initOnly",value:null},bytesUploaded:{readOnly:!0,value:0},type:{writeOnce:"initOnly",value:null},file:{writeOnce:"initOnly",value:null},xhr:{readOnly:!0,value:null},xhrHeaders:{value:{}},xhrWithCredentials:{value:!0},boundEventHandler:{readOnly:!0,value:null}},isValidFile:function(e){return i&&i.File&&e instanceof File},canUpload:function(){return i&&i.FormData&&i.XMLHttpRequest}}),e.FileHTML5=s},"3.18.1",{requires:["base"]}); PK\;&`B`B3.18.1/file-html5/file-html5.jsnu[YUI.add('file-html5', function (Y, NAME) { /** * The FileHTML5 class provides a wrapper for a file pointer in an HTML5 The File wrapper * also implements the mechanics for uploading a file and tracking its progress. * @module file-html5 */ /** * The class provides a wrapper for a file pointer. * @class FileHTML5 * @extends Base * @constructor * @param {Object} config Configuration object. */ var Lang = Y.Lang, Bind = Y.bind, Win = Y.config.win; var FileHTML5 = function(o) { var file = null; if (FileHTML5.isValidFile(o)) { file = o; } else if (FileHTML5.isValidFile(o.file)) { file = o.file; } else { file = false; } FileHTML5.superclass.constructor.apply(this, arguments); if (file && FileHTML5.canUpload()) { if (!this.get("file")) { this._set("file", file); } if (!this.get("name")) { this._set("name", file.name || file.fileName); } if (this.get("size") != (file.size || file.fileSize)) { this._set("size", file.size || file.fileSize); } if (!this.get("type")) { this._set("type", file.type); } if (file.hasOwnProperty("lastModifiedDate") && !this.get("dateModified")) { this._set("dateModified", file.lastModifiedDate); } } }; Y.extend(FileHTML5, Y.Base, { /** * Construction logic executed during FileHTML5 instantiation. * * @method initializer * @protected */ initializer : function (cfg) { if (!this.get("id")) { this._set("id", Y.guid("file")); } }, /** * Handler of events dispatched by the XMLHTTPRequest. * * @method _uploadEventHandler * @param {Event} event The event object received from the XMLHTTPRequest. * @protected */ _uploadEventHandler: function (event) { var xhr = this.get("xhr"); switch (event.type) { case "progress": /** * Signals that progress has been made on the upload of this file. * * @event uploadprogress * @param event {Event} The event object for the `uploadprogress` with the * following payload: *
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      bytesLoaded
      *
      The number of bytes of the file that has been uploaded.
      *
      bytesTotal
      *
      The total number of bytes in the file (the file size)
      *
      percentLoaded
      *
      The fraction of the file that has been uploaded, out of 100.
      *
      */ this.fire("uploadprogress", {originEvent: event, bytesLoaded: event.loaded, bytesTotal: this.get("size"), percentLoaded: Math.min(100, Math.round(10000*event.loaded/this.get("size"))/100) }); this._set("bytesUploaded", event.loaded); break; case "load": /** * Signals that this file's upload has completed and data has been received from the server. * * @event uploadcomplete * @param event {Event} The event object for the `uploadcomplete` with the * following payload: *
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      data
      *
      The data returned by the server.
      *
      */ if (xhr.status >= 200 && xhr.status <= 299) { this.fire("uploadcomplete", {originEvent: event, data: event.target.responseText}); var xhrupload = xhr.upload, boundEventHandler = this.get("boundEventHandler"); xhrupload.removeEventListener ("progress", boundEventHandler); xhrupload.removeEventListener ("error", boundEventHandler); xhrupload.removeEventListener ("abort", boundEventHandler); xhr.removeEventListener ("load", boundEventHandler); xhr.removeEventListener ("error", boundEventHandler); xhr.removeEventListener ("readystatechange", boundEventHandler); this._set("xhr", null); } else { this.fire("uploaderror", {originEvent: event, data: xhr.responseText, status: xhr.status, statusText: xhr.statusText, source: "http"}); } break; case "error": /** * Signals that this file's upload has encountered an error. * * @event uploaderror * @param event {Event} The event object for the `uploaderror` with the * following payload: *
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      data
      *
      The data returned by the server.
      *
      status
      *
      The status code reported by the XMLHttpRequest. If it's an HTTP error, then this corresponds to the HTTP status code received by the uploader.
      *
      statusText
      *
      The text of the error event reported by the XMLHttpRequest instance
      *
      source
      *
      Either "http" (if it's an HTTP error), or "io" (if it's a network transmission * error.)
      * *
      */ this.fire("uploaderror", {originEvent: event, data: xhr.responseText, status: xhr.status, statusText: xhr.statusText, source: "io"}); break; case "abort": /** * Signals that this file's upload has been cancelled. * * @event uploadcancel * @param event {Event} The event object for the `uploadcancel` with the * following payload: *
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      */ this.fire("uploadcancel", {originEvent: event}); break; case "readystatechange": /** * Signals that XMLHttpRequest has fired a readystatechange event. * * @event readystatechange * @param event {Event} The event object for the `readystatechange` with the * following payload: *
      *
      readyState
      *
      The readyState code reported by the XMLHttpRequest instance.
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      */ this.fire("readystatechange", {readyState: event.target.readyState, originEvent: event}); break; } }, /** * Starts the upload of a specific file. * * @method startUpload * @param url {String} The URL to upload the file to. * @param parameters {Object} (optional) A set of key-value pairs to send as variables along with the file upload HTTP request. * @param fileFieldName {String} (optional) The name of the POST variable that should contain the uploaded file ('Filedata' by default) */ startUpload: function(url, parameters, fileFieldName) { this._set("bytesUploaded", 0); this._set("xhr", new XMLHttpRequest()); this._set("boundEventHandler", Bind(this._uploadEventHandler, this)); var uploadData = new FormData(), fileField = fileFieldName || "Filedata", xhr = this.get("xhr"), xhrupload = this.get("xhr").upload, boundEventHandler = this.get("boundEventHandler"); Y.each(parameters, function (value, key) {uploadData.append(key, value);}); uploadData.append(fileField, this.get("file")); xhr.addEventListener ("loadstart", boundEventHandler, false); xhrupload.addEventListener ("progress", boundEventHandler, false); xhr.addEventListener ("load", boundEventHandler, false); xhr.addEventListener ("error", boundEventHandler, false); xhrupload.addEventListener ("error", boundEventHandler, false); xhrupload.addEventListener ("abort", boundEventHandler, false); xhr.addEventListener ("abort", boundEventHandler, false); xhr.addEventListener ("loadend", boundEventHandler, false); xhr.addEventListener ("readystatechange", boundEventHandler, false); xhr.open("POST", url, true); xhr.withCredentials = this.get("xhrWithCredentials"); Y.each(this.get("xhrHeaders"), function (value, key) { xhr.setRequestHeader(key, value); }); xhr.send(uploadData); /** * Signals that this file's upload has started. * * @event uploadstart * @param event {Event} The event object for the `uploadstart` with the * following payload: *
      *
      xhr
      *
      The XMLHttpRequest instance handling the file upload.
      *
      */ this.fire("uploadstart", {xhr: xhr}); }, /** * Cancels the upload of a specific file, if currently in progress. * * @method cancelUpload */ cancelUpload: function () { var xhr = this.get('xhr'); if (xhr) { xhr.abort(); } } }, { /** * The identity of the class. * * @property NAME * @type String * @default 'file' * @readOnly * @protected * @static */ NAME: 'file', /** * The type of transport. * * @property TYPE * @type String * @default 'html5' * @readOnly * @protected * @static */ TYPE: 'html5', /** * Static property used to define the default attribute configuration of * the File. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * A String containing the unique id of the file wrapped by the FileFlash instance. * The id is supplied by the Flash player uploader. * * @attribute id * @type {String} * @initOnly */ id: { writeOnce: "initOnly", value: null }, /** * The size of the file wrapped by FileHTML5. This value is supplied by the instance of File(). * * @attribute size * @type {Number} * @initOnly */ size: { writeOnce: "initOnly", value: 0 }, /** * The name of the file wrapped by FileHTML5. This value is supplied by the instance of File(). * * @attribute name * @type {String} * @initOnly */ name: { writeOnce: "initOnly", value: null }, /** * The date that the file wrapped by FileHTML5 was created on. This value is supplied by the instance of File(). * * @attribute dateCreated * @type {Date} * @initOnly * @default null */ dateCreated: { writeOnce: "initOnly", value: null }, /** * The date that the file wrapped by FileHTML5 was last modified on. This value is supplied by the instance of File(). * * @attribute dateModified * @type {Date} * @initOnly */ dateModified: { writeOnce: "initOnly", value: null }, /** * The number of bytes of the file that has been uploaded to the server. This value is * non-zero only while a file is being uploaded. * * @attribute bytesUploaded * @type {Date} * @readOnly */ bytesUploaded: { readOnly: true, value: 0 }, /** * The type of the file wrapped by FileHTML. This value is provided by the instance of File() * * @attribute type * @type {String} * @initOnly */ type: { writeOnce: "initOnly", value: null }, /** * The pointer to the instance of File() wrapped by FileHTML5. * * @attribute file * @type {File} * @initOnly */ file: { writeOnce: "initOnly", value: null }, /** * The pointer to the instance of XMLHttpRequest used by FileHTML5 to upload the file. * * @attribute xhr * @type {XMLHttpRequest} * @initOnly */ xhr: { readOnly: true, value: null }, /** * The dictionary of headers that should be set on the XMLHttpRequest object before * sending it. * * @attribute xhrHeaders * @type {Object} * @initOnly */ xhrHeaders: { value: {} }, /** * A Boolean indicating whether the XMLHttpRequest should be sent with user credentials. * This does not affect same-site requests. * * @attribute xhrWithCredentials * @type {Boolean} * @initOnly */ xhrWithCredentials: { value: true }, /** * The bound event handler used to handle events from XMLHttpRequest. * * @attribute boundEventHandler * @type {Function} * @initOnly */ boundEventHandler: { readOnly: true, value: null } }, /** * Checks whether a specific native file instance is valid * * @method isValidFile * @param file {File} A native File() instance. * @static */ isValidFile: function (file) { return (Win && Win.File && file instanceof File); }, /** * Checks whether the browser has a native upload capability * via XMLHttpRequest Level 2. * * @method canUpload * @static */ canUpload: function () { return (Win && Win.FormData && Win.XMLHttpRequest); } }); Y.FileHTML5 = FileHTML5; }, '3.18.1', {"requires": ["base"]}); PK\;&`B`B%3.18.1/file-html5/file-html5-debug.jsnu[YUI.add('file-html5', function (Y, NAME) { /** * The FileHTML5 class provides a wrapper for a file pointer in an HTML5 The File wrapper * also implements the mechanics for uploading a file and tracking its progress. * @module file-html5 */ /** * The class provides a wrapper for a file pointer. * @class FileHTML5 * @extends Base * @constructor * @param {Object} config Configuration object. */ var Lang = Y.Lang, Bind = Y.bind, Win = Y.config.win; var FileHTML5 = function(o) { var file = null; if (FileHTML5.isValidFile(o)) { file = o; } else if (FileHTML5.isValidFile(o.file)) { file = o.file; } else { file = false; } FileHTML5.superclass.constructor.apply(this, arguments); if (file && FileHTML5.canUpload()) { if (!this.get("file")) { this._set("file", file); } if (!this.get("name")) { this._set("name", file.name || file.fileName); } if (this.get("size") != (file.size || file.fileSize)) { this._set("size", file.size || file.fileSize); } if (!this.get("type")) { this._set("type", file.type); } if (file.hasOwnProperty("lastModifiedDate") && !this.get("dateModified")) { this._set("dateModified", file.lastModifiedDate); } } }; Y.extend(FileHTML5, Y.Base, { /** * Construction logic executed during FileHTML5 instantiation. * * @method initializer * @protected */ initializer : function (cfg) { if (!this.get("id")) { this._set("id", Y.guid("file")); } }, /** * Handler of events dispatched by the XMLHTTPRequest. * * @method _uploadEventHandler * @param {Event} event The event object received from the XMLHTTPRequest. * @protected */ _uploadEventHandler: function (event) { var xhr = this.get("xhr"); switch (event.type) { case "progress": /** * Signals that progress has been made on the upload of this file. * * @event uploadprogress * @param event {Event} The event object for the `uploadprogress` with the * following payload: *
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      bytesLoaded
      *
      The number of bytes of the file that has been uploaded.
      *
      bytesTotal
      *
      The total number of bytes in the file (the file size)
      *
      percentLoaded
      *
      The fraction of the file that has been uploaded, out of 100.
      *
      */ this.fire("uploadprogress", {originEvent: event, bytesLoaded: event.loaded, bytesTotal: this.get("size"), percentLoaded: Math.min(100, Math.round(10000*event.loaded/this.get("size"))/100) }); this._set("bytesUploaded", event.loaded); break; case "load": /** * Signals that this file's upload has completed and data has been received from the server. * * @event uploadcomplete * @param event {Event} The event object for the `uploadcomplete` with the * following payload: *
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      data
      *
      The data returned by the server.
      *
      */ if (xhr.status >= 200 && xhr.status <= 299) { this.fire("uploadcomplete", {originEvent: event, data: event.target.responseText}); var xhrupload = xhr.upload, boundEventHandler = this.get("boundEventHandler"); xhrupload.removeEventListener ("progress", boundEventHandler); xhrupload.removeEventListener ("error", boundEventHandler); xhrupload.removeEventListener ("abort", boundEventHandler); xhr.removeEventListener ("load", boundEventHandler); xhr.removeEventListener ("error", boundEventHandler); xhr.removeEventListener ("readystatechange", boundEventHandler); this._set("xhr", null); } else { this.fire("uploaderror", {originEvent: event, data: xhr.responseText, status: xhr.status, statusText: xhr.statusText, source: "http"}); } break; case "error": /** * Signals that this file's upload has encountered an error. * * @event uploaderror * @param event {Event} The event object for the `uploaderror` with the * following payload: *
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      data
      *
      The data returned by the server.
      *
      status
      *
      The status code reported by the XMLHttpRequest. If it's an HTTP error, then this corresponds to the HTTP status code received by the uploader.
      *
      statusText
      *
      The text of the error event reported by the XMLHttpRequest instance
      *
      source
      *
      Either "http" (if it's an HTTP error), or "io" (if it's a network transmission * error.)
      * *
      */ this.fire("uploaderror", {originEvent: event, data: xhr.responseText, status: xhr.status, statusText: xhr.statusText, source: "io"}); break; case "abort": /** * Signals that this file's upload has been cancelled. * * @event uploadcancel * @param event {Event} The event object for the `uploadcancel` with the * following payload: *
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      */ this.fire("uploadcancel", {originEvent: event}); break; case "readystatechange": /** * Signals that XMLHttpRequest has fired a readystatechange event. * * @event readystatechange * @param event {Event} The event object for the `readystatechange` with the * following payload: *
      *
      readyState
      *
      The readyState code reported by the XMLHttpRequest instance.
      *
      originEvent
      *
      The original event fired by the XMLHttpRequest instance.
      *
      */ this.fire("readystatechange", {readyState: event.target.readyState, originEvent: event}); break; } }, /** * Starts the upload of a specific file. * * @method startUpload * @param url {String} The URL to upload the file to. * @param parameters {Object} (optional) A set of key-value pairs to send as variables along with the file upload HTTP request. * @param fileFieldName {String} (optional) The name of the POST variable that should contain the uploaded file ('Filedata' by default) */ startUpload: function(url, parameters, fileFieldName) { this._set("bytesUploaded", 0); this._set("xhr", new XMLHttpRequest()); this._set("boundEventHandler", Bind(this._uploadEventHandler, this)); var uploadData = new FormData(), fileField = fileFieldName || "Filedata", xhr = this.get("xhr"), xhrupload = this.get("xhr").upload, boundEventHandler = this.get("boundEventHandler"); Y.each(parameters, function (value, key) {uploadData.append(key, value);}); uploadData.append(fileField, this.get("file")); xhr.addEventListener ("loadstart", boundEventHandler, false); xhrupload.addEventListener ("progress", boundEventHandler, false); xhr.addEventListener ("load", boundEventHandler, false); xhr.addEventListener ("error", boundEventHandler, false); xhrupload.addEventListener ("error", boundEventHandler, false); xhrupload.addEventListener ("abort", boundEventHandler, false); xhr.addEventListener ("abort", boundEventHandler, false); xhr.addEventListener ("loadend", boundEventHandler, false); xhr.addEventListener ("readystatechange", boundEventHandler, false); xhr.open("POST", url, true); xhr.withCredentials = this.get("xhrWithCredentials"); Y.each(this.get("xhrHeaders"), function (value, key) { xhr.setRequestHeader(key, value); }); xhr.send(uploadData); /** * Signals that this file's upload has started. * * @event uploadstart * @param event {Event} The event object for the `uploadstart` with the * following payload: *
      *
      xhr
      *
      The XMLHttpRequest instance handling the file upload.
      *
      */ this.fire("uploadstart", {xhr: xhr}); }, /** * Cancels the upload of a specific file, if currently in progress. * * @method cancelUpload */ cancelUpload: function () { var xhr = this.get('xhr'); if (xhr) { xhr.abort(); } } }, { /** * The identity of the class. * * @property NAME * @type String * @default 'file' * @readOnly * @protected * @static */ NAME: 'file', /** * The type of transport. * * @property TYPE * @type String * @default 'html5' * @readOnly * @protected * @static */ TYPE: 'html5', /** * Static property used to define the default attribute configuration of * the File. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * A String containing the unique id of the file wrapped by the FileFlash instance. * The id is supplied by the Flash player uploader. * * @attribute id * @type {String} * @initOnly */ id: { writeOnce: "initOnly", value: null }, /** * The size of the file wrapped by FileHTML5. This value is supplied by the instance of File(). * * @attribute size * @type {Number} * @initOnly */ size: { writeOnce: "initOnly", value: 0 }, /** * The name of the file wrapped by FileHTML5. This value is supplied by the instance of File(). * * @attribute name * @type {String} * @initOnly */ name: { writeOnce: "initOnly", value: null }, /** * The date that the file wrapped by FileHTML5 was created on. This value is supplied by the instance of File(). * * @attribute dateCreated * @type {Date} * @initOnly * @default null */ dateCreated: { writeOnce: "initOnly", value: null }, /** * The date that the file wrapped by FileHTML5 was last modified on. This value is supplied by the instance of File(). * * @attribute dateModified * @type {Date} * @initOnly */ dateModified: { writeOnce: "initOnly", value: null }, /** * The number of bytes of the file that has been uploaded to the server. This value is * non-zero only while a file is being uploaded. * * @attribute bytesUploaded * @type {Date} * @readOnly */ bytesUploaded: { readOnly: true, value: 0 }, /** * The type of the file wrapped by FileHTML. This value is provided by the instance of File() * * @attribute type * @type {String} * @initOnly */ type: { writeOnce: "initOnly", value: null }, /** * The pointer to the instance of File() wrapped by FileHTML5. * * @attribute file * @type {File} * @initOnly */ file: { writeOnce: "initOnly", value: null }, /** * The pointer to the instance of XMLHttpRequest used by FileHTML5 to upload the file. * * @attribute xhr * @type {XMLHttpRequest} * @initOnly */ xhr: { readOnly: true, value: null }, /** * The dictionary of headers that should be set on the XMLHttpRequest object before * sending it. * * @attribute xhrHeaders * @type {Object} * @initOnly */ xhrHeaders: { value: {} }, /** * A Boolean indicating whether the XMLHttpRequest should be sent with user credentials. * This does not affect same-site requests. * * @attribute xhrWithCredentials * @type {Boolean} * @initOnly */ xhrWithCredentials: { value: true }, /** * The bound event handler used to handle events from XMLHttpRequest. * * @attribute boundEventHandler * @type {Function} * @initOnly */ boundEventHandler: { readOnly: true, value: null } }, /** * Checks whether a specific native file instance is valid * * @method isValidFile * @param file {File} A native File() instance. * @static */ isValidFile: function (file) { return (Win && Win.File && file instanceof File); }, /** * Checks whether the browser has a native upload capability * via XMLHttpRequest Level 2. * * @method canUpload * @static */ canUpload: function () { return (Win && Win.FormData && Win.XMLHttpRequest); } }); Y.FileHTML5 = FileHTML5; }, '3.18.1', {"requires": ["base"]}); PK\q/23.18.1/autocomplete-list/lang/autocomplete-list.jsnu[YUI.add("lang/autocomplete-list",function(e){e.Intl.add("autocomplete-list","",{item_selected:"{item} selected.",items_available:"Suggestions are available. Use the up and down arrow keys to select suggestions."})},"3.18.1"); PK\ 53.18.1/autocomplete-list/lang/autocomplete-list_es.jsnu[YUI.add("lang/autocomplete-list_es",function(e){e.Intl.add("autocomplete-list","es",{item_selected:"{item} seleccionado.",items_available:"Hay sugerencias disponibles. Use flecha arriba y abajo para seleccionar."})},"3.18.1"); PK\*DF  53.18.1/autocomplete-list/lang/autocomplete-list_hu.jsnu[YUI.add("lang/autocomplete-list_hu",function(e){e.Intl.add("autocomplete-list","hu",{item_selected:"{item} kiv\u00e1lasztva.",items_available:"Javaslatok \u00e1llnak rendelkez\u00e9sre. Haszn\u00e1lja a fel \u00e9s le nyilakat a v\u00e1laszt\u00e1shoz."})},"3.18.1"); PK\Bm53.18.1/autocomplete-list/lang/autocomplete-list_it.jsnu[YUI.add("lang/autocomplete-list_it",function(e){e.Intl.add("autocomplete-list","it",{item_selected:"{item} selezionato.",items_available:"Sono disponibili suggerimenti. Usa la freccia su e gi\u00f9 per selezionare."})},"3.18.1"); PK\{53.18.1/autocomplete-list/lang/autocomplete-list_en.jsnu[YUI.add("lang/autocomplete-list_en",function(e){e.Intl.add("autocomplete-list","en",{item_selected:"{item} selected.",items_available:"Suggestions are available. Use up and down arrows to select."})},"3.18.1"); PK\7?3.18.1/autocomplete-list/assets/skins/sam/autocomplete-list.cssnu[.yui3-aclist{position:absolute;z-index:1}.yui3-aclist-hidden{visibility:hidden}.yui3-aclist-aria{left:-9999px;position:absolute}.yui3-aclist-list{list-style:none;margin:0;overflow:hidden;padding:0}.yui3-aclist-item{cursor:pointer;list-style:none;padding:2px 5px}.yui3-aclist-item-active{outline:#afafaf dotted thin}.yui3-skin-sam .yui3-aclist-content{background:#fff;border:1px solid #afafaf;-moz-box-shadow:1px 1px 4px rgba(0,0,0,0.58);-webkit-box-shadow:1px 1px 4px rgba(0,0,0,0.58);box-shadow:1px 1px 4px rgba(0,0,0,0.58)}.yui3-skin-sam .yui3-aclist-item-hover{background:#bfdaff}.yui3-skin-sam .yui3-aclist-item-active{background:#2647a0;color:#fff;outline:0}#yui3-css-stamp.skin-sam-autocomplete-list{display:none} PK\u߹D3.18.1/autocomplete-list/assets/skins/sam/autocomplete-list-skin.cssnu[.yui3-skin-sam .yui3-aclist-content { background: #fff; border: 1px solid #afafaf; -moz-box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.58); -webkit-box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.58); box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.58); } .yui3-skin-sam .yui3-aclist-item-hover { background: #bfdaff; } .yui3-skin-sam .yui3-aclist-item-active { background: #2647a0; color: #fff; outline: none; } PK\1A3.18.1/autocomplete-list/assets/skins/night/autocomplete-list.cssnu[.yui3-aclist{position:absolute;z-index:1}.yui3-aclist-hidden{visibility:hidden}.yui3-aclist-aria{left:-9999px;position:absolute}.yui3-aclist-list{list-style:none;margin:0;overflow:hidden;padding:0}.yui3-aclist-item{cursor:pointer;list-style:none;padding:2px 5px}.yui3-aclist-item-active{outline:#afafaf dotted thin}.yui3-skin-night [for=ac-input]{color:#cbcbcb}.yui3-skin-night .yui3-aclist-content{font-size:100%;background-color:#151515;color:#ccc;border:1px solid #303030;-moz-box-shadow:0 0 17px rgba(0,0,0,0.58);-webkit-box-shadow:0 0 17px rgba(0,0,0,0.58);box-shadow:0 0 17px rgba(0,0,0,0.58)}.yui3-skin-night .yui3-aclist-item-active{background-color:#2f3030;background:-moz-linear-gradient(0% 100% 90deg,#252626 0,#333434 100%);background:-webkit-gradient(linear,left top,left bottom,from(#333434),to(#252626))}.yui3-skin-night .yui3-aclist-item-hover{background-color:#262727;background:-moz-linear-gradient(0% 100% 90deg,#202121 0,#282929 100%);background:-webkit-gradient(linear,left top,left bottom,from(#282929),to(#202121))}.yui3-skin-night .yui3-aclist-item{padding:0 1em;line-height:2.25}.yui3-skin-night .yui3-aclist-item-active{outline:0}.yui3-skin-night .yui3-highlight{color:#efefef}#yui3-css-stamp.skin-night-autocomplete-list{display:none} PK\.o0(F3.18.1/autocomplete-list/assets/skins/night/autocomplete-list-skin.cssnu[.yui3-skin-night [for=ac-input] { /* autocomplete label color */ color: #CBCBCB; } .yui3-skin-night .yui3-aclist-content { font-size: 100%; background-color: #151515; color: #ccc; border: 1px solid #303030; -moz-box-shadow: 0 0 17px rgba(0,0,0,0.58); -webkit-box-shadow: 0 0 17px rgba(0,0,0,0.58); box-shadow: 0 0 17px rgba(0,0,0,0.58); } .yui3-skin-night .yui3-aclist-item-active { background-color: #2F3030; background: -moz-linear-gradient( 0% 100% 90deg, #252626 0%, #333434 100% ); background: -webkit-gradient( linear, left top, left bottom, from(#333434), to(#252626) ); } .yui3-skin-night .yui3-aclist-item-hover { background-color: #262727; background: -moz-linear-gradient( 0% 100% 90deg, #202121 0%, #282929 100% ); background: -webkit-gradient( linear, left top, left bottom, from(#282929), to(#202121) ); } .yui3-skin-night .yui3-aclist-item { padding: 0 1em; /*0.4em 1em 0.6em*/ line-height: 2.25; } .yui3-skin-night .yui3-aclist-item-active { outline: none; } .yui3-skin-night .yui3-highlight { color:#EFEFEF; } PK\ѡ:3.18.1/autocomplete-list/assets/autocomplete-list-core.cssnu[.yui3-aclist { position: absolute; z-index: 1; } .yui3-aclist-hidden { visibility: hidden; } .yui3-aclist-aria { /* Hide from sighted users, show to screen readers. */ left: -9999px; position: absolute; } .yui3-aclist-list { list-style: none; margin: 0; overflow: hidden; padding: 0; } .yui3-aclist-item { cursor: pointer; list-style: none; padding: 2px 5px; } .yui3-aclist-item-active { outline: #afafaf dotted thin; } PK\ǷBp _ _-3.18.1/autocomplete-list/autocomplete-list.jsnu[YUI.add('autocomplete-list', function (Y, NAME) { /** Traditional autocomplete dropdown list widget, just like Mom used to make. @module autocomplete @submodule autocomplete-list **/ /** Traditional autocomplete dropdown list widget, just like Mom used to make. @class AutoCompleteList @extends Widget @uses AutoCompleteBase @uses WidgetPosition @uses WidgetPositionAlign @constructor @param {Object} config Configuration object. **/ var Lang = Y.Lang, Node = Y.Node, YArray = Y.Array, // Whether or not we need an iframe shim. useShim = Y.UA.ie && Y.UA.ie < 7, // keyCode constants. KEY_TAB = 9, // String shorthand. _CLASS_ITEM = '_CLASS_ITEM', _CLASS_ITEM_ACTIVE = '_CLASS_ITEM_ACTIVE', _CLASS_ITEM_HOVER = '_CLASS_ITEM_HOVER', _SELECTOR_ITEM = '_SELECTOR_ITEM', ACTIVE_ITEM = 'activeItem', ALWAYS_SHOW_LIST = 'alwaysShowList', CIRCULAR = 'circular', HOVERED_ITEM = 'hoveredItem', ID = 'id', ITEM = 'item', LIST = 'list', RESULT = 'result', RESULTS = 'results', VISIBLE = 'visible', WIDTH = 'width', // Event names. EVT_SELECT = 'select', List = Y.Base.create('autocompleteList', Y.Widget, [ Y.AutoCompleteBase, Y.WidgetPosition, Y.WidgetPositionAlign ], { // -- Prototype Properties ------------------------------------------------- ARIA_TEMPLATE: '
      ', ITEM_TEMPLATE: '
    • ', LIST_TEMPLATE: '
        ', // Widget automatically attaches delegated event handlers to everything in // Y.Node.DOM_EVENTS, including synthetic events. Since Widget's event // delegation won't work for the synthetic valuechange event, and since // it creates a name collision between the backcompat "valueChange" synth // event alias and AutoCompleteList's "valueChange" event for the "value" // attr, this hack is necessary in order to prevent Widget from attaching // valuechange handlers. UI_EVENTS: (function () { var uiEvents = Y.merge(Y.Node.DOM_EVENTS); delete uiEvents.valuechange; delete uiEvents.valueChange; return uiEvents; }()), // -- Lifecycle Prototype Methods ------------------------------------------ initializer: function () { var inputNode = this.get('inputNode'); if (!inputNode) { Y.error('No inputNode specified.'); return; } this._inputNode = inputNode; this._listEvents = []; // This ensures that the list is rendered inside the same parent as the // input node by default, which is necessary for proper ARIA support. this.DEF_PARENT_NODE = inputNode.get('parentNode'); // Cache commonly used classnames and selectors for performance. this[_CLASS_ITEM] = this.getClassName(ITEM); this[_CLASS_ITEM_ACTIVE] = this.getClassName(ITEM, 'active'); this[_CLASS_ITEM_HOVER] = this.getClassName(ITEM, 'hover'); this[_SELECTOR_ITEM] = '.' + this[_CLASS_ITEM]; /** Fires when an autocomplete suggestion is selected from the list, typically via a keyboard action or mouse click. @event select @param {Node} itemNode List item node that was selected. @param {Object} result AutoComplete result object. @preventable _defSelectFn **/ this.publish(EVT_SELECT, { defaultFn: this._defSelectFn }); }, destructor: function () { while (this._listEvents.length) { this._listEvents.pop().detach(); } if (this._ariaNode) { this._ariaNode.remove().destroy(true); } }, bindUI: function () { this._bindInput(); this._bindList(); }, renderUI: function () { var ariaNode = this._createAriaNode(), boundingBox = this.get('boundingBox'), contentBox = this.get('contentBox'), inputNode = this._inputNode, listNode = this._createListNode(), parentNode = inputNode.get('parentNode'); inputNode.addClass(this.getClassName('input')).setAttrs({ 'aria-autocomplete': LIST, 'aria-expanded' : false, 'aria-owns' : listNode.get('id') }); // ARIA node must be outside the widget or announcements won't be made // when the widget is hidden. parentNode.append(ariaNode); // Add an iframe shim for IE6. if (useShim) { boundingBox.plug(Y.Plugin.Shim); } this._ariaNode = ariaNode; this._boundingBox = boundingBox; this._contentBox = contentBox; this._listNode = listNode; this._parentNode = parentNode; }, syncUI: function () { // No need to call _syncPosition() here; the other _sync methods will // call it when necessary. this._syncResults(); this._syncVisibility(); }, // -- Public Prototype Methods --------------------------------------------- /** Hides the list, unless the `alwaysShowList` attribute is `true`. @method hide @see show @chainable **/ hide: function () { return this.get(ALWAYS_SHOW_LIST) ? this : this.set(VISIBLE, false); }, /** Selects the specified _itemNode_, or the current `activeItem` if _itemNode_ is not specified. @method selectItem @param {Node} [itemNode] Item node to select. @param {EventFacade} [originEvent] Event that triggered the selection, if any. @chainable **/ selectItem: function (itemNode, originEvent) { if (itemNode) { if (!itemNode.hasClass(this[_CLASS_ITEM])) { return this; } } else { itemNode = this.get(ACTIVE_ITEM); if (!itemNode) { return this; } } this.fire(EVT_SELECT, { itemNode : itemNode, originEvent: originEvent || null, result : itemNode.getData(RESULT) }); return this; }, // -- Protected Prototype Methods ------------------------------------------ /** Activates the next item after the currently active item. If there is no next item and the `circular` attribute is `true`, focus will wrap back to the input node. @method _activateNextItem @chainable @protected **/ _activateNextItem: function () { var item = this.get(ACTIVE_ITEM), nextItem; if (item) { nextItem = item.next(this[_SELECTOR_ITEM]) || (this.get(CIRCULAR) ? null : item); } else { nextItem = this._getFirstItemNode(); } this.set(ACTIVE_ITEM, nextItem); return this; }, /** Activates the item previous to the currently active item. If there is no previous item and the `circular` attribute is `true`, focus will wrap back to the input node. @method _activatePrevItem @chainable @protected **/ _activatePrevItem: function () { var item = this.get(ACTIVE_ITEM), prevItem = item ? item.previous(this[_SELECTOR_ITEM]) : this.get(CIRCULAR) && this._getLastItemNode(); this.set(ACTIVE_ITEM, prevItem || null); return this; }, /** Appends the specified result _items_ to the list inside a new item node. @method _add @param {Array|Node|HTMLElement|String} items Result item or array of result items. @return {NodeList} Added nodes. @protected **/ _add: function (items) { var itemNodes = []; YArray.each(Lang.isArray(items) ? items : [items], function (item) { itemNodes.push(this._createItemNode(item).setData(RESULT, item)); }, this); itemNodes = Y.all(itemNodes); this._listNode.append(itemNodes.toFrag()); return itemNodes; }, /** Updates the ARIA live region with the specified message. @method _ariaSay @param {String} stringId String id (from the `strings` attribute) of the message to speak. @param {Object} [subs] Substitutions for placeholders in the string. @protected **/ _ariaSay: function (stringId, subs) { var message = this.get('strings.' + stringId); this._ariaNode.set('text', subs ? Lang.sub(message, subs) : message); }, /** Binds `inputNode` events and behavior. @method _bindInput @protected **/ _bindInput: function () { var inputNode = this._inputNode, alignNode, alignWidth, tokenInput; // Null align means we can auto-align. Set align to false to prevent // auto-alignment, or a valid alignment config to customize the // alignment. if (this.get('align') === null) { // If this is a tokenInput, align with its bounding box. // Otherwise, align with the inputNode. Bit of a cheat. tokenInput = this.get('tokenInput'); alignNode = (tokenInput && tokenInput.get('boundingBox')) || inputNode; this.set('align', { node : alignNode, points: ['tl', 'bl'] }); // If no width config is set, attempt to set the list's width to the // width of the alignment node. If the alignment node's width is // falsy, do nothing. if (!this.get(WIDTH) && (alignWidth = alignNode.get('offsetWidth'))) { this.set(WIDTH, alignWidth); } } // Attach inputNode events. this._listEvents = this._listEvents.concat([ inputNode.after('blur', this._afterListInputBlur, this), inputNode.after('focus', this._afterListInputFocus, this) ]); }, /** Binds list events. @method _bindList @protected **/ _bindList: function () { this._listEvents = this._listEvents.concat([ Y.one('doc').after('click', this._afterDocClick, this), Y.one('win').after('windowresize', this._syncPosition, this), this.after({ mouseover: this._afterMouseOver, mouseout : this._afterMouseOut, activeItemChange : this._afterActiveItemChange, alwaysShowListChange: this._afterAlwaysShowListChange, hoveredItemChange : this._afterHoveredItemChange, resultsChange : this._afterResultsChange, visibleChange : this._afterVisibleChange }), this._listNode.delegate('click', this._onItemClick, this[_SELECTOR_ITEM], this) ]); }, /** Clears the contents of the tray. @method _clear @protected **/ _clear: function () { this.set(ACTIVE_ITEM, null); this._set(HOVERED_ITEM, null); this._listNode.get('children').remove(true); }, /** Creates and returns an ARIA live region node. @method _createAriaNode @return {Node} ARIA node. @protected **/ _createAriaNode: function () { var ariaNode = Node.create(this.ARIA_TEMPLATE); return ariaNode.addClass(this.getClassName('aria')).setAttrs({ 'aria-live': 'polite', role : 'status' }); }, /** Creates and returns an item node with the specified _content_. @method _createItemNode @param {Object} result Result object. @return {Node} Item node. @protected **/ _createItemNode: function (result) { var itemNode = Node.create(this.ITEM_TEMPLATE); return itemNode.addClass(this[_CLASS_ITEM]).setAttrs({ id : Y.stamp(itemNode), role: 'option' }).setAttribute('data-text', result.text).append(result.display); }, /** Creates and returns a list node. If the `listNode` attribute is already set to an existing node, that node will be used. @method _createListNode @return {Node} List node. @protected **/ _createListNode: function () { var listNode = this.get('listNode') || Node.create(this.LIST_TEMPLATE); listNode.addClass(this.getClassName(LIST)).setAttrs({ id : Y.stamp(listNode), role: 'listbox' }); this._set('listNode', listNode); this.get('contentBox').append(listNode); return listNode; }, /** Gets the first item node in the list, or `null` if the list is empty. @method _getFirstItemNode @return {Node|null} @protected **/ _getFirstItemNode: function () { return this._listNode.one(this[_SELECTOR_ITEM]); }, /** Gets the last item node in the list, or `null` if the list is empty. @method _getLastItemNode @return {Node|null} @protected **/ _getLastItemNode: function () { return this._listNode.one(this[_SELECTOR_ITEM] + ':last-child'); }, /** Synchronizes the result list's position and alignment. @method _syncPosition @protected **/ _syncPosition: function () { // Force WidgetPositionAlign to refresh its alignment. this._syncUIPosAlign(); // Resize the IE6 iframe shim to match the list's dimensions. this._syncShim(); }, /** Synchronizes the results displayed in the list with those in the _results_ argument, or with the `results` attribute if an argument is not provided. @method _syncResults @param {Array} [results] Results. @protected **/ _syncResults: function (results) { if (!results) { results = this.get(RESULTS); } this._clear(); if (results.length) { this._add(results); this._ariaSay('items_available'); } this._syncPosition(); if (this.get('activateFirstItem') && !this.get(ACTIVE_ITEM)) { this.set(ACTIVE_ITEM, this._getFirstItemNode()); } }, /** Synchronizes the size of the iframe shim used for IE6 and lower. In other browsers, this method is a noop. @method _syncShim @protected **/ _syncShim: useShim ? function () { var shim = this._boundingBox.shim; if (shim) { shim.sync(); } } : function () {}, /** Synchronizes the visibility of the tray with the _visible_ argument, or with the `visible` attribute if an argument is not provided. @method _syncVisibility @param {Boolean} [visible] Visibility. @protected **/ _syncVisibility: function (visible) { if (this.get(ALWAYS_SHOW_LIST)) { visible = true; this.set(VISIBLE, visible); } if (typeof visible === 'undefined') { visible = this.get(VISIBLE); } this._inputNode.set('aria-expanded', visible); this._boundingBox.set('aria-hidden', !visible); if (visible) { this._syncPosition(); } else { this.set(ACTIVE_ITEM, null); this._set(HOVERED_ITEM, null); // Force a reflow to work around a glitch in IE6 and 7 where some of // the contents of the list will sometimes remain visible after the // container is hidden. this._boundingBox.get('offsetWidth'); } // In some pages, IE7 fails to repaint the contents of the list after it // becomes visible. Toggling a bogus class on the body forces a repaint // that fixes the issue. if (Y.UA.ie === 7) { // Note: We don't actually need to use ClassNameManager here. This // class isn't applying any actual styles; it's just frobbing the // body element to force a repaint. The actual class name doesn't // really matter. Y.one('body') .addClass('yui3-ie7-sucks') .removeClass('yui3-ie7-sucks'); } }, // -- Protected Event Handlers --------------------------------------------- /** Handles `activeItemChange` events. @method _afterActiveItemChange @param {EventFacade} e @protected **/ _afterActiveItemChange: function (e) { var inputNode = this._inputNode, newVal = e.newVal, prevVal = e.prevVal, node; // The previous item may have disappeared by the time this handler runs, // so we need to be careful. if (prevVal && prevVal._node) { prevVal.removeClass(this[_CLASS_ITEM_ACTIVE]); } if (newVal) { newVal.addClass(this[_CLASS_ITEM_ACTIVE]); inputNode.set('aria-activedescendant', newVal.get(ID)); } else { inputNode.removeAttribute('aria-activedescendant'); } if (this.get('scrollIntoView')) { node = newVal || inputNode; if (!node.inRegion(Y.DOM.viewportRegion(), true) || !node.inRegion(this._contentBox, true)) { node.scrollIntoView(); } } }, /** Handles `alwaysShowListChange` events. @method _afterAlwaysShowListChange @param {EventFacade} e @protected **/ _afterAlwaysShowListChange: function (e) { this.set(VISIBLE, e.newVal || this.get(RESULTS).length > 0); }, /** Handles click events on the document. If the click is outside both the input node and the bounding box, the list will be hidden. @method _afterDocClick @param {EventFacade} e @protected @since 3.5.0 **/ _afterDocClick: function (e) { var boundingBox = this._boundingBox, target = e.target; if (target !== this._inputNode && target !== boundingBox && !target.ancestor('#' + boundingBox.get('id'), true)){ this.hide(); } }, /** Handles `hoveredItemChange` events. @method _afterHoveredItemChange @param {EventFacade} e @protected **/ _afterHoveredItemChange: function (e) { var newVal = e.newVal, prevVal = e.prevVal; if (prevVal) { prevVal.removeClass(this[_CLASS_ITEM_HOVER]); } if (newVal) { newVal.addClass(this[_CLASS_ITEM_HOVER]); } }, /** Handles `inputNode` blur events. @method _afterListInputBlur @protected **/ _afterListInputBlur: function () { this._listInputFocused = false; if (this.get(VISIBLE) && !this._mouseOverList && (this._lastInputKey !== KEY_TAB || !this.get('tabSelect') || !this.get(ACTIVE_ITEM))) { this.hide(); } }, /** Handles `inputNode` focus events. @method _afterListInputFocus @protected **/ _afterListInputFocus: function () { this._listInputFocused = true; }, /** Handles `mouseover` events. @method _afterMouseOver @param {EventFacade} e @protected **/ _afterMouseOver: function (e) { var itemNode = e.domEvent.target.ancestor(this[_SELECTOR_ITEM], true); this._mouseOverList = true; if (itemNode) { this._set(HOVERED_ITEM, itemNode); } }, /** Handles `mouseout` events. @method _afterMouseOut @param {EventFacade} e @protected **/ _afterMouseOut: function () { this._mouseOverList = false; this._set(HOVERED_ITEM, null); }, /** Handles `resultsChange` events. @method _afterResultsChange @param {EventFacade} e @protected **/ _afterResultsChange: function (e) { this._syncResults(e.newVal); if (!this.get(ALWAYS_SHOW_LIST)) { this.set(VISIBLE, !!e.newVal.length); } }, /** Handles `visibleChange` events. @method _afterVisibleChange @param {EventFacade} e @protected **/ _afterVisibleChange: function (e) { this._syncVisibility(!!e.newVal); }, /** Delegated event handler for item `click` events. @method _onItemClick @param {EventFacade} e @protected **/ _onItemClick: function (e) { var itemNode = e.currentTarget; this.set(ACTIVE_ITEM, itemNode); this.selectItem(itemNode, e); }, // -- Protected Default Event Handlers ------------------------------------- /** Default `select` event handler. @method _defSelectFn @param {EventFacade} e @protected **/ _defSelectFn: function (e) { var text = e.result.text; // TODO: support typeahead completion, etc. this._inputNode.focus(); this._updateValue(text); this._ariaSay('item_selected', {item: text}); this.hide(); } }, { ATTRS: { /** If `true`, the first item in the list will be activated by default when the list is initially displayed and when results change. @attribute activateFirstItem @type Boolean @default false **/ activateFirstItem: { value: false }, /** Item that's currently active, if any. When the user presses enter, this is the item that will be selected. @attribute activeItem @type Node **/ activeItem: { setter: Y.one, value: null }, /** If `true`, the list will remain visible even when there are no results to display. @attribute alwaysShowList @type Boolean @default false **/ alwaysShowList: { value: false }, /** If `true`, keyboard navigation will wrap around to the opposite end of the list when navigating past the first or last item. @attribute circular @type Boolean @default true **/ circular: { value: true }, /** Item currently being hovered over by the mouse, if any. @attribute hoveredItem @type Node|null @readOnly **/ hoveredItem: { readOnly: true, value: null }, /** Node that will contain result items. @attribute listNode @type Node|null @initOnly **/ listNode: { writeOnce: 'initOnly', value: null }, /** If `true`, the viewport will be scrolled to ensure that the active list item is visible when necessary. @attribute scrollIntoView @type Boolean @default false **/ scrollIntoView: { value: false }, /** Translatable strings used by the AutoCompleteList widget. @attribute strings @type Object **/ strings: { valueFn: function () { return Y.Intl.get('autocomplete-list'); } }, /** If `true`, pressing the tab key while the list is visible will select the active item, if any. @attribute tabSelect @type Boolean @default true **/ tabSelect: { value: true }, // The "visible" attribute is documented in Widget. visible: { value: false } }, CSS_PREFIX: Y.ClassNameManager.getClassName('aclist') }); Y.AutoCompleteList = List; /** Alias for `AutoCompleteList`. See that class for API docs. @class AutoComplete **/ Y.AutoComplete = List; }, '3.18.1', { "lang": [ "en", "es", "hu", "it" ], "requires": [ "autocomplete-base", "event-resize", "node-screen", "selector-css3", "shim-plugin", "widget", "widget-position", "widget-position-align" ], "skinnable": true }); PK\ǷBp _ _33.18.1/autocomplete-list/autocomplete-list-debug.jsnu[YUI.add('autocomplete-list', function (Y, NAME) { /** Traditional autocomplete dropdown list widget, just like Mom used to make. @module autocomplete @submodule autocomplete-list **/ /** Traditional autocomplete dropdown list widget, just like Mom used to make. @class AutoCompleteList @extends Widget @uses AutoCompleteBase @uses WidgetPosition @uses WidgetPositionAlign @constructor @param {Object} config Configuration object. **/ var Lang = Y.Lang, Node = Y.Node, YArray = Y.Array, // Whether or not we need an iframe shim. useShim = Y.UA.ie && Y.UA.ie < 7, // keyCode constants. KEY_TAB = 9, // String shorthand. _CLASS_ITEM = '_CLASS_ITEM', _CLASS_ITEM_ACTIVE = '_CLASS_ITEM_ACTIVE', _CLASS_ITEM_HOVER = '_CLASS_ITEM_HOVER', _SELECTOR_ITEM = '_SELECTOR_ITEM', ACTIVE_ITEM = 'activeItem', ALWAYS_SHOW_LIST = 'alwaysShowList', CIRCULAR = 'circular', HOVERED_ITEM = 'hoveredItem', ID = 'id', ITEM = 'item', LIST = 'list', RESULT = 'result', RESULTS = 'results', VISIBLE = 'visible', WIDTH = 'width', // Event names. EVT_SELECT = 'select', List = Y.Base.create('autocompleteList', Y.Widget, [ Y.AutoCompleteBase, Y.WidgetPosition, Y.WidgetPositionAlign ], { // -- Prototype Properties ------------------------------------------------- ARIA_TEMPLATE: '
        ', ITEM_TEMPLATE: '
      • ', LIST_TEMPLATE: '
          ', // Widget automatically attaches delegated event handlers to everything in // Y.Node.DOM_EVENTS, including synthetic events. Since Widget's event // delegation won't work for the synthetic valuechange event, and since // it creates a name collision between the backcompat "valueChange" synth // event alias and AutoCompleteList's "valueChange" event for the "value" // attr, this hack is necessary in order to prevent Widget from attaching // valuechange handlers. UI_EVENTS: (function () { var uiEvents = Y.merge(Y.Node.DOM_EVENTS); delete uiEvents.valuechange; delete uiEvents.valueChange; return uiEvents; }()), // -- Lifecycle Prototype Methods ------------------------------------------ initializer: function () { var inputNode = this.get('inputNode'); if (!inputNode) { Y.error('No inputNode specified.'); return; } this._inputNode = inputNode; this._listEvents = []; // This ensures that the list is rendered inside the same parent as the // input node by default, which is necessary for proper ARIA support. this.DEF_PARENT_NODE = inputNode.get('parentNode'); // Cache commonly used classnames and selectors for performance. this[_CLASS_ITEM] = this.getClassName(ITEM); this[_CLASS_ITEM_ACTIVE] = this.getClassName(ITEM, 'active'); this[_CLASS_ITEM_HOVER] = this.getClassName(ITEM, 'hover'); this[_SELECTOR_ITEM] = '.' + this[_CLASS_ITEM]; /** Fires when an autocomplete suggestion is selected from the list, typically via a keyboard action or mouse click. @event select @param {Node} itemNode List item node that was selected. @param {Object} result AutoComplete result object. @preventable _defSelectFn **/ this.publish(EVT_SELECT, { defaultFn: this._defSelectFn }); }, destructor: function () { while (this._listEvents.length) { this._listEvents.pop().detach(); } if (this._ariaNode) { this._ariaNode.remove().destroy(true); } }, bindUI: function () { this._bindInput(); this._bindList(); }, renderUI: function () { var ariaNode = this._createAriaNode(), boundingBox = this.get('boundingBox'), contentBox = this.get('contentBox'), inputNode = this._inputNode, listNode = this._createListNode(), parentNode = inputNode.get('parentNode'); inputNode.addClass(this.getClassName('input')).setAttrs({ 'aria-autocomplete': LIST, 'aria-expanded' : false, 'aria-owns' : listNode.get('id') }); // ARIA node must be outside the widget or announcements won't be made // when the widget is hidden. parentNode.append(ariaNode); // Add an iframe shim for IE6. if (useShim) { boundingBox.plug(Y.Plugin.Shim); } this._ariaNode = ariaNode; this._boundingBox = boundingBox; this._contentBox = contentBox; this._listNode = listNode; this._parentNode = parentNode; }, syncUI: function () { // No need to call _syncPosition() here; the other _sync methods will // call it when necessary. this._syncResults(); this._syncVisibility(); }, // -- Public Prototype Methods --------------------------------------------- /** Hides the list, unless the `alwaysShowList` attribute is `true`. @method hide @see show @chainable **/ hide: function () { return this.get(ALWAYS_SHOW_LIST) ? this : this.set(VISIBLE, false); }, /** Selects the specified _itemNode_, or the current `activeItem` if _itemNode_ is not specified. @method selectItem @param {Node} [itemNode] Item node to select. @param {EventFacade} [originEvent] Event that triggered the selection, if any. @chainable **/ selectItem: function (itemNode, originEvent) { if (itemNode) { if (!itemNode.hasClass(this[_CLASS_ITEM])) { return this; } } else { itemNode = this.get(ACTIVE_ITEM); if (!itemNode) { return this; } } this.fire(EVT_SELECT, { itemNode : itemNode, originEvent: originEvent || null, result : itemNode.getData(RESULT) }); return this; }, // -- Protected Prototype Methods ------------------------------------------ /** Activates the next item after the currently active item. If there is no next item and the `circular` attribute is `true`, focus will wrap back to the input node. @method _activateNextItem @chainable @protected **/ _activateNextItem: function () { var item = this.get(ACTIVE_ITEM), nextItem; if (item) { nextItem = item.next(this[_SELECTOR_ITEM]) || (this.get(CIRCULAR) ? null : item); } else { nextItem = this._getFirstItemNode(); } this.set(ACTIVE_ITEM, nextItem); return this; }, /** Activates the item previous to the currently active item. If there is no previous item and the `circular` attribute is `true`, focus will wrap back to the input node. @method _activatePrevItem @chainable @protected **/ _activatePrevItem: function () { var item = this.get(ACTIVE_ITEM), prevItem = item ? item.previous(this[_SELECTOR_ITEM]) : this.get(CIRCULAR) && this._getLastItemNode(); this.set(ACTIVE_ITEM, prevItem || null); return this; }, /** Appends the specified result _items_ to the list inside a new item node. @method _add @param {Array|Node|HTMLElement|String} items Result item or array of result items. @return {NodeList} Added nodes. @protected **/ _add: function (items) { var itemNodes = []; YArray.each(Lang.isArray(items) ? items : [items], function (item) { itemNodes.push(this._createItemNode(item).setData(RESULT, item)); }, this); itemNodes = Y.all(itemNodes); this._listNode.append(itemNodes.toFrag()); return itemNodes; }, /** Updates the ARIA live region with the specified message. @method _ariaSay @param {String} stringId String id (from the `strings` attribute) of the message to speak. @param {Object} [subs] Substitutions for placeholders in the string. @protected **/ _ariaSay: function (stringId, subs) { var message = this.get('strings.' + stringId); this._ariaNode.set('text', subs ? Lang.sub(message, subs) : message); }, /** Binds `inputNode` events and behavior. @method _bindInput @protected **/ _bindInput: function () { var inputNode = this._inputNode, alignNode, alignWidth, tokenInput; // Null align means we can auto-align. Set align to false to prevent // auto-alignment, or a valid alignment config to customize the // alignment. if (this.get('align') === null) { // If this is a tokenInput, align with its bounding box. // Otherwise, align with the inputNode. Bit of a cheat. tokenInput = this.get('tokenInput'); alignNode = (tokenInput && tokenInput.get('boundingBox')) || inputNode; this.set('align', { node : alignNode, points: ['tl', 'bl'] }); // If no width config is set, attempt to set the list's width to the // width of the alignment node. If the alignment node's width is // falsy, do nothing. if (!this.get(WIDTH) && (alignWidth = alignNode.get('offsetWidth'))) { this.set(WIDTH, alignWidth); } } // Attach inputNode events. this._listEvents = this._listEvents.concat([ inputNode.after('blur', this._afterListInputBlur, this), inputNode.after('focus', this._afterListInputFocus, this) ]); }, /** Binds list events. @method _bindList @protected **/ _bindList: function () { this._listEvents = this._listEvents.concat([ Y.one('doc').after('click', this._afterDocClick, this), Y.one('win').after('windowresize', this._syncPosition, this), this.after({ mouseover: this._afterMouseOver, mouseout : this._afterMouseOut, activeItemChange : this._afterActiveItemChange, alwaysShowListChange: this._afterAlwaysShowListChange, hoveredItemChange : this._afterHoveredItemChange, resultsChange : this._afterResultsChange, visibleChange : this._afterVisibleChange }), this._listNode.delegate('click', this._onItemClick, this[_SELECTOR_ITEM], this) ]); }, /** Clears the contents of the tray. @method _clear @protected **/ _clear: function () { this.set(ACTIVE_ITEM, null); this._set(HOVERED_ITEM, null); this._listNode.get('children').remove(true); }, /** Creates and returns an ARIA live region node. @method _createAriaNode @return {Node} ARIA node. @protected **/ _createAriaNode: function () { var ariaNode = Node.create(this.ARIA_TEMPLATE); return ariaNode.addClass(this.getClassName('aria')).setAttrs({ 'aria-live': 'polite', role : 'status' }); }, /** Creates and returns an item node with the specified _content_. @method _createItemNode @param {Object} result Result object. @return {Node} Item node. @protected **/ _createItemNode: function (result) { var itemNode = Node.create(this.ITEM_TEMPLATE); return itemNode.addClass(this[_CLASS_ITEM]).setAttrs({ id : Y.stamp(itemNode), role: 'option' }).setAttribute('data-text', result.text).append(result.display); }, /** Creates and returns a list node. If the `listNode` attribute is already set to an existing node, that node will be used. @method _createListNode @return {Node} List node. @protected **/ _createListNode: function () { var listNode = this.get('listNode') || Node.create(this.LIST_TEMPLATE); listNode.addClass(this.getClassName(LIST)).setAttrs({ id : Y.stamp(listNode), role: 'listbox' }); this._set('listNode', listNode); this.get('contentBox').append(listNode); return listNode; }, /** Gets the first item node in the list, or `null` if the list is empty. @method _getFirstItemNode @return {Node|null} @protected **/ _getFirstItemNode: function () { return this._listNode.one(this[_SELECTOR_ITEM]); }, /** Gets the last item node in the list, or `null` if the list is empty. @method _getLastItemNode @return {Node|null} @protected **/ _getLastItemNode: function () { return this._listNode.one(this[_SELECTOR_ITEM] + ':last-child'); }, /** Synchronizes the result list's position and alignment. @method _syncPosition @protected **/ _syncPosition: function () { // Force WidgetPositionAlign to refresh its alignment. this._syncUIPosAlign(); // Resize the IE6 iframe shim to match the list's dimensions. this._syncShim(); }, /** Synchronizes the results displayed in the list with those in the _results_ argument, or with the `results` attribute if an argument is not provided. @method _syncResults @param {Array} [results] Results. @protected **/ _syncResults: function (results) { if (!results) { results = this.get(RESULTS); } this._clear(); if (results.length) { this._add(results); this._ariaSay('items_available'); } this._syncPosition(); if (this.get('activateFirstItem') && !this.get(ACTIVE_ITEM)) { this.set(ACTIVE_ITEM, this._getFirstItemNode()); } }, /** Synchronizes the size of the iframe shim used for IE6 and lower. In other browsers, this method is a noop. @method _syncShim @protected **/ _syncShim: useShim ? function () { var shim = this._boundingBox.shim; if (shim) { shim.sync(); } } : function () {}, /** Synchronizes the visibility of the tray with the _visible_ argument, or with the `visible` attribute if an argument is not provided. @method _syncVisibility @param {Boolean} [visible] Visibility. @protected **/ _syncVisibility: function (visible) { if (this.get(ALWAYS_SHOW_LIST)) { visible = true; this.set(VISIBLE, visible); } if (typeof visible === 'undefined') { visible = this.get(VISIBLE); } this._inputNode.set('aria-expanded', visible); this._boundingBox.set('aria-hidden', !visible); if (visible) { this._syncPosition(); } else { this.set(ACTIVE_ITEM, null); this._set(HOVERED_ITEM, null); // Force a reflow to work around a glitch in IE6 and 7 where some of // the contents of the list will sometimes remain visible after the // container is hidden. this._boundingBox.get('offsetWidth'); } // In some pages, IE7 fails to repaint the contents of the list after it // becomes visible. Toggling a bogus class on the body forces a repaint // that fixes the issue. if (Y.UA.ie === 7) { // Note: We don't actually need to use ClassNameManager here. This // class isn't applying any actual styles; it's just frobbing the // body element to force a repaint. The actual class name doesn't // really matter. Y.one('body') .addClass('yui3-ie7-sucks') .removeClass('yui3-ie7-sucks'); } }, // -- Protected Event Handlers --------------------------------------------- /** Handles `activeItemChange` events. @method _afterActiveItemChange @param {EventFacade} e @protected **/ _afterActiveItemChange: function (e) { var inputNode = this._inputNode, newVal = e.newVal, prevVal = e.prevVal, node; // The previous item may have disappeared by the time this handler runs, // so we need to be careful. if (prevVal && prevVal._node) { prevVal.removeClass(this[_CLASS_ITEM_ACTIVE]); } if (newVal) { newVal.addClass(this[_CLASS_ITEM_ACTIVE]); inputNode.set('aria-activedescendant', newVal.get(ID)); } else { inputNode.removeAttribute('aria-activedescendant'); } if (this.get('scrollIntoView')) { node = newVal || inputNode; if (!node.inRegion(Y.DOM.viewportRegion(), true) || !node.inRegion(this._contentBox, true)) { node.scrollIntoView(); } } }, /** Handles `alwaysShowListChange` events. @method _afterAlwaysShowListChange @param {EventFacade} e @protected **/ _afterAlwaysShowListChange: function (e) { this.set(VISIBLE, e.newVal || this.get(RESULTS).length > 0); }, /** Handles click events on the document. If the click is outside both the input node and the bounding box, the list will be hidden. @method _afterDocClick @param {EventFacade} e @protected @since 3.5.0 **/ _afterDocClick: function (e) { var boundingBox = this._boundingBox, target = e.target; if (target !== this._inputNode && target !== boundingBox && !target.ancestor('#' + boundingBox.get('id'), true)){ this.hide(); } }, /** Handles `hoveredItemChange` events. @method _afterHoveredItemChange @param {EventFacade} e @protected **/ _afterHoveredItemChange: function (e) { var newVal = e.newVal, prevVal = e.prevVal; if (prevVal) { prevVal.removeClass(this[_CLASS_ITEM_HOVER]); } if (newVal) { newVal.addClass(this[_CLASS_ITEM_HOVER]); } }, /** Handles `inputNode` blur events. @method _afterListInputBlur @protected **/ _afterListInputBlur: function () { this._listInputFocused = false; if (this.get(VISIBLE) && !this._mouseOverList && (this._lastInputKey !== KEY_TAB || !this.get('tabSelect') || !this.get(ACTIVE_ITEM))) { this.hide(); } }, /** Handles `inputNode` focus events. @method _afterListInputFocus @protected **/ _afterListInputFocus: function () { this._listInputFocused = true; }, /** Handles `mouseover` events. @method _afterMouseOver @param {EventFacade} e @protected **/ _afterMouseOver: function (e) { var itemNode = e.domEvent.target.ancestor(this[_SELECTOR_ITEM], true); this._mouseOverList = true; if (itemNode) { this._set(HOVERED_ITEM, itemNode); } }, /** Handles `mouseout` events. @method _afterMouseOut @param {EventFacade} e @protected **/ _afterMouseOut: function () { this._mouseOverList = false; this._set(HOVERED_ITEM, null); }, /** Handles `resultsChange` events. @method _afterResultsChange @param {EventFacade} e @protected **/ _afterResultsChange: function (e) { this._syncResults(e.newVal); if (!this.get(ALWAYS_SHOW_LIST)) { this.set(VISIBLE, !!e.newVal.length); } }, /** Handles `visibleChange` events. @method _afterVisibleChange @param {EventFacade} e @protected **/ _afterVisibleChange: function (e) { this._syncVisibility(!!e.newVal); }, /** Delegated event handler for item `click` events. @method _onItemClick @param {EventFacade} e @protected **/ _onItemClick: function (e) { var itemNode = e.currentTarget; this.set(ACTIVE_ITEM, itemNode); this.selectItem(itemNode, e); }, // -- Protected Default Event Handlers ------------------------------------- /** Default `select` event handler. @method _defSelectFn @param {EventFacade} e @protected **/ _defSelectFn: function (e) { var text = e.result.text; // TODO: support typeahead completion, etc. this._inputNode.focus(); this._updateValue(text); this._ariaSay('item_selected', {item: text}); this.hide(); } }, { ATTRS: { /** If `true`, the first item in the list will be activated by default when the list is initially displayed and when results change. @attribute activateFirstItem @type Boolean @default false **/ activateFirstItem: { value: false }, /** Item that's currently active, if any. When the user presses enter, this is the item that will be selected. @attribute activeItem @type Node **/ activeItem: { setter: Y.one, value: null }, /** If `true`, the list will remain visible even when there are no results to display. @attribute alwaysShowList @type Boolean @default false **/ alwaysShowList: { value: false }, /** If `true`, keyboard navigation will wrap around to the opposite end of the list when navigating past the first or last item. @attribute circular @type Boolean @default true **/ circular: { value: true }, /** Item currently being hovered over by the mouse, if any. @attribute hoveredItem @type Node|null @readOnly **/ hoveredItem: { readOnly: true, value: null }, /** Node that will contain result items. @attribute listNode @type Node|null @initOnly **/ listNode: { writeOnce: 'initOnly', value: null }, /** If `true`, the viewport will be scrolled to ensure that the active list item is visible when necessary. @attribute scrollIntoView @type Boolean @default false **/ scrollIntoView: { value: false }, /** Translatable strings used by the AutoCompleteList widget. @attribute strings @type Object **/ strings: { valueFn: function () { return Y.Intl.get('autocomplete-list'); } }, /** If `true`, pressing the tab key while the list is visible will select the active item, if any. @attribute tabSelect @type Boolean @default true **/ tabSelect: { value: true }, // The "visible" attribute is documented in Widget. visible: { value: false } }, CSS_PREFIX: Y.ClassNameManager.getClassName('aclist') }); Y.AutoCompleteList = List; /** Alias for `AutoCompleteList`. See that class for API docs. @class AutoComplete **/ Y.AutoComplete = List; }, '3.18.1', { "lang": [ "en", "es", "hu", "it" ], "requires": [ "autocomplete-base", "event-resize", "node-screen", "selector-css3", "shim-plugin", "widget", "widget-position", "widget-position-align" ], "skinnable": true }); PK\%O7713.18.1/autocomplete-list/autocomplete-list-min.jsnu[YUI.add("autocomplete-list",function(e,t){var n=e.Lang,r=e.Node,i=e.Array,s=e.UA.ie&&e.UA.ie<7,o=9,u="_CLASS_ITEM",a="_CLASS_ITEM_ACTIVE",f="_CLASS_ITEM_HOVER",l="_SELECTOR_ITEM",c="activeItem",h="alwaysShowList",p="circular",d="hoveredItem",v="id",m="item",g="list",y="result",b="results",w="visible",E="width",S="select",x=e.Base.create("autocompleteList",e.Widget,[e.AutoCompleteBase,e.WidgetPosition,e.WidgetPositionAlign],{ARIA_TEMPLATE:"
          ",ITEM_TEMPLATE:"
        • ",LIST_TEMPLATE:"
            ",UI_EVENTS:function(){var t=e.merge(e.Node.DOM_EVENTS);return delete t.valuechange,delete t.valueChange,t}(),initializer:function(){var t=this.get("inputNode");if(!t){e.error("No inputNode specified.");return}this._inputNode=t,this._listEvents=[],this.DEF_PARENT_NODE=t.get("parentNode"),this[u]=this.getClassName(m),this[a]=this.getClassName(m,"active"),this[f]=this.getClassName(m,"hover"),this[l]="."+this[u],this.publish(S,{defaultFn:this._defSelectFn})},destructor:function(){while(this._listEvents.length)this._listEvents.pop().detach();this._ariaNode&&this._ariaNode.remove().destroy(!0)},bindUI:function(){this._bindInput(),this._bindList()},renderUI:function(){var t=this._createAriaNode(),n=this.get("boundingBox"),r=this.get("contentBox"),i=this._inputNode,o=this._createListNode(),u=i.get("parentNode");i.addClass(this.getClassName("input")).setAttrs({"aria-autocomplete":g,"aria-expanded":!1,"aria-owns":o.get("id")}),u.append(t),s&&n.plug(e.Plugin.Shim),this._ariaNode=t,this._boundingBox=n,this._contentBox=r,this._listNode=o,this._parentNode=u},syncUI:function(){this._syncResults(),this._syncVisibility()},hide:function(){return this.get(h)?this:this.set(w,!1)},selectItem:function(e,t){if(e){if(!e.hasClass(this[u]))return this}else{e=this.get(c);if(!e)return this}return this.fire(S,{itemNode:e,originEvent:t||null,result:e.getData(y)}),this},_activateNextItem:function(){var e=this.get(c),t;return e?t=e.next(this[l])||(this.get(p)?null:e):t=this._getFirstItemNode(),this.set(c,t),this},_activatePrevItem:function(){var e=this.get(c),t=e?e.previous(this[l]):this.get(p)&&this._getLastItemNode();return this.set(c,t||null),this},_add:function(t){var r=[];return i.each(n.isArray(t)?t:[t],function(e){r.push(this._createItemNode(e).setData(y,e))},this),r=e.all(r),this._listNode.append(r.toFrag()),r},_ariaSay:function(e,t){var r=this.get("strings."+e);this._ariaNode.set("text",t?n.sub(r,t):r)},_bindInput:function(){var e=this._inputNode,t,n,r;this.get("align")===null&&(r=this.get("tokenInput"),t=r&&r.get("boundingBox")||e,this.set("align",{node:t,points:["tl","bl"]}),!this.get(E)&&(n=t.get("offsetWidth"))&&this.set(E,n)),this._listEvents=this._listEvents.concat([e.after("blur",this._afterListInputBlur,this),e.after("focus",this._afterListInputFocus,this)])},_bindList:function(){this._listEvents=this._listEvents.concat([e.one("doc").after("click",this._afterDocClick,this),e.one("win").after("windowresize",this._syncPosition,this),this.after({mouseover:this._afterMouseOver,mouseout:this._afterMouseOut,activeItemChange:this._afterActiveItemChange,alwaysShowListChange:this._afterAlwaysShowListChange,hoveredItemChange:this._afterHoveredItemChange,resultsChange:this._afterResultsChange,visibleChange:this._afterVisibleChange}),this._listNode.delegate("click",this._onItemClick,this[l],this)])},_clear:function(){this.set(c,null),this._set(d,null),this._listNode.get("children").remove(!0)},_createAriaNode:function(){var e=r.create(this.ARIA_TEMPLATE);return e.addClass(this.getClassName("aria")).setAttrs({"aria-live":"polite",role:"status"})},_createItemNode:function(t){var n=r.create(this.ITEM_TEMPLATE);return n.addClass(this[u]).setAttrs({id:e.stamp(n),role:"option"}).setAttribute("data-text",t.text).append(t.display)},_createListNode:function(){var t=this.get("listNode")||r.create(this.LIST_TEMPLATE);return t.addClass(this.getClassName(g)).setAttrs({id:e.stamp(t),role:"listbox"}),this._set("listNode",t),this.get("contentBox").append(t),t},_getFirstItemNode:function(){return this._listNode.one(this[l])},_getLastItemNode:function(){return this._listNode.one(this[l]+":last-child")},_syncPosition:function(){this._syncUIPosAlign(),this._syncShim()},_syncResults:function(e){e||(e=this.get(b)),this._clear(),e.length&&(this._add(e),this._ariaSay("items_available")),this._syncPosition(),this.get("activateFirstItem")&&!this.get(c)&&this.set(c,this._getFirstItemNode())},_syncShim:s?function(){var e=this._boundingBox.shim;e&&e.sync()}:function(){},_syncVisibility:function(t){this.get(h)&&(t=!0,this.set(w,t)),typeof t=="undefined"&&(t=this.get(w)),this._inputNode.set("aria-expanded",t),this._boundingBox.set("aria-hidden",!t),t?this._syncPosition():(this.set(c,null),this._set(d,null),this._boundingBox.get("offsetWidth")),e.UA.ie===7&&e.one("body").addClass("yui3-ie7-sucks").removeClass("yui3-ie7-sucks")},_afterActiveItemChange:function(t){var n=this._inputNode,r=t.newVal,i=t.prevVal,s;i&&i._node&&i.removeClass(this[a]),r?(r.addClass(this[a]),n.set("aria-activedescendant",r.get(v))):n.removeAttribute("aria-activedescendant"),this.get("scrollIntoView")&&(s=r||n,(!s.inRegion(e.DOM.viewportRegion(),!0)||!s.inRegion(this._contentBox,!0))&&s.scrollIntoView())},_afterAlwaysShowListChange:function(e){this.set(w,e.newVal||this.get(b).length>0)},_afterDocClick:function(e){var t=this._boundingBox,n=e.target;n!==this._inputNode&&n!==t&&!n.ancestor("#"+t.get("id"),!0)&&this.hide()},_afterHoveredItemChange:function(e){var t=e.newVal,n=e.prevVal;n&&n.removeClass(this[f]),t&&t.addClass(this[f])},_afterListInputBlur:function(){this._listInputFocused=!1,this.get(w)&&!this._mouseOverList&&(this._lastInputKey!==o||!this.get("tabSelect")||!this.get(c))&&this.hide()},_afterListInputFocus:function(){this._listInputFocused=!0},_afterMouseOver:function(e){var t=e.domEvent.target.ancestor(this[l],!0);this._mouseOverList=!0,t&&this._set(d,t)},_afterMouseOut:function(){this._mouseOverList=!1,this._set(d,null)},_afterResultsChange:function(e){this._syncResults(e.newVal ),this.get(h)||this.set(w,!!e.newVal.length)},_afterVisibleChange:function(e){this._syncVisibility(!!e.newVal)},_onItemClick:function(e){var t=e.currentTarget;this.set(c,t),this.selectItem(t,e)},_defSelectFn:function(e){var t=e.result.text;this._inputNode.focus(),this._updateValue(t),this._ariaSay("item_selected",{item:t}),this.hide()}},{ATTRS:{activateFirstItem:{value:!1},activeItem:{setter:e.one,value:null},alwaysShowList:{value:!1},circular:{value:!0},hoveredItem:{readOnly:!0,value:null},listNode:{writeOnce:"initOnly",value:null},scrollIntoView:{value:!1},strings:{valueFn:function(){return e.Intl.get("autocomplete-list")}},tabSelect:{value:!0},visible:{value:!1}},CSS_PREFIX:e.ClassNameManager.getClassName("aclist")});e.AutoCompleteList=x,e.AutoComplete=x},"3.18.1",{lang:["en","es","hu","it"],requires:["autocomplete-base","event-resize","node-screen","selector-css3","shim-plugin","widget","widget-position","widget-position-align"],skinnable:!0}); PK\*"*"+3.18.1/io-upload-iframe/io-upload-iframe.jsnu[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(''; Stack.prototype = { initializer : function() { this._stackNode = this.get(BOUNDING_BOX); this._stackHandles = {}; // WIDGET METHOD OVERLAP Y.after(this._renderUIStack, this, RENDER_UI); Y.after(this._syncUIStack, this, SYNC_UI); Y.after(this._bindUIStack, this, BIND_UI); }, /** * Synchronizes the UI to match the Widgets stack state. This method in * invoked after syncUI is invoked for the Widget class using YUI's aop infrastructure. * * @method _syncUIStack * @protected */ _syncUIStack: function() { this._uiSetShim(this.get(SHIM)); this._uiSetZIndex(this.get(ZINDEX)); }, /** * Binds event listeners responsible for updating the UI state in response to * Widget stack related state changes. *

            * This method is invoked after bindUI is invoked for the Widget class * using YUI's aop infrastructure. *

            * @method _bindUIStack * @protected */ _bindUIStack: function() { this.after(ShimChange, this._afterShimChange); this.after(ZIndexChange, this._afterZIndexChange); }, /** * Creates/Initializes the DOM to support stackability. *

            * This method in invoked after renderUI is invoked for the Widget class * using YUI's aop infrastructure. *

            * @method _renderUIStack * @protected */ _renderUIStack: function() { this._stackNode.addClass(Stack.STACKED_CLASS_NAME); }, /** Parses a `zIndex` attribute value from this widget's `srcNode`. @method _parseZIndex @param {Node} srcNode The node to parse a `zIndex` value from. @return {Mixed} The parsed `zIndex` value. @protected **/ _parseZIndex: function (srcNode) { var zIndex; // Prefers how WebKit handles `z-index` which better matches the // spec: // // * http://www.w3.org/TR/CSS2/visuren.html#z-index // * https://bugs.webkit.org/show_bug.cgi?id=15562 // // When a node isn't rendered in the document, and/or when a // node is not positioned, then it doesn't have a context to derive // a valid `z-index` value from. if (!srcNode.inDoc() || srcNode.getStyle('position') === 'static') { zIndex = 'auto'; } else { // Uses `getComputedStyle()` because it has greater accuracy in // more browsers than `getStyle()` does for `z-index`. zIndex = srcNode.getComputedStyle('zIndex'); } // This extension adds a stacking context to widgets, therefore a // `srcNode` witout a stacking context (i.e. "auto") will return // `null` from this DOM parser. This way the widget's default or // user provided value for `zIndex` will be used. return zIndex === 'auto' ? null : zIndex; }, /** * Default setter for zIndex attribute changes. Normalizes zIndex values to * numbers, converting non-numerical values to 0. * * @method _setZIndex * @protected * @param {String | Number} zIndex * @return {Number} Normalized zIndex */ _setZIndex: function(zIndex) { if (L.isString(zIndex)) { zIndex = parseInt(zIndex, 10); } if (!L.isNumber(zIndex)) { zIndex = 0; } return zIndex; }, /** * Default attribute change listener for the shim attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterShimChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterShimChange : function(e) { this._uiSetShim(e.newVal); }, /** * Default attribute change listener for the zIndex attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterZIndexChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterZIndexChange : function(e) { this._uiSetZIndex(e.newVal); }, /** * Updates the UI to reflect the zIndex value passed in. * * @method _uiSetZIndex * @protected * @param {number} zIndex The zindex to be reflected in the UI */ _uiSetZIndex: function (zIndex) { this._stackNode.setStyle(ZINDEX, zIndex); }, /** * Updates the UI to enable/disable the shim. If the widget is not currently visible, * creation of the shim is deferred until it is made visible, for performance reasons. * * @method _uiSetShim * @protected * @param {boolean} enable If true, creates/renders the shim, if false, removes it. */ _uiSetShim: function (enable) { if (enable) { // Lazy creation if (this.get(VISIBLE)) { this._renderShim(); } else { this._renderShimDeferred(); } // Eagerly attach resize handlers // // Required because of Event stack behavior, commit ref: cd8dddc // Should be revisted after Ticket #2531067 is resolved. if (UA.ie == 6) { this._addShimResizeHandlers(); } } else { this._destroyShim(); } }, /** * Sets up change handlers for the visible attribute, to defer shim creation/rendering * until the Widget is made visible. * * @method _renderShimDeferred * @private */ _renderShimDeferred : function() { this._stackHandles[SHIM_DEFERRED] = this._stackHandles[SHIM_DEFERRED] || []; var handles = this._stackHandles[SHIM_DEFERRED], createBeforeVisible = function(e) { if (e.newVal) { this._renderShim(); } }; handles.push(this.on(VisibleChange, createBeforeVisible)); // Depending how how Ticket #2531067 is resolved, a reversal of // commit ref: cd8dddc could lead to a more elagent solution, with // the addition of this line here: // // handles.push(this.after(VisibleChange, this.sizeShim)); }, /** * Sets up event listeners to resize the shim when the size of the Widget changes. *

            * NOTE: This method is only used for IE6 currently, since IE6 doesn't support a way to * resize the shim purely through CSS, when the Widget does not have an explicit width/height * set. *

            * @method _addShimResizeHandlers * @private */ _addShimResizeHandlers : function() { this._stackHandles[SHIM_RESIZE] = this._stackHandles[SHIM_RESIZE] || []; var sizeShim = this.sizeShim, handles = this._stackHandles[SHIM_RESIZE]; handles.push(this.after(VisibleChange, sizeShim)); handles.push(this.after(WidthChange, sizeShim)); handles.push(this.after(HeightChange, sizeShim)); handles.push(this.after(ContentUpdate, sizeShim)); }, /** * Detaches any handles stored for the provided key * * @method _detachStackHandles * @param String handleKey The key defining the group of handles which should be detached * @private */ _detachStackHandles : function(handleKey) { var handles = this._stackHandles[handleKey], handle; if (handles && handles.length > 0) { while((handle = handles.pop())) { handle.detach(); } } }, /** * Creates the shim element and adds it to the DOM * * @method _renderShim * @private */ _renderShim : function() { var shimEl = this._shimNode, stackEl = this._stackNode; if (!shimEl) { shimEl = this._shimNode = this._getShimTemplate(); stackEl.insertBefore(shimEl, stackEl.get(FIRST_CHILD)); this._detachStackHandles(SHIM_DEFERRED); this.sizeShim(); } }, /** * Removes the shim from the DOM, and detaches any related event * listeners. * * @method _destroyShim * @private */ _destroyShim : function() { if (this._shimNode) { this._shimNode.get(PARENT_NODE).removeChild(this._shimNode); this._shimNode = null; this._detachStackHandles(SHIM_DEFERRED); this._detachStackHandles(SHIM_RESIZE); } }, /** * For IE6, synchronizes the size and position of iframe shim to that of * Widget bounding box which it is protecting. For all other browsers, * this method does not do anything. * * @method sizeShim */ sizeShim: function () { var shim = this._shimNode, node = this._stackNode; if (shim && UA.ie === 6 && this.get(VISIBLE)) { shim.setStyle(WIDTH, node.get(OFFSET_WIDTH) + PX); shim.setStyle(HEIGHT, node.get(OFFSET_HEIGHT) + PX); } }, /** * Creates a cloned shim node, using the SHIM_TEMPLATE html template, for use on a new instance. * * @method _getShimTemplate * @private * @return {Node} node A new shim Node instance. */ _getShimTemplate : function() { return Node.create(Stack.SHIM_TEMPLATE, this._stackNode.get(OWNER_DOCUMENT)); } }; Y.WidgetStack = Stack; }, '3.18.1', {"requires": ["base-build", "widget"], "skinnable": true}); PK\:3.18.1/widget-stack/assets/skins/sam/widget-stack-skin.cssnu[PK\:E 53.18.1/widget-stack/assets/skins/sam/widget-stack.cssnu[.yui3-widget-stacked .yui3-widget-shim{opacity:0;filter:alpha(opacity=0);position:absolute;border:0;top:0;left:0;padding:0;margin:0;z-index:-1;width:100%;height:100%;_width:0;_height:0}#yui3-css-stamp.skin-sam-widget-stack{display:none} PK\<3.18.1/widget-stack/assets/skins/night/widget-stack-skin.cssnu[PK\>s73.18.1/widget-stack/assets/skins/night/widget-stack.cssnu[.yui3-widget-stacked .yui3-widget-shim{opacity:0;filter:alpha(opacity=0);position:absolute;border:0;top:0;left:0;padding:0;margin:0;z-index:-1;width:100%;height:100%;_width:0;_height:0}#yui3-css-stamp.skin-night-widget-stack{display:none} PK\h4403.18.1/widget-stack/assets/widget-stack-core.cssnu[.yui3-widget-stacked .yui3-widget-shim { opacity:0; filter:alpha(opacity=0); position:absolute; border:none; top:0px; left:0px; padding:0; margin:0; z-index:-1; width:100%; height:100%; /* We'll be setting these programmatically for IE6, to account for cases where height is not set */ _width:0; _height:0; } PK\f '3.18.1/widget-stack/widget-stack-min.jsnu[YUI.add("widget-stack",function(e,t){function O(e){}var n=e.Lang,r=e.UA,i=e.Node,s=e.Widget,o="zIndex",u="shim",a="visible",f="boundingBox",l="renderUI",c="bindUI",h="syncUI",p="offsetWidth",d="offsetHeight",v="parentNode",m="firstChild",g="ownerDocument",y="width",b="height",w="px",E="shimdeferred",S="shimresize",x="visibleChange",T="widthChange",N="heightChange",C="shimChange",k="zIndexChange",L="contentUpdate",A="stacked";O.ATTRS={shim:{value:r.ie==6},zIndex:{value:0,setter:"_setZIndex"}},O.HTML_PARSER={zIndex:function(e){return this._parseZIndex(e)}},O.SHIM_CLASS_NAME=s.getClassName(u),O.STACKED_CLASS_NAME=s.getClassName(A),O.SHIM_TEMPLATE='',O.prototype={initializer:function(){this._stackNode=this.get(f),this._stackHandles={},e.after(this._renderUIStack,this,l),e.after(this._syncUIStack,this,h),e.after(this._bindUIStack,this,c)},_syncUIStack:function(){this._uiSetShim(this.get(u)),this._uiSetZIndex(this.get(o))},_bindUIStack:function(){this.after(C,this._afterShimChange),this.after(k,this._afterZIndexChange)},_renderUIStack:function(){this._stackNode.addClass(O.STACKED_CLASS_NAME)},_parseZIndex:function(e){var t;return!e.inDoc()||e.getStyle("position")==="static"?t="auto":t=e.getComputedStyle("zIndex"),t==="auto"?null:t},_setZIndex:function(e){return n.isString(e)&&(e=parseInt(e,10)),n.isNumber(e)||(e=0),e},_afterShimChange:function(e){this._uiSetShim(e.newVal)},_afterZIndexChange:function(e){this._uiSetZIndex(e.newVal)},_uiSetZIndex:function(e){this._stackNode.setStyle(o,e)},_uiSetShim:function(e){e?(this.get(a)?this._renderShim():this._renderShimDeferred(),r.ie==6&&this._addShimResizeHandlers()):this._destroyShim()},_renderShimDeferred:function(){this._stackHandles[E]=this._stackHandles[E]||[];var e=this._stackHandles[E],t=function(e){e.newVal&&this._renderShim()};e.push(this.on(x,t))},_addShimResizeHandlers:function(){this._stackHandles[S]=this._stackHandles[S]||[];var e=this.sizeShim,t=this._stackHandles[S];t.push(this.after(x,e)),t.push(this.after(T,e)),t.push(this.after(N,e)),t.push(this.after(L,e))},_detachStackHandles:function(e){var t=this._stackHandles[e],n;if(t&&t.length>0)while(n=t.pop())n.detach()},_renderShim:function(){var e=this._shimNode,t=this._stackNode;e||(e=this._shimNode=this._getShimTemplate(),t.insertBefore(e,t.get(m)),this._detachStackHandles(E),this.sizeShim())},_destroyShim:function(){this._shimNode&&(this._shimNode.get(v).removeChild(this._shimNode),this._shimNode=null,this._detachStackHandles(E),this._detachStackHandles(S))},sizeShim:function(){var e=this._shimNode,t=this._stackNode;e&&r.ie===6&&this.get(a)&&(e.setStyle(y,t.get(p)+w),e.setStyle(b,t.get(d)+w))},_getShimTemplate:function(){return i.create(O.SHIM_TEMPLATE,this._stackNode.get(g))}},e.WidgetStack=O},"3.18.1",{requires:["base-build","widget"],skinnable:!0}); PK\3j7j7)3.18.1/widget-stack/widget-stack-debug.jsnu[YUI.add('widget-stack', function (Y, NAME) { /** * Provides stackable (z-index) support for Widgets through an extension. * * @module widget-stack */ var L = Y.Lang, UA = Y.UA, Node = Y.Node, Widget = Y.Widget, ZINDEX = "zIndex", SHIM = "shim", VISIBLE = "visible", BOUNDING_BOX = "boundingBox", RENDER_UI = "renderUI", BIND_UI = "bindUI", SYNC_UI = "syncUI", OFFSET_WIDTH = "offsetWidth", OFFSET_HEIGHT = "offsetHeight", PARENT_NODE = "parentNode", FIRST_CHILD = "firstChild", OWNER_DOCUMENT = "ownerDocument", WIDTH = "width", HEIGHT = "height", PX = "px", // HANDLE KEYS SHIM_DEFERRED = "shimdeferred", SHIM_RESIZE = "shimresize", // Events VisibleChange = "visibleChange", WidthChange = "widthChange", HeightChange = "heightChange", ShimChange = "shimChange", ZIndexChange = "zIndexChange", ContentUpdate = "contentUpdate", // CSS STACKED = "stacked"; /** * Widget extension, which can be used to add stackable (z-index) support to the * base Widget class along with a shimming solution, through the * Base.build method. * * @class WidgetStack * @param {Object} User configuration object */ function Stack(config) {} // Static Properties /** * Static property used to define the default attribute * configuration introduced by WidgetStack. * * @property ATTRS * @type Object * @static */ Stack.ATTRS = { /** * @attribute shim * @type boolean * @default false, for all browsers other than IE6, for which a shim is enabled by default. * * @description Boolean flag to indicate whether or not a shim should be added to the Widgets * boundingBox, to protect it from select box bleedthrough. */ shim: { value: (UA.ie == 6) }, /** * @attribute zIndex * @type number * @default 0 * @description The z-index to apply to the Widgets boundingBox. Non-numerical values for * zIndex will be converted to 0 */ zIndex: { value : 0, setter: '_setZIndex' } }; /** * The HTML parsing rules for the WidgetStack class. * * @property HTML_PARSER * @static * @type Object */ Stack.HTML_PARSER = { zIndex: function (srcNode) { return this._parseZIndex(srcNode); } }; /** * Default class used to mark the shim element * * @property SHIM_CLASS_NAME * @type String * @static * @default "yui3-widget-shim" */ Stack.SHIM_CLASS_NAME = Widget.getClassName(SHIM); /** * Default class used to mark the boundingBox of a stacked widget. * * @property STACKED_CLASS_NAME * @type String * @static * @default "yui3-widget-stacked" */ Stack.STACKED_CLASS_NAME = Widget.getClassName(STACKED); /** * Default markup template used to generate the shim element. * * @property SHIM_TEMPLATE * @type String * @static */ Stack.SHIM_TEMPLATE = ''; Stack.prototype = { initializer : function() { this._stackNode = this.get(BOUNDING_BOX); this._stackHandles = {}; // WIDGET METHOD OVERLAP Y.after(this._renderUIStack, this, RENDER_UI); Y.after(this._syncUIStack, this, SYNC_UI); Y.after(this._bindUIStack, this, BIND_UI); }, /** * Synchronizes the UI to match the Widgets stack state. This method in * invoked after syncUI is invoked for the Widget class using YUI's aop infrastructure. * * @method _syncUIStack * @protected */ _syncUIStack: function() { this._uiSetShim(this.get(SHIM)); this._uiSetZIndex(this.get(ZINDEX)); }, /** * Binds event listeners responsible for updating the UI state in response to * Widget stack related state changes. *

            * This method is invoked after bindUI is invoked for the Widget class * using YUI's aop infrastructure. *

            * @method _bindUIStack * @protected */ _bindUIStack: function() { this.after(ShimChange, this._afterShimChange); this.after(ZIndexChange, this._afterZIndexChange); }, /** * Creates/Initializes the DOM to support stackability. *

            * This method in invoked after renderUI is invoked for the Widget class * using YUI's aop infrastructure. *

            * @method _renderUIStack * @protected */ _renderUIStack: function() { this._stackNode.addClass(Stack.STACKED_CLASS_NAME); }, /** Parses a `zIndex` attribute value from this widget's `srcNode`. @method _parseZIndex @param {Node} srcNode The node to parse a `zIndex` value from. @return {Mixed} The parsed `zIndex` value. @protected **/ _parseZIndex: function (srcNode) { var zIndex; // Prefers how WebKit handles `z-index` which better matches the // spec: // // * http://www.w3.org/TR/CSS2/visuren.html#z-index // * https://bugs.webkit.org/show_bug.cgi?id=15562 // // When a node isn't rendered in the document, and/or when a // node is not positioned, then it doesn't have a context to derive // a valid `z-index` value from. if (!srcNode.inDoc() || srcNode.getStyle('position') === 'static') { zIndex = 'auto'; } else { // Uses `getComputedStyle()` because it has greater accuracy in // more browsers than `getStyle()` does for `z-index`. zIndex = srcNode.getComputedStyle('zIndex'); } // This extension adds a stacking context to widgets, therefore a // `srcNode` witout a stacking context (i.e. "auto") will return // `null` from this DOM parser. This way the widget's default or // user provided value for `zIndex` will be used. return zIndex === 'auto' ? null : zIndex; }, /** * Default setter for zIndex attribute changes. Normalizes zIndex values to * numbers, converting non-numerical values to 0. * * @method _setZIndex * @protected * @param {String | Number} zIndex * @return {Number} Normalized zIndex */ _setZIndex: function(zIndex) { if (L.isString(zIndex)) { zIndex = parseInt(zIndex, 10); } if (!L.isNumber(zIndex)) { zIndex = 0; } return zIndex; }, /** * Default attribute change listener for the shim attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterShimChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterShimChange : function(e) { this._uiSetShim(e.newVal); }, /** * Default attribute change listener for the zIndex attribute, responsible * for updating the UI, in response to attribute changes. * * @method _afterZIndexChange * @protected * @param {EventFacade} e The event facade for the attribute change */ _afterZIndexChange : function(e) { this._uiSetZIndex(e.newVal); }, /** * Updates the UI to reflect the zIndex value passed in. * * @method _uiSetZIndex * @protected * @param {number} zIndex The zindex to be reflected in the UI */ _uiSetZIndex: function (zIndex) { this._stackNode.setStyle(ZINDEX, zIndex); }, /** * Updates the UI to enable/disable the shim. If the widget is not currently visible, * creation of the shim is deferred until it is made visible, for performance reasons. * * @method _uiSetShim * @protected * @param {boolean} enable If true, creates/renders the shim, if false, removes it. */ _uiSetShim: function (enable) { if (enable) { // Lazy creation if (this.get(VISIBLE)) { this._renderShim(); } else { this._renderShimDeferred(); } // Eagerly attach resize handlers // // Required because of Event stack behavior, commit ref: cd8dddc // Should be revisted after Ticket #2531067 is resolved. if (UA.ie == 6) { this._addShimResizeHandlers(); } } else { this._destroyShim(); } }, /** * Sets up change handlers for the visible attribute, to defer shim creation/rendering * until the Widget is made visible. * * @method _renderShimDeferred * @private */ _renderShimDeferred : function() { this._stackHandles[SHIM_DEFERRED] = this._stackHandles[SHIM_DEFERRED] || []; var handles = this._stackHandles[SHIM_DEFERRED], createBeforeVisible = function(e) { if (e.newVal) { this._renderShim(); } }; handles.push(this.on(VisibleChange, createBeforeVisible)); // Depending how how Ticket #2531067 is resolved, a reversal of // commit ref: cd8dddc could lead to a more elagent solution, with // the addition of this line here: // // handles.push(this.after(VisibleChange, this.sizeShim)); }, /** * Sets up event listeners to resize the shim when the size of the Widget changes. *

            * NOTE: This method is only used for IE6 currently, since IE6 doesn't support a way to * resize the shim purely through CSS, when the Widget does not have an explicit width/height * set. *

            * @method _addShimResizeHandlers * @private */ _addShimResizeHandlers : function() { this._stackHandles[SHIM_RESIZE] = this._stackHandles[SHIM_RESIZE] || []; var sizeShim = this.sizeShim, handles = this._stackHandles[SHIM_RESIZE]; handles.push(this.after(VisibleChange, sizeShim)); handles.push(this.after(WidthChange, sizeShim)); handles.push(this.after(HeightChange, sizeShim)); handles.push(this.after(ContentUpdate, sizeShim)); }, /** * Detaches any handles stored for the provided key * * @method _detachStackHandles * @param String handleKey The key defining the group of handles which should be detached * @private */ _detachStackHandles : function(handleKey) { var handles = this._stackHandles[handleKey], handle; if (handles && handles.length > 0) { while((handle = handles.pop())) { handle.detach(); } } }, /** * Creates the shim element and adds it to the DOM * * @method _renderShim * @private */ _renderShim : function() { var shimEl = this._shimNode, stackEl = this._stackNode; if (!shimEl) { shimEl = this._shimNode = this._getShimTemplate(); stackEl.insertBefore(shimEl, stackEl.get(FIRST_CHILD)); this._detachStackHandles(SHIM_DEFERRED); this.sizeShim(); } }, /** * Removes the shim from the DOM, and detaches any related event * listeners. * * @method _destroyShim * @private */ _destroyShim : function() { if (this._shimNode) { this._shimNode.get(PARENT_NODE).removeChild(this._shimNode); this._shimNode = null; this._detachStackHandles(SHIM_DEFERRED); this._detachStackHandles(SHIM_RESIZE); } }, /** * For IE6, synchronizes the size and position of iframe shim to that of * Widget bounding box which it is protecting. For all other browsers, * this method does not do anything. * * @method sizeShim */ sizeShim: function () { var shim = this._shimNode, node = this._stackNode; if (shim && UA.ie === 6 && this.get(VISIBLE)) { shim.setStyle(WIDTH, node.get(OFFSET_WIDTH) + PX); shim.setStyle(HEIGHT, node.get(OFFSET_HEIGHT) + PX); } }, /** * Creates a cloned shim node, using the SHIM_TEMPLATE html template, for use on a new instance. * * @method _getShimTemplate * @private * @return {Node} node A new shim Node instance. */ _getShimTemplate : function() { return Node.create(Stack.SHIM_TEMPLATE, this._stackNode.get(OWNER_DOCUMENT)); } }; Y.WidgetStack = Stack; }, '3.18.1', {"requires": ["base-build", "widget"], "skinnable": true}); PK\g` /3.18.1/datasource-polling/datasource-polling.jsnu[YUI.add('datasource-polling', function (Y, NAME) { /** * Extends DataSource with polling functionality. * * @module datasource * @submodule datasource-polling */ /** * Adds polling to the DataSource Utility. * @class Pollable * @extends DataSource.Local */ function Pollable() { this._intervals = {}; } Pollable.prototype = { /** * @property _intervals * @description Hash of polling interval IDs that have been enabled, * stored here to be able to clear all intervals. * @private */ _intervals: null, /** * Sets up a polling mechanism to send requests at set intervals and * forward responses to given callback. * * @method setInterval * @param msec {Number} Length of interval in milliseconds. * @param [request] {Object} An object literal with the following properties: *
            *
            request
            *
            The request to send to the live data source, if any.
            *
            callback
            *
            An object literal with the following properties: *
            *
            success
            *
            The function to call when the data is ready.
            *
            failure
            *
            The function to call upon a response failure condition.
            *
            argument
            *
            Arbitrary data payload that will be passed back to the success and failure handlers.
            *
            *
            *
            cfg
            *
            Configuration object, if any.
            *
            * @return {Number} Interval ID. */ setInterval: function(msec, request) { var x = Y.later(msec, this, this.sendRequest, [ request ], true); this._intervals[x.id] = x; // First call happens immediately, but async Y.later(0, this, this.sendRequest, [request]); return x.id; }, /** * Disables polling mechanism associated with the given interval ID. * * @method clearInterval * @param id {Number} Interval ID. */ clearInterval: function(id, key) { // In case of being called by clearAllIntervals() id = key || id; if(this._intervals[id]) { // Clear the interval this._intervals[id].cancel(); // Clear from tracker delete this._intervals[id]; } }, /** * Clears all intervals. * * @method clearAllIntervals */ clearAllIntervals: function() { Y.each(this._intervals, this.clearInterval, this); } }; Y.augment(Y.DataSource.Local, Pollable); }, '3.18.1', {"requires": ["datasource-local"]}); PK\33.18.1/datasource-polling/datasource-polling-min.jsnu[YUI.add("datasource-polling",function(e,t){function n(){this._intervals={}}n.prototype={_intervals:null,setInterval:function(t,n){var r=e.later(t,this,this.sendRequest,[n],!0);return this._intervals[r.id]=r,e.later(0,this,this.sendRequest,[n]),r.id},clearInterval:function(e,t){e=t||e,this._intervals[e]&&(this._intervals[e].cancel(),delete this._intervals[e])},clearAllIntervals:function(){e.each(this._intervals,this.clearInterval,this)}},e.augment(e.DataSource.Local,n)},"3.18.1",{requires:["datasource-local"]}); PK\g` 53.18.1/datasource-polling/datasource-polling-debug.jsnu[YUI.add('datasource-polling', function (Y, NAME) { /** * Extends DataSource with polling functionality. * * @module datasource * @submodule datasource-polling */ /** * Adds polling to the DataSource Utility. * @class Pollable * @extends DataSource.Local */ function Pollable() { this._intervals = {}; } Pollable.prototype = { /** * @property _intervals * @description Hash of polling interval IDs that have been enabled, * stored here to be able to clear all intervals. * @private */ _intervals: null, /** * Sets up a polling mechanism to send requests at set intervals and * forward responses to given callback. * * @method setInterval * @param msec {Number} Length of interval in milliseconds. * @param [request] {Object} An object literal with the following properties: *
            *
            request
            *
            The request to send to the live data source, if any.
            *
            callback
            *
            An object literal with the following properties: *
            *
            success
            *
            The function to call when the data is ready.
            *
            failure
            *
            The function to call upon a response failure condition.
            *
            argument
            *
            Arbitrary data payload that will be passed back to the success and failure handlers.
            *
            *
            *
            cfg
            *
            Configuration object, if any.
            *
            * @return {Number} Interval ID. */ setInterval: function(msec, request) { var x = Y.later(msec, this, this.sendRequest, [ request ], true); this._intervals[x.id] = x; // First call happens immediately, but async Y.later(0, this, this.sendRequest, [request]); return x.id; }, /** * Disables polling mechanism associated with the given interval ID. * * @method clearInterval * @param id {Number} Interval ID. */ clearInterval: function(id, key) { // In case of being called by clearAllIntervals() id = key || id; if(this._intervals[id]) { // Clear the interval this._intervals[id].cancel(); // Clear from tracker delete this._intervals[id]; } }, /** * Clears all intervals. * * @method clearAllIntervals */ clearAllIntervals: function() { Y.each(this._intervals, this.clearInterval, this); } }; Y.augment(Y.DataSource.Local, Pollable); }, '3.18.1', {"requires": ["datasource-local"]}); PK\}yԹԹ-3.18.1/autocomplete-base/autocomplete-base.jsnu[YUI.add('autocomplete-base', function (Y, NAME) { /** Provides automatic input completion or suggestions for text input fields and textareas. @module autocomplete @main autocomplete @since 3.3.0 **/ /** `Y.Base` extension that provides core autocomplete logic (but no UI implementation) for a text input field or textarea. Must be mixed into a `Y.Base`-derived class to be useful. @module autocomplete @submodule autocomplete-base **/ /** Extension that provides core autocomplete logic (but no UI implementation) for a text input field or textarea. The `AutoCompleteBase` class provides events and attributes that abstract away core autocomplete logic and configuration, but does not provide a widget implementation or suggestion UI. For a prepackaged autocomplete widget, see `AutoCompleteList`. This extension cannot be instantiated directly, since it doesn't provide an actual implementation. It's intended to be mixed into a `Y.Base`-based class or widget. `Y.Widget`-based example: YUI().use('autocomplete-base', 'widget', function (Y) { var MyAC = Y.Base.create('myAC', Y.Widget, [Y.AutoCompleteBase], { // Custom prototype methods and properties. }, { // Custom static methods and properties. }); // Custom implementation code. }); `Y.Base`-based example: YUI().use('autocomplete-base', function (Y) { var MyAC = Y.Base.create('myAC', Y.Base, [Y.AutoCompleteBase], { initializer: function () { this._bindUIACBase(); this._syncUIACBase(); }, // Custom prototype methods and properties. }, { // Custom static methods and properties. }); // Custom implementation code. }); @class AutoCompleteBase **/ var Escape = Y.Escape, Lang = Y.Lang, YArray = Y.Array, YObject = Y.Object, isFunction = Lang.isFunction, isString = Lang.isString, trim = Lang.trim, INVALID_VALUE = Y.Attribute.INVALID_VALUE, _FUNCTION_VALIDATOR = '_functionValidator', _SOURCE_SUCCESS = '_sourceSuccess', ALLOW_BROWSER_AC = 'allowBrowserAutocomplete', INPUT_NODE = 'inputNode', QUERY = 'query', QUERY_DELIMITER = 'queryDelimiter', REQUEST_TEMPLATE = 'requestTemplate', RESULTS = 'results', RESULT_LIST_LOCATOR = 'resultListLocator', VALUE = 'value', VALUE_CHANGE = 'valueChange', EVT_CLEAR = 'clear', EVT_QUERY = QUERY, EVT_RESULTS = RESULTS; function AutoCompleteBase() {} AutoCompleteBase.prototype = { // -- Lifecycle Methods ---------------------------------------------------- initializer: function () { // AOP bindings. Y.before(this._bindUIACBase, this, 'bindUI'); Y.before(this._syncUIACBase, this, 'syncUI'); // -- Public Events ---------------------------------------------------- /** Fires after the query has been completely cleared or no longer meets the minimum query length requirement. @event clear @param {String} prevVal Value of the query before it was cleared. @param {String} src Source of the event. @preventable _defClearFn **/ this.publish(EVT_CLEAR, { defaultFn: this._defClearFn }); /** Fires when the contents of the input field have changed and the input value meets the criteria necessary to generate an autocomplete query. @event query @param {String} inputValue Full contents of the text input field or textarea that generated the query. @param {String} query AutoComplete query. This is the string that will be used to request completion results. It may or may not be the same as `inputValue`. @param {String} src Source of the event. @preventable _defQueryFn **/ this.publish(EVT_QUERY, { defaultFn: this._defQueryFn }); /** Fires after query results are received from the source. If no source has been set, this event will not fire. @event results @param {Array|Object} data Raw, unfiltered result data (if available). @param {String} query Query that generated these results. @param {Object[]} results Array of filtered, formatted, and highlighted results. Each item in the array is an object with the following properties: @param {Node|HTMLElement|String} results.display Formatted result HTML suitable for display to the user. If no custom formatter is set, this will be an HTML-escaped version of the string in the `text` property. @param {String} [results.highlighted] Highlighted (but not formatted) result text. This property will only be set if a highlighter is in use. @param {Any} results.raw Raw, unformatted result in whatever form it was provided by the source. @param {String} results.text Plain text version of the result, suitable for being inserted into the value of a text input field or textarea when the result is selected by a user. This value is not HTML-escaped and should not be inserted into the page using `innerHTML` or `Node#setContent()`. @preventable _defResultsFn **/ this.publish(EVT_RESULTS, { defaultFn: this._defResultsFn }); }, destructor: function () { this._acBaseEvents && this._acBaseEvents.detach(); delete this._acBaseEvents; delete this._cache; delete this._inputNode; delete this._rawSource; }, // -- Public Prototype Methods --------------------------------------------- /** Clears the result cache. @method clearCache @chainable @since 3.5.0 **/ clearCache: function () { this._cache && (this._cache = {}); return this; }, /** Sends a request to the configured source. If no source is configured, this method won't do anything. Usually there's no reason to call this method manually; it will be called automatically when user input causes a `query` event to be fired. The only time you'll need to call this method manually is if you want to force a request to be sent when no user input has occurred. @method sendRequest @param {String} [query] Query to send. If specified, the `query` attribute will be set to this query. If not specified, the current value of the `query` attribute will be used. @param {Function} [requestTemplate] Request template function. If not specified, the current value of the `requestTemplate` attribute will be used. @chainable **/ sendRequest: function (query, requestTemplate) { var request, source = this.get('source'); if (query || query === '') { this._set(QUERY, query); } else { query = this.get(QUERY) || ''; } if (source) { if (!requestTemplate) { requestTemplate = this.get(REQUEST_TEMPLATE); } request = requestTemplate ? requestTemplate.call(this, query) : query; source.sendRequest({ query : query, request: request, callback: { success: Y.bind(this._onResponse, this, query) } }); } return this; }, // -- Protected Lifecycle Methods ------------------------------------------ /** Attaches event listeners and behaviors. @method _bindUIACBase @protected **/ _bindUIACBase: function () { var inputNode = this.get(INPUT_NODE), tokenInput = inputNode && inputNode.tokenInput; // If the inputNode has a node-tokeninput plugin attached, bind to the // plugin's inputNode instead. if (tokenInput) { inputNode = tokenInput.get(INPUT_NODE); this._set('tokenInput', tokenInput); } if (!inputNode) { Y.error('No inputNode specified.'); return; } this._inputNode = inputNode; this._acBaseEvents = new Y.EventHandle([ // This is the valueChange event on the inputNode, provided by the // event-valuechange module, not our own valueChange. inputNode.on(VALUE_CHANGE, this._onInputValueChange, this), inputNode.on('blur', this._onInputBlur, this), this.after(ALLOW_BROWSER_AC + 'Change', this._syncBrowserAutocomplete), this.after('sourceTypeChange', this._afterSourceTypeChange), this.after(VALUE_CHANGE, this._afterValueChange) ]); }, /** Synchronizes the UI state of the `inputNode`. @method _syncUIACBase @protected **/ _syncUIACBase: function () { this._syncBrowserAutocomplete(); this.set(VALUE, this.get(INPUT_NODE).get(VALUE)); }, // -- Protected Prototype Methods ------------------------------------------ /** Creates a DataSource-like object that simply returns the specified array as a response. See the `source` attribute for more details. @method _createArraySource @param {Array} source @return {Object} DataSource-like object. @protected **/ _createArraySource: function (source) { var that = this; return { type: 'array', sendRequest: function (request) { that[_SOURCE_SUCCESS](source.concat(), request); } }; }, /** Creates a DataSource-like object that passes the query to a custom-defined function, which is expected to call the provided callback with an array of results. See the `source` attribute for more details. @method _createFunctionSource @param {Function} source Function that accepts a query and a callback as parameters, and calls the callback with an array of results. @return {Object} DataSource-like object. @protected **/ _createFunctionSource: function (source) { var that = this; return { type: 'function', sendRequest: function (request) { var value; function afterResults(results) { that[_SOURCE_SUCCESS](results || [], request); } // Allow both synchronous and asynchronous functions. If we get // a truthy return value, assume the function is synchronous. if ((value = source(request.query, afterResults))) { afterResults(value); } } }; }, /** Creates a DataSource-like object that looks up queries as properties on the specified object, and returns the found value (if any) as a response. See the `source` attribute for more details. @method _createObjectSource @param {Object} source @return {Object} DataSource-like object. @protected **/ _createObjectSource: function (source) { var that = this; return { type: 'object', sendRequest: function (request) { var query = request.query; that[_SOURCE_SUCCESS]( YObject.owns(source, query) ? source[query] : [], request ); } }; }, /** Returns `true` if _value_ is either a function or `null`. @method _functionValidator @param {Function|null} value Value to validate. @protected **/ _functionValidator: function (value) { return value === null || isFunction(value); }, /** Faster and safer alternative to `Y.Object.getValue()`. Doesn't bother casting the path to an array (since we already know it's an array) and doesn't throw an error if a value in the middle of the object hierarchy is neither `undefined` nor an object. @method _getObjectValue @param {Object} obj @param {Array} path @return {Any} Located value, or `undefined` if the value was not found at the specified path. @protected **/ _getObjectValue: function (obj, path) { if (!obj) { return; } for (var i = 0, len = path.length; obj && i < len; i++) { obj = obj[path[i]]; } return obj; }, /** Parses result responses, performs filtering and highlighting, and fires the `results` event. @method _parseResponse @param {String} query Query that generated these results. @param {Object} response Response containing results. @param {Object} data Raw response data. @protected **/ _parseResponse: function (query, response, data) { var facade = { data : data, query : query, results: [] }, listLocator = this.get(RESULT_LIST_LOCATOR), results = [], unfiltered = response && response.results, filters, formatted, formatter, highlighted, highlighter, i, len, maxResults, result, text, textLocator; if (unfiltered && listLocator) { unfiltered = listLocator.call(this, unfiltered); } if (unfiltered && unfiltered.length) { filters = this.get('resultFilters'); textLocator = this.get('resultTextLocator'); // Create a lightweight result object for each result to make them // easier to work with. The various properties on the object // represent different formats of the result, and will be populated // as we go. for (i = 0, len = unfiltered.length; i < len; ++i) { result = unfiltered[i]; text = textLocator ? textLocator.call(this, result) : result.toString(); results.push({ display: Escape.html(text), raw : result, text : text }); } // Run the results through all configured result filters. Each // filter returns an array of (potentially fewer) result objects, // which is then passed to the next filter, and so on. for (i = 0, len = filters.length; i < len; ++i) { results = filters[i].call(this, query, results.concat()); if (!results) { return; } if (!results.length) { break; } } if (results.length) { formatter = this.get('resultFormatter'); highlighter = this.get('resultHighlighter'); maxResults = this.get('maxResults'); // If maxResults is set and greater than 0, limit the number of // results. if (maxResults && maxResults > 0 && results.length > maxResults) { results.length = maxResults; } // Run the results through the configured highlighter (if any). // The highlighter returns an array of highlighted strings (not // an array of result objects), and these strings are then added // to each result object. if (highlighter) { highlighted = highlighter.call(this, query, results.concat()); if (!highlighted) { return; } for (i = 0, len = highlighted.length; i < len; ++i) { result = results[i]; result.highlighted = highlighted[i]; result.display = result.highlighted; } } // Run the results through the configured formatter (if any) to // produce the final formatted results. The formatter returns an // array of strings or Node instances (not an array of result // objects), and these strings/Nodes are then added to each // result object. if (formatter) { formatted = formatter.call(this, query, results.concat()); if (!formatted) { return; } for (i = 0, len = formatted.length; i < len; ++i) { results[i].display = formatted[i]; } } } } facade.results = results; this.fire(EVT_RESULTS, facade); }, /** Returns the query portion of the specified input value, or `null` if there is no suitable query within the input value. If a query delimiter is defined, the query will be the last delimited part of of the string. @method _parseValue @param {String} value Input value from which to extract the query. @return {String|null} query @protected **/ _parseValue: function (value) { var delim = this.get(QUERY_DELIMITER); if (delim) { value = value.split(delim); value = value[value.length - 1]; } return Lang.trimLeft(value); }, /** Setter for the `enableCache` attribute. @method _setEnableCache @param {Boolean} value @protected @since 3.5.0 **/ _setEnableCache: function (value) { // When `this._cache` is an object, result sources will store cached // results in it. When it's falsy, they won't. This way result sources // don't need to get the value of the `enableCache` attribute on every // request, which would be sloooow. this._cache = value ? {} : null; }, /** Setter for locator attributes. @method _setLocator @param {Function|String|null} locator @return {Function|null} @protected **/ _setLocator: function (locator) { if (this[_FUNCTION_VALIDATOR](locator)) { return locator; } var that = this; locator = locator.toString().split('.'); return function (result) { return result && that._getObjectValue(result, locator); }; }, /** Setter for the `requestTemplate` attribute. @method _setRequestTemplate @param {Function|String|null} template @return {Function|null} @protected **/ _setRequestTemplate: function (template) { if (this[_FUNCTION_VALIDATOR](template)) { return template; } template = template.toString(); return function (query) { return Lang.sub(template, {query: encodeURIComponent(query)}); }; }, /** Setter for the `resultFilters` attribute. @method _setResultFilters @param {Array|Function|String|null} filters `null`, a filter function, an array of filter functions, or a string or array of strings representing the names of methods on `Y.AutoCompleteFilters`. @return {Function[]} Array of filter functions (empty if filters is `null`). @protected **/ _setResultFilters: function (filters) { var acFilters, getFilterFunction; if (filters === null) { return []; } acFilters = Y.AutoCompleteFilters; getFilterFunction = function (filter) { if (isFunction(filter)) { return filter; } if (isString(filter) && acFilters && isFunction(acFilters[filter])) { return acFilters[filter]; } return false; }; if (Lang.isArray(filters)) { filters = YArray.map(filters, getFilterFunction); return YArray.every(filters, function (f) { return !!f; }) ? filters : INVALID_VALUE; } else { filters = getFilterFunction(filters); return filters ? [filters] : INVALID_VALUE; } }, /** Setter for the `resultHighlighter` attribute. @method _setResultHighlighter @param {Function|String|null} highlighter `null`, a highlighter function, or a string representing the name of a method on `Y.AutoCompleteHighlighters`. @return {Function|null} @protected **/ _setResultHighlighter: function (highlighter) { var acHighlighters; if (this[_FUNCTION_VALIDATOR](highlighter)) { return highlighter; } acHighlighters = Y.AutoCompleteHighlighters; if (isString(highlighter) && acHighlighters && isFunction(acHighlighters[highlighter])) { return acHighlighters[highlighter]; } return INVALID_VALUE; }, /** Setter for the `source` attribute. Returns a DataSource or a DataSource-like object depending on the type of _source_ and/or the value of the `sourceType` attribute. @method _setSource @param {Any} source AutoComplete source. See the `source` attribute for details. @return {DataSource|Object} @protected **/ _setSource: function (source) { var sourceType = this.get('sourceType') || Lang.type(source), sourceSetter; if ((source && isFunction(source.sendRequest)) || source === null || sourceType === 'datasource') { // Quacks like a DataSource instance (or null). Make it so! this._rawSource = source; return source; } // See if there's a registered setter for this source type. if ((sourceSetter = AutoCompleteBase.SOURCE_TYPES[sourceType])) { this._rawSource = source; return Lang.isString(sourceSetter) ? this[sourceSetter](source) : sourceSetter(source); } Y.error("Unsupported source type '" + sourceType + "'. Maybe autocomplete-sources isn't loaded?"); return INVALID_VALUE; }, /** Shared success callback for non-DataSource sources. @method _sourceSuccess @param {Any} data Response data. @param {Object} request Request object. @protected **/ _sourceSuccess: function (data, request) { request.callback.success({ data: data, response: {results: data} }); }, /** Synchronizes the UI state of the `allowBrowserAutocomplete` attribute. @method _syncBrowserAutocomplete @protected **/ _syncBrowserAutocomplete: function () { var inputNode = this.get(INPUT_NODE); if (inputNode.get('nodeName').toLowerCase() === 'input') { inputNode.setAttribute('autocomplete', this.get(ALLOW_BROWSER_AC) ? 'on' : 'off'); } }, /** Updates the query portion of the `value` attribute. If a query delimiter is defined, the last delimited portion of the input value will be replaced with the specified _value_. @method _updateValue @param {String} newVal New value. @protected **/ _updateValue: function (newVal) { var delim = this.get(QUERY_DELIMITER), insertDelim, len, prevVal; newVal = Lang.trimLeft(newVal); if (delim) { insertDelim = trim(delim); // so we don't double up on spaces prevVal = YArray.map(trim(this.get(VALUE)).split(delim), trim); len = prevVal.length; if (len > 1) { prevVal[len - 1] = newVal; newVal = prevVal.join(insertDelim + ' '); } newVal = newVal + insertDelim + ' '; } this.set(VALUE, newVal); }, // -- Protected Event Handlers --------------------------------------------- /** Updates the current `source` based on the new `sourceType` to ensure that the two attributes don't get out of sync when they're changed separately. @method _afterSourceTypeChange @param {EventFacade} e @protected **/ _afterSourceTypeChange: function (e) { if (this._rawSource) { this.set('source', this._rawSource); } }, /** Handles change events for the `value` attribute. @method _afterValueChange @param {EventFacade} e @protected **/ _afterValueChange: function (e) { var newVal = e.newVal, self = this, uiChange = e.src === AutoCompleteBase.UI_SRC, delay, fire, minQueryLength, query; // Update the UI if the value was changed programmatically. if (!uiChange) { self._inputNode.set(VALUE, newVal); } minQueryLength = self.get('minQueryLength'); query = self._parseValue(newVal) || ''; if (minQueryLength >= 0 && query.length >= minQueryLength) { // Only query on changes that originate from the UI. if (uiChange) { delay = self.get('queryDelay'); fire = function () { self.fire(EVT_QUERY, { inputValue: newVal, query : query, src : e.src }); }; if (delay) { clearTimeout(self._delay); self._delay = setTimeout(fire, delay); } else { fire(); } } else { // For programmatic value changes, just update the query // attribute without sending a query. self._set(QUERY, query); } } else { clearTimeout(self._delay); self.fire(EVT_CLEAR, { prevVal: e.prevVal ? self._parseValue(e.prevVal) : null, src : e.src }); } }, /** Handles `blur` events on the input node. @method _onInputBlur @param {EventFacade} e @protected **/ _onInputBlur: function (e) { var delim = this.get(QUERY_DELIMITER), delimPos, newVal, value; // If a query delimiter is set and the input's value contains one or // more trailing delimiters, strip them. if (delim && !this.get('allowTrailingDelimiter')) { delim = Lang.trimRight(delim); value = newVal = this._inputNode.get(VALUE); if (delim) { while ((newVal = Lang.trimRight(newVal)) && (delimPos = newVal.length - delim.length) && newVal.lastIndexOf(delim) === delimPos) { newVal = newVal.substring(0, delimPos); } } else { // Delimiter is one or more space characters, so just trim the // value. newVal = Lang.trimRight(newVal); } if (newVal !== value) { this.set(VALUE, newVal); } } }, /** Handles `valueChange` events on the input node and fires a `query` event when the input value meets the configured criteria. @method _onInputValueChange @param {EventFacade} e @protected **/ _onInputValueChange: function (e) { var newVal = e.newVal; // Don't query if the internal value is the same as the new value // reported by valueChange. if (newVal !== this.get(VALUE)) { this.set(VALUE, newVal, {src: AutoCompleteBase.UI_SRC}); } }, /** Handles source responses and fires the `results` event. @method _onResponse @param {EventFacade} e @protected **/ _onResponse: function (query, e) { // Ignore stale responses that aren't for the current query. if (query === (this.get(QUERY) || '')) { this._parseResponse(query || '', e.response, e.data); } }, // -- Protected Default Event Handlers ------------------------------------- /** Default `clear` event handler. Sets the `results` attribute to an empty array and `query` to null. @method _defClearFn @protected **/ _defClearFn: function () { this._set(QUERY, null); this._set(RESULTS, []); }, /** Default `query` event handler. Sets the `query` attribute and sends a request to the source if one is configured. @method _defQueryFn @param {EventFacade} e @protected **/ _defQueryFn: function (e) { this.sendRequest(e.query); // sendRequest will set the 'query' attribute }, /** Default `results` event handler. Sets the `results` attribute to the latest results. @method _defResultsFn @param {EventFacade} e @protected **/ _defResultsFn: function (e) { this._set(RESULTS, e[RESULTS]); } }; AutoCompleteBase.ATTRS = { /** Whether or not to enable the browser's built-in autocomplete functionality for input fields. @attribute allowBrowserAutocomplete @type Boolean @default false **/ allowBrowserAutocomplete: { value: false }, /** When a `queryDelimiter` is set, trailing delimiters will automatically be stripped from the input value by default when the input node loses focus. Set this to `true` to allow trailing delimiters. @attribute allowTrailingDelimiter @type Boolean @default false **/ allowTrailingDelimiter: { value: false }, /** Whether or not to enable in-memory caching in result sources that support it. @attribute enableCache @type Boolean @default true @since 3.5.0 **/ enableCache: { lazyAdd: false, // we need the setter to run on init setter: '_setEnableCache', value: true }, /** Node to monitor for changes, which will generate `query` events when appropriate. May be either an `` or a `";j.innerHTML=i;},formatTextbox:function(j,k,m,o,n){var l=(h.isValue(o))?h.escapeHTML(o.toString()):"",i='';j.innerHTML=i;},formatDefault:function(i,j,k,m,l){i.innerHTML=(h.isValue(m)&&m!=="")?m.toString():" ";},validateNumber:function(j){var i=j*1;if(h.isNumber(i)){return i;}else{return undefined;}}});d.Formatter={button:d.formatButton,checkbox:d.formatCheckbox,currency:d.formatCurrency,"date":d.formatDate,dropdown:d.formatDropdown,email:d.formatEmail,link:d.formatLink,"number":d.formatNumber,radio:d.formatRadio,text:d.formatText,textarea:d.formatTextarea,textbox:d.formatTextbox,defaultFormatter:d.formatDefault};h.extend(d,a.Element,{initAttributes:function(i){i=i||{};d.superclass.initAttributes.call(this,i);this.setAttributeConfig("summary",{value:"",validator:h.isString,method:function(j){if(this._elTable){this._elTable.summary=j;}}});this.setAttributeConfig("selectionMode",{value:"standard",validator:h.isString});this.setAttributeConfig("sortedBy",{value:null,validator:function(j){if(j){return(h.isObject(j)&&j.key); }else{return(j===null);}},method:function(k){var r=this.get("sortedBy");this._configs.sortedBy.value=k;var j,o,m,q;if(this._elThead){if(r&&r.key&&r.dir){j=this._oColumnSet.getColumn(r.key);o=j.getKeyIndex();var u=j.getThEl();c.removeClass(u,r.dir);this.formatTheadCell(j.getThLinerEl().firstChild,j,k);}if(k){m=(k.column)?k.column:this._oColumnSet.getColumn(k.key);q=m.getKeyIndex();var v=m.getThEl();if(k.dir&&((k.dir=="asc")||(k.dir=="desc"))){var p=(k.dir=="desc")?d.CLASS_DESC:d.CLASS_ASC;c.addClass(v,p);}else{var l=k.dir||d.CLASS_ASC;c.addClass(v,l);}this.formatTheadCell(m.getThLinerEl().firstChild,m,k);}}if(this._elTbody){this._elTbody.style.display="none";var s=this._elTbody.rows,t;for(var n=s.length-1;n>-1;n--){t=s[n].childNodes;if(t[o]){c.removeClass(t[o],r.dir);}if(t[q]){c.addClass(t[q],k.dir);}}this._elTbody.style.display="";}this._clearTrTemplateEl();}});this.setAttributeConfig("paginator",{value:null,validator:function(j){return j===null||j instanceof e.Paginator;},method:function(){this._updatePaginator.apply(this,arguments);}});this.setAttributeConfig("caption",{value:null,validator:h.isString,method:function(j){this._initCaptionEl(j);}});this.setAttributeConfig("draggableColumns",{value:false,validator:h.isBoolean,method:function(j){if(this._elThead){if(j){this._initDraggableColumns();}else{this._destroyDraggableColumns();}}}});this.setAttributeConfig("renderLoopSize",{value:0,validator:h.isNumber});this.setAttributeConfig("sortFunction",{value:function(k,j,o,n){var m=YAHOO.util.Sort.compare,l=m(k.getData(n),j.getData(n),o);if(l===0){return m(k.getCount(),j.getCount(),o);}else{return l;}}});this.setAttributeConfig("formatRow",{value:null,validator:h.isFunction});this.setAttributeConfig("generateRequest",{value:function(k,n){k=k||{pagination:null,sortedBy:null};var m=encodeURIComponent((k.sortedBy)?k.sortedBy.key:n.getColumnSet().keys[0].getKey());var j=(k.sortedBy&&k.sortedBy.dir===YAHOO.widget.DataTable.CLASS_DESC)?"desc":"asc";var o=(k.pagination)?k.pagination.recordOffset:0;var l=(k.pagination)?k.pagination.rowsPerPage:null;return"sort="+m+"&dir="+j+"&startIndex="+o+((l!==null)?"&results="+l:"");},validator:h.isFunction});this.setAttributeConfig("initialRequest",{value:null});this.setAttributeConfig("initialLoad",{value:true});this.setAttributeConfig("dynamicData",{value:false,validator:h.isBoolean});this.setAttributeConfig("MSG_EMPTY",{value:"No records found.",validator:h.isString});this.setAttributeConfig("MSG_LOADING",{value:"Loading...",validator:h.isString});this.setAttributeConfig("MSG_ERROR",{value:"Data error.",validator:h.isString});this.setAttributeConfig("MSG_SORTASC",{value:"Click to sort ascending",validator:h.isString,method:function(k){if(this._elThead){for(var l=0,m=this.getColumnSet().keys,j=m.length;l=0;--j){if(k[j].editor){g.purgeElement(k[j].editor._elContainer);}}m.innerHTML="";this._elContainer=null;this._elColgroup=null;this._elThead=null;this._elTbody=null;},_initContainerEl:function(j){j=c.get(j);if(j&&j.nodeName&&(j.nodeName.toLowerCase()=="div")){this._destroyContainerEl(j);c.addClass(j,d.CLASS_DATATABLE);g.addListener(j,"focus",this._onTableFocus,this);g.addListener(j,"dblclick",this._onTableDblclick,this);this._elContainer=j;var i=document.createElement("div");i.className=d.CLASS_MASK;i.style.display="none";this._elMask=j.appendChild(i);}},_destroyTableEl:function(){var i=this._elTable;if(i){g.purgeElement(i,true);i.parentNode.removeChild(i);this._elCaption=null;this._elColgroup=null;this._elThead=null;this._elTbody=null;}},_initCaptionEl:function(i){if(this._elTable&&i){if(!this._elCaption){this._elCaption=this._elTable.createCaption();}this._elCaption.innerHTML=i;}else{if(this._elCaption){this._elCaption.parentNode.removeChild(this._elCaption);}}},_initTableEl:function(i){if(i){this._destroyTableEl();this._elTable=i.appendChild(document.createElement("table"));this._elTable.summary=this.get("summary");if(this.get("caption")){this._initCaptionEl(this.get("caption"));}g.delegate(this._elTable,"mouseenter",this._onTableMouseover,"thead ."+d.CLASS_LABEL,this);g.delegate(this._elTable,"mouseleave",this._onTableMouseout,"thead ."+d.CLASS_LABEL,this);g.delegate(this._elTable,"mouseenter",this._onTableMouseover,"tbody.yui-dt-data>tr>td",this);g.delegate(this._elTable,"mouseleave",this._onTableMouseout,"tbody.yui-dt-data>tr>td",this);g.delegate(this._elTable,"mouseenter",this._onTableMouseover,"tbody.yui-dt-message>tr>td",this);g.delegate(this._elTable,"mouseleave",this._onTableMouseout,"tbody.yui-dt-message>tr>td",this);}},_destroyColgroupEl:function(){var i=this._elColgroup;if(i){var j=i.parentNode;g.purgeElement(i,true);j.removeChild(i);this._elColgroup=null;}},_initColgroupEl:function(s){if(s){this._destroyColgroupEl();var l=this._aColIds||[],r=this._oColumnSet.keys,m=0,p=l.length,j,o,q=document.createDocumentFragment(),n=document.createElement("col");for(m=0,p=r.length;ml[l.length-1])){var j,n=[];for(j=l.length-1;j>-1;j--){n.push(this._elColgroup.removeChild(this._elColgroup.childNodes[l[j]]));}var m=this._elColgroup.childNodes[k]||null;for(j=n.length-1;j>-1;j--){this._elColgroup.insertBefore(n[j],m);}}},_destroyTheadEl:function(){var j=this._elThead;if(j){var i=j.parentNode;g.purgeElement(j,true);this._destroyColumnHelpers();i.removeChild(j);this._elThead=null;}},_initTheadEl:function(v){v=v||this._elTable;if(v){this._destroyTheadEl();var q=(this._elColgroup)?v.insertBefore(document.createElement("thead"),this._elColgroup.nextSibling):v.appendChild(document.createElement("thead"));g.addListener(q,"focus",this._onTheadFocus,this);g.addListener(q,"keydown",this._onTheadKeydown,this);g.addListener(q,"mousedown",this._onTableMousedown,this);g.addListener(q,"mouseup",this._onTableMouseup,this);g.addListener(q,"click",this._onTheadClick,this);var x=this._oColumnSet,t,r,p,n;var w=x.tree;var o;for(r=0;r'+p+"";}else{i.innerHTML=p;}},_destroyDraggableColumns:function(){var l,m;for(var k=0,j=this._oColumnSet.tree[0].length;k-2)&&(j1)){s=q+l;}}}for(var k=q;k0)||(n.length>0)){var m=this._oColumnSet,k;for(var j=0;j-1){if(this.getRecord(k[j])){return k[j];}j--;}return null;},getNextTrEl:function(l,i){var j=this.getTrIndex(l);if(j!==null){var k=this._elTbody.rows;if(i){while(j0){l=k[j-1];if(this.getRecord(l)){return l;}j--;}}else{if(j>0){return k[j-1];}}}return null;},getCellIndex:function(k){k=this.getTdEl(k);if(k){if(b.ie>0){var l=0,n=k.parentNode,m=n.childNodes,j=m.length;for(;l0){return j.cells[k]||null;}}}return null;},getFirstTdEl:function(j){var i=h.isValue(j)?this.getTrEl(j):this.getFirstTrEl();if(i){if(i.cells&&i.cells.length>0){return i.cells[0];}else{if(i.childNodes&&i.childNodes.length>0){return i.childNodes[0];}}}return null;},getLastTdEl:function(j){var i=h.isValue(j)?this.getTrEl(j):this.getLastTrEl();if(i){if(i.cells&&i.cells.length>0){return i.cells[i.cells.length-1];}else{if(i.childNodes&&i.childNodes.length>0){return i.childNodes[i.childNodes.length-1];}}}return null;},getNextTdEl:function(i){var m=this.getTdEl(i);if(m){var k=this.getCellIndex(m);var j=this.getTrEl(m);if(j.cells&&(j.cells.length)>0&&(k0&&(k0){if(j.cells&&j.cells.length>0){return j.cells[k-1];}else{if(j.childNodes&&j.childNodes.length>0){return j.childNodes[k-1];}}}else{var l=this.getPreviousTrEl(j);if(l){return this.getLastTdEl(l);}}}return null;},getAboveTdEl:function(j,i){var m=this.getTdEl(j);if(m){var l=this.getPreviousTrEl(m,i);if(l){var k=this.getCellIndex(m);if(l.cells&&l.cells.length>0){return l.cells[k]?l.cells[k]:null;}else{if(l.childNodes&&l.childNodes.length>0){return l.childNodes[k]?l.childNodes[k]:null;}}}}return null;},getBelowTdEl:function(j,i){var m=this.getTdEl(j);if(m){var l=this.getNextTrEl(m,i);if(l){var k=this.getCellIndex(m);if(l.cells&&l.cells.length>0){return l.cells[k]?l.cells[k]:null;}else{if(l.childNodes&&l.childNodes.length>0){return l.childNodes[k]?l.childNodes[k]:null;}}}}return null;},getThLinerEl:function(j){var i=this.getColumn(j);return(i)?i.getThLinerEl():null;},getThEl:function(k){var l;if(k instanceof YAHOO.widget.Column){var j=k;l=j.getThEl();if(l){return l;}}else{var i=c.get(k);if(i&&(i.ownerDocument==document)){if(i.nodeName.toLowerCase()!="th"){l=c.getAncestorByTagName(i,"th"); }else{l=i;}return l;}}return null;},getTrIndex:function(m){var i=this.getRecord(m),k=this.getRecordIndex(i),l;if(i){l=this.getTrEl(i);if(l){return l.sectionRowIndex;}else{var j=this.get("paginator");if(j){return j.get("recordOffset")+k;}else{return k;}}}return null;},load:function(i){i=i||{};(i.datasource||this._oDataSource).sendRequest(i.request||this.get("initialRequest"),i.callback||{success:this.onDataReturnInitializeTable,failure:this.onDataReturnInitializeTable,scope:this,argument:this.getState()});},initializeTable:function(){this._bInit=true;this._oRecordSet.reset();var i=this.get("paginator");if(i){i.set("totalRecords",0);}this._unselectAllTrEls();this._unselectAllTdEls();this._aSelections=null;this._oAnchorRecord=null;this._oAnchorCell=null;this.set("sortedBy",null);},_runRenderChain:function(){this._oChainRender.run();},_getViewRecords:function(){var i=this.get("paginator");if(i){return this._oRecordSet.getRecords(i.getStartIndex(),i.getRowsPerPage());}else{return this._oRecordSet.getRecords();}},render:function(){this._oChainRender.stop();this.fireEvent("beforeRenderEvent");var r,p,o,s,l=this._getViewRecords();var m=this._elTbody,q=this.get("renderLoopSize"),t=l.length;if(t>0){m.style.display="none";while(m.lastChild){m.removeChild(m.lastChild);}m.style.display="";this._oChainRender.add({method:function(u){if((this instanceof d)&&this._sId){var k=u.nCurrentRecord,w=((u.nCurrentRecord+u.nLoopLength)>t)?t:(u.nCurrentRecord+u.nLoopLength),j,v;m.style.display="none";for(;k0)?Math.ceil(t/q):1,argument:{nCurrentRecord:0,nLoopLength:(q>0)?q:t},timeout:(q>0)?0:-1});this._oChainRender.add({method:function(i){if((this instanceof d)&&this._sId){while(m.rows.length>t){m.removeChild(m.lastChild);}this._setFirstRow();this._setLastRow();this._setRowStripes();this._setSelections();}},scope:this,timeout:(q>0)?0:-1});}else{var n=m.rows.length;if(n>0){this._oChainRender.add({method:function(k){if((this instanceof d)&&this._sId){var j=k.nCurrent,v=k.nLoopLength,u=(j-v<0)?0:j-v;m.style.display="none";for(;j>u;j--){m.deleteRow(-1);}m.style.display="";k.nCurrent=j;}},scope:this,iterations:(q>0)?Math.ceil(n/q):1,argument:{nCurrent:n,nLoopLength:(q>0)?q:n},timeout:(q>0)?0:-1});}}this._runRenderChain();},disable:function(){this._disabled=true;var i=this._elTable;var j=this._elMask;j.style.width=i.offsetWidth+"px";j.style.height=i.offsetHeight+"px";j.style.left=i.offsetLeft+"px";j.style.display="";this.fireEvent("disableEvent");},undisable:function(){this._disabled=false;this._elMask.style.display="none";this.fireEvent("undisableEvent");},isDisabled:function(){return this._disabled;},destroy:function(){var k=this.toString();this._oChainRender.stop();this._destroyColumnHelpers();var m;for(var l=0,j=this._oColumnSet.flat.length;lj.minWidth)?i:j.minWidth;j.width=i;this._setColumnWidth(j,i+"px");this.fireEvent("columnSetWidthEvent",{column:j,width:i});}else{if(i===null){j.width=i;this._setColumnWidth(j,"auto");this.validateColumnWidths(j);this.fireEvent("columnUnsetWidthEvent",{column:j});}}this._clearTrTemplateEl();}else{}},_setColumnWidth:function(j,i,k){if(j&&(j.getKeyIndex()!==null)){k=k||(((i==="")||(i==="auto"))?"visible":"hidden");if(!d._bDynStylesFallback){this._setColumnWidthDynStyles(j,i,k);}else{this._setColumnWidthDynFunction(j,i,k);}}else{}},_setColumnWidthDynStyles:function(m,l,n){var j=d._elDynStyleNode,k;if(!j){j=document.createElement("style");j.type="text/css";j=document.getElementsByTagName("head").item(0).appendChild(j);d._elDynStyleNode=j;}if(j){var i="."+this.getId()+"-col-"+m.getSanitizedKey()+" ."+d.CLASS_LINER;if(this._elTbody){this._elTbody.style.display="none";}k=d._oDynStyles[i];if(!k){if(j.styleSheet&&j.styleSheet.addRule){j.styleSheet.addRule(i,"overflow:"+n);j.styleSheet.addRule(i,"width:"+l);k=j.styleSheet.rules[j.styleSheet.rules.length-1];d._oDynStyles[i]=k;}else{if(j.sheet&&j.sheet.insertRule){j.sheet.insertRule(i+" {overflow:"+n+";width:"+l+";}",j.sheet.cssRules.length);k=j.sheet.cssRules[j.sheet.cssRules.length-1];d._oDynStyles[i]=k;}}}else{k.style.overflow=n;k.style.width=l;}if(this._elTbody){this._elTbody.style.display="";}}if(!k){d._bDynStylesFallback=true;this._setColumnWidthDynFunction(m,l);}},_setColumnWidthDynFunction:function(r,m,s){if(m=="auto"){m="";}var l=this._elTbody?this._elTbody.rows.length:0;if(!this._aDynFunctions[l]){var q,p,o;var t=["var colIdx=oColumn.getKeyIndex();","oColumn.getThLinerEl().style.overflow="];for(q=l-1,p=2;q>=0;--q){t[p++]="this._elTbody.rows[";t[p++]=q;t[p++]="].cells[colIdx].firstChild.style.overflow=";}t[p]="sOverflow;";t[p+1]="oColumn.getThLinerEl().style.width=";for(q=l-1,o=p+2;q>=0;--q){t[o++]="this._elTbody.rows[";t[o++]=q;t[o++]="].cells[colIdx].firstChild.style.width=";}t[o]="sWidth;";this._aDynFunctions[l]=new Function("oColumn","sWidth","sOverflow",t.join(""));}var n=this._aDynFunctions[l];if(n){n.call(this,r,m,s);}},validateColumnWidths:function(o){var l=this._elColgroup;var q=l.cloneNode(true);var p=false;var n=this._oColumnSet.keys;var k;if(o&&!o.hidden&&!o.width&&(o.getKeyIndex()!==null)){k=o.getThLinerEl();if((o.minWidth>0)&&(k.offsetWidth0)&&(k.offsetWidth>o.maxAutoWidth)){this._setColumnWidth(o,o.maxAutoWidth+"px","hidden");}}}else{for(var m=0,j=n.length;m0)&&(k.offsetWidth0)&&(k.offsetWidth>o.maxAutoWidth)){this._setColumnWidth(o,o.maxAutoWidth+"px","hidden");}}}}}if(p){l.parentNode.replaceChild(q,l);this._elColgroup=q;}},_clearMinWidth:function(i){if(i.getKeyIndex()!==null){this._elColgroup.childNodes[i.getKeyIndex()].style.width="";}},_restoreMinWidth:function(i){if(i.minWidth&&(i.getKeyIndex()!==null)){this._elColgroup.childNodes[i.getKeyIndex()].style.width=i.minWidth+"px";}},hideColumn:function(r){if(!(r instanceof YAHOO.widget.Column)){r=this.getColumn(r);}if(r&&!r.hidden&&r.getTreeIndex()!==null){var o=this.getTbodyEl().rows;var n=o.length;var m=this._oColumnSet.getDescendants(r);for(var q=0,s=m.length;q0){q=u;}}else{q=[q];}if(q!==null){q.sort(function(v,i){return YAHOO.util.Sort.compare(v,i);});this._destroyTheadEl();var k=this._oColumnSet.getDefinitions();p=k.splice(m,1)[0];this._initColumnSet(k);this._initTheadEl();for(o=q.length-1;o>-1;o--){this._removeColgroupColEl(q[o]);}var t=this._elTbody.rows;if(t.length>0){var n=this.get("renderLoopSize"),l=t.length; this._oChainRender.add({method:function(y){if((this instanceof d)&&this._sId){var x=y.nCurrentRow,v=n>0?Math.min(x+n,t.length):t.length,z=y.aIndexes,w;for(;x-1;w--){t[x].removeChild(t[x].childNodes[z[w]]);}}y.nCurrentRow=x;}},iterations:(n>0)?Math.ceil(l/n):1,argument:{nCurrentRow:0,aIndexes:q},scope:this,timeout:(n>0)?0:-1});this._runRenderChain();}this.fireEvent("columnRemoveEvent",{column:p});return p;}}}},insertColumn:function(r,s){if(r instanceof YAHOO.widget.Column){r=r.getDefinition();}else{if(r.constructor!==Object){return;}}var x=this._oColumnSet;if(!h.isValue(s)||!h.isNumber(s)){s=x.tree[0].length;}this._destroyTheadEl();var z=this._oColumnSet.getDefinitions();z.splice(s,0,r);this._initColumnSet(z);this._initTheadEl();x=this._oColumnSet;var n=x.tree[0][s];var p,t,w=[];var l=x.getDescendants(n);for(p=0,t=l.length;p0){var y=w.sort(function(A,i){return YAHOO.util.Sort.compare(A,i);})[0];for(p=w.length-1;p>-1;p--){this._insertColgroupColEl(w[p]);}var v=this._elTbody.rows;if(v.length>0){var o=this.get("renderLoopSize"),m=v.length;var k=[],q;for(p=0,t=w.length;p0?Math.min(C+o,v.length):v.length,E;for(;C-1;B--){v[C].insertBefore(D.aTdTemplates[F[B]].cloneNode(true),E);}}D.nCurrentRow=C;}},iterations:(o>0)?Math.ceil(m/o):1,argument:{nCurrentRow:0,aTdTemplates:k,descKeyIndexes:w},scope:this,timeout:(o>0)?0:-1});this._runRenderChain();}this.fireEvent("columnInsertEvent",{column:r,index:s});return n;}},reorderColumn:function(q,r){if(!(q instanceof YAHOO.widget.Column)){q=this.getColumn(q);}if(q&&YAHOO.lang.isNumber(r)){var z=q.getTreeIndex();if((z!==null)&&(z!==r)){var p,s,l=q.getKeyIndex(),k,v=[],t;if(l===null){k=this._oColumnSet.getDescendants(q);for(p=0,s=k.length;p0){l=v;}}else{l=[l];}if(l!==null){l.sort(function(A,i){return YAHOO.util.Sort.compare(A,i);});this._destroyTheadEl();var w=this._oColumnSet.getDefinitions();var j=w.splice(z,1)[0];w.splice(r,0,j);this._initColumnSet(w);this._initTheadEl();var n=this._oColumnSet.tree[0][r];var y=n.getKeyIndex();if(y===null){v=[];k=this._oColumnSet.getDescendants(n);for(p=0,s=k.length;p0){y=v;}}else{y=[y];}var x=y.sort(function(A,i){return YAHOO.util.Sort.compare(A,i);})[0];this._reorderColgroupColEl(l,x);var u=this._elTbody.rows;if(u.length>0){var o=this.get("renderLoopSize"),m=u.length;this._oChainRender.add({method:function(D){if((this instanceof d)&&this._sId){var C=D.nCurrentRow,B,F,E,A=o>0?Math.min(C+o,u.length):u.length,H=D.aIndexes,G;for(;C-1;B--){F.push(G.removeChild(G.childNodes[H[B]]));}E=G.childNodes[x]||null;for(B=F.length-1;B>-1;B--){G.insertBefore(F[B],E);}}D.nCurrentRow=C;}},iterations:(o>0)?Math.ceil(m/o):1,argument:{nCurrentRow:0,aIndexes:l},scope:this,timeout:(o>0)?0:-1});this._runRenderChain();}this.fireEvent("columnReorderEvent",{column:n,oldIndex:z});return n;}}}},selectColumn:function(k){k=this.getColumn(k);if(k&&!k.selected){if(k.getKeyIndex()!==null){k.selected=true;var l=k.getThEl();c.addClass(l,d.CLASS_SELECTED);var j=this.getTbodyEl().rows;var i=this._oChainRender;i.add({method:function(m){if((this instanceof d)&&this._sId&&j[m.rowIndex]&&j[m.rowIndex].cells[m.cellIndex]){c.addClass(j[m.rowIndex].cells[m.cellIndex],d.CLASS_SELECTED);}m.rowIndex++;},scope:this,iterations:j.length,argument:{rowIndex:0,cellIndex:k.getKeyIndex()}});this._clearTrTemplateEl();this._elTbody.style.display="none";this._runRenderChain();this._elTbody.style.display="";this.fireEvent("columnSelectEvent",{column:k});}else{}}},unselectColumn:function(k){k=this.getColumn(k);if(k&&k.selected){if(k.getKeyIndex()!==null){k.selected=false;var l=k.getThEl();c.removeClass(l,d.CLASS_SELECTED);var j=this.getTbodyEl().rows;var i=this._oChainRender;i.add({method:function(m){if((this instanceof d)&&this._sId&&j[m.rowIndex]&&j[m.rowIndex].cells[m.cellIndex]){c.removeClass(j[m.rowIndex].cells[m.cellIndex],d.CLASS_SELECTED);}m.rowIndex++;},scope:this,iterations:j.length,argument:{rowIndex:0,cellIndex:k.getKeyIndex()}});this._clearTrTemplateEl();this._elTbody.style.display="none";this._runRenderChain();this._elTbody.style.display="";this.fireEvent("columnUnselectEvent",{column:k});}else{}}},getSelectedColumns:function(n){var k=[];var l=this._oColumnSet.keys;for(var m=0,j=l.length;mthis._oRecordSet.getLength())){return;}if(o&&h.isObject(o)){var m=this._oRecordSet.addRecord(o,k);if(m){var i;var j=this.get("paginator");if(j){var n=j.get("totalRecords");if(n!==e.Paginator.VALUE_UNLIMITED){j.set("totalRecords",n+1);}i=this.getRecordIndex(m);var l=(j.getPageRecords())[1];if(i<=l){this.render();}this.fireEvent("rowAddEvent",{record:m});return;}else{i=this.getRecordIndex(m);if(h.isNumber(i)){this._oChainRender.add({method:function(r){if((this instanceof d)&&this._sId){var s=r.record;var p=r.recIndex;var t=this._addTrEl(s);if(t){var q=(this._elTbody.rows[p])?this._elTbody.rows[p]:null;this._elTbody.insertBefore(t,q);if(p===0){this._setFirstRow();}if(q===null){this._setLastRow();}this._setRowStripes();this.hideTableMessage();this.fireEvent("rowAddEvent",{record:s});}}},argument:{record:m,recIndex:i},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});this._runRenderChain();return;}}}}},addRows:function(k,n){if(h.isNumber(n)&&(n<0||n>this._oRecordSet.getLength())){return;}if(h.isArray(k)){var o=this._oRecordSet.addRecords(k,n);if(o){var s=this.getRecordIndex(o[0]);var r=this.get("paginator");if(r){var p=r.get("totalRecords");if(p!==e.Paginator.VALUE_UNLIMITED){r.set("totalRecords",p+o.length);}var q=(r.getPageRecords())[1];if(s<=q){this.render();}this.fireEvent("rowsAddEvent",{records:o});return;}else{var m=this.get("renderLoopSize");var j=s+k.length;var i=(j-s);var l=(s>=this._elTbody.rows.length);this._oChainRender.add({method:function(x){if((this instanceof d)&&this._sId){var y=x.aRecords,w=x.nCurrentRow,v=x.nCurrentRecord,t=m>0?Math.min(w+m,j):j,z=document.createDocumentFragment(),u=(this._elTbody.rows[w])?this._elTbody.rows[w]:null;for(;w0)?Math.ceil(j/m):1,argument:{nCurrentRow:s,nCurrentRecord:0,aRecords:o},scope:this,timeout:(m>0)?0:-1});this._oChainRender.add({method:function(u){var t=u.recIndex;if(t===0){this._setFirstRow();}if(u.isLast){this._setLastRow();}this._setRowStripes();this.fireEvent("rowsAddEvent",{records:o});},argument:{recIndex:s,isLast:l},scope:this,timeout:-1});this._runRenderChain();this.hideTableMessage();return;}}}},updateRow:function(u,k){var r=u;if(!h.isNumber(r)){r=this.getRecordIndex(u);}if(h.isNumber(r)&&(r>=0)){var s=this._oRecordSet,q=s.getRecord(r);if(q){var o=this._oRecordSet.setRecord(k,r),j=this.getTrEl(q),p=q?q.getData():null;if(o){var t=this._aSelections||[],n=0,l=q.getId(),m=o.getId();for(;n=i)||(r<=w)){this.render();}}else{if(j){this._updateTrEl(j,o);}else{this.getTbodyEl().appendChild(this._addTrEl(o));}}this.fireEvent("rowUpdateEvent",{record:o,oldData:p});}},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});this._runRenderChain();return;}}}return;},updateRows:function(A,m){if(h.isArray(m)){var s=A,l=this._oRecordSet,o=l.getLength();if(!h.isNumber(A)){s=this.getRecordIndex(A);}if(h.isNumber(s)&&(s>=0)&&(s=r)||(E<=p)){this.render();}this.fireEvent("rowsAddEvent",{newRecords:G,oldRecords:B});return;}else{var k=this.get("renderLoopSize"),v=m.length,w=(E>=o),q=(E>o);this._oChainRender.add({method:function(K){if((this instanceof d)&&this._sId){var L=K.aRecords,J=K.nCurrentRow,I=K.nDataPointer,H=k>0?Math.min(J+k,s+L.length):s+L.length;for(;J=o)){this._elTbody.appendChild(this._addTrEl(L[I]));}else{this._updateTrEl(this._elTbody.rows[J],L[I]);}}K.nCurrentRow=J;K.nDataPointer=I;}},iterations:(k>0)?Math.ceil(v/k):1,argument:{nCurrentRow:s,aRecords:G,nDataPointer:0,isAdding:q},scope:this,timeout:(k>0)?0:-1});this._oChainRender.add({method:function(j){var i=j.recIndex;if(i===0){this._setFirstRow();}if(j.isLast){this._setLastRow();}this._setRowStripes();this.fireEvent("rowsAddEvent",{newRecords:G,oldRecords:B});},argument:{recIndex:s,isLast:w},scope:this,timeout:-1});this._runRenderChain();this.hideTableMessage();return;}}}}},deleteRow:function(s){var k=(h.isNumber(s))?s:this.getRecordIndex(s);if(h.isNumber(k)){var t=this.getRecord(k);if(t){var m=this.getTrIndex(k);var p=t.getId();var r=this._aSelections||[];for(var n=r.length-1;n>-1;n--){if((h.isString(r[n])&&(r[n]===p))||(h.isObject(r[n])&&(r[n].recordId===p))){r.splice(n,1);}}var l=this._oRecordSet.deleteRecord(k);if(l){var q=this.get("paginator");if(q){var o=q.get("totalRecords"),i=q.getPageRecords();if(o!==e.Paginator.VALUE_UNLIMITED){q.set("totalRecords",o-1);}if(!i||k<=i[1]){this.render();}this._oChainRender.add({method:function(){if((this instanceof d)&&this._sId){this.fireEvent("rowDeleteEvent",{recordIndex:k,oldData:l,trElIndex:m});}},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});this._runRenderChain();}else{if(h.isNumber(m)){this._oChainRender.add({method:function(){if((this instanceof d)&&this._sId){var j=(k===this._oRecordSet.getLength());this._deleteTrEl(m);if(this._elTbody.rows.length>0){if(m===0){this._setFirstRow(); }if(j){this._setLastRow();}if(m!=this._elTbody.rows.length){this._setRowStripes(m);}}this.fireEvent("rowDeleteEvent",{recordIndex:k,oldData:l,trElIndex:m});}},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});this._runRenderChain();return;}}}}}return null;},deleteRows:function(y,s){var l=(h.isNumber(y))?y:this.getRecordIndex(y);if(h.isNumber(l)){var z=this.getRecord(l);if(z){var m=this.getTrIndex(l);var u=z.getId();var x=this._aSelections||[];for(var q=x.length-1;q>-1;q--){if((h.isString(x[q])&&(x[q]===u))||(h.isObject(x[q])&&(x[q].recordId===u))){x.splice(q,1);}}var n=l;var w=l;if(s&&h.isNumber(s)){n=(s>0)?l+s-1:l;w=(s>0)?l:l+s+1;s=(s>0)?s:s*-1;if(w<0){w=0;s=n-w+1;}}else{s=1;}var p=this._oRecordSet.deleteRecords(w,s);if(p){var v=this.get("paginator"),r=this.get("renderLoopSize");if(v){var t=v.get("totalRecords"),k=v.getPageRecords();if(t!==e.Paginator.VALUE_UNLIMITED){v.set("totalRecords",t-p.length);}if(!k||w<=k[1]){this.render();}this._oChainRender.add({method:function(j){if((this instanceof d)&&this._sId){this.fireEvent("rowsDeleteEvent",{recordIndex:w,oldData:p,count:s});}},scope:this,timeout:(r>0)?0:-1});this._runRenderChain();return;}else{if(h.isNumber(m)){var o=w;var i=s;this._oChainRender.add({method:function(B){if((this instanceof d)&&this._sId){var A=B.nCurrentRow,j=(r>0)?(Math.max(A-r,o)-1):o-1;for(;A>j;--A){this._deleteTrEl(A);}B.nCurrentRow=A;}},iterations:(r>0)?Math.ceil(s/r):1,argument:{nCurrentRow:n},scope:this,timeout:(r>0)?0:-1});this._oChainRender.add({method:function(){if(this._elTbody.rows.length>0){this._setFirstRow();this._setLastRow();this._setRowStripes();}this.fireEvent("rowsDeleteEvent",{recordIndex:w,oldData:p,count:s});},scope:this,timeout:-1});this._runRenderChain();return;}}}}}return null;},formatCell:function(j,l,m){if(!l){l=this.getRecord(j);}if(!m){m=this.getColumn(this.getCellIndex(j.parentNode));}if(l&&m){var i=m.field;var n=l.getData(i);var k=typeof m.formatter==="function"?m.formatter:d.Formatter[m.formatter+""]||d.Formatter.defaultFormatter;if(k){k.call(this,j,l,m,n);}else{j.innerHTML=n;}this.fireEvent("cellFormatEvent",{record:l,column:m,key:m.key,el:j});}else{}},updateCell:function(k,m,o,j){m=(m instanceof YAHOO.widget.Column)?m:this.getColumn(m);if(m&&m.getField()&&(k instanceof YAHOO.widget.Record)){var l=m.getField(),n=k.getData(l);this._oRecordSet.updateRecordValue(k,l,o);var i=this.getTdEl({record:k,column:m});if(i){this._oChainRender.add({method:function(){if((this instanceof d)&&this._sId){this.formatCell(i.firstChild,k,m);this.fireEvent("cellUpdateEvent",{record:k,column:m,oldData:n});}},scope:this,timeout:(this.get("renderLoopSize")>0)?0:-1});if(!j){this._runRenderChain();}}else{this.fireEvent("cellUpdateEvent",{record:k,column:m,oldData:n});}}},_updatePaginator:function(j){var i=this.get("paginator");if(i&&j!==i){i.unsubscribe("changeRequest",this.onPaginatorChangeRequest,this,true);}if(j){j.subscribe("changeRequest",this.onPaginatorChangeRequest,this,true);}},_handlePaginatorChange:function(l){if(l.prevValue===l.newValue){return;}var n=l.newValue,m=l.prevValue,k=this._defaultPaginatorContainers();if(m){if(m.getContainerNodes()[0]==k[0]){m.set("containers",[]);}m.destroy();if(k[0]){if(n&&!n.getContainerNodes().length){n.set("containers",k);}else{for(var j=k.length-1;j>=0;--j){if(k[j]){k[j].parentNode.removeChild(k[j]);}}}}}if(!this._bInit){this.render();}if(n){this.renderPaginator();}},_defaultPaginatorContainers:function(l){var j=this._sId+"-paginator0",k=this._sId+"-paginator1",i=c.get(j),m=c.get(k);if(l&&(!i||!m)){if(!i){i=document.createElement("div");i.id=j;c.addClass(i,d.CLASS_PAGINATOR);this._elContainer.insertBefore(i,this._elContainer.firstChild);}if(!m){m=document.createElement("div");m.id=k;c.addClass(m,d.CLASS_PAGINATOR);this._elContainer.appendChild(m);}}return[i,m];},_destroyPaginator:function(){var i=this.get("paginator");if(i){i.destroy();}},renderPaginator:function(){var i=this.get("paginator");if(!i){return;}if(!i.getContainerNodes().length){i.set("containers",this._defaultPaginatorContainers(true));}i.render();},doBeforePaginatorChange:function(i){this.showTableMessage(this.get("MSG_LOADING"),d.CLASS_LOADING);return true;},onPaginatorChangeRequest:function(l){var j=this.doBeforePaginatorChange(l);if(j){if(this.get("dynamicData")){var i=this.getState();i.pagination=l;var k=this.get("generateRequest")(i,this);this.unselectAllRows();this.unselectAllCells();var m={success:this.onDataReturnSetRows,failure:this.onDataReturnSetRows,argument:i,scope:this};this._oDataSource.sendRequest(k,m);}else{l.paginator.setStartIndex(l.recordOffset,true);l.paginator.setRowsPerPage(l.rowsPerPage,true);this.render();}}else{}},_elLastHighlightedTd:null,_aSelections:null,_oAnchorRecord:null,_oAnchorCell:null,_unselectAllTrEls:function(){var i=c.getElementsByClassName(d.CLASS_SELECTED,"tr",this._elTbody);c.removeClass(i,d.CLASS_SELECTED);},_getSelectionTrigger:function(){var l=this.get("selectionMode");var k={};var o,i,j,n,m;if((l=="cellblock")||(l=="cellrange")||(l=="singlecell")){o=this.getLastSelectedCell();if(!o){return null;}else{i=this.getRecord(o.recordId);j=this.getRecordIndex(i);n=this.getTrEl(i);m=this.getTrIndex(n);if(m===null){return null;}else{k.record=i;k.recordIndex=j;k.el=this.getTdEl(o);k.trIndex=m;k.column=this.getColumn(o.columnKey);k.colKeyIndex=k.column.getKeyIndex();k.cell=o;return k;}}}else{i=this.getLastSelectedRecord();if(!i){return null;}else{i=this.getRecord(i);j=this.getRecordIndex(i);n=this.getTrEl(i);m=this.getTrIndex(n);if(m===null){return null;}else{k.record=i;k.recordIndex=j;k.el=n;k.trIndex=m;return k;}}}},_getSelectionAnchor:function(k){var j=this.get("selectionMode");var l={};var m,o,i;if((j=="cellblock")||(j=="cellrange")||(j=="singlecell")){var n=this._oAnchorCell;if(!n){if(k){n=this._oAnchorCell=k.cell;}else{return null;}}m=this._oAnchorCell.record;o=this._oRecordSet.getRecordIndex(m);i=this.getTrIndex(m);if(i===null){if(o=l;n--){if(!this.isSelected(n)){this.selectRow(n);}}}}else{if(q.recordIndex=l;n--){this.selectRow(n);}}}else{this._oAnchorRecord=r;this.selectRow(r);}}else{if(o){this._oAnchorRecord=r;if(this.isSelected(r)){this.unselectRow(r);}else{this.selectRow(r);}}else{this._handleSingleSelectionByMouse(k);return;}}}}},_handleStandardSelectionByKey:function(m){var i=g.getCharCode(m);if((i==38)||(i==40)){var k=m.shiftKey;var j=this._getSelectionTrigger();if(!j){return null;}g.stopEvent(m);var l=this._getSelectionAnchor(j);if(k){if((i==40)&&(l.recordIndex<=j.trIndex)){this.selectRow(this.getNextTrEl(j.el));}else{if((i==38)&&(l.recordIndex>=j.trIndex)){this.selectRow(this.getPreviousTrEl(j.el));}else{this.unselectRow(j.el);}}}else{this._handleSingleSelectionByKey(m);}}},_handleSingleSelectionByMouse:function(k){var l=k.target;var j=this.getTrEl(l);if(j){var i=this.getRecord(j);this._oAnchorRecord=i;this.unselectAllRows();this.selectRow(i);}},_handleSingleSelectionByKey:function(l){var i=g.getCharCode(l);if((i==38)||(i==40)){var j=this._getSelectionTrigger();if(!j){return null;}g.stopEvent(l);var k;if(i==38){k=this.getPreviousTrEl(j.el);if(k===null){k=this.getFirstTrEl();}}else{if(i==40){k=this.getNextTrEl(j.el);if(k===null){k=this.getLastTrEl();}}}this.unselectAllRows();this.selectRow(k);this._oAnchorRecord=this.getRecord(k);}},_handleCellBlockSelectionByMouse:function(A){var B=A.target;var l=this.getTdEl(B);if(l){var z=A.event;var q=z.shiftKey;var m=z.ctrlKey||((navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&z.metaKey);var s=this.getTrEl(l);var r=this.getTrIndex(s);var v=this.getColumn(l);var w=v.getKeyIndex();var u=this.getRecord(s);var D=this._oRecordSet.getRecordIndex(u);var p={record:u,column:v};var t=this._getSelectionAnchor();var o=this.getTbodyEl().rows;var n,k,C,y,x;if(q&&m){if(t){if(this.isSelected(t.cell)){if(t.recordIndex===D){if(t.colKeyIndex=r;y--){for(x=k;x>=n;x--){this.selectCell(o[y].cells[x]);}}}}}else{if(t.recordIndex===D){if(t.colKeyIndext.colKeyIndex){this.unselectCell(C.cells[x]);}}else{if(C.sectionRowIndex===r){if(xw){this.unselectCell(C.cells[x]);}}else{if(C.sectionRowIndex==t.trIndex){if(x36)&&(j<41)){var u=this._getSelectionTrigger();if(!u){return null;}g.stopEvent(o);var r=this._getSelectionAnchor(u);var k,s,l,q,m;var p=this.getTbodyEl().rows;var n=u.el.parentNode;if(j==40){if(r.recordIndex<=u.recordIndex){m=this.getNextTrEl(u.el);if(m){s=r.colKeyIndex;l=u.colKeyIndex;if(s>l){for(k=s;k>=l;k--){q=m.cells[k];this.selectCell(q);}}else{for(k=s;k<=l;k++){q=m.cells[k];this.selectCell(q);}}}}else{s=Math.min(r.colKeyIndex,u.colKeyIndex);l=Math.max(r.colKeyIndex,u.colKeyIndex);for(k=s;k<=l;k++){this.unselectCell(n.cells[k]);}}}else{if(j==38){if(r.recordIndex>=u.recordIndex){m=this.getPreviousTrEl(u.el); if(m){s=r.colKeyIndex;l=u.colKeyIndex;if(s>l){for(k=s;k>=l;k--){q=m.cells[k];this.selectCell(q);}}else{for(k=s;k<=l;k++){q=m.cells[k];this.selectCell(q);}}}}else{s=Math.min(r.colKeyIndex,u.colKeyIndex);l=Math.max(r.colKeyIndex,u.colKeyIndex);for(k=s;k<=l;k++){this.unselectCell(n.cells[k]);}}}else{if(j==39){if(r.colKeyIndex<=u.colKeyIndex){if(u.colKeyIndexl){for(k=s;k>=l;k--){q=p[k].cells[u.colKeyIndex+1];this.selectCell(q);}}else{for(k=s;k<=l;k++){q=p[k].cells[u.colKeyIndex+1];this.selectCell(q);}}}}else{s=Math.min(r.trIndex,u.trIndex);l=Math.max(r.trIndex,u.trIndex);for(k=s;k<=l;k++){this.unselectCell(p[k].cells[u.colKeyIndex]);}}}else{if(j==37){if(r.colKeyIndex>=u.colKeyIndex){if(u.colKeyIndex>0){s=r.trIndex;l=u.trIndex;if(s>l){for(k=s;k>=l;k--){q=p[k].cells[u.colKeyIndex-1];this.selectCell(q);}}else{for(k=s;k<=l;k++){q=p[k].cells[u.colKeyIndex-1];this.selectCell(q);}}}}else{s=Math.min(r.trIndex,u.trIndex);l=Math.max(r.trIndex,u.trIndex);for(k=s;k<=l;k++){this.unselectCell(p[k].cells[u.colKeyIndex]);}}}}}}}},_handleCellRangeSelectionByMouse:function(y){var z=y.target;var k=this.getTdEl(z);if(k){var x=y.event;var o=x.shiftKey;var l=x.ctrlKey||((navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&x.metaKey);var q=this.getTrEl(k);var p=this.getTrIndex(q);var t=this.getColumn(k);var u=t.getKeyIndex();var s=this.getRecord(q);var B=this._oRecordSet.getRecordIndex(s);var n={record:s,column:t};var r=this._getSelectionAnchor();var m=this.getTbodyEl().rows;var A,w,v;if(o&&l){if(r){if(this.isSelected(r.cell)){if(r.recordIndex===B){if(r.colKeyIndexr.colKeyIndex){this.unselectCell(A.cells[v]);}}else{if(A.sectionRowIndex===p){if(vu){this.unselectCell(A.cells[v]);}}else{if(A.sectionRowIndex==r.trIndex){if(v=r.colKeyIndex){this.selectCell(A.cells[v]);}}else{if(A.sectionRowIndex==p){if(v<=u){this.selectCell(A.cells[v]);}}else{this.selectCell(A.cells[v]);}}}}}else{for(w=p;w<=r.trIndex;w++){A=m[w];for(v=0;v=u){this.selectCell(A.cells[v]);}}else{if(A.sectionRowIndex==r.trIndex){if(v<=r.colKeyIndex){this.selectCell(A.cells[v]);}}else{this.selectCell(A.cells[v]);}}}}}}}else{this._oAnchorCell=n;this.selectCell(n);}}else{if(l){this._oAnchorCell=n;if(this.isSelected(n)){this.unselectCell(n);}else{this.selectCell(n);}}else{this._handleSingleCellSelectionByMouse(y);}}}}},_handleCellRangeSelectionByKey:function(n){var j=g.getCharCode(n);var r=n.shiftKey;if((j==9)||!r){this._handleSingleCellSelectionByKey(n);return;}if((j>36)&&(j<41)){var s=this._getSelectionTrigger();if(!s){return null;}g.stopEvent(n);var q=this._getSelectionAnchor(s);var k,l,p;var o=this.getTbodyEl().rows;var m=s.el.parentNode;if(j==40){l=this.getNextTrEl(s.el);if(q.recordIndex<=s.recordIndex){for(k=s.colKeyIndex+1;k=s.recordIndex){for(k=s.colKeyIndex-1;k>-1;k--){p=m.cells[k];this.selectCell(p);}if(l){for(k=m.cells.length-1;k>=s.colKeyIndex;k--){p=l.cells[k];this.selectCell(p);}}}else{for(k=s.colKeyIndex;k>-1;k--){this.unselectCell(m.cells[k]);}if(l){for(k=m.cells.length-1;k>s.colKeyIndex;k--){this.unselectCell(l.cells[k]);}}}}else{if(j==39){l=this.getNextTrEl(s.el);if(q.recordIndexs.recordIndex){this.unselectCell(m.cells[s.colKeyIndex]);if(s.colKeyIndex0){}else{}}else{if(q.recordIndex>s.recordIndex){if(s.colKeyIndex>0){p=m.cells[s.colKeyIndex-1];this.selectCell(p);}else{if(s.trIndex>0){p=l.cells[l.cells.length-1];this.selectCell(p); }}}else{if(q.colKeyIndex>=s.colKeyIndex){if(s.colKeyIndex>0){p=m.cells[s.colKeyIndex-1];this.selectCell(p);}else{if(s.trIndex>0){p=l.cells[l.cells.length-1];this.selectCell(p);}}}else{this.unselectCell(m.cells[s.colKeyIndex]);if(s.colKeyIndex>0){}else{}}}}}}}}}},_handleSingleCellSelectionByMouse:function(n){var o=n.target;var k=this.getTdEl(o);if(k){var j=this.getTrEl(k);var i=this.getRecord(j);var m=this.getColumn(k);var l={record:i,column:m};this._oAnchorCell=l;this.unselectAllCells();this.selectCell(l);}},_handleSingleCellSelectionByKey:function(m){var i=g.getCharCode(m);if((i==9)||((i>36)&&(i<41))){var k=m.shiftKey;var j=this._getSelectionTrigger();if(!j){return null;}var l;if(i==40){l=this.getBelowTdEl(j.el);if(l===null){l=j.el;}}else{if(i==38){l=this.getAboveTdEl(j.el);if(l===null){l=j.el;}}else{if((i==39)||(!k&&(i==9))){l=this.getNextTdEl(j.el);if(l===null){return;}}else{if((i==37)||(k&&(i==9))){l=this.getPreviousTdEl(j.el);if(l===null){return;}}}}}g.stopEvent(m);this.unselectAllCells();this.selectCell(l);this._oAnchorCell={record:this.getRecord(l),column:this.getColumn(l)};}},getSelectedTrEls:function(){return c.getElementsByClassName(d.CLASS_SELECTED,"tr",this._elTbody);},selectRow:function(p){var o,i;if(p instanceof YAHOO.widget.Record){o=this._oRecordSet.getRecord(p);i=this.getTrEl(o);}else{if(h.isNumber(p)){o=this.getRecord(p);i=this.getTrEl(o);}else{i=this.getTrEl(p);o=this.getRecord(i);}}if(o){var n=this._aSelections||[];var m=o.getId();var l=-1;if(n.indexOf){l=n.indexOf(m);}else{for(var k=n.length-1;k>-1;k--){if(n[k]===m){l=k;break;}}}if(l>-1){n.splice(l,1);}n.push(m);this._aSelections=n;if(!this._oAnchorRecord){this._oAnchorRecord=o;}if(i){c.addClass(i,d.CLASS_SELECTED);}this.fireEvent("rowSelectEvent",{record:o,el:i});}else{}},unselectRow:function(p){var i=this.getTrEl(p);var o;if(p instanceof YAHOO.widget.Record){o=this._oRecordSet.getRecord(p);}else{if(h.isNumber(p)){o=this.getRecord(p);}else{o=this.getRecord(i);}}if(o){var n=this._aSelections||[];var m=o.getId();var l=-1;if(n.indexOf){l=n.indexOf(m);}else{for(var k=n.length-1;k>-1;k--){if(n[k]===m){l=k;break;}}}if(l>-1){n.splice(l,1);this._aSelections=n;c.removeClass(i,d.CLASS_SELECTED);this.fireEvent("rowUnselectEvent",{record:o,el:i});return;}}},unselectAllRows:function(){var k=this._aSelections||[],m,l=[];for(var i=k.length-1;i>-1;i--){if(h.isString(k[i])){m=k.splice(i,1);l[l.length]=this.getRecord(h.isArray(m)?m[0]:m);}}this._aSelections=k;this._unselectAllTrEls();this.fireEvent("unselectAllRowsEvent",{records:l});},_unselectAllTdEls:function(){var i=c.getElementsByClassName(d.CLASS_SELECTED,"td",this._elTbody);c.removeClass(i,d.CLASS_SELECTED);},getSelectedTdEls:function(){return c.getElementsByClassName(d.CLASS_SELECTED,"td",this._elTbody);},selectCell:function(i){var p=this.getTdEl(i);if(p){var o=this.getRecord(p);var q=this.getColumn(this.getCellIndex(p));var m=q.getKey();if(o&&m){var n=this._aSelections||[];var l=o.getId();for(var k=n.length-1;k>-1;k--){if((n[k].recordId===l)&&(n[k].columnKey===m)){n.splice(k,1);break;}}n.push({recordId:l,columnKey:m});this._aSelections=n;if(!this._oAnchorCell){this._oAnchorCell={record:o,column:q};}c.addClass(p,d.CLASS_SELECTED);this.fireEvent("cellSelectEvent",{record:o,column:q,key:m,el:p});return;}}},unselectCell:function(i){var o=this.getTdEl(i);if(o){var n=this.getRecord(o);var p=this.getColumn(this.getCellIndex(o));var l=p.getKey();if(n&&l){var m=this._aSelections||[];var q=n.getId();for(var k=m.length-1;k>-1;k--){if((m[k].recordId===q)&&(m[k].columnKey===l)){m.splice(k,1);this._aSelections=m;c.removeClass(o,d.CLASS_SELECTED);this.fireEvent("cellUnselectEvent",{record:n,column:p,key:l,el:o});return;}}}}},unselectAllCells:function(){var k=this._aSelections||[];for(var i=k.length-1;i>-1;i--){if(h.isObject(k[i])){k.splice(i,1);}}this._aSelections=k;this._unselectAllTdEls();this.fireEvent("unselectAllCellsEvent");},isSelected:function(p){if(p&&(p.ownerDocument==document)){return(c.hasClass(this.getTdEl(p),d.CLASS_SELECTED)||c.hasClass(this.getTrEl(p),d.CLASS_SELECTED));}else{var n,k,i;var m=this._aSelections;if(m&&m.length>0){if(p instanceof YAHOO.widget.Record){n=p;}else{if(h.isNumber(p)){n=this.getRecord(p);}}if(n){k=n.getId();if(m.indexOf){if(m.indexOf(k)>-1){return true;}}else{for(i=m.length-1;i>-1;i--){if(m[i]===k){return true;}}}}else{if(p.record&&p.column){k=p.record.getId();var l=p.column.getKey();for(i=m.length-1;i>-1;i--){if((m[i].recordId===k)&&(m[i].columnKey===l)){return true;}}}}}}return false;},getSelectedRows:function(){var i=[];var l=this._aSelections||[];for(var k=0;k0){for(var j=k.length-1;j>-1;j--){if(h.isString(k[j])){return k[j];}}}},getLastSelectedCell:function(){var k=this._aSelections;if(k&&k.length>0){for(var j=k.length-1;j>-1;j--){if(k[j].recordId&&k[j].columnKey){return k[j];}}}},highlightRow:function(k){var i=this.getTrEl(k);if(i){var j=this.getRecord(i);c.addClass(i,d.CLASS_HIGHLIGHTED);this.fireEvent("rowHighlightEvent",{record:j,el:i});return;}},unhighlightRow:function(k){var i=this.getTrEl(k);if(i){var j=this.getRecord(i);c.removeClass(i,d.CLASS_HIGHLIGHTED);this.fireEvent("rowUnhighlightEvent",{record:j,el:i});return;}},highlightCell:function(i){var l=this.getTdEl(i);if(l){if(this._elLastHighlightedTd){this.unhighlightCell(this._elLastHighlightedTd);}var k=this.getRecord(l);var m=this.getColumn(this.getCellIndex(l));var j=m.getKey();c.addClass(l,d.CLASS_HIGHLIGHTED);this._elLastHighlightedTd=l;this.fireEvent("cellHighlightEvent",{record:k,column:m,key:j,el:l});return;}},unhighlightCell:function(i){var k=this.getTdEl(i);if(k){var j=this.getRecord(k);c.removeClass(k,d.CLASS_HIGHLIGHTED);this._elLastHighlightedTd=null;this.fireEvent("cellUnhighlightEvent",{record:j,column:this.getColumn(this.getCellIndex(k)),key:this.getColumn(this.getCellIndex(k)).getKey(),el:k}); return;}},addCellEditor:function(j,i){j.editor=i;j.editor.subscribe("showEvent",this._onEditorShowEvent,this,true);j.editor.subscribe("keydownEvent",this._onEditorKeydownEvent,this,true);j.editor.subscribe("revertEvent",this._onEditorRevertEvent,this,true);j.editor.subscribe("saveEvent",this._onEditorSaveEvent,this,true);j.editor.subscribe("cancelEvent",this._onEditorCancelEvent,this,true);j.editor.subscribe("blurEvent",this._onEditorBlurEvent,this,true);j.editor.subscribe("blockEvent",this._onEditorBlockEvent,this,true);j.editor.subscribe("unblockEvent",this._onEditorUnblockEvent,this,true);},getCellEditor:function(){return this._oCellEditor;},showCellEditor:function(p,q,l){p=this.getTdEl(p);if(p){l=this.getColumn(p);if(l&&l.editor){var j=this._oCellEditor;if(j){if(this._oCellEditor.cancel){this._oCellEditor.cancel();}else{if(j.isActive){this.cancelCellEditor();}}}if(l.editor instanceof YAHOO.widget.BaseCellEditor){j=l.editor;var n=j.attach(this,p);if(n){j.render();j.move();n=this.doBeforeShowCellEditor(j);if(n){j.show();this._oCellEditor=j;}}}else{if(!q||!(q instanceof YAHOO.widget.Record)){q=this.getRecord(p);}if(!l||!(l instanceof YAHOO.widget.Column)){l=this.getColumn(p);}if(q&&l){if(!this._oCellEditor||this._oCellEditor.container){this._initCellEditorEl();}j=this._oCellEditor;j.cell=p;j.record=q;j.column=l;j.validator=(l.editorOptions&&h.isFunction(l.editorOptions.validator))?l.editorOptions.validator:null;j.value=q.getData(l.key);j.defaultValue=null;var k=j.container;var o=c.getX(p);var m=c.getY(p);if(isNaN(o)||isNaN(m)){o=p.offsetLeft+c.getX(this._elTbody.parentNode)-this._elTbody.scrollLeft;m=p.offsetTop+c.getY(this._elTbody.parentNode)-this._elTbody.scrollTop+this._elThead.offsetHeight;}k.style.left=o+"px";k.style.top=m+"px";this.doBeforeShowCellEditor(this._oCellEditor);k.style.display="";g.addListener(k,"keydown",function(s,r){if((s.keyCode==27)){r.cancelCellEditor();r.focusTbodyEl();}else{r.fireEvent("editorKeydownEvent",{editor:r._oCellEditor,event:s});}},this);var i;if(h.isString(l.editor)){switch(l.editor){case"checkbox":i=d.editCheckbox;break;case"date":i=d.editDate;break;case"dropdown":i=d.editDropdown;break;case"radio":i=d.editRadio;break;case"textarea":i=d.editTextarea;break;case"textbox":i=d.editTextbox;break;default:i=null;}}else{if(h.isFunction(l.editor)){i=l.editor;}}if(i){i(this._oCellEditor,this);if(!l.editorOptions||!l.editorOptions.disableBtns){this.showCellEditorBtns(k);}j.isActive=true;this.fireEvent("editorShowEvent",{editor:j});return;}}}}}},_initCellEditorEl:function(){var i=document.createElement("div");i.id=this._sId+"-celleditor";i.style.display="none";i.tabIndex=0;c.addClass(i,d.CLASS_EDITOR);var k=c.getFirstChild(document.body);if(k){i=c.insertBefore(i,k);}else{i=document.body.appendChild(i);}var j={};j.container=i;j.value=null;j.isActive=false;this._oCellEditor=j;},doBeforeShowCellEditor:function(i){return true;},saveCellEditor:function(){if(this._oCellEditor){if(this._oCellEditor.save){this._oCellEditor.save();}else{if(this._oCellEditor.isActive){var i=this._oCellEditor.value;var j=this._oCellEditor.record.getData(this._oCellEditor.column.key);if(this._oCellEditor.validator){i=this._oCellEditor.value=this._oCellEditor.validator.call(this,i,j,this._oCellEditor);if(i===null){this.resetCellEditor();this.fireEvent("editorRevertEvent",{editor:this._oCellEditor,oldData:j,newData:i});return;}}this._oRecordSet.updateRecordValue(this._oCellEditor.record,this._oCellEditor.column.key,this._oCellEditor.value);this.formatCell(this._oCellEditor.cell.firstChild,this._oCellEditor.record,this._oCellEditor.column);this._oChainRender.add({method:function(){this.validateColumnWidths();},scope:this});this._oChainRender.run();this.resetCellEditor();this.fireEvent("editorSaveEvent",{editor:this._oCellEditor,oldData:j,newData:i});}}}},cancelCellEditor:function(){if(this._oCellEditor){if(this._oCellEditor.cancel){this._oCellEditor.cancel();}else{if(this._oCellEditor.isActive){this.resetCellEditor();this.fireEvent("editorCancelEvent",{editor:this._oCellEditor});}}}},destroyCellEditor:function(){if(this._oCellEditor){this._oCellEditor.destroy();this._oCellEditor=null;}},_onEditorShowEvent:function(i){this.fireEvent("editorShowEvent",i);},_onEditorKeydownEvent:function(i){this.fireEvent("editorKeydownEvent",i);},_onEditorRevertEvent:function(i){this.fireEvent("editorRevertEvent",i);},_onEditorSaveEvent:function(i){this.fireEvent("editorSaveEvent",i);},_onEditorCancelEvent:function(i){this.fireEvent("editorCancelEvent",i);},_onEditorBlurEvent:function(i){this.fireEvent("editorBlurEvent",i);},_onEditorBlockEvent:function(i){this.fireEvent("editorBlockEvent",i);},_onEditorUnblockEvent:function(i){this.fireEvent("editorUnblockEvent",i);},onEditorBlurEvent:function(i){if(i.editor.disableBtns){if(i.editor.save){i.editor.save();}}else{if(i.editor.cancel){i.editor.cancel();}}},onEditorBlockEvent:function(i){this.disable();},onEditorUnblockEvent:function(i){this.undisable();},doBeforeLoadData:function(i,j,k){return true;},onEventSortColumn:function(k){var i=k.event;var m=k.target;var j=this.getThEl(m)||this.getTdEl(m);if(j){var l=this.getColumn(j);if(l.sortable){g.stopEvent(i);this.sortColumn(l);}}else{}},onEventSelectColumn:function(i){this.selectColumn(i.target);},onEventHighlightColumn:function(i){this.highlightColumn(i.target);},onEventUnhighlightColumn:function(i){this.unhighlightColumn(i.target);},onEventSelectRow:function(j){var i=this.get("selectionMode");if(i=="single"){this._handleSingleSelectionByMouse(j);}else{this._handleStandardSelectionByMouse(j);}},onEventSelectCell:function(j){var i=this.get("selectionMode");if(i=="cellblock"){this._handleCellBlockSelectionByMouse(j);}else{if(i=="cellrange"){this._handleCellRangeSelectionByMouse(j);}else{this._handleSingleCellSelectionByMouse(j);}}},onEventHighlightRow:function(i){this.highlightRow(i.target);},onEventUnhighlightRow:function(i){this.unhighlightRow(i.target);},onEventHighlightCell:function(i){this.highlightCell(i.target); },onEventUnhighlightCell:function(i){this.unhighlightCell(i.target);},onEventFormatCell:function(i){var l=i.target;var j=this.getTdEl(l);if(j){var k=this.getColumn(this.getCellIndex(j));this.formatCell(j.firstChild,this.getRecord(j),k);}else{}},onEventShowCellEditor:function(i){if(!this.isDisabled()){this.showCellEditor(i.target);}},onEventSaveCellEditor:function(i){if(this._oCellEditor){if(this._oCellEditor.save){this._oCellEditor.save();}else{this.saveCellEditor();}}},onEventCancelCellEditor:function(i){if(this._oCellEditor){if(this._oCellEditor.cancel){this._oCellEditor.cancel();}else{this.cancelCellEditor();}}},onDataReturnInitializeTable:function(i,j,k){if((this instanceof d)&&this._sId){this.initializeTable();this.onDataReturnSetRows(i,j,k);}},onDataReturnReplaceRows:function(m,l,n){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:m,response:l,payload:n});var j=this.doBeforeLoadData(m,l,n),k=this.get("paginator"),i=0;if(j&&l&&!l.error&&h.isArray(l.results)){this._oRecordSet.reset();if(this.get("dynamicData")){if(n&&n.pagination&&h.isNumber(n.pagination.recordOffset)){i=n.pagination.recordOffset;}else{if(k){i=k.getStartIndex();}}}this._oRecordSet.setRecords(l.results,i|0);this._handleDataReturnPayload(m,l,n);this.render();}else{if(j&&l.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR);}}}},onDataReturnAppendRows:function(j,k,l){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:j,response:k,payload:l});var i=this.doBeforeLoadData(j,k,l);if(i&&k&&!k.error&&h.isArray(k.results)){this.addRows(k.results);this._handleDataReturnPayload(j,k,l);}else{if(i&&k.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR);}}}},onDataReturnInsertRows:function(j,k,l){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:j,response:k,payload:l});var i=this.doBeforeLoadData(j,k,l);if(i&&k&&!k.error&&h.isArray(k.results)){this.addRows(k.results,(l?l.insertIndex:0));this._handleDataReturnPayload(j,k,l);}else{if(i&&k.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR);}}}},onDataReturnUpdateRows:function(j,k,l){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:j,response:k,payload:l});var i=this.doBeforeLoadData(j,k,l);if(i&&k&&!k.error&&h.isArray(k.results)){this.updateRows((l?l.updateIndex:0),k.results);this._handleDataReturnPayload(j,k,l);}else{if(i&&k.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR);}}}},onDataReturnSetRows:function(m,l,n){if((this instanceof d)&&this._sId){this.fireEvent("dataReturnEvent",{request:m,response:l,payload:n});var j=this.doBeforeLoadData(m,l,n),k=this.get("paginator"),i=0;if(j&&l&&!l.error&&h.isArray(l.results)){if(this.get("dynamicData")){if(n&&n.pagination&&h.isNumber(n.pagination.recordOffset)){i=n.pagination.recordOffset;}else{if(k){i=k.getStartIndex();}}this._oRecordSet.reset();}this._oRecordSet.setRecords(l.results,i|0);this._handleDataReturnPayload(m,l,n);this.render();}else{if(j&&l.error){this.showTableMessage(this.get("MSG_ERROR"),d.CLASS_ERROR);}}}else{}},handleDataReturnPayload:function(j,i,k){return k||{};},_handleDataReturnPayload:function(k,j,l){l=this.handleDataReturnPayload(k,j,l);if(l){var i=this.get("paginator");if(i){if(this.get("dynamicData")){if(e.Paginator.isNumeric(l.totalRecords)){i.set("totalRecords",l.totalRecords);}}else{i.set("totalRecords",this._oRecordSet.getLength());}if(h.isObject(l.pagination)){i.set("rowsPerPage",l.pagination.rowsPerPage);i.set("recordOffset",l.pagination.recordOffset);}}if(l.sortedBy){this.set("sortedBy",l.sortedBy);}else{if(l.sorting){this.set("sortedBy",l.sorting);}}}},showCellEditorBtns:function(k){var l=k.appendChild(document.createElement("div"));c.addClass(l,d.CLASS_BUTTON);var j=l.appendChild(document.createElement("button"));c.addClass(j,d.CLASS_DEFAULT);j.innerHTML="OK";g.addListener(j,"click",function(n,m){m.onEventSaveCellEditor(n,m);m.focusTbodyEl();},this,true);var i=l.appendChild(document.createElement("button"));i.innerHTML="Cancel";g.addListener(i,"click",function(n,m){m.onEventCancelCellEditor(n,m);m.focusTbodyEl();},this,true);},resetCellEditor:function(){var i=this._oCellEditor.container;i.style.display="none";g.purgeElement(i,true);i.innerHTML="";this._oCellEditor.value=null;this._oCellEditor.isActive=false;},getBody:function(){return this.getTbodyEl();},getCell:function(i){return this.getTdEl(i);},getRow:function(i){return this.getTrEl(i);},refreshView:function(){this.render();},select:function(k){if(!h.isArray(k)){k=[k];}for(var j=0;j0)?"-"+this._elTbody.offsetTop+"px":0;},_focusEl:function(l){l=l||this._elTbody;var k=this;this._storeScrollPositions();setTimeout(function(){setTimeout(function(){try{l.focus();k._restoreScrollPositions();}catch(m){}},0);},0);},_runRenderChain:function(){this._storeScrollPositions();this._oChainRender.run();},_storeScrollPositions:function(){this._nScrollTop=this._elBdContainer.scrollTop;this._nScrollLeft=this._elBdContainer.scrollLeft;},clearScrollPositions:function(){this._nScrollTop=0;this._nScrollLeft=0;},_restoreScrollPositions:function(){if(this._nScrollTop){this._elBdContainer.scrollTop=this._nScrollTop;this._nScrollTop=null;}if(this._nScrollLeft){this._elBdContainer.scrollLeft=this._nScrollLeft;this._elHdContainer.scrollLeft=this._nScrollLeft;this._nScrollLeft=null;}},_validateColumnWidth:function(n,k){if(!n.width&&!n.hidden){var p=n.getThEl();if(n._calculatedWidth){this._setColumnWidth(n,"auto","visible");}if(p.offsetWidth!==k.offsetWidth){var m=(p.offsetWidth>k.offsetWidth)?n.getThLinerEl():k.firstChild;var l=Math.max(0,(m.offsetWidth-(parseInt(d.getStyle(m,"paddingLeft"),10)|0)-(parseInt(d.getStyle(m,"paddingRight"),10)|0)),n.minWidth);var o="visible";if((n.maxAutoWidth>0)&&(l>n.maxAutoWidth)){l=n.maxAutoWidth;o="hidden";}this._elTbody.style.display="none";this._setColumnWidth(n,l+"px",o);n._calculatedWidth=l;this._elTbody.style.display="";}}},validateColumnWidths:function(s){var u=this._oColumnSet.keys,w=u.length,l=this.getFirstTrEl();if(a.ie){this._setOverhangValue(1);}if(u&&l&&(l.childNodes.length===w)){var m=this.get("width");if(m){this._elHdContainer.style.width="";this._elBdContainer.style.width="";}this._elContainer.style.width="";if(s&&c.isNumber(s.getKeyIndex())){this._validateColumnWidth(s,l.childNodes[s.getKeyIndex()]);}else{var t,k=[],o,q,r;for(q=0;qt.offsetWidth)?s.getThLinerEl():t.firstChild;var p=Math.max(0,(v.offsetWidth-(parseInt(d.getStyle(v,"paddingLeft"),10)|0)-(parseInt(d.getStyle(v,"paddingRight"),10)|0)),s.minWidth);var x="visible";if((s.maxAutoWidth>0)&&(p>s.maxAutoWidth)){p=s.maxAutoWidth;x="hidden";}k[k.length]=[s,p,x];}}}this._elTbody.style.display="none";for(q=0,r=k.length;ql.clientHeight)?(k.parentNode.clientWidth+19)+"px":(k.parentNode.clientWidth+2)+"px";}},_syncScrollX:function(){var k=this._elTbody,l=this._elBdContainer;if(!this.get("height")&&(a.ie)){l.style.height=(l.scrollWidth>l.offsetWidth)?(k.parentNode.offsetHeight+18)+"px":k.parentNode.offsetHeight+"px";}if(this._elTbody.rows.length===0){this._elMsgTbody.parentNode.style.width=this.getTheadEl().parentNode.offsetWidth+"px";}else{this._elMsgTbody.parentNode.style.width="";}},_syncScrollOverhang:function(){var l=this._elBdContainer,k=1;if((l.scrollHeight>l.clientHeight)&&(l.scrollWidth>l.clientWidth)){k=18;}this._setOverhangValue(k);},_setOverhangValue:function(n){var p=this._oColumnSet.headers[this._oColumnSet.headers.length-1]||[],l=p.length,k=this._sId+"-fixedth-",o=n+"px solid "+this.get("COLOR_COLUMNFILLER");this._elThead.style.display="none";for(var m=0;ml.minWidth)?k:l.minWidth;l.width=k;this._setColumnWidth(l,k+"px");this._syncScroll();this.fireEvent("columnSetWidthEvent",{column:l,width:k});}else{if(k===null){l.width=k;this._setColumnWidth(l,"auto");this.validateColumnWidths(l);this.fireEvent("columnUnsetWidthEvent",{column:l});}}this._clearTrTemplateEl();}else{}},scrollTo:function(m){var l=this.getTdEl(m);if(l){this.clearScrollPositions();this.getBdContainerEl().scrollLeft=l.offsetLeft;this.getBdContainerEl().scrollTop=l.parentNode.offsetTop;}else{var k=this.getTrEl(m);if(k){this.clearScrollPositions();this.getBdContainerEl().scrollTop=k.offsetTop;}}},showTableMessage:function(o,k){var p=this._elMsgTd;if(c.isString(o)){p.firstChild.innerHTML=o;}if(c.isString(k)){d.addClass(p.firstChild,k);}var n=this.getTheadEl();var l=n.parentNode;var m=l.offsetWidth;this._elMsgTbody.parentNode.style.width=this.getTheadEl().parentNode.offsetWidth+"px";this._elMsgTbody.style.display="";this.fireEvent("tableMsgShowEvent",{html:o,className:k});},_onColumnChange:function(k){var l=(k.column)?k.column:(k.editor)?k.editor.column:null;this._storeScrollPositions();this.validateColumnWidths(l);},_onScroll:function(m,l){l._elHdContainer.scrollLeft=l._elBdContainer.scrollLeft;if(l._oCellEditor&&l._oCellEditor.isActive){l.fireEvent("editorBlurEvent",{editor:l._oCellEditor});l.cancelCellEditor();}var n=j.getTarget(m);var k=n.nodeName.toLowerCase();l.fireEvent("tableScrollEvent",{event:m,target:n});},_onTheadKeydown:function(n,l){if(j.getCharCode(n)===9){setTimeout(function(){if((l instanceof h)&&l._sId){l._elBdContainer.scrollLeft=l._elHdContainer.scrollLeft;}},0);}var o=j.getTarget(n);var k=o.nodeName.toLowerCase();var m=true;while(o&&(k!="table")){switch(k){case"body":return;case"input":case"textarea":break;case"thead":m=l.fireEvent("theadKeyEvent",{target:o,event:n});break;default:break;}if(m===false){return;}else{o=o.parentNode;if(o){k=o.nodeName.toLowerCase();}}}l.fireEvent("tableKeyEvent",{target:(o||l._elContainer),event:n});}});})();(function(){var c=YAHOO.lang,f=YAHOO.util,e=YAHOO.widget,b=YAHOO.env.ua,d=f.Dom,i=f.Event,h=e.DataTable;e.BaseCellEditor=function(k,j){this._sId=this._sId||d.generateId(null,"yui-ceditor");YAHOO.widget.BaseCellEditor._nCount++;this._sType=k;this._initConfigs(j);this._initEvents();this._needsRender=true;};var a=e.BaseCellEditor;c.augmentObject(a,{_nCount:0,CLASS_CELLEDITOR:"yui-ceditor"});a.prototype={_sId:null,_sType:null,_oDataTable:null,_oColumn:null,_oRecord:null,_elTd:null,_elContainer:null,_elCancelBtn:null,_elSaveBtn:null,_initConfigs:function(k){if(k&&YAHOO.lang.isObject(k)){for(var j in k){if(j){this[j]=k[j];}}}},_initEvents:function(){this.createEvent("showEvent");this.createEvent("keydownEvent");this.createEvent("invalidDataEvent");this.createEvent("revertEvent");this.createEvent("saveEvent");this.createEvent("cancelEvent");this.createEvent("blurEvent");this.createEvent("blockEvent");this.createEvent("unblockEvent");},_initContainerEl:function(){if(this._elContainer){YAHOO.util.Event.purgeElement(this._elContainer,true);this._elContainer.innerHTML="";}var j=document.createElement("div");j.id=this.getId()+"-container";j.style.display="none";j.tabIndex=0;this.className=c.isArray(this.className)?this.className:this.className?[this.className]:[];this.className[this.className.length]=h.CLASS_EDITOR;j.className=this.className.join(" ");document.body.insertBefore(j,document.body.firstChild);this._elContainer=j;},_initShimEl:function(){if(this.useIFrame){if(!this._elIFrame){var j=document.createElement("iframe"); j.src="javascript:false";j.frameBorder=0;j.scrolling="no";j.style.display="none";j.className=h.CLASS_EDITOR_SHIM;j.tabIndex=-1;j.role="presentation";j.title="Presentational iframe shim";document.body.insertBefore(j,document.body.firstChild);this._elIFrame=j;}}},_hide:function(){this.getContainerEl().style.display="none";if(this._elIFrame){this._elIFrame.style.display="none";}this.isActive=false;this.getDataTable()._oCellEditor=null;},asyncSubmitter:null,value:null,defaultValue:null,validator:null,resetInvalidData:true,isActive:false,LABEL_SAVE:"Save",LABEL_CANCEL:"Cancel",disableBtns:false,useIFrame:false,className:null,toString:function(){return"CellEditor instance "+this._sId;},getId:function(){return this._sId;},getDataTable:function(){return this._oDataTable;},getColumn:function(){return this._oColumn;},getRecord:function(){return this._oRecord;},getTdEl:function(){return this._elTd;},getContainerEl:function(){return this._elContainer;},destroy:function(){this.unsubscribeAll();var k=this.getColumn();if(k){k.editor=null;}var j=this.getContainerEl();if(j){i.purgeElement(j,true);j.parentNode.removeChild(j);}},render:function(){if(!this._needsRender){return;}this._initContainerEl();this._initShimEl();i.addListener(this.getContainerEl(),"keydown",function(l,j){if((l.keyCode==27)){var k=i.getTarget(l);if(k.nodeName&&k.nodeName.toLowerCase()==="select"){k.blur();}j.cancel();}j.fireEvent("keydownEvent",{editor:j,event:l});},this);this.renderForm();if(!this.disableBtns){this.renderBtns();}this.doAfterRender();this._needsRender=false;},renderBtns:function(){var l=this.getContainerEl().appendChild(document.createElement("div"));l.className=h.CLASS_BUTTON;var k=l.appendChild(document.createElement("button"));k.className=h.CLASS_DEFAULT;k.innerHTML=this.LABEL_SAVE;i.addListener(k,"click",function(m){this.save();},this,true);this._elSaveBtn=k;var j=l.appendChild(document.createElement("button"));j.innerHTML=this.LABEL_CANCEL;i.addListener(j,"click",function(m){this.cancel();},this,true);this._elCancelBtn=j;},attach:function(n,l){if(n instanceof YAHOO.widget.DataTable){this._oDataTable=n;l=n.getTdEl(l);if(l){this._elTd=l;var m=n.getColumn(l);if(m){this._oColumn=m;var j=n.getRecord(l);if(j){this._oRecord=j;var k=j.getData(this.getColumn().getField());this.value=(k!==undefined)?k:this.defaultValue;return true;}}}}return false;},move:function(){var m=this.getContainerEl(),l=this.getTdEl(),j=d.getX(l),n=d.getY(l);if(isNaN(j)||isNaN(n)){var k=this.getDataTable().getTbodyEl();j=l.offsetLeft+d.getX(k.parentNode)-k.scrollLeft;n=l.offsetTop+d.getY(k.parentNode)-k.scrollTop+this.getDataTable().getTheadEl().offsetHeight;}m.style.left=j+"px";m.style.top=n+"px";if(this._elIFrame){this._elIFrame.style.left=j+"px";this._elIFrame.style.top=n+"px";}},show:function(){var k=this.getContainerEl(),j=this._elIFrame;this.resetForm();this.isActive=true;k.style.display="";if(j){j.style.width=k.offsetWidth+"px";j.style.height=k.offsetHeight+"px";j.style.display="";}this.focus();this.fireEvent("showEvent",{editor:this});},block:function(){this.fireEvent("blockEvent",{editor:this});},unblock:function(){this.fireEvent("unblockEvent",{editor:this});},save:function(){var k=this.getInputValue();var l=k;if(this.validator){l=this.validator.call(this.getDataTable(),k,this.value,this);if(l===undefined){if(this.resetInvalidData){this.resetForm();}this.fireEvent("invalidDataEvent",{editor:this,oldData:this.value,newData:k});return;}}var m=this;var j=function(o,n){var p=m.value;if(o){m.value=n;m.getDataTable().updateCell(m.getRecord(),m.getColumn(),n);m._hide();m.fireEvent("saveEvent",{editor:m,oldData:p,newData:m.value});}else{m.resetForm();m.fireEvent("revertEvent",{editor:m,oldData:p,newData:n});}m.unblock();};this.block();if(c.isFunction(this.asyncSubmitter)){this.asyncSubmitter.call(this,j,l);}else{j(true,l);}},cancel:function(){if(this.isActive){this._hide();this.fireEvent("cancelEvent",{editor:this});}else{}},renderForm:function(){},doAfterRender:function(){},handleDisabledBtns:function(){},resetForm:function(){},focus:function(){},getInputValue:function(){}};c.augmentProto(a,f.EventProvider);e.CheckboxCellEditor=function(j){j=j||{};this._sId=this._sId||d.generateId(null,"yui-checkboxceditor");YAHOO.widget.BaseCellEditor._nCount++;e.CheckboxCellEditor.superclass.constructor.call(this,j.type||"checkbox",j);};c.extend(e.CheckboxCellEditor,a,{checkboxOptions:null,checkboxes:null,value:null,renderForm:function(){if(c.isArray(this.checkboxOptions)){var n,o,q,l,m,k;for(m=0,k=this.checkboxOptions.length;m';l=this.getContainerEl().appendChild(document.createElement("label"));l.htmlFor=q;l.innerHTML=c.isValue(n.label)?n.label:n;}var p=[];for(m=0;m';o=this.getContainerEl().appendChild(document.createElement("label"));o.htmlFor=r;o.innerHTML=(c.isValue(k.label))?k.label:k;}var q=[],s;for(var m=0;m420){j=this.getContainerEl().appendChild(document.createElement("form")).appendChild(document.createElement("input"));}else{j=this.getContainerEl().appendChild(document.createElement("input"));}j.type="text";this.textbox=j;i.addListener(j,"keypress",function(k){if((k.keyCode===13)){YAHOO.util.Event.preventDefault(k);this.save();}},this,true);if(this.disableBtns){this.handleDisabledBtns();}},move:function(){this.textbox.style.width=this.getTdEl().offsetWidth+"px";e.TextboxCellEditor.superclass.move.call(this);},resetForm:function(){this.textbox.value=c.isValue(this.value)?this.value.toString():"";},focus:function(){this.getDataTable()._focusEl(this.textbox);this.textbox.select();},getInputValue:function(){return this.textbox.value; }});c.augmentObject(e.TextboxCellEditor,a);h.Editors={checkbox:e.CheckboxCellEditor,"date":e.DateCellEditor,dropdown:e.DropdownCellEditor,radio:e.RadioCellEditor,textarea:e.TextareaCellEditor,textbox:e.TextboxCellEditor};e.CellEditor=function(k,j){if(k&&h.Editors[k]){c.augmentObject(a,h.Editors[k]);return new h.Editors[k](j);}else{return new a(null,j);}};var g=e.CellEditor;c.augmentObject(g,a);})();YAHOO.register("datatable",YAHOO.widget.DataTable,{version:"2.9.0",build:"2800"}); }, '2.9.0' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-event", "yui2-skin-sam-datatable", "yui2-element", "yui2-datasource"], "optional": ["yui2-skin-sam-paginator", "yui2-paginator", "yui2-dragdrop", "yui2-skin-sam-calendar", "yui2-calendar"]}); PK\#3=s" s" 72in3/2.9.0/build/yui2-datatable/yui2-datatable-debug.jsnu[YUI.add('yui2-datatable', function(Y) { var YAHOO = Y.YUI2; /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ /** * Mechanism to execute a series of callbacks in a non-blocking queue. Each callback is executed via setTimout unless configured with a negative timeout, in which case it is run in blocking mode in the same execution thread as the previous callback. Callbacks can be function references or object literals with the following keys: *
              *
            • method - {Function} REQUIRED the callback function.
            • *
            • scope - {Object} the scope from which to execute the callback. Default is the global window scope.
            • *
            • argument - {Array} parameters to be passed to method as individual arguments.
            • *
            • timeout - {number} millisecond delay to wait after previous callback completion before executing this callback. Negative values cause immediate blocking execution. Default 0.
            • *
            • until - {Function} boolean function executed before each iteration. Return true to indicate completion and proceed to the next callback.
            • *
            • iterations - {Number} number of times to execute the callback before proceeding to the next callback in the chain. Incompatible with until.
            • *
            * * @namespace YAHOO.util * @class Chain * @constructor * @param callback* {Function|Object} Any number of callbacks to initialize the queue */ YAHOO.util.Chain = function () { /** * The callback queue * @property q * @type {Array} * @private */ this.q = [].slice.call(arguments); /** * Event fired when the callback queue is emptied via execution (not via * a call to chain.stop(). * @event end */ this.createEvent('end'); }; YAHOO.util.Chain.prototype = { /** * Timeout id used to pause or stop execution and indicate the execution state of the Chain. 0 indicates paused or stopped, -1 indicates blocking execution, and any positive number indicates non-blocking execution. * @property id * @type {number} * @private */ id : 0, /** * Begin executing the chain, or resume execution from the last paused position. * @method run * @return {Chain} the Chain instance */ run : function () { // Grab the first callback in the queue var c = this.q[0], fn; // If there is no callback in the queue or the Chain is currently // in an execution mode, return if (!c) { this.fireEvent('end'); return this; } else if (this.id) { return this; } fn = c.method || c; if (typeof fn === 'function') { var o = c.scope || {}, args = c.argument || [], ms = c.timeout || 0, me = this; if (!(args instanceof Array)) { args = [args]; } // Execute immediately if the callback timeout is negative. if (ms < 0) { this.id = ms; if (c.until) { for (;!c.until();) { // Execute the callback from scope, with argument fn.apply(o,args); } } else if (c.iterations) { for (;c.iterations-- > 0;) { fn.apply(o,args); } } else { fn.apply(o,args); } this.q.shift(); this.id = 0; return this.run(); } else { // If the until condition is set, check if we're done if (c.until) { if (c.until()) { // Shift this callback from the queue and execute the next // callback this.q.shift(); return this.run(); } // Otherwise if either iterations is not set or we're // executing the last iteration, shift callback from the queue } else if (!c.iterations || !--c.iterations) { this.q.shift(); } // Otherwise set to execute after the configured timeout this.id = setTimeout(function () { // Execute the callback from scope, with argument fn.apply(o,args); // Check if the Chain was not paused from inside the callback if (me.id) { // Indicate ready to run state me.id = 0; // Start the fun all over again me.run(); } },ms); } } return this; }, /** * Add a callback to the end of the queue * @method add * @param c {Function|Object} the callback function ref or object literal * @return {Chain} the Chain instance */ add : function (c) { this.q.push(c); return this; }, /** * Pause the execution of the Chain after the current execution of the * current callback completes. If called interstitially, clears the * timeout for the pending callback. Paused Chains can be restarted with * chain.run() * @method pause * @return {Chain} the Chain instance */ pause: function () { // Conditional added for Caja compatibility if (this.id > 0) { clearTimeout(this.id); } this.id = 0; return this; }, /** * Stop and clear the Chain's queue after the current execution of the * current callback completes. * @method stop * @return {Chain} the Chain instance */ stop : function () { this.pause(); this.q = []; return this; } }; YAHOO.lang.augmentProto(YAHOO.util.Chain,YAHOO.util.EventProvider); /** * Augments the Event Utility with a delegate method that * facilitates easy creation of delegated event listeners. (Note: Using CSS * selectors as the filtering criteria for delegated event listeners requires * inclusion of the Selector Utility.) * * @module event-delegate * @title Event Utility Event Delegation Module * @namespace YAHOO.util * @requires event */ (function () { var Event = YAHOO.util.Event, Lang = YAHOO.lang, delegates = [], getMatch = function(el, selector, container) { var returnVal; if (!el || el === container) { returnVal = false; } else { returnVal = YAHOO.util.Selector.test(el, selector) ? el: getMatch(el.parentNode, selector, container); } return returnVal; }; Lang.augmentObject(Event, { /** * Creates a delegate function used to call event listeners specified * via the YAHOO.util.Event.delegate method. * * @method _createDelegate * * @param {Function} fn The method (event listener) to call. * @param {Function|string} filter Function or CSS selector used to * determine for what element(s) the event listener should be called. * @param {Object} obj An arbitrary object that will be * passed as a parameter to the listener. * @param {Boolean|object} overrideContext If true, the value of the * obj parameter becomes the execution context * of the listener. If an object, this object * becomes the execution context. * @return {Function} Function that will call the event listener * specified by the YAHOO.util.Event.delegate method. * @private * @for Event * @static */ _createDelegate: function (fn, filter, obj, overrideContext) { return function (event) { var container = this, target = Event.getTarget(event), selector = filter, // The user might have specified the document object // as the delegation container, in which case it is not // nessary to scope the provided CSS selector(s) to the // delegation container bDocument = (container.nodeType === 9), matchedEl, context, sID, sIDSelector; if (Lang.isFunction(filter)) { matchedEl = filter(target); } else if (Lang.isString(filter)) { if (!bDocument) { sID = container.id; if (!sID) { sID = Event.generateId(container); } // Scope all selectors to the container sIDSelector = ("#" + sID + " "); selector = (sIDSelector + filter).replace(/,/gi, ("," + sIDSelector)); } if (YAHOO.util.Selector.test(target, selector)) { matchedEl = target; } else if (YAHOO.util.Selector.test(target, ((selector.replace(/,/gi, " *,")) + " *"))) { // The target is a descendant of an element matching // the selector, so crawl up to find the ancestor that // matches the selector matchedEl = getMatch(target, selector, container); } } if (matchedEl) { // The default context for delegated listeners is the // element that matched the filter. context = matchedEl; if (overrideContext) { if (overrideContext === true) { context = obj; } else { context = overrideContext; } } // Call the listener passing in the container and the // element that matched the filter in case the user // needs those. return fn.call(context, event, matchedEl, container, obj); } }; }, /** * Appends a delegated event listener. Delegated event listeners * receive three arguments by default: the DOM event, the element * specified by the filtering function or CSS selector, and the * container element (the element to which the event listener is * bound). (Note: Using the delegate method requires the event-delegate * module. Using CSS selectors as the filtering criteria for delegated * event listeners requires inclusion of the Selector Utility.) * * @method delegate * * @param {String|HTMLElement|Array|NodeList} container An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {String} type The type of event listener to append * @param {Function} fn The method the event invokes * @param {Function|string} filter Function or CSS selector used to * determine for what element(s) the event listener should be called. * When a function is specified, the function should return an * HTML element. Using a CSS Selector requires the inclusion of the * CSS Selector Utility. * @param {Object} obj An arbitrary object that will be * passed as a parameter to the listener * @param {Boolean|object} overrideContext If true, the value of the obj parameter becomes * the execution context of the listener. If an * object, this object becomes the execution * context. * @return {Boolean} Returns true if the action was successful or defered, * false if one or more of the elements * could not have the listener attached, * or if the operation throws an exception. * @static * @for Event */ delegate: function (container, type, fn, filter, obj, overrideContext) { var sType = type, fnMouseDelegate, fnDelegate; if (Lang.isString(filter) && !YAHOO.util.Selector) { YAHOO.log("Using a CSS selector to define the filtering criteria for a delegated listener requires the Selector Utility.", "error", "Event"); return false; } if (type == "mouseenter" || type == "mouseleave") { if (!Event._createMouseDelegate) { YAHOO.log("Delegating a " + type + " event requires the event-mouseenter module.", "error", "Event"); return false; } // Look up the real event--either mouseover or mouseout sType = Event._getType(type); fnMouseDelegate = Event._createMouseDelegate(fn, obj, overrideContext); fnDelegate = Event._createDelegate(function (event, matchedEl, container) { return fnMouseDelegate.call(matchedEl, event, container); }, filter, obj, overrideContext); } else { fnDelegate = Event._createDelegate(fn, filter, obj, overrideContext); } delegates.push([container, sType, fn, fnDelegate]); return Event.on(container, sType, fnDelegate); }, /** * Removes a delegated event listener. * * @method removeDelegate * * @param {String|HTMLElement|Array|NodeList} container An id, an element * reference, or a collection of ids and/or elements to remove * the listener from. * @param {String} type The type of event to remove. * @param {Function} fn The method the event invokes. If fn is * undefined, then all event listeners for the type of event are * removed. * @return {boolean} Returns true if the unbind was successful, false * otherwise. * @static * @for Event */ removeDelegate: function (container, type, fn) { var sType = type, returnVal = false, index, cacheItem; // Look up the real event--either mouseover or mouseout if (type == "mouseenter" || type == "mouseleave") { sType = Event._getType(type); } index = Event._getCacheIndex(delegates, container, sType, fn); if (index >= 0) { cacheItem = delegates[index]; } if (container && cacheItem) { returnVal = Event.removeListener(cacheItem[0], cacheItem[1], cacheItem[3]); if (returnVal) { delete delegates[index][2]; delete delegates[index][3]; delegates.splice(index, 1); } } return returnVal; } }); }()); /** * Augments the Event Utility with support for the mouseenter and mouseleave * events: A mouseenter event fires the first time the mouse enters an * element; a mouseleave event first the first time the mouse leaves an * element. * * @module event-mouseenter * @title Event Utility mouseenter and mouseout Module * @namespace YAHOO.util * @requires event */ (function () { var Event = YAHOO.util.Event, Lang = YAHOO.lang, addListener = Event.addListener, removeListener = Event.removeListener, getListeners = Event.getListeners, delegates = [], specialTypes = { mouseenter: "mouseover", mouseleave: "mouseout" }, remove = function(el, type, fn) { var index = Event._getCacheIndex(delegates, el, type, fn), cacheItem, returnVal; if (index >= 0) { cacheItem = delegates[index]; } if (el && cacheItem) { // removeListener will translate the value of type returnVal = removeListener.call(Event, cacheItem[0], type, cacheItem[3]); if (returnVal) { delete delegates[index][2]; delete delegates[index][3]; delegates.splice(index, 1); } } return returnVal; }; Lang.augmentObject(Event._specialTypes, specialTypes); Lang.augmentObject(Event, { /** * Creates a delegate function used to call mouseover and mouseleave * event listeners specified via the * YAHOO.util.Event.addListener * or YAHOO.util.Event.on method. * * @method _createMouseDelegate * * @param {Function} fn The method (event listener) to call * @param {Object} obj An arbitrary object that will be * passed as a parameter to the listener * @param {Boolean|object} overrideContext If true, the value of the * obj parameter becomes the execution context * of the listener. If an object, this object * becomes the execution context. * @return {Function} Function that will call the event listener * specified by either the YAHOO.util.Event.addListener * or YAHOO.util.Event.on method. * @private * @static * @for Event */ _createMouseDelegate: function (fn, obj, overrideContext) { return function (event, container) { var el = this, relatedTarget = Event.getRelatedTarget(event), context, args; if (el != relatedTarget && !YAHOO.util.Dom.isAncestor(el, relatedTarget)) { context = el; if (overrideContext) { if (overrideContext === true) { context = obj; } else { context = overrideContext; } } // The default args passed back to a mouseenter or // mouseleave listener are: the event, and any object // the user passed when subscribing args = [event, obj]; // Add the element and delegation container as arguments // when delegating mouseenter and mouseleave if (container) { args.splice(1, 0, el, container); } return fn.apply(context, args); } }; }, addListener: function (el, type, fn, obj, overrideContext) { var fnDelegate, returnVal; if (specialTypes[type]) { fnDelegate = Event._createMouseDelegate(fn, obj, overrideContext); fnDelegate.mouseDelegate = true; delegates.push([el, type, fn, fnDelegate]); // addListener will translate the value of type returnVal = addListener.call(Event, el, type, fnDelegate); } else { returnVal = addListener.apply(Event, arguments); } return returnVal; }, removeListener: function (el, type, fn) { var returnVal; if (specialTypes[type]) { returnVal = remove.apply(Event, arguments); } else { returnVal = removeListener.apply(Event, arguments); } return returnVal; }, getListeners: function (el, type) { // If the user specified the type as mouseover or mouseout, // need to filter out those used by mouseenter and mouseleave. // If the user specified the type as mouseenter or mouseleave, // need to filter out the true mouseover and mouseout listeners. var listeners = [], elListeners, bMouseOverOrOut = (type === "mouseover" || type === "mouseout"), bMouseDelegate, i, l; if (type && (bMouseOverOrOut || specialTypes[type])) { elListeners = getListeners.call(Event, el, this._getType(type)); if (elListeners) { for (i=elListeners.length-1; i>-1; i--) { l = elListeners[i]; bMouseDelegate = l.fn.mouseDelegate; if ((specialTypes[type] && bMouseDelegate) || (bMouseOverOrOut && !bMouseDelegate)) { listeners.push(l); } } } } else { listeners = getListeners.apply(Event, arguments); } return (listeners && listeners.length) ? listeners : null; } }, true); Event.on = Event.addListener; }()); YAHOO.register("event-mouseenter", YAHOO.util.Event, {version: "2.9.0", build: "2800"}); var Y = YAHOO, Y_DOM = YAHOO.util.Dom, EMPTY_ARRAY = [], Y_UA = Y.env.ua, Y_Lang = Y.lang, Y_DOC = document, Y_DOCUMENT_ELEMENT = Y_DOC.documentElement, Y_DOM_inDoc = Y_DOM.inDocument, Y_mix = Y_Lang.augmentObject, Y_guid = Y_DOM.generateId, Y_getDoc = function(element) { var doc = Y_DOC; if (element) { doc = (element.nodeType === 9) ? element : // element === document element.ownerDocument || // element === DOM node element.document || // element === window Y_DOC; // default } return doc; }, Y_Array = function(o, startIdx) { var l, a, start = startIdx || 0; // IE errors when trying to slice HTMLElement collections try { return Array.prototype.slice.call(o, start); } catch (e) { a = []; l = o.length; for (; start < l; start++) { a.push(o[start]); } return a; } }, Y_DOM_allById = function(id, root) { root = root || Y_DOC; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_getDoc(root).getElementById(id)]; } return ret; }; /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument', Selector = { _foundCache: [], useNative: true, _compare: ('sourceIndex' in Y_DOCUMENT_ELEMENT) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y_DOCUMENT_ELEMENT[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y_Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { if (typeof root == 'string') { root = Y_DOM.get(root); if (!root) { return (firstOnly) ? null : []; } } else { root = root || Y_DOC; } var ret = [], useNative = (Selector.useNative && Y_DOC.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Selector._nativeQuery : Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y_Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } Y.log('query: ' + selector + ' returning: ' + ret.length, 'info', 'Selector'); return (firstOnly) ? (ret[0] || null) : ret; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { var groups = selector.split(','), queries = [], prefix = '', i, len; if (node) { // enforce for element scoping if (node.tagName) { node.id = node.id || Y_guid(); prefix = '[id="' + node.id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y_UA.webkit && selector.indexOf(':checked') > -1 && (Selector.pseudos && Selector.pseudos.checked)) { // webkit (chrome, safari) fails to find "selected" return Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { //Y.log('trying native query with: ' + selector, 'info', 'selector-native'); return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available //Y.log('native query error; reverting to brute query with: ' + selector, 'info', 'selector-native'); return Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Selector.test(node, selector)) { ret[ret.length] = node; } } } else { Y.log('invalid filter input (nodes: ' + nodes + ', selector: ' + selector + ')', 'warn', 'Selector'); } return ret; }, test: function(node, selector, root) { var ret = false, groups = selector.split(','), useFrag = false, parent, item, items, frag, i, j, group; if (node && node.tagName) { // only test HTMLElements // we need a root if off-doc if (!root && !Y_DOM_inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; if (!node.id) { node.id = Y_guid(); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + node.id + '"]'; items = Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } } return ret; } }; YAHOO.util.Selector = Selector; /** * 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 = 'pseudos', SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, // TODO: move? SORT_RESULTS: true, _children: function(node, tag) { var ret = node.children, i, children = [], childNodes, child; if (node.children && tag && node.children.tags) { children = node.children.tags(tag); } else if ((!ret && node[TAG_NAME]) || (ret && tag)) { // only HTMLElements have children childNodes = ret || node.childNodes; ret = []; for (i = 0; (child = childNodes[i++]);) { if (child.tagName) { if (!tag || tag === child.tagName) { ret.push(child); } } } } return ret || []; }, _re: { //attr: /(\[.*\])/g, attr: /(\[[^\]]*\])/g, //esc: /\\[:\[][\w\d\]]*/gi, esc: /\\[:\[\]\(\)#\.\'\>+~"]/gi, //pseudos: /:([\-\w]+(?:\(?:['"]?(.+)['"]?\))*)/i pseudos: /(\([^\)]*\))/g }, /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { //'\\#([^\\s\\\\(\\[:]*)': '[id=$1]', '\\#(-?[_a-z]+[-\\w\\uE000]*)': '[id=$1]', //'\\#([^\\s\\\.:\\[\\]]*)': '[id=$1]', //'\\.([^\\s\\\\(\\[:]*)': '[className=$1]' '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return !!node.getAttribute(attr); }, // Just test for existence of attribute //'': '.+', //'=': '^{val}$', // equality '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}(?:-|$)' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Selector._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y_getDoc(root), child, id, className, tagName; // if we have an initial ID, set to root when in document /* if (tokens[0] && rootDoc === root && (id = tokens[0].id) && rootDoc.getElementById(id)) { root = rootDoc.getElementById(id); } */ if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) // TODO: move to allById? if (id && (root.all || (root.nodeType === 9 || Y_DOM_inDoc(root)))) { nodes = Y_DOM_allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName('*') child = root.firstChild; while (child) { if (child.tagName) { // only collect HTMLElements nodes.push(child); } child = child.nextSilbing || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Selector.getters, operator, combinator, token, path, pass, //FUNCTION = 'function', value, tests, test; //do { for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; // use getAttribute for non-standard attributes if (value === undefined && tmpNode.getAttribute) { value = tmpNode.getAttribute(test[0]); } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } }// while (tmpNode = node = nodes[++i]); node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, //re: /^\[(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\]]*?)['"]?\]/i, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y_DOCUMENT_ELEMENT.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1].toUpperCase(); token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /** Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._replaceShorthand(Y_Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed Y.log('query: ' + query + ' contains unsupported token in: ' + selector, 'warn', 'Selector'); tokens = []; } return tokens; }, _replaceShorthand: function(selector) { var shorthand = Selector.shorthand, esc = selector.match(Selector._re.esc), // pull escaped colon, brackets, etc. attrs, pseudos, re, i, len; if (esc) { selector = selector.replace(Selector._re.esc, '\uE000'); } attrs = selector.match(Selector._re.attr); pseudos = selector.match(Selector._re.pseudos); if (attrs) { selector = selector.replace(Selector._re.attr, '\uE001'); } if (pseudos) { selector = selector.replace(Selector._re.pseudos, '\uE002'); } for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } if (attrs) { for (i = 0, len = attrs.length; i < len; ++i) { selector = selector.replace(/\uE001/, attrs[i]); } } if (pseudos) { for (i = 0, len = pseudos.length; i < len; ++i) { selector = selector.replace(/\uE002/, pseudos[i]); } } selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); if (esc) { for (i = 0, len = esc.length; i < len; ++i) { selector = selector.replace('\uE000', esc[i]); } } return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y_DOM.getAttribute(node, attr); } } }; Y_mix(Selector, SelectorCSS2, true); Selector.getters.src = Selector.getters.rel = Selector.getters.href; // IE wants class with native queries if (Selector.useNative && Y_DOC.querySelector) { Selector.shorthand['\\.([^\\s\\\\(\\[:]*)'] = '[class~=$1]'; } /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Selector._getNth = function(node, expr, tag, reverse) { Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Selector._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y_mix(Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Selector._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Selector._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Selector._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Selector._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Selector._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y_mix(Selector.operators, { '^=': '^{val}', // Match starts with value '!=': function(node, attr, val) { return node[attr] !== val; }, // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Selector.combinators['~'] = { axis: 'previousSibling' }; YAHOO.register("selector", YAHOO.util.Selector, {version: "2.9.0", build: "2800"}); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ var Dom = YAHOO.util.Dom; /** * The ColumnSet class defines and manages a DataTable's Columns, * including nested hierarchies and access to individual Column instances. * * @namespace YAHOO.widget * @class ColumnSet * @uses YAHOO.util.EventProvider * @constructor * @param aDefinitions {Object[]} Array of object literals that define cells in * the THEAD. */ YAHOO.widget.ColumnSet = function(aDefinitions) { this._sId = Dom.generateId(null, "yui-cs"); // "yui-cs" + YAHOO.widget.ColumnSet._nCount; // First clone the defs aDefinitions = YAHOO.widget.DataTable._cloneObject(aDefinitions); this._init(aDefinitions); YAHOO.widget.ColumnSet._nCount++; YAHOO.log("ColumnSet initialized", "info", this.toString()); }; ///////////////////////////////////////////////////////////////////////////// // // Private member variables // ///////////////////////////////////////////////////////////////////////////// /** * Internal class variable to index multiple ColumnSet instances. * * @property ColumnSet._nCount * @type Number * @private * @static */ YAHOO.widget.ColumnSet._nCount = 0; YAHOO.widget.ColumnSet.prototype = { /** * Unique instance name. * * @property _sId * @type String * @private */ _sId : null, /** * Array of object literal Column definitions passed to the constructor. * * @property _aDefinitions * @type Object[] * @private */ _aDefinitions : null, ///////////////////////////////////////////////////////////////////////////// // // Public member variables // ///////////////////////////////////////////////////////////////////////////// /** * Top-down tree representation of Column hierarchy. * * @property tree * @type YAHOO.widget.Column[] */ tree : null, /** * Flattened representation of all Columns. * * @property flat * @type YAHOO.widget.Column[] * @default [] */ flat : null, /** * Array of Columns that map one-to-one to a table column. * * @property keys * @type YAHOO.widget.Column[] * @default [] */ keys : null, /** * ID index of nested parent hierarchies for HEADERS accessibility attribute. * * @property headers * @type String[] * @default [] */ headers : null, ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Initializes ColumnSet instance with data from Column definitions. * * @method _init * @param aDefinitions {Object[]} Array of object literals that define cells in * the THEAD . * @private */ _init : function(aDefinitions) { // DOM tree representation of all Columns var tree = []; // Flat representation of all Columns var flat = []; // Flat representation of only Columns that are meant to display data var keys = []; // Array of HEADERS attribute values for all keys in the "keys" array var headers = []; // Tracks current node list depth being tracked var nodeDepth = -1; // Internal recursive function to define Column instances var parseColumns = function(nodeList, parent) { // One level down nodeDepth++; // Create corresponding tree node if not already there for this depth if(!tree[nodeDepth]) { tree[nodeDepth] = []; } // Parse each node at this depth for attributes and any children for(var j=0; j maxRowDepth) { maxRowDepth = tmpRowDepth; } } } }; // Count max row depth for each row for(var m=0; m-1; i--) { if(allColumns[i]._sId === column) { return allColumns[i]; } } } return null; }, /** * Returns Column instance with given key or ColumnSet key index. * * @method getColumn * @param column {String | Number} Column key or ColumnSet key index. * @return {YAHOO.widget.Column} Column instance. */ getColumn : function(column) { if(YAHOO.lang.isNumber(column) && this.keys[column]) { return this.keys[column]; } else if(YAHOO.lang.isString(column)) { var allColumns = this.flat; var aColumns = []; for(var i=0; i 1) { return aColumns; } } return null; }, /** * Public accessor returns array of given Column's desendants (if any), including itself. * * @method getDescendants * @parem {YAHOO.widget.Column} Column instance. * @return {Array} Array including the Column itself and all descendants (if any). */ getDescendants : function(oColumn) { var oSelf = this; var allDescendants = []; var i; // Recursive function to loop thru all children var parse = function(oParent) { allDescendants.push(oParent); // This Column has children if(oParent.children) { for(i=0; i
          * * @class AutoComplete * @constructor * @param elInput {HTMLElement} DOM element reference of an input field. * @param elInput {String} String ID of an input field. * @param elContainer {HTMLElement} DOM element reference of an existing DIV. * @param elContainer {String} String ID of an existing DIV. * @param oDataSource {YAHOO.widget.DataSource} DataSource instance. * @param oConfigs {Object} (optional) Object literal of configuration params. */ YAHOO.widget.AutoComplete = function(elInput,elContainer,oDataSource,oConfigs) { if(elInput && elContainer && oDataSource) { // Validate DataSource if(oDataSource && YAHOO.lang.isFunction(oDataSource.sendRequest)) { this.dataSource = oDataSource; } else { return; } // YAHOO.widget.DataSource schema backwards compatibility // Converted deprecated schema into supported schema // First assume key data is held in position 0 of results array this.key = 0; var schema = oDataSource.responseSchema; // An old school schema has been defined in the deprecated DataSource constructor if(oDataSource._aDeprecatedSchema) { var aDeprecatedSchema = oDataSource._aDeprecatedSchema; if(YAHOO.lang.isArray(aDeprecatedSchema)) { if((oDataSource.responseType === YAHOO.util.DataSourceBase.TYPE_JSON) || (oDataSource.responseType === YAHOO.util.DataSourceBase.TYPE_UNKNOWN)) { // Used to default to unknown // Store the resultsList schema.resultsList = aDeprecatedSchema[0]; // Store the key this.key = aDeprecatedSchema[1]; // Only resultsList and key are defined, so grab all the data schema.fields = (aDeprecatedSchema.length < 3) ? null : aDeprecatedSchema.slice(1); } else if(oDataSource.responseType === YAHOO.util.DataSourceBase.TYPE_XML) { schema.resultNode = aDeprecatedSchema[0]; this.key = aDeprecatedSchema[1]; schema.fields = aDeprecatedSchema.slice(1); } else if(oDataSource.responseType === YAHOO.util.DataSourceBase.TYPE_TEXT) { schema.recordDelim = aDeprecatedSchema[0]; schema.fieldDelim = aDeprecatedSchema[1]; } oDataSource.responseSchema = schema; } } // Validate input element if(YAHOO.util.Dom.inDocument(elInput)) { if(YAHOO.lang.isString(elInput)) { this._sName = "instance" + YAHOO.widget.AutoComplete._nIndex + " " + elInput; this._elTextbox = document.getElementById(elInput); } else { this._sName = (elInput.id) ? "instance" + YAHOO.widget.AutoComplete._nIndex + " " + elInput.id: "instance" + YAHOO.widget.AutoComplete._nIndex; this._elTextbox = elInput; } YAHOO.util.Dom.addClass(this._elTextbox, "yui-ac-input"); } else { return; } // Validate container element if(YAHOO.util.Dom.inDocument(elContainer)) { if(YAHOO.lang.isString(elContainer)) { this._elContainer = document.getElementById(elContainer); } else { this._elContainer = elContainer; } if(this._elContainer.style.display == "none") { } // For skinning var elParent = this._elContainer.parentNode; var elTag = elParent.tagName.toLowerCase(); if(elTag == "div") { YAHOO.util.Dom.addClass(elParent, "yui-ac"); } else { } } else { return; } // Default applyLocalFilter setting is to enable for local sources if(this.dataSource.dataType === YAHOO.util.DataSourceBase.TYPE_LOCAL) { this.applyLocalFilter = true; } // Set any config params passed in to override defaults if(oConfigs && (oConfigs.constructor == Object)) { for(var sConfig in oConfigs) { if(sConfig) { this[sConfig] = oConfigs[sConfig]; } } } // Initialization sequence this._initContainerEl(); this._initProps(); this._initListEl(); this._initContainerHelperEls(); // Set up events var oSelf = this; var elTextbox = this._elTextbox; // Dom events YAHOO.util.Event.addListener(elTextbox,"keyup",oSelf._onTextboxKeyUp,oSelf); YAHOO.util.Event.addListener(elTextbox,"keydown",oSelf._onTextboxKeyDown,oSelf); YAHOO.util.Event.addListener(elTextbox,"focus",oSelf._onTextboxFocus,oSelf); YAHOO.util.Event.addListener(elTextbox,"blur",oSelf._onTextboxBlur,oSelf); YAHOO.util.Event.addListener(elContainer,"mouseover",oSelf._onContainerMouseover,oSelf); YAHOO.util.Event.addListener(elContainer,"mouseout",oSelf._onContainerMouseout,oSelf); YAHOO.util.Event.addListener(elContainer,"click",oSelf._onContainerClick,oSelf); YAHOO.util.Event.addListener(elContainer,"scroll",oSelf._onContainerScroll,oSelf); YAHOO.util.Event.addListener(elContainer,"resize",oSelf._onContainerResize,oSelf); YAHOO.util.Event.addListener(elTextbox,"keypress",oSelf._onTextboxKeyPress,oSelf); YAHOO.util.Event.addListener(window,"unload",oSelf._onWindowUnload,oSelf); // Custom events this.textboxFocusEvent = new YAHOO.util.CustomEvent("textboxFocus", this); this.textboxKeyEvent = new YAHOO.util.CustomEvent("textboxKey", this); this.dataRequestEvent = new YAHOO.util.CustomEvent("dataRequest", this); this.dataRequestCancelEvent = new YAHOO.util.CustomEvent("dataRequestCancel", this); this.dataReturnEvent = new YAHOO.util.CustomEvent("dataReturn", this); this.dataErrorEvent = new YAHOO.util.CustomEvent("dataError", this); this.containerPopulateEvent = new YAHOO.util.CustomEvent("containerPopulate", this); this.containerExpandEvent = new YAHOO.util.CustomEvent("containerExpand", this); this.typeAheadEvent = new YAHOO.util.CustomEvent("typeAhead", this); this.itemMouseOverEvent = new YAHOO.util.CustomEvent("itemMouseOver", this); this.itemMouseOutEvent = new YAHOO.util.CustomEvent("itemMouseOut", this); this.itemArrowToEvent = new YAHOO.util.CustomEvent("itemArrowTo", this); this.itemArrowFromEvent = new YAHOO.util.CustomEvent("itemArrowFrom", this); this.itemSelectEvent = new YAHOO.util.CustomEvent("itemSelect", this); this.unmatchedItemSelectEvent = new YAHOO.util.CustomEvent("unmatchedItemSelect", this); this.selectionEnforceEvent = new YAHOO.util.CustomEvent("selectionEnforce", this); this.containerCollapseEvent = new YAHOO.util.CustomEvent("containerCollapse", this); this.textboxBlurEvent = new YAHOO.util.CustomEvent("textboxBlur", this); this.textboxChangeEvent = new YAHOO.util.CustomEvent("textboxChange", this); // Finish up elTextbox.setAttribute("autocomplete","off"); YAHOO.widget.AutoComplete._nIndex++; } // Required arguments were not found else { } }; ///////////////////////////////////////////////////////////////////////////// // // Public member variables // ///////////////////////////////////////////////////////////////////////////// /** * The DataSource object that encapsulates the data used for auto completion. * This object should be an inherited object from YAHOO.widget.DataSource. * * @property dataSource * @type YAHOO.widget.DataSource */ YAHOO.widget.AutoComplete.prototype.dataSource = null; /** * By default, results from local DataSources will pass through the filterResults * method to apply a client-side matching algorithm. * * @property applyLocalFilter * @type Boolean * @default true for local arrays and json, otherwise false */ YAHOO.widget.AutoComplete.prototype.applyLocalFilter = null; /** * When applyLocalFilter is true, the local filtering algorthim can have case sensitivity * enabled. * * @property queryMatchCase * @type Boolean * @default false */ YAHOO.widget.AutoComplete.prototype.queryMatchCase = false; /** * When applyLocalFilter is true, results can be locally filtered to return * matching strings that "contain" the query string rather than simply "start with" * the query string. * * @property queryMatchContains * @type Boolean * @default false */ YAHOO.widget.AutoComplete.prototype.queryMatchContains = false; /** * Enables query subset matching. When the DataSource's cache is enabled and queryMatchSubset is * true, substrings of queries will return matching cached results. For * instance, if the first query is for "abc" susequent queries that start with * "abc", like "abcd", will be queried against the cache, and not the live data * source. Recommended only for DataSources that return comprehensive results * for queries with very few characters. * * @property queryMatchSubset * @type Boolean * @default false * */ YAHOO.widget.AutoComplete.prototype.queryMatchSubset = false; /** * Number of characters that must be entered before querying for results. A negative value * effectively turns off the widget. A value of 0 allows queries of null or empty string * values. * * @property minQueryLength * @type Number * @default 1 */ YAHOO.widget.AutoComplete.prototype.minQueryLength = 1; /** * Maximum number of results to display in results container. * * @property maxResultsDisplayed * @type Number * @default 10 */ YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed = 10; /** * Number of seconds to delay before submitting a query request. If a query * request is received before a previous one has completed its delay, the * previous request is cancelled and the new request is set to the delay. If * typeAhead is also enabled, this value must always be less than the typeAheadDelay * in order to avoid certain race conditions. * * @property queryDelay * @type Number * @default 0.2 */ YAHOO.widget.AutoComplete.prototype.queryDelay = 0.2; /** * If typeAhead is true, number of seconds to delay before updating input with * typeAhead value. In order to prevent certain race conditions, this value must * always be greater than the queryDelay. * * @property typeAheadDelay * @type Number * @default 0.5 */ YAHOO.widget.AutoComplete.prototype.typeAheadDelay = 0.5; /** * When IME usage is detected or interval detection is explicitly enabled, * AutoComplete will detect the input value at the given interval and send a * query if the value has changed. * * @property queryInterval * @type Number * @default 500 */ YAHOO.widget.AutoComplete.prototype.queryInterval = 500; /** * Class name of a highlighted item within results container. * * @property highlightClassName * @type String * @default "yui-ac-highlight" */ YAHOO.widget.AutoComplete.prototype.highlightClassName = "yui-ac-highlight"; /** * Class name of a pre-highlighted item within results container. * * @property prehighlightClassName * @type String */ YAHOO.widget.AutoComplete.prototype.prehighlightClassName = null; /** * Query delimiter. A single character separator for multiple delimited * selections. Multiple delimiter characteres may be defined as an array of * strings. A null value or empty string indicates that query results cannot * be delimited. This feature is not recommended if you need forceSelection to * be true. * * @property delimChar * @type String | String[] */ YAHOO.widget.AutoComplete.prototype.delimChar = null; /** * Whether or not the first item in results container should be automatically highlighted * on expand. * * @property autoHighlight * @type Boolean * @default true */ YAHOO.widget.AutoComplete.prototype.autoHighlight = true; /** * If autohighlight is enabled, whether or not the input field should be automatically updated * with the first query result as the user types, auto-selecting the substring portion * of the first result that the user has not yet typed. * * @property typeAhead * @type Boolean * @default false */ YAHOO.widget.AutoComplete.prototype.typeAhead = false; /** * Whether or not to animate the expansion/collapse of the results container in the * horizontal direction. * * @property animHoriz * @type Boolean * @default false */ YAHOO.widget.AutoComplete.prototype.animHoriz = false; /** * Whether or not to animate the expansion/collapse of the results container in the * vertical direction. * * @property animVert * @type Boolean * @default true */ YAHOO.widget.AutoComplete.prototype.animVert = true; /** * Speed of container expand/collapse animation, in seconds.. * * @property animSpeed * @type Number * @default 0.3 */ YAHOO.widget.AutoComplete.prototype.animSpeed = 0.3; /** * Whether or not to force the user's selection to match one of the query * results. Enabling this feature essentially transforms the input field into a * <select> field. This feature is not recommended with delimiter character(s) * defined. * * @property forceSelection * @type Boolean * @default false */ YAHOO.widget.AutoComplete.prototype.forceSelection = false; /** * Whether or not to allow browsers to cache user-typed input in the input * field. Disabling this feature will prevent the widget from setting the * autocomplete="off" on the input field. When autocomplete="off" * and users click the back button after form submission, user-typed input can * be prefilled by the browser from its cache. This caching of user input may * not be desired for sensitive data, such as credit card numbers, in which * case, implementers should consider setting allowBrowserAutocomplete to false. * * @property allowBrowserAutocomplete * @type Boolean * @default true */ YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete = true; /** * Enabling this feature prevents the toggling of the container to a collapsed state. * Setting to true does not automatically trigger the opening of the container. * Implementers are advised to pre-load the container with an explicit "sendQuery()" call. * * @property alwaysShowContainer * @type Boolean * @default false */ YAHOO.widget.AutoComplete.prototype.alwaysShowContainer = false; /** * Whether or not to use an iFrame to layer over Windows form elements in * IE. Set to true only when the results container will be on top of a * <select> field in IE and thus exposed to the IE z-index bug (i.e., * 5.5 < IE < 7). * * @property useIFrame * @type Boolean * @default false */ YAHOO.widget.AutoComplete.prototype.useIFrame = false; /** * Whether or not the results container should have a shadow. * * @property useShadow * @type Boolean * @default false */ YAHOO.widget.AutoComplete.prototype.useShadow = false; /** * Whether or not the input field should be updated with selections. * * @property suppressInputUpdate * @type Boolean * @default false */ YAHOO.widget.AutoComplete.prototype.suppressInputUpdate = false; /** * For backward compatibility to pre-2.6.0 formatResults() signatures, setting * resultsTypeList to true will take each object literal result returned by * DataSource and flatten into an array. * * @property resultTypeList * @type Boolean * @default true */ YAHOO.widget.AutoComplete.prototype.resultTypeList = true; /** * For XHR DataSources, AutoComplete will automatically insert a "?" between the server URI and * the "query" param/value pair. To prevent this behavior, implementers should * set this value to false. To more fully customize the query syntax, implementers * should override the generateRequest() method. * * @property queryQuestionMark * @type Boolean * @default true */ YAHOO.widget.AutoComplete.prototype.queryQuestionMark = true; /** * If true, before each time the container expands, the container element will be * positioned to snap to the bottom-left corner of the input element. If * autoSnapContainer is set to false, this positioning will not be done. * * @property autoSnapContainer * @type Boolean * @default true */ YAHOO.widget.AutoComplete.prototype.autoSnapContainer = true; ///////////////////////////////////////////////////////////////////////////// // // Public methods // ///////////////////////////////////////////////////////////////////////////// /** * Public accessor to the unique name of the AutoComplete instance. * * @method toString * @return {String} Unique name of the AutoComplete instance. */ YAHOO.widget.AutoComplete.prototype.toString = function() { return "AutoComplete " + this._sName; }; /** * Returns DOM reference to input element. * * @method getInputEl * @return {HTMLELement} DOM reference to input element. */ YAHOO.widget.AutoComplete.prototype.getInputEl = function() { return this._elTextbox; }; /** * Returns DOM reference to container element. * * @method getContainerEl * @return {HTMLELement} DOM reference to container element. */ YAHOO.widget.AutoComplete.prototype.getContainerEl = function() { return this._elContainer; }; /** * Returns true if widget instance is currently active. * * @method isFocused * @return {Boolean} Returns true if widget instance is currently active. */ YAHOO.widget.AutoComplete.prototype.isFocused = function() { return this._bFocused; }; /** * Returns true if container is in an expanded state, false otherwise. * * @method isContainerOpen * @return {Boolean} Returns true if container is in an expanded state, false otherwise. */ YAHOO.widget.AutoComplete.prototype.isContainerOpen = function() { return this._bContainerOpen; }; /** * Public accessor to the <ul> element that displays query results within the results container. * * @method getListEl * @return {HTMLElement[]} Reference to <ul> element within the results container. */ YAHOO.widget.AutoComplete.prototype.getListEl = function() { return this._elList; }; /** * Public accessor to the matching string associated with a given <li> result. * * @method getListItemMatch * @param elListItem {HTMLElement} Reference to <LI> element. * @return {String} Matching string. */ YAHOO.widget.AutoComplete.prototype.getListItemMatch = function(elListItem) { if(elListItem._sResultMatch) { return elListItem._sResultMatch; } else { return null; } }; /** * Public accessor to the result data associated with a given <li> result. * * @method getListItemData * @param elListItem {HTMLElement} Reference to <LI> element. * @return {Object} Result data. */ YAHOO.widget.AutoComplete.prototype.getListItemData = function(elListItem) { if(elListItem._oResultData) { return elListItem._oResultData; } else { return null; } }; /** * Public accessor to the index of the associated with a given <li> result. * * @method getListItemIndex * @param elListItem {HTMLElement} Reference to <LI> element. * @return {Number} Index. */ YAHOO.widget.AutoComplete.prototype.getListItemIndex = function(elListItem) { if(YAHOO.lang.isNumber(elListItem._nItemIndex)) { return elListItem._nItemIndex; } else { return null; } }; /** * Sets HTML markup for the results container header. This markup will be * inserted within a <div> tag with a class of "yui-ac-hd". * * @method setHeader * @param sHeader {HTML} HTML markup for results container header. */ YAHOO.widget.AutoComplete.prototype.setHeader = function(sHeader) { if(this._elHeader) { var elHeader = this._elHeader; if(sHeader) { elHeader.innerHTML = sHeader; elHeader.style.display = ""; } else { elHeader.innerHTML = ""; elHeader.style.display = "none"; } } }; /** * Sets HTML markup for the results container footer. This markup will be * inserted within a <div> tag with a class of "yui-ac-ft". * * @method setFooter * @param sFooter {HTML} HTML markup for results container footer. */ YAHOO.widget.AutoComplete.prototype.setFooter = function(sFooter) { if(this._elFooter) { var elFooter = this._elFooter; if(sFooter) { elFooter.innerHTML = sFooter; elFooter.style.display = ""; } else { elFooter.innerHTML = ""; elFooter.style.display = "none"; } } }; /** * Sets HTML markup for the results container body. This markup will be * inserted within a <div> tag with a class of "yui-ac-bd". * * @method setBody * @param sBody {HTML} HTML markup for results container body. */ YAHOO.widget.AutoComplete.prototype.setBody = function(sBody) { if(this._elBody) { var elBody = this._elBody; YAHOO.util.Event.purgeElement(elBody, true); if(sBody) { elBody.innerHTML = sBody; elBody.style.display = ""; } else { elBody.innerHTML = ""; elBody.style.display = "none"; } this._elList = null; } }; /** * A function that converts an AutoComplete query into a request value which is then * passed to the DataSource's sendRequest method in order to retrieve data for * the query. By default, returns a String with the syntax: "query={query}" * Implementers can customize this method for custom request syntaxes. * * @method generateRequest * @param sQuery {String} Query string * @return {MIXED} Request */ YAHOO.widget.AutoComplete.prototype.generateRequest = function(sQuery) { var dataType = this.dataSource.dataType; // Transform query string in to a request for remote data // By default, local data doesn't need a transformation, just passes along the query as is. if(dataType === YAHOO.util.DataSourceBase.TYPE_XHR) { // By default, XHR GET requests look like "{scriptURI}?{scriptQueryParam}={sQuery}&{scriptQueryAppend}" if(!this.dataSource.connMethodPost) { sQuery = (this.queryQuestionMark ? "?" : "") + (this.dataSource.scriptQueryParam || "query") + "=" + sQuery + (this.dataSource.scriptQueryAppend ? ("&" + this.dataSource.scriptQueryAppend) : ""); } // By default, XHR POST bodies are sent to the {scriptURI} like "{scriptQueryParam}={sQuery}&{scriptQueryAppend}" else { sQuery = (this.dataSource.scriptQueryParam || "query") + "=" + sQuery + (this.dataSource.scriptQueryAppend ? ("&" + this.dataSource.scriptQueryAppend) : ""); } } // By default, remote script node requests look like "{scriptURI}&{scriptCallbackParam}={callbackString}&{scriptQueryParam}={sQuery}&{scriptQueryAppend}" else if(dataType === YAHOO.util.DataSourceBase.TYPE_SCRIPTNODE) { sQuery = "&" + (this.dataSource.scriptQueryParam || "query") + "=" + sQuery + (this.dataSource.scriptQueryAppend ? ("&" + this.dataSource.scriptQueryAppend) : ""); } return sQuery; }; /** * Makes query request to the DataSource. * * @method sendQuery * @param sQuery {String} Query string. */ YAHOO.widget.AutoComplete.prototype.sendQuery = function(sQuery) { // Activate focus for a new interaction this._bFocused = true; // Adjust programatically sent queries to look like they were input by user // when delimiters are enabled var newQuery = (this.delimChar) ? this._elTextbox.value + sQuery : sQuery; this._sendQuery(newQuery); }; /** * Snaps container to bottom-left corner of input element * * @method snapContainer */ YAHOO.widget.AutoComplete.prototype.snapContainer = function() { var oTextbox = this._elTextbox, pos = YAHOO.util.Dom.getXY(oTextbox); pos[1] += YAHOO.util.Dom.get(oTextbox).offsetHeight + 2; YAHOO.util.Dom.setXY(this._elContainer,pos); }; /** * Expands container. * * @method expandContainer */ YAHOO.widget.AutoComplete.prototype.expandContainer = function() { this._toggleContainer(true); }; /** * Collapses container. * * @method collapseContainer */ YAHOO.widget.AutoComplete.prototype.collapseContainer = function() { this._toggleContainer(false); }; /** * Clears entire list of suggestions. * * @method clearList */ YAHOO.widget.AutoComplete.prototype.clearList = function() { var allItems = this._elList.childNodes, i=allItems.length-1; for(; i>-1; i--) { allItems[i].style.display = "none"; } }; /** * Handles subset matching for when queryMatchSubset is enabled. * * @method getSubsetMatches * @param sQuery {String} Query string. * @return {Object} oParsedResponse or null. */ YAHOO.widget.AutoComplete.prototype.getSubsetMatches = function(sQuery) { var subQuery, oCachedResponse, subRequest; // Loop through substrings of each cached element's query property... for(var i = sQuery.length; i >= this.minQueryLength ; i--) { subRequest = this.generateRequest(sQuery.substr(0,i)); this.dataRequestEvent.fire(this, subQuery, subRequest); // If a substring of the query is found in the cache oCachedResponse = this.dataSource.getCachedResponse(subRequest); if(oCachedResponse) { return this.filterResults.apply(this.dataSource, [sQuery, oCachedResponse, oCachedResponse, {scope:this}]); } } return null; }; /** * Executed by DataSource (within DataSource scope via doBeforeParseData()) to * handle responseStripAfter cleanup. * * @method preparseRawResponse * @param sQuery {String} Query string. * @return {Object} oParsedResponse or null. */ YAHOO.widget.AutoComplete.prototype.preparseRawResponse = function(oRequest, oFullResponse, oCallback) { var nEnd = ((this.responseStripAfter !== "") && (oFullResponse.indexOf)) ? oFullResponse.indexOf(this.responseStripAfter) : -1; if(nEnd != -1) { oFullResponse = oFullResponse.substring(0,nEnd); } return oFullResponse; }; /** * Executed by DataSource (within DataSource scope via doBeforeCallback()) to * filter results through a simple client-side matching algorithm. * * @method filterResults * @param sQuery {String} Original request. * @param oFullResponse {Object} Full response object. * @param oParsedResponse {Object} Parsed response object. * @param oCallback {Object} Callback object. * @return {Object} Filtered response object. */ YAHOO.widget.AutoComplete.prototype.filterResults = function(sQuery, oFullResponse, oParsedResponse, oCallback) { // If AC has passed a query string value back to itself, grab it if(oCallback && oCallback.argument && YAHOO.lang.isValue(oCallback.argument.query)) { sQuery = oCallback.argument.query; } // Only if a query string is available to match against if(sQuery && sQuery !== "") { // First make a copy of the oParseResponse oParsedResponse = YAHOO.widget.AutoComplete._cloneObject(oParsedResponse); var oAC = oCallback.scope, oDS = this, allResults = oParsedResponse.results, // the array of results filteredResults = [], // container for filtered results, nMax = oAC.maxResultsDisplayed, // max to find bMatchCase = (oDS.queryMatchCase || oAC.queryMatchCase), // backward compat bMatchContains = (oDS.queryMatchContains || oAC.queryMatchContains); // backward compat // Loop through each result object... for(var i=0, len=allResults.length; i -1))) { // Stash the match filteredResults.push(oResult); } } // Filter no more if maxResultsDisplayed is reached if(len>nMax && filteredResults.length===nMax) { break; } } oParsedResponse.results = filteredResults; } else { } return oParsedResponse; }; /** * Handles response for display. This is the callback function method passed to * YAHOO.util.DataSourceBase#sendRequest so results from the DataSource are * returned to the AutoComplete instance. * * @method handleResponse * @param sQuery {String} Original request. * @param oResponse {Object} Response object. * @param oPayload {MIXED} (optional) Additional argument(s) */ YAHOO.widget.AutoComplete.prototype.handleResponse = function(sQuery, oResponse, oPayload) { if((this instanceof YAHOO.widget.AutoComplete) && this._sName) { this._populateList(sQuery, oResponse, oPayload); } }; /** * Overridable method called before container is loaded with result data. * * @method doBeforeLoadData * @param sQuery {String} Original request. * @param oResponse {Object} Response object. * @param oPayload {MIXED} (optional) Additional argument(s) * @return {Boolean} Return true to continue loading data, false to cancel. */ YAHOO.widget.AutoComplete.prototype.doBeforeLoadData = function(sQuery, oResponse, oPayload) { return true; }; /** * Overridable method that returns HTML markup for one result to be populated * as innerHTML of an <LI> element. * * @method formatResult * @param oResultData {Object} Result data object. * @param sQuery {String} The corresponding query string. * @param sResultMatch {HTMLElement} The current query string. * @return {HTML} HTML markup of formatted result data. */ YAHOO.widget.AutoComplete.prototype.formatResult = function(oResultData, sQuery, sResultMatch) { var sMarkup = (sResultMatch) ? sResultMatch : ""; return sMarkup; }; /** * An alternative to the formatResult() method, escapes the result data before * inserting into DOM. Implementers should point to this method when accessing * data from third-party sources, from user input, or from otherwise * untrustworthy sources: * myAutoComplete.formatResult = myAutoComplete.formatEscapedResult; * * @method formatEscapedResult * @param oResultData {Object} Result data object. * @param sQuery {String} The corresponding query string. * @param sResultMatch {HTMLElement} The current query string. * @return {String} Formatted result data. */ YAHOO.widget.AutoComplete.prototype.formatEscapedResult = function(oResultData, sQuery, sResultMatch) { var sResult = (sResultMatch) ? sResultMatch : ""; return YAHOO.lang.escapeHTML(sResult); }; /** * Overridable method called before container expands allows implementers to access data * and DOM elements. * * @method doBeforeExpandContainer * @param elTextbox {HTMLElement} The text input box. * @param elContainer {HTMLElement} The container element. * @param sQuery {String} The query string. * @param aResults {Object[]} An array of query results. * @return {Boolean} Return true to continue expanding container, false to cancel the expand. */ YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer = function(elTextbox, elContainer, sQuery, aResults) { return true; }; /** * Nulls out the entire AutoComplete instance and related objects, removes attached * event listeners, and clears out DOM elements inside the container. After * calling this method, the instance reference should be expliclitly nulled by * implementer, as in myAutoComplete = null. Use with caution! * * @method destroy */ YAHOO.widget.AutoComplete.prototype.destroy = function() { var instanceName = this.toString(); var elInput = this._elTextbox; var elContainer = this._elContainer; // Unhook custom events this.textboxFocusEvent.unsubscribeAll(); this.textboxKeyEvent.unsubscribeAll(); this.dataRequestEvent.unsubscribeAll(); this.dataReturnEvent.unsubscribeAll(); this.dataErrorEvent.unsubscribeAll(); this.containerPopulateEvent.unsubscribeAll(); this.containerExpandEvent.unsubscribeAll(); this.typeAheadEvent.unsubscribeAll(); this.itemMouseOverEvent.unsubscribeAll(); this.itemMouseOutEvent.unsubscribeAll(); this.itemArrowToEvent.unsubscribeAll(); this.itemArrowFromEvent.unsubscribeAll(); this.itemSelectEvent.unsubscribeAll(); this.unmatchedItemSelectEvent.unsubscribeAll(); this.selectionEnforceEvent.unsubscribeAll(); this.containerCollapseEvent.unsubscribeAll(); this.textboxBlurEvent.unsubscribeAll(); this.textboxChangeEvent.unsubscribeAll(); // Unhook DOM events YAHOO.util.Event.purgeElement(elInput, true); YAHOO.util.Event.purgeElement(elContainer, true); // Remove DOM elements elContainer.innerHTML = ""; // Null out objects for(var key in this) { if(YAHOO.lang.hasOwnProperty(this, key)) { this[key] = null; } } }; ///////////////////////////////////////////////////////////////////////////// // // Public events // ///////////////////////////////////////////////////////////////////////////// /** * Fired when the input field receives focus. * * @event textboxFocusEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. */ YAHOO.widget.AutoComplete.prototype.textboxFocusEvent = null; /** * Fired when the input field receives key input. * * @event textboxKeyEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {Number} The keycode number. */ YAHOO.widget.AutoComplete.prototype.textboxKeyEvent = null; /** * Fired when the AutoComplete instance makes a request to the DataSource. * * @event dataRequestEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {String} The query string. * @param args[2] {Object} The request. */ YAHOO.widget.AutoComplete.prototype.dataRequestEvent = null; /** * Fired when the AutoComplete request to the DataSource is canceled. * * @event dataRequestCancelEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {String} The query string. */ YAHOO.widget.AutoComplete.prototype.dataRequestCancelEvent = null; /** * Fired when the AutoComplete instance receives query results from the data * source. * * @event dataReturnEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {String} The query string. * @param args[2] {Object[]} Results array. */ YAHOO.widget.AutoComplete.prototype.dataReturnEvent = null; /** * Fired when the AutoComplete instance does not receive query results from the * DataSource due to an error. * * @event dataErrorEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {String} The query string. * @param args[2] {Object} The response object, if available. */ YAHOO.widget.AutoComplete.prototype.dataErrorEvent = null; /** * Fired when the results container is populated. * * @event containerPopulateEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. */ YAHOO.widget.AutoComplete.prototype.containerPopulateEvent = null; /** * Fired when the results container is expanded. * * @event containerExpandEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. */ YAHOO.widget.AutoComplete.prototype.containerExpandEvent = null; /** * Fired when the input field has been prefilled by the type-ahead * feature. * * @event typeAheadEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {String} The query string. * @param args[2] {String} The prefill string. */ YAHOO.widget.AutoComplete.prototype.typeAheadEvent = null; /** * Fired when result item has been moused over. * * @event itemMouseOverEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {HTMLElement} The <li> element item moused to. */ YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent = null; /** * Fired when result item has been moused out. * * @event itemMouseOutEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {HTMLElement} The <li> element item moused from. */ YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent = null; /** * Fired when result item has been arrowed to. * * @event itemArrowToEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {HTMLElement} The <li> element item arrowed to. */ YAHOO.widget.AutoComplete.prototype.itemArrowToEvent = null; /** * Fired when result item has been arrowed away from. * * @event itemArrowFromEvent * @param type {String} Name of the event. * @param args[0[ {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {HTMLElement} The <li> element item arrowed from. */ YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent = null; /** * Fired when an item is selected via mouse click, ENTER key, or TAB key. * * @event itemSelectEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {HTMLElement} The selected <li> element item. * @param args[2] {Object} The data returned for the item, either as an object, * or mapped from the schema into an array. */ YAHOO.widget.AutoComplete.prototype.itemSelectEvent = null; /** * Fired when a user selection does not match any of the displayed result items. * * @event unmatchedItemSelectEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {String} The selected string. */ YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent = null; /** * Fired if forceSelection is enabled and the user's input has been cleared * because it did not match one of the returned query results. * * @event selectionEnforceEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. * @param args[1] {String} The cleared value (including delimiters if applicable). */ YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent = null; /** * Fired when the results container is collapsed. * * @event containerCollapseEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. */ YAHOO.widget.AutoComplete.prototype.containerCollapseEvent = null; /** * Fired when the input field loses focus. * * @event textboxBlurEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. */ YAHOO.widget.AutoComplete.prototype.textboxBlurEvent = null; /** * Fired when the input field value has changed when it loses focus. * * @event textboxChangeEvent * @param type {String} Name of the event. * @param args[0] {YAHOO.widget.AutoComplete} The AutoComplete instance. */ YAHOO.widget.AutoComplete.prototype.textboxChangeEvent = null; ///////////////////////////////////////////////////////////////////////////// // // Private member variables // ///////////////////////////////////////////////////////////////////////////// /** * Internal class variable to index multiple AutoComplete instances. * * @property _nIndex * @type Number * @default 0 * @private */ YAHOO.widget.AutoComplete._nIndex = 0; /** * Name of AutoComplete instance. * * @property _sName * @type String * @private */ YAHOO.widget.AutoComplete.prototype._sName = null; /** * Text input field DOM element. * * @property _elTextbox * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elTextbox = null; /** * Container DOM element. * * @property _elContainer * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elContainer = null; /** * Reference to content element within container element. * * @property _elContent * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elContent = null; /** * Reference to header element within content element. * * @property _elHeader * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elHeader = null; /** * Reference to body element within content element. * * @property _elBody * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elBody = null; /** * Reference to footer element within content element. * * @property _elFooter * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elFooter = null; /** * Reference to shadow element within container element. * * @property _elShadow * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elShadow = null; /** * Reference to iframe element within container element. * * @property _elIFrame * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elIFrame = null; /** * Whether or not the widget instance is currently active. If query results come back * but the user has already moved on, do not proceed with auto complete behavior. * * @property _bFocused * @type Boolean * @private */ YAHOO.widget.AutoComplete.prototype._bFocused = false; /** * Animation instance for container expand/collapse. * * @property _oAnim * @type Boolean * @private */ YAHOO.widget.AutoComplete.prototype._oAnim = null; /** * Whether or not the results container is currently open. * * @property _bContainerOpen * @type Boolean * @private */ YAHOO.widget.AutoComplete.prototype._bContainerOpen = false; /** * Whether or not the mouse is currently over the results * container. This is necessary in order to prevent clicks on container items * from being text input field blur events. * * @property _bOverContainer * @type Boolean * @private */ YAHOO.widget.AutoComplete.prototype._bOverContainer = false; /** * Internal reference to <ul> elements that contains query results within the * results container. * * @property _elList * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elList = null; /* * Array of <li> elements references that contain query results within the * results container. * * @property _aListItemEls * @type HTMLElement[] * @private */ //YAHOO.widget.AutoComplete.prototype._aListItemEls = null; /** * Number of <li> elements currently displayed in results container. * * @property _nDisplayedItems * @type Number * @private */ YAHOO.widget.AutoComplete.prototype._nDisplayedItems = 0; /* * Internal count of <li> elements displayed and hidden in results container. * * @property _maxResultsDisplayed * @type Number * @private */ //YAHOO.widget.AutoComplete.prototype._maxResultsDisplayed = 0; /** * Current query string * * @property _sCurQuery * @type String * @private */ YAHOO.widget.AutoComplete.prototype._sCurQuery = null; /** * Selections from previous queries (for saving delimited queries). * * @property _sPastSelections * @type String * @default "" * @private */ YAHOO.widget.AutoComplete.prototype._sPastSelections = ""; /** * Stores initial input value used to determine if textboxChangeEvent should be fired. * * @property _sInitInputValue * @type String * @private */ YAHOO.widget.AutoComplete.prototype._sInitInputValue = null; /** * Pointer to the currently highlighted <li> element in the container. * * @property _elCurListItem * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elCurListItem = null; /** * Pointer to the currently pre-highlighted <li> element in the container. * * @property _elCurPrehighlightItem * @type HTMLElement * @private */ YAHOO.widget.AutoComplete.prototype._elCurPrehighlightItem = null; /** * Whether or not an item has been selected since the container was populated * with results. Reset to false by _populateList, and set to true when item is * selected. * * @property _bItemSelected * @type Boolean * @private */ YAHOO.widget.AutoComplete.prototype._bItemSelected = false; /** * Key code of the last key pressed in textbox. * * @property _nKeyCode * @type Number * @private */ YAHOO.widget.AutoComplete.prototype._nKeyCode = null; /** * Delay timeout ID. * * @property _nDelayID * @type Number * @private */ YAHOO.widget.AutoComplete.prototype._nDelayID = -1; /** * TypeAhead delay timeout ID. * * @property _nTypeAheadDelayID * @type Number * @private */ YAHOO.widget.AutoComplete.prototype._nTypeAheadDelayID = -1; /** * Src to iFrame used when useIFrame = true. Supports implementations over SSL * as well. * * @property _iFrameSrc * @type String * @private */ YAHOO.widget.AutoComplete.prototype._iFrameSrc = "javascript:false;"; /** * For users typing via certain IMEs, queries must be triggered by intervals, * since key events yet supported across all browsers for all IMEs. * * @property _queryInterval * @type Object * @private */ YAHOO.widget.AutoComplete.prototype._queryInterval = null; /** * Internal tracker to last known textbox value, used to determine whether or not * to trigger a query via interval for certain IME users. * * @event _sLastTextboxValue * @type String * @private */ YAHOO.widget.AutoComplete.prototype._sLastTextboxValue = null; ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Updates and validates latest public config properties. * * @method __initProps * @private */ YAHOO.widget.AutoComplete.prototype._initProps = function() { // Correct any invalid values var minQueryLength = this.minQueryLength; if(!YAHOO.lang.isNumber(minQueryLength)) { this.minQueryLength = 1; } var maxResultsDisplayed = this.maxResultsDisplayed; if(!YAHOO.lang.isNumber(maxResultsDisplayed) || (maxResultsDisplayed < 1)) { this.maxResultsDisplayed = 10; } var queryDelay = this.queryDelay; if(!YAHOO.lang.isNumber(queryDelay) || (queryDelay < 0)) { this.queryDelay = 0.2; } var typeAheadDelay = this.typeAheadDelay; if(!YAHOO.lang.isNumber(typeAheadDelay) || (typeAheadDelay < 0)) { this.typeAheadDelay = 0.2; } var delimChar = this.delimChar; if(YAHOO.lang.isString(delimChar) && (delimChar.length > 0)) { this.delimChar = [delimChar]; } else if(!YAHOO.lang.isArray(delimChar)) { this.delimChar = null; } var animSpeed = this.animSpeed; if((this.animHoriz || this.animVert) && YAHOO.util.Anim) { if(!YAHOO.lang.isNumber(animSpeed) || (animSpeed < 0)) { this.animSpeed = 0.3; } if(!this._oAnim ) { this._oAnim = new YAHOO.util.Anim(this._elContent, {}, this.animSpeed); } else { this._oAnim.duration = this.animSpeed; } } if(this.forceSelection && delimChar) { } }; /** * Initializes the results container helpers if they are enabled and do * not exist * * @method _initContainerHelperEls * @private */ YAHOO.widget.AutoComplete.prototype._initContainerHelperEls = function() { if(this.useShadow && !this._elShadow) { var elShadow = document.createElement("div"); elShadow.className = "yui-ac-shadow"; elShadow.style.width = 0; elShadow.style.height = 0; this._elShadow = this._elContainer.appendChild(elShadow); } if(this.useIFrame && !this._elIFrame) { var elIFrame = document.createElement("iframe"); elIFrame.src = this._iFrameSrc; elIFrame.frameBorder = 0; elIFrame.scrolling = "no"; elIFrame.style.position = "absolute"; elIFrame.style.width = 0; elIFrame.style.height = 0; elIFrame.style.padding = 0; elIFrame.tabIndex = -1; elIFrame.role = "presentation"; elIFrame.title = "Presentational iframe shim"; this._elIFrame = this._elContainer.appendChild(elIFrame); } }; /** * Initializes the results container once at object creation * * @method _initContainerEl * @private */ YAHOO.widget.AutoComplete.prototype._initContainerEl = function() { YAHOO.util.Dom.addClass(this._elContainer, "yui-ac-container"); if(!this._elContent) { // The elContent div is assigned DOM listeners and // helps size the iframe and shadow properly var elContent = document.createElement("div"); elContent.className = "yui-ac-content"; elContent.style.display = "none"; this._elContent = this._elContainer.appendChild(elContent); var elHeader = document.createElement("div"); elHeader.className = "yui-ac-hd"; elHeader.style.display = "none"; this._elHeader = this._elContent.appendChild(elHeader); var elBody = document.createElement("div"); elBody.className = "yui-ac-bd"; this._elBody = this._elContent.appendChild(elBody); var elFooter = document.createElement("div"); elFooter.className = "yui-ac-ft"; elFooter.style.display = "none"; this._elFooter = this._elContent.appendChild(elFooter); } else { } }; /** * Clears out contents of container body and creates up to * YAHOO.widget.AutoComplete#maxResultsDisplayed <li> elements in an * <ul> element. * * @method _initListEl * @private */ YAHOO.widget.AutoComplete.prototype._initListEl = function() { var nListLength = this.maxResultsDisplayed, elList = this._elList || document.createElement("ul"), elListItem; while(elList.childNodes.length < nListLength) { elListItem = document.createElement("li"); elListItem.style.display = "none"; elListItem._nItemIndex = elList.childNodes.length; elList.appendChild(elListItem); } if(!this._elList) { var elBody = this._elBody; YAHOO.util.Event.purgeElement(elBody, true); elBody.innerHTML = ""; this._elList = elBody.appendChild(elList); } this._elBody.style.display = ""; }; /** * Focuses input field. * * @method _focus * @private */ YAHOO.widget.AutoComplete.prototype._focus = function() { // http://developer.mozilla.org/en/docs/index.php?title=Key-navigable_custom_DHTML_widgets var oSelf = this; setTimeout(function() { try { oSelf._elTextbox.focus(); } catch(e) { } },0); }; /** * Enables interval detection for IME support. * * @method _enableIntervalDetection * @private */ YAHOO.widget.AutoComplete.prototype._enableIntervalDetection = function() { var oSelf = this; if(!oSelf._queryInterval && oSelf.queryInterval) { oSelf._queryInterval = setInterval(function() { oSelf._onInterval(); }, oSelf.queryInterval); } }; /** * Enables interval detection for a less performant but brute force mechanism to * detect input values at an interval set by queryInterval and send queries if * input value has changed. Needed to support right-click+paste or shift+insert * edge cases. Please note that intervals are cleared at the end of each interaction, * so enableIntervalDetection must be called for each new interaction. The * recommended approach is to call it in response to textboxFocusEvent. * * @method enableIntervalDetection */ YAHOO.widget.AutoComplete.prototype.enableIntervalDetection = YAHOO.widget.AutoComplete.prototype._enableIntervalDetection; /** * Enables query triggers based on text input detection by intervals (rather * than by key events). * * @method _onInterval * @private */ YAHOO.widget.AutoComplete.prototype._onInterval = function() { var currValue = this._elTextbox.value; var lastValue = this._sLastTextboxValue; if(currValue != lastValue) { this._sLastTextboxValue = currValue; this._sendQuery(currValue); } }; /** * Cancels text input detection by intervals. * * @method _clearInterval * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._clearInterval = function() { if(this._queryInterval) { clearInterval(this._queryInterval); this._queryInterval = null; } }; /** * Whether or not key is functional or should be ignored. Note that the right * arrow key is NOT an ignored key since it triggers queries for certain intl * charsets. * * @method _isIgnoreKey * @param nKeycode {Number} Code of key pressed. * @return {Boolean} True if key should be ignored, false otherwise. * @private */ YAHOO.widget.AutoComplete.prototype._isIgnoreKey = function(nKeyCode) { if((nKeyCode == 9) || (nKeyCode == 13) || // tab, enter (nKeyCode == 16) || (nKeyCode == 17) || // shift, ctl (nKeyCode >= 18 && nKeyCode <= 20) || // alt, pause/break,caps lock (nKeyCode == 27) || // esc (nKeyCode >= 33 && nKeyCode <= 35) || // page up,page down,end /*(nKeyCode >= 36 && nKeyCode <= 38) || // home,left,up (nKeyCode == 40) || // down*/ (nKeyCode >= 36 && nKeyCode <= 40) || // home,left,up, right, down (nKeyCode >= 44 && nKeyCode <= 45) || // print screen,insert (nKeyCode == 229) // Bug 2041973: Korean XP fires 2 keyup events, the key and 229 ) { return true; } return false; }; /** * Makes query request to the DataSource. * * @method _sendQuery * @param sQuery {String} Query string. * @private */ YAHOO.widget.AutoComplete.prototype._sendQuery = function(sQuery) { // Widget has been effectively turned off if(this.minQueryLength < 0) { this._toggleContainer(false); return; } // Delimiter has been enabled if(this.delimChar) { var extraction = this._extractQuery(sQuery); // Here is the query itself sQuery = extraction.query; // ...and save the rest of the string for later this._sPastSelections = extraction.previous; } // Don't search queries that are too short if((sQuery && (sQuery.length < this.minQueryLength)) || (!sQuery && this.minQueryLength > 0)) { if(this._nDelayID != -1) { clearTimeout(this._nDelayID); } this._toggleContainer(false); return; } sQuery = encodeURIComponent(sQuery); this._nDelayID = -1; // Reset timeout ID because request is being made // Subset matching if(this.dataSource.queryMatchSubset || this.queryMatchSubset) { // backward compat var oResponse = this.getSubsetMatches(sQuery); if(oResponse) { this.handleResponse(sQuery, oResponse, {query: sQuery}); return; } } if(this.dataSource.responseStripAfter) { this.dataSource.doBeforeParseData = this.preparseRawResponse; } if(this.applyLocalFilter) { this.dataSource.doBeforeCallback = this.filterResults; } var sRequest = this.generateRequest(sQuery); if(sRequest !== undefined) { this.dataRequestEvent.fire(this, sQuery, sRequest); this.dataSource.sendRequest(sRequest, { success : this.handleResponse, failure : this.handleResponse, scope : this, argument: { query: sQuery } }); } else { this.dataRequestCancelEvent.fire(this, sQuery); } }; /** * Populates the given <li> element with return value from formatResult(). * * @method _populateListItem * @param elListItem {HTMLElement} The LI element. * @param oResult {Object} The result object. * @param sCurQuery {String} The query string. * @private */ YAHOO.widget.AutoComplete.prototype._populateListItem = function(elListItem, oResult, sQuery) { elListItem.innerHTML = this.formatResult(oResult, sQuery, elListItem._sResultMatch); }; /** * Populates the array of <li> elements in the container with query * results. * * @method _populateList * @param sQuery {String} Original request. * @param oResponse {Object} Response object. * @param oPayload {MIXED} (optional) Additional argument(s) * @private */ YAHOO.widget.AutoComplete.prototype._populateList = function(sQuery, oResponse, oPayload) { // Clear previous timeout if(this._nTypeAheadDelayID != -1) { clearTimeout(this._nTypeAheadDelayID); } sQuery = (oPayload && oPayload.query) ? oPayload.query : sQuery; // Pass data through abstract method for any transformations var ok = this.doBeforeLoadData(sQuery, oResponse, oPayload); // Data is ok if(ok && !oResponse.error) { this.dataReturnEvent.fire(this, sQuery, oResponse.results); // Continue only if instance is still active (i.e., user hasn't already moved on) if(this._bFocused) { // Store state for this interaction var sCurQuery = decodeURIComponent(sQuery); this._sCurQuery = sCurQuery; this._bItemSelected = false; var allResults = oResponse.results, nItemsToShow = Math.min(allResults.length,this.maxResultsDisplayed), sMatchKey = (this.dataSource.responseSchema.fields) ? (this.dataSource.responseSchema.fields[0].key || this.dataSource.responseSchema.fields[0]) : 0; if(nItemsToShow > 0) { // Make sure container and helpers are ready to go if(!this._elList || (this._elList.childNodes.length < nItemsToShow)) { this._initListEl(); } this._initContainerHelperEls(); var allListItemEls = this._elList.childNodes; // Fill items with data from the bottom up for(var i = nItemsToShow-1; i >= 0; i--) { var elListItem = allListItemEls[i], oResult = allResults[i]; // Backward compatibility if(this.resultTypeList) { // Results need to be converted back to an array var aResult = []; // Match key is first aResult[0] = (YAHOO.lang.isString(oResult)) ? oResult : oResult[sMatchKey] || oResult[this.key]; // Add additional data to the result array var fields = this.dataSource.responseSchema.fields; if(YAHOO.lang.isArray(fields) && (fields.length > 1)) { for(var k=1, len=fields.length; k= nItemsToShow; j--) { extraListItem = allListItemEls[j]; extraListItem.style.display = "none"; } } this._nDisplayedItems = nItemsToShow; this.containerPopulateEvent.fire(this, sQuery, allResults); // Highlight the first item if(this.autoHighlight) { var elFirstListItem = this._elList.firstChild; this._toggleHighlight(elFirstListItem,"to"); this.itemArrowToEvent.fire(this, elFirstListItem); this._typeAhead(elFirstListItem,sQuery); } // Unhighlight any previous time else { this._toggleHighlight(this._elCurListItem,"from"); } // Pre-expansion stuff ok = this._doBeforeExpandContainer(this._elTextbox, this._elContainer, sQuery, allResults); // Expand the container this._toggleContainer(ok); } else { this._toggleContainer(false); } return; } } // Error else { this.dataErrorEvent.fire(this, sQuery, oResponse); } }; /** * Called before container expands, by default snaps container to the * bottom-left corner of the input element, then calls public overrideable method. * * @method _doBeforeExpandContainer * @param elTextbox {HTMLElement} The text input box. * @param elContainer {HTMLElement} The container element. * @param sQuery {String} The query string. * @param aResults {Object[]} An array of query results. * @return {Boolean} Return true to continue expanding container, false to cancel the expand. * @private */ YAHOO.widget.AutoComplete.prototype._doBeforeExpandContainer = function(elTextbox, elContainer, sQuery, aResults) { if(this.autoSnapContainer) { this.snapContainer(); } return this.doBeforeExpandContainer(elTextbox, elContainer, sQuery, aResults); }; /** * When forceSelection is true and the user attempts * leave the text input box without selecting an item from the query results, * the user selection is cleared. * * @method _clearSelection * @private */ YAHOO.widget.AutoComplete.prototype._clearSelection = function() { var extraction = (this.delimChar) ? this._extractQuery(this._elTextbox.value) : {previous:"",query:this._elTextbox.value}; this._elTextbox.value = extraction.previous; this.selectionEnforceEvent.fire(this, extraction.query); }; /** * Whether or not user-typed value in the text input box matches any of the * query results. * * @method _textMatchesOption * @return {HTMLElement} Matching list item element if user-input text matches * a result, null otherwise. * @private */ YAHOO.widget.AutoComplete.prototype._textMatchesOption = function() { var elMatch = null; for(var i=0; i= 0; i--) { nNewIndex = sQuery.lastIndexOf(aDelimChar[i]); if(nNewIndex > nDelimIndex) { nDelimIndex = nNewIndex; } } // If we think the last delimiter is a space (" "), make sure it is NOT // a false positive by also checking the char directly before it if(aDelimChar[i] == " ") { for (var j = aDelimChar.length-1; j >= 0; j--) { if(sQuery[nDelimIndex - 1] == aDelimChar[j]) { nDelimIndex--; break; } } } // A delimiter has been found in the query so extract the latest query from past selections if(nDelimIndex > -1) { nQueryStart = nDelimIndex + 1; // Trim any white space from the beginning... while(sQuery.charAt(nQueryStart) == " ") { nQueryStart += 1; } // ...and save the rest of the string for later sPrevious = sQuery.substring(0,nQueryStart); // Here is the query itself sQuery = sQuery.substr(nQueryStart); } // No delimiter found in the query, so there are no selections from past queries else { sPrevious = ""; } return { previous: sPrevious, query: sQuery }; }; /** * Syncs results container with its helpers. * * @method _toggleContainerHelpers * @param bShow {Boolean} True if container is expanded, false if collapsed * @private */ YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers = function(bShow) { var width = this._elContent.offsetWidth + "px"; var height = this._elContent.offsetHeight + "px"; if(this.useIFrame && this._elIFrame) { var elIFrame = this._elIFrame; if(bShow) { elIFrame.style.width = width; elIFrame.style.height = height; elIFrame.style.padding = ""; } else { elIFrame.style.width = 0; elIFrame.style.height = 0; elIFrame.style.padding = 0; } } if(this.useShadow && this._elShadow) { var elShadow = this._elShadow; if(bShow) { elShadow.style.width = width; elShadow.style.height = height; } else { elShadow.style.width = 0; elShadow.style.height = 0; } } }; /** * Animates expansion or collapse of the container. * * @method _toggleContainer * @param bShow {Boolean} True if container should be expanded, false if container should be collapsed * @private */ YAHOO.widget.AutoComplete.prototype._toggleContainer = function(bShow) { var elContainer = this._elContainer; // If implementer has container always open and it's already open, don't mess with it // Container is initialized with display "none" so it may need to be shown first time through if(this.alwaysShowContainer && this._bContainerOpen) { return; } // Reset states if(!bShow) { this._toggleHighlight(this._elCurListItem,"from"); this._nDisplayedItems = 0; this._sCurQuery = null; // Container is already closed, so don't bother with changing the UI if(this._elContent.style.display == "none") { return; } } // If animation is enabled... var oAnim = this._oAnim; if(oAnim && oAnim.getEl() && (this.animHoriz || this.animVert)) { if(oAnim.isAnimated()) { oAnim.stop(true); } // Clone container to grab current size offscreen var oClone = this._elContent.cloneNode(true); elContainer.appendChild(oClone); oClone.style.top = "-9000px"; oClone.style.width = ""; oClone.style.height = ""; oClone.style.display = ""; // Current size of the container is the EXPANDED size var wExp = oClone.offsetWidth; var hExp = oClone.offsetHeight; // Calculate COLLAPSED sizes based on horiz and vert anim var wColl = (this.animHoriz) ? 0 : wExp; var hColl = (this.animVert) ? 0 : hExp; // Set animation sizes oAnim.attributes = (bShow) ? {width: { to: wExp }, height: { to: hExp }} : {width: { to: wColl}, height: { to: hColl }}; // If opening anew, set to a collapsed size... if(bShow && !this._bContainerOpen) { this._elContent.style.width = wColl+"px"; this._elContent.style.height = hColl+"px"; } // Else, set it to its last known size. else { this._elContent.style.width = wExp+"px"; this._elContent.style.height = hExp+"px"; } elContainer.removeChild(oClone); oClone = null; var oSelf = this; var onAnimComplete = function() { // Finish the collapse oAnim.onComplete.unsubscribeAll(); if(bShow) { oSelf._toggleContainerHelpers(true); oSelf._bContainerOpen = bShow; oSelf.containerExpandEvent.fire(oSelf); } else { oSelf._elContent.style.display = "none"; oSelf._bContainerOpen = bShow; oSelf.containerCollapseEvent.fire(oSelf); } }; // Display container and animate it this._toggleContainerHelpers(false); // Bug 1424486: Be early to hide, late to show; this._elContent.style.display = ""; oAnim.onComplete.subscribe(onAnimComplete); oAnim.animate(); } // Else don't animate, just show or hide else { if(bShow) { this._elContent.style.display = ""; this._toggleContainerHelpers(true); this._bContainerOpen = bShow; this.containerExpandEvent.fire(this); } else { this._toggleContainerHelpers(false); this._elContent.style.display = "none"; this._bContainerOpen = bShow; this.containerCollapseEvent.fire(this); } } }; /** * Toggles the highlight on or off for an item in the container, and also cleans * up highlighting of any previous item. * * @method _toggleHighlight * @param elNewListItem {HTMLElement} The <li> element item to receive highlight behavior. * @param sType {String} Type "mouseover" will toggle highlight on, and "mouseout" will toggle highlight off. * @private */ YAHOO.widget.AutoComplete.prototype._toggleHighlight = function(elNewListItem, sType) { if(elNewListItem) { var sHighlight = this.highlightClassName; if(this._elCurListItem) { // Remove highlight from old item YAHOO.util.Dom.removeClass(this._elCurListItem, sHighlight); this._elCurListItem = null; } if((sType == "to") && sHighlight) { // Apply highlight to new item YAHOO.util.Dom.addClass(elNewListItem, sHighlight); this._elCurListItem = elNewListItem; } } }; /** * Toggles the pre-highlight on or off for an item in the container, and also cleans * up pre-highlighting of any previous item. * * @method _togglePrehighlight * @param elNewListItem {HTMLElement} The <li> element item to receive highlight behavior. * @param sType {String} Type "mouseover" will toggle highlight on, and "mouseout" will toggle highlight off. * @private */ YAHOO.widget.AutoComplete.prototype._togglePrehighlight = function(elNewListItem, sType) { var sPrehighlight = this.prehighlightClassName; if(this._elCurPrehighlightItem) { YAHOO.util.Dom.removeClass(this._elCurPrehighlightItem, sPrehighlight); } if(elNewListItem == this._elCurListItem) { return; } if((sType == "mouseover") && sPrehighlight) { // Apply prehighlight to new item YAHOO.util.Dom.addClass(elNewListItem, sPrehighlight); this._elCurPrehighlightItem = elNewListItem; } else { // Remove prehighlight from old item YAHOO.util.Dom.removeClass(elNewListItem, sPrehighlight); } }; /** * Updates the text input box value with selected query result. If a delimiter * has been defined, then the value gets appended with the delimiter. * * @method _updateValue * @param elListItem {HTMLElement} The <li> element item with which to update the value. * @private */ YAHOO.widget.AutoComplete.prototype._updateValue = function(elListItem) { if(!this.suppressInputUpdate) { var elTextbox = this._elTextbox; var sDelimChar = (this.delimChar) ? (this.delimChar[0] || this.delimChar) : null; var sResultMatch = elListItem._sResultMatch; // Calculate the new value var sNewValue = ""; if(sDelimChar) { // Preserve selections from past queries sNewValue = this._sPastSelections; // Add new selection plus delimiter sNewValue += sResultMatch + sDelimChar; if(sDelimChar != " ") { sNewValue += " "; } } else { sNewValue = sResultMatch; } // Update input field elTextbox.value = sNewValue; // Scroll to bottom of textarea if necessary if(elTextbox.type == "textarea") { elTextbox.scrollTop = elTextbox.scrollHeight; } // Move cursor to end var end = elTextbox.value.length; this._selectText(elTextbox,end,end); this._elCurListItem = elListItem; } }; /** * Selects a result item from the container * * @method _selectItem * @param elListItem {HTMLElement} The selected <li> element item. * @private */ YAHOO.widget.AutoComplete.prototype._selectItem = function(elListItem) { this._bItemSelected = true; this._updateValue(elListItem); this._sPastSelections = this._elTextbox.value; this._clearInterval(); this.itemSelectEvent.fire(this, elListItem, elListItem._oResultData); this._toggleContainer(false); }; /** * If an item is highlighted in the container, the right arrow key jumps to the * end of the textbox and selects the highlighted item, otherwise the container * is closed. * * @method _jumpSelection * @private */ YAHOO.widget.AutoComplete.prototype._jumpSelection = function() { if(this._elCurListItem) { this._selectItem(this._elCurListItem); } else { this._toggleContainer(false); } }; /** * Triggered by up and down arrow keys, changes the current highlighted * <li> element item. Scrolls container if necessary. * * @method _moveSelection * @param nKeyCode {Number} Code of key pressed. * @private */ YAHOO.widget.AutoComplete.prototype._moveSelection = function(nKeyCode) { if(this._bContainerOpen) { // Determine current item's id number var elCurListItem = this._elCurListItem, nCurItemIndex = -1; if(elCurListItem) { nCurItemIndex = elCurListItem._nItemIndex; } var nNewItemIndex = (nKeyCode == 40) ? (nCurItemIndex + 1) : (nCurItemIndex - 1); // Out of bounds if(nNewItemIndex < -2 || nNewItemIndex >= this._nDisplayedItems) { return; } if(elCurListItem) { // Unhighlight current item this._toggleHighlight(elCurListItem, "from"); this.itemArrowFromEvent.fire(this, elCurListItem); } if(nNewItemIndex == -1) { // Go back to query (remove type-ahead string) if(this.delimChar) { this._elTextbox.value = this._sPastSelections + this._sCurQuery; } else { this._elTextbox.value = this._sCurQuery; } return; } if(nNewItemIndex == -2) { // Close container this._toggleContainer(false); return; } var elNewListItem = this._elList.childNodes[nNewItemIndex], // Scroll the container if necessary elContent = this._elContent, sOF = YAHOO.util.Dom.getStyle(elContent,"overflow"), sOFY = YAHOO.util.Dom.getStyle(elContent,"overflowY"), scrollOn = ((sOF == "auto") || (sOF == "scroll") || (sOFY == "auto") || (sOFY == "scroll")); if(scrollOn && (nNewItemIndex > -1) && (nNewItemIndex < this._nDisplayedItems)) { // User is keying down if(nKeyCode == 40) { // Bottom of selected item is below scroll area... if((elNewListItem.offsetTop+elNewListItem.offsetHeight) > (elContent.scrollTop + elContent.offsetHeight)) { // Set bottom of scroll area to bottom of selected item elContent.scrollTop = (elNewListItem.offsetTop+elNewListItem.offsetHeight) - elContent.offsetHeight; } // Bottom of selected item is above scroll area... else if((elNewListItem.offsetTop+elNewListItem.offsetHeight) < elContent.scrollTop) { // Set top of selected item to top of scroll area elContent.scrollTop = elNewListItem.offsetTop; } } // User is keying up else { // Top of selected item is above scroll area if(elNewListItem.offsetTop < elContent.scrollTop) { // Set top of scroll area to top of selected item this._elContent.scrollTop = elNewListItem.offsetTop; } // Top of selected item is below scroll area else if(elNewListItem.offsetTop > (elContent.scrollTop + elContent.offsetHeight)) { // Set bottom of selected item to bottom of scroll area this._elContent.scrollTop = (elNewListItem.offsetTop+elNewListItem.offsetHeight) - elContent.offsetHeight; } } } this._toggleHighlight(elNewListItem, "to"); this.itemArrowToEvent.fire(this, elNewListItem); if(this.typeAhead) { this._updateValue(elNewListItem); // Bug 2528552: Store as a selection this._sCurQuery = elNewListItem._sResultMatch; } } }; ///////////////////////////////////////////////////////////////////////////// // // Private event handlers // ///////////////////////////////////////////////////////////////////////////// /** * Handles container mouseover events. * * @method _onContainerMouseover * @param v {HTMLEvent} The mouseover event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onContainerMouseover = function(v,oSelf) { var elTarget = YAHOO.util.Event.getTarget(v); var elTag = elTarget.nodeName.toLowerCase(); while(elTarget && (elTag != "table")) { switch(elTag) { case "body": return; case "li": if(oSelf.prehighlightClassName) { oSelf._togglePrehighlight(elTarget,"mouseover"); } else { oSelf._toggleHighlight(elTarget,"to"); } oSelf.itemMouseOverEvent.fire(oSelf, elTarget); break; case "div": if(YAHOO.util.Dom.hasClass(elTarget,"yui-ac-container")) { oSelf._bOverContainer = true; return; } break; default: break; } elTarget = elTarget.parentNode; if(elTarget) { elTag = elTarget.nodeName.toLowerCase(); } } }; /** * Handles container mouseout events. * * @method _onContainerMouseout * @param v {HTMLEvent} The mouseout event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onContainerMouseout = function(v,oSelf) { var elTarget = YAHOO.util.Event.getTarget(v); var elTag = elTarget.nodeName.toLowerCase(); while(elTarget && (elTag != "table")) { switch(elTag) { case "body": return; case "li": if(oSelf.prehighlightClassName) { oSelf._togglePrehighlight(elTarget,"mouseout"); } else { oSelf._toggleHighlight(elTarget,"from"); } oSelf.itemMouseOutEvent.fire(oSelf, elTarget); break; case "ul": oSelf._toggleHighlight(oSelf._elCurListItem,"to"); break; case "div": if(YAHOO.util.Dom.hasClass(elTarget,"yui-ac-container")) { oSelf._bOverContainer = false; return; } break; default: break; } elTarget = elTarget.parentNode; if(elTarget) { elTag = elTarget.nodeName.toLowerCase(); } } }; /** * Handles container click events. * * @method _onContainerClick * @param v {HTMLEvent} The click event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onContainerClick = function(v,oSelf) { var elTarget = YAHOO.util.Event.getTarget(v); var elTag = elTarget.nodeName.toLowerCase(); while(elTarget && (elTag != "table")) { switch(elTag) { case "body": return; case "li": // In case item has not been moused over oSelf._toggleHighlight(elTarget,"to"); oSelf._selectItem(elTarget); return; default: break; } elTarget = elTarget.parentNode; if(elTarget) { elTag = elTarget.nodeName.toLowerCase(); } } }; /** * Handles container scroll events. * * @method _onContainerScroll * @param v {HTMLEvent} The scroll event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onContainerScroll = function(v,oSelf) { oSelf._focus(); }; /** * Handles container resize events. * * @method _onContainerResize * @param v {HTMLEvent} The resize event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onContainerResize = function(v,oSelf) { oSelf._toggleContainerHelpers(oSelf._bContainerOpen); }; /** * Handles textbox keydown events of functional keys, mainly for UI behavior. * * @method _onTextboxKeyDown * @param v {HTMLEvent} The keydown event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown = function(v,oSelf) { var nKeyCode = v.keyCode; // Clear timeout if(oSelf._nTypeAheadDelayID != -1) { clearTimeout(oSelf._nTypeAheadDelayID); } switch (nKeyCode) { case 9: // tab if(!YAHOO.env.ua.opera && (navigator.userAgent.toLowerCase().indexOf("mac") == -1) || (YAHOO.env.ua.webkit>420)) { // select an item or clear out if(oSelf._elCurListItem) { if(oSelf.delimChar && (oSelf._nKeyCode != nKeyCode)) { if(oSelf._bContainerOpen) { YAHOO.util.Event.stopEvent(v); } } oSelf._selectItem(oSelf._elCurListItem); } else { oSelf._toggleContainer(false); } } break; case 13: // enter if(!YAHOO.env.ua.opera && (navigator.userAgent.toLowerCase().indexOf("mac") == -1) || (YAHOO.env.ua.webkit>420)) { if(oSelf._elCurListItem) { if(oSelf._nKeyCode != nKeyCode) { if(oSelf._bContainerOpen) { YAHOO.util.Event.stopEvent(v); } } oSelf._selectItem(oSelf._elCurListItem); } else { oSelf._toggleContainer(false); } } break; case 27: // esc oSelf._toggleContainer(false); return; case 39: // right oSelf._jumpSelection(); break; case 38: // up if(oSelf._bContainerOpen) { YAHOO.util.Event.stopEvent(v); oSelf._moveSelection(nKeyCode); } break; case 40: // down if(oSelf._bContainerOpen) { YAHOO.util.Event.stopEvent(v); oSelf._moveSelection(nKeyCode); } break; default: oSelf._bItemSelected = false; oSelf._toggleHighlight(oSelf._elCurListItem, "from"); oSelf.textboxKeyEvent.fire(oSelf, nKeyCode); break; } if(nKeyCode === 18){ oSelf._enableIntervalDetection(); } oSelf._nKeyCode = nKeyCode; }; /** * Handles textbox keypress events. * @method _onTextboxKeyPress * @param v {HTMLEvent} The keypress event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress = function(v,oSelf) { var nKeyCode = v.keyCode; // Expose only to non SF3 (bug 1978549) Mac browsers (bug 790337) and Opera browsers (bug 583531), // where stopEvent is ineffective on keydown events if(YAHOO.env.ua.opera || (navigator.userAgent.toLowerCase().indexOf("mac") != -1) && (YAHOO.env.ua.webkit < 420)) { switch (nKeyCode) { case 9: // tab // select an item or clear out if(oSelf._bContainerOpen) { if(oSelf.delimChar) { YAHOO.util.Event.stopEvent(v); } if(oSelf._elCurListItem) { oSelf._selectItem(oSelf._elCurListItem); } else { oSelf._toggleContainer(false); } } break; case 13: // enter if(oSelf._bContainerOpen) { YAHOO.util.Event.stopEvent(v); if(oSelf._elCurListItem) { oSelf._selectItem(oSelf._elCurListItem); } else { oSelf._toggleContainer(false); } } break; default: break; } } //TODO: (?) limit only to non-IE, non-Mac-FF for Korean IME support (bug 811948) // Korean IME detected else if(nKeyCode == 229) { oSelf._enableIntervalDetection(); } }; /** * Handles textbox keyup events to trigger queries. * * @method _onTextboxKeyUp * @param v {HTMLEvent} The keyup event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp = function(v,oSelf) { var sText = this.value; //string in textbox // Check to see if any of the public properties have been updated oSelf._initProps(); // Filter out chars that don't trigger queries var nKeyCode = v.keyCode; if(oSelf._isIgnoreKey(nKeyCode)) { return; } // Clear previous timeout if(oSelf._nDelayID != -1) { clearTimeout(oSelf._nDelayID); } // Set new timeout oSelf._nDelayID = setTimeout(function(){ oSelf._sendQuery(sText); },(oSelf.queryDelay * 1000)); }; /** * Handles text input box receiving focus. * * @method _onTextboxFocus * @param v {HTMLEvent} The focus event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onTextboxFocus = function (v,oSelf) { // Start of a new interaction if(!oSelf._bFocused) { oSelf._elTextbox.setAttribute("autocomplete","off"); oSelf._bFocused = true; oSelf._sInitInputValue = oSelf._elTextbox.value; oSelf.textboxFocusEvent.fire(oSelf); } }; /** * Handles text input box losing focus. * * @method _onTextboxBlur * @param v {HTMLEvent} The focus event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onTextboxBlur = function (v,oSelf) { // Is a true blur if(!oSelf._bOverContainer || (oSelf._nKeyCode == 9)) { // Current query needs to be validated as a selection if(!oSelf._bItemSelected) { var elMatchListItem = oSelf._textMatchesOption(); // Container is closed or current query doesn't match any result if(!oSelf._bContainerOpen || (oSelf._bContainerOpen && (elMatchListItem === null))) { // Force selection is enabled so clear the current query if(oSelf.forceSelection) { oSelf._clearSelection(); } // Treat current query as a valid selection else { oSelf.unmatchedItemSelectEvent.fire(oSelf, oSelf._sCurQuery); } } // Container is open and current query matches a result else { // Force a selection when textbox is blurred with a match if(oSelf.forceSelection) { oSelf._selectItem(elMatchListItem); } } } oSelf._clearInterval(); oSelf._bFocused = false; if(oSelf._sInitInputValue !== oSelf._elTextbox.value) { oSelf.textboxChangeEvent.fire(oSelf); } oSelf.textboxBlurEvent.fire(oSelf); oSelf._toggleContainer(false); } // Not a true blur if it was a selection via mouse click else { oSelf._focus(); } }; /** * Handles window unload event. * * @method _onWindowUnload * @param v {HTMLEvent} The unload event. * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance. * @private */ YAHOO.widget.AutoComplete.prototype._onWindowUnload = function(v,oSelf) { if(oSelf && oSelf._elTextbox && oSelf.allowBrowserAutocomplete) { oSelf._elTextbox.setAttribute("autocomplete","on"); } }; ///////////////////////////////////////////////////////////////////////////// // // Deprecated for Backwards Compatibility // ///////////////////////////////////////////////////////////////////////////// /** * @method doBeforeSendQuery * @deprecated Use generateRequest. */ YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery = function(sQuery) { return this.generateRequest(sQuery); }; /** * @method getListItems * @deprecated Use getListEl().childNodes. */ YAHOO.widget.AutoComplete.prototype.getListItems = function() { var allListItemEls = [], els = this._elList.childNodes; for(var i=els.length-1; i>=0; i--) { allListItemEls[i] = els[i]; } return allListItemEls; }; ///////////////////////////////////////////////////////////////////////// // // Private static methods // ///////////////////////////////////////////////////////////////////////// /** * Clones object literal or array of object literals. * * @method AutoComplete._cloneObject * @param o {Object} Object. * @private * @static */ YAHOO.widget.AutoComplete._cloneObject = function(o) { if(!YAHOO.lang.isValue(o)) { return o; } var copy = {}; if(YAHOO.lang.isFunction(o)) { copy = o; } else if(YAHOO.lang.isArray(o)) { var array = []; for(var i=0,len=o.length;i-1;a--){b[a].style.display="none";}};YAHOO.widget.AutoComplete.prototype.getSubsetMatches=function(e){var d,c,a;for(var b=e.length;b>=this.minQueryLength;b--){a=this.generateRequest(e.substr(0,b));this.dataRequestEvent.fire(this,d,a);c=this.dataSource.getCachedResponse(a);if(c){return this.filterResults.apply(this.dataSource,[e,c,c,{scope:this}]);}}return null;};YAHOO.widget.AutoComplete.prototype.preparseRawResponse=function(c,b,a){var d=((this.responseStripAfter!=="")&&(b.indexOf))?b.indexOf(this.responseStripAfter):-1;if(d!=-1){b=b.substring(0,d);}return b;};YAHOO.widget.AutoComplete.prototype.filterResults=function(l,n,r,m){if(m&&m.argument&&YAHOO.lang.isValue(m.argument.query)){l=m.argument.query;}if(l&&l!==""){r=YAHOO.widget.AutoComplete._cloneObject(r);var j=m.scope,q=this,c=r.results,o=[],b=j.maxResultsDisplayed,k=(q.queryMatchCase||j.queryMatchCase),a=(q.queryMatchContains||j.queryMatchContains);for(var d=0,h=c.length;d-1))){o.push(f);}}if(h>b&&o.length===b){break;}}r.results=o;}else{}return r;};YAHOO.widget.AutoComplete.prototype.handleResponse=function(c,a,b){if((this instanceof YAHOO.widget.AutoComplete)&&this._sName){this._populateList(c,a,b);}};YAHOO.widget.AutoComplete.prototype.doBeforeLoadData=function(c,a,b){return true;};YAHOO.widget.AutoComplete.prototype.formatResult=function(b,d,a){var c=(a)?a:"";return c;};YAHOO.widget.AutoComplete.prototype.formatEscapedResult=function(c,d,b){var a=(b)?b:"";return YAHOO.lang.escapeHTML(a);};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(d,a,c,b){return true;};YAHOO.widget.AutoComplete.prototype.destroy=function(){var b=this.toString();var a=this._elTextbox;var d=this._elContainer;this.textboxFocusEvent.unsubscribeAll();this.textboxKeyEvent.unsubscribeAll();this.dataRequestEvent.unsubscribeAll();this.dataReturnEvent.unsubscribeAll();this.dataErrorEvent.unsubscribeAll();this.containerPopulateEvent.unsubscribeAll();this.containerExpandEvent.unsubscribeAll();this.typeAheadEvent.unsubscribeAll();this.itemMouseOverEvent.unsubscribeAll();this.itemMouseOutEvent.unsubscribeAll();this.itemArrowToEvent.unsubscribeAll();this.itemArrowFromEvent.unsubscribeAll();this.itemSelectEvent.unsubscribeAll();this.unmatchedItemSelectEvent.unsubscribeAll();this.selectionEnforceEvent.unsubscribeAll();this.containerCollapseEvent.unsubscribeAll();this.textboxBlurEvent.unsubscribeAll();this.textboxChangeEvent.unsubscribeAll();YAHOO.util.Event.purgeElement(a,true);YAHOO.util.Event.purgeElement(d,true);d.innerHTML="";for(var c in this){if(YAHOO.lang.hasOwnProperty(this,c)){this[c]=null;}}};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestCancelEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null; YAHOO.widget.AutoComplete.prototype.containerPopulateEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;YAHOO.widget.AutoComplete.prototype.textboxChangeEvent=null;YAHOO.widget.AutoComplete._nIndex=0;YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._elTextbox=null;YAHOO.widget.AutoComplete.prototype._elContainer=null;YAHOO.widget.AutoComplete.prototype._elContent=null;YAHOO.widget.AutoComplete.prototype._elHeader=null;YAHOO.widget.AutoComplete.prototype._elBody=null;YAHOO.widget.AutoComplete.prototype._elFooter=null;YAHOO.widget.AutoComplete.prototype._elShadow=null;YAHOO.widget.AutoComplete.prototype._elIFrame=null;YAHOO.widget.AutoComplete.prototype._bFocused=false;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._elList=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sPastSelections="";YAHOO.widget.AutoComplete.prototype._sInitInputValue=null;YAHOO.widget.AutoComplete.prototype._elCurListItem=null;YAHOO.widget.AutoComplete.prototype._elCurPrehighlightItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._nTypeAheadDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var b=this.minQueryLength;if(!YAHOO.lang.isNumber(b)){this.minQueryLength=1;}var e=this.maxResultsDisplayed;if(!YAHOO.lang.isNumber(e)||(e<1)){this.maxResultsDisplayed=10;}var f=this.queryDelay;if(!YAHOO.lang.isNumber(f)||(f<0)){this.queryDelay=0.2;}var c=this.typeAheadDelay;if(!YAHOO.lang.isNumber(c)||(c<0)){this.typeAheadDelay=0.2;}var a=this.delimChar;if(YAHOO.lang.isString(a)&&(a.length>0)){this.delimChar=[a];}else{if(!YAHOO.lang.isArray(a)){this.delimChar=null;}}var d=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(!YAHOO.lang.isNumber(d)||(d<0)){this.animSpeed=0.3;}if(!this._oAnim){this._oAnim=new YAHOO.util.Anim(this._elContent,{},this.animSpeed);}else{this._oAnim.duration=this.animSpeed;}}if(this.forceSelection&&a){}};YAHOO.widget.AutoComplete.prototype._initContainerHelperEls=function(){if(this.useShadow&&!this._elShadow){var a=document.createElement("div");a.className="yui-ac-shadow";a.style.width=0;a.style.height=0;this._elShadow=this._elContainer.appendChild(a);}if(this.useIFrame&&!this._elIFrame){var b=document.createElement("iframe");b.src=this._iFrameSrc;b.frameBorder=0;b.scrolling="no";b.style.position="absolute";b.style.width=0;b.style.height=0;b.style.padding=0;b.tabIndex=-1;b.role="presentation";b.title="Presentational iframe shim";this._elIFrame=this._elContainer.appendChild(b);}};YAHOO.widget.AutoComplete.prototype._initContainerEl=function(){YAHOO.util.Dom.addClass(this._elContainer,"yui-ac-container");if(!this._elContent){var c=document.createElement("div");c.className="yui-ac-content";c.style.display="none";this._elContent=this._elContainer.appendChild(c);var b=document.createElement("div");b.className="yui-ac-hd";b.style.display="none";this._elHeader=this._elContent.appendChild(b);var d=document.createElement("div");d.className="yui-ac-bd";this._elBody=this._elContent.appendChild(d);var a=document.createElement("div");a.className="yui-ac-ft";a.style.display="none";this._elFooter=this._elContent.appendChild(a);}else{}};YAHOO.widget.AutoComplete.prototype._initListEl=function(){var c=this.maxResultsDisplayed,a=this._elList||document.createElement("ul"),b;while(a.childNodes.length=18&&a<=20)||(a==27)||(a>=33&&a<=35)||(a>=36&&a<=40)||(a>=44&&a<=45)||(a==229)){return true;}return false;};YAHOO.widget.AutoComplete.prototype._sendQuery=function(d){if(this.minQueryLength<0){this._toggleContainer(false);return;}if(this.delimChar){var a=this._extractQuery(d);d=a.query;this._sPastSelections=a.previous;}if((d&&(d.length0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID); }this._toggleContainer(false);return;}d=encodeURIComponent(d);this._nDelayID=-1;if(this.dataSource.queryMatchSubset||this.queryMatchSubset){var c=this.getSubsetMatches(d);if(c){this.handleResponse(d,c,{query:d});return;}}if(this.dataSource.responseStripAfter){this.dataSource.doBeforeParseData=this.preparseRawResponse;}if(this.applyLocalFilter){this.dataSource.doBeforeCallback=this.filterResults;}var b=this.generateRequest(d);if(b!==undefined){this.dataRequestEvent.fire(this,d,b);this.dataSource.sendRequest(b,{success:this.handleResponse,failure:this.handleResponse,scope:this,argument:{query:d}});}else{this.dataRequestCancelEvent.fire(this,d);}};YAHOO.widget.AutoComplete.prototype._populateListItem=function(b,a,c){b.innerHTML=this.formatResult(a,c,b._sResultMatch);};YAHOO.widget.AutoComplete.prototype._populateList=function(n,f,c){if(this._nTypeAheadDelayID!=-1){clearTimeout(this._nTypeAheadDelayID);}n=(c&&c.query)?c.query:n;var h=this.doBeforeLoadData(n,f,c);if(h&&!f.error){this.dataReturnEvent.fire(this,n,f.results);if(this._bFocused){var p=decodeURIComponent(n);this._sCurQuery=p;this._bItemSelected=false;var u=f.results,a=Math.min(u.length,this.maxResultsDisplayed),m=(this.dataSource.responseSchema.fields)?(this.dataSource.responseSchema.fields[0].key||this.dataSource.responseSchema.fields[0]):0;if(a>0){if(!this._elList||(this._elList.childNodes.length=0;t--){var s=l[t],e=u[t];if(this.resultTypeList){var b=[];b[0]=(YAHOO.lang.isString(e))?e:e[m]||e[this.key];var o=this.dataSource.responseSchema.fields;if(YAHOO.lang.isArray(o)&&(o.length>1)){for(var q=1,v=o.length;q=a;r--){g=l[r];g.style.display="none";}}this._nDisplayedItems=a;this.containerPopulateEvent.fire(this,n,u);if(this.autoHighlight){var d=this._elList.firstChild;this._toggleHighlight(d,"to");this.itemArrowToEvent.fire(this,d);this._typeAhead(d,n);}else{this._toggleHighlight(this._elCurListItem,"from");}h=this._doBeforeExpandContainer(this._elTextbox,this._elContainer,n,u);this._toggleContainer(h);}else{this._toggleContainer(false);}return;}}else{this.dataErrorEvent.fire(this,n,f);}};YAHOO.widget.AutoComplete.prototype._doBeforeExpandContainer=function(d,a,c,b){if(this.autoSnapContainer){this.snapContainer();}return this.doBeforeExpandContainer(d,a,c,b);};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var a=(this.delimChar)?this._extractQuery(this._elTextbox.value):{previous:"",query:this._elTextbox.value};this._elTextbox.value=a.previous;this.selectionEnforceEvent.fire(this,a.query);};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var a=null;for(var b=0;b=0;b--){g=h.lastIndexOf(c[b]);if(g>f){f=g;}}if(c[b]==" "){for(var a=c.length-1;a>=0;a--){if(h[f-1]==c[a]){f--;break;}}}if(f>-1){e=f+1;while(h.charAt(e)==" "){e+=1;}d=h.substring(0,e);h=h.substr(e);}else{d="";}return{previous:d,query:h};};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(d){var e=this._elContent.offsetWidth+"px";var b=this._elContent.offsetHeight+"px";if(this.useIFrame&&this._elIFrame){var c=this._elIFrame;if(d){c.style.width=e;c.style.height=b;c.style.padding="";}else{c.style.width=0;c.style.height=0;c.style.padding=0;}}if(this.useShadow&&this._elShadow){var a=this._elShadow;if(d){a.style.width=e;a.style.height=b;}else{a.style.width=0;a.style.height=0;}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(i){var d=this._elContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return;}if(!i){this._toggleHighlight(this._elCurListItem,"from");this._nDisplayedItems=0;this._sCurQuery=null;if(this._elContent.style.display=="none"){return;}}var a=this._oAnim;if(a&&a.getEl()&&(this.animHoriz||this.animVert)){if(a.isAnimated()){a.stop(true);}var g=this._elContent.cloneNode(true);d.appendChild(g);g.style.top="-9000px";g.style.width="";g.style.height="";g.style.display="";var f=g.offsetWidth;var c=g.offsetHeight;var b=(this.animHoriz)?0:f;var e=(this.animVert)?0:c;a.attributes=(i)?{width:{to:f},height:{to:c}}:{width:{to:b},height:{to:e}};if(i&&!this._bContainerOpen){this._elContent.style.width=b+"px";this._elContent.style.height=e+"px";}else{this._elContent.style.width=f+"px";this._elContent.style.height=c+"px";}d.removeChild(g);g=null;var h=this;var j=function(){a.onComplete.unsubscribeAll();if(i){h._toggleContainerHelpers(true);h._bContainerOpen=i;h.containerExpandEvent.fire(h);}else{h._elContent.style.display="none";h._bContainerOpen=i;h.containerCollapseEvent.fire(h);}};this._toggleContainerHelpers(false);this._elContent.style.display="";a.onComplete.subscribe(j);a.animate();}else{if(i){this._elContent.style.display="";this._toggleContainerHelpers(true); this._bContainerOpen=i;this.containerExpandEvent.fire(this);}else{this._toggleContainerHelpers(false);this._elContent.style.display="none";this._bContainerOpen=i;this.containerCollapseEvent.fire(this);}}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(a,c){if(a){var b=this.highlightClassName;if(this._elCurListItem){YAHOO.util.Dom.removeClass(this._elCurListItem,b);this._elCurListItem=null;}if((c=="to")&&b){YAHOO.util.Dom.addClass(a,b);this._elCurListItem=a;}}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(b,c){var a=this.prehighlightClassName;if(this._elCurPrehighlightItem){YAHOO.util.Dom.removeClass(this._elCurPrehighlightItem,a);}if(b==this._elCurListItem){return;}if((c=="mouseover")&&a){YAHOO.util.Dom.addClass(b,a);this._elCurPrehighlightItem=b;}else{YAHOO.util.Dom.removeClass(b,a);}};YAHOO.widget.AutoComplete.prototype._updateValue=function(c){if(!this.suppressInputUpdate){var f=this._elTextbox;var e=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var b=c._sResultMatch;var d="";if(e){d=this._sPastSelections;d+=b+e;if(e!=" "){d+=" ";}}else{d=b;}f.value=d;if(f.type=="textarea"){f.scrollTop=f.scrollHeight;}var a=f.value.length;this._selectText(f,a,a);this._elCurListItem=c;}};YAHOO.widget.AutoComplete.prototype._selectItem=function(a){this._bItemSelected=true;this._updateValue(a);this._sPastSelections=this._elTextbox.value;this._clearInterval();this.itemSelectEvent.fire(this,a,a._oResultData);this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(this._elCurListItem){this._selectItem(this._elCurListItem);}else{this._toggleContainer(false);}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(g){if(this._bContainerOpen){var h=this._elCurListItem,d=-1;if(h){d=h._nItemIndex;}var e=(g==40)?(d+1):(d-1);if(e<-2||e>=this._nDisplayedItems){return;}if(h){this._toggleHighlight(h,"from");this.itemArrowFromEvent.fire(this,h);}if(e==-1){if(this.delimChar){this._elTextbox.value=this._sPastSelections+this._sCurQuery;}else{this._elTextbox.value=this._sCurQuery;}return;}if(e==-2){this._toggleContainer(false);return;}var f=this._elList.childNodes[e],b=this._elContent,c=YAHOO.util.Dom.getStyle(b,"overflow"),i=YAHOO.util.Dom.getStyle(b,"overflowY"),a=((c=="auto")||(c=="scroll")||(i=="auto")||(i=="scroll"));if(a&&(e>-1)&&(e(b.scrollTop+b.offsetHeight)){b.scrollTop=(f.offsetTop+f.offsetHeight)-b.offsetHeight;}else{if((f.offsetTop+f.offsetHeight)(b.scrollTop+b.offsetHeight)){this._elContent.scrollTop=(f.offsetTop+f.offsetHeight)-b.offsetHeight;}}}}this._toggleHighlight(f,"to");this.itemArrowToEvent.fire(this,f);if(this.typeAhead){this._updateValue(f);this._sCurQuery=f._sResultMatch;}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(a,c){var d=YAHOO.util.Event.getTarget(a);var b=d.nodeName.toLowerCase();while(d&&(b!="table")){switch(b){case"body":return;case"li":if(c.prehighlightClassName){c._togglePrehighlight(d,"mouseover");}else{c._toggleHighlight(d,"to");}c.itemMouseOverEvent.fire(c,d);break;case"div":if(YAHOO.util.Dom.hasClass(d,"yui-ac-container")){c._bOverContainer=true;return;}break;default:break;}d=d.parentNode;if(d){b=d.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(a,c){var d=YAHOO.util.Event.getTarget(a);var b=d.nodeName.toLowerCase();while(d&&(b!="table")){switch(b){case"body":return;case"li":if(c.prehighlightClassName){c._togglePrehighlight(d,"mouseout");}else{c._toggleHighlight(d,"from");}c.itemMouseOutEvent.fire(c,d);break;case"ul":c._toggleHighlight(c._elCurListItem,"to");break;case"div":if(YAHOO.util.Dom.hasClass(d,"yui-ac-container")){c._bOverContainer=false;return;}break;default:break;}d=d.parentNode;if(d){b=d.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerClick=function(a,c){var d=YAHOO.util.Event.getTarget(a);var b=d.nodeName.toLowerCase();while(d&&(b!="table")){switch(b){case"body":return;case"li":c._toggleHighlight(d,"to");c._selectItem(d);return;default:break;}d=d.parentNode;if(d){b=d.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(a,b){b._focus();};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(a,b){b._toggleContainerHelpers(b._bContainerOpen);};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(a,b){var c=a.keyCode;if(b._nTypeAheadDelayID!=-1){clearTimeout(b._nTypeAheadDelayID);}switch(c){case 9:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(b._elCurListItem){if(b.delimChar&&(b._nKeyCode!=c)){if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);}}b._selectItem(b._elCurListItem);}else{b._toggleContainer(false);}}break;case 13:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(b._elCurListItem){if(b._nKeyCode!=c){if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);}}b._selectItem(b._elCurListItem);}else{b._toggleContainer(false);}}break;case 27:b._toggleContainer(false);return;case 39:b._jumpSelection();break;case 38:if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);b._moveSelection(c);}break;case 40:if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a);b._moveSelection(c);}break;default:b._bItemSelected=false;b._toggleHighlight(b._elCurListItem,"from");b.textboxKeyEvent.fire(b,c);break;}if(c===18){b._enableIntervalDetection();}b._nKeyCode=c;};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(a,b){var c=a.keyCode;if(YAHOO.env.ua.opera||(navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&(YAHOO.env.ua.webkit<420)){switch(c){case 9:if(b._bContainerOpen){if(b.delimChar){YAHOO.util.Event.stopEvent(a);}if(b._elCurListItem){b._selectItem(b._elCurListItem);}else{b._toggleContainer(false);}}break;case 13:if(b._bContainerOpen){YAHOO.util.Event.stopEvent(a); if(b._elCurListItem){b._selectItem(b._elCurListItem);}else{b._toggleContainer(false);}}break;default:break;}}else{if(c==229){b._enableIntervalDetection();}}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(a,c){var b=this.value;c._initProps();var d=a.keyCode;if(c._isIgnoreKey(d)){return;}if(c._nDelayID!=-1){clearTimeout(c._nDelayID);}c._nDelayID=setTimeout(function(){c._sendQuery(b);},(c.queryDelay*1000));};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(a,b){if(!b._bFocused){b._elTextbox.setAttribute("autocomplete","off");b._bFocused=true;b._sInitInputValue=b._elTextbox.value;b.textboxFocusEvent.fire(b);}};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(a,c){if(!c._bOverContainer||(c._nKeyCode==9)){if(!c._bItemSelected){var b=c._textMatchesOption();if(!c._bContainerOpen||(c._bContainerOpen&&(b===null))){if(c.forceSelection){c._clearSelection();}else{c.unmatchedItemSelectEvent.fire(c,c._sCurQuery);}}else{if(c.forceSelection){c._selectItem(b);}}}c._clearInterval();c._bFocused=false;if(c._sInitInputValue!==c._elTextbox.value){c.textboxChangeEvent.fire(c);}c.textboxBlurEvent.fire(c);c._toggleContainer(false);}else{c._focus();}};YAHOO.widget.AutoComplete.prototype._onWindowUnload=function(a,b){if(b&&b._elTextbox&&b.allowBrowserAutocomplete){b._elTextbox.setAttribute("autocomplete","on");}};YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery=function(a){return this.generateRequest(a);};YAHOO.widget.AutoComplete.prototype.getListItems=function(){var c=[],b=this._elList.childNodes;for(var a=b.length-1;a>=0;a--){c[a]=b[a];}return c;};YAHOO.widget.AutoComplete._cloneObject=function(d){if(!YAHOO.lang.isValue(d)){return d;}var f={};if(YAHOO.lang.isFunction(d)){f=d;}else{if(YAHOO.lang.isArray(d)){var e=[];for(var c=0,b=d.length;c 0) { // Substring until first space sClass = sSource.substring(0,spaceIndex); // The rest of the source sDetail = sSource.substring(spaceIndex,sSource.length); } else { sClass = sSource; } if(this._isNewSource(sClass)) { this._createNewSource(sClass); } } var timestamp = new Date(); var logEntry = new YAHOO.widget.LogMsg({ msg: sMsg, time: timestamp, category: sCategory, source: sClass, sourceDetail: sDetail }); var stack = this._stack; var maxStackEntries = this.maxStackEntries; if(maxStackEntries && !isNaN(maxStackEntries) && (stack.length >= maxStackEntries)) { stack.shift(); } stack.push(logEntry); this.newLogEvent.fire(logEntry); if(this._browserConsoleEnabled) { this._printToBrowserConsole(logEntry); } return true; } else { return false; } }; /** * Resets internal stack and startTime, enables Logger, and fires logResetEvent. * * @method reset */ YAHOO.widget.Logger.reset = function() { this._stack = []; this._startTime = new Date().getTime(); this.loggerEnabled = true; this.log("Logger reset"); this.logResetEvent.fire(); }; /** * Public accessor to internal stack of log message objects. * * @method getStack * @return {Object[]} Array of log message objects. */ YAHOO.widget.Logger.getStack = function() { return this._stack; }; /** * Public accessor to internal start time. * * @method getStartTime * @return {Date} Internal date of when Logger singleton was initialized. */ YAHOO.widget.Logger.getStartTime = function() { return this._startTime; }; /** * Disables output to the browser's global console.log() function, which is used * by the Firebug extension to Firefox as well as Safari. * * @method disableBrowserConsole */ YAHOO.widget.Logger.disableBrowserConsole = function() { YAHOO.log("Logger output to the function console.log() has been disabled."); this._browserConsoleEnabled = false; }; /** * Enables output to the browser's global console.log() function, which is used * by the Firebug extension to Firefox as well as Safari. * * @method enableBrowserConsole */ YAHOO.widget.Logger.enableBrowserConsole = function() { this._browserConsoleEnabled = true; YAHOO.log("Logger output to the function console.log() has been enabled."); }; /** * Surpresses native JavaScript errors and outputs to console. By default, * Logger does not handle JavaScript window error events. * NB: Not all browsers support the window.onerror event. * * @method handleWindowErrors */ YAHOO.widget.Logger.handleWindowErrors = function() { if(!YAHOO.widget.Logger._windowErrorsHandled) { // Save any previously defined handler to call if(window.error) { YAHOO.widget.Logger._origOnWindowError = window.onerror; } window.onerror = YAHOO.widget.Logger._onWindowError; YAHOO.widget.Logger._windowErrorsHandled = true; YAHOO.log("Logger handling of window.onerror has been enabled."); } else { YAHOO.log("Logger handling of window.onerror had already been enabled."); } }; /** * Unsurpresses native JavaScript errors. By default, * Logger does not handle JavaScript window error events. * NB: Not all browsers support the window.onerror event. * * @method unhandleWindowErrors */ YAHOO.widget.Logger.unhandleWindowErrors = function() { if(YAHOO.widget.Logger._windowErrorsHandled) { // Revert to any previously defined handler to call if(YAHOO.widget.Logger._origOnWindowError) { window.onerror = YAHOO.widget.Logger._origOnWindowError; YAHOO.widget.Logger._origOnWindowError = null; } else { window.onerror = null; } YAHOO.widget.Logger._windowErrorsHandled = false; YAHOO.log("Logger handling of window.onerror has been disabled."); } else { YAHOO.log("Logger handling of window.onerror had already been disabled."); } }; ///////////////////////////////////////////////////////////////////////////// // // Public events // ///////////////////////////////////////////////////////////////////////////// /** * Fired when a new category has been created. * * @event categoryCreateEvent * @param sCategory {String} Category name. */ YAHOO.widget.Logger.categoryCreateEvent = new YAHOO.util.CustomEvent("categoryCreate", this, true); /** * Fired when a new source has been named. * * @event sourceCreateEvent * @param sSource {String} Source name. */ YAHOO.widget.Logger.sourceCreateEvent = new YAHOO.util.CustomEvent("sourceCreate", this, true); /** * Fired when a new log message has been created. * * @event newLogEvent * @param sMsg {String} Log message. */ YAHOO.widget.Logger.newLogEvent = new YAHOO.util.CustomEvent("newLog", this, true); /** * Fired when the Logger has been reset has been created. * * @event logResetEvent */ YAHOO.widget.Logger.logResetEvent = new YAHOO.util.CustomEvent("logReset", this, true); ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Creates a new category of log messages and fires categoryCreateEvent. * * @method _createNewCategory * @param sCategory {String} Category name. * @private */ YAHOO.widget.Logger._createNewCategory = function(sCategory) { this.categories.push(sCategory); this.categoryCreateEvent.fire(sCategory); }; /** * Checks to see if a category has already been created. * * @method _isNewCategory * @param sCategory {String} Category name. * @return {Boolean} Returns true if category is unknown, else returns false. * @private */ YAHOO.widget.Logger._isNewCategory = function(sCategory) { for(var i=0; i < this.categories.length; i++) { if(sCategory == this.categories[i]) { return false; } } return true; }; /** * Creates a new source of log messages and fires sourceCreateEvent. * * @method _createNewSource * @param sSource {String} Source name. * @private */ YAHOO.widget.Logger._createNewSource = function(sSource) { this.sources.push(sSource); this.sourceCreateEvent.fire(sSource); }; /** * Checks to see if a source already exists. * * @method _isNewSource * @param sSource {String} Source name. * @return {Boolean} Returns true if source is unknown, else returns false. * @private */ YAHOO.widget.Logger._isNewSource = function(sSource) { if(sSource) { for(var i=0; i < this.sources.length; i++) { if(sSource == this.sources[i]) { return false; } } return true; } }; /** * Outputs a log message to global console.log() function. * * @method _printToBrowserConsole * @param oEntry {Object} Log entry object. * @private */ YAHOO.widget.Logger._printToBrowserConsole = function(oEntry) { if ((window.console && console.log) || (window.opera && opera.postError)) { var category = oEntry.category; var label = oEntry.category.substring(0,4).toUpperCase(); var time = oEntry.time; var localTime; if (time.toLocaleTimeString) { localTime = time.toLocaleTimeString(); } else { localTime = time.toString(); } var msecs = time.getTime(); var elapsedTime = (YAHOO.widget.Logger._lastTime) ? (msecs - YAHOO.widget.Logger._lastTime) : 0; YAHOO.widget.Logger._lastTime = msecs; var output = localTime + " (" + elapsedTime + "ms): " + oEntry.source + ": "; if (window.console) { console.log(output, oEntry.msg); } else { opera.postError(output + oEntry.msg); } } }; ///////////////////////////////////////////////////////////////////////////// // // Private event handlers // ///////////////////////////////////////////////////////////////////////////// /** * Handles logging of messages due to window error events. * * @method _onWindowError * @param sMsg {String} The error message. * @param sUrl {String} URL of the error. * @param sLine {String} Line number of the error. * @private */ YAHOO.widget.Logger._onWindowError = function(sMsg,sUrl,sLine) { // Logger is not in scope of this event handler try { YAHOO.widget.Logger.log(sMsg+' ('+sUrl+', line '+sLine+')', "window"); if(YAHOO.widget.Logger._origOnWindowError) { YAHOO.widget.Logger._origOnWindowError(); } } catch(e) { return false; } }; ///////////////////////////////////////////////////////////////////////////// // // First log // ///////////////////////////////////////////////////////////////////////////// YAHOO.widget.Logger.log("Logger initialized"); } /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ (function () { var Logger = YAHOO.widget.Logger, u = YAHOO.util, Dom = u.Dom, Event = u.Event, d = document; function make(el,props) { el = d.createElement(el); if (props) { for (var p in props) { if (props.hasOwnProperty(p)) { el[p] = props[p]; } } } return el; } /** * The LogReader class provides UI to read messages logged to YAHOO.widget.Logger. * * @class LogReader * @constructor * @param elContainer {HTMLElement} (optional) DOM element reference of an existing DIV. * @param elContainer {String} (optional) String ID of an existing DIV. * @param oConfigs {Object} (optional) Object literal of configuration params. */ function LogReader(elContainer, oConfigs) { this._sName = LogReader._index; LogReader._index++; this._init.apply(this,arguments); /** * Render the LogReader immediately upon instantiation. If set to false, * you must call myLogReader.render() to generate the UI. * * @property autoRender * @type {Boolean} * @default true */ if (this.autoRender !== false) { this.render(); } } ///////////////////////////////////////////////////////////////////////////// // // Static member variables // ///////////////////////////////////////////////////////////////////////////// YAHOO.lang.augmentObject(LogReader, { /** * Internal class member to index multiple LogReader instances. * * @property _memberName * @static * @type Number * @default 0 * @private */ _index : 0, /** * Node template for the log entries * @property ENTRY_TEMPLATE * @static * @type {HTMLElement} * @default pre element with class yui-log-entry */ ENTRY_TEMPLATE : (function () { return make('pre',{ className: 'yui-log-entry' }); })(), /** * Template used for innerHTML of verbose entry output. * @property VERBOSE_TEMPLATE * @static * @default "<p><span class='{category}'>{label}</span>{totalTime}ms (+{elapsedTime}) {localTime}:</p><p>{sourceAndDetail}</p><p>{message}</p>" */ VERBOSE_TEMPLATE : "

          {label} {totalTime}ms (+{elapsedTime}) {localTime}:

          {sourceAndDetail}

          {message}

          ", /** * Template used for innerHTML of compact entry output. * @property BASIC_TEMPLATE * @static * @default "<p><span class='{category}'>{label}</span>{totalTime}ms (+{elapsedTime}) {localTime}: {sourceAndDetail}: {message}</p>" */ BASIC_TEMPLATE : "

          {label} {totalTime}ms (+{elapsedTime}) {localTime}: {sourceAndDetail}: {message}

          " }); ///////////////////////////////////////////////////////////////////////////// // // Public member variables // ///////////////////////////////////////////////////////////////////////////// LogReader.prototype = { /** * Whether or not LogReader is enabled to output log messages. * * @property logReaderEnabled * @type Boolean * @default true */ logReaderEnabled : true, /** * Public member to access CSS width of the LogReader container. * * @property width * @type String */ width : null, /** * Public member to access CSS height of the LogReader container. * * @property height * @type String */ height : null, /** * Public member to access CSS top position of the LogReader container. * * @property top * @type String */ top : null, /** * Public member to access CSS left position of the LogReader container. * * @property left * @type String */ left : null, /** * Public member to access CSS right position of the LogReader container. * * @property right * @type String */ right : null, /** * Public member to access CSS bottom position of the LogReader container. * * @property bottom * @type String */ bottom : null, /** * Public member to access CSS font size of the LogReader container. * * @property fontSize * @type String */ fontSize : null, /** * Whether or not the footer UI is enabled for the LogReader. * * @property footerEnabled * @type Boolean * @default true */ footerEnabled : true, /** * Whether or not output is verbose (more readable). Setting to true will make * output more compact (less readable). * * @property verboseOutput * @type Boolean * @default true */ verboseOutput : true, /** * Custom output format for log messages. Defaults to null, which falls * back to verboseOutput param deciding between LogReader.VERBOSE_TEMPLATE * and LogReader.BASIC_TEMPLATE. Use bracketed place holders to mark where * message info should go. Available place holder names include: *
            *
          • category
          • *
          • label
          • *
          • sourceAndDetail
          • *
          • message
          • *
          • localTime
          • *
          • elapsedTime
          • *
          • totalTime
          • *
          * * @property entryFormat * @type String * @default null */ entryFormat : null, /** * Whether or not newest message is printed on top. * * @property newestOnTop * @type Boolean */ newestOnTop : true, /** * Output timeout buffer in milliseconds. * * @property outputBuffer * @type Number * @default 100 */ outputBuffer : 100, /** * Maximum number of messages a LogReader console will display. * * @property thresholdMax * @type Number * @default 500 */ thresholdMax : 500, /** * When a LogReader console reaches its thresholdMax, it will clear out messages * and print out the latest thresholdMin number of messages. * * @property thresholdMin * @type Number * @default 100 */ thresholdMin : 100, /** * True when LogReader is in a collapsed state, false otherwise. * * @property isCollapsed * @type Boolean * @default false */ isCollapsed : false, /** * True when LogReader is in a paused state, false otherwise. * * @property isPaused * @type Boolean * @default false */ isPaused : false, /** * Enables draggable LogReader if DragDrop Utility is present. * * @property draggable * @type Boolean * @default true */ draggable : true, ///////////////////////////////////////////////////////////////////////////// // // Public methods // ///////////////////////////////////////////////////////////////////////////// /** * Public accessor to the unique name of the LogReader instance. * * @method toString * @return {String} Unique name of the LogReader instance. */ toString : function() { return "LogReader instance" + this._sName; }, /** * Pauses output of log messages. While paused, log messages are not lost, but * get saved to a buffer and then output upon resume of LogReader. * * @method pause */ pause : function() { this.isPaused = true; this._timeout = null; this.logReaderEnabled = false; if (this._btnPause) { this._btnPause.value = "Resume"; } }, /** * Resumes output of log messages, including outputting any log messages that * have been saved to buffer while paused. * * @method resume */ resume : function() { this.isPaused = false; this.logReaderEnabled = true; this._printBuffer(); if (this._btnPause) { this._btnPause.value = "Pause"; } }, /** * Adds the UI to the DOM, attaches event listeners, and bootstraps initial * UI state. * * @method render */ render : function () { if (this.rendered) { return; } this._initContainerEl(); this._initHeaderEl(); this._initConsoleEl(); this._initFooterEl(); this._initCategories(); this._initSources(); this._initDragDrop(); // Subscribe to Logger custom events Logger.newLogEvent.subscribe(this._onNewLog, this); Logger.logResetEvent.subscribe(this._onReset, this); Logger.categoryCreateEvent.subscribe(this._onCategoryCreate, this); Logger.sourceCreateEvent.subscribe(this._onSourceCreate, this); this.rendered = true; this._filterLogs(); }, /** * Removes the UI from the DOM entirely and detaches all event listeners. * Implementers should note that Logger will still accumulate messages. * * @method destroy */ destroy : function () { Event.purgeElement(this._elContainer,true); this._elContainer.innerHTML = ''; this._elContainer.parentNode.removeChild(this._elContainer); this.rendered = false; }, /** * Hides UI of LogReader. Logging functionality is not disrupted. * * @method hide */ hide : function() { this._elContainer.style.display = "none"; }, /** * Shows UI of LogReader. Logging functionality is not disrupted. * * @method show */ show : function() { this._elContainer.style.display = "block"; }, /** * Collapses UI of LogReader. Logging functionality is not disrupted. * * @method collapse */ collapse : function() { this._elConsole.style.display = "none"; if(this._elFt) { this._elFt.style.display = "none"; } this._btnCollapse.value = "Expand"; this.isCollapsed = true; }, /** * Expands UI of LogReader. Logging functionality is not disrupted. * * @method expand */ expand : function() { this._elConsole.style.display = "block"; if(this._elFt) { this._elFt.style.display = "block"; } this._btnCollapse.value = "Collapse"; this.isCollapsed = false; }, /** * Returns related checkbox element for given filter (i.e., category or source). * * @method getCheckbox * @param {String} Category or source name. * @return {Array} Array of all filter checkboxes. */ getCheckbox : function(filter) { return this._filterCheckboxes[filter]; }, /** * Returns array of enabled categories. * * @method getCategories * @return {String[]} Array of enabled categories. */ getCategories : function() { return this._categoryFilters; }, /** * Shows log messages associated with given category. * * @method showCategory * @param {String} Category name. */ showCategory : function(sCategory) { var filtersArray = this._categoryFilters; // Don't do anything if category is already enabled // Use Array.indexOf if available... if(filtersArray.indexOf) { if(filtersArray.indexOf(sCategory) > -1) { return; } } // ...or do it the old-fashioned way else { for(var i=0; i -1) { return; } } // ...or do it the old-fashioned way else { for(var i=0; i", and "&" to HTML entities. * * @method html2Text * @param sHtml {String} String to convert. * @private */ html2Text : function(sHtml) { if(sHtml) { sHtml += ""; return sHtml.replace(/&/g, "&"). replace(//g, ">"); } return ""; }, ///////////////////////////////////////////////////////////////////////////// // // Private member variables // ///////////////////////////////////////////////////////////////////////////// /** * Name of LogReader instance. * * @property _sName * @type String * @private */ _sName : null, //TODO: remove /** * A class member shared by all LogReaders if a container needs to be * created during instantiation. Will be null if a container element never needs to * be created on the fly, such as when the implementer passes in their own element. * * @property _elDefaultContainer * @type HTMLElement * @private */ //YAHOO.widget.LogReader._elDefaultContainer = null; /** * Buffer of log message objects for batch output. * * @property _buffer * @type Object[] * @private */ _buffer : null, /** * Number of log messages output to console. * * @property _consoleMsgCount * @type Number * @default 0 * @private */ _consoleMsgCount : 0, /** * Date of last output log message. * * @property _lastTime * @type Date * @private */ _lastTime : null, /** * Batched output timeout ID. * * @property _timeout * @type Number * @private */ _timeout : null, /** * Hash of filters and their related checkbox elements. * * @property _filterCheckboxes * @type Object * @private */ _filterCheckboxes : null, /** * Array of filters for log message categories. * * @property _categoryFilters * @type String[] * @private */ _categoryFilters : null, /** * Array of filters for log message sources. * * @property _sourceFilters * @type String[] * @private */ _sourceFilters : null, /** * LogReader container element. * * @property _elContainer * @type HTMLElement * @private */ _elContainer : null, /** * LogReader header element. * * @property _elHd * @type HTMLElement * @private */ _elHd : null, /** * LogReader collapse element. * * @property _elCollapse * @type HTMLElement * @private */ _elCollapse : null, /** * LogReader collapse button element. * * @property _btnCollapse * @type HTMLElement * @private */ _btnCollapse : null, /** * LogReader title header element. * * @property _title * @type HTMLElement * @private */ _title : null, /** * LogReader console element. * * @property _elConsole * @type HTMLElement * @private */ _elConsole : null, /** * LogReader footer element. * * @property _elFt * @type HTMLElement * @private */ _elFt : null, /** * LogReader buttons container element. * * @property _elBtns * @type HTMLElement * @private */ _elBtns : null, /** * Container element for LogReader category filter checkboxes. * * @property _elCategoryFilters * @type HTMLElement * @private */ _elCategoryFilters : null, /** * Container element for LogReader source filter checkboxes. * * @property _elSourceFilters * @type HTMLElement * @private */ _elSourceFilters : null, /** * LogReader pause button element. * * @property _btnPause * @type HTMLElement * @private */ _btnPause : null, /** * Clear button element. * * @property _btnClear * @type HTMLElement * @private */ _btnClear : null, ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Initializes the instance's message buffer, start time, etc * * @method _init * @param container {String|HTMLElement} (optional) the render target * @param config {Object} (optional) instance configuration * @protected */ _init : function (container, config) { // Internal vars this._buffer = []; // output buffer this._filterCheckboxes = {}; // pointers to checkboxes this._lastTime = Logger.getStartTime(); // timestamp of last log message to console // Parse config vars here if (config && (config.constructor == Object)) { for(var param in config) { if (config.hasOwnProperty(param)) { this[param] = config[param]; } } } this._elContainer = Dom.get(container); YAHOO.log("LogReader initialized", null, this.toString()); }, /** * Initializes the primary container element. * * @method _initContainerEl * @private */ _initContainerEl : function() { // Default the container if unset or not a div if(!this._elContainer || !/div$/i.test(this._elContainer.tagName)) { this._elContainer = d.body.insertBefore(make("div"),d.body.firstChild); // Only position absolutely if an in-DOM element is not supplied Dom.addClass(this._elContainer,"yui-log-container"); } Dom.addClass(this._elContainer,"yui-log"); // If implementer has provided container values, trust and set those var style = this._elContainer.style, styleProps = ['width','right','top','fontSize'], prop,i; for (i = styleProps.length - 1; i >= 0; --i) { prop = styleProps[i]; if (this[prop]){ style[prop] = this[prop]; } } if(this.left) { style.left = this.left; style.right = "auto"; } if(this.bottom) { style.bottom = this.bottom; style.top = "auto"; } // Opera needs a little prodding to reflow sometimes if (YAHOO.env.ua.opera) { d.body.style += ''; } }, /** * Initializes the header element. * * @method _initHeaderEl * @private */ _initHeaderEl : function() { // Destroy header if present if(this._elHd) { // Unhook DOM events Event.purgeElement(this._elHd, true); // Remove DOM elements this._elHd.innerHTML = ""; } // Create header // TODO: refactor this into an innerHTML this._elHd = make("div",{ className: "yui-log-hd" }); Dom.generateId(this._elHd, 'yui-log-hd' + this._sName); this._elCollapse = make("div",{ className: 'yui-log-btns' }); this._btnCollapse = make("input",{ type: 'button', className: 'yui-log-button', value: 'Collapse' }); Event.on(this._btnCollapse,'click',this._onClickCollapseBtn,this); this._title = make("h4",{ innerHTML : "Logger Console" }); this._elCollapse.appendChild(this._btnCollapse); this._elHd.appendChild(this._elCollapse); this._elHd.appendChild(this._title); this._elContainer.appendChild(this._elHd); }, /** * Initializes the console element. * * @method _initConsoleEl * @private */ _initConsoleEl : function() { // Destroy console if(this._elConsole) { // Unhook DOM events Event.purgeElement(this._elConsole, true); // Remove DOM elements this._elConsole.innerHTML = ""; } // Ceate console this._elConsole = make("div", { className: "yui-log-bd" }); // If implementer has provided console, trust and set those if(this.height) { this._elConsole.style.height = this.height; } this._elContainer.appendChild(this._elConsole); }, /** * Initializes the footer element. * * @method _initFooterEl * @private */ _initFooterEl : function() { // Don't create footer elements if footer is disabled if(this.footerEnabled) { // Destroy console if(this._elFt) { // Unhook DOM events Event.purgeElement(this._elFt, true); // Remove DOM elements this._elFt.innerHTML = ""; } // TODO: use innerHTML this._elFt = make("div",{ className: "yui-log-ft" }); this._elBtns = make("div", { className: "yui-log-btns" }); this._btnPause = make("input", { type: "button", className: "yui-log-button", value: "Pause" }); Event.on(this._btnPause,'click',this._onClickPauseBtn,this); this._btnClear = make("input", { type: "button", className: "yui-log-button", value: "Clear" }); Event.on(this._btnClear,'click',this._onClickClearBtn,this); this._elCategoryFilters = make("div", { className: "yui-log-categoryfilters" }); this._elSourceFilters = make("div", { className: "yui-log-sourcefilters" }); this._elBtns.appendChild(this._btnPause); this._elBtns.appendChild(this._btnClear); this._elFt.appendChild(this._elBtns); this._elFt.appendChild(this._elCategoryFilters); this._elFt.appendChild(this._elSourceFilters); this._elContainer.appendChild(this._elFt); } }, /** * Initializes Drag and Drop on the header element. * * @method _initDragDrop * @private */ _initDragDrop : function() { // If Drag and Drop utility is available... // ...and draggable is true... // ...then make the header draggable if(u.DD && this.draggable && this._elHd) { var ylog_dd = new u.DD(this._elContainer); ylog_dd.setHandleElId(this._elHd.id); //TODO: use class name this._elHd.style.cursor = "move"; } }, /** * Initializes category filters. * * @method _initCategories * @private */ _initCategories : function() { // Initialize category filters this._categoryFilters = []; var aInitialCategories = Logger.categories; for(var j=0; j < aInitialCategories.length; j++) { var sCategory = aInitialCategories[j]; // Add category to the internal array of filters this._categoryFilters.push(sCategory); // Add checkbox element if UI is enabled if(this._elCategoryFilters) { this._createCategoryCheckbox(sCategory); } } }, /** * Initializes source filters. * * @method _initSources * @private */ _initSources : function() { // Initialize source filters this._sourceFilters = []; var aInitialSources = Logger.sources; for(var j=0; j < aInitialSources.length; j++) { var sSource = aInitialSources[j]; // Add source to the internal array of filters this._sourceFilters.push(sSource); // Add checkbox element if UI is enabled if(this._elSourceFilters) { this._createSourceCheckbox(sSource); } } }, /** * Creates the UI for a category filter in the LogReader footer element. * * @method _createCategoryCheckbox * @param sCategory {String} Category name. * @private */ _createCategoryCheckbox : function(sCategory) { if(this._elFt) { var filter = make("span",{ className: "yui-log-filtergrp" }), checkid = Dom.generateId(null, "yui-log-filter-" + sCategory + this._sName), check = make("input", { id: checkid, className: "yui-log-filter-" + sCategory, type: "checkbox", category: sCategory }), label = make("label", { htmlFor: checkid, className: sCategory, innerHTML: sCategory }); // Subscribe to the click event Event.on(check,'click',this._onCheckCategory,this); this._filterCheckboxes[sCategory] = check; // Append el at the end so IE 5.5 can set "type" attribute // and THEN set checked property filter.appendChild(check); filter.appendChild(label); this._elCategoryFilters.appendChild(filter); check.checked = true; } }, /** * Creates a checkbox in the LogReader footer element to filter by source. * * @method _createSourceCheckbox * @param sSource {String} Source name. * @private */ _createSourceCheckbox : function(sSource) { if(this._elFt) { var filter = make("span",{ className: "yui-log-filtergrp" }), checkid = Dom.generateId(null, "yui-log-filter-" + sSource + this._sName), check = make("input", { id: checkid, className: "yui-log-filter-" + sSource, type: "checkbox", source: sSource }), label = make("label", { htmlFor: checkid, className: sSource, innerHTML: sSource }); // Subscribe to the click event Event.on(check,'click',this._onCheckSource,this); this._filterCheckboxes[sSource] = check; // Append el at the end so IE 5.5 can set "type" attribute // and THEN set checked property filter.appendChild(check); filter.appendChild(label); this._elSourceFilters.appendChild(filter); check.checked = true; } }, /** * Reprints all log messages in the stack through filters. * * @method _filterLogs * @private */ _filterLogs : function() { // Reprint stack with new filters if (this._elConsole !== null) { this.clearConsole(); this._printToConsole(Logger.getStack()); } }, /** * Sends buffer of log messages to output and clears buffer. * * @method _printBuffer * @private */ _printBuffer : function() { this._timeout = null; if(this._elConsole !== null) { var thresholdMax = this.thresholdMax; thresholdMax = (thresholdMax && !isNaN(thresholdMax)) ? thresholdMax : 500; if(this._consoleMsgCount < thresholdMax) { var entries = []; for (var i=0; i this.thresholdMax)) { thresholdMin = 0; } entriesStartIndex = (entriesLen > thresholdMin) ? (entriesLen - thresholdMin) : 0; // Iterate through all log entries for(i=entriesStartIndex; i 0) { // Substring until first space sClass = sSource.substring(0,spaceIndex); // The rest of the source sDetail = sSource.substring(spaceIndex,sSource.length); } else { sClass = sSource; } if(this._isNewSource(sClass)) { this._createNewSource(sClass); } } var timestamp = new Date(); var logEntry = new YAHOO.widget.LogMsg({ msg: sMsg, time: timestamp, category: sCategory, source: sClass, sourceDetail: sDetail }); var stack = this._stack; var maxStackEntries = this.maxStackEntries; if(maxStackEntries && !isNaN(maxStackEntries) && (stack.length >= maxStackEntries)) { stack.shift(); } stack.push(logEntry); this.newLogEvent.fire(logEntry); if(this._browserConsoleEnabled) { this._printToBrowserConsole(logEntry); } return true; } else { return false; } }; /** * Resets internal stack and startTime, enables Logger, and fires logResetEvent. * * @method reset */ YAHOO.widget.Logger.reset = function() { this._stack = []; this._startTime = new Date().getTime(); this.loggerEnabled = true; this.log("Logger reset"); this.logResetEvent.fire(); }; /** * Public accessor to internal stack of log message objects. * * @method getStack * @return {Object[]} Array of log message objects. */ YAHOO.widget.Logger.getStack = function() { return this._stack; }; /** * Public accessor to internal start time. * * @method getStartTime * @return {Date} Internal date of when Logger singleton was initialized. */ YAHOO.widget.Logger.getStartTime = function() { return this._startTime; }; /** * Disables output to the browser's global console.log() function, which is used * by the Firebug extension to Firefox as well as Safari. * * @method disableBrowserConsole */ YAHOO.widget.Logger.disableBrowserConsole = function() { YAHOO.log("Logger output to the function console.log() has been disabled."); this._browserConsoleEnabled = false; }; /** * Enables output to the browser's global console.log() function, which is used * by the Firebug extension to Firefox as well as Safari. * * @method enableBrowserConsole */ YAHOO.widget.Logger.enableBrowserConsole = function() { this._browserConsoleEnabled = true; YAHOO.log("Logger output to the function console.log() has been enabled."); }; /** * Surpresses native JavaScript errors and outputs to console. By default, * Logger does not handle JavaScript window error events. * NB: Not all browsers support the window.onerror event. * * @method handleWindowErrors */ YAHOO.widget.Logger.handleWindowErrors = function() { if(!YAHOO.widget.Logger._windowErrorsHandled) { // Save any previously defined handler to call if(window.error) { YAHOO.widget.Logger._origOnWindowError = window.onerror; } window.onerror = YAHOO.widget.Logger._onWindowError; YAHOO.widget.Logger._windowErrorsHandled = true; YAHOO.log("Logger handling of window.onerror has been enabled."); } else { YAHOO.log("Logger handling of window.onerror had already been enabled."); } }; /** * Unsurpresses native JavaScript errors. By default, * Logger does not handle JavaScript window error events. * NB: Not all browsers support the window.onerror event. * * @method unhandleWindowErrors */ YAHOO.widget.Logger.unhandleWindowErrors = function() { if(YAHOO.widget.Logger._windowErrorsHandled) { // Revert to any previously defined handler to call if(YAHOO.widget.Logger._origOnWindowError) { window.onerror = YAHOO.widget.Logger._origOnWindowError; YAHOO.widget.Logger._origOnWindowError = null; } else { window.onerror = null; } YAHOO.widget.Logger._windowErrorsHandled = false; YAHOO.log("Logger handling of window.onerror has been disabled."); } else { YAHOO.log("Logger handling of window.onerror had already been disabled."); } }; ///////////////////////////////////////////////////////////////////////////// // // Public events // ///////////////////////////////////////////////////////////////////////////// /** * Fired when a new category has been created. * * @event categoryCreateEvent * @param sCategory {String} Category name. */ YAHOO.widget.Logger.categoryCreateEvent = new YAHOO.util.CustomEvent("categoryCreate", this, true); /** * Fired when a new source has been named. * * @event sourceCreateEvent * @param sSource {String} Source name. */ YAHOO.widget.Logger.sourceCreateEvent = new YAHOO.util.CustomEvent("sourceCreate", this, true); /** * Fired when a new log message has been created. * * @event newLogEvent * @param sMsg {String} Log message. */ YAHOO.widget.Logger.newLogEvent = new YAHOO.util.CustomEvent("newLog", this, true); /** * Fired when the Logger has been reset has been created. * * @event logResetEvent */ YAHOO.widget.Logger.logResetEvent = new YAHOO.util.CustomEvent("logReset", this, true); ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Creates a new category of log messages and fires categoryCreateEvent. * * @method _createNewCategory * @param sCategory {String} Category name. * @private */ YAHOO.widget.Logger._createNewCategory = function(sCategory) { this.categories.push(sCategory); this.categoryCreateEvent.fire(sCategory); }; /** * Checks to see if a category has already been created. * * @method _isNewCategory * @param sCategory {String} Category name. * @return {Boolean} Returns true if category is unknown, else returns false. * @private */ YAHOO.widget.Logger._isNewCategory = function(sCategory) { for(var i=0; i < this.categories.length; i++) { if(sCategory == this.categories[i]) { return false; } } return true; }; /** * Creates a new source of log messages and fires sourceCreateEvent. * * @method _createNewSource * @param sSource {String} Source name. * @private */ YAHOO.widget.Logger._createNewSource = function(sSource) { this.sources.push(sSource); this.sourceCreateEvent.fire(sSource); }; /** * Checks to see if a source already exists. * * @method _isNewSource * @param sSource {String} Source name. * @return {Boolean} Returns true if source is unknown, else returns false. * @private */ YAHOO.widget.Logger._isNewSource = function(sSource) { if(sSource) { for(var i=0; i < this.sources.length; i++) { if(sSource == this.sources[i]) { return false; } } return true; } }; /** * Outputs a log message to global console.log() function. * * @method _printToBrowserConsole * @param oEntry {Object} Log entry object. * @private */ YAHOO.widget.Logger._printToBrowserConsole = function(oEntry) { if ((window.console && console.log) || (window.opera && opera.postError)) { var category = oEntry.category; var label = oEntry.category.substring(0,4).toUpperCase(); var time = oEntry.time; var localTime; if (time.toLocaleTimeString) { localTime = time.toLocaleTimeString(); } else { localTime = time.toString(); } var msecs = time.getTime(); var elapsedTime = (YAHOO.widget.Logger._lastTime) ? (msecs - YAHOO.widget.Logger._lastTime) : 0; YAHOO.widget.Logger._lastTime = msecs; var output = localTime + " (" + elapsedTime + "ms): " + oEntry.source + ": "; if (window.console) { console.log(output, oEntry.msg); } else { opera.postError(output + oEntry.msg); } } }; ///////////////////////////////////////////////////////////////////////////// // // Private event handlers // ///////////////////////////////////////////////////////////////////////////// /** * Handles logging of messages due to window error events. * * @method _onWindowError * @param sMsg {String} The error message. * @param sUrl {String} URL of the error. * @param sLine {String} Line number of the error. * @private */ YAHOO.widget.Logger._onWindowError = function(sMsg,sUrl,sLine) { // Logger is not in scope of this event handler try { YAHOO.widget.Logger.log(sMsg+' ('+sUrl+', line '+sLine+')', "window"); if(YAHOO.widget.Logger._origOnWindowError) { YAHOO.widget.Logger._origOnWindowError(); } } catch(e) { return false; } }; ///////////////////////////////////////////////////////////////////////////// // // First log // ///////////////////////////////////////////////////////////////////////////// YAHOO.widget.Logger.log("Logger initialized"); } /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ (function () { var Logger = YAHOO.widget.Logger, u = YAHOO.util, Dom = u.Dom, Event = u.Event, d = document; function make(el,props) { el = d.createElement(el); if (props) { for (var p in props) { if (props.hasOwnProperty(p)) { el[p] = props[p]; } } } return el; } /** * The LogReader class provides UI to read messages logged to YAHOO.widget.Logger. * * @class LogReader * @constructor * @param elContainer {HTMLElement} (optional) DOM element reference of an existing DIV. * @param elContainer {String} (optional) String ID of an existing DIV. * @param oConfigs {Object} (optional) Object literal of configuration params. */ function LogReader(elContainer, oConfigs) { this._sName = LogReader._index; LogReader._index++; this._init.apply(this,arguments); /** * Render the LogReader immediately upon instantiation. If set to false, * you must call myLogReader.render() to generate the UI. * * @property autoRender * @type {Boolean} * @default true */ if (this.autoRender !== false) { this.render(); } } ///////////////////////////////////////////////////////////////////////////// // // Static member variables // ///////////////////////////////////////////////////////////////////////////// YAHOO.lang.augmentObject(LogReader, { /** * Internal class member to index multiple LogReader instances. * * @property _memberName * @static * @type Number * @default 0 * @private */ _index : 0, /** * Node template for the log entries * @property ENTRY_TEMPLATE * @static * @type {HTMLElement} * @default pre element with class yui-log-entry */ ENTRY_TEMPLATE : (function () { return make('pre',{ className: 'yui-log-entry' }); })(), /** * Template used for innerHTML of verbose entry output. * @property VERBOSE_TEMPLATE * @static * @default "<p><span class='{category}'>{label}</span>{totalTime}ms (+{elapsedTime}) {localTime}:</p><p>{sourceAndDetail}</p><p>{message}</p>" */ VERBOSE_TEMPLATE : "

          {label} {totalTime}ms (+{elapsedTime}) {localTime}:

          {sourceAndDetail}

          {message}

          ", /** * Template used for innerHTML of compact entry output. * @property BASIC_TEMPLATE * @static * @default "<p><span class='{category}'>{label}</span>{totalTime}ms (+{elapsedTime}) {localTime}: {sourceAndDetail}: {message}</p>" */ BASIC_TEMPLATE : "

          {label} {totalTime}ms (+{elapsedTime}) {localTime}: {sourceAndDetail}: {message}

          " }); ///////////////////////////////////////////////////////////////////////////// // // Public member variables // ///////////////////////////////////////////////////////////////////////////// LogReader.prototype = { /** * Whether or not LogReader is enabled to output log messages. * * @property logReaderEnabled * @type Boolean * @default true */ logReaderEnabled : true, /** * Public member to access CSS width of the LogReader container. * * @property width * @type String */ width : null, /** * Public member to access CSS height of the LogReader container. * * @property height * @type String */ height : null, /** * Public member to access CSS top position of the LogReader container. * * @property top * @type String */ top : null, /** * Public member to access CSS left position of the LogReader container. * * @property left * @type String */ left : null, /** * Public member to access CSS right position of the LogReader container. * * @property right * @type String */ right : null, /** * Public member to access CSS bottom position of the LogReader container. * * @property bottom * @type String */ bottom : null, /** * Public member to access CSS font size of the LogReader container. * * @property fontSize * @type String */ fontSize : null, /** * Whether or not the footer UI is enabled for the LogReader. * * @property footerEnabled * @type Boolean * @default true */ footerEnabled : true, /** * Whether or not output is verbose (more readable). Setting to true will make * output more compact (less readable). * * @property verboseOutput * @type Boolean * @default true */ verboseOutput : true, /** * Custom output format for log messages. Defaults to null, which falls * back to verboseOutput param deciding between LogReader.VERBOSE_TEMPLATE * and LogReader.BASIC_TEMPLATE. Use bracketed place holders to mark where * message info should go. Available place holder names include: *
            *
          • category
          • *
          • label
          • *
          • sourceAndDetail
          • *
          • message
          • *
          • localTime
          • *
          • elapsedTime
          • *
          • totalTime
          • *
          * * @property entryFormat * @type String * @default null */ entryFormat : null, /** * Whether or not newest message is printed on top. * * @property newestOnTop * @type Boolean */ newestOnTop : true, /** * Output timeout buffer in milliseconds. * * @property outputBuffer * @type Number * @default 100 */ outputBuffer : 100, /** * Maximum number of messages a LogReader console will display. * * @property thresholdMax * @type Number * @default 500 */ thresholdMax : 500, /** * When a LogReader console reaches its thresholdMax, it will clear out messages * and print out the latest thresholdMin number of messages. * * @property thresholdMin * @type Number * @default 100 */ thresholdMin : 100, /** * True when LogReader is in a collapsed state, false otherwise. * * @property isCollapsed * @type Boolean * @default false */ isCollapsed : false, /** * True when LogReader is in a paused state, false otherwise. * * @property isPaused * @type Boolean * @default false */ isPaused : false, /** * Enables draggable LogReader if DragDrop Utility is present. * * @property draggable * @type Boolean * @default true */ draggable : true, ///////////////////////////////////////////////////////////////////////////// // // Public methods // ///////////////////////////////////////////////////////////////////////////// /** * Public accessor to the unique name of the LogReader instance. * * @method toString * @return {String} Unique name of the LogReader instance. */ toString : function() { return "LogReader instance" + this._sName; }, /** * Pauses output of log messages. While paused, log messages are not lost, but * get saved to a buffer and then output upon resume of LogReader. * * @method pause */ pause : function() { this.isPaused = true; this._timeout = null; this.logReaderEnabled = false; if (this._btnPause) { this._btnPause.value = "Resume"; } }, /** * Resumes output of log messages, including outputting any log messages that * have been saved to buffer while paused. * * @method resume */ resume : function() { this.isPaused = false; this.logReaderEnabled = true; this._printBuffer(); if (this._btnPause) { this._btnPause.value = "Pause"; } }, /** * Adds the UI to the DOM, attaches event listeners, and bootstraps initial * UI state. * * @method render */ render : function () { if (this.rendered) { return; } this._initContainerEl(); this._initHeaderEl(); this._initConsoleEl(); this._initFooterEl(); this._initCategories(); this._initSources(); this._initDragDrop(); // Subscribe to Logger custom events Logger.newLogEvent.subscribe(this._onNewLog, this); Logger.logResetEvent.subscribe(this._onReset, this); Logger.categoryCreateEvent.subscribe(this._onCategoryCreate, this); Logger.sourceCreateEvent.subscribe(this._onSourceCreate, this); this.rendered = true; this._filterLogs(); }, /** * Removes the UI from the DOM entirely and detaches all event listeners. * Implementers should note that Logger will still accumulate messages. * * @method destroy */ destroy : function () { Event.purgeElement(this._elContainer,true); this._elContainer.innerHTML = ''; this._elContainer.parentNode.removeChild(this._elContainer); this.rendered = false; }, /** * Hides UI of LogReader. Logging functionality is not disrupted. * * @method hide */ hide : function() { this._elContainer.style.display = "none"; }, /** * Shows UI of LogReader. Logging functionality is not disrupted. * * @method show */ show : function() { this._elContainer.style.display = "block"; }, /** * Collapses UI of LogReader. Logging functionality is not disrupted. * * @method collapse */ collapse : function() { this._elConsole.style.display = "none"; if(this._elFt) { this._elFt.style.display = "none"; } this._btnCollapse.value = "Expand"; this.isCollapsed = true; }, /** * Expands UI of LogReader. Logging functionality is not disrupted. * * @method expand */ expand : function() { this._elConsole.style.display = "block"; if(this._elFt) { this._elFt.style.display = "block"; } this._btnCollapse.value = "Collapse"; this.isCollapsed = false; }, /** * Returns related checkbox element for given filter (i.e., category or source). * * @method getCheckbox * @param {String} Category or source name. * @return {Array} Array of all filter checkboxes. */ getCheckbox : function(filter) { return this._filterCheckboxes[filter]; }, /** * Returns array of enabled categories. * * @method getCategories * @return {String[]} Array of enabled categories. */ getCategories : function() { return this._categoryFilters; }, /** * Shows log messages associated with given category. * * @method showCategory * @param {String} Category name. */ showCategory : function(sCategory) { var filtersArray = this._categoryFilters; // Don't do anything if category is already enabled // Use Array.indexOf if available... if(filtersArray.indexOf) { if(filtersArray.indexOf(sCategory) > -1) { return; } } // ...or do it the old-fashioned way else { for(var i=0; i -1) { return; } } // ...or do it the old-fashioned way else { for(var i=0; i", and "&" to HTML entities. * * @method html2Text * @param sHtml {String} String to convert. * @private */ html2Text : function(sHtml) { if(sHtml) { sHtml += ""; return sHtml.replace(/&/g, "&"). replace(//g, ">"); } return ""; }, ///////////////////////////////////////////////////////////////////////////// // // Private member variables // ///////////////////////////////////////////////////////////////////////////// /** * Name of LogReader instance. * * @property _sName * @type String * @private */ _sName : null, //TODO: remove /** * A class member shared by all LogReaders if a container needs to be * created during instantiation. Will be null if a container element never needs to * be created on the fly, such as when the implementer passes in their own element. * * @property _elDefaultContainer * @type HTMLElement * @private */ //YAHOO.widget.LogReader._elDefaultContainer = null; /** * Buffer of log message objects for batch output. * * @property _buffer * @type Object[] * @private */ _buffer : null, /** * Number of log messages output to console. * * @property _consoleMsgCount * @type Number * @default 0 * @private */ _consoleMsgCount : 0, /** * Date of last output log message. * * @property _lastTime * @type Date * @private */ _lastTime : null, /** * Batched output timeout ID. * * @property _timeout * @type Number * @private */ _timeout : null, /** * Hash of filters and their related checkbox elements. * * @property _filterCheckboxes * @type Object * @private */ _filterCheckboxes : null, /** * Array of filters for log message categories. * * @property _categoryFilters * @type String[] * @private */ _categoryFilters : null, /** * Array of filters for log message sources. * * @property _sourceFilters * @type String[] * @private */ _sourceFilters : null, /** * LogReader container element. * * @property _elContainer * @type HTMLElement * @private */ _elContainer : null, /** * LogReader header element. * * @property _elHd * @type HTMLElement * @private */ _elHd : null, /** * LogReader collapse element. * * @property _elCollapse * @type HTMLElement * @private */ _elCollapse : null, /** * LogReader collapse button element. * * @property _btnCollapse * @type HTMLElement * @private */ _btnCollapse : null, /** * LogReader title header element. * * @property _title * @type HTMLElement * @private */ _title : null, /** * LogReader console element. * * @property _elConsole * @type HTMLElement * @private */ _elConsole : null, /** * LogReader footer element. * * @property _elFt * @type HTMLElement * @private */ _elFt : null, /** * LogReader buttons container element. * * @property _elBtns * @type HTMLElement * @private */ _elBtns : null, /** * Container element for LogReader category filter checkboxes. * * @property _elCategoryFilters * @type HTMLElement * @private */ _elCategoryFilters : null, /** * Container element for LogReader source filter checkboxes. * * @property _elSourceFilters * @type HTMLElement * @private */ _elSourceFilters : null, /** * LogReader pause button element. * * @property _btnPause * @type HTMLElement * @private */ _btnPause : null, /** * Clear button element. * * @property _btnClear * @type HTMLElement * @private */ _btnClear : null, ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Initializes the instance's message buffer, start time, etc * * @method _init * @param container {String|HTMLElement} (optional) the render target * @param config {Object} (optional) instance configuration * @protected */ _init : function (container, config) { // Internal vars this._buffer = []; // output buffer this._filterCheckboxes = {}; // pointers to checkboxes this._lastTime = Logger.getStartTime(); // timestamp of last log message to console // Parse config vars here if (config && (config.constructor == Object)) { for(var param in config) { if (config.hasOwnProperty(param)) { this[param] = config[param]; } } } this._elContainer = Dom.get(container); YAHOO.log("LogReader initialized", null, this.toString()); }, /** * Initializes the primary container element. * * @method _initContainerEl * @private */ _initContainerEl : function() { // Default the container if unset or not a div if(!this._elContainer || !/div$/i.test(this._elContainer.tagName)) { this._elContainer = d.body.insertBefore(make("div"),d.body.firstChild); // Only position absolutely if an in-DOM element is not supplied Dom.addClass(this._elContainer,"yui-log-container"); } Dom.addClass(this._elContainer,"yui-log"); // If implementer has provided container values, trust and set those var style = this._elContainer.style, styleProps = ['width','right','top','fontSize'], prop,i; for (i = styleProps.length - 1; i >= 0; --i) { prop = styleProps[i]; if (this[prop]){ style[prop] = this[prop]; } } if(this.left) { style.left = this.left; style.right = "auto"; } if(this.bottom) { style.bottom = this.bottom; style.top = "auto"; } // Opera needs a little prodding to reflow sometimes if (YAHOO.env.ua.opera) { d.body.style += ''; } }, /** * Initializes the header element. * * @method _initHeaderEl * @private */ _initHeaderEl : function() { // Destroy header if present if(this._elHd) { // Unhook DOM events Event.purgeElement(this._elHd, true); // Remove DOM elements this._elHd.innerHTML = ""; } // Create header // TODO: refactor this into an innerHTML this._elHd = make("div",{ className: "yui-log-hd" }); Dom.generateId(this._elHd, 'yui-log-hd' + this._sName); this._elCollapse = make("div",{ className: 'yui-log-btns' }); this._btnCollapse = make("input",{ type: 'button', className: 'yui-log-button', value: 'Collapse' }); Event.on(this._btnCollapse,'click',this._onClickCollapseBtn,this); this._title = make("h4",{ innerHTML : "Logger Console" }); this._elCollapse.appendChild(this._btnCollapse); this._elHd.appendChild(this._elCollapse); this._elHd.appendChild(this._title); this._elContainer.appendChild(this._elHd); }, /** * Initializes the console element. * * @method _initConsoleEl * @private */ _initConsoleEl : function() { // Destroy console if(this._elConsole) { // Unhook DOM events Event.purgeElement(this._elConsole, true); // Remove DOM elements this._elConsole.innerHTML = ""; } // Ceate console this._elConsole = make("div", { className: "yui-log-bd" }); // If implementer has provided console, trust and set those if(this.height) { this._elConsole.style.height = this.height; } this._elContainer.appendChild(this._elConsole); }, /** * Initializes the footer element. * * @method _initFooterEl * @private */ _initFooterEl : function() { // Don't create footer elements if footer is disabled if(this.footerEnabled) { // Destroy console if(this._elFt) { // Unhook DOM events Event.purgeElement(this._elFt, true); // Remove DOM elements this._elFt.innerHTML = ""; } // TODO: use innerHTML this._elFt = make("div",{ className: "yui-log-ft" }); this._elBtns = make("div", { className: "yui-log-btns" }); this._btnPause = make("input", { type: "button", className: "yui-log-button", value: "Pause" }); Event.on(this._btnPause,'click',this._onClickPauseBtn,this); this._btnClear = make("input", { type: "button", className: "yui-log-button", value: "Clear" }); Event.on(this._btnClear,'click',this._onClickClearBtn,this); this._elCategoryFilters = make("div", { className: "yui-log-categoryfilters" }); this._elSourceFilters = make("div", { className: "yui-log-sourcefilters" }); this._elBtns.appendChild(this._btnPause); this._elBtns.appendChild(this._btnClear); this._elFt.appendChild(this._elBtns); this._elFt.appendChild(this._elCategoryFilters); this._elFt.appendChild(this._elSourceFilters); this._elContainer.appendChild(this._elFt); } }, /** * Initializes Drag and Drop on the header element. * * @method _initDragDrop * @private */ _initDragDrop : function() { // If Drag and Drop utility is available... // ...and draggable is true... // ...then make the header draggable if(u.DD && this.draggable && this._elHd) { var ylog_dd = new u.DD(this._elContainer); ylog_dd.setHandleElId(this._elHd.id); //TODO: use class name this._elHd.style.cursor = "move"; } }, /** * Initializes category filters. * * @method _initCategories * @private */ _initCategories : function() { // Initialize category filters this._categoryFilters = []; var aInitialCategories = Logger.categories; for(var j=0; j < aInitialCategories.length; j++) { var sCategory = aInitialCategories[j]; // Add category to the internal array of filters this._categoryFilters.push(sCategory); // Add checkbox element if UI is enabled if(this._elCategoryFilters) { this._createCategoryCheckbox(sCategory); } } }, /** * Initializes source filters. * * @method _initSources * @private */ _initSources : function() { // Initialize source filters this._sourceFilters = []; var aInitialSources = Logger.sources; for(var j=0; j < aInitialSources.length; j++) { var sSource = aInitialSources[j]; // Add source to the internal array of filters this._sourceFilters.push(sSource); // Add checkbox element if UI is enabled if(this._elSourceFilters) { this._createSourceCheckbox(sSource); } } }, /** * Creates the UI for a category filter in the LogReader footer element. * * @method _createCategoryCheckbox * @param sCategory {String} Category name. * @private */ _createCategoryCheckbox : function(sCategory) { if(this._elFt) { var filter = make("span",{ className: "yui-log-filtergrp" }), checkid = Dom.generateId(null, "yui-log-filter-" + sCategory + this._sName), check = make("input", { id: checkid, className: "yui-log-filter-" + sCategory, type: "checkbox", category: sCategory }), label = make("label", { htmlFor: checkid, className: sCategory, innerHTML: sCategory }); // Subscribe to the click event Event.on(check,'click',this._onCheckCategory,this); this._filterCheckboxes[sCategory] = check; // Append el at the end so IE 5.5 can set "type" attribute // and THEN set checked property filter.appendChild(check); filter.appendChild(label); this._elCategoryFilters.appendChild(filter); check.checked = true; } }, /** * Creates a checkbox in the LogReader footer element to filter by source. * * @method _createSourceCheckbox * @param sSource {String} Source name. * @private */ _createSourceCheckbox : function(sSource) { if(this._elFt) { var filter = make("span",{ className: "yui-log-filtergrp" }), checkid = Dom.generateId(null, "yui-log-filter-" + sSource + this._sName), check = make("input", { id: checkid, className: "yui-log-filter-" + sSource, type: "checkbox", source: sSource }), label = make("label", { htmlFor: checkid, className: sSource, innerHTML: sSource }); // Subscribe to the click event Event.on(check,'click',this._onCheckSource,this); this._filterCheckboxes[sSource] = check; // Append el at the end so IE 5.5 can set "type" attribute // and THEN set checked property filter.appendChild(check); filter.appendChild(label); this._elSourceFilters.appendChild(filter); check.checked = true; } }, /** * Reprints all log messages in the stack through filters. * * @method _filterLogs * @private */ _filterLogs : function() { // Reprint stack with new filters if (this._elConsole !== null) { this.clearConsole(); this._printToConsole(Logger.getStack()); } }, /** * Sends buffer of log messages to output and clears buffer. * * @method _printBuffer * @private */ _printBuffer : function() { this._timeout = null; if(this._elConsole !== null) { var thresholdMax = this.thresholdMax; thresholdMax = (thresholdMax && !isNaN(thresholdMax)) ? thresholdMax : 500; if(this._consoleMsgCount < thresholdMax) { var entries = []; for (var i=0; i this.thresholdMax)) { thresholdMin = 0; } entriesStartIndex = (entriesLen > thresholdMin) ? (entriesLen - thresholdMin) : 0; // Iterate through all log entries for(i=entriesStartIndex; i0){c=g.substring(0,d);a=g.substring(d,g.length);}else{c=g;}if(this._isNewSource(c)){this._createNewSource(c);}}var h=new Date();var j=new YAHOO.widget.LogMsg({msg:b,time:h,category:f,source:c,sourceDetail:a});var i=this._stack;var e=this.maxStackEntries;if(e&&!isNaN(e)&&(i.length>=e)){i.shift();}i.push(j);this.newLogEvent.fire(j);if(this._browserConsoleEnabled){this._printToBrowserConsole(j);}return true;}else{return false;}};YAHOO.widget.Logger.reset=function(){this._stack=[];this._startTime=new Date().getTime();this.loggerEnabled=true;this.log("Logger reset");this.logResetEvent.fire();};YAHOO.widget.Logger.getStack=function(){return this._stack;};YAHOO.widget.Logger.getStartTime=function(){return this._startTime;};YAHOO.widget.Logger.disableBrowserConsole=function(){YAHOO.log("Logger output to the function console.log() has been disabled.");this._browserConsoleEnabled=false;};YAHOO.widget.Logger.enableBrowserConsole=function(){this._browserConsoleEnabled=true;YAHOO.log("Logger output to the function console.log() has been enabled.");};YAHOO.widget.Logger.handleWindowErrors=function(){if(!YAHOO.widget.Logger._windowErrorsHandled){if(window.error){YAHOO.widget.Logger._origOnWindowError=window.onerror;}window.onerror=YAHOO.widget.Logger._onWindowError;YAHOO.widget.Logger._windowErrorsHandled=true;YAHOO.log("Logger handling of window.onerror has been enabled.");}else{YAHOO.log("Logger handling of window.onerror had already been enabled.");}};YAHOO.widget.Logger.unhandleWindowErrors=function(){if(YAHOO.widget.Logger._windowErrorsHandled){if(YAHOO.widget.Logger._origOnWindowError){window.onerror=YAHOO.widget.Logger._origOnWindowError;YAHOO.widget.Logger._origOnWindowError=null;}else{window.onerror=null;}YAHOO.widget.Logger._windowErrorsHandled=false;YAHOO.log("Logger handling of window.onerror has been disabled.");}else{YAHOO.log("Logger handling of window.onerror had already been disabled.");}};YAHOO.widget.Logger.categoryCreateEvent=new YAHOO.util.CustomEvent("categoryCreate",this,true);YAHOO.widget.Logger.sourceCreateEvent=new YAHOO.util.CustomEvent("sourceCreate",this,true);YAHOO.widget.Logger.newLogEvent=new YAHOO.util.CustomEvent("newLog",this,true);YAHOO.widget.Logger.logResetEvent=new YAHOO.util.CustomEvent("logReset",this,true);YAHOO.widget.Logger._createNewCategory=function(a){this.categories.push(a);this.categoryCreateEvent.fire(a);};YAHOO.widget.Logger._isNewCategory=function(b){for(var a=0;a{label} {totalTime}ms (+{elapsedTime}) {localTime}:

          {sourceAndDetail}

          {message}

          ",BASIC_TEMPLATE:"

          {label} {totalTime}ms (+{elapsedTime}) {localTime}: {sourceAndDetail}: {message}

          "});g.prototype={logReaderEnabled:true,width:null,height:null,top:null,left:null,right:null,bottom:null,fontSize:null,footerEnabled:true,verboseOutput:true,entryFormat:null,newestOnTop:true,outputBuffer:100,thresholdMax:500,thresholdMin:100,isCollapsed:false,isPaused:false,draggable:true,toString:function(){return"LogReader instance"+this._sName;},pause:function(){this.isPaused=true;this._timeout=null; this.logReaderEnabled=false;if(this._btnPause){this._btnPause.value="Resume";}},resume:function(){this.isPaused=false;this.logReaderEnabled=true;this._printBuffer();if(this._btnPause){this._btnPause.value="Pause";}},render:function(){if(this.rendered){return;}this._initContainerEl();this._initHeaderEl();this._initConsoleEl();this._initFooterEl();this._initCategories();this._initSources();this._initDragDrop();c.newLogEvent.subscribe(this._onNewLog,this);c.logResetEvent.subscribe(this._onReset,this);c.categoryCreateEvent.subscribe(this._onCategoryCreate,this);c.sourceCreateEvent.subscribe(this._onSourceCreate,this);this.rendered=true;this._filterLogs();},destroy:function(){a.purgeElement(this._elContainer,true);this._elContainer.innerHTML="";this._elContainer.parentNode.removeChild(this._elContainer);this.rendered=false;},hide:function(){this._elContainer.style.display="none";},show:function(){this._elContainer.style.display="block";},collapse:function(){this._elConsole.style.display="none";if(this._elFt){this._elFt.style.display="none";}this._btnCollapse.value="Expand";this.isCollapsed=true;},expand:function(){this._elConsole.style.display="block";if(this._elFt){this._elFt.style.display="block";}this._btnCollapse.value="Collapse";this.isCollapsed=false;},getCheckbox:function(d){return this._filterCheckboxes[d];},getCategories:function(){return this._categoryFilters;},showCategory:function(j){var l=this._categoryFilters;if(l.indexOf){if(l.indexOf(j)>-1){return;}}else{for(var d=0;d-1){return;}}else{for(var j=0;j/g,">");}return"";},_sName:null,_buffer:null,_consoleMsgCount:0,_lastTime:null,_timeout:null,_filterCheckboxes:null,_categoryFilters:null,_sourceFilters:null,_elContainer:null,_elHd:null,_elCollapse:null,_btnCollapse:null,_title:null,_elConsole:null,_elFt:null,_elBtns:null,_elCategoryFilters:null,_elSourceFilters:null,_btnPause:null,_btnClear:null,_init:function(d,i){this._buffer=[];this._filterCheckboxes={};this._lastTime=c.getStartTime();if(i&&(i.constructor==Object)){for(var j in i){if(i.hasOwnProperty(j)){this[j]=i[j];}}}this._elContainer=f.get(d);YAHOO.log("LogReader initialized",null,this.toString());},_initContainerEl:function(){if(!this._elContainer||!/div$/i.test(this._elContainer.tagName)){this._elContainer=h.body.insertBefore(b("div"),h.body.firstChild);f.addClass(this._elContainer,"yui-log-container");}f.addClass(this._elContainer,"yui-log");var k=this._elContainer.style,d=["width","right","top","fontSize"],l,j;for(j=d.length-1;j>=0;--j){l=d[j];if(this[l]){k[l]=this[l];}}if(this.left){k.left=this.left;k.right="auto";}if(this.bottom){k.bottom=this.bottom;k.top="auto";}if(YAHOO.env.ua.opera){h.body.style+="";}},_initHeaderEl:function(){if(this._elHd){a.purgeElement(this._elHd,true);this._elHd.innerHTML="";}this._elHd=b("div",{className:"yui-log-hd"});f.generateId(this._elHd,"yui-log-hd"+this._sName);this._elCollapse=b("div",{className:"yui-log-btns"});this._btnCollapse=b("input",{type:"button",className:"yui-log-button",value:"Collapse"});a.on(this._btnCollapse,"click",this._onClickCollapseBtn,this);this._title=b("h4",{innerHTML:"Logger Console"});this._elCollapse.appendChild(this._btnCollapse);this._elHd.appendChild(this._elCollapse);this._elHd.appendChild(this._title);this._elContainer.appendChild(this._elHd);},_initConsoleEl:function(){if(this._elConsole){a.purgeElement(this._elConsole,true);this._elConsole.innerHTML="";}this._elConsole=b("div",{className:"yui-log-bd"});if(this.height){this._elConsole.style.height=this.height;}this._elContainer.appendChild(this._elConsole);},_initFooterEl:function(){if(this.footerEnabled){if(this._elFt){a.purgeElement(this._elFt,true);this._elFt.innerHTML="";}this._elFt=b("div",{className:"yui-log-ft"});this._elBtns=b("div",{className:"yui-log-btns"});this._btnPause=b("input",{type:"button",className:"yui-log-button",value:"Pause"});a.on(this._btnPause,"click",this._onClickPauseBtn,this);this._btnClear=b("input",{type:"button",className:"yui-log-button",value:"Clear"});a.on(this._btnClear,"click",this._onClickClearBtn,this);this._elCategoryFilters=b("div",{className:"yui-log-categoryfilters"});this._elSourceFilters=b("div",{className:"yui-log-sourcefilters"});this._elBtns.appendChild(this._btnPause);this._elBtns.appendChild(this._btnClear); this._elFt.appendChild(this._elBtns);this._elFt.appendChild(this._elCategoryFilters);this._elFt.appendChild(this._elSourceFilters);this._elContainer.appendChild(this._elFt);}},_initDragDrop:function(){if(e.DD&&this.draggable&&this._elHd){var d=new e.DD(this._elContainer);d.setHandleElId(this._elHd.id);this._elHd.style.cursor="move";}},_initCategories:function(){this._categoryFilters=[];var k=c.categories;for(var d=0;dthis.thresholdMax)){z=0;}t=(k>z)?(k-z):0;for(q=t;qCreates a rich custom Toolbar Button. Primarily used with the Rich Text Editor's Toolbar

          * @class ToolbarButtonAdvanced * @namespace YAHOO.widget * @requires yahoo, dom, element, event, container_core, menu, button * * Provides a toolbar button based on the button and menu widgets. * @constructor * @class ToolbarButtonAdvanced * @param {String/HTMLElement} el The element to turn into a button. * @param {Object} attrs Object liternal containing configuration parameters. */ if (YAHOO.widget.Button) { YAHOO.widget.ToolbarButtonAdvanced = YAHOO.widget.Button; /** * @property buttonType * @private * @description Tells if the Button is a Rich Button or a Simple Button */ YAHOO.widget.ToolbarButtonAdvanced.prototype.buttonType = 'rich'; /** * @method checkValue * @param {String} value The value of the option that we want to mark as selected * @description Select an option by value */ YAHOO.widget.ToolbarButtonAdvanced.prototype.checkValue = function(value) { var _menuItems = this.getMenu().getItems(); if (_menuItems.length === 0) { this.getMenu()._onBeforeShow(); _menuItems = this.getMenu().getItems(); } for (var i = 0; i < _menuItems.length; i++) { _menuItems[i].cfg.setProperty('checked', false); if (_menuItems[i].value == value) { _menuItems[i].cfg.setProperty('checked', true); } } }; } else { YAHOO.widget.ToolbarButtonAdvanced = function() {}; } /** * @description

          Creates a basic custom Toolbar Button. Primarily used with the Rich Text Editor's Toolbar

          Provides a toolbar button based on the button and menu widgets, <select> elements are used in place of menu's.

          * @class ToolbarButton * @namespace YAHOO.widget * @requires yahoo, dom, element, event * @extends YAHOO.util.Element * * * @constructor * @param {String/HTMLElement} el The element to turn into a button. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.ToolbarButton = function(el, attrs) { if (Lang.isObject(arguments[0]) && !Dom.get(el).nodeType) { attrs = el; } var local_attrs = (attrs || {}); var oConfig = { element: null, attributes: local_attrs }; if (!oConfig.attributes.type) { oConfig.attributes.type = 'push'; } oConfig.element = document.createElement('span'); oConfig.element.setAttribute('unselectable', 'on'); oConfig.element.className = 'yui-button yui-' + oConfig.attributes.type + '-button'; oConfig.element.innerHTML = 'LABEL'; oConfig.element.firstChild.firstChild.tabIndex = '-1'; oConfig.attributes.id = (oConfig.attributes.id || Dom.generateId()); oConfig.element.id = oConfig.attributes.id; YAHOO.widget.ToolbarButton.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.ToolbarButton, YAHOO.util.Element, { /** * @property buttonType * @private * @description Tells if the Button is a Rich Button or a Simple Button */ buttonType: 'normal', /** * @method _handleMouseOver * @private * @description Adds classes to the button elements on mouseover (hover) */ _handleMouseOver: function() { if (!this.get('disabled')) { this.addClass('yui-button-hover'); this.addClass('yui-' + this.get('type') + '-button-hover'); } }, /** * @method _handleMouseOut * @private * @description Removes classes from the button elements on mouseout (hover) */ _handleMouseOut: function() { this.removeClass('yui-button-hover'); this.removeClass('yui-' + this.get('type') + '-button-hover'); }, /** * @method checkValue * @param {String} value The value of the option that we want to mark as selected * @description Select an option by value */ checkValue: function(value) { if (this.get('type') == 'menu') { var opts = this._button.options; if (opts) { for (var i = 0; i < opts.length; i++) { if (opts[i].value == value) { opts.selectedIndex = i; } } } } }, /** * @method init * @description The ToolbarButton class's initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.widget.ToolbarButton.superclass.init.call(this, p_oElement, p_oAttributes); this.on('mouseover', this._handleMouseOver, this, true); this.on('mouseout', this._handleMouseOut, this, true); this.on('click', function(ev) { Event.stopEvent(ev); return false; }, this, true); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the toolbar. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the toolbar. */ initAttributes: function(attr) { YAHOO.widget.ToolbarButton.superclass.initAttributes.call(this, attr); /** * @attribute value * @description The value of the button * @type String */ this.setAttributeConfig('value', { value: attr.value }); /** * @attribute menu * @description The menu attribute, see YAHOO.widget.Button * @type Object */ this.setAttributeConfig('menu', { value: attr.menu || false }); /** * @attribute type * @description The type of button to create: push, menu, color, select, spin * @type String */ this.setAttributeConfig('type', { value: attr.type, writeOnce: true, method: function(type) { var el, opt; if (!this._button) { this._button = this.get('element').getElementsByTagName('a')[0]; } switch (type) { case 'select': case 'menu': el = document.createElement('select'); el.id = this.get('id'); var menu = this.get('menu'); for (var i = 0; i < menu.length; i++) { opt = document.createElement('option'); opt.innerHTML = menu[i].text; opt.value = menu[i].value; if (menu[i].checked) { opt.selected = true; } el.appendChild(opt); } this._button.parentNode.replaceChild(el, this._button); Event.on(el, 'change', this._handleSelect, this, true); this._button = el; break; } } }); /** * @attribute disabled * @description Set the button into a disabled state * @type String */ this.setAttributeConfig('disabled', { value: attr.disabled || false, method: function(disabled) { if (disabled) { this.addClass('yui-button-disabled'); this.addClass('yui-' + this.get('type') + '-button-disabled'); } else { this.removeClass('yui-button-disabled'); this.removeClass('yui-' + this.get('type') + '-button-disabled'); } if ((this.get('type') == 'menu') || (this.get('type') == 'select')) { this._button.disabled = disabled; } } }); /** * @attribute label * @description The text label for the button * @type String */ this.setAttributeConfig('label', { value: attr.label, method: function(label) { if (!this._button) { this._button = this.get('element').getElementsByTagName('a')[0]; } if (this.get('type') == 'push') { this._button.innerHTML = label; } } }); /** * @attribute title * @description The title of the button * @type String */ this.setAttributeConfig('title', { value: attr.title }); /** * @config container * @description The container that the button is rendered to, handled by Toolbar * @type String */ this.setAttributeConfig('container', { value: null, writeOnce: true, method: function(cont) { this.appendTo(cont); } }); }, /** * @private * @method _handleSelect * @description The event fired when a change event gets fired on a select element * @param {Event} ev The change event. */ _handleSelect: function(ev) { var tar = Event.getTarget(ev); var value = tar.options[tar.selectedIndex].value; this.fireEvent('change', {type: 'change', value: value }); }, /** * @method getMenu * @description A stub function to mimic YAHOO.widget.Button's getMenu method */ getMenu: function() { return this.get('menu'); }, /** * @method destroy * @description Destroy the button */ destroy: function() { Event.purgeElement(this.get('element'), true); this.get('element').parentNode.removeChild(this.get('element')); //Brutal Object Destroy for (var i in this) { if (Lang.hasOwnProperty(this, i)) { this[i] = null; } } }, /** * @method fireEvent * @description Overridden fireEvent method to prevent DOM events from firing if the button is disabled. */ fireEvent: function(p_sType, p_aArgs) { // Disabled buttons should not respond to DOM events if (this.DOM_EVENTS[p_sType] && this.get('disabled')) { Event.stopEvent(p_aArgs); return; } YAHOO.widget.ToolbarButton.superclass.fireEvent.call(this, p_sType, p_aArgs); }, /** * @method toString * @description Returns a string representing the toolbar. * @return {String} */ toString: function() { return 'ToolbarButton (' + this.get('id') + ')'; } }); })(); /** * @module editor * @description

          Creates a rich Toolbar widget based on Button. Primarily used with the Rich Text Editor

          * @namespace YAHOO.widget * @requires yahoo, dom, element, event, toolbarbutton * @optional container_core, dragdrop */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang; var getButton = function(id) { var button = id; if (Lang.isString(id)) { button = this.getButtonById(id); } if (Lang.isNumber(id)) { button = this.getButtonByIndex(id); } if ((!(button instanceof YAHOO.widget.ToolbarButton)) && (!(button instanceof YAHOO.widget.ToolbarButtonAdvanced))) { button = this.getButtonByValue(id); } if ((button instanceof YAHOO.widget.ToolbarButton) || (button instanceof YAHOO.widget.ToolbarButtonAdvanced)) { return button; } return false; }; /** * Provides a rich toolbar widget based on the button and menu widgets * @constructor * @class Toolbar * @extends YAHOO.util.Element * @param {String/HTMLElement} el The element to turn into a toolbar. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.Toolbar = function(el, attrs) { if (Lang.isObject(arguments[0]) && !Dom.get(el).nodeType) { attrs = el; } var local_attrs = {}; if (attrs) { Lang.augmentObject(local_attrs, attrs); //Break the config reference } var oConfig = { element: null, attributes: local_attrs }; if (Lang.isString(el) && Dom.get(el)) { oConfig.element = Dom.get(el); } else if (Lang.isObject(el) && Dom.get(el) && Dom.get(el).nodeType) { oConfig.element = Dom.get(el); } if (!oConfig.element) { oConfig.element = document.createElement('DIV'); oConfig.element.id = Dom.generateId(); if (local_attrs.container && Dom.get(local_attrs.container)) { Dom.get(local_attrs.container).appendChild(oConfig.element); } } if (!oConfig.element.id) { oConfig.element.id = ((Lang.isString(el)) ? el : Dom.generateId()); } var fs = document.createElement('fieldset'); var lg = document.createElement('legend'); lg.innerHTML = 'Toolbar'; fs.appendChild(lg); var cont = document.createElement('DIV'); oConfig.attributes.cont = cont; Dom.addClass(cont, 'yui-toolbar-subcont'); fs.appendChild(cont); oConfig.element.appendChild(fs); oConfig.element.tabIndex = -1; oConfig.attributes.element = oConfig.element; oConfig.attributes.id = oConfig.element.id; this._configuredButtons = []; YAHOO.widget.Toolbar.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.Toolbar, YAHOO.util.Element, { /** * @protected * @property _configuredButtons * @type Array */ _configuredButtons: null, /** * @method _addMenuClasses * @private * @description This method is called from Menu's renderEvent to add a few more classes to the menu items * @param {String} ev The event that fired. * @param {Array} na Array of event information. * @param {Object} o Button config object. */ _addMenuClasses: function(ev, na, o) { Dom.addClass(this.element, 'yui-toolbar-' + o.get('value') + '-menu'); if (Dom.hasClass(o._button.parentNode.parentNode, 'yui-toolbar-select')) { Dom.addClass(this.element, 'yui-toolbar-select-menu'); } var items = this.getItems(); for (var i = 0; i < items.length; i++) { Dom.addClass(items[i].element, 'yui-toolbar-' + o.get('value') + '-' + ((items[i].value) ? items[i].value.replace(/ /g, '-').toLowerCase() : items[i]._oText.nodeValue.replace(/ /g, '-').toLowerCase())); Dom.addClass(items[i].element, 'yui-toolbar-' + o.get('value') + '-' + ((items[i].value) ? items[i].value.replace(/ /g, '-') : items[i]._oText.nodeValue.replace(/ /g, '-'))); } }, /** * @property buttonType * @description The default button to use * @type Object */ buttonType: YAHOO.widget.ToolbarButton, /** * @property dd * @description The DragDrop instance associated with the Toolbar * @type Object */ dd: null, /** * @property _colorData * @description Object reference containing colors hex and text values. * @type Object */ _colorData: { /* {{{ _colorData */ '#111111': 'Obsidian', '#2D2D2D': 'Dark Gray', '#434343': 'Shale', '#5B5B5B': 'Flint', '#737373': 'Gray', '#8B8B8B': 'Concrete', '#A2A2A2': 'Gray', '#B9B9B9': 'Titanium', '#000000': 'Black', '#D0D0D0': 'Light Gray', '#E6E6E6': 'Silver', '#FFFFFF': 'White', '#BFBF00': 'Pumpkin', '#FFFF00': 'Yellow', '#FFFF40': 'Banana', '#FFFF80': 'Pale Yellow', '#FFFFBF': 'Butter', '#525330': 'Raw Siena', '#898A49': 'Mildew', '#AEA945': 'Olive', '#7F7F00': 'Paprika', '#C3BE71': 'Earth', '#E0DCAA': 'Khaki', '#FCFAE1': 'Cream', '#60BF00': 'Cactus', '#80FF00': 'Chartreuse', '#A0FF40': 'Green', '#C0FF80': 'Pale Lime', '#DFFFBF': 'Light Mint', '#3B5738': 'Green', '#668F5A': 'Lime Gray', '#7F9757': 'Yellow', '#407F00': 'Clover', '#8A9B55': 'Pistachio', '#B7C296': 'Light Jade', '#E6EBD5': 'Breakwater', '#00BF00': 'Spring Frost', '#00FF80': 'Pastel Green', '#40FFA0': 'Light Emerald', '#80FFC0': 'Sea Foam', '#BFFFDF': 'Sea Mist', '#033D21': 'Dark Forrest', '#438059': 'Moss', '#7FA37C': 'Medium Green', '#007F40': 'Pine', '#8DAE94': 'Yellow Gray Green', '#ACC6B5': 'Aqua Lung', '#DDEBE2': 'Sea Vapor', '#00BFBF': 'Fog', '#00FFFF': 'Cyan', '#40FFFF': 'Turquoise Blue', '#80FFFF': 'Light Aqua', '#BFFFFF': 'Pale Cyan', '#033D3D': 'Dark Teal', '#347D7E': 'Gray Turquoise', '#609A9F': 'Green Blue', '#007F7F': 'Seaweed', '#96BDC4': 'Green Gray', '#B5D1D7': 'Soapstone', '#E2F1F4': 'Light Turquoise', '#0060BF': 'Summer Sky', '#0080FF': 'Sky Blue', '#40A0FF': 'Electric Blue', '#80C0FF': 'Light Azure', '#BFDFFF': 'Ice Blue', '#1B2C48': 'Navy', '#385376': 'Biscay', '#57708F': 'Dusty Blue', '#00407F': 'Sea Blue', '#7792AC': 'Sky Blue Gray', '#A8BED1': 'Morning Sky', '#DEEBF6': 'Vapor', '#0000BF': 'Deep Blue', '#0000FF': 'Blue', '#4040FF': 'Cerulean Blue', '#8080FF': 'Evening Blue', '#BFBFFF': 'Light Blue', '#212143': 'Deep Indigo', '#373E68': 'Sea Blue', '#444F75': 'Night Blue', '#00007F': 'Indigo Blue', '#585E82': 'Dockside', '#8687A4': 'Blue Gray', '#D2D1E1': 'Light Blue Gray', '#6000BF': 'Neon Violet', '#8000FF': 'Blue Violet', '#A040FF': 'Violet Purple', '#C080FF': 'Violet Dusk', '#DFBFFF': 'Pale Lavender', '#302449': 'Cool Shale', '#54466F': 'Dark Indigo', '#655A7F': 'Dark Violet', '#40007F': 'Violet', '#726284': 'Smoky Violet', '#9E8FA9': 'Slate Gray', '#DCD1DF': 'Violet White', '#BF00BF': 'Royal Violet', '#FF00FF': 'Fuchsia', '#FF40FF': 'Magenta', '#FF80FF': 'Orchid', '#FFBFFF': 'Pale Magenta', '#4A234A': 'Dark Purple', '#794A72': 'Medium Purple', '#936386': 'Cool Granite', '#7F007F': 'Purple', '#9D7292': 'Purple Moon', '#C0A0B6': 'Pale Purple', '#ECDAE5': 'Pink Cloud', '#BF005F': 'Hot Pink', '#FF007F': 'Deep Pink', '#FF409F': 'Grape', '#FF80BF': 'Electric Pink', '#FFBFDF': 'Pink', '#451528': 'Purple Red', '#823857': 'Purple Dino', '#A94A76': 'Purple Gray', '#7F003F': 'Rose', '#BC6F95': 'Antique Mauve', '#D8A5BB': 'Cool Marble', '#F7DDE9': 'Pink Granite', '#C00000': 'Apple', '#FF0000': 'Fire Truck', '#FF4040': 'Pale Red', '#FF8080': 'Salmon', '#FFC0C0': 'Warm Pink', '#441415': 'Sepia', '#82393C': 'Rust', '#AA4D4E': 'Brick', '#800000': 'Brick Red', '#BC6E6E': 'Mauve', '#D8A3A4': 'Shrimp Pink', '#F8DDDD': 'Shell Pink', '#BF5F00': 'Dark Orange', '#FF7F00': 'Orange', '#FF9F40': 'Grapefruit', '#FFBF80': 'Canteloupe', '#FFDFBF': 'Wax', '#482C1B': 'Dark Brick', '#855A40': 'Dirt', '#B27C51': 'Tan', '#7F3F00': 'Nutmeg', '#C49B71': 'Mustard', '#E1C4A8': 'Pale Tan', '#FDEEE0': 'Marble' /* }}} */ }, /** * @property _colorPicker * @description The HTML Element containing the colorPicker * @type HTMLElement */ _colorPicker: null, /** * @property STR_COLLAPSE * @description String for Toolbar Collapse Button * @type String */ STR_COLLAPSE: 'Collapse Toolbar', /** * @property STR_EXPAND * @description String for Toolbar Collapse Button - Expand * @type String */ STR_EXPAND: 'Expand Toolbar', /** * @property STR_SPIN_LABEL * @description String for spinbutton dynamic label. Note the {VALUE} will be replaced with YAHOO.lang.substitute * @type String */ STR_SPIN_LABEL: 'Spin Button with value {VALUE}. Use Control Shift Up Arrow and Control Shift Down arrow keys to increase or decrease the value.', /** * @property STR_SPIN_UP * @description String for spinbutton up * @type String */ STR_SPIN_UP: 'Click to increase the value of this input', /** * @property STR_SPIN_DOWN * @description String for spinbutton down * @type String */ STR_SPIN_DOWN: 'Click to decrease the value of this input', /** * @property _titlebar * @description Object reference to the titlebar * @type HTMLElement */ _titlebar: null, /** * @property browser * @description Standard browser detection * @type Object */ browser: YAHOO.env.ua, /** * @protected * @property _buttonList * @description Internal property list of current buttons in the toolbar * @type Array */ _buttonList: null, /** * @protected * @property _buttonGroupList * @description Internal property list of current button groups in the toolbar * @type Array */ _buttonGroupList: null, /** * @protected * @property _sep * @description Internal reference to the separator HTML Element for cloning * @type HTMLElement */ _sep: null, /** * @protected * @property _sepCount * @description Internal refernce for counting separators, so we can give them a useful class name for styling * @type Number */ _sepCount: null, /** * @protected * @property draghandle * @type HTMLElement */ _dragHandle: null, /** * @protected * @property _toolbarConfigs * @type Object */ _toolbarConfigs: { renderer: true }, /** * @protected * @property CLASS_CONTAINER * @description Default CSS class to apply to the toolbar container element * @type String */ CLASS_CONTAINER: 'yui-toolbar-container', /** * @protected * @property CLASS_DRAGHANDLE * @description Default CSS class to apply to the toolbar's drag handle element * @type String */ CLASS_DRAGHANDLE: 'yui-toolbar-draghandle', /** * @protected * @property CLASS_SEPARATOR * @description Default CSS class to apply to all separators in the toolbar * @type String */ CLASS_SEPARATOR: 'yui-toolbar-separator', /** * @protected * @property CLASS_DISABLED * @description Default CSS class to apply when the toolbar is disabled * @type String */ CLASS_DISABLED: 'yui-toolbar-disabled', /** * @protected * @property CLASS_PREFIX * @description Default prefix for dynamically created class names * @type String */ CLASS_PREFIX: 'yui-toolbar', /** * @method init * @description The Toolbar class's initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.widget.Toolbar.superclass.init.call(this, p_oElement, p_oAttributes); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the toolbar. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the toolbar. */ initAttributes: function(attr) { YAHOO.widget.Toolbar.superclass.initAttributes.call(this, attr); this.addClass(this.CLASS_CONTAINER); /** * @attribute buttonType * @description The buttonType to use (advanced or basic) * @type String */ this.setAttributeConfig('buttonType', { value: attr.buttonType || 'basic', writeOnce: true, validator: function(type) { switch (type) { case 'advanced': case 'basic': return true; } return false; }, method: function(type) { if (type == 'advanced') { if (YAHOO.widget.Button) { this.buttonType = YAHOO.widget.ToolbarButtonAdvanced; } else { this.buttonType = YAHOO.widget.ToolbarButton; } } else { this.buttonType = YAHOO.widget.ToolbarButton; } } }); /** * @attribute buttons * @description Object specifying the buttons to include in the toolbar * Example: *
                      * {
                      *   { id: 'b3', type: 'button', label: 'Underline', value: 'underline' },
                      *   { type: 'separator' },
                      *   { id: 'b4', type: 'menu', label: 'Align', value: 'align',
                      *       menu: [
                      *           { text: "Left", value: 'alignleft' },
                      *           { text: "Center", value: 'aligncenter' },
                      *           { text: "Right", value: 'alignright' }
                      *       ]
                      *   }
                      * }
                      * 
          * @type Array */ this.setAttributeConfig('buttons', { value: [], writeOnce: true, method: function(data) { var i, button, buttons, len, b; for (i in data) { if (Lang.hasOwnProperty(data, i)) { if (data[i].type == 'separator') { this.addSeparator(); } else if (data[i].group !== undefined) { buttons = this.addButtonGroup(data[i]); if (buttons) { len = buttons.length; for(b = 0; b < len; b++) { if (buttons[b]) { this._configuredButtons[this._configuredButtons.length] = buttons[b].id; } } } } else { button = this.addButton(data[i]); if (button) { this._configuredButtons[this._configuredButtons.length] = button.id; } } } } } }); /** * @attribute disabled * @description Boolean indicating if the toolbar should be disabled. It will also disable the draggable attribute if it is on. * @default false * @type Boolean */ this.setAttributeConfig('disabled', { value: false, method: function(disabled) { if (this.get('disabled') === disabled) { return false; } if (disabled) { this.addClass(this.CLASS_DISABLED); this.set('draggable', false); this.disableAllButtons(); } else { this.removeClass(this.CLASS_DISABLED); if (this._configs.draggable._initialConfig.value) { //Draggable by default, set it back this.set('draggable', true); } this.resetAllButtons(); } } }); /** * @config cont * @description The container for the toolbar. * @type HTMLElement */ this.setAttributeConfig('cont', { value: attr.cont, readOnly: true }); /** * @attribute grouplabels * @description Boolean indicating if the toolbar should show the group label's text string. * @default true * @type Boolean */ this.setAttributeConfig('grouplabels', { value: ((attr.grouplabels === false) ? false : true), method: function(grouplabels) { if (grouplabels) { Dom.removeClass(this.get('cont'), (this.CLASS_PREFIX + '-nogrouplabels')); } else { Dom.addClass(this.get('cont'), (this.CLASS_PREFIX + '-nogrouplabels')); } } }); /** * @attribute titlebar * @description Boolean indicating if the toolbar should have a titlebar. If * passed a string, it will use that as the titlebar text * @default false * @type Boolean or String */ this.setAttributeConfig('titlebar', { value: false, method: function(titlebar) { if (titlebar) { if (this._titlebar && this._titlebar.parentNode) { this._titlebar.parentNode.removeChild(this._titlebar); } this._titlebar = document.createElement('DIV'); this._titlebar.tabIndex = '-1'; Event.on(this._titlebar, 'focus', function() { this._handleFocus(); }, this, true); Dom.addClass(this._titlebar, this.CLASS_PREFIX + '-titlebar'); if (Lang.isString(titlebar)) { var h2 = document.createElement('h2'); h2.tabIndex = '-1'; h2.innerHTML = '' + titlebar + ''; this._titlebar.appendChild(h2); Event.on(h2.firstChild, 'click', function(ev) { Event.stopEvent(ev); }); Event.on([h2, h2.firstChild], 'focus', function() { this._handleFocus(); }, this, true); } if (this.get('firstChild')) { this.insertBefore(this._titlebar, this.get('firstChild')); } else { this.appendChild(this._titlebar); } if (this.get('collapse')) { this.set('collapse', true); } } else if (this._titlebar) { if (this._titlebar && this._titlebar.parentNode) { this._titlebar.parentNode.removeChild(this._titlebar); } } } }); /** * @attribute collapse * @description Boolean indicating if the the titlebar should have a collapse button. * The collapse button will not remove the toolbar, it will minimize it to the titlebar * @default false * @type Boolean */ this.setAttributeConfig('collapse', { value: false, method: function(collapse) { if (this._titlebar) { var collapseEl = null; var el = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapse) { if (el.length > 0) { //There is already a collapse button return true; } collapseEl = document.createElement('SPAN'); collapseEl.innerHTML = 'X'; collapseEl.title = this.STR_COLLAPSE; Dom.addClass(collapseEl, 'collapse'); this._titlebar.appendChild(collapseEl); Event.addListener(collapseEl, 'click', function() { if (Dom.hasClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed')) { this.collapse(false); //Expand Toolbar } else { this.collapse(); //Collapse Toolbar } }, this, true); } else { collapseEl = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapseEl[0]) { if (Dom.hasClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed')) { //We are closed, reopen the titlebar.. this.collapse(false); //Expand Toolbar } collapseEl[0].parentNode.removeChild(collapseEl[0]); } } } } }); /** * @attribute draggable * @description Boolean indicating if the toolbar should be draggable. * @default false * @type Boolean */ this.setAttributeConfig('draggable', { value: (attr.draggable || false), method: function(draggable) { if (draggable && !this.get('titlebar')) { if (!this._dragHandle) { this._dragHandle = document.createElement('SPAN'); this._dragHandle.innerHTML = '|'; this._dragHandle.setAttribute('title', 'Click to drag the toolbar'); this._dragHandle.id = this.get('id') + '_draghandle'; Dom.addClass(this._dragHandle, this.CLASS_DRAGHANDLE); if (this.get('cont').hasChildNodes()) { this.get('cont').insertBefore(this._dragHandle, this.get('cont').firstChild); } else { this.get('cont').appendChild(this._dragHandle); } this.dd = new YAHOO.util.DD(this.get('id')); this.dd.setHandleElId(this._dragHandle.id); } } else { if (this._dragHandle) { this._dragHandle.parentNode.removeChild(this._dragHandle); this._dragHandle = null; this.dd = null; } } if (this._titlebar) { if (draggable) { this.dd = new YAHOO.util.DD(this.get('id')); this.dd.setHandleElId(this._titlebar); Dom.addClass(this._titlebar, 'draggable'); } else { Dom.removeClass(this._titlebar, 'draggable'); if (this.dd) { this.dd.unreg(); this.dd = null; } } } }, validator: function(value) { var ret = true; if (!YAHOO.util.DD) { ret = false; } return ret; } }); }, /** * @method addButtonGroup * @description Add a new button group to the toolbar. (uses addButton) * @param {Object} oGroup Object literal reference to the Groups Config (contains an array of button configs as well as the group label) */ addButtonGroup: function(oGroup) { if (!this.get('element')) { this._queue[this._queue.length] = ['addButtonGroup', arguments]; return false; } if (!this.hasClass(this.CLASS_PREFIX + '-grouped')) { this.addClass(this.CLASS_PREFIX + '-grouped'); } var div = document.createElement('DIV'); Dom.addClass(div, this.CLASS_PREFIX + '-group'); Dom.addClass(div, this.CLASS_PREFIX + '-group-' + oGroup.group); if (oGroup.label) { var label = document.createElement('h3'); label.innerHTML = oGroup.label; div.appendChild(label); } if (!this.get('grouplabels')) { Dom.addClass(this.get('cont'), this.CLASS_PREFIX, '-nogrouplabels'); } this.get('cont').appendChild(div); //For accessibility, let's put all of the group buttons in an Unordered List var ul = document.createElement('ul'); div.appendChild(ul); if (!this._buttonGroupList) { this._buttonGroupList = {}; } this._buttonGroupList[oGroup.group] = ul; //An array of the button ids added to this group //This is used for destruction later... var addedButtons = [], button; for (var i = 0; i < oGroup.buttons.length; i++) { var li = document.createElement('li'); li.className = this.CLASS_PREFIX + '-groupitem'; ul.appendChild(li); if ((oGroup.buttons[i].type !== undefined) && oGroup.buttons[i].type == 'separator') { this.addSeparator(li); } else { oGroup.buttons[i].container = li; button = this.addButton(oGroup.buttons[i]); if (button) { addedButtons[addedButtons.length] = button.id; } } } return addedButtons; }, /** * @method addButtonToGroup * @description Add a new button to a toolbar group. Buttons supported: * push, split, menu, select, color, spin * @param {Object} oButton Object literal reference to the Button's Config * @param {String} group The Group identifier passed into the initial config * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addButtonToGroup: function(oButton, group, after) { var groupCont = this._buttonGroupList[group], li = document.createElement('li'); li.className = this.CLASS_PREFIX + '-groupitem'; oButton.container = li; this.addButton(oButton, after); groupCont.appendChild(li); }, /** * @method addButton * @description Add a new button to the toolbar. Buttons supported: * push, split, menu, select, color, spin * @param {Object} oButton Object literal reference to the Button's Config * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addButton: function(oButton, after) { if (!this.get('element')) { this._queue[this._queue.length] = ['addButton', arguments]; return false; } if (!this._buttonList) { this._buttonList = []; } if (!oButton.container) { oButton.container = this.get('cont'); } if ((oButton.type == 'menu') || (oButton.type == 'split') || (oButton.type == 'select')) { if (Lang.isArray(oButton.menu)) { for (var i in oButton.menu) { if (Lang.hasOwnProperty(oButton.menu, i)) { var funcObject = { fn: function(ev, x, oMenu) { if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ((oMenu.value) ? oMenu.value : oMenu._oText.nodeValue); }, scope: this }; oButton.menu[i].onclick = funcObject; } } } } var _oButton = {}, skip = false; for (var o in oButton) { if (Lang.hasOwnProperty(oButton, o)) { if (!this._toolbarConfigs[o]) { _oButton[o] = oButton[o]; } } } if (oButton.type == 'select') { _oButton.type = 'menu'; } if (oButton.type == 'spin') { _oButton.type = 'push'; } if (_oButton.type == 'color') { if (YAHOO.widget.Overlay) { _oButton = this._makeColorButton(_oButton); } else { skip = true; } } if (_oButton.menu) { if ((YAHOO.widget.Overlay) && (oButton.menu instanceof YAHOO.widget.Overlay)) { oButton.menu.showEvent.subscribe(function() { this._button = _oButton; }); } else { for (var m = 0; m < _oButton.menu.length; m++) { if (!_oButton.menu[m].value) { _oButton.menu[m].value = _oButton.menu[m].text; } } if (this.browser.webkit) { _oButton.focusmenu = false; } } } if (skip) { oButton = false; } else { //Add to .get('buttons') manually this._configs.buttons.value[this._configs.buttons.value.length] = oButton; var tmp = new this.buttonType(_oButton); tmp.get('element').tabIndex = '-1'; tmp.get('element').setAttribute('role', 'button'); tmp._selected = true; if (this.get('disabled')) { //Toolbar is disabled, disable the new button too! tmp.set('disabled', true); } if (!oButton.id) { oButton.id = tmp.get('id'); } if (after) { var el = tmp.get('element'); var nextSib = null; if (after.get) { nextSib = after.get('element').nextSibling; } else if (after.nextSibling) { nextSib = after.nextSibling; } if (nextSib) { nextSib.parentNode.insertBefore(el, nextSib); } } tmp.addClass(this.CLASS_PREFIX + '-' + tmp.get('value')); var icon = document.createElement('span'); icon.className = this.CLASS_PREFIX + '-icon'; tmp.get('element').insertBefore(icon, tmp.get('firstChild')); if (tmp._button.tagName.toLowerCase() == 'button') { tmp.get('element').setAttribute('unselectable', 'on'); //Replace the Button HTML Element with an a href if it exists var a = document.createElement('a'); a.innerHTML = tmp._button.innerHTML; a.href = '#'; a.tabIndex = '-1'; Event.on(a, 'click', function(ev) { Event.stopEvent(ev); }); tmp._button.parentNode.replaceChild(a, tmp._button); tmp._button = a; } if (oButton.type == 'select') { if (tmp._button.tagName.toLowerCase() == 'select') { icon.parentNode.removeChild(icon); var iel = tmp._button, parEl = tmp.get('element'); parEl.parentNode.replaceChild(iel, parEl); //The 'element' value is currently the orphaned element //In order for "destroy" to execute we need to get('element') to reference the correct node. //I'm not sure if there is a direct approach to setting this value. tmp._configs.element.value = iel; } else { //Don't put a class on it if it's a real select element tmp.addClass(this.CLASS_PREFIX + '-select'); } } if (oButton.type == 'spin') { if (!Lang.isArray(oButton.range)) { oButton.range = [ 10, 100 ]; } this._makeSpinButton(tmp, oButton); } tmp.get('element').setAttribute('title', tmp.get('label')); if (oButton.type != 'spin') { if ((YAHOO.widget.Overlay) && (_oButton.menu instanceof YAHOO.widget.Overlay)) { var showPicker = function(ev) { var exec = true; if (ev.keyCode && (ev.keyCode == 9)) { exec = false; } if (exec) { if (this._colorPicker) { this._colorPicker._button = oButton.value; } var menuEL = tmp.getMenu().element; if (Dom.getStyle(menuEL, 'visibility') == 'hidden') { tmp.getMenu().show(); } else { tmp.getMenu().hide(); } } YAHOO.util.Event.stopEvent(ev); }; tmp.on('mousedown', showPicker, oButton, this); tmp.on('keydown', showPicker, oButton, this); } else if ((oButton.type != 'menu') && (oButton.type != 'select')) { tmp.on('keypress', this._buttonClick, oButton, this); tmp.on('mousedown', function(ev) { YAHOO.util.Event.stopEvent(ev); this._buttonClick(ev, oButton); }, oButton, this); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }); } else { //Stop the mousedown event so we can trap the selection in the editor! tmp.on('mousedown', function(ev) { //YAHOO.util.Event.stopEvent(ev); }); tmp.on('click', function(ev) { //YAHOO.util.Event.stopEvent(ev); }); tmp.on('change', function(ev) { if (!ev.target) { if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ev.value; this._buttonClick(ev, oButton); } }, this, true); var self = this; //Hijack the mousedown event in the menu and make it fire a button click.. tmp.on('appendTo', function() { var tmp = this; if (tmp.getMenu() && tmp.getMenu().mouseDownEvent) { tmp.getMenu().mouseDownEvent.subscribe(function(ev, args) { var oMenu = args[1]; YAHOO.util.Event.stopEvent(args[0]); tmp._onMenuClick(args[0], tmp); if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ((oMenu.value) ? oMenu.value : oMenu._oText.nodeValue); self._buttonClick.call(self, args[1], oButton); tmp._hideMenu(); return false; }); tmp.getMenu().clickEvent.subscribe(function(ev, args) { YAHOO.util.Event.stopEvent(args[0]); }); tmp.getMenu().mouseUpEvent.subscribe(function(ev, args) { YAHOO.util.Event.stopEvent(args[0]); }); } }); } } else { //Stop the mousedown event so we can trap the selection in the editor! tmp.on('mousedown', function(ev) { YAHOO.util.Event.stopEvent(ev); }); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }); } if (this.browser.ie) { /* //Add a couple of new events for IE tmp.DOM_EVENTS.focusin = true; tmp.DOM_EVENTS.focusout = true; //Stop them so we don't loose focus in the Editor tmp.on('focusin', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); tmp.on('focusout', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); */ } if (this.browser.webkit) { //This will keep the document from gaining focus and the editor from loosing it.. //Forcefully remove the focus calls in button! tmp.hasFocus = function() { return true; }; } this._buttonList[this._buttonList.length] = tmp; if ((oButton.type == 'menu') || (oButton.type == 'split') || (oButton.type == 'select')) { if (Lang.isArray(oButton.menu)) { var menu = tmp.getMenu(); if (menu && menu.renderEvent) { menu.renderEvent.subscribe(this._addMenuClasses, tmp); if (oButton.renderer) { menu.renderEvent.subscribe(oButton.renderer, tmp); } } } } } return oButton; }, /** * @method addSeparator * @description Add a new button separator to the toolbar. * @param {HTMLElement} cont Optional HTML element to insert this button into. * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addSeparator: function(cont, after) { if (!this.get('element')) { this._queue[this._queue.length] = ['addSeparator', arguments]; return false; } var sepCont = ((cont) ? cont : this.get('cont')); if (!this.get('element')) { this._queue[this._queue.length] = ['addSeparator', arguments]; return false; } if (this._sepCount === null) { this._sepCount = 0; } if (!this._sep) { this._sep = document.createElement('SPAN'); Dom.addClass(this._sep, this.CLASS_SEPARATOR); this._sep.innerHTML = '|'; } var _sep = this._sep.cloneNode(true); this._sepCount++; Dom.addClass(_sep, this.CLASS_SEPARATOR + '-' + this._sepCount); if (after) { var nextSib = null; if (after.get) { nextSib = after.get('element').nextSibling; } else if (after.nextSibling) { nextSib = after.nextSibling; } else { nextSib = after; } if (nextSib) { if (nextSib == after) { nextSib.parentNode.appendChild(_sep); } else { nextSib.parentNode.insertBefore(_sep, nextSib); } } } else { sepCont.appendChild(_sep); } return _sep; }, /** * @method _createColorPicker * @private * @description Creates the core DOM reference to the color picker menu item. * @param {String} id the id of the toolbar to prefix this DOM container with. */ _createColorPicker: function(id) { if (Dom.get(id + '_colors')) { Dom.get(id + '_colors').parentNode.removeChild(Dom.get(id + '_colors')); } var picker = document.createElement('div'); picker.className = 'yui-toolbar-colors'; picker.id = id + '_colors'; picker.style.display = 'none'; Event.on(window, 'load', function() { document.body.appendChild(picker); }, this, true); this._colorPicker = picker; var html = ''; for (var i in this._colorData) { if (Lang.hasOwnProperty(this._colorData, i)) { html += '' + i.replace('#', '') + ''; } } html += 'X'; window.setTimeout(function() { picker.innerHTML = html; }, 0); Event.on(picker, 'mouseover', function(ev) { var picker = this._colorPicker; var em = picker.getElementsByTagName('em')[0]; var strong = picker.getElementsByTagName('strong')[0]; var tar = Event.getTarget(ev); if (tar.tagName.toLowerCase() == 'a') { em.style.backgroundColor = tar.style.backgroundColor; strong.innerHTML = this._colorData['#' + tar.innerHTML] + '
          ' + tar.innerHTML; } }, this, true); Event.on(picker, 'focus', function(ev) { Event.stopEvent(ev); }); Event.on(picker, 'click', function(ev) { Event.stopEvent(ev); }); Event.on(picker, 'mousedown', function(ev) { Event.stopEvent(ev); var tar = Event.getTarget(ev); if (tar.tagName.toLowerCase() == 'a') { var retVal = this.fireEvent('colorPickerClicked', { type: 'colorPickerClicked', target: this, button: this._colorPicker._button, color: tar.innerHTML, colorName: this._colorData['#' + tar.innerHTML] } ); if (retVal !== false) { var info = { color: tar.innerHTML, colorName: this._colorData['#' + tar.innerHTML], value: this._colorPicker._button }; this.fireEvent('buttonClick', { type: 'buttonClick', target: this.get('element'), button: info }); } this.getButtonByValue(this._colorPicker._button).getMenu().hide(); } }, this, true); }, /** * @method _resetColorPicker * @private * @description Clears the currently selected color or mouseover color in the color picker. */ _resetColorPicker: function() { var em = this._colorPicker.getElementsByTagName('em')[0]; var strong = this._colorPicker.getElementsByTagName('strong')[0]; em.style.backgroundColor = 'transparent'; strong.innerHTML = ''; }, /** * @method _makeColorButton * @private * @description Called to turn a "color" button into a menu button with an Overlay for the menu. * @param {Object} _oButton YAHOO.widget.ToolbarButton reference */ _makeColorButton: function(_oButton) { if (!this._colorPicker) { this._createColorPicker(this.get('id')); } _oButton.type = 'color'; _oButton.menu = new YAHOO.widget.Overlay(this.get('id') + '_' + _oButton.value + '_menu', { visible: false, position: 'absolute', iframe: true }); _oButton.menu.setBody(''); _oButton.menu.render(this.get('cont')); Dom.addClass(_oButton.menu.element, 'yui-button-menu'); Dom.addClass(_oButton.menu.element, 'yui-color-button-menu'); _oButton.menu.beforeShowEvent.subscribe(function() { _oButton.menu.cfg.setProperty('zindex', 5); //Re Adjust the overlays zIndex.. not sure why. _oButton.menu.cfg.setProperty('context', [this.getButtonById(_oButton.id).get('element'), 'tl', 'bl']); //Re Adjust the overlay.. not sure why. //Move the DOM reference of the color picker to the Overlay that we are about to show. this._resetColorPicker(); var _p = this._colorPicker; if (_p.parentNode) { _p.parentNode.removeChild(_p); } _oButton.menu.setBody(''); _oButton.menu.appendToBody(_p); this._colorPicker.style.display = 'block'; }, this, true); return _oButton; }, /** * @private * @method _makeSpinButton * @description Create a button similar to an OS Spin button.. It has an up/down arrow combo to scroll through a range of int values. * @param {Object} _button YAHOO.widget.ToolbarButton reference * @param {Object} oButton Object literal containing the buttons initial config */ _makeSpinButton: function(_button, oButton) { _button.addClass(this.CLASS_PREFIX + '-spinbutton'); var self = this, _par = _button._button.parentNode.parentNode, //parentNode of Button Element for appending child range = oButton.range, _b1 = document.createElement('a'), _b2 = document.createElement('a'); _b1.href = '#'; _b2.href = '#'; _b1.tabIndex = '-1'; _b2.tabIndex = '-1'; //Setup the up and down arrows _b1.className = 'up'; _b1.title = this.STR_SPIN_UP; _b1.innerHTML = this.STR_SPIN_UP; _b2.className = 'down'; _b2.title = this.STR_SPIN_DOWN; _b2.innerHTML = this.STR_SPIN_DOWN; //Append them to the container _par.appendChild(_b1); _par.appendChild(_b2); var label = YAHOO.lang.substitute(this.STR_SPIN_LABEL, { VALUE: _button.get('label') }); _button.set('title', label); var cleanVal = function(value) { value = ((value < range[0]) ? range[0] : value); value = ((value > range[1]) ? range[1] : value); return value; }; var br = this.browser; var tbar = false; var strLabel = this.STR_SPIN_LABEL; if (this._titlebar && this._titlebar.firstChild) { tbar = this._titlebar.firstChild; } var _intUp = function(ev) { YAHOO.util.Event.stopEvent(ev); if (!_button.get('disabled') && (ev.keyCode != 9)) { var value = parseInt(_button.get('label'), 10); value++; value = cleanVal(value); _button.set('label', ''+value); var label = YAHOO.lang.substitute(strLabel, { VALUE: _button.get('label') }); _button.set('title', label); if (!br.webkit && tbar) { //tbar.focus(); //We do this for accessibility, on the re-focus of the element, a screen reader will re-read the title that was just changed //_button.focus(); } self._buttonClick(ev, oButton); } }; var _intDown = function(ev) { YAHOO.util.Event.stopEvent(ev); if (!_button.get('disabled') && (ev.keyCode != 9)) { var value = parseInt(_button.get('label'), 10); value--; value = cleanVal(value); _button.set('label', ''+value); var label = YAHOO.lang.substitute(strLabel, { VALUE: _button.get('label') }); _button.set('title', label); if (!br.webkit && tbar) { //tbar.focus(); //We do this for accessibility, on the re-focus of the element, a screen reader will re-read the title that was just changed //_button.focus(); } self._buttonClick(ev, oButton); } }; var _intKeyUp = function(ev) { if (ev.keyCode == 38) { _intUp(ev); } else if (ev.keyCode == 40) { _intDown(ev); } else if (ev.keyCode == 107 && ev.shiftKey) { //Plus Key _intUp(ev); } else if (ev.keyCode == 109 && ev.shiftKey) { //Minus Key _intDown(ev); } }; //Handle arrow keys.. _button.on('keydown', _intKeyUp, this, true); //Listen for the click on the up button and act on it //Listen for the click on the down button and act on it Event.on(_b1, 'mousedown',function(ev) { Event.stopEvent(ev); }, this, true); Event.on(_b2, 'mousedown', function(ev) { Event.stopEvent(ev); }, this, true); Event.on(_b1, 'click', _intUp, this, true); Event.on(_b2, 'click', _intDown, this, true); }, /** * @protected * @method _buttonClick * @description Click handler for all buttons in the toolbar. * @param {String} ev The event that was passed in. * @param {Object} info Object literal of information about the button that was clicked. */ _buttonClick: function(ev, info) { var doEvent = true; if (ev && ev.type == 'keypress') { if (ev.keyCode == 9) { doEvent = false; } else if ((ev.keyCode === 13) || (ev.keyCode === 0) || (ev.keyCode === 32)) { } else { doEvent = false; } } if (doEvent) { var fireNextEvent = true, retValue = false; info.isSelected = this.isSelected(info.id); if (info.value) { retValue = this.fireEvent(info.value + 'Click', { type: info.value + 'Click', target: this.get('element'), button: info }); if (retValue === false) { fireNextEvent = false; } } if (info.menucmd && fireNextEvent) { retValue = this.fireEvent(info.menucmd + 'Click', { type: info.menucmd + 'Click', target: this.get('element'), button: info }); if (retValue === false) { fireNextEvent = false; } } if (fireNextEvent) { this.fireEvent('buttonClick', { type: 'buttonClick', target: this.get('element'), button: info }); } if (info.type == 'select') { var button = this.getButtonById(info.id); if (button.buttonType == 'rich') { var txt = info.value; for (var i = 0; i < info.menu.length; i++) { if (info.menu[i].value == info.value) { txt = info.menu[i].text; break; } } button.set('label', '' + txt + ''); var _items = button.getMenu().getItems(); for (var m = 0; m < _items.length; m++) { if (_items[m].value.toLowerCase() == info.value.toLowerCase()) { _items[m].cfg.setProperty('checked', true); } else { _items[m].cfg.setProperty('checked', false); } } } } if (ev) { Event.stopEvent(ev); } } }, /** * @private * @property _keyNav * @description Flag to determine if the arrow nav listeners have been attached * @type Boolean */ _keyNav: null, /** * @private * @property _navCounter * @description Internal counter for walking the buttons in the toolbar with the arrow keys * @type Number */ _navCounter: null, /** * @private * @method _navigateButtons * @description Handles the navigation/focus of toolbar buttons with the Arrow Keys * @param {Event} ev The Key Event */ _navigateButtons: function(ev) { switch (ev.keyCode) { case 37: case 39: if (ev.keyCode == 37) { this._navCounter--; } else { this._navCounter++; } if (this._navCounter > (this._buttonList.length - 1)) { this._navCounter = 0; } if (this._navCounter < 0) { this._navCounter = (this._buttonList.length - 1); } if (this._buttonList[this._navCounter]) { var el = this._buttonList[this._navCounter].get('element'); if (this.browser.ie) { el = this._buttonList[this._navCounter].get('element').getElementsByTagName('a')[0]; } if (this._buttonList[this._navCounter].get('disabled')) { this._navigateButtons(ev); } else { el.focus(); } } break; } }, /** * @private * @method _handleFocus * @description Sets up the listeners for the arrow key navigation */ _handleFocus: function() { if (!this._keyNav) { var ev = 'keypress'; if (this.browser.ie) { ev = 'keydown'; } Event.on(this.get('element'), ev, this._navigateButtons, this, true); this._keyNav = true; this._navCounter = -1; } }, /** * @method getButtonById * @description Gets a button instance from the toolbar by is Dom id. * @param {String} id The Dom id to query for. * @return {YAHOO.widget.ToolbarButton} */ getButtonById: function(id) { var len = this._buttonList.length; for (var i = 0; i < len; i++) { if (this._buttonList[i] && this._buttonList[i].get('id') == id) { return this._buttonList[i]; } } return false; }, /** * @method getButtonByValue * @description Gets a button instance or a menuitem instance from the toolbar by it's value. * @param {String} value The button value to query for. * @return {YAHOO.widget.ToolbarButton or YAHOO.widget.MenuItem} */ getButtonByValue: function(value) { var _buttons = this.get('buttons'); if (!_buttons) { return false; } var len = _buttons.length; for (var i = 0; i < len; i++) { if (_buttons[i].group !== undefined) { for (var m = 0; m < _buttons[i].buttons.length; m++) { if ((_buttons[i].buttons[m].value == value) || (_buttons[i].buttons[m].menucmd == value)) { return this.getButtonById(_buttons[i].buttons[m].id); } if (_buttons[i].buttons[m].menu) { //Menu Button, loop through the values for (var s = 0; s < _buttons[i].buttons[m].menu.length; s++) { if (_buttons[i].buttons[m].menu[s].value == value) { return this.getButtonById(_buttons[i].buttons[m].id); } } } } } else { if ((_buttons[i].value == value) || (_buttons[i].menucmd == value)) { return this.getButtonById(_buttons[i].id); } if (_buttons[i].menu) { //Menu Button, loop through the values for (var j = 0; j < _buttons[i].menu.length; j++) { if (_buttons[i].menu[j].value == value) { return this.getButtonById(_buttons[i].id); } } } } } return false; }, /** * @method getButtonByIndex * @description Gets a button instance from the toolbar by is index in _buttonList. * @param {Number} index The index of the button in _buttonList. * @return {YAHOO.widget.ToolbarButton} */ getButtonByIndex: function(index) { if (this._buttonList[index]) { return this._buttonList[index]; } else { return false; } }, /** * @method getButtons * @description Returns an array of buttons in the current toolbar * @return {Array} */ getButtons: function() { return this._buttonList; }, /** * @method disableButton * @description Disables a button in the toolbar. * @param {String/Number} id Disable a button by it's id, index or value. * @return {Boolean} */ disableButton: function(id) { var button = getButton.call(this, id); if (button) { button.set('disabled', true); } else { return false; } }, /** * @method enableButton * @description Enables a button in the toolbar. * @param {String/Number} id Enable a button by it's id, index or value. * @return {Boolean} */ enableButton: function(id) { if (this.get('disabled')) { return false; } var button = getButton.call(this, id); if (button) { if (button.get('disabled')) { button.set('disabled', false); } } else { return false; } }, /** * @method isSelected * @description Tells if a button is selected or not. * @param {String/Number} id A button by it's id, index or value. * @return {Boolean} */ isSelected: function(id) { var button = getButton.call(this, id); if (button) { return button._selected; } return false; }, /** * @method selectButton * @description Selects a button in the toolbar. * @param {String/Number} id Select a button by it's id, index or value. * @param {String} value If this is a Menu Button, check this item in the menu * @return {Boolean} */ selectButton: function(id, value) { var button = getButton.call(this, id); if (button) { button.addClass('yui-button-selected'); button.addClass('yui-button-' + button.get('value') + '-selected'); button._selected = true; if (value) { if (button.buttonType == 'rich') { var _items = button.getMenu().getItems(); for (var m = 0; m < _items.length; m++) { if (_items[m].value == value) { _items[m].cfg.setProperty('checked', true); button.set('label', '' + _items[m]._oText.nodeValue + ''); } else { _items[m].cfg.setProperty('checked', false); } } } } } else { return false; } }, /** * @method deselectButton * @description Deselects a button in the toolbar. * @param {String/Number} id Deselect a button by it's id, index or value. * @return {Boolean} */ deselectButton: function(id) { var button = getButton.call(this, id); if (button) { button.removeClass('yui-button-selected'); button.removeClass('yui-button-' + button.get('value') + '-selected'); button.removeClass('yui-button-hover'); button._selected = false; } else { return false; } }, /** * @method deselectAllButtons * @description Deselects all buttons in the toolbar. * @return {Boolean} */ deselectAllButtons: function() { var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.deselectButton(this._buttonList[i]); } }, /** * @method disableAllButtons * @description Disables all buttons in the toolbar. * @return {Boolean} */ disableAllButtons: function() { if (this.get('disabled')) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.disableButton(this._buttonList[i]); } }, /** * @method enableAllButtons * @description Enables all buttons in the toolbar. * @return {Boolean} */ enableAllButtons: function() { if (this.get('disabled')) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.enableButton(this._buttonList[i]); } }, /** * @method resetAllButtons * @description Resets all buttons to their initial state. * @param {Object} _ex Except these buttons * @return {Boolean} */ resetAllButtons: function(_ex) { if (!Lang.isObject(_ex)) { _ex = {}; } if (this.get('disabled') || !this._buttonList) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { var _button = this._buttonList[i]; if (_button) { var disabled = _button._configs.disabled._initialConfig.value; if (_ex[_button.get('id')]) { this.enableButton(_button); this.selectButton(_button); } else { if (disabled) { this.disableButton(_button); } else { this.enableButton(_button); } this.deselectButton(_button); } } } }, /** * @method destroyButton * @description Destroy a button in the toolbar. * @param {String/Number} id Destroy a button by it's id or index. * @return {Boolean} */ destroyButton: function(id) { var button = getButton.call(this, id); if (button) { var thisID = button.get('id'), new_list = [], i = 0, len = this._buttonList.length; button.destroy(); for (i = 0; i < len; i++) { if (this._buttonList[i].get('id') != thisID) { new_list[new_list.length]= this._buttonList[i]; } } this._buttonList = new_list; } else { return false; } }, /** * @method destroy * @description Destroys the toolbar, all of it's elements and objects. * @return {Boolean} */ destroy: function() { var len = this._configuredButtons.length, j, i, b; for(b = 0; b < len; b++) { this.destroyButton(this._configuredButtons[b]); } this._configuredButtons = null; this.get('element').innerHTML = ''; this.get('element').className = ''; //Brutal Object Destroy for (i in this) { if (Lang.hasOwnProperty(this, i)) { this[i] = null; } } return true; }, /** * @method collapse * @description Programatically collapse the toolbar. * @param {Boolean} collapse True to collapse, false to expand. */ collapse: function(collapse) { var el = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapse === false) { Dom.removeClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed'); if (el[0]) { Dom.removeClass(el[0], 'collapsed'); el[0].title = this.STR_COLLAPSE; } this.fireEvent('toolbarExpanded', { type: 'toolbarExpanded', target: this }); } else { if (el[0]) { Dom.addClass(el[0], 'collapsed'); el[0].title = this.STR_EXPAND; } Dom.addClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed'); this.fireEvent('toolbarCollapsed', { type: 'toolbarCollapsed', target: this }); } }, /** * @method toString * @description Returns a string representing the toolbar. * @return {String} */ toString: function() { return 'Toolbar (#' + this.get('element').id + ') with ' + this._buttonList.length + ' buttons.'; } }); /** * @event buttonClick * @param {Object} o The object passed to this handler is the button config used to create the button. * @description Fires when any botton receives a click event. Passes back a single object representing the buttons config object. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event valueClick * @param {Object} o The object passed to this handler is the button config used to create the button. * @description This is a special dynamic event that is created and dispatched based on the value property * of the button config. See Element.addListener for more information on listening for this event. * Example: *
          * buttons : [
          *   { type: 'button', value: 'test', value: 'testButton' }
          * ]
          *
          * With the valueClick event you could subscribe to this buttons click event with this: * tbar.in('testButtonClick', function() { alert('test button clicked'); }) * @type YAHOO.util.CustomEvent */ /** * @event toolbarExpanded * @description Fires when the toolbar is expanded via the collapse button. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event toolbarCollapsed * @description Fires when the toolbar is collapsed via the collapse button. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ })(); /** * @module editor * @description

          The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization.

          * @namespace YAHOO.widget * @requires yahoo, dom, element, event, toolbar * @optional animation, container_core, resize, dragdrop */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, Toolbar = YAHOO.widget.Toolbar; /** * The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization. * @constructor * @class SimpleEditor * @extends YAHOO.util.Element * @param {String/HTMLElement} el The textarea element to turn into an editor. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.SimpleEditor = function(el, attrs) { var o = {}; if (Lang.isObject(el) && (!el.tagName) && !attrs) { Lang.augmentObject(o, el); //Break the config reference el = document.createElement('textarea'); this.DOMReady = true; if (o.container) { var c = Dom.get(o.container); c.appendChild(el); } else { document.body.appendChild(el); } } else { if (attrs) { Lang.augmentObject(o, attrs); //Break the config reference } } var oConfig = { element: null, attributes: o }, id = null; if (Lang.isString(el)) { id = el; } else { if (oConfig.attributes.id) { id = oConfig.attributes.id; } else { this.DOMReady = true; id = Dom.generateId(el); } } oConfig.element = el; var element_cont = document.createElement('DIV'); oConfig.attributes.element_cont = new YAHOO.util.Element(element_cont, { id: id + '_container' }); var div = document.createElement('div'); Dom.addClass(div, 'first-child'); oConfig.attributes.element_cont.appendChild(div); if (!oConfig.attributes.toolbar_cont) { oConfig.attributes.toolbar_cont = document.createElement('DIV'); oConfig.attributes.toolbar_cont.id = id + '_toolbar'; div.appendChild(oConfig.attributes.toolbar_cont); } var editorWrapper = document.createElement('DIV'); div.appendChild(editorWrapper); oConfig.attributes.editor_wrapper = editorWrapper; YAHOO.widget.SimpleEditor.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.SimpleEditor, YAHOO.util.Element, { /** * @private * @property _resizeConfig * @description The default config for the Resize Utility */ _resizeConfig: { handles: ['br'], autoRatio: true, status: true, proxy: true, useShim: true, setSize: false }, /** * @private * @method _setupResize * @description Creates the Resize instance and binds its events. */ _setupResize: function() { if (!YAHOO.util.DD || !YAHOO.util.Resize) { return false; } if (this.get('resize')) { var config = {}; Lang.augmentObject(config, this._resizeConfig); //Break the config reference this.resize = new YAHOO.util.Resize(this.get('element_cont').get('element'), config); this.resize.on('resize', function(args) { var anim = this.get('animate'); this.set('animate', false); this.set('width', args.width + 'px'); var h = args.height, th = (this.toolbar.get('element').clientHeight + 2), dh = 0; if (this.dompath) { dh = (this.dompath.clientHeight + 1); //It has a 1px top border.. } var newH = (h - th - dh); this.set('height', newH + 'px'); this.get('element_cont').setStyle('height', ''); this.set('animate', anim); }, this, true); } }, /** * @property resize * @description A reference to the Resize object * @type YAHOO.util.Resize */ resize: null, /** * @private * @method _setupDD * @description Sets up the DD instance used from the 'drag' config option. */ _setupDD: function() { if (!YAHOO.util.DD) { return false; } if (this.get('drag')) { var d = this.get('drag'), dd = YAHOO.util.DD; if (d === 'proxy') { dd = YAHOO.util.DDProxy; } this.dd = new dd(this.get('element_cont').get('element')); this.toolbar.addClass('draggable'); this.dd.setHandleElId(this.toolbar._titlebar); } }, /** * @property dd * @description A reference to the DragDrop object. * @type YAHOO.util.DD/YAHOO.util.DDProxy */ dd: null, /** * @private * @property _lastCommand * @description A cache of the last execCommand (used for Undo/Redo so they don't mark an undo level) * @type String */ _lastCommand: null, _undoNodeChange: function() {}, _storeUndo: function() {}, /** * @private * @method _checkKey * @description Checks a keyMap entry against a key event * @param {Object} k The _keyMap object * @param {Event} e The Mouse Event * @return {Boolean} */ _checkKey: function(k, e) { var ret = false; if ((e.keyCode === k.key)) { if (k.mods && (k.mods.length > 0)) { var val = 0; for (var i = 0; i < k.mods.length; i++) { if (this.browser.mac) { if (k.mods[i] == 'ctrl') { k.mods[i] = 'meta'; } } if (e[k.mods[i] + 'Key'] === true) { val++; } } if (val === k.mods.length) { ret = true; } } else { ret = true; } } return ret; }, /** * @private * @property _keyMap * @description Named key maps for various actions in the Editor. Example: CLOSE_WINDOW: { key: 87, mods: ['shift', 'ctrl'] }. * This entry shows that when key 87 (W) is found with the modifiers of shift and control, the window will close. You can customize this object to tweak keyboard shortcuts. * @type {Object/Mixed} */ _keyMap: { SELECT_ALL: { key: 65, //A key mods: ['ctrl'] }, CLOSE_WINDOW: { key: 87, //W key mods: ['shift', 'ctrl'] }, FOCUS_TOOLBAR: { key: 27, mods: ['shift'] }, FOCUS_AFTER: { key: 27 }, FONT_SIZE_UP: { key: 38, mods: ['shift', 'ctrl'] }, FONT_SIZE_DOWN: { key: 40, mods: ['shift', 'ctrl'] }, CREATE_LINK: { key: 76, mods: ['shift', 'ctrl'] }, BOLD: { key: 66, mods: ['shift', 'ctrl'] }, ITALIC: { key: 73, mods: ['shift', 'ctrl'] }, UNDERLINE: { key: 85, mods: ['shift', 'ctrl'] }, UNDO: { key: 90, mods: ['ctrl'] }, REDO: { key: 90, mods: ['shift', 'ctrl'] }, JUSTIFY_LEFT: { key: 219, mods: ['shift', 'ctrl'] }, JUSTIFY_CENTER: { key: 220, mods: ['shift', 'ctrl'] }, JUSTIFY_RIGHT: { key: 221, mods: ['shift', 'ctrl'] } }, /** * @private * @method _cleanClassName * @description Makes a useable classname from dynamic data, by dropping it to lowercase and replacing spaces with -'s. * @param {String} str The classname to clean up * @return {String} */ _cleanClassName: function(str) { return str.replace(/ /g, '-').toLowerCase(); }, /** * @property _textarea * @description Flag to determine if we are using a textarea or an HTML Node. * @type Boolean */ _textarea: null, /** * @property _docType * @description The DOCTYPE to use in the editable container. * @type String */ _docType: '', /** * @property editorDirty * @description This flag will be set when certain things in the Editor happen. It is to be used by the developer to check to see if content has changed. * @type Boolean */ editorDirty: null, /** * @property _defaultCSS * @description The default CSS used in the config for 'css'. This way you can add to the config like this: { css: YAHOO.widget.SimpleEditor.prototype._defaultCSS + 'ADD MYY CSS HERE' } * @type String */ _defaultCSS: 'html { height: 95%; } body { padding: 7px; background-color: #fff; font: 13px/1.22 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small; } a, a:visited, a:hover { color: blue !important; text-decoration: underline !important; cursor: text !important; } .warning-localfile { border-bottom: 1px dashed red !important; } .yui-busy { cursor: wait !important; } img.selected { border: 2px dotted #808080; } img { cursor: pointer !important; border: none; } body.ptags.webkit div.yui-wk-p { margin: 11px 0; } body.ptags.webkit div.yui-wk-div { margin: 0; }', /** * @property _defaultToolbar * @private * @description Default toolbar config. * @type Object */ _defaultToolbar: null, /** * @property _lastButton * @private * @description The last button pressed, so we don't disable it. * @type Object */ _lastButton: null, /** * @property _baseHREF * @private * @description The base location of the editable page (this page) so that relative paths for image work. * @type String */ _baseHREF: function() { var href = document.location.href; if (href.indexOf('?') !== -1) { //Remove the query string href = href.substring(0, href.indexOf('?')); } href = href.substring(0, href.lastIndexOf('/')) + '/'; return href; }(), /** * @property _lastImage * @private * @description Safari reference for the last image selected (for styling as selected). * @type HTMLElement */ _lastImage: null, /** * @property _blankImageLoaded * @private * @description Don't load the blank image more than once.. * @type Boolean */ _blankImageLoaded: null, /** * @property _fixNodesTimer * @private * @description Holder for the fixNodes timer * @type Date */ _fixNodesTimer: null, /** * @property _nodeChangeTimer * @private * @description Holds a reference to the nodeChange setTimeout call * @type Number */ _nodeChangeTimer: null, /** * @property _nodeChangeDelayTimer * @private * @description Holds a reference to the nodeChangeDelay setTimeout call * @type Number */ _nodeChangeDelayTimer: null, /** * @property _lastNodeChangeEvent * @private * @description Flag to determine the last event that fired a node change * @type Event */ _lastNodeChangeEvent: null, /** * @property _lastNodeChange * @private * @description Flag to determine when the last node change was fired * @type Date */ _lastNodeChange: 0, /** * @property _rendered * @private * @description Flag to determine if editor has been rendered or not * @type Boolean */ _rendered: null, /** * @property DOMReady * @private * @description Flag to determine if DOM is ready or not * @type Boolean */ DOMReady: null, /** * @property _selection * @private * @description Holder for caching iframe selections * @type Object */ _selection: null, /** * @property _mask * @private * @description DOM Element holder for the editor Mask when disabled * @type Object */ _mask: null, /** * @property _showingHiddenElements * @private * @description Status of the hidden elements button * @type Boolean */ _showingHiddenElements: null, /** * @property currentWindow * @description A reference to the currently open EditorWindow * @type Object */ currentWindow: null, /** * @property currentEvent * @description A reference to the current editor event * @type Event */ currentEvent: null, /** * @property operaEvent * @private * @description setTimeout holder for Opera and Image DoubleClick event.. * @type Object */ operaEvent: null, /** * @property currentFont * @description A reference to the last font selected from the Toolbar * @type HTMLElement */ currentFont: null, /** * @property currentElement * @description A reference to the current working element in the editor * @type Array */ currentElement: null, /** * @property dompath * @description A reference to the dompath container for writing the current working dom path to. * @type HTMLElement */ dompath: null, /** * @property beforeElement * @description A reference to the H2 placed before the editor for Accessibilty. * @type HTMLElement */ beforeElement: null, /** * @property afterElement * @description A reference to the H2 placed after the editor for Accessibilty. * @type HTMLElement */ afterElement: null, /** * @property invalidHTML * @description Contains a list of HTML elements that are invalid inside the editor. They will be removed when they are found. If you set the value of a key to "{ keepContents: true }", then the element will be replaced with a yui-non span to be filtered out when cleanHTML is called. The only tag that is ignored here is the span tag as it will force the Editor into a loop and freeze the browser. However.. all of these tags will be removed in the cleanHTML routine. * @type Object */ invalidHTML: { form: true, input: true, button: true, select: true, link: true, html: true, body: true, iframe: true, script: true, style: true, textarea: true }, /** * @property toolbar * @description Local property containing the YAHOO.widget.Toolbar instance * @type YAHOO.widget.Toolbar */ toolbar: null, /** * @private * @property _contentTimer * @description setTimeout holder for documentReady check */ _contentTimer: null, /** * @private * @property _contentTimerMax * @description The number of times the loaded content should be checked before giving up. Default: 500 */ _contentTimerMax: 500, /** * @private * @property _contentTimerCounter * @description Counter to check the number of times the body is polled for before giving up * @type Number */ _contentTimerCounter: 0, /** * @private * @property _disabled * @description The Toolbar items that should be disabled if there is no selection present in the editor. * @type Array */ _disabled: [ 'createlink', 'fontname', 'fontsize', 'forecolor', 'backcolor' ], /** * @private * @property _alwaysDisabled * @description The Toolbar items that should ALWAYS be disabled event if there is a selection present in the editor. * @type Object */ _alwaysDisabled: { undo: true, redo: true }, /** * @private * @property _alwaysEnabled * @description The Toolbar items that should ALWAYS be enabled event if there isn't a selection present in the editor. * @type Object */ _alwaysEnabled: { }, /** * @private * @property _semantic * @description The Toolbar commands that we should attempt to make tags out of instead of using styles. * @type Object */ _semantic: { 'bold': true, 'italic' : true, 'underline' : true }, /** * @private * @property _tag2cmd * @description A tag map of HTML tags to convert to the different types of commands so we can select the proper toolbar button. * @type Object */ _tag2cmd: { 'b': 'bold', 'strong': 'bold', 'i': 'italic', 'em': 'italic', 'u': 'underline', 'sup': 'superscript', 'sub': 'subscript', 'img': 'insertimage', 'a' : 'createlink', 'ul' : 'insertunorderedlist', 'ol' : 'insertorderedlist' }, /** * @private _createIframe * @description Creates the DOM and YUI Element for the iFrame editor area. * @param {String} id The string ID to prefix the iframe with * @return {Object} iFrame object */ _createIframe: function() { var ifrmDom = document.createElement('iframe'); ifrmDom.id = this.get('id') + '_editor'; var config = { border: '0', frameBorder: '0', marginWidth: '0', marginHeight: '0', leftMargin: '0', topMargin: '0', allowTransparency: 'true', width: '100%' }; if (this.get('autoHeight')) { config.scrolling = 'no'; } for (var i in config) { if (Lang.hasOwnProperty(config, i)) { ifrmDom.setAttribute(i, config[i]); } } var isrc = 'javascript:;'; if (this.browser.ie) { //isrc = 'about:blank'; //TODO - Check this, I have changed it before.. isrc = 'javascript:false;'; } ifrmDom.setAttribute('src', isrc); var ifrm = new YAHOO.util.Element(ifrmDom); ifrm.setStyle('visibility', 'hidden'); return ifrm; }, /** * @private _isElement * @description Checks to see if an Element reference is a valid one and has a certain tag type * @param {HTMLElement} el The element to check * @param {String} tag The tag that the element needs to be * @return {Boolean} */ _isElement: function(el, tag) { if (el && el.tagName && (el.tagName.toLowerCase() == tag)) { return true; } if (el && el.getAttribute && (el.getAttribute('tag') == tag)) { return true; } return false; }, /** * @private _hasParent * @description Checks to see if an Element reference or one of it's parents is a valid one and has a certain tag type * @param {HTMLElement} el The element to check * @param {String} tag The tag that the element needs to be * @return HTMLElement */ _hasParent: function(el, tag) { if (!el || !el.parentNode) { return false; } while (el.parentNode) { if (this._isElement(el, tag)) { return el; } if (el.parentNode) { el = el.parentNode; } else { return false; } } return false; }, /** * @private * @method _getDoc * @description Get the Document of the IFRAME * @return {Object} */ _getDoc: function() { var value = false; try { if (this.get('iframe').get('element').contentWindow.document) { value = this.get('iframe').get('element').contentWindow.document; return value; } } catch (e) { return false; } }, /** * @private * @method _getWindow * @description Get the Window of the IFRAME * @return {Object} */ _getWindow: function() { return this.get('iframe').get('element').contentWindow; }, /** * @method focus * @description Attempt to set the focus of the iframes window. */ focus: function() { this._getWindow().focus(); }, /** * @private * @depreciated - This should not be used, moved to this.focus(); * @method _focusWindow * @description Attempt to set the focus of the iframes window. */ _focusWindow: function() { this.focus(); }, /** * @private * @method _hasSelection * @description Determines if there is a selection in the editor document. * @return {Boolean} */ _hasSelection: function() { var sel = this._getSelection(); var range = this._getRange(); var hasSel = false; if (!sel || !range) { return hasSel; } //Internet Explorer if (this.browser.ie) { if (range.text) { hasSel = true; } if (range.html) { hasSel = true; } } else { if (this.browser.webkit) { if (sel+'' !== '') { hasSel = true; } } else { if (sel && (sel.toString() !== '') && (sel !== undefined)) { hasSel = true; } } } return hasSel; }, /** * @private * @method _getSelection * @description Handles the different selection objects across the A-Grade list. * @return {Object} Selection Object */ _getSelection: function() { var _sel = null; if (this._getDoc() && this._getWindow()) { if (this._getDoc().selection &&! this.browser.opera) { _sel = this._getDoc().selection; } else { _sel = this._getWindow().getSelection(); } //Handle Safari's lack of Selection Object if (this.browser.webkit) { if (_sel.baseNode) { this._selection = {}; this._selection.baseNode = _sel.baseNode; this._selection.baseOffset = _sel.baseOffset; this._selection.extentNode = _sel.extentNode; this._selection.extentOffset = _sel.extentOffset; } else if (this._selection !== null) { _sel = this._getWindow().getSelection(); _sel.setBaseAndExtent( this._selection.baseNode, this._selection.baseOffset, this._selection.extentNode, this._selection.extentOffset); this._selection = null; } } } return _sel; }, /** * @private * @method _selectNode * @description Places the highlight around a given node * @param {HTMLElement} node The node to select */ _selectNode: function(node, collapse) { if (!node) { return false; } var sel = this._getSelection(), range = null; if (this.browser.ie) { try { //IE freaks out here sometimes.. range = this._getDoc().body.createTextRange(); range.moveToElementText(node); range.select(); } catch (e) { } } else if (this.browser.webkit) { if (collapse) { sel.setBaseAndExtent(node, 1, node, node.innerText.length); } else { sel.setBaseAndExtent(node, 0, node, node.innerText.length); } } else if (this.browser.opera) { sel = this._getWindow().getSelection(); range = this._getDoc().createRange(); range.selectNode(node); sel.removeAllRanges(); sel.addRange(range); } else { range = this._getDoc().createRange(); range.selectNodeContents(node); sel.removeAllRanges(); sel.addRange(range); } //TODO - Check Performance this.nodeChange(); }, /** * @private * @method _getRange * @description Handles the different range objects across the A-Grade list. * @return {Object} Range Object */ _getRange: function() { var sel = this._getSelection(); if (sel === null) { return null; } if (this.browser.webkit && !sel.getRangeAt) { var _range = this._getDoc().createRange(); try { _range.setStart(sel.anchorNode, sel.anchorOffset); _range.setEnd(sel.focusNode, sel.focusOffset); } catch (e) { _range = this._getWindow().getSelection()+''; } return _range; } if (this.browser.ie) { try { return sel.createRange(); } catch (e2) { return null; } } if (sel.rangeCount > 0) { return sel.getRangeAt(0); } return null; }, /** * @private * @method _setDesignMode * @description Sets the designMode property of the iFrame document's body. * @param {String} state This should be either on or off */ _setDesignMode: function(state) { if (this.get('setDesignMode')) { try { this._getDoc().designMode = ((state.toLowerCase() == 'off') ? 'off' : 'on'); } catch(e) { } } }, /** * @private * @method _toggleDesignMode * @description Toggles the designMode property of the iFrame document on and off. * @return {String} The state that it was set to. */ _toggleDesignMode: function() { var _dMode = this._getDoc().designMode, _state = ((_dMode.toLowerCase() == 'on') ? 'off' : 'on'); this._setDesignMode(_state); return _state; }, /** * @private * @property _focused * @description Holder for trapping focus/blur state and prevent double events * @type Boolean */ _focused: null, /** * @private * @method _handleFocus * @description Handles the focus of the iframe. Note, this is window focus event, not an Editor focus event. * @param {Event} e The DOM Event */ _handleFocus: function(e) { if (!this._focused) { this._focused = true; this.fireEvent('editorWindowFocus', { type: 'editorWindowFocus', target: this }); } }, /** * @private * @method _handleBlur * @description Handles the blur of the iframe. Note, this is window blur event, not an Editor blur event. * @param {Event} e The DOM Event */ _handleBlur: function(e) { if (this._focused) { this._focused = false; this.fireEvent('editorWindowBlur', { type: 'editorWindowBlur', target: this }); } }, /** * @private * @method _initEditorEvents * @description This method sets up the listeners on the Editors document. */ _initEditorEvents: function() { //Setup Listeners on iFrame var doc = this._getDoc(), win = this._getWindow(); Event.on(doc, 'mouseup', this._handleMouseUp, this, true); Event.on(doc, 'mousedown', this._handleMouseDown, this, true); Event.on(doc, 'click', this._handleClick, this, true); Event.on(doc, 'dblclick', this._handleDoubleClick, this, true); Event.on(doc, 'keypress', this._handleKeyPress, this, true); Event.on(doc, 'keyup', this._handleKeyUp, this, true); Event.on(doc, 'keydown', this._handleKeyDown, this, true); /* TODO -- Everyone but Opera works here.. Event.on(doc, 'paste', function() { }, this, true); */ //Focus and blur.. Event.on(win, 'focus', this._handleFocus, this, true); Event.on(win, 'blur', this._handleBlur, this, true); }, /** * @private * @method _removeEditorEvents * @description This method removes the listeners on the Editors document (for disabling). */ _removeEditorEvents: function() { //Remove Listeners on iFrame var doc = this._getDoc(), win = this._getWindow(); Event.removeListener(doc, 'mouseup', this._handleMouseUp, this, true); Event.removeListener(doc, 'mousedown', this._handleMouseDown, this, true); Event.removeListener(doc, 'click', this._handleClick, this, true); Event.removeListener(doc, 'dblclick', this._handleDoubleClick, this, true); Event.removeListener(doc, 'keypress', this._handleKeyPress, this, true); Event.removeListener(doc, 'keyup', this._handleKeyUp, this, true); Event.removeListener(doc, 'keydown', this._handleKeyDown, this, true); //Focus and blur.. Event.removeListener(win, 'focus', this._handleFocus, this, true); Event.removeListener(win, 'blur', this._handleBlur, this, true); }, _fixWebkitDivs: function() { if (this.browser.webkit) { var divs = this._getDoc().body.getElementsByTagName('div'); Dom.addClass(divs, 'yui-wk-div'); } }, /** * @private * @method _initEditor * @param {Boolean} raw Don't add events. * @description This method is fired from _checkLoaded when the document is ready. It turns on designMode and set's up the listeners. */ _initEditor: function(raw) { if (this._editorInit) { return; } this._editorInit = true; if (this.browser.ie) { this._getDoc().body.style.margin = '0'; } if (!this.get('disabled')) { this._setDesignMode('on'); this._contentTimerCounter = 0; } if (!this._getDoc().body) { this._contentTimerCounter = 0; this._editorInit = false; this._checkLoaded(); return false; } if (!raw) { this.toolbar.on('buttonClick', this._handleToolbarClick, this, true); } if (!this.get('disabled')) { this._initEditorEvents(); this.toolbar.set('disabled', false); } if (raw) { this.fireEvent('editorContentReloaded', { type: 'editorreloaded', target: this }); } else { this.fireEvent('editorContentLoaded', { type: 'editorLoaded', target: this }); } this._fixWebkitDivs(); if (this.get('dompath')) { var self = this; setTimeout(function() { self._writeDomPath.call(self); self._setupResize.call(self); }, 150); } var br = []; for (var i in this.browser) { if (this.browser[i]) { br.push(i); } } if (this.get('ptags')) { br.push('ptags'); } Dom.addClass(this._getDoc().body, br.join(' ')); this.nodeChange(true); }, /** * @private * @method _checkLoaded * @param {Boolean} raw Don't add events. * @description Called from a setTimeout loop to check if the iframes body.onload event has fired, then it will init the editor. */ _checkLoaded: function(raw) { this._editorInit = false; this._contentTimerCounter++; if (this._contentTimer) { clearTimeout(this._contentTimer); } if (this._contentTimerCounter > this._contentTimerMax) { return false; } var init = false; try { if (this._getDoc() && this._getDoc().body) { if (this.browser.ie) { if (this._getDoc().body.readyState == 'complete') { init = true; } } else { if (this._getDoc().body._rteLoaded === true) { init = true; } } } } catch (e) { init = false; } if (init === true) { //The onload event has fired, clean up after ourselves and fire the _initEditor method this._initEditor(raw); } else { var self = this; this._contentTimer = setTimeout(function() { self._checkLoaded.call(self, raw); }, 20); } }, /** * @private * @method _setInitialContent * @param {Boolean} raw Don't add events. * @description This method will open the iframes content document and write the textareas value into it, then start the body.onload checking. */ _setInitialContent: function(raw) { var value = ((this._textarea) ? this.get('element').value : this.get('element').innerHTML), doc = null; if (value === '') { value = '
          '; } var html = Lang.substitute(this.get('html'), { TITLE: this.STR_TITLE, CONTENT: this._cleanIncomingHTML(value), CSS: this.get('css'), HIDDEN_CSS: ((this.get('hiddencss')) ? this.get('hiddencss') : '/* No Hidden CSS */'), EXTRA_CSS: ((this.get('extracss')) ? this.get('extracss') : '/* No Extra CSS */') }), check = true; html = html.replace(/RIGHT_BRACKET/gi, '{'); html = html.replace(/LEFT_BRACKET/gi, '}'); if (document.compatMode != 'BackCompat') { html = this._docType + "\n" + html; } else { } if (this.browser.ie || this.browser.webkit || this.browser.opera || (navigator.userAgent.indexOf('Firefox/1.5') != -1)) { //Firefox 1.5 doesn't like setting designMode on an document created with a data url try { //Adobe AIR Code if (this.browser.air) { doc = this._getDoc().implementation.createHTMLDocument(); var origDoc = this._getDoc(); origDoc.open(); origDoc.close(); doc.open(); doc.write(html); doc.close(); var node = origDoc.importNode(doc.getElementsByTagName("html")[0], true); origDoc.replaceChild(node, origDoc.getElementsByTagName("html")[0]); origDoc.body._rteLoaded = true; } else { doc = this._getDoc(); doc.open(); doc.write(html); doc.close(); } } catch (e) { //Safari will only be here if we are hidden check = false; } } else { //This keeps Firefox 2 from writing the iframe to history preserving the back buttons functionality this.get('iframe').get('element').src = 'data:text/html;charset=utf-8,' + encodeURIComponent(html); } this.get('iframe').setStyle('visibility', ''); if (check) { this._checkLoaded(raw); } }, /** * @private * @method _setMarkupType * @param {String} action The action to take. Possible values are: css, default or semantic * @description This method will turn on/off the useCSS execCommand. */ _setMarkupType: function(action) { switch (this.get('markup')) { case 'css': this._setEditorStyle(true); break; case 'default': this._setEditorStyle(false); break; case 'semantic': case 'xhtml': if (this._semantic[action]) { this._setEditorStyle(false); } else { this._setEditorStyle(true); } break; } }, /** * Set the editor to use CSS instead of HTML * @param {Booleen} stat True/False */ _setEditorStyle: function(stat) { try { this._getDoc().execCommand('useCSS', false, !stat); } catch (ex) { } }, /** * @private * @method _getSelectedElement * @description This method will attempt to locate the element that was last interacted with, either via selection, location or event. * @return {HTMLElement} The currently selected element. */ _getSelectedElement: function() { var doc = this._getDoc(), range = null, sel = null, elm = null, check = true; if (this.browser.ie) { this.currentEvent = this._getWindow().event; //Event utility assumes window.event, so we need to reset it to this._getWindow().event; range = this._getRange(); if (range) { elm = range.item ? range.item(0) : range.parentElement(); if (this._hasSelection()) { //TODO //WTF.. Why can't I get an element reference here?!??! } if (elm === doc.body) { elm = null; } } if ((this.currentEvent !== null) && (this.currentEvent.keyCode === 0)) { elm = Event.getTarget(this.currentEvent); } } else { sel = this._getSelection(); range = this._getRange(); if (!sel || !range) { return null; } //TODO if (!this._hasSelection() && this.browser.webkit3) { //check = false; } if (this.browser.gecko) { //Added in 2.6.0 if (range.startContainer) { if (range.startContainer.nodeType === 3) { elm = range.startContainer.parentNode; } else if (range.startContainer.nodeType === 1) { elm = range.startContainer; } //Added in 2.7.0 if (this.currentEvent) { var tar = Event.getTarget(this.currentEvent); if (!this._isElement(tar, 'html')) { if (elm !== tar) { elm = tar; } } } } } if (check) { if (sel.anchorNode && (sel.anchorNode.nodeType == 3)) { if (sel.anchorNode.parentNode) { //next check parentNode elm = sel.anchorNode.parentNode; } if (sel.anchorNode.nextSibling != sel.focusNode.nextSibling) { elm = sel.anchorNode.nextSibling; } } if (this._isElement(elm, 'br')) { elm = null; } if (!elm) { elm = range.commonAncestorContainer; if (!range.collapsed) { if (range.startContainer == range.endContainer) { if (range.startOffset - range.endOffset < 2) { if (range.startContainer.hasChildNodes()) { elm = range.startContainer.childNodes[range.startOffset]; } } } } } } } if (this.currentEvent !== null) { try { switch (this.currentEvent.type) { case 'click': case 'mousedown': case 'mouseup': if (this.browser.webkit) { elm = Event.getTarget(this.currentEvent); } break; default: //Do nothing break; } } catch (e) { } } else if ((this.currentElement && this.currentElement[0]) && (!this.browser.ie)) { //TODO is this still needed? //elm = this.currentElement[0]; } if (this.browser.opera || this.browser.webkit) { if (this.currentEvent && !elm) { elm = YAHOO.util.Event.getTarget(this.currentEvent); } } if (!elm || !elm.tagName) { elm = doc.body; } if (this._isElement(elm, 'html')) { //Safari sometimes gives us the HTML node back.. elm = doc.body; } if (this._isElement(elm, 'body')) { //make sure that body means this body not the parent.. elm = doc.body; } if (elm && !elm.parentNode) { //Not in document elm = doc.body; } if (elm === undefined) { elm = null; } return elm; }, /** * @private * @method _getDomPath * @description This method will attempt to build the DOM path from the currently selected element. * @param HTMLElement el The element to start with, if not provided _getSelectedElement is used * @return {Array} An array of node references that will create the DOM Path. */ _getDomPath: function(el) { if (!el) { el = this._getSelectedElement(); } var domPath = []; while (el !== null) { if (el.ownerDocument != this._getDoc()) { el = null; break; } //Check to see if we get el.nodeName and nodeType if (el.nodeName && el.nodeType && (el.nodeType == 1)) { domPath[domPath.length] = el; } if (this._isElement(el, 'body')) { break; } el = el.parentNode; } if (domPath.length === 0) { if (this._getDoc() && this._getDoc().body) { domPath[0] = this._getDoc().body; } } return domPath.reverse(); }, /** * @private * @method _writeDomPath * @description Write the current DOM path out to the dompath container below the editor. */ _writeDomPath: function() { var path = this._getDomPath(), pathArr = [], classPath = '', pathStr = ''; for (var i = 0; i < path.length; i++) { var tag = path[i].tagName.toLowerCase(); if ((tag == 'ol') && (path[i].type)) { tag += ':' + path[i].type; } if (Dom.hasClass(path[i], 'yui-tag')) { tag = path[i].getAttribute('tag'); } if ((this.get('markup') == 'semantic') || (this.get('markup') == 'xhtml')) { switch (tag) { case 'b': tag = 'strong'; break; case 'i': tag = 'em'; break; } } if (!Dom.hasClass(path[i], 'yui-non')) { if (Dom.hasClass(path[i], 'yui-tag')) { pathStr = tag; } else { classPath = ((path[i].className !== '') ? '.' + path[i].className.replace(/ /g, '.') : ''); if ((classPath.indexOf('yui') != -1) || (classPath.toLowerCase().indexOf('apple-style-span') != -1)) { classPath = ''; } pathStr = tag + ((path[i].id) ? '#' + path[i].id : '') + classPath; } switch (tag) { case 'body': pathStr = 'body'; break; case 'a': if (path[i].getAttribute('href', 2)) { pathStr += ':' + path[i].getAttribute('href', 2).replace('mailto:', '').replace('http:/'+'/', '').replace('https:/'+'/', ''); //May need to add others here ftp } break; case 'img': var h = path[i].height; var w = path[i].width; if (path[i].style.height) { h = parseInt(path[i].style.height, 10); } if (path[i].style.width) { w = parseInt(path[i].style.width, 10); } pathStr += '(' + w + 'x' + h + ')'; break; } if (pathStr.length > 10) { pathStr = '' + pathStr.substring(0, 10) + '...' + ''; } else { pathStr = '' + pathStr + ''; } pathArr[pathArr.length] = pathStr; } } var str = pathArr.join(' ' + this.SEP_DOMPATH + ' '); //Prevent flickering if (this.dompath.innerHTML != str) { this.dompath.innerHTML = str; } }, /** * @private * @method _fixNodes * @description Fix href and imgs as well as remove invalid HTML. */ _fixNodes: function() { try { var doc = this._getDoc(), els = []; for (var v in this.invalidHTML) { if (YAHOO.lang.hasOwnProperty(this.invalidHTML, v)) { if (v.toLowerCase() != 'span') { var tags = doc.body.getElementsByTagName(v); if (tags.length) { for (var i = 0; i < tags.length; i++) { els.push(tags[i]); } } } } } for (var h = 0; h < els.length; h++) { if (els[h].parentNode) { if (Lang.isObject(this.invalidHTML[els[h].tagName.toLowerCase()]) && this.invalidHTML[els[h].tagName.toLowerCase()].keepContents) { this._swapEl(els[h], 'span', function(el) { el.className = 'yui-non'; }); } else { els[h].parentNode.removeChild(els[h]); } } } var imgs = this._getDoc().getElementsByTagName('img'); Dom.addClass(imgs, 'yui-img'); } catch(e) {} }, /** * @private * @method _isNonEditable * @param Event ev The Dom event being checked * @description Method is called at the beginning of all event handlers to check if this element or a parent element has the class yui-noedit (this.CLASS_NOEDIT) applied. * If it does, then this method will stop the event and return true. The event handlers will then return false and stop the nodeChange from occuring. This method will also * disable and enable the Editor's toolbar based on the noedit state. * @return Boolean */ _isNonEditable: function(ev) { if (this.get('allowNoEdit')) { var el = Event.getTarget(ev); if (this._isElement(el, 'html')) { el = null; } var path = this._getDomPath(el); for (var i = (path.length - 1); i > -1; i--) { if (Dom.hasClass(path[i], this.CLASS_NOEDIT)) { //if (this.toolbar.get('disabled') === false) { // this.toolbar.set('disabled', true); //} try { this._getDoc().execCommand('enableObjectResizing', false, 'false'); } catch (e) {} this.nodeChange(); Event.stopEvent(ev); return true; } } //if (this.toolbar.get('disabled') === true) { //Should only happen once.. //this.toolbar.set('disabled', false); try { this._getDoc().execCommand('enableObjectResizing', false, 'true'); } catch (e2) {} //} } return false; }, /** * @private * @method _setCurrentEvent * @param {Event} ev The event to cache * @description Sets the current event property */ _setCurrentEvent: function(ev) { this.currentEvent = ev; }, /** * @private * @method _handleClick * @param {Event} ev The event we are working on. * @description Handles all click events inside the iFrame document. */ _handleClick: function(ev) { var ret = this.fireEvent('beforeEditorClick', { type: 'beforeEditorClick', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); if (this.currentWindow) { this.closeWindow(); } if (this.currentWindow) { this.closeWindow(); } if (this.browser.webkit) { var tar =Event.getTarget(ev); if (this._isElement(tar, 'a') || this._isElement(tar.parentNode, 'a')) { Event.stopEvent(ev); this.nodeChange(); } } else { this.nodeChange(); } this.fireEvent('editorClick', { type: 'editorClick', target: this, ev: ev }); }, /** * @private * @method _handleMouseUp * @param {Event} ev The event we are working on. * @description Handles all mouseup events inside the iFrame document. */ _handleMouseUp: function(ev) { var ret = this.fireEvent('beforeEditorMouseUp', { type: 'beforeEditorMouseUp', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } //Don't set current event for mouseup. //It get's fired after a menu is closed and gives up a bogus event to work with //this._setCurrentEvent(ev); var self = this; if (this.browser.opera) { /* * @knownissue Opera appears to stop the MouseDown, Click and DoubleClick events on an image inside of a document with designMode on.. * @browser Opera * @description This work around traps the MouseUp event and sets a timer to check if another MouseUp event fires in so many seconds. If another event is fired, they we internally fire the DoubleClick event. */ var sel = Event.getTarget(ev); if (this._isElement(sel, 'img')) { this.nodeChange(); if (this.operaEvent) { clearTimeout(this.operaEvent); this.operaEvent = null; this._handleDoubleClick(ev); } else { this.operaEvent = window.setTimeout(function() { self.operaEvent = false; }, 700); } } } //This will stop Safari from selecting the entire document if you select all the text in the editor if (this.browser.webkit || this.browser.opera) { if (this.browser.webkit) { Event.stopEvent(ev); } } this.nodeChange(); this.fireEvent('editorMouseUp', { type: 'editorMouseUp', target: this, ev: ev }); }, /** * @private * @method _handleMouseDown * @param {Event} ev The event we are working on. * @description Handles all mousedown events inside the iFrame document. */ _handleMouseDown: function(ev) { var ret = this.fireEvent('beforeEditorMouseDown', { type: 'beforeEditorMouseDown', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); var sel = Event.getTarget(ev); if (this.browser.webkit && this._hasSelection()) { var _sel = this._getSelection(); if (!this.browser.webkit3) { _sel.collapse(true); } else { _sel.collapseToStart(); } } if (this.browser.webkit && this._lastImage) { Dom.removeClass(this._lastImage, 'selected'); this._lastImage = null; } if (this._isElement(sel, 'img') || this._isElement(sel, 'a')) { if (this.browser.webkit) { Event.stopEvent(ev); if (this._isElement(sel, 'img')) { Dom.addClass(sel, 'selected'); this._lastImage = sel; } } if (this.currentWindow) { this.closeWindow(); } this.nodeChange(); } this.fireEvent('editorMouseDown', { type: 'editorMouseDown', target: this, ev: ev }); }, /** * @private * @method _handleDoubleClick * @param {Event} ev The event we are working on. * @description Handles all doubleclick events inside the iFrame document. */ _handleDoubleClick: function(ev) { var ret = this.fireEvent('beforeEditorDoubleClick', { type: 'beforeEditorDoubleClick', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); var sel = Event.getTarget(ev); if (this._isElement(sel, 'img')) { this.currentElement[0] = sel; this.toolbar.fireEvent('insertimageClick', { type: 'insertimageClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); } else if (this._hasParent(sel, 'a')) { //Handle elements inside an a this.currentElement[0] = this._hasParent(sel, 'a'); this.toolbar.fireEvent('createlinkClick', { type: 'createlinkClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); } this.nodeChange(); this.fireEvent('editorDoubleClick', { type: 'editorDoubleClick', target: this, ev: ev }); }, /** * @private * @method _handleKeyUp * @param {Event} ev The event we are working on. * @description Handles all keyup events inside the iFrame document. */ _handleKeyUp: function(ev) { var ret = this.fireEvent('beforeEditorKeyUp', { type: 'beforeEditorKeyUp', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._storeUndo(); this._setCurrentEvent(ev); switch (ev.keyCode) { case this._keyMap.SELECT_ALL.key: if (this._checkKey(this._keyMap.SELECT_ALL, ev)) { this.nodeChange(); } break; case 32: //Space Bar case 35: //End case 36: //Home case 37: //Left Arrow case 38: //Up Arrow case 39: //Right Arrow case 40: //Down Arrow case 46: //Forward Delete case 8: //Delete case this._keyMap.CLOSE_WINDOW.key: //W key if window is open if ((ev.keyCode == this._keyMap.CLOSE_WINDOW.key) && this.currentWindow) { if (this._checkKey(this._keyMap.CLOSE_WINDOW, ev)) { this.closeWindow(); } } else { if (!this.browser.ie) { if (this._nodeChangeTimer) { clearTimeout(this._nodeChangeTimer); } var self = this; this._nodeChangeTimer = setTimeout(function() { self._nodeChangeTimer = null; self.nodeChange.call(self); }, 100); } else { this.nodeChange(); } this.editorDirty = true; } break; } this.fireEvent('editorKeyUp', { type: 'editorKeyUp', target: this, ev: ev }); }, /** * @private * @method _handleKeyPress * @param {Event} ev The event we are working on. * @description Handles all keypress events inside the iFrame document. */ _handleKeyPress: function(ev) { var ret = this.fireEvent('beforeEditorKeyPress', { type: 'beforeEditorKeyPress', target: this, ev: ev }); if (ret === false) { return false; } if (this.get('allowNoEdit')) { //if (ev && ev.keyCode && ((ev.keyCode == 46) || ev.keyCode == 63272)) { if (ev && ev.keyCode && (ev.keyCode == 63272)) { //Forward delete key Event.stopEvent(ev); } } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); this._storeUndo(); if (this.browser.opera) { if (ev.keyCode === 13) { var tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { this.execCommand('inserthtml', '
          '); Event.stopEvent(ev); } } } if (this.browser.webkit) { if (!this.browser.webkit3) { if (ev.keyCode && (ev.keyCode == 122) && (ev.metaKey)) { //This is CMD + z (for undo) if (this._hasParent(this._getSelectedElement(), 'li')) { Event.stopEvent(ev); } } } this._listFix(ev); } this._fixListDupIds(); this.fireEvent('editorKeyPress', { type: 'editorKeyPress', target: this, ev: ev }); }, /** * @private * @method _handleKeyDown * @param {Event} ev The event we are working on. * @description Handles all keydown events inside the iFrame document. */ _handleKeyDown: function(ev) { var ret = this.fireEvent('beforeEditorKeyDown', { type: 'beforeEditorKeyDown', target: this, ev: ev }); if (ret === false) { return false; } var tar = null, _range = null; if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); if (this.currentWindow) { this.closeWindow(); } if (this.currentWindow) { this.closeWindow(); } var doExec = false, action = null, value = null, exec = false; switch (ev.keyCode) { case this._keyMap.FOCUS_TOOLBAR.key: if (this._checkKey(this._keyMap.FOCUS_TOOLBAR, ev)) { var h = this.toolbar.getElementsByTagName('h2')[0]; if (h && h.firstChild) { h.firstChild.focus(); } } else if (this._checkKey(this._keyMap.FOCUS_AFTER, ev)) { //Focus After Element - Esc this.afterElement.focus(); } Event.stopEvent(ev); doExec = false; break; //case 76: //L case this._keyMap.CREATE_LINK.key: //L if (this._hasSelection()) { if (this._checkKey(this._keyMap.CREATE_LINK, ev)) { var makeLink = true; if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('createlink')) { makeLink = false; } } if (makeLink) { this.execCommand('createlink', ''); this.toolbar.fireEvent('createlinkClick', { type: 'createlinkClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); doExec = false; } } } break; //case 90: //Z case this._keyMap.UNDO.key: case this._keyMap.REDO.key: if (this._checkKey(this._keyMap.REDO, ev)) { action = 'redo'; doExec = true; } else if (this._checkKey(this._keyMap.UNDO, ev)) { action = 'undo'; doExec = true; } break; //case 66: //B case this._keyMap.BOLD.key: if (this._checkKey(this._keyMap.BOLD, ev)) { action = 'bold'; doExec = true; } break; case this._keyMap.FONT_SIZE_UP.key: case this._keyMap.FONT_SIZE_DOWN.key: var uk = false, dk = false; if (this._checkKey(this._keyMap.FONT_SIZE_UP, ev)) { uk = true; } if (this._checkKey(this._keyMap.FONT_SIZE_DOWN, ev)) { dk = true; } if (uk || dk) { var fs_button = this.toolbar.getButtonByValue('fontsize'), label = parseInt(fs_button.get('label'), 10), newValue = (label + 1); if (dk) { newValue = (label - 1); } action = 'fontsize'; value = newValue + 'px'; doExec = true; } break; //case 73: //I case this._keyMap.ITALIC.key: if (this._checkKey(this._keyMap.ITALIC, ev)) { action = 'italic'; doExec = true; } break; //case 85: //U case this._keyMap.UNDERLINE.key: if (this._checkKey(this._keyMap.UNDERLINE, ev)) { action = 'underline'; doExec = true; } break; case 9: if (this.browser.ie) { //Insert a tab in Internet Explorer _range = this._getRange(); tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { if (_range) { _range.pasteHTML('    '); _range.collapse(false); _range.select(); } Event.stopEvent(ev); } } //Firefox 3 code if (this.browser.gecko > 1.8) { tar = this._getSelectedElement(); if (this._isElement(tar, 'li')) { if (ev.shiftKey) { this._getDoc().execCommand('outdent', null, ''); } else { this._getDoc().execCommand('indent', null, ''); } } else if (!this._hasSelection()) { this.execCommand('inserthtml', '    '); } Event.stopEvent(ev); } break; case 13: var p = null, i = 0; if (this.get('ptags') && !ev.shiftKey) { if (this.browser.gecko) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { if (this._hasParent(tar, 'p')) { p = this._getDoc().createElement('p'); p.innerHTML = ' '; Dom.insertAfter(p, tar); this._selectNode(p.firstChild); } else if (this._isElement(tar, 'body')) { this.execCommand('insertparagraph', null); var ps = this._getDoc().body.getElementsByTagName('p'); for (i = 0; i < ps.length; i++) { if (ps[i].getAttribute('_moz_dirty') !== null) { p = this._getDoc().createElement('p'); p.innerHTML = ' '; Dom.insertAfter(p, ps[i]); this._selectNode(p.firstChild); ps[i].removeAttribute('_moz_dirty'); } } } else { doExec = true; action = 'insertparagraph'; } Event.stopEvent(ev); } } if (this.browser.webkit) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { this.execCommand('insertparagraph', null); var divs = this._getDoc().body.getElementsByTagName('div'); for (i = 0; i < divs.length; i++) { if (!Dom.hasClass(divs[i], 'yui-wk-div')) { Dom.addClass(divs[i], 'yui-wk-p'); } } Event.stopEvent(ev); } } } else { if (this.browser.webkit) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { if (this.browser.webkit4) { this.execCommand('insertlinebreak'); } else { this.execCommand('inserthtml', ''); var holder = this._getDoc().getElementById('yui-br'), br = this._getDoc().createElement('br'), caret = this._getDoc().createElement('span'); holder.parentNode.replaceChild(br, holder); caret.className = 'yui-non'; caret.innerHTML = ' '; Dom.insertAfter(caret, br); this._selectNode(caret); } Event.stopEvent(ev); } } if (this.browser.ie) { //Insert a
          instead of a

          in Internet Explorer _range = this._getRange(); tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { if (_range) { _range.pasteHTML('
          '); _range.collapse(false); _range.select(); } Event.stopEvent(ev); } } } break; } if (this.browser.ie) { this._listFix(ev); } if (doExec && action) { this.execCommand(action, value); Event.stopEvent(ev); this.nodeChange(); } this._storeUndo(); this.fireEvent('editorKeyDown', { type: 'editorKeyDown', target: this, ev: ev }); }, /** * @private * @property _fixListRunning * @type Boolean * @description Keeps more than one _fixListDupIds from running at the same time. */ _fixListRunning: null, /** * @private * @method _fixListDupIds * @description Some browsers will duplicate the id of an LI when created in designMode. * This method will fix the duplicate id issue. However it will only preserve the first element * in the document list with the unique id. */ _fixListDupIds: function() { if (this._fixListRunning) { return false; } if (this._getDoc()) { this._fixListRunning = true; var lis = this._getDoc().body.getElementsByTagName('li'), i = 0, ids = {}; for (i = 0; i < lis.length; i++) { if (lis[i].id) { if (ids[lis[i].id]) { lis[i].id = ''; } ids[lis[i].id] = true; } } this._fixListRunning = false; } }, /** * @private * @method _listFix * @param {Event} ev The event we are working on. * @description Handles the Enter key, Tab Key and Shift + Tab keys for List Items. */ _listFix: function(ev) { var testLi = null, par = null, preContent = false, range = null; //Enter Key if (this.browser.webkit) { if (ev.keyCode && (ev.keyCode == 13)) { if (this._hasParent(this._getSelectedElement(), 'li')) { var tar = this._hasParent(this._getSelectedElement(), 'li'); if (tar.previousSibling) { if (tar.firstChild && (tar.firstChild.length == 1)) { this._selectNode(tar); } } } } } //Shift + Tab Key if (ev.keyCode && ((!this.browser.webkit3 && (ev.keyCode == 25)) || ((this.browser.webkit3 || !this.browser.webkit) && ((ev.keyCode == 9) && ev.shiftKey)))) { testLi = this._getSelectedElement(); if (this._hasParent(testLi, 'li')) { testLi = this._hasParent(testLi, 'li'); if (this._hasParent(testLi, 'ul') || this._hasParent(testLi, 'ol')) { par = this._hasParent(testLi, 'ul'); if (!par) { par = this._hasParent(testLi, 'ol'); } if (this._isElement(par.previousSibling, 'li')) { par.removeChild(testLi); par.parentNode.insertBefore(testLi, par.nextSibling); if (this.browser.ie) { range = this._getDoc().body.createTextRange(); range.moveToElementText(testLi); range.collapse(false); range.select(); } if (this.browser.webkit) { this._selectNode(testLi.firstChild); } Event.stopEvent(ev); } } } } //Tab Key if (ev.keyCode && ((ev.keyCode == 9) && (!ev.shiftKey))) { var preLi = this._getSelectedElement(); if (this._hasParent(preLi, 'li')) { preContent = this._hasParent(preLi, 'li').innerHTML; } if (this.browser.webkit) { this._getDoc().execCommand('inserttext', false, '\t'); } testLi = this._getSelectedElement(); if (this._hasParent(testLi, 'li')) { par = this._hasParent(testLi, 'li'); var newUl = this._getDoc().createElement(par.parentNode.tagName.toLowerCase()); if (this.browser.webkit) { var span = Dom.getElementsByClassName('Apple-tab-span', 'span', par); //Remove the span element that Safari puts in if (span[0]) { par.removeChild(span[0]); par.innerHTML = Lang.trim(par.innerHTML); //Put the HTML from the LI into this new LI if (preContent) { par.innerHTML = '' + preContent + ' '; } else { par.innerHTML = '  '; } } } else { if (preContent) { par.innerHTML = preContent + ' '; } else { par.innerHTML = ' '; } } par.parentNode.replaceChild(newUl, par); newUl.appendChild(par); if (this.browser.webkit) { this._getSelection().setBaseAndExtent(par.firstChild, 1, par.firstChild, par.firstChild.innerText.length); if (!this.browser.webkit3) { par.parentNode.parentNode.style.display = 'list-item'; setTimeout(function() { par.parentNode.parentNode.style.display = 'block'; }, 1); } } else if (this.browser.ie) { range = this._getDoc().body.createTextRange(); range.moveToElementText(par); range.collapse(false); range.select(); } else { this._selectNode(par); } Event.stopEvent(ev); } if (this.browser.webkit) { Event.stopEvent(ev); } this.nodeChange(); } }, /** * @method nodeChange * @param {Boolean} force Optional paramenter to skip the threshold counter * @description Handles setting up the toolbar buttons, getting the Dom path, fixing nodes. */ nodeChange: function(force) { var NCself = this; this._storeUndo(); if (this.get('nodeChangeDelay')) { this._nodeChangeDelayTimer = window.setTimeout(function() { NCself._nodeChangeDelayTimer = null; NCself._nodeChange.apply(NCself, arguments); }, 0); } else { this._nodeChange(); } }, /** * @private * @method _nodeChange * @param {Boolean} force Optional paramenter to skip the threshold counter * @description Fired from nodeChange in a setTimeout. */ _nodeChange: function(force) { var threshold = parseInt(this.get('nodeChangeThreshold'), 10), thisNodeChange = Math.round(new Date().getTime() / 1000), self = this; if (force === true) { this._lastNodeChange = 0; } if ((this._lastNodeChange + threshold) < thisNodeChange) { if (this._fixNodesTimer === null) { this._fixNodesTimer = window.setTimeout(function() { self._fixNodes.call(self); self._fixNodesTimer = null; }, 0); } } this._lastNodeChange = thisNodeChange; if (this.currentEvent) { try { this._lastNodeChangeEvent = this.currentEvent.type; } catch (e) {} } var beforeNodeChange = this.fireEvent('beforeNodeChange', { type: 'beforeNodeChange', target: this }); if (beforeNodeChange === false) { return false; } if (this.get('dompath')) { window.setTimeout(function() { self._writeDomPath.call(self); }, 0); } //Check to see if we are disabled before continuing if (!this.get('disabled')) { if (this.STOP_NODE_CHANGE) { //Reset this var for next action this.STOP_NODE_CHANGE = false; return false; } else { var sel = this._getSelection(), range = this._getRange(), el = this._getSelectedElement(), fn_button = this.toolbar.getButtonByValue('fontname'), fs_button = this.toolbar.getButtonByValue('fontsize'), undo_button = this.toolbar.getButtonByValue('undo'), redo_button = this.toolbar.getButtonByValue('redo'); //Handle updating the toolbar with active buttons var _ex = {}; if (this._lastButton) { _ex[this._lastButton.id] = true; //this._lastButton = null; } if (!this._isElement(el, 'body')) { if (fn_button) { _ex[fn_button.get('id')] = true; } if (fs_button) { _ex[fs_button.get('id')] = true; } } if (redo_button) { delete _ex[redo_button.get('id')]; } this.toolbar.resetAllButtons(_ex); //Handle disabled buttons for (var d = 0; d < this._disabled.length; d++) { var _button = this.toolbar.getButtonByValue(this._disabled[d]); if (_button && _button.get) { if (this._lastButton && (_button.get('id') === this._lastButton.id)) { //Skip } else { if (!this._hasSelection() && !this.get('insert')) { switch (this._disabled[d]) { case 'fontname': case 'fontsize': break; default: //No Selection - disable this.toolbar.disableButton(_button); } } else { if (!this._alwaysDisabled[this._disabled[d]]) { this.toolbar.enableButton(_button); } } if (!this._alwaysEnabled[this._disabled[d]]) { this.toolbar.deselectButton(_button); } } } } var path = this._getDomPath(); var tag = null, cmd = null; for (var i = 0; i < path.length; i++) { tag = path[i].tagName.toLowerCase(); if (path[i].getAttribute('tag')) { tag = path[i].getAttribute('tag').toLowerCase(); } cmd = this._tag2cmd[tag]; if (cmd === undefined) { cmd = []; } if (!Lang.isArray(cmd)) { cmd = [cmd]; } //Bold and Italic styles if (path[i].style.fontWeight.toLowerCase() == 'bold') { cmd[cmd.length] = 'bold'; } if (path[i].style.fontStyle.toLowerCase() == 'italic') { cmd[cmd.length] = 'italic'; } if (path[i].style.textDecoration.toLowerCase() == 'underline') { cmd[cmd.length] = 'underline'; } if (path[i].style.textDecoration.toLowerCase() == 'line-through') { cmd[cmd.length] = 'strikethrough'; } if (cmd.length > 0) { for (var j = 0; j < cmd.length; j++) { this.toolbar.selectButton(cmd[j]); this.toolbar.enableButton(cmd[j]); } } //Handle Alignment switch (path[i].style.textAlign.toLowerCase()) { case 'left': case 'right': case 'center': case 'justify': var alignType = path[i].style.textAlign.toLowerCase(); if (path[i].style.textAlign.toLowerCase() == 'justify') { alignType = 'full'; } this.toolbar.selectButton('justify' + alignType); this.toolbar.enableButton('justify' + alignType); break; } } //After for loop //Reset Font Family and Size to the inital configs if (fn_button) { var family = fn_button._configs.label._initialConfig.value; fn_button.set('label', '' + family + ''); this._updateMenuChecked('fontname', family); } if (fs_button) { fs_button.set('label', fs_button._configs.label._initialConfig.value); } var hd_button = this.toolbar.getButtonByValue('heading'); if (hd_button) { hd_button.set('label', hd_button._configs.label._initialConfig.value); this._updateMenuChecked('heading', 'none'); } var img_button = this.toolbar.getButtonByValue('insertimage'); if (img_button && this.currentWindow && (this.currentWindow.name == 'insertimage')) { this.toolbar.disableButton(img_button); } if (this._lastButton && this._lastButton.isSelected) { this.toolbar.deselectButton(this._lastButton.id); } this._undoNodeChange(); } } this.fireEvent('afterNodeChange', { type: 'afterNodeChange', target: this }); }, /** * @private * @method _updateMenuChecked * @param {Object} button The command identifier of the button you want to check * @param {String} value The value of the menu item you want to check * @param {YAHOO.widget.Toolbar} The Toolbar instance the button belongs to (defaults to this.toolbar) * @description Gets the menu from a button instance, if the menu is not rendered it will render it. It will then search the menu for the specified value, unchecking all other items and checking the specified on. */ _updateMenuChecked: function(button, value, tbar) { if (!tbar) { tbar = this.toolbar; } var _button = tbar.getButtonByValue(button); _button.checkValue(value); }, /** * @private * @method _handleToolbarClick * @param {Event} ev The event that triggered the button click * @description This is an event handler attached to the Toolbar's buttonClick event. It will fire execCommand with the command identifier from the Toolbar Button. */ _handleToolbarClick: function(ev) { var value = ''; var str = ''; var cmd = ev.button.value; if (ev.button.menucmd) { value = cmd; cmd = ev.button.menucmd; } this._lastButton = ev.button; if (this.STOP_EXEC_COMMAND) { this.STOP_EXEC_COMMAND = false; return false; } else { this.execCommand(cmd, value); if (!this.browser.webkit) { var Fself = this; setTimeout(function() { Fself.focus.call(Fself); }, 5); } } Event.stopEvent(ev); }, /** * @private * @method _setupAfterElement * @description Creates the accessibility h2 header and places it after the iframe in the Dom for navigation. */ _setupAfterElement: function() { if (!this.beforeElement) { this.beforeElement = document.createElement('h2'); this.beforeElement.className = 'yui-editor-skipheader'; this.beforeElement.tabIndex = '-1'; this.beforeElement.innerHTML = this.STR_BEFORE_EDITOR; this.get('element_cont').get('firstChild').insertBefore(this.beforeElement, this.toolbar.get('nextSibling')); } if (!this.afterElement) { this.afterElement = document.createElement('h2'); this.afterElement.className = 'yui-editor-skipheader'; this.afterElement.tabIndex = '-1'; this.afterElement.innerHTML = this.STR_LEAVE_EDITOR; this.get('element_cont').get('firstChild').appendChild(this.afterElement); } }, /** * @private * @method _disableEditor * @param {Boolean} disabled Pass true to disable, false to enable * @description Creates a mask to place over the Editor. */ _disableEditor: function(disabled) { var iframe, par, html, height; if (!this.get('disabled_iframe')) { iframe = this._createIframe(); iframe.set('id', 'disabled_' + this.get('iframe').get('id')); iframe.setStyle('height', '100%'); iframe.setStyle('display', 'none'); iframe.setStyle('visibility', 'visible'); this.set('disabled_iframe', iframe); par = this.get('iframe').get('parentNode'); par.appendChild(iframe.get('element')); } if (!iframe) { iframe = this.get('disabled_iframe'); } if (disabled) { this._orgIframe = this.get('iframe'); if (this.toolbar) { this.toolbar.set('disabled', true); } html = this.getEditorHTML(); height = this.get('iframe').get('offsetHeight'); iframe.setStyle('visibility', ''); iframe.setStyle('position', ''); iframe.setStyle('top', ''); iframe.setStyle('left', ''); this._orgIframe.setStyle('visibility', 'hidden'); this._orgIframe.setStyle('position', 'absolute'); this._orgIframe.setStyle('top', '-99999px'); this._orgIframe.setStyle('left', '-99999px'); this.set('iframe', iframe); this._setInitialContent(true); if (!this._mask) { this._mask = document.createElement('DIV'); Dom.addClass(this._mask, 'yui-editor-masked'); if (this.browser.ie) { this._mask.style.height = height + 'px'; } this.get('iframe').get('parentNode').appendChild(this._mask); } this.on('editorContentReloaded', function() { this._getDoc().body._rteLoaded = false; this.setEditorHTML(html); iframe.setStyle('display', 'block'); this.unsubscribeAll('editorContentReloaded'); }); } else { if (this._mask) { this._mask.parentNode.removeChild(this._mask); this._mask = null; if (this.toolbar) { this.toolbar.set('disabled', false); } iframe.setStyle('visibility', 'hidden'); iframe.setStyle('position', 'absolute'); iframe.setStyle('top', '-99999px'); iframe.setStyle('left', '-99999px'); this._orgIframe.setStyle('visibility', ''); this._orgIframe.setStyle('position', ''); this._orgIframe.setStyle('top', ''); this._orgIframe.setStyle('left', ''); this.set('iframe', this._orgIframe); this.focus(); var self = this; window.setTimeout(function() { self.nodeChange.call(self); }, 100); } } }, /** * @property SEP_DOMPATH * @description The value to place in between the Dom path items * @type String */ SEP_DOMPATH: '<', /** * @property STR_LEAVE_EDITOR * @description The accessibility string for the element after the iFrame * @type String */ STR_LEAVE_EDITOR: 'You have left the Rich Text Editor.', /** * @property STR_BEFORE_EDITOR * @description The accessibility string for the element before the iFrame * @type String */ STR_BEFORE_EDITOR: 'This text field can contain stylized text and graphics. To cycle through all formatting options, use the keyboard shortcut Shift + Escape to place focus on the toolbar and navigate between options with your arrow keys. To exit this text editor use the Escape key and continue tabbing.

          Common formatting keyboard shortcuts:

          • Control Shift B sets text to bold
          • Control Shift I sets text to italic
          • Control Shift U underlines text
          • Control Shift L adds an HTML link
          ', /** * @property STR_TITLE * @description The Title of the HTML document that is created in the iFrame * @type String */ STR_TITLE: 'Rich Text Area.', /** * @property STR_IMAGE_HERE * @description The text to place in the URL textbox when using the blankimage. * @type String */ STR_IMAGE_HERE: 'Image URL Here', /** * @property STR_IMAGE_URL * @description The label string for Image URL * @type String */ STR_IMAGE_URL: 'Image URL', /** * @property STR_LINK_URL * @description The label string for the Link URL. * @type String */ STR_LINK_URL: 'Link URL', /** * @protected * @property STOP_EXEC_COMMAND * @description Set to true when you want the default execCommand function to not process anything * @type Boolean */ STOP_EXEC_COMMAND: false, /** * @protected * @property STOP_NODE_CHANGE * @description Set to true when you want the default nodeChange function to not process anything * @type Boolean */ STOP_NODE_CHANGE: false, /** * @protected * @property CLASS_NOEDIT * @description CSS class applied to elements that are not editable. * @type String */ CLASS_NOEDIT: 'yui-noedit', /** * @protected * @property CLASS_CONTAINER * @description Default CSS class to apply to the editors container element * @type String */ CLASS_CONTAINER: 'yui-editor-container', /** * @protected * @property CLASS_EDITABLE * @description Default CSS class to apply to the editors iframe element * @type String */ CLASS_EDITABLE: 'yui-editor-editable', /** * @protected * @property CLASS_EDITABLE_CONT * @description Default CSS class to apply to the editors iframe's parent element * @type String */ CLASS_EDITABLE_CONT: 'yui-editor-editable-container', /** * @protected * @property CLASS_PREFIX * @description Default prefix for dynamically created class names * @type String */ CLASS_PREFIX: 'yui-editor', /** * @property browser * @description Standard browser detection * @type Object */ browser: function() { var br = YAHOO.env.ua; //Check for webkit3 if (br.webkit >= 420) { br.webkit3 = br.webkit; } else { br.webkit3 = 0; } if (br.webkit >= 530) { br.webkit4 = br.webkit; } else { br.webkit4 = 0; } br.mac = false; //Check for Mac if (navigator.userAgent.indexOf('Macintosh') !== -1) { br.mac = true; } return br; }(), /** * @method init * @description The Editor class' initialization method */ init: function(p_oElement, p_oAttributes) { if (!this._defaultToolbar) { this._defaultToolbar = { collapse: true, titlebar: 'Text Editing Tools', draggable: false, buttons: [ { group: 'fontstyle', label: 'Font Name and Size', buttons: [ { type: 'select', label: 'Arial', value: 'fontname', disabled: true, menu: [ { text: 'Arial', checked: true }, { text: 'Arial Black' }, { text: 'Comic Sans MS' }, { text: 'Courier New' }, { text: 'Lucida Console' }, { text: 'Tahoma' }, { text: 'Times New Roman' }, { text: 'Trebuchet MS' }, { text: 'Verdana' } ] }, { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true } ] }, { type: 'separator' }, { group: 'textstyle', label: 'Font Style', buttons: [ { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' }, { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' }, { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' }, { type: 'push', label: 'Strike Through', value: 'strikethrough' }, { type: 'separator' }, { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true }, { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true } ] }, { type: 'separator' }, { group: 'indentlist', label: 'Lists', buttons: [ { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' }, { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' } ] }, { type: 'separator' }, { group: 'insertitem', label: 'Insert Item', buttons: [ { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true }, { type: 'push', label: 'Insert Image', value: 'insertimage' } ] } ] }; } YAHOO.widget.SimpleEditor.superclass.init.call(this, p_oElement, p_oAttributes); YAHOO.widget.EditorInfo._instances[this.get('id')] = this; this.currentElement = []; this.on('contentReady', function() { this.DOMReady = true; this.fireQueue(); }, this, true); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the editor. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the editor. */ initAttributes: function(attr) { YAHOO.widget.SimpleEditor.superclass.initAttributes.call(this, attr); var self = this; /** * @config setDesignMode * @description Should the Editor set designMode on the document. Default: true. * @default true * @type Boolean */ this.setAttributeConfig('setDesignMode', { value: ((attr.setDesignMode === false) ? false : true) }); /** * @config nodeChangeDelay * @description Do we wrap the nodeChange method in a timeout for performance. Default: true. * @default true * @type Boolean */ this.setAttributeConfig('nodeChangeDelay', { value: ((attr.nodeChangeDelay === false) ? false : true) }); /** * @config maxUndo * @description The max number of undo levels to store. * @default 30 * @type Number */ this.setAttributeConfig('maxUndo', { writeOnce: true, value: attr.maxUndo || 30 }); /** * @config ptags * @description If true, the editor uses <P> tags instead of <br> tags. (Use Shift + Enter to get a <br>) * @default false * @type Boolean */ this.setAttributeConfig('ptags', { writeOnce: true, value: attr.ptags || false }); /** * @config insert * @description If true, selection is not required for: fontname, fontsize, forecolor, backcolor. * @default false * @type Boolean */ this.setAttributeConfig('insert', { writeOnce: true, value: attr.insert || false, method: function(insert) { if (insert) { var buttons = { fontname: true, fontsize: true, forecolor: true, backcolor: true }; var tmp = this._defaultToolbar.buttons; for (var i = 0; i < tmp.length; i++) { if (tmp[i].buttons) { for (var a = 0; a < tmp[i].buttons.length; a++) { if (tmp[i].buttons[a].value) { if (buttons[tmp[i].buttons[a].value]) { delete tmp[i].buttons[a].disabled; } } } } } } } }); /** * @config container * @description Used when dynamically creating the Editor from Javascript with no default textarea. * We will create one and place it in this container. If no container is passed we will append to document.body. * @default false * @type HTMLElement */ this.setAttributeConfig('container', { writeOnce: true, value: attr.container || false }); /** * @config plainText * @description Process the inital textarea data as if it was plain text. Accounting for spaces, tabs and line feeds. * @default false * @type Boolean */ this.setAttributeConfig('plainText', { writeOnce: true, value: attr.plainText || false }); /** * @private * @config iframe * @description Internal config for holding the iframe element. * @default null * @type HTMLElement */ this.setAttributeConfig('iframe', { value: null }); /** * @private * @config disabled_iframe * @description Internal config for holding the iframe element used when disabling the Editor. * @default null * @type HTMLElement */ this.setAttributeConfig('disabled_iframe', { value: null }); /** * @private * @depreciated - No longer used, should use this.get('element') * @config textarea * @description Internal config for holding the textarea element (replaced with element). * @default null * @type HTMLElement */ this.setAttributeConfig('textarea', { value: null, writeOnce: true }); /** * @config nodeChangeThreshold * @description The number of seconds that need to be in between nodeChange processing * @default 3 * @type Number */ this.setAttributeConfig('nodeChangeThreshold', { value: attr.nodeChangeThreshold || 3, validator: YAHOO.lang.isNumber }); /** * @config allowNoEdit * @description Should the editor check for non-edit fields. It should be noted that this technique is not perfect. If the user does the right things, they will still be able to make changes. * Such as highlighting an element below and above the content and hitting a toolbar button or a shortcut key. * @default false * @type Boolean */ this.setAttributeConfig('allowNoEdit', { value: attr.allowNoEdit || false, validator: YAHOO.lang.isBoolean }); /** * @config limitCommands * @description Should the Editor limit the allowed execCommands to the ones available in the toolbar. If true, then execCommand and keyboard shortcuts will fail if they are not defined in the toolbar. * @default false * @type Boolean */ this.setAttributeConfig('limitCommands', { value: attr.limitCommands || false, validator: YAHOO.lang.isBoolean }); /** * @config element_cont * @description Internal config for the editors container * @default false * @type HTMLElement */ this.setAttributeConfig('element_cont', { value: attr.element_cont }); /** * @private * @config editor_wrapper * @description The outter wrapper for the entire editor. * @default null * @type HTMLElement */ this.setAttributeConfig('editor_wrapper', { value: attr.editor_wrapper || null, writeOnce: true }); /** * @attribute height * @description The height of the editor iframe container, not including the toolbar.. * @default Best guessed size of the textarea, for best results use CSS to style the height of the textarea or pass it in as an argument * @type String */ this.setAttributeConfig('height', { value: attr.height || Dom.getStyle(self.get('element'), 'height'), method: function(height) { if (this._rendered) { //We have been rendered, change the height if (this.get('animate')) { var anim = new YAHOO.util.Anim(this.get('iframe').get('parentNode'), { height: { to: parseInt(height, 10) } }, 0.5); anim.animate(); } else { Dom.setStyle(this.get('iframe').get('parentNode'), 'height', height); } } } }); /** * @config autoHeight * @description Remove the scrollbars from the edit area and resize it to fit the content. It will not go any lower than the current config height. * @default false * @type Boolean || Number */ this.setAttributeConfig('autoHeight', { value: attr.autoHeight || false, method: function(a) { if (a) { if (this.get('iframe')) { this.get('iframe').get('element').setAttribute('scrolling', 'no'); } this.on('afterNodeChange', this._handleAutoHeight, this, true); this.on('editorKeyDown', this._handleAutoHeight, this, true); this.on('editorKeyPress', this._handleAutoHeight, this, true); } else { if (this.get('iframe')) { this.get('iframe').get('element').setAttribute('scrolling', 'auto'); } this.unsubscribe('afterNodeChange', this._handleAutoHeight); this.unsubscribe('editorKeyDown', this._handleAutoHeight); this.unsubscribe('editorKeyPress', this._handleAutoHeight); } } }); /** * @attribute width * @description The width of the editor container. * @default Best guessed size of the textarea, for best results use CSS to style the width of the textarea or pass it in as an argument * @type String */ this.setAttributeConfig('width', { value: attr.width || Dom.getStyle(this.get('element'), 'width'), method: function(width) { if (this._rendered) { //We have been rendered, change the width if (this.get('animate')) { var anim = new YAHOO.util.Anim(this.get('element_cont').get('element'), { width: { to: parseInt(width, 10) } }, 0.5); anim.animate(); } else { this.get('element_cont').setStyle('width', width); } } } }); /** * @attribute blankimage * @description The URL for the image placeholder to put in when inserting an image. * @default The yahooapis.com address for the current release + 'assets/blankimage.png' * @type String */ this.setAttributeConfig('blankimage', { value: attr.blankimage || this._getBlankImage() }); /** * @attribute css * @description The Base CSS used to format the content of the editor * @default
          html {
                          height: 95%;
                      }
                      body {
                          height: 100%;
                          padding: 7px; background-color: #fff; font:13px/1.22 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;
                      }
                      a {
                          color: blue;
                          text-decoration: underline;
                          cursor: pointer;
                      }
                      .warning-localfile {
                          border-bottom: 1px dashed red !important;
                      }
                      .yui-busy {
                          cursor: wait !important;
                      }
                      img.selected { //Safari image selection
                          border: 2px dotted #808080;
                      }
                      img {
                          cursor: pointer !important;
                          border: none;
                      }
                      
          * @type String */ this.setAttributeConfig('css', { value: attr.css || this._defaultCSS, writeOnce: true }); /** * @attribute html * @description The default HTML to be written to the iframe document before the contents are loaded (Note that the DOCTYPE attr will be added at render item) * @default This HTML requires a few things if you are to override:

          {TITLE}, {CSS}, {HIDDEN_CSS}, {EXTRA_CSS} and {CONTENT} need to be there, they are passed to YAHOO.lang.substitute to be replace with other strings.

          onload="document.body._rteLoaded = true;" : the onload statement must be there or the editor will not finish loading.

                          <html>
                              <head>
                                  <title>{TITLE}</title>
                                  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                                  <style>
                                  {CSS}
                                  </style>
                                  <style>
                                  {HIDDEN_CSS}
                                  </style>
                                  <style>
                                  {EXTRA_CSS}
                                  </style>
                              </head>
                          <body onload="document.body._rteLoaded = true;">
                          {CONTENT}
                          </body>
                          </html>
                          
          * @type String */ this.setAttributeConfig('html', { value: attr.html || '{TITLE}{CONTENT}', writeOnce: true }); /** * @attribute extracss * @description Extra user defined css to load after the default SimpleEditor CSS * @default '' * @type String */ this.setAttributeConfig('extracss', { value: attr.extracss || '', writeOnce: true }); /** * @attribute handleSubmit * @description Config handles if the editor will attach itself to the textareas parent form's submit handler. If it is set to true, the editor will attempt to attach a submit listener to the textareas parent form. Then it will trigger the editors save handler and place the new content back into the text area before the form is submitted. * @default false * @type Boolean */ this.setAttributeConfig('handleSubmit', { value: attr.handleSubmit || false, method: function(exec) { if (this.get('element').form) { if (!this._formButtons) { this._formButtons = []; } if (exec) { Event.on(this.get('element').form, 'submit', this._handleFormSubmit, this, true); var i = this.get('element').form.getElementsByTagName('input'); for (var s = 0; s < i.length; s++) { var type = i[s].getAttribute('type'); if (type && (type.toLowerCase() == 'submit')) { Event.on(i[s], 'click', this._handleFormButtonClick, this, true); this._formButtons[this._formButtons.length] = i[s]; } } } else { Event.removeListener(this.get('element').form, 'submit', this._handleFormSubmit); if (this._formButtons) { Event.removeListener(this._formButtons, 'click', this._handleFormButtonClick); } } } } }); /** * @attribute disabled * @description This will toggle the editor's disabled state. When the editor is disabled, designMode is turned off and a mask is placed over the iframe so no interaction can take place. All Toolbar buttons are also disabled so they cannot be used. * @default false * @type Boolean */ this.setAttributeConfig('disabled', { value: false, method: function(disabled) { if (this._rendered) { this._disableEditor(disabled); } } }); /** * @config saveEl * @description When save HTML is called, this element will be updated as well as the source of data. * @default element * @type HTMLElement */ this.setAttributeConfig('saveEl', { value: this.get('element') }); /** * @config toolbar_cont * @description Internal config for the toolbars container * @default false * @type Boolean */ this.setAttributeConfig('toolbar_cont', { value: null, writeOnce: true }); /** * @attribute toolbar * @description The default toolbar config. * @type Object */ this.setAttributeConfig('toolbar', { value: attr.toolbar || this._defaultToolbar, writeOnce: true, method: function(toolbar) { if (!toolbar.buttonType) { toolbar.buttonType = this._defaultToolbar.buttonType; } this._defaultToolbar = toolbar; } }); /** * @attribute animate * @description Should the editor animate window movements * @default false unless Animation is found, then true * @type Boolean */ this.setAttributeConfig('animate', { value: ((attr.animate) ? ((YAHOO.util.Anim) ? true : false) : false), validator: function(value) { var ret = true; if (!YAHOO.util.Anim) { ret = false; } return ret; } }); /** * @config panel * @description A reference to the panel we are using for windows. * @default false * @type Boolean */ this.setAttributeConfig('panel', { value: null, writeOnce: true, validator: function(value) { var ret = true; if (!YAHOO.widget.Overlay) { ret = false; } return ret; } }); /** * @attribute focusAtStart * @description Should we focus the window when the content is ready? * @default false * @type Boolean */ this.setAttributeConfig('focusAtStart', { value: attr.focusAtStart || false, writeOnce: true, method: function(fs) { if (fs) { this.on('editorContentLoaded', function() { var self = this; setTimeout(function() { self.focus.call(self); self.editorDirty = false; }, 400); }, this, true); } } }); /** * @attribute dompath * @description Toggle the display of the current Dom path below the editor * @default false * @type Boolean */ this.setAttributeConfig('dompath', { value: attr.dompath || false, method: function(dompath) { if (dompath && !this.dompath) { this.dompath = document.createElement('DIV'); this.dompath.id = this.get('id') + '_dompath'; Dom.addClass(this.dompath, 'dompath'); this.get('element_cont').get('firstChild').appendChild(this.dompath); if (this.get('iframe')) { this._writeDomPath(); } } else if (!dompath && this.dompath) { this.dompath.parentNode.removeChild(this.dompath); this.dompath = null; } } }); /** * @attribute markup * @description Should we try to adjust the markup for the following types: semantic, css, default or xhtml * @default "semantic" * @type String */ this.setAttributeConfig('markup', { value: attr.markup || 'semantic', validator: function(markup) { switch (markup.toLowerCase()) { case 'semantic': case 'css': case 'default': case 'xhtml': return true; } return false; } }); /** * @attribute removeLineBreaks * @description Should we remove linebreaks and extra spaces on cleanup * @default false * @type Boolean */ this.setAttributeConfig('removeLineBreaks', { value: attr.removeLineBreaks || false, validator: YAHOO.lang.isBoolean }); /** * @config drag * @description Set this config to make the Editor draggable, pass 'proxy' to make use YAHOO.util.DDProxy. * @type {Boolean/String} */ this.setAttributeConfig('drag', { writeOnce: true, value: attr.drag || false }); /** * @config resize * @description Set this to true to make the Editor Resizable with YAHOO.util.Resize. The default config is available: myEditor._resizeConfig * Animation will be ignored while performing this resize to allow for the dynamic change in size of the toolbar. * @type Boolean */ this.setAttributeConfig('resize', { writeOnce: true, value: attr.resize || false }); /** * @config filterWord * @description Attempt to filter out MS Word HTML from the Editor's output. * @type Boolean */ this.setAttributeConfig('filterWord', { value: attr.filterWord || false, validator: YAHOO.lang.isBoolean }); }, /** * @private * @method _getBlankImage * @description Retrieves the full url of the image to use as the blank image. * @return {String} The URL to the blank image */ _getBlankImage: function() { if (!this.DOMReady) { this._queue[this._queue.length] = ['_getBlankImage', arguments]; return ''; } var img = ''; if (!this._blankImageLoaded) { if (YAHOO.widget.EditorInfo.blankImage) { this.set('blankimage', YAHOO.widget.EditorInfo.blankImage); this._blankImageLoaded = true; } else { var div = document.createElement('div'); div.style.position = 'absolute'; div.style.top = '-9999px'; div.style.left = '-9999px'; div.className = this.CLASS_PREFIX + '-blankimage'; document.body.appendChild(div); img = YAHOO.util.Dom.getStyle(div, 'background-image'); img = img.replace('url(', '').replace(')', '').replace(/"/g, ''); //Adobe AIR Code img = img.replace('app:/', ''); this.set('blankimage', img); this._blankImageLoaded = true; div.parentNode.removeChild(div); YAHOO.widget.EditorInfo.blankImage = img; } } else { img = this.get('blankimage'); } return img; }, /** * @private * @method _handleAutoHeight * @description Handles resizing the editor's height based on the content */ _handleAutoHeight: function() { var doc = this._getDoc(), body = doc.body, docEl = doc.documentElement; var height = parseInt(Dom.getStyle(this.get('editor_wrapper'), 'height'), 10); var newHeight = body.scrollHeight; if (this.browser.webkit) { newHeight = docEl.scrollHeight; } if (newHeight < parseInt(this.get('height'), 10)) { newHeight = parseInt(this.get('height'), 10); } if ((height != newHeight) && (newHeight >= parseInt(this.get('height'), 10))) { var anim = this.get('animate'); this.set('animate', false); this.set('height', newHeight + 'px'); this.set('animate', anim); if (this.browser.ie) { //Internet Explorer needs this this.get('iframe').setStyle('height', '99%'); this.get('iframe').setStyle('zoom', '1'); var self = this; window.setTimeout(function() { self.get('iframe').setStyle('height', '100%'); }, 1); } } }, /** * @private * @property _formButtons * @description Array of buttons that are in the Editor's parent form (for handleSubmit) * @type Array */ _formButtons: null, /** * @private * @property _formButtonClicked * @description The form button that was clicked to submit the form. * @type HTMLElement */ _formButtonClicked: null, /** * @private * @method _handleFormButtonClick * @description The click listener assigned to each submit button in the Editor's parent form. * @param {Event} ev The click event */ _handleFormButtonClick: function(ev) { var tar = Event.getTarget(ev); this._formButtonClicked = tar; }, /** * @private * @method _handleFormSubmit * @description Handles the form submission. * @param {Object} ev The Form Submit Event */ _handleFormSubmit: function(ev) { this.saveHTML(); var form = this.get('element').form, tar = this._formButtonClicked || false; Event.removeListener(form, 'submit', this._handleFormSubmit); if (YAHOO.env.ua.ie) { //form.fireEvent("onsubmit"); if (tar && !tar.disabled) { tar.click(); } } else { // Gecko, Opera, and Safari if (tar && !tar.disabled) { tar.click(); } var oEvent = document.createEvent("HTMLEvents"); oEvent.initEvent("submit", true, true); form.dispatchEvent(oEvent); if (YAHOO.env.ua.webkit) { if (YAHOO.lang.isFunction(form.submit)) { form.submit(); } } } //2.6.0 //Removed this, not need since removing Safari 2.x //Event.stopEvent(ev); }, /** * @private * @method _handleFontSize * @description Handles the font size button in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleFontSize: function(o) { var button = this.toolbar.getButtonById(o.button.id); var value = button.get('label') + 'px'; this.execCommand('fontsize', value); return false; }, /** * @private * @description Handles the colorpicker buttons in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleColorPicker: function(o) { var cmd = o.button; var value = '#' + o.color; if ((cmd == 'forecolor') || (cmd == 'backcolor')) { this.execCommand(cmd, value); } }, /** * @private * @method _handleAlign * @description Handles the alignment buttons in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleAlign: function(o) { var cmd = null; for (var i = 0; i < o.button.menu.length; i++) { if (o.button.menu[i].value == o.button.value) { cmd = o.button.menu[i].value; } } var value = this._getSelection(); this.execCommand(cmd, value); return false; }, /** * @private * @method _handleAfterNodeChange * @description Fires after a nodeChange happens to setup the things that where reset on the node change (button state). */ _handleAfterNodeChange: function() { var path = this._getDomPath(), elm = null, family = null, fontsize = null, validFont = false, fn_button = this.toolbar.getButtonByValue('fontname'), fs_button = this.toolbar.getButtonByValue('fontsize'), hd_button = this.toolbar.getButtonByValue('heading'); for (var i = 0; i < path.length; i++) { elm = path[i]; var tag = elm.tagName.toLowerCase(); if (elm.getAttribute('tag')) { tag = elm.getAttribute('tag'); } family = elm.getAttribute('face'); if (Dom.getStyle(elm, 'font-family')) { family = Dom.getStyle(elm, 'font-family'); //Adobe AIR Code family = family.replace(/'/g, ''); } if (tag.substring(0, 1) == 'h') { if (hd_button) { for (var h = 0; h < hd_button._configs.menu.value.length; h++) { if (hd_button._configs.menu.value[h].value.toLowerCase() == tag) { hd_button.set('label', hd_button._configs.menu.value[h].text); } } this._updateMenuChecked('heading', tag); } } } if (fn_button) { for (var b = 0; b < fn_button._configs.menu.value.length; b++) { if (family && fn_button._configs.menu.value[b].text.toLowerCase() == family.toLowerCase()) { validFont = true; family = fn_button._configs.menu.value[b].text; //Put the proper menu name in the button } } if (!validFont) { family = fn_button._configs.label._initialConfig.value; } var familyLabel = '' + family + ''; if (fn_button.get('label') != familyLabel) { fn_button.set('label', familyLabel); this._updateMenuChecked('fontname', family); } } if (fs_button) { fontsize = parseInt(Dom.getStyle(elm, 'fontSize'), 10); if ((fontsize === null) || isNaN(fontsize)) { fontsize = fs_button._configs.label._initialConfig.value; } fs_button.set('label', ''+fontsize); } if (!this._isElement(elm, 'body') && !this._isElement(elm, 'img')) { this.toolbar.enableButton(fn_button); this.toolbar.enableButton(fs_button); this.toolbar.enableButton('forecolor'); this.toolbar.enableButton('backcolor'); } if (this._isElement(elm, 'img')) { if (YAHOO.widget.Overlay) { this.toolbar.enableButton('createlink'); } } if (this._hasParent(elm, 'blockquote')) { this.toolbar.selectButton('indent'); this.toolbar.disableButton('indent'); this.toolbar.enableButton('outdent'); } if (this._hasParent(elm, 'ol') || this._hasParent(elm, 'ul')) { this.toolbar.disableButton('indent'); } this._lastButton = null; }, /** * @private * @method _handleInsertImageClick * @description Opens the Image Properties Window when the insert Image button is clicked or an Image is Double Clicked. */ _handleInsertImageClick: function() { if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('insertimage')) { return false; } } this.toolbar.set('disabled', true); //Disable the toolbar when the prompt is showing var _handleAEC = function() { var el = this.currentElement[0], src = 'http://'; if (!el) { el = this._getSelectedElement(); } if (el) { if (el.getAttribute('src')) { src = el.getAttribute('src', 2); if (src.indexOf(this.get('blankimage')) != -1) { src = this.STR_IMAGE_HERE; } } } var str = prompt(this.STR_IMAGE_URL + ': ', src); if ((str !== '') && (str !== null)) { el.setAttribute('src', str); } else if (str === '') { el.parentNode.removeChild(el); this.currentElement = []; this.nodeChange(); } else if ((str === null)) { src = el.getAttribute('src', 2); if (src.indexOf(this.get('blankimage')) != -1) { el.parentNode.removeChild(el); this.currentElement = []; this.nodeChange(); } } this.closeWindow(); this.toolbar.set('disabled', false); this.unsubscribe('afterExecCommand', _handleAEC, this, true); }; this.on('afterExecCommand', _handleAEC, this, true); }, /** * @private * @method _handleInsertImageWindowClose * @description Handles the closing of the Image Properties Window. */ _handleInsertImageWindowClose: function() { this.nodeChange(); }, /** * @private * @method _isLocalFile * @param {String} url THe url/string to check * @description Checks to see if a string (href or img src) is possibly a local file reference.. */ _isLocalFile: function(url) { if ((url) && (url !== '') && ((url.indexOf('file:/') != -1) || (url.indexOf(':\\') != -1))) { return true; } return false; }, /** * @private * @method _handleCreateLinkClick * @description Handles the opening of the Link Properties Window when the Create Link button is clicked or an href is doubleclicked. */ _handleCreateLinkClick: function() { if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('createlink')) { return false; } } this.toolbar.set('disabled', true); //Disable the toolbar when the prompt is showing var _handleAEC = function() { var el = this.currentElement[0], url = ''; if (el) { if (el.getAttribute('href', 2) !== null) { url = el.getAttribute('href', 2); } } var str = prompt(this.STR_LINK_URL + ': ', url); if ((str !== '') && (str !== null)) { var urlValue = str; if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { //Found an @ sign, prefix with mailto: urlValue = 'mailto:' + urlValue; } else { /* :// not found adding */ if (urlValue.substring(0, 1) != '#') { //urlValue = 'http:/'+'/' + urlValue; } } } el.setAttribute('href', urlValue); } else if (str !== null) { var _span = this._getDoc().createElement('span'); _span.innerHTML = el.innerHTML; Dom.addClass(_span, 'yui-non'); el.parentNode.replaceChild(_span, el); } this.closeWindow(); this.toolbar.set('disabled', false); this.unsubscribe('afterExecCommand', _handleAEC, this, true); }; this.on('afterExecCommand', _handleAEC, this); }, /** * @private * @method _handleCreateLinkWindowClose * @description Handles the closing of the Link Properties Window. */ _handleCreateLinkWindowClose: function() { this.nodeChange(); this.currentElement = []; }, /** * @method render * @description Calls the private method _render in a setTimeout to allow for other things on the page to continue to load. */ render: function() { if (this._rendered) { return false; } if (!this.DOMReady) { this._queue[this._queue.length] = ['render', arguments]; return false; } if (this.get('element')) { if (this.get('element').tagName) { this._textarea = true; if (this.get('element').tagName.toLowerCase() !== 'textarea') { this._textarea = false; } } else { return false; } } else { return false; } this._rendered = true; var self = this; window.setTimeout(function() { self._render.call(self); }, 4); }, /** * @private * @method _render * @description Causes the toolbar and the editor to render and replace the textarea. */ _render: function() { var self = this; this.set('textarea', this.get('element')); this.get('element_cont').setStyle('display', 'none'); this.get('element_cont').addClass(this.CLASS_CONTAINER); this.set('iframe', this._createIframe()); window.setTimeout(function() { self._setInitialContent.call(self); }, 10); this.get('editor_wrapper').appendChild(this.get('iframe').get('element')); if (this.get('disabled')) { this._disableEditor(true); } var tbarConf = this.get('toolbar'); //Create Toolbar instance if (tbarConf instanceof Toolbar) { this.toolbar = tbarConf; //Set the toolbar to disabled until content is loaded this.toolbar.set('disabled', true); } else { //Set the toolbar to disabled until content is loaded tbarConf.disabled = true; this.toolbar = new Toolbar(this.get('toolbar_cont'), tbarConf); } this.fireEvent('toolbarLoaded', { type: 'toolbarLoaded', target: this.toolbar }); this.toolbar.on('toolbarCollapsed', function() { if (this.currentWindow) { this.moveWindow(); } }, this, true); this.toolbar.on('toolbarExpanded', function() { if (this.currentWindow) { this.moveWindow(); } }, this, true); this.toolbar.on('fontsizeClick', this._handleFontSize, this, true); this.toolbar.on('colorPickerClicked', function(o) { this._handleColorPicker(o); return false; //Stop the buttonClick event }, this, true); this.toolbar.on('alignClick', this._handleAlign, this, true); this.on('afterNodeChange', this._handleAfterNodeChange, this, true); this.toolbar.on('insertimageClick', this._handleInsertImageClick, this, true); this.on('windowinsertimageClose', this._handleInsertImageWindowClose, this, true); this.toolbar.on('createlinkClick', this._handleCreateLinkClick, this, true); this.on('windowcreatelinkClose', this._handleCreateLinkWindowClose, this, true); //Replace Textarea with editable area this.get('parentNode').replaceChild(this.get('element_cont').get('element'), this.get('element')); this.setStyle('visibility', 'hidden'); this.setStyle('position', 'absolute'); this.setStyle('top', '-9999px'); this.setStyle('left', '-9999px'); this.get('element_cont').appendChild(this.get('element')); this.get('element_cont').setStyle('display', 'block'); Dom.addClass(this.get('iframe').get('parentNode'), this.CLASS_EDITABLE_CONT); this.get('iframe').addClass(this.CLASS_EDITABLE); //Set height and width of editor container this.get('element_cont').setStyle('width', this.get('width')); Dom.setStyle(this.get('iframe').get('parentNode'), 'height', this.get('height')); this.get('iframe').setStyle('width', '100%'); //WIDTH this.get('iframe').setStyle('height', '100%'); this._setupDD(); window.setTimeout(function() { self._setupAfterElement.call(self); }, 0); this.fireEvent('afterRender', { type: 'afterRender', target: this }); }, /** * @method execCommand * @param {String} action The "execCommand" action to try to execute (Example: bold, insertimage, inserthtml) * @param {String} value (optional) The value for a given action such as action: fontname value: 'Verdana' * @description This method attempts to try and level the differences in the various browsers and their support for execCommand actions */ execCommand: function(action, value) { var beforeExec = this.fireEvent('beforeExecCommand', { type: 'beforeExecCommand', target: this, args: arguments }); if ((beforeExec === false) || (this.STOP_EXEC_COMMAND)) { this.STOP_EXEC_COMMAND = false; return false; } this._lastCommand = action; this._setMarkupType(action); if (this.browser.ie) { this._getWindow().focus(); } var exec = true; if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue(action)) { exec = false; } } this.editorDirty = true; if ((typeof this['cmd_' + action.toLowerCase()] == 'function') && exec) { var retValue = this['cmd_' + action.toLowerCase()](value); exec = retValue[0]; if (retValue[1]) { action = retValue[1]; } if (retValue[2]) { value = retValue[2]; } } if (exec) { try { this._getDoc().execCommand(action, false, value); } catch(e) { } } else { } this.on('afterExecCommand', function() { this.unsubscribeAll('afterExecCommand'); this.nodeChange(); }, this, true); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); }, /* {{{ Command Overrides */ /** * @method cmd_bold * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('bold') is used. */ cmd_bold: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span') && this._hasSelection()) { if (el.style.fontWeight == 'bold') { el.style.fontWeight = ''; var b = this._getDoc().createElement('b'), par = el.parentNode; par.replaceChild(b, el); b.appendChild(el); } } } return [true]; }, /** * @method cmd_italic * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('italic') is used. */ cmd_italic: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span') && this._hasSelection()) { if (el.style.fontStyle == 'italic') { el.style.fontStyle = ''; var i = this._getDoc().createElement('i'), par = el.parentNode; par.replaceChild(i, el); i.appendChild(el); } } } return [true]; }, /** * @method cmd_underline * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('underline') is used. */ cmd_underline: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span')) { if (el.style.textDecoration == 'underline') { el.style.textDecoration = 'none'; } else { el.style.textDecoration = 'underline'; } return [false]; } } return [true]; }, /** * @method cmd_backcolor * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('backcolor') is used. */ cmd_backcolor: function(value) { var exec = true, el = this._getSelectedElement(), action = 'backcolor'; if (this.browser.gecko || this.browser.opera) { this._setEditorStyle(true); action = 'hilitecolor'; } if (!this._isElement(el, 'body') && !this._hasSelection()) { el.style.backgroundColor = value; this._selectNode(el); exec = false; } else { if (this.get('insert')) { el = this._createInsertElement({ backgroundColor: value }); } else { this._createCurrentElement('span', { backgroundColor: value, color: el.style.color, fontSize: el.style.fontSize, fontFamily: el.style.fontFamily }); this._selectNode(this.currentElement[0]); } exec = false; } return [exec, action]; }, /** * @method cmd_forecolor * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('forecolor') is used. */ cmd_forecolor: function(value) { var exec = true, el = this._getSelectedElement(); if (!this._isElement(el, 'body') && !this._hasSelection()) { Dom.setStyle(el, 'color', value); this._selectNode(el); exec = false; } else { if (this.get('insert')) { el = this._createInsertElement({ color: value }); } else { this._createCurrentElement('span', { color: value, fontSize: el.style.fontSize, fontFamily: el.style.fontFamily, backgroundColor: el.style.backgroundColor }); this._selectNode(this.currentElement[0]); } exec = false; } return [exec]; }, /** * @method cmd_unlink * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('unlink') is used. */ cmd_unlink: function(value) { this._swapEl(this.currentElement[0], 'span', function(el) { el.className = 'yui-non'; }); return [false]; }, /** * @method cmd_createlink * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('createlink') is used. */ cmd_createlink: function(value) { var el = this._getSelectedElement(), _a = null; if (this._hasParent(el, 'a')) { this.currentElement[0] = this._hasParent(el, 'a'); } else if (this._isElement(el, 'li')) { _a = this._getDoc().createElement('a'); _a.innerHTML = el.innerHTML; el.innerHTML = ''; el.appendChild(_a); this.currentElement[0] = _a; } else if (!this._isElement(el, 'a')) { this._createCurrentElement('a'); _a = this._swapEl(this.currentElement[0], 'a'); this.currentElement[0] = _a; } else { this.currentElement[0] = el; } return [false]; }, /** * @method cmd_insertimage * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertimage') is used. */ cmd_insertimage: function(value) { var exec = true, _img = null, action = 'insertimage', el = this._getSelectedElement(); if (value === '') { value = this.get('blankimage'); } /* * @knownissue Safari Cursor Position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ if (this._isElement(el, 'img')) { this.currentElement[0] = el; exec = false; } else { if (this._getDoc().queryCommandEnabled(action)) { this._getDoc().execCommand(action, false, value); var imgs = this._getDoc().getElementsByTagName('img'); for (var i = 0; i < imgs.length; i++) { if (!YAHOO.util.Dom.hasClass(imgs[i], 'yui-img')) { YAHOO.util.Dom.addClass(imgs[i], 'yui-img'); this.currentElement[0] = imgs[i]; } } exec = false; } else { if (el == this._getDoc().body) { _img = this._getDoc().createElement('img'); _img.setAttribute('src', value); YAHOO.util.Dom.addClass(_img, 'yui-img'); this._getDoc().body.appendChild(_img); } else { this._createCurrentElement('img'); _img = this._getDoc().createElement('img'); _img.setAttribute('src', value); YAHOO.util.Dom.addClass(_img, 'yui-img'); this.currentElement[0].parentNode.replaceChild(_img, this.currentElement[0]); } this.currentElement[0] = _img; exec = false; } } return [exec]; }, /** * @method cmd_inserthtml * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('inserthtml') is used. */ cmd_inserthtml: function(value) { var exec = true, action = 'inserthtml', _span = null, _range = null; /* * @knownissue Safari cursor position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ if (this.browser.webkit && !this._getDoc().queryCommandEnabled(action)) { this._createCurrentElement('img'); _span = this._getDoc().createElement('span'); _span.innerHTML = value; this.currentElement[0].parentNode.replaceChild(_span, this.currentElement[0]); exec = false; } else if (this.browser.ie) { _range = this._getRange(); if (_range.item) { _range.item(0).outerHTML = value; } else { _range.pasteHTML(value); } exec = false; } return [exec]; }, /** * @method cmd_list * @param tag The tag of the list you want to create (eg, ul or ol) * @description This is a combined execCommand override method. It is called from the cmd_insertorderedlist and cmd_insertunorderedlist methods. */ cmd_list: function(tag) { var exec = true, list = null, li = 0, el = null, str = '', selEl = this._getSelectedElement(), action = 'insertorderedlist'; if (tag == 'ul') { action = 'insertunorderedlist'; } /* * @knownissue Safari 2.+ doesn't support ordered and unordered lists * @browser Safari 2.x * The issue with this workaround is that when applied to a set of text * that has BR's in it, Safari may or may not pick up the individual items as * list items. This is fixed in WebKit (Safari 3) * 2.6.0: Seems there are still some issues with List Creation and Safari 3, reverting to previously working Safari 2.x code */ //if ((this.browser.webkit && !this._getDoc().queryCommandEnabled(action))) { if ((this.browser.webkit && !this.browser.webkit4) || (this.browser.opera)) { if (this._isElement(selEl, 'li') && this._isElement(selEl.parentNode, tag)) { el = selEl.parentNode; list = this._getDoc().createElement('span'); YAHOO.util.Dom.addClass(list, 'yui-non'); str = ''; var lis = el.getElementsByTagName('li'), p_tag = ((this.browser.opera && this.get('ptags')) ? 'p' : 'div'); for (li = 0; li < lis.length; li++) { str += '<' + p_tag + '>' + lis[li].innerHTML + ''; } list.innerHTML = str; this.currentElement[0] = el; this.currentElement[0].parentNode.replaceChild(list, this.currentElement[0]); } else { this._createCurrentElement(tag.toLowerCase()); list = this._getDoc().createElement(tag); for (li = 0; li < this.currentElement.length; li++) { var newli = this._getDoc().createElement('li'); newli.innerHTML = this.currentElement[li].innerHTML + '  '; list.appendChild(newli); if (li > 0) { this.currentElement[li].parentNode.removeChild(this.currentElement[li]); } } var b_tag = ((this.browser.opera) ? '
          ' : '
          '), items = list.firstChild.innerHTML.split(b_tag), i, item; if (items.length > 0) { list.innerHTML = ''; for (i = 0; i < items.length; i++) { item = this._getDoc().createElement('li'); item.innerHTML = items[i]; list.appendChild(item); } } this.currentElement[0].parentNode.replaceChild(list, this.currentElement[0]); this.currentElement[0] = list; var _h = this.currentElement[0].firstChild; _h = Dom.getElementsByClassName('yui-non', 'span', _h)[0]; if (this.browser.webkit) { this._getSelection().setBaseAndExtent(_h, 1, _h, _h.innerText.length); } } exec = false; } else { el = this._getSelectedElement(); if (this._isElement(el, 'li') && this._isElement(el.parentNode, tag) || (this.browser.ie && this._isElement(this._getRange().parentElement, 'li')) || (this.browser.ie && this._isElement(el, 'ul')) || (this.browser.ie && this._isElement(el, 'ol'))) { //we are in a list.. if (this.browser.ie) { if ((this.browser.ie && this._isElement(el, 'ul')) || (this.browser.ie && this._isElement(el, 'ol'))) { el = el.getElementsByTagName('li')[0]; } str = ''; var lis2 = el.parentNode.getElementsByTagName('li'); for (var j = 0; j < lis2.length; j++) { str += lis2[j].innerHTML + '
          '; } var newEl = this._getDoc().createElement('span'); newEl.innerHTML = str; el.parentNode.parentNode.replaceChild(newEl, el.parentNode); } else { this.nodeChange(); this._getDoc().execCommand(action, '', el.parentNode); this.nodeChange(); } exec = false; } if (this.browser.opera) { var self = this; window.setTimeout(function() { var liso = self._getDoc().getElementsByTagName('li'); for (var i = 0; i < liso.length; i++) { if (liso[i].innerHTML.toLowerCase() == '
          ') { liso[i].parentNode.parentNode.removeChild(liso[i].parentNode); } } },30); } if (this.browser.ie && exec) { var html = ''; if (this._getRange().html) { html = '
        • ' + this._getRange().html+ '
        • '; } else { var t = this._getRange().text.split('\n'); if (t.length > 1) { html = ''; for (var ie = 0; ie < t.length; ie++) { html += '
        • ' + t[ie] + '
        • '; } } else { var txt = this._getRange().text; if (txt === '') { html = '
        • ' + txt + '
        • '; } else { html = '
        • ' + txt + '
        • '; } } } this._getRange().pasteHTML('<' + tag + '>' + html + ''); var new_item = this._getDoc().getElementById('new_list_item'); if (new_item) { var range = this._getDoc().body.createTextRange(); range.moveToElementText(new_item); range.collapse(false); range.select(); new_item.id = ''; } exec = false; } } return exec; }, /** * @method cmd_insertorderedlist * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertorderedlist ') is used. */ cmd_insertorderedlist: function(value) { return [this.cmd_list('ol')]; }, /** * @method cmd_insertunorderedlist * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertunorderedlist') is used. */ cmd_insertunorderedlist: function(value) { return [this.cmd_list('ul')]; }, /** * @method cmd_fontname * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('fontname') is used. */ cmd_fontname: function(value) { var exec = true, selEl = this._getSelectedElement(); this.currentFont = value; if (selEl && selEl.tagName && !this._hasSelection() && !this._isElement(selEl, 'body') && !this.get('insert')) { YAHOO.util.Dom.setStyle(selEl, 'font-family', value); exec = false; } else if (this.get('insert') && !this._hasSelection()) { var el = this._createInsertElement({ fontFamily: value }); exec = false; } return [exec]; }, /** * @method cmd_fontsize * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('fontsize') is used. */ cmd_fontsize: function(value) { var el = null, go = true; el = this._getSelectedElement(); if (this.browser.webkit) { if (this.currentElement[0]) { if (el == this.currentElement[0]) { go = false; YAHOO.util.Dom.setStyle(el, 'fontSize', value); this._selectNode(el); this.currentElement[0] = el; } } } if (go) { if (!this._isElement(this._getSelectedElement(), 'body') && (!this._hasSelection())) { el = this._getSelectedElement(); YAHOO.util.Dom.setStyle(el, 'fontSize', value); if (this.get('insert') && this.browser.ie) { var r = this._getRange(); r.collapse(false); r.select(); } else { this._selectNode(el); } } else if (this.currentElement && (this.currentElement.length > 0) && (!this._hasSelection()) && (!this.get('insert'))) { YAHOO.util.Dom.setStyle(this.currentElement, 'fontSize', value); } else { if (this.get('insert') && !this._hasSelection()) { el = this._createInsertElement({ fontSize: value }); this.currentElement[0] = el; this._selectNode(this.currentElement[0]); } else { this._createCurrentElement('span', {'fontSize': value, fontFamily: el.style.fontFamily, color: el.style.color, backgroundColor: el.style.backgroundColor }); this._selectNode(this.currentElement[0]); } } } return [false]; }, /* }}} */ /** * @private * @method _swapEl * @param {HTMLElement} el The element to swap with * @param {String} tagName The tagname of the element that you wish to create * @param {Function} callback (optional) A function to run on the element after it is created, but before it is replaced. An element reference is passed to this function. * @description This function will create a new element in the DOM and populate it with the contents of another element. Then it will assume it's place. */ _swapEl: function(el, tagName, callback) { var _el = this._getDoc().createElement(tagName); if (el) { _el.innerHTML = el.innerHTML; } if (typeof callback == 'function') { callback.call(this, _el); } if (el) { el.parentNode.replaceChild(_el, el); } return _el; }, /** * @private * @method _createInsertElement * @description Creates a new "currentElement" then adds some text (and other things) to make it selectable and stylable. Then the user can continue typing. * @param {Object} css (optional) Object literal containing styles to apply to the new element. * @return {HTMLElement} */ _createInsertElement: function(css) { this._createCurrentElement('span', css); var el = this.currentElement[0]; if (this.browser.webkit) { //Little Safari Hackery here.. el.innerHTML = ' '; el = el.firstChild; this._getSelection().setBaseAndExtent(el, 1, el, el.innerText.length); } else if (this.browser.ie || this.browser.opera) { el.innerHTML = ' '; } this.focus(); this._selectNode(el, true); return el; }, /** * @private * @method _createCurrentElement * @param {String} tagName (optional defaults to a) The tagname of the element that you wish to create * @param {Object} tagStyle (optional) Object literal containing styles to apply to the new element. * @description This is a work around for the various browser issues with execCommand. This method will run execCommand('fontname', false, 'yui-tmp') on the given selection. * It will then search the document for an element with the font-family set to yui-tmp and replace that with another span that has other information in it, then assign the new span to the * this.currentElement array, so we now have element references to the elements that were just modified. At this point we can use standard DOM manipulation to change them as we see fit. */ _createCurrentElement: function(tagName, tagStyle) { tagName = ((tagName) ? tagName : 'a'); var tar = null, el = [], _doc = this._getDoc(); if (this.currentFont) { if (!tagStyle) { tagStyle = {}; } tagStyle.fontFamily = this.currentFont; this.currentFont = null; } this.currentElement = []; var _elCreate = function(tagName, tagStyle) { var el = null; tagName = ((tagName) ? tagName : 'span'); tagName = tagName.toLowerCase(); switch (tagName) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': el = _doc.createElement(tagName); break; default: el = _doc.createElement(tagName); if (tagName === 'span') { YAHOO.util.Dom.addClass(el, 'yui-tag-' + tagName); YAHOO.util.Dom.addClass(el, 'yui-tag'); el.setAttribute('tag', tagName); } for (var k in tagStyle) { if (YAHOO.lang.hasOwnProperty(tagStyle, k)) { el.style[k] = tagStyle[k]; } } break; } return el; }; if (!this._hasSelection()) { if (this._getDoc().queryCommandEnabled('insertimage')) { this._getDoc().execCommand('insertimage', false, 'yui-tmp-img'); var imgs = this._getDoc().getElementsByTagName('img'); for (var j = 0; j < imgs.length; j++) { if (imgs[j].getAttribute('src', 2) == 'yui-tmp-img') { el = _elCreate(tagName, tagStyle); imgs[j].parentNode.replaceChild(el, imgs[j]); this.currentElement[this.currentElement.length] = el; } } } else { if (this.currentEvent) { tar = YAHOO.util.Event.getTarget(this.currentEvent); } else { //For Safari.. tar = this._getDoc().body; } } if (tar) { /* * @knownissue Safari Cursor Position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ el = _elCreate(tagName, tagStyle); if (this._isElement(tar, 'body') || this._isElement(tar, 'html')) { if (this._isElement(tar, 'html')) { tar = this._getDoc().body; } tar.appendChild(el); } else if (tar.nextSibling) { tar.parentNode.insertBefore(el, tar.nextSibling); } else { tar.parentNode.appendChild(el); } //this.currentElement = el; this.currentElement[this.currentElement.length] = el; this.currentEvent = null; if (this.browser.webkit) { //Force Safari to focus the new element this._getSelection().setBaseAndExtent(el, 0, el, 0); if (this.browser.webkit3) { this._getSelection().collapseToStart(); } else { this._getSelection().collapse(true); } } } } else { //Force CSS Styling for this action... this._setEditorStyle(true); this._getDoc().execCommand('fontname', false, 'yui-tmp'); var _tmp = [], __tmp, __els = ['font', 'span', 'i', 'b', 'u']; if (!this._isElement(this._getSelectedElement(), 'body')) { __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().tagName); __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().parentNode.tagName); } for (var _els = 0; _els < __els.length; _els++) { var _tmp1 = this._getDoc().getElementsByTagName(__els[_els]); for (var e = 0; e < _tmp1.length; e++) { _tmp[_tmp.length] = _tmp1[e]; } } for (var i = 0; i < _tmp.length; i++) { if ((YAHOO.util.Dom.getStyle(_tmp[i], 'font-family') == 'yui-tmp') || (_tmp[i].face && (_tmp[i].face == 'yui-tmp'))) { if (tagName !== 'span') { el = _elCreate(tagName, tagStyle); } else { el = _elCreate(_tmp[i].tagName, tagStyle); } el.innerHTML = _tmp[i].innerHTML; if (this._isElement(_tmp[i], 'ol') || (this._isElement(_tmp[i], 'ul'))) { var fc = _tmp[i].getElementsByTagName('li')[0]; _tmp[i].style.fontFamily = 'inherit'; fc.style.fontFamily = 'inherit'; el.innerHTML = fc.innerHTML; fc.innerHTML = ''; fc.appendChild(el); this.currentElement[this.currentElement.length] = el; } else if (this._isElement(_tmp[i], 'li')) { _tmp[i].innerHTML = ''; _tmp[i].appendChild(el); _tmp[i].style.fontFamily = 'inherit'; this.currentElement[this.currentElement.length] = el; } else { if (_tmp[i].parentNode) { _tmp[i].parentNode.replaceChild(el, _tmp[i]); this.currentElement[this.currentElement.length] = el; this.currentEvent = null; if (this.browser.webkit) { //Force Safari to focus the new element this._getSelection().setBaseAndExtent(el, 0, el, 0); if (this.browser.webkit3) { this._getSelection().collapseToStart(); } else { this._getSelection().collapse(true); } } if (this.browser.ie && tagStyle && tagStyle.fontSize) { this._getSelection().empty(); } if (this.browser.gecko) { this._getSelection().collapseToStart(); } } } } } var len = this.currentElement.length; for (var o = 0; o < len; o++) { if ((o + 1) != len) { //Skip the last one in the list if (this.currentElement[o] && this.currentElement[o].nextSibling) { if (this._isElement(this.currentElement[o], 'br')) { this.currentElement[this.currentElement.length] = this.currentElement[o].nextSibling; } } } } } }, /** * @method saveHTML * @description Cleans the HTML with the cleanHTML method then places that string back into the textarea. * @return String */ saveHTML: function() { var html = this.cleanHTML(); if (this._textarea) { this.get('element').value = html; } else { this.get('element').innerHTML = html; } if (this.get('saveEl') !== this.get('element')) { var out = this.get('saveEl'); if (Lang.isString(out)) { out = Dom.get(out); } if (out) { if (out.tagName.toLowerCase() === 'textarea') { out.value = html; } else { out.innerHTML = html; } } } return html; }, /** * @method setEditorHTML * @param {String} incomingHTML The html content to load into the editor * @description Loads HTML into the editors body */ setEditorHTML: function(incomingHTML) { var html = this._cleanIncomingHTML(incomingHTML); html = html.replace(/RIGHT_BRACKET/gi, '{'); html = html.replace(/LEFT_BRACKET/gi, '}'); this._getDoc().body.innerHTML = html; this.nodeChange(); }, /** * @method getEditorHTML * @description Gets the unprocessed/unfiltered HTML from the editor */ getEditorHTML: function() { try { var b = this._getDoc().body; if (b === null) { return null; } return this._getDoc().body.innerHTML; } catch (e) { return ''; } }, /** * @method show * @description This method needs to be called if the Editor was hidden (like in a TabView or Panel). It is used to reset the editor after being in a container that was set to display none. */ show: function() { if (this.browser.gecko) { this._setDesignMode('on'); this.focus(); } if (this.browser.webkit) { var self = this; window.setTimeout(function() { self._setInitialContent.call(self); }, 10); } //Adding this will close all other Editor window's when showing this one. if (this.currentWindow) { this.closeWindow(); } //Put the iframe back in place this.get('iframe').setStyle('position', 'static'); this.get('iframe').setStyle('left', ''); }, /** * @method hide * @description This method needs to be called if the Editor is to be hidden (like in a TabView or Panel). It should be called to clear timeouts and close open editor windows. */ hide: function() { //Adding this will close all other Editor window's. if (this.currentWindow) { this.closeWindow(); } if (this._fixNodesTimer) { clearTimeout(this._fixNodesTimer); this._fixNodesTimer = null; } if (this._nodeChangeTimer) { clearTimeout(this._nodeChangeTimer); this._nodeChangeTimer = null; } this._lastNodeChange = 0; //Move the iframe off of the screen, so that in containers with visiblity hidden, IE will not cover other elements. this.get('iframe').setStyle('position', 'absolute'); this.get('iframe').setStyle('left', '-9999px'); }, /** * @method _cleanIncomingHTML * @param {String} html The unfiltered HTML * @description Process the HTML with a few regexes to clean it up and stabilize the input * @return {String} The filtered HTML */ _cleanIncomingHTML: function(html) { html = html.replace(/{/gi, 'RIGHT_BRACKET'); html = html.replace(/}/gi, 'LEFT_BRACKET'); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/strong>/gi, ''); //replace embed before em check html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/embed>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/em>/gi, ''); html = html.replace(/_moz_dirty=""/gi, ''); //Put embed tags back in.. html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/YUI_EMBED>/gi, ''); if (this.get('plainText')) { html = html.replace(/\n/g, '
          ').replace(/\r/g, '
          '); html = html.replace(/ /gi, '  '); //Replace all double spaces html = html.replace(/\t/gi, '    '); //Replace all tabs } //Removing Script Tags from the Editor html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/script([^>]*)>/gi, ''); html = html.replace(/<script([^>]*)>/gi, ''); html = html.replace(/<\/script([^>]*)>/gi, ''); //Replace the line feeds html = html.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\r/g, ''); //Remove Bad HTML elements (used to be script nodes) html = html.replace(new RegExp(']*)>(.*?)<\/bad>', 'gi'), ''); //Replace the lines feeds html = html.replace(//g, '\n'); return html; }, /** * @method cleanHTML * @param {String} html The unfiltered HTML * @description Process the HTML with a few regexes to clean it up and stabilize the output * @return {String} The filtered HTML */ cleanHTML: function(html) { //Start Filtering Output //Begin RegExs.. if (!html) { html = this.getEditorHTML(); } var markup = this.get('markup'); //Make some backups... html = this.pre_filter_linebreaks(html, markup); //Filter MS Word html = this.filter_msword(html); html = html.replace(/]*)\/>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/]*)\/>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/ul>/gi, '<\/YUI_UL>'); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/blockquote>/gi, '<\/YUI_BQ>'); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/embed>/gi, '<\/YUI_EMBED>'); //Convert b and i tags to strong and em tags if ((markup == 'semantic') || (markup == 'xhtml')) { //html = html.replace(/]*)?>/gi, ""); html = html.replace(/]*)>/gi, ""); html = html.replace(/<\/i>/gi, ''); //html = html.replace(/]*)?>/gi, ""); html = html.replace(/]*)>/gi, ""); html = html.replace(/<\/b>/gi, ''); } html = html.replace(/_moz_dirty=""/gi, ''); //normalize strikethrough html = html.replace(//gi, '/span>'); //Case Changing if (this.browser.ie) { html = html.replace(/text-decoration/gi, 'text-decoration'); html = html.replace(/font-weight/gi, 'font-weight'); html = html.replace(/_width="([^>]*)"/gi, ''); html = html.replace(/_height="([^>]*)"/gi, ''); //Cleanup Image URL's var url = this._baseHREF.replace(/\//gi, '\\/'), re = new RegExp('src="' + url, 'gi'); html = html.replace(re, 'src="'); } html = html.replace(//gi, ''); html = html.replace(//gi, ''); if ((markup == 'semantic') || (markup == 'xhtml') || (markup == 'css')) { html = html.replace(new RegExp(']*)face="([^>]*)">(.*?)<\/font>', 'gi'), '$3'); html = html.replace(/([^>]*)<\/span>', 'gi'), '$1'); html = html.replace(new RegExp('([^>]*)<\/span>', 'gi'), '$1'); } html = html.replace(/\/u>/gi, '/span>'); if (markup == 'css') { html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/em>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/strong>/gi, ''); html = html.replace(//gi, '/span>'); html = html.replace(//gi, '/span>'); } html = html.replace(/ /gi, ' '); //Replace all double spaces and replace with a single } else { html = html.replace(//gi, '/u>'); } html = html.replace(/]*)>/gi, ''); html = html.replace(/\/ol>/gi, '/ol>'); html = html.replace(/
        • /gi, '/li>'); html = this.filter_safari(html); html = this.filter_internals(html); html = this.filter_all_rgb(html); //Replace our backups with the real thing html = this.post_filter_linebreaks(html, markup); if (markup == 'xhtml') { html = html.replace(/]*)>/g, ''); html = html.replace(/]*)>/g, ''); } else { html = html.replace(/]*)>/g, ''); html = html.replace(/]*)>/g, ''); } html = html.replace(/]*)>/g, ''); html = html.replace(/<\/YUI_UL>/g, '<\/ul>'); html = this.filter_invalid_lists(html); html = html.replace(/]*)>/g, ''); html = html.replace(/<\/YUI_BQ>/g, '<\/blockquote>'); html = html.replace(/]*)>/g, ''); html = html.replace(/<\/YUI_EMBED>/g, '<\/embed>'); //This should fix &'s in URL's html = html.replace(/ & /gi, ' YUI_AMP '); html = html.replace(/ &/gi, ' YUI_AMP_F '); html = html.replace(/& /gi, ' YUI_AMP_R '); html = html.replace(/&/gi, '&'); html = html.replace(/ YUI_AMP /gi, ' & '); html = html.replace(/ YUI_AMP_F /gi, ' &'); html = html.replace(/ YUI_AMP_R /gi, '& '); //Trim the output, removing whitespace from the beginning and end html = YAHOO.lang.trim(html); if (this.get('removeLineBreaks')) { html = html.replace(/\n/g, '').replace(/\r/g, ''); html = html.replace(/ /gi, ' '); //Replace all double spaces and replace with a single } for (var v in this.invalidHTML) { if (YAHOO.lang.hasOwnProperty(this.invalidHTML, v)) { if (Lang.isObject(v) && v.keepContents) { html = html.replace(new RegExp('<' + v + '([^>]*)>(.*?)<\/' + v + '>', 'gi'), '$1'); } else { html = html.replace(new RegExp('<' + v + '([^>]*)>(.*?)<\/' + v + '>', 'gi'), ''); } } } /* LATER -- Add DOM manipulation console.log(html); var frag = document.createDocumentFragment(); frag.innerHTML = html; var ps = frag.getElementsByTagName('p'), len = ps.length; for (var i = 0; i < len; i++) { var ps2 = ps[i].getElementsByTagName('p'); if (ps2.length) { } } html = frag.innerHTML; console.log(html); */ this.fireEvent('cleanHTML', { type: 'cleanHTML', target: this, html: html }); return html; }, /** * @method filter_msword * @param String html The HTML string to filter * @description Filters out msword html attributes and other junk. Activate with filterWord: true in config */ filter_msword: function(html) { if (!this.get('filterWord')) { return html; } //Remove the ms o: tags html = html.replace(/\s*<\/o:p>/g, ''); html = html.replace(/[\s\S]*?<\/o:p>/g, ' '); //Remove the ms w: tags html = html.replace( /]*>[\s\S]*?<\/w:[^>]*>/gi, ''); //Remove mso-? styles. html = html.replace( /\s*mso-[^:]+:[^;"]+;?/gi, ''); //Remove more bogus MS styles. html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, ''); html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\""); html = html.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, ''); html = html.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\""); html = html.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\""); html = html.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ); html = html.replace( /\s*tab-stops:[^;"]*;?/gi, ''); html = html.replace( /\s*tab-stops:[^"]*/gi, ''); //Remove XML declarations html = html.replace(/<\\?\?xml[^>]*>/gi, ''); //Remove lang html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3"); //Remove language tags html = html.replace( /<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, "<$1$3"); //Remove onmouseover and onmouseout events (from MS Word comments effect) html = html.replace( /<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3"); html = html.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3"); return html; }, /** * @method filter_invalid_lists * @param String html The HTML string to filter * @description Filters invalid ol and ul list markup, converts this:
          1. ..
          to this:
          1. ..
        • */ filter_invalid_lists: function(html) { html = html.replace(/<\/li>\n/gi, ''); html = html.replace(/<\/li>
            /gi, '
            1. '); html = html.replace(/<\/ol>/gi, '
          1. '); html = html.replace(/<\/ol><\/li>\n/gi, "
          "); html = html.replace(/<\/li>
            /gi, '
            • '); html = html.replace(/<\/ul>/gi, '
          • '); html = html.replace(/<\/ul><\/li>\n?/gi, "
          "); html = html.replace(/<\/li>/gi, ""); html = html.replace(/<\/ol>/gi, ""); html = html.replace(/
            /gi, "
              "); html = html.replace(/
                /gi, "
                  "); return html; }, /** * @method filter_safari * @param String html The HTML string to filter * @description Filters strings specific to Safari * @return String */ filter_safari: function(html) { if (this.browser.webkit) { // html = html.replace(/([^>])<\/span>/gi, '    '); html = html.replace(/Apple-style-span/gi, ''); html = html.replace(/style="line-height: normal;"/gi, ''); html = html.replace(/yui-wk-div/gi, ''); html = html.replace(/yui-wk-p/gi, ''); //Remove bogus LI's html = html.replace(/
                • <\/li>/gi, ''); html = html.replace(/
                • <\/li>/gi, ''); html = html.replace(/
                • <\/li>/gi, ''); //Remove bogus DIV's - updated from just removing the div's to replacing /div with a break if (this.get('ptags')) { html = html.replace(/]*)>/g, ''); html = html.replace(/<\/div>/gi, '

                  '); } else { //html = html.replace(/
                  /gi, '
                  '); html = html.replace(/]*)>([ tnr]*)<\/div>/gi, '
                  '); html = html.replace(/<\/div>/gi, ''); } } return html; }, /** * @method filter_internals * @param String html The HTML string to filter * @description Filters internal RTE strings and bogus attrs we don't want * @return String */ filter_internals: function(html) { html = html.replace(/\r/g, ''); //Fix stuff we don't want html = html.replace(/<\/?(body|head|html)[^>]*>/gi, ''); //Fix last BR in LI html = html.replace(/<\/li>/gi, '
                • '); html = html.replace(/yui-tag-span/gi, ''); html = html.replace(/yui-tag/gi, ''); html = html.replace(/yui-non/gi, ''); html = html.replace(/yui-img/gi, ''); html = html.replace(/ tag="span"/gi, ''); html = html.replace(/ class=""/gi, ''); html = html.replace(/ style=""/gi, ''); html = html.replace(/ class=" "/gi, ''); html = html.replace(/ class=" "/gi, ''); html = html.replace(/ target=""/gi, ''); html = html.replace(/ title=""/gi, ''); if (this.browser.ie) { html = html.replace(/ class= /gi, ''); html = html.replace(/ class= >/gi, ''); } return html; }, /** * @method filter_all_rgb * @param String str The HTML string to filter * @description Converts all RGB color strings found in passed string to a hex color, example: style="color: rgb(0, 255, 0)" converts to style="color: #00ff00" * @return String */ filter_all_rgb: function(str) { var exp = new RegExp("rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)", "gi"); var arr = str.match(exp); if (Lang.isArray(arr)) { for (var i = 0; i < arr.length; i++) { var color = this.filter_rgb(arr[i]); str = str.replace(arr[i].toString(), color); } } return str; }, /** * @method filter_rgb * @param String css The CSS string containing rgb(#,#,#); * @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00 * @return String */ filter_rgb: function(css) { if (css.toLowerCase().indexOf('rgb') != -1) { var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"); var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','); if (rgb.length == 5) { var r = parseInt(rgb[1], 10).toString(16); var g = parseInt(rgb[2], 10).toString(16); var b = parseInt(rgb[3], 10).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; css = "#" + r + g + b; } } return css; }, /** * @method pre_filter_linebreaks * @param String html The HTML to filter * @param String markup The markup type to filter to * @description HTML Pre Filter * @return String */ pre_filter_linebreaks: function(html, markup) { if (this.browser.webkit) { html = html.replace(/
                  /gi, ''); html = html.replace(/
                  /gi, ''); } html = html.replace(/
                  /gi, ''); html = html.replace(/
                  /gi, ''); html = html.replace(//gi, ''); html = html.replace(/
                  /gi, ''); html = html.replace(/
                  <\/div>/gi, ''); html = html.replace(/

                  ( | )<\/p>/g, ''); html = html.replace(/


                   <\/p>/gi, ''); html = html.replace(/

                   <\/p>/gi, ''); //Fix last BR html = html.replace(/$/, ''); //Fix last BR in P html = html.replace(/<\/p>/g, '

                  '); if (this.browser.ie) { html = html.replace(/    /g, '\t'); } return html; }, /** * @method post_filter_linebreaks * @param String html The HTML to filter * @param String markup The markup type to filter to * @description HTML Pre Filter * @return String */ post_filter_linebreaks: function(html, markup) { if (markup == 'xhtml') { html = html.replace(//g, '
                  '); } else { html = html.replace(//g, '
                  '); } return html; }, /** * @method clearEditorDoc * @description Clear the doc of the Editor */ clearEditorDoc: function() { this._getDoc().body.innerHTML = ' '; }, /** * @method openWindow * @description Override Method for Advanced Editor */ openWindow: function(win) { }, /** * @method moveWindow * @description Override Method for Advanced Editor */ moveWindow: function() { }, /** * @private * @method _closeWindow * @description Override Method for Advanced Editor */ _closeWindow: function() { }, /** * @method closeWindow * @description Override Method for Advanced Editor */ closeWindow: function() { //this.unsubscribeAll('afterExecCommand'); this.toolbar.resetAllButtons(); this.focus(); }, /** * @method destroy * @description Destroys the editor, all of it's elements and objects. * @return {Boolean} */ destroy: function() { if (this._nodeChangeDelayTimer) { clearTimeout(this._nodeChangeDelayTimer); } this.hide(); if (this.resize) { this.resize.destroy(); } if (this.dd) { this.dd.unreg(); } if (this.get('panel')) { this.get('panel').destroy(); } this.saveHTML(); this.toolbar.destroy(); this.setStyle('visibility', 'visible'); this.setStyle('position', 'static'); this.setStyle('top', ''); this.setStyle('left', ''); var textArea = this.get('element'); this.get('element_cont').get('parentNode').replaceChild(textArea, this.get('element_cont').get('element')); this.get('element_cont').get('element').innerHTML = ''; this.set('handleSubmit', false); //Remove the submit handler return true; }, /** * @method toString * @description Returns a string representing the editor. * @return {String} */ toString: function() { var str = 'SimpleEditor'; if (this.get && this.get('element_cont')) { str = 'SimpleEditor (#' + this.get('element_cont').get('id') + ')' + ((this.get('disabled') ? ' Disabled' : '')); } return str; } }); /** * @event toolbarLoaded * @description Event is fired during the render process directly after the Toolbar is loaded. Allowing you to attach events to the toolbar. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event cleanHTML * @description Event is fired after the cleanHTML method is called. * @type YAHOO.util.CustomEvent */ /** * @event afterRender * @description Event is fired after the render process finishes. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorContentLoaded * @description Event is fired after the editor iframe's document fully loads and fires it's onload event. From here you can start injecting your own things into the document. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeNodeChange * @description Event fires at the beginning of the nodeChange process. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event afterNodeChange * @description Event fires at the end of the nodeChange process. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeExecCommand * @description Event fires at the beginning of the execCommand process. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event afterExecCommand * @description Event fires at the end of the execCommand process. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorMouseUp * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorMouseDown * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorDoubleClick * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorClick * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyUp * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyPress * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyDown * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorMouseUp * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorMouseDown * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorDoubleClick * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorClick * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyUp * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyPress * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyDown * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event editorWindowFocus * @description Fires when the iframe is focused. Note, this is window focus event, not an Editor focus event. * @type YAHOO.util.CustomEvent */ /** * @event editorWindowBlur * @description Fires when the iframe is blurred. Note, this is window blur event, not an Editor blur event. * @type YAHOO.util.CustomEvent */ /** * @description Singleton object used to track the open window objects and panels across the various open editors * @class EditorInfo * @static */ YAHOO.widget.EditorInfo = { /** * @private * @property _instances * @description A reference to all editors on the page. * @type Object */ _instances: {}, /** * @private * @property blankImage * @description A reference to the blankImage url * @type String */ blankImage: '', /** * @private * @property window * @description A reference to the currently open window object in any editor on the page. * @type Object YAHOO.widget.EditorWindow */ window: {}, /** * @private * @property panel * @description A reference to the currently open panel in any editor on the page. * @type Object YAHOO.widget.Overlay */ panel: null, /** * @method getEditorById * @description Returns a reference to the Editor object associated with the given textarea * @param {String/HTMLElement} id The id or reference of the textarea to return the Editor instance of * @return Object YAHOO.widget.Editor */ getEditorById: function(id) { if (!YAHOO.lang.isString(id)) { //Not a string, assume a node Reference id = id.id; } if (this._instances[id]) { return this._instances[id]; } return false; }, /** * @method saveAll * @description Saves all Editor instances on the page. If a form reference is passed, only Editor's bound to this form will be saved. * @param {HTMLElement} form The form to check if this Editor instance belongs to */ saveAll: function(form) { var i, e, items = YAHOO.widget.EditorInfo._instances; if (form) { for (i in items) { if (Lang.hasOwnProperty(items, i)) { e = items[i]; if (e.get('element').form && (e.get('element').form == form)) { e.saveHTML(); } } } } else { for (i in items) { if (Lang.hasOwnProperty(items, i)) { items[i].saveHTML(); } } } }, /** * @method toString * @description Returns a string representing the EditorInfo. * @return {String} */ toString: function() { var len = 0; for (var i in this._instances) { if (Lang.hasOwnProperty(this._instances, i)) { len++; } } return 'Editor Info (' + len + ' registered intance' + ((len > 1) ? 's' : '') + ')'; } }; })(); YAHOO.register("simpleeditor", YAHOO.widget.SimpleEditor, {version: "2.9.0", build: "2800"}); }, '2.9.0' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-skin-sam-simpleeditor", "yui2-event", "yui2-element"], "optional": ["yui2-containercore", "yui2-dragdrop", "yui2-skin-sam-button", "yui2-skin-sam-menu", "yui2-menu", "yui2-button", "yui2-animation"]}); PK\M=2in3/2.9.0/build/yui2-simpleeditor/yui2-simpleeditor-debug.jsnu[YUI.add('yui2-simpleeditor', function(Y) { var YAHOO = Y.YUI2; /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang; /** * @module editor * @description

                  Creates a rich custom Toolbar Button. Primarily used with the Rich Text Editor's Toolbar

                  * @class ToolbarButtonAdvanced * @namespace YAHOO.widget * @requires yahoo, dom, element, event, container_core, menu, button * * Provides a toolbar button based on the button and menu widgets. * @constructor * @class ToolbarButtonAdvanced * @param {String/HTMLElement} el The element to turn into a button. * @param {Object} attrs Object liternal containing configuration parameters. */ if (YAHOO.widget.Button) { YAHOO.widget.ToolbarButtonAdvanced = YAHOO.widget.Button; /** * @property buttonType * @private * @description Tells if the Button is a Rich Button or a Simple Button */ YAHOO.widget.ToolbarButtonAdvanced.prototype.buttonType = 'rich'; /** * @method checkValue * @param {String} value The value of the option that we want to mark as selected * @description Select an option by value */ YAHOO.widget.ToolbarButtonAdvanced.prototype.checkValue = function(value) { var _menuItems = this.getMenu().getItems(); if (_menuItems.length === 0) { this.getMenu()._onBeforeShow(); _menuItems = this.getMenu().getItems(); } for (var i = 0; i < _menuItems.length; i++) { _menuItems[i].cfg.setProperty('checked', false); if (_menuItems[i].value == value) { _menuItems[i].cfg.setProperty('checked', true); } } }; } else { YAHOO.widget.ToolbarButtonAdvanced = function() {}; } /** * @description

                  Creates a basic custom Toolbar Button. Primarily used with the Rich Text Editor's Toolbar

                  Provides a toolbar button based on the button and menu widgets, <select> elements are used in place of menu's.

                  * @class ToolbarButton * @namespace YAHOO.widget * @requires yahoo, dom, element, event * @extends YAHOO.util.Element * * * @constructor * @param {String/HTMLElement} el The element to turn into a button. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.ToolbarButton = function(el, attrs) { YAHOO.log('ToolbarButton Initalizing', 'info', 'ToolbarButton'); YAHOO.log(arguments.length + ' arguments passed to constructor', 'info', 'Toolbar'); if (Lang.isObject(arguments[0]) && !Dom.get(el).nodeType) { attrs = el; } var local_attrs = (attrs || {}); var oConfig = { element: null, attributes: local_attrs }; if (!oConfig.attributes.type) { oConfig.attributes.type = 'push'; } oConfig.element = document.createElement('span'); oConfig.element.setAttribute('unselectable', 'on'); oConfig.element.className = 'yui-button yui-' + oConfig.attributes.type + '-button'; oConfig.element.innerHTML = 'LABEL'; oConfig.element.firstChild.firstChild.tabIndex = '-1'; oConfig.attributes.id = (oConfig.attributes.id || Dom.generateId()); oConfig.element.id = oConfig.attributes.id; YAHOO.widget.ToolbarButton.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.ToolbarButton, YAHOO.util.Element, { /** * @property buttonType * @private * @description Tells if the Button is a Rich Button or a Simple Button */ buttonType: 'normal', /** * @method _handleMouseOver * @private * @description Adds classes to the button elements on mouseover (hover) */ _handleMouseOver: function() { if (!this.get('disabled')) { this.addClass('yui-button-hover'); this.addClass('yui-' + this.get('type') + '-button-hover'); } }, /** * @method _handleMouseOut * @private * @description Removes classes from the button elements on mouseout (hover) */ _handleMouseOut: function() { this.removeClass('yui-button-hover'); this.removeClass('yui-' + this.get('type') + '-button-hover'); }, /** * @method checkValue * @param {String} value The value of the option that we want to mark as selected * @description Select an option by value */ checkValue: function(value) { if (this.get('type') == 'menu') { var opts = this._button.options; if (opts) { for (var i = 0; i < opts.length; i++) { if (opts[i].value == value) { opts.selectedIndex = i; } } } } }, /** * @method init * @description The ToolbarButton class's initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.widget.ToolbarButton.superclass.init.call(this, p_oElement, p_oAttributes); this.on('mouseover', this._handleMouseOver, this, true); this.on('mouseout', this._handleMouseOut, this, true); this.on('click', function(ev) { Event.stopEvent(ev); return false; }, this, true); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the toolbar. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the toolbar. */ initAttributes: function(attr) { YAHOO.widget.ToolbarButton.superclass.initAttributes.call(this, attr); /** * @attribute value * @description The value of the button * @type String */ this.setAttributeConfig('value', { value: attr.value }); /** * @attribute menu * @description The menu attribute, see YAHOO.widget.Button * @type Object */ this.setAttributeConfig('menu', { value: attr.menu || false }); /** * @attribute type * @description The type of button to create: push, menu, color, select, spin * @type String */ this.setAttributeConfig('type', { value: attr.type, writeOnce: true, method: function(type) { var el, opt; if (!this._button) { this._button = this.get('element').getElementsByTagName('a')[0]; } switch (type) { case 'select': case 'menu': el = document.createElement('select'); el.id = this.get('id'); var menu = this.get('menu'); for (var i = 0; i < menu.length; i++) { opt = document.createElement('option'); opt.innerHTML = menu[i].text; opt.value = menu[i].value; if (menu[i].checked) { opt.selected = true; } el.appendChild(opt); } this._button.parentNode.replaceChild(el, this._button); Event.on(el, 'change', this._handleSelect, this, true); this._button = el; break; } } }); /** * @attribute disabled * @description Set the button into a disabled state * @type String */ this.setAttributeConfig('disabled', { value: attr.disabled || false, method: function(disabled) { if (disabled) { this.addClass('yui-button-disabled'); this.addClass('yui-' + this.get('type') + '-button-disabled'); } else { this.removeClass('yui-button-disabled'); this.removeClass('yui-' + this.get('type') + '-button-disabled'); } if ((this.get('type') == 'menu') || (this.get('type') == 'select')) { this._button.disabled = disabled; } } }); /** * @attribute label * @description The text label for the button * @type String */ this.setAttributeConfig('label', { value: attr.label, method: function(label) { if (!this._button) { this._button = this.get('element').getElementsByTagName('a')[0]; } if (this.get('type') == 'push') { this._button.innerHTML = label; } } }); /** * @attribute title * @description The title of the button * @type String */ this.setAttributeConfig('title', { value: attr.title }); /** * @config container * @description The container that the button is rendered to, handled by Toolbar * @type String */ this.setAttributeConfig('container', { value: null, writeOnce: true, method: function(cont) { this.appendTo(cont); } }); }, /** * @private * @method _handleSelect * @description The event fired when a change event gets fired on a select element * @param {Event} ev The change event. */ _handleSelect: function(ev) { var tar = Event.getTarget(ev); var value = tar.options[tar.selectedIndex].value; this.fireEvent('change', {type: 'change', value: value }); }, /** * @method getMenu * @description A stub function to mimic YAHOO.widget.Button's getMenu method */ getMenu: function() { return this.get('menu'); }, /** * @method destroy * @description Destroy the button */ destroy: function() { Event.purgeElement(this.get('element'), true); this.get('element').parentNode.removeChild(this.get('element')); //Brutal Object Destroy for (var i in this) { if (Lang.hasOwnProperty(this, i)) { this[i] = null; } } }, /** * @method fireEvent * @description Overridden fireEvent method to prevent DOM events from firing if the button is disabled. */ fireEvent: function(p_sType, p_aArgs) { // Disabled buttons should not respond to DOM events if (this.DOM_EVENTS[p_sType] && this.get('disabled')) { Event.stopEvent(p_aArgs); return; } YAHOO.widget.ToolbarButton.superclass.fireEvent.call(this, p_sType, p_aArgs); }, /** * @method toString * @description Returns a string representing the toolbar. * @return {String} */ toString: function() { return 'ToolbarButton (' + this.get('id') + ')'; } }); })(); /** * @module editor * @description

                  Creates a rich Toolbar widget based on Button. Primarily used with the Rich Text Editor

                  * @namespace YAHOO.widget * @requires yahoo, dom, element, event, toolbarbutton * @optional container_core, dragdrop */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang; var getButton = function(id) { var button = id; if (Lang.isString(id)) { button = this.getButtonById(id); } if (Lang.isNumber(id)) { button = this.getButtonByIndex(id); } if ((!(button instanceof YAHOO.widget.ToolbarButton)) && (!(button instanceof YAHOO.widget.ToolbarButtonAdvanced))) { button = this.getButtonByValue(id); } if ((button instanceof YAHOO.widget.ToolbarButton) || (button instanceof YAHOO.widget.ToolbarButtonAdvanced)) { return button; } return false; }; /** * Provides a rich toolbar widget based on the button and menu widgets * @constructor * @class Toolbar * @extends YAHOO.util.Element * @param {String/HTMLElement} el The element to turn into a toolbar. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.Toolbar = function(el, attrs) { YAHOO.log('Toolbar Initalizing', 'info', 'Toolbar'); YAHOO.log(arguments.length + ' arguments passed to constructor', 'info', 'Toolbar'); if (Lang.isObject(arguments[0]) && !Dom.get(el).nodeType) { attrs = el; } var local_attrs = {}; if (attrs) { Lang.augmentObject(local_attrs, attrs); //Break the config reference } var oConfig = { element: null, attributes: local_attrs }; if (Lang.isString(el) && Dom.get(el)) { oConfig.element = Dom.get(el); } else if (Lang.isObject(el) && Dom.get(el) && Dom.get(el).nodeType) { oConfig.element = Dom.get(el); } if (!oConfig.element) { YAHOO.log('No element defined, creating toolbar container', 'warn', 'Toolbar'); oConfig.element = document.createElement('DIV'); oConfig.element.id = Dom.generateId(); if (local_attrs.container && Dom.get(local_attrs.container)) { YAHOO.log('Container found in config appending to it (' + Dom.get(local_attrs.container).id + ')', 'info', 'Toolbar'); Dom.get(local_attrs.container).appendChild(oConfig.element); } } if (!oConfig.element.id) { oConfig.element.id = ((Lang.isString(el)) ? el : Dom.generateId()); YAHOO.log('No element ID defined for toolbar container, creating..', 'warn', 'Toolbar'); } YAHOO.log('Initing toolbar with id: ' + oConfig.element.id, 'info', 'Toolbar'); var fs = document.createElement('fieldset'); var lg = document.createElement('legend'); lg.innerHTML = 'Toolbar'; fs.appendChild(lg); var cont = document.createElement('DIV'); oConfig.attributes.cont = cont; Dom.addClass(cont, 'yui-toolbar-subcont'); fs.appendChild(cont); oConfig.element.appendChild(fs); oConfig.element.tabIndex = -1; oConfig.attributes.element = oConfig.element; oConfig.attributes.id = oConfig.element.id; this._configuredButtons = []; YAHOO.widget.Toolbar.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.Toolbar, YAHOO.util.Element, { /** * @protected * @property _configuredButtons * @type Array */ _configuredButtons: null, /** * @method _addMenuClasses * @private * @description This method is called from Menu's renderEvent to add a few more classes to the menu items * @param {String} ev The event that fired. * @param {Array} na Array of event information. * @param {Object} o Button config object. */ _addMenuClasses: function(ev, na, o) { Dom.addClass(this.element, 'yui-toolbar-' + o.get('value') + '-menu'); if (Dom.hasClass(o._button.parentNode.parentNode, 'yui-toolbar-select')) { Dom.addClass(this.element, 'yui-toolbar-select-menu'); } var items = this.getItems(); for (var i = 0; i < items.length; i++) { Dom.addClass(items[i].element, 'yui-toolbar-' + o.get('value') + '-' + ((items[i].value) ? items[i].value.replace(/ /g, '-').toLowerCase() : items[i]._oText.nodeValue.replace(/ /g, '-').toLowerCase())); Dom.addClass(items[i].element, 'yui-toolbar-' + o.get('value') + '-' + ((items[i].value) ? items[i].value.replace(/ /g, '-') : items[i]._oText.nodeValue.replace(/ /g, '-'))); } }, /** * @property buttonType * @description The default button to use * @type Object */ buttonType: YAHOO.widget.ToolbarButton, /** * @property dd * @description The DragDrop instance associated with the Toolbar * @type Object */ dd: null, /** * @property _colorData * @description Object reference containing colors hex and text values. * @type Object */ _colorData: { /* {{{ _colorData */ '#111111': 'Obsidian', '#2D2D2D': 'Dark Gray', '#434343': 'Shale', '#5B5B5B': 'Flint', '#737373': 'Gray', '#8B8B8B': 'Concrete', '#A2A2A2': 'Gray', '#B9B9B9': 'Titanium', '#000000': 'Black', '#D0D0D0': 'Light Gray', '#E6E6E6': 'Silver', '#FFFFFF': 'White', '#BFBF00': 'Pumpkin', '#FFFF00': 'Yellow', '#FFFF40': 'Banana', '#FFFF80': 'Pale Yellow', '#FFFFBF': 'Butter', '#525330': 'Raw Siena', '#898A49': 'Mildew', '#AEA945': 'Olive', '#7F7F00': 'Paprika', '#C3BE71': 'Earth', '#E0DCAA': 'Khaki', '#FCFAE1': 'Cream', '#60BF00': 'Cactus', '#80FF00': 'Chartreuse', '#A0FF40': 'Green', '#C0FF80': 'Pale Lime', '#DFFFBF': 'Light Mint', '#3B5738': 'Green', '#668F5A': 'Lime Gray', '#7F9757': 'Yellow', '#407F00': 'Clover', '#8A9B55': 'Pistachio', '#B7C296': 'Light Jade', '#E6EBD5': 'Breakwater', '#00BF00': 'Spring Frost', '#00FF80': 'Pastel Green', '#40FFA0': 'Light Emerald', '#80FFC0': 'Sea Foam', '#BFFFDF': 'Sea Mist', '#033D21': 'Dark Forrest', '#438059': 'Moss', '#7FA37C': 'Medium Green', '#007F40': 'Pine', '#8DAE94': 'Yellow Gray Green', '#ACC6B5': 'Aqua Lung', '#DDEBE2': 'Sea Vapor', '#00BFBF': 'Fog', '#00FFFF': 'Cyan', '#40FFFF': 'Turquoise Blue', '#80FFFF': 'Light Aqua', '#BFFFFF': 'Pale Cyan', '#033D3D': 'Dark Teal', '#347D7E': 'Gray Turquoise', '#609A9F': 'Green Blue', '#007F7F': 'Seaweed', '#96BDC4': 'Green Gray', '#B5D1D7': 'Soapstone', '#E2F1F4': 'Light Turquoise', '#0060BF': 'Summer Sky', '#0080FF': 'Sky Blue', '#40A0FF': 'Electric Blue', '#80C0FF': 'Light Azure', '#BFDFFF': 'Ice Blue', '#1B2C48': 'Navy', '#385376': 'Biscay', '#57708F': 'Dusty Blue', '#00407F': 'Sea Blue', '#7792AC': 'Sky Blue Gray', '#A8BED1': 'Morning Sky', '#DEEBF6': 'Vapor', '#0000BF': 'Deep Blue', '#0000FF': 'Blue', '#4040FF': 'Cerulean Blue', '#8080FF': 'Evening Blue', '#BFBFFF': 'Light Blue', '#212143': 'Deep Indigo', '#373E68': 'Sea Blue', '#444F75': 'Night Blue', '#00007F': 'Indigo Blue', '#585E82': 'Dockside', '#8687A4': 'Blue Gray', '#D2D1E1': 'Light Blue Gray', '#6000BF': 'Neon Violet', '#8000FF': 'Blue Violet', '#A040FF': 'Violet Purple', '#C080FF': 'Violet Dusk', '#DFBFFF': 'Pale Lavender', '#302449': 'Cool Shale', '#54466F': 'Dark Indigo', '#655A7F': 'Dark Violet', '#40007F': 'Violet', '#726284': 'Smoky Violet', '#9E8FA9': 'Slate Gray', '#DCD1DF': 'Violet White', '#BF00BF': 'Royal Violet', '#FF00FF': 'Fuchsia', '#FF40FF': 'Magenta', '#FF80FF': 'Orchid', '#FFBFFF': 'Pale Magenta', '#4A234A': 'Dark Purple', '#794A72': 'Medium Purple', '#936386': 'Cool Granite', '#7F007F': 'Purple', '#9D7292': 'Purple Moon', '#C0A0B6': 'Pale Purple', '#ECDAE5': 'Pink Cloud', '#BF005F': 'Hot Pink', '#FF007F': 'Deep Pink', '#FF409F': 'Grape', '#FF80BF': 'Electric Pink', '#FFBFDF': 'Pink', '#451528': 'Purple Red', '#823857': 'Purple Dino', '#A94A76': 'Purple Gray', '#7F003F': 'Rose', '#BC6F95': 'Antique Mauve', '#D8A5BB': 'Cool Marble', '#F7DDE9': 'Pink Granite', '#C00000': 'Apple', '#FF0000': 'Fire Truck', '#FF4040': 'Pale Red', '#FF8080': 'Salmon', '#FFC0C0': 'Warm Pink', '#441415': 'Sepia', '#82393C': 'Rust', '#AA4D4E': 'Brick', '#800000': 'Brick Red', '#BC6E6E': 'Mauve', '#D8A3A4': 'Shrimp Pink', '#F8DDDD': 'Shell Pink', '#BF5F00': 'Dark Orange', '#FF7F00': 'Orange', '#FF9F40': 'Grapefruit', '#FFBF80': 'Canteloupe', '#FFDFBF': 'Wax', '#482C1B': 'Dark Brick', '#855A40': 'Dirt', '#B27C51': 'Tan', '#7F3F00': 'Nutmeg', '#C49B71': 'Mustard', '#E1C4A8': 'Pale Tan', '#FDEEE0': 'Marble' /* }}} */ }, /** * @property _colorPicker * @description The HTML Element containing the colorPicker * @type HTMLElement */ _colorPicker: null, /** * @property STR_COLLAPSE * @description String for Toolbar Collapse Button * @type String */ STR_COLLAPSE: 'Collapse Toolbar', /** * @property STR_EXPAND * @description String for Toolbar Collapse Button - Expand * @type String */ STR_EXPAND: 'Expand Toolbar', /** * @property STR_SPIN_LABEL * @description String for spinbutton dynamic label. Note the {VALUE} will be replaced with YAHOO.lang.substitute * @type String */ STR_SPIN_LABEL: 'Spin Button with value {VALUE}. Use Control Shift Up Arrow and Control Shift Down arrow keys to increase or decrease the value.', /** * @property STR_SPIN_UP * @description String for spinbutton up * @type String */ STR_SPIN_UP: 'Click to increase the value of this input', /** * @property STR_SPIN_DOWN * @description String for spinbutton down * @type String */ STR_SPIN_DOWN: 'Click to decrease the value of this input', /** * @property _titlebar * @description Object reference to the titlebar * @type HTMLElement */ _titlebar: null, /** * @property browser * @description Standard browser detection * @type Object */ browser: YAHOO.env.ua, /** * @protected * @property _buttonList * @description Internal property list of current buttons in the toolbar * @type Array */ _buttonList: null, /** * @protected * @property _buttonGroupList * @description Internal property list of current button groups in the toolbar * @type Array */ _buttonGroupList: null, /** * @protected * @property _sep * @description Internal reference to the separator HTML Element for cloning * @type HTMLElement */ _sep: null, /** * @protected * @property _sepCount * @description Internal refernce for counting separators, so we can give them a useful class name for styling * @type Number */ _sepCount: null, /** * @protected * @property draghandle * @type HTMLElement */ _dragHandle: null, /** * @protected * @property _toolbarConfigs * @type Object */ _toolbarConfigs: { renderer: true }, /** * @protected * @property CLASS_CONTAINER * @description Default CSS class to apply to the toolbar container element * @type String */ CLASS_CONTAINER: 'yui-toolbar-container', /** * @protected * @property CLASS_DRAGHANDLE * @description Default CSS class to apply to the toolbar's drag handle element * @type String */ CLASS_DRAGHANDLE: 'yui-toolbar-draghandle', /** * @protected * @property CLASS_SEPARATOR * @description Default CSS class to apply to all separators in the toolbar * @type String */ CLASS_SEPARATOR: 'yui-toolbar-separator', /** * @protected * @property CLASS_DISABLED * @description Default CSS class to apply when the toolbar is disabled * @type String */ CLASS_DISABLED: 'yui-toolbar-disabled', /** * @protected * @property CLASS_PREFIX * @description Default prefix for dynamically created class names * @type String */ CLASS_PREFIX: 'yui-toolbar', /** * @method init * @description The Toolbar class's initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.widget.Toolbar.superclass.init.call(this, p_oElement, p_oAttributes); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the toolbar. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the toolbar. */ initAttributes: function(attr) { YAHOO.widget.Toolbar.superclass.initAttributes.call(this, attr); this.addClass(this.CLASS_CONTAINER); /** * @attribute buttonType * @description The buttonType to use (advanced or basic) * @type String */ this.setAttributeConfig('buttonType', { value: attr.buttonType || 'basic', writeOnce: true, validator: function(type) { switch (type) { case 'advanced': case 'basic': return true; } return false; }, method: function(type) { if (type == 'advanced') { if (YAHOO.widget.Button) { this.buttonType = YAHOO.widget.ToolbarButtonAdvanced; } else { YAHOO.log('Can not find YAHOO.widget.Button', 'error', 'Toolbar'); this.buttonType = YAHOO.widget.ToolbarButton; } } else { this.buttonType = YAHOO.widget.ToolbarButton; } } }); /** * @attribute buttons * @description Object specifying the buttons to include in the toolbar * Example: *
                              * {
                              *   { id: 'b3', type: 'button', label: 'Underline', value: 'underline' },
                              *   { type: 'separator' },
                              *   { id: 'b4', type: 'menu', label: 'Align', value: 'align',
                              *       menu: [
                              *           { text: "Left", value: 'alignleft' },
                              *           { text: "Center", value: 'aligncenter' },
                              *           { text: "Right", value: 'alignright' }
                              *       ]
                              *   }
                              * }
                              * 
                  * @type Array */ this.setAttributeConfig('buttons', { value: [], writeOnce: true, method: function(data) { var i, button, buttons, len, b; for (i in data) { if (Lang.hasOwnProperty(data, i)) { if (data[i].type == 'separator') { this.addSeparator(); } else if (data[i].group !== undefined) { buttons = this.addButtonGroup(data[i]); if (buttons) { len = buttons.length; for(b = 0; b < len; b++) { if (buttons[b]) { this._configuredButtons[this._configuredButtons.length] = buttons[b].id; } } } } else { button = this.addButton(data[i]); if (button) { this._configuredButtons[this._configuredButtons.length] = button.id; } } } } } }); /** * @attribute disabled * @description Boolean indicating if the toolbar should be disabled. It will also disable the draggable attribute if it is on. * @default false * @type Boolean */ this.setAttributeConfig('disabled', { value: false, method: function(disabled) { if (this.get('disabled') === disabled) { return false; } if (disabled) { this.addClass(this.CLASS_DISABLED); this.set('draggable', false); this.disableAllButtons(); } else { this.removeClass(this.CLASS_DISABLED); if (this._configs.draggable._initialConfig.value) { //Draggable by default, set it back this.set('draggable', true); } this.resetAllButtons(); } } }); /** * @config cont * @description The container for the toolbar. * @type HTMLElement */ this.setAttributeConfig('cont', { value: attr.cont, readOnly: true }); /** * @attribute grouplabels * @description Boolean indicating if the toolbar should show the group label's text string. * @default true * @type Boolean */ this.setAttributeConfig('grouplabels', { value: ((attr.grouplabels === false) ? false : true), method: function(grouplabels) { if (grouplabels) { Dom.removeClass(this.get('cont'), (this.CLASS_PREFIX + '-nogrouplabels')); } else { Dom.addClass(this.get('cont'), (this.CLASS_PREFIX + '-nogrouplabels')); } } }); /** * @attribute titlebar * @description Boolean indicating if the toolbar should have a titlebar. If * passed a string, it will use that as the titlebar text * @default false * @type Boolean or String */ this.setAttributeConfig('titlebar', { value: false, method: function(titlebar) { if (titlebar) { if (this._titlebar && this._titlebar.parentNode) { this._titlebar.parentNode.removeChild(this._titlebar); } this._titlebar = document.createElement('DIV'); this._titlebar.tabIndex = '-1'; Event.on(this._titlebar, 'focus', function() { this._handleFocus(); }, this, true); Dom.addClass(this._titlebar, this.CLASS_PREFIX + '-titlebar'); if (Lang.isString(titlebar)) { var h2 = document.createElement('h2'); h2.tabIndex = '-1'; h2.innerHTML = '' + titlebar + ''; this._titlebar.appendChild(h2); Event.on(h2.firstChild, 'click', function(ev) { Event.stopEvent(ev); }); Event.on([h2, h2.firstChild], 'focus', function() { this._handleFocus(); }, this, true); } if (this.get('firstChild')) { this.insertBefore(this._titlebar, this.get('firstChild')); } else { this.appendChild(this._titlebar); } if (this.get('collapse')) { this.set('collapse', true); } } else if (this._titlebar) { if (this._titlebar && this._titlebar.parentNode) { this._titlebar.parentNode.removeChild(this._titlebar); } } } }); /** * @attribute collapse * @description Boolean indicating if the the titlebar should have a collapse button. * The collapse button will not remove the toolbar, it will minimize it to the titlebar * @default false * @type Boolean */ this.setAttributeConfig('collapse', { value: false, method: function(collapse) { if (this._titlebar) { var collapseEl = null; var el = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapse) { if (el.length > 0) { //There is already a collapse button return true; } collapseEl = document.createElement('SPAN'); collapseEl.innerHTML = 'X'; collapseEl.title = this.STR_COLLAPSE; Dom.addClass(collapseEl, 'collapse'); this._titlebar.appendChild(collapseEl); Event.addListener(collapseEl, 'click', function() { if (Dom.hasClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed')) { this.collapse(false); //Expand Toolbar } else { this.collapse(); //Collapse Toolbar } }, this, true); } else { collapseEl = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapseEl[0]) { if (Dom.hasClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed')) { //We are closed, reopen the titlebar.. this.collapse(false); //Expand Toolbar } collapseEl[0].parentNode.removeChild(collapseEl[0]); } } } } }); /** * @attribute draggable * @description Boolean indicating if the toolbar should be draggable. * @default false * @type Boolean */ this.setAttributeConfig('draggable', { value: (attr.draggable || false), method: function(draggable) { if (draggable && !this.get('titlebar')) { YAHOO.log('Dragging enabled', 'info', 'Toolbar'); if (!this._dragHandle) { this._dragHandle = document.createElement('SPAN'); this._dragHandle.innerHTML = '|'; this._dragHandle.setAttribute('title', 'Click to drag the toolbar'); this._dragHandle.id = this.get('id') + '_draghandle'; Dom.addClass(this._dragHandle, this.CLASS_DRAGHANDLE); if (this.get('cont').hasChildNodes()) { this.get('cont').insertBefore(this._dragHandle, this.get('cont').firstChild); } else { this.get('cont').appendChild(this._dragHandle); } this.dd = new YAHOO.util.DD(this.get('id')); this.dd.setHandleElId(this._dragHandle.id); } } else { YAHOO.log('Dragging disabled', 'info', 'Toolbar'); if (this._dragHandle) { this._dragHandle.parentNode.removeChild(this._dragHandle); this._dragHandle = null; this.dd = null; } } if (this._titlebar) { if (draggable) { this.dd = new YAHOO.util.DD(this.get('id')); this.dd.setHandleElId(this._titlebar); Dom.addClass(this._titlebar, 'draggable'); } else { Dom.removeClass(this._titlebar, 'draggable'); if (this.dd) { this.dd.unreg(); this.dd = null; } } } }, validator: function(value) { var ret = true; if (!YAHOO.util.DD) { ret = false; } return ret; } }); }, /** * @method addButtonGroup * @description Add a new button group to the toolbar. (uses addButton) * @param {Object} oGroup Object literal reference to the Groups Config (contains an array of button configs as well as the group label) */ addButtonGroup: function(oGroup) { if (!this.get('element')) { this._queue[this._queue.length] = ['addButtonGroup', arguments]; return false; } if (!this.hasClass(this.CLASS_PREFIX + '-grouped')) { this.addClass(this.CLASS_PREFIX + '-grouped'); } var div = document.createElement('DIV'); Dom.addClass(div, this.CLASS_PREFIX + '-group'); Dom.addClass(div, this.CLASS_PREFIX + '-group-' + oGroup.group); if (oGroup.label) { var label = document.createElement('h3'); label.innerHTML = oGroup.label; div.appendChild(label); } if (!this.get('grouplabels')) { Dom.addClass(this.get('cont'), this.CLASS_PREFIX, '-nogrouplabels'); } this.get('cont').appendChild(div); //For accessibility, let's put all of the group buttons in an Unordered List var ul = document.createElement('ul'); div.appendChild(ul); if (!this._buttonGroupList) { this._buttonGroupList = {}; } this._buttonGroupList[oGroup.group] = ul; //An array of the button ids added to this group //This is used for destruction later... var addedButtons = [], button; for (var i = 0; i < oGroup.buttons.length; i++) { var li = document.createElement('li'); li.className = this.CLASS_PREFIX + '-groupitem'; ul.appendChild(li); if ((oGroup.buttons[i].type !== undefined) && oGroup.buttons[i].type == 'separator') { this.addSeparator(li); } else { oGroup.buttons[i].container = li; button = this.addButton(oGroup.buttons[i]); if (button) { addedButtons[addedButtons.length] = button.id; } } } return addedButtons; }, /** * @method addButtonToGroup * @description Add a new button to a toolbar group. Buttons supported: * push, split, menu, select, color, spin * @param {Object} oButton Object literal reference to the Button's Config * @param {String} group The Group identifier passed into the initial config * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addButtonToGroup: function(oButton, group, after) { var groupCont = this._buttonGroupList[group], li = document.createElement('li'); li.className = this.CLASS_PREFIX + '-groupitem'; oButton.container = li; this.addButton(oButton, after); groupCont.appendChild(li); }, /** * @method addButton * @description Add a new button to the toolbar. Buttons supported: * push, split, menu, select, color, spin * @param {Object} oButton Object literal reference to the Button's Config * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addButton: function(oButton, after) { if (!this.get('element')) { this._queue[this._queue.length] = ['addButton', arguments]; return false; } if (!this._buttonList) { this._buttonList = []; } YAHOO.log('Adding button of type: ' + oButton.type, 'info', 'Toolbar'); if (!oButton.container) { oButton.container = this.get('cont'); } if ((oButton.type == 'menu') || (oButton.type == 'split') || (oButton.type == 'select')) { if (Lang.isArray(oButton.menu)) { for (var i in oButton.menu) { if (Lang.hasOwnProperty(oButton.menu, i)) { var funcObject = { fn: function(ev, x, oMenu) { if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ((oMenu.value) ? oMenu.value : oMenu._oText.nodeValue); }, scope: this }; oButton.menu[i].onclick = funcObject; } } } } var _oButton = {}, skip = false; for (var o in oButton) { if (Lang.hasOwnProperty(oButton, o)) { if (!this._toolbarConfigs[o]) { _oButton[o] = oButton[o]; } } } if (oButton.type == 'select') { _oButton.type = 'menu'; } if (oButton.type == 'spin') { _oButton.type = 'push'; } if (_oButton.type == 'color') { if (YAHOO.widget.Overlay) { _oButton = this._makeColorButton(_oButton); } else { skip = true; } } if (_oButton.menu) { if ((YAHOO.widget.Overlay) && (oButton.menu instanceof YAHOO.widget.Overlay)) { oButton.menu.showEvent.subscribe(function() { this._button = _oButton; }); } else { for (var m = 0; m < _oButton.menu.length; m++) { if (!_oButton.menu[m].value) { _oButton.menu[m].value = _oButton.menu[m].text; } } if (this.browser.webkit) { _oButton.focusmenu = false; } } } if (skip) { oButton = false; } else { //Add to .get('buttons') manually this._configs.buttons.value[this._configs.buttons.value.length] = oButton; var tmp = new this.buttonType(_oButton); tmp.get('element').tabIndex = '-1'; tmp.get('element').setAttribute('role', 'button'); tmp._selected = true; if (this.get('disabled')) { //Toolbar is disabled, disable the new button too! tmp.set('disabled', true); } if (!oButton.id) { oButton.id = tmp.get('id'); } YAHOO.log('Button created (' + oButton.type + ')', 'info', 'Toolbar'); if (after) { var el = tmp.get('element'); var nextSib = null; if (after.get) { nextSib = after.get('element').nextSibling; } else if (after.nextSibling) { nextSib = after.nextSibling; } if (nextSib) { nextSib.parentNode.insertBefore(el, nextSib); } } tmp.addClass(this.CLASS_PREFIX + '-' + tmp.get('value')); var icon = document.createElement('span'); icon.className = this.CLASS_PREFIX + '-icon'; tmp.get('element').insertBefore(icon, tmp.get('firstChild')); if (tmp._button.tagName.toLowerCase() == 'button') { tmp.get('element').setAttribute('unselectable', 'on'); //Replace the Button HTML Element with an a href if it exists var a = document.createElement('a'); a.innerHTML = tmp._button.innerHTML; a.href = '#'; a.tabIndex = '-1'; Event.on(a, 'click', function(ev) { Event.stopEvent(ev); }); tmp._button.parentNode.replaceChild(a, tmp._button); tmp._button = a; } if (oButton.type == 'select') { if (tmp._button.tagName.toLowerCase() == 'select') { icon.parentNode.removeChild(icon); var iel = tmp._button, parEl = tmp.get('element'); parEl.parentNode.replaceChild(iel, parEl); //The 'element' value is currently the orphaned element //In order for "destroy" to execute we need to get('element') to reference the correct node. //I'm not sure if there is a direct approach to setting this value. tmp._configs.element.value = iel; } else { //Don't put a class on it if it's a real select element tmp.addClass(this.CLASS_PREFIX + '-select'); } } if (oButton.type == 'spin') { if (!Lang.isArray(oButton.range)) { oButton.range = [ 10, 100 ]; } this._makeSpinButton(tmp, oButton); } tmp.get('element').setAttribute('title', tmp.get('label')); if (oButton.type != 'spin') { if ((YAHOO.widget.Overlay) && (_oButton.menu instanceof YAHOO.widget.Overlay)) { var showPicker = function(ev) { var exec = true; if (ev.keyCode && (ev.keyCode == 9)) { exec = false; } if (exec) { if (this._colorPicker) { this._colorPicker._button = oButton.value; } var menuEL = tmp.getMenu().element; if (Dom.getStyle(menuEL, 'visibility') == 'hidden') { tmp.getMenu().show(); } else { tmp.getMenu().hide(); } } YAHOO.util.Event.stopEvent(ev); }; tmp.on('mousedown', showPicker, oButton, this); tmp.on('keydown', showPicker, oButton, this); } else if ((oButton.type != 'menu') && (oButton.type != 'select')) { tmp.on('keypress', this._buttonClick, oButton, this); tmp.on('mousedown', function(ev) { YAHOO.util.Event.stopEvent(ev); this._buttonClick(ev, oButton); }, oButton, this); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }); } else { //Stop the mousedown event so we can trap the selection in the editor! tmp.on('mousedown', function(ev) { //YAHOO.util.Event.stopEvent(ev); }); tmp.on('click', function(ev) { //YAHOO.util.Event.stopEvent(ev); }); tmp.on('change', function(ev) { if (!ev.target) { if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ev.value; this._buttonClick(ev, oButton); } }, this, true); var self = this; //Hijack the mousedown event in the menu and make it fire a button click.. tmp.on('appendTo', function() { var tmp = this; if (tmp.getMenu() && tmp.getMenu().mouseDownEvent) { tmp.getMenu().mouseDownEvent.subscribe(function(ev, args) { YAHOO.log('mouseDownEvent', 'warn', 'Toolbar'); var oMenu = args[1]; YAHOO.util.Event.stopEvent(args[0]); tmp._onMenuClick(args[0], tmp); if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ((oMenu.value) ? oMenu.value : oMenu._oText.nodeValue); self._buttonClick.call(self, args[1], oButton); tmp._hideMenu(); return false; }); tmp.getMenu().clickEvent.subscribe(function(ev, args) { YAHOO.log('clickEvent', 'warn', 'Toolbar'); YAHOO.util.Event.stopEvent(args[0]); }); tmp.getMenu().mouseUpEvent.subscribe(function(ev, args) { YAHOO.log('mouseUpEvent', 'warn', 'Toolbar'); YAHOO.util.Event.stopEvent(args[0]); }); } }); } } else { //Stop the mousedown event so we can trap the selection in the editor! tmp.on('mousedown', function(ev) { YAHOO.util.Event.stopEvent(ev); }); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }); } if (this.browser.ie) { /* //Add a couple of new events for IE tmp.DOM_EVENTS.focusin = true; tmp.DOM_EVENTS.focusout = true; //Stop them so we don't loose focus in the Editor tmp.on('focusin', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); tmp.on('focusout', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); */ } if (this.browser.webkit) { //This will keep the document from gaining focus and the editor from loosing it.. //Forcefully remove the focus calls in button! tmp.hasFocus = function() { return true; }; } this._buttonList[this._buttonList.length] = tmp; if ((oButton.type == 'menu') || (oButton.type == 'split') || (oButton.type == 'select')) { if (Lang.isArray(oButton.menu)) { YAHOO.log('Button type is (' + oButton.type + '), doing extra renderer work.', 'info', 'Toolbar'); var menu = tmp.getMenu(); if (menu && menu.renderEvent) { menu.renderEvent.subscribe(this._addMenuClasses, tmp); if (oButton.renderer) { menu.renderEvent.subscribe(oButton.renderer, tmp); } } } } } return oButton; }, /** * @method addSeparator * @description Add a new button separator to the toolbar. * @param {HTMLElement} cont Optional HTML element to insert this button into. * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addSeparator: function(cont, after) { if (!this.get('element')) { this._queue[this._queue.length] = ['addSeparator', arguments]; return false; } var sepCont = ((cont) ? cont : this.get('cont')); if (!this.get('element')) { this._queue[this._queue.length] = ['addSeparator', arguments]; return false; } if (this._sepCount === null) { this._sepCount = 0; } if (!this._sep) { YAHOO.log('Separator does not yet exist, creating', 'info', 'Toolbar'); this._sep = document.createElement('SPAN'); Dom.addClass(this._sep, this.CLASS_SEPARATOR); this._sep.innerHTML = '|'; } YAHOO.log('Separator does exist, cloning', 'info', 'Toolbar'); var _sep = this._sep.cloneNode(true); this._sepCount++; Dom.addClass(_sep, this.CLASS_SEPARATOR + '-' + this._sepCount); if (after) { var nextSib = null; if (after.get) { nextSib = after.get('element').nextSibling; } else if (after.nextSibling) { nextSib = after.nextSibling; } else { nextSib = after; } if (nextSib) { if (nextSib == after) { nextSib.parentNode.appendChild(_sep); } else { nextSib.parentNode.insertBefore(_sep, nextSib); } } } else { sepCont.appendChild(_sep); } return _sep; }, /** * @method _createColorPicker * @private * @description Creates the core DOM reference to the color picker menu item. * @param {String} id the id of the toolbar to prefix this DOM container with. */ _createColorPicker: function(id) { if (Dom.get(id + '_colors')) { Dom.get(id + '_colors').parentNode.removeChild(Dom.get(id + '_colors')); } var picker = document.createElement('div'); picker.className = 'yui-toolbar-colors'; picker.id = id + '_colors'; picker.style.display = 'none'; Event.on(window, 'load', function() { document.body.appendChild(picker); }, this, true); this._colorPicker = picker; var html = ''; for (var i in this._colorData) { if (Lang.hasOwnProperty(this._colorData, i)) { html += '' + i.replace('#', '') + ''; } } html += 'X'; window.setTimeout(function() { picker.innerHTML = html; }, 0); Event.on(picker, 'mouseover', function(ev) { var picker = this._colorPicker; var em = picker.getElementsByTagName('em')[0]; var strong = picker.getElementsByTagName('strong')[0]; var tar = Event.getTarget(ev); if (tar.tagName.toLowerCase() == 'a') { em.style.backgroundColor = tar.style.backgroundColor; strong.innerHTML = this._colorData['#' + tar.innerHTML] + '
                  ' + tar.innerHTML; } }, this, true); Event.on(picker, 'focus', function(ev) { Event.stopEvent(ev); }); Event.on(picker, 'click', function(ev) { Event.stopEvent(ev); }); Event.on(picker, 'mousedown', function(ev) { Event.stopEvent(ev); var tar = Event.getTarget(ev); if (tar.tagName.toLowerCase() == 'a') { var retVal = this.fireEvent('colorPickerClicked', { type: 'colorPickerClicked', target: this, button: this._colorPicker._button, color: tar.innerHTML, colorName: this._colorData['#' + tar.innerHTML] } ); if (retVal !== false) { var info = { color: tar.innerHTML, colorName: this._colorData['#' + tar.innerHTML], value: this._colorPicker._button }; this.fireEvent('buttonClick', { type: 'buttonClick', target: this.get('element'), button: info }); } this.getButtonByValue(this._colorPicker._button).getMenu().hide(); } }, this, true); }, /** * @method _resetColorPicker * @private * @description Clears the currently selected color or mouseover color in the color picker. */ _resetColorPicker: function() { var em = this._colorPicker.getElementsByTagName('em')[0]; var strong = this._colorPicker.getElementsByTagName('strong')[0]; em.style.backgroundColor = 'transparent'; strong.innerHTML = ''; }, /** * @method _makeColorButton * @private * @description Called to turn a "color" button into a menu button with an Overlay for the menu. * @param {Object} _oButton YAHOO.widget.ToolbarButton reference */ _makeColorButton: function(_oButton) { if (!this._colorPicker) { this._createColorPicker(this.get('id')); } _oButton.type = 'color'; _oButton.menu = new YAHOO.widget.Overlay(this.get('id') + '_' + _oButton.value + '_menu', { visible: false, position: 'absolute', iframe: true }); _oButton.menu.setBody(''); _oButton.menu.render(this.get('cont')); Dom.addClass(_oButton.menu.element, 'yui-button-menu'); Dom.addClass(_oButton.menu.element, 'yui-color-button-menu'); _oButton.menu.beforeShowEvent.subscribe(function() { _oButton.menu.cfg.setProperty('zindex', 5); //Re Adjust the overlays zIndex.. not sure why. _oButton.menu.cfg.setProperty('context', [this.getButtonById(_oButton.id).get('element'), 'tl', 'bl']); //Re Adjust the overlay.. not sure why. //Move the DOM reference of the color picker to the Overlay that we are about to show. this._resetColorPicker(); var _p = this._colorPicker; if (_p.parentNode) { _p.parentNode.removeChild(_p); } _oButton.menu.setBody(''); _oButton.menu.appendToBody(_p); this._colorPicker.style.display = 'block'; }, this, true); return _oButton; }, /** * @private * @method _makeSpinButton * @description Create a button similar to an OS Spin button.. It has an up/down arrow combo to scroll through a range of int values. * @param {Object} _button YAHOO.widget.ToolbarButton reference * @param {Object} oButton Object literal containing the buttons initial config */ _makeSpinButton: function(_button, oButton) { _button.addClass(this.CLASS_PREFIX + '-spinbutton'); var self = this, _par = _button._button.parentNode.parentNode, //parentNode of Button Element for appending child range = oButton.range, _b1 = document.createElement('a'), _b2 = document.createElement('a'); _b1.href = '#'; _b2.href = '#'; _b1.tabIndex = '-1'; _b2.tabIndex = '-1'; //Setup the up and down arrows _b1.className = 'up'; _b1.title = this.STR_SPIN_UP; _b1.innerHTML = this.STR_SPIN_UP; _b2.className = 'down'; _b2.title = this.STR_SPIN_DOWN; _b2.innerHTML = this.STR_SPIN_DOWN; //Append them to the container _par.appendChild(_b1); _par.appendChild(_b2); var label = YAHOO.lang.substitute(this.STR_SPIN_LABEL, { VALUE: _button.get('label') }); _button.set('title', label); var cleanVal = function(value) { value = ((value < range[0]) ? range[0] : value); value = ((value > range[1]) ? range[1] : value); return value; }; var br = this.browser; var tbar = false; var strLabel = this.STR_SPIN_LABEL; if (this._titlebar && this._titlebar.firstChild) { tbar = this._titlebar.firstChild; } var _intUp = function(ev) { YAHOO.util.Event.stopEvent(ev); if (!_button.get('disabled') && (ev.keyCode != 9)) { var value = parseInt(_button.get('label'), 10); value++; value = cleanVal(value); _button.set('label', ''+value); var label = YAHOO.lang.substitute(strLabel, { VALUE: _button.get('label') }); _button.set('title', label); if (!br.webkit && tbar) { //tbar.focus(); //We do this for accessibility, on the re-focus of the element, a screen reader will re-read the title that was just changed //_button.focus(); } self._buttonClick(ev, oButton); } }; var _intDown = function(ev) { YAHOO.util.Event.stopEvent(ev); if (!_button.get('disabled') && (ev.keyCode != 9)) { var value = parseInt(_button.get('label'), 10); value--; value = cleanVal(value); _button.set('label', ''+value); var label = YAHOO.lang.substitute(strLabel, { VALUE: _button.get('label') }); _button.set('title', label); if (!br.webkit && tbar) { //tbar.focus(); //We do this for accessibility, on the re-focus of the element, a screen reader will re-read the title that was just changed //_button.focus(); } self._buttonClick(ev, oButton); } }; var _intKeyUp = function(ev) { if (ev.keyCode == 38) { _intUp(ev); } else if (ev.keyCode == 40) { _intDown(ev); } else if (ev.keyCode == 107 && ev.shiftKey) { //Plus Key _intUp(ev); } else if (ev.keyCode == 109 && ev.shiftKey) { //Minus Key _intDown(ev); } }; //Handle arrow keys.. _button.on('keydown', _intKeyUp, this, true); //Listen for the click on the up button and act on it //Listen for the click on the down button and act on it Event.on(_b1, 'mousedown',function(ev) { Event.stopEvent(ev); }, this, true); Event.on(_b2, 'mousedown', function(ev) { Event.stopEvent(ev); }, this, true); Event.on(_b1, 'click', _intUp, this, true); Event.on(_b2, 'click', _intDown, this, true); }, /** * @protected * @method _buttonClick * @description Click handler for all buttons in the toolbar. * @param {String} ev The event that was passed in. * @param {Object} info Object literal of information about the button that was clicked. */ _buttonClick: function(ev, info) { var doEvent = true; if (ev && ev.type == 'keypress') { if (ev.keyCode == 9) { doEvent = false; } else if ((ev.keyCode === 13) || (ev.keyCode === 0) || (ev.keyCode === 32)) { } else { doEvent = false; } } if (doEvent) { var fireNextEvent = true, retValue = false; info.isSelected = this.isSelected(info.id); if (info.value) { YAHOO.log('fireEvent::' + info.value + 'Click', 'info', 'Toolbar'); retValue = this.fireEvent(info.value + 'Click', { type: info.value + 'Click', target: this.get('element'), button: info }); if (retValue === false) { fireNextEvent = false; } } if (info.menucmd && fireNextEvent) { YAHOO.log('fireEvent::' + info.menucmd + 'Click', 'info', 'Toolbar'); retValue = this.fireEvent(info.menucmd + 'Click', { type: info.menucmd + 'Click', target: this.get('element'), button: info }); if (retValue === false) { fireNextEvent = false; } } if (fireNextEvent) { YAHOO.log('fireEvent::buttonClick', 'info', 'Toolbar'); this.fireEvent('buttonClick', { type: 'buttonClick', target: this.get('element'), button: info }); } if (info.type == 'select') { var button = this.getButtonById(info.id); if (button.buttonType == 'rich') { var txt = info.value; for (var i = 0; i < info.menu.length; i++) { if (info.menu[i].value == info.value) { txt = info.menu[i].text; break; } } button.set('label', '' + txt + ''); var _items = button.getMenu().getItems(); for (var m = 0; m < _items.length; m++) { if (_items[m].value.toLowerCase() == info.value.toLowerCase()) { _items[m].cfg.setProperty('checked', true); } else { _items[m].cfg.setProperty('checked', false); } } } } if (ev) { Event.stopEvent(ev); } } }, /** * @private * @property _keyNav * @description Flag to determine if the arrow nav listeners have been attached * @type Boolean */ _keyNav: null, /** * @private * @property _navCounter * @description Internal counter for walking the buttons in the toolbar with the arrow keys * @type Number */ _navCounter: null, /** * @private * @method _navigateButtons * @description Handles the navigation/focus of toolbar buttons with the Arrow Keys * @param {Event} ev The Key Event */ _navigateButtons: function(ev) { switch (ev.keyCode) { case 37: case 39: if (ev.keyCode == 37) { this._navCounter--; } else { this._navCounter++; } if (this._navCounter > (this._buttonList.length - 1)) { this._navCounter = 0; } if (this._navCounter < 0) { this._navCounter = (this._buttonList.length - 1); } if (this._buttonList[this._navCounter]) { var el = this._buttonList[this._navCounter].get('element'); if (this.browser.ie) { el = this._buttonList[this._navCounter].get('element').getElementsByTagName('a')[0]; } if (this._buttonList[this._navCounter].get('disabled')) { this._navigateButtons(ev); } else { el.focus(); } } break; } }, /** * @private * @method _handleFocus * @description Sets up the listeners for the arrow key navigation */ _handleFocus: function() { if (!this._keyNav) { var ev = 'keypress'; if (this.browser.ie) { ev = 'keydown'; } Event.on(this.get('element'), ev, this._navigateButtons, this, true); this._keyNav = true; this._navCounter = -1; } }, /** * @method getButtonById * @description Gets a button instance from the toolbar by is Dom id. * @param {String} id The Dom id to query for. * @return {YAHOO.widget.ToolbarButton} */ getButtonById: function(id) { var len = this._buttonList.length; for (var i = 0; i < len; i++) { if (this._buttonList[i] && this._buttonList[i].get('id') == id) { return this._buttonList[i]; } } return false; }, /** * @method getButtonByValue * @description Gets a button instance or a menuitem instance from the toolbar by it's value. * @param {String} value The button value to query for. * @return {YAHOO.widget.ToolbarButton or YAHOO.widget.MenuItem} */ getButtonByValue: function(value) { var _buttons = this.get('buttons'); if (!_buttons) { return false; } var len = _buttons.length; for (var i = 0; i < len; i++) { if (_buttons[i].group !== undefined) { for (var m = 0; m < _buttons[i].buttons.length; m++) { if ((_buttons[i].buttons[m].value == value) || (_buttons[i].buttons[m].menucmd == value)) { return this.getButtonById(_buttons[i].buttons[m].id); } if (_buttons[i].buttons[m].menu) { //Menu Button, loop through the values for (var s = 0; s < _buttons[i].buttons[m].menu.length; s++) { if (_buttons[i].buttons[m].menu[s].value == value) { return this.getButtonById(_buttons[i].buttons[m].id); } } } } } else { if ((_buttons[i].value == value) || (_buttons[i].menucmd == value)) { return this.getButtonById(_buttons[i].id); } if (_buttons[i].menu) { //Menu Button, loop through the values for (var j = 0; j < _buttons[i].menu.length; j++) { if (_buttons[i].menu[j].value == value) { return this.getButtonById(_buttons[i].id); } } } } } return false; }, /** * @method getButtonByIndex * @description Gets a button instance from the toolbar by is index in _buttonList. * @param {Number} index The index of the button in _buttonList. * @return {YAHOO.widget.ToolbarButton} */ getButtonByIndex: function(index) { if (this._buttonList[index]) { return this._buttonList[index]; } else { return false; } }, /** * @method getButtons * @description Returns an array of buttons in the current toolbar * @return {Array} */ getButtons: function() { return this._buttonList; }, /** * @method disableButton * @description Disables a button in the toolbar. * @param {String/Number} id Disable a button by it's id, index or value. * @return {Boolean} */ disableButton: function(id) { var button = getButton.call(this, id); if (button) { button.set('disabled', true); } else { return false; } }, /** * @method enableButton * @description Enables a button in the toolbar. * @param {String/Number} id Enable a button by it's id, index or value. * @return {Boolean} */ enableButton: function(id) { if (this.get('disabled')) { return false; } var button = getButton.call(this, id); if (button) { if (button.get('disabled')) { button.set('disabled', false); } } else { return false; } }, /** * @method isSelected * @description Tells if a button is selected or not. * @param {String/Number} id A button by it's id, index or value. * @return {Boolean} */ isSelected: function(id) { var button = getButton.call(this, id); if (button) { return button._selected; } return false; }, /** * @method selectButton * @description Selects a button in the toolbar. * @param {String/Number} id Select a button by it's id, index or value. * @param {String} value If this is a Menu Button, check this item in the menu * @return {Boolean} */ selectButton: function(id, value) { var button = getButton.call(this, id); if (button) { button.addClass('yui-button-selected'); button.addClass('yui-button-' + button.get('value') + '-selected'); button._selected = true; if (value) { if (button.buttonType == 'rich') { var _items = button.getMenu().getItems(); for (var m = 0; m < _items.length; m++) { if (_items[m].value == value) { _items[m].cfg.setProperty('checked', true); button.set('label', '' + _items[m]._oText.nodeValue + ''); } else { _items[m].cfg.setProperty('checked', false); } } } } } else { return false; } }, /** * @method deselectButton * @description Deselects a button in the toolbar. * @param {String/Number} id Deselect a button by it's id, index or value. * @return {Boolean} */ deselectButton: function(id) { var button = getButton.call(this, id); if (button) { button.removeClass('yui-button-selected'); button.removeClass('yui-button-' + button.get('value') + '-selected'); button.removeClass('yui-button-hover'); button._selected = false; } else { return false; } }, /** * @method deselectAllButtons * @description Deselects all buttons in the toolbar. * @return {Boolean} */ deselectAllButtons: function() { var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.deselectButton(this._buttonList[i]); } }, /** * @method disableAllButtons * @description Disables all buttons in the toolbar. * @return {Boolean} */ disableAllButtons: function() { if (this.get('disabled')) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.disableButton(this._buttonList[i]); } }, /** * @method enableAllButtons * @description Enables all buttons in the toolbar. * @return {Boolean} */ enableAllButtons: function() { if (this.get('disabled')) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.enableButton(this._buttonList[i]); } }, /** * @method resetAllButtons * @description Resets all buttons to their initial state. * @param {Object} _ex Except these buttons * @return {Boolean} */ resetAllButtons: function(_ex) { if (!Lang.isObject(_ex)) { _ex = {}; } if (this.get('disabled') || !this._buttonList) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { var _button = this._buttonList[i]; if (_button) { var disabled = _button._configs.disabled._initialConfig.value; if (_ex[_button.get('id')]) { this.enableButton(_button); this.selectButton(_button); } else { if (disabled) { this.disableButton(_button); } else { this.enableButton(_button); } this.deselectButton(_button); } } } }, /** * @method destroyButton * @description Destroy a button in the toolbar. * @param {String/Number} id Destroy a button by it's id or index. * @return {Boolean} */ destroyButton: function(id) { var button = getButton.call(this, id); if (button) { var thisID = button.get('id'), new_list = [], i = 0, len = this._buttonList.length; button.destroy(); for (i = 0; i < len; i++) { if (this._buttonList[i].get('id') != thisID) { new_list[new_list.length]= this._buttonList[i]; } } this._buttonList = new_list; } else { return false; } }, /** * @method destroy * @description Destroys the toolbar, all of it's elements and objects. * @return {Boolean} */ destroy: function() { var len = this._configuredButtons.length, j, i, b; for(b = 0; b < len; b++) { this.destroyButton(this._configuredButtons[b]); } this._configuredButtons = null; this.get('element').innerHTML = ''; this.get('element').className = ''; //Brutal Object Destroy for (i in this) { if (Lang.hasOwnProperty(this, i)) { this[i] = null; } } return true; }, /** * @method collapse * @description Programatically collapse the toolbar. * @param {Boolean} collapse True to collapse, false to expand. */ collapse: function(collapse) { var el = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapse === false) { Dom.removeClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed'); if (el[0]) { Dom.removeClass(el[0], 'collapsed'); el[0].title = this.STR_COLLAPSE; } this.fireEvent('toolbarExpanded', { type: 'toolbarExpanded', target: this }); } else { if (el[0]) { Dom.addClass(el[0], 'collapsed'); el[0].title = this.STR_EXPAND; } Dom.addClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed'); this.fireEvent('toolbarCollapsed', { type: 'toolbarCollapsed', target: this }); } }, /** * @method toString * @description Returns a string representing the toolbar. * @return {String} */ toString: function() { return 'Toolbar (#' + this.get('element').id + ') with ' + this._buttonList.length + ' buttons.'; } }); /** * @event buttonClick * @param {Object} o The object passed to this handler is the button config used to create the button. * @description Fires when any botton receives a click event. Passes back a single object representing the buttons config object. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event valueClick * @param {Object} o The object passed to this handler is the button config used to create the button. * @description This is a special dynamic event that is created and dispatched based on the value property * of the button config. See Element.addListener for more information on listening for this event. * Example: *
                  * buttons : [
                  *   { type: 'button', value: 'test', value: 'testButton' }
                  * ]
                  *
                  * With the valueClick event you could subscribe to this buttons click event with this: * tbar.in('testButtonClick', function() { alert('test button clicked'); }) * @type YAHOO.util.CustomEvent */ /** * @event toolbarExpanded * @description Fires when the toolbar is expanded via the collapse button. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event toolbarCollapsed * @description Fires when the toolbar is collapsed via the collapse button. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ })(); /** * @module editor * @description

                  The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization.

                  * @namespace YAHOO.widget * @requires yahoo, dom, element, event, toolbar * @optional animation, container_core, resize, dragdrop */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, Toolbar = YAHOO.widget.Toolbar; /** * The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization. * @constructor * @class SimpleEditor * @extends YAHOO.util.Element * @param {String/HTMLElement} el The textarea element to turn into an editor. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.SimpleEditor = function(el, attrs) { YAHOO.log('SimpleEditor Initalizing', 'info', 'SimpleEditor'); var o = {}; if (Lang.isObject(el) && (!el.tagName) && !attrs) { Lang.augmentObject(o, el); //Break the config reference el = document.createElement('textarea'); this.DOMReady = true; if (o.container) { var c = Dom.get(o.container); c.appendChild(el); } else { document.body.appendChild(el); } } else { if (attrs) { Lang.augmentObject(o, attrs); //Break the config reference } } var oConfig = { element: null, attributes: o }, id = null; if (Lang.isString(el)) { id = el; } else { if (oConfig.attributes.id) { id = oConfig.attributes.id; } else { this.DOMReady = true; id = Dom.generateId(el); } } oConfig.element = el; var element_cont = document.createElement('DIV'); oConfig.attributes.element_cont = new YAHOO.util.Element(element_cont, { id: id + '_container' }); var div = document.createElement('div'); Dom.addClass(div, 'first-child'); oConfig.attributes.element_cont.appendChild(div); if (!oConfig.attributes.toolbar_cont) { oConfig.attributes.toolbar_cont = document.createElement('DIV'); oConfig.attributes.toolbar_cont.id = id + '_toolbar'; div.appendChild(oConfig.attributes.toolbar_cont); } var editorWrapper = document.createElement('DIV'); div.appendChild(editorWrapper); oConfig.attributes.editor_wrapper = editorWrapper; YAHOO.widget.SimpleEditor.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.SimpleEditor, YAHOO.util.Element, { /** * @private * @property _resizeConfig * @description The default config for the Resize Utility */ _resizeConfig: { handles: ['br'], autoRatio: true, status: true, proxy: true, useShim: true, setSize: false }, /** * @private * @method _setupResize * @description Creates the Resize instance and binds its events. */ _setupResize: function() { if (!YAHOO.util.DD || !YAHOO.util.Resize) { return false; } if (this.get('resize')) { var config = {}; Lang.augmentObject(config, this._resizeConfig); //Break the config reference this.resize = new YAHOO.util.Resize(this.get('element_cont').get('element'), config); this.resize.on('resize', function(args) { var anim = this.get('animate'); this.set('animate', false); this.set('width', args.width + 'px'); var h = args.height, th = (this.toolbar.get('element').clientHeight + 2), dh = 0; if (this.dompath) { dh = (this.dompath.clientHeight + 1); //It has a 1px top border.. } var newH = (h - th - dh); this.set('height', newH + 'px'); this.get('element_cont').setStyle('height', ''); this.set('animate', anim); }, this, true); } }, /** * @property resize * @description A reference to the Resize object * @type YAHOO.util.Resize */ resize: null, /** * @private * @method _setupDD * @description Sets up the DD instance used from the 'drag' config option. */ _setupDD: function() { if (!YAHOO.util.DD) { return false; } if (this.get('drag')) { YAHOO.log('Attaching DD instance to Editor', 'info', 'SimpleEditor'); var d = this.get('drag'), dd = YAHOO.util.DD; if (d === 'proxy') { dd = YAHOO.util.DDProxy; } this.dd = new dd(this.get('element_cont').get('element')); this.toolbar.addClass('draggable'); this.dd.setHandleElId(this.toolbar._titlebar); } }, /** * @property dd * @description A reference to the DragDrop object. * @type YAHOO.util.DD/YAHOO.util.DDProxy */ dd: null, /** * @private * @property _lastCommand * @description A cache of the last execCommand (used for Undo/Redo so they don't mark an undo level) * @type String */ _lastCommand: null, _undoNodeChange: function() {}, _storeUndo: function() {}, /** * @private * @method _checkKey * @description Checks a keyMap entry against a key event * @param {Object} k The _keyMap object * @param {Event} e The Mouse Event * @return {Boolean} */ _checkKey: function(k, e) { var ret = false; if ((e.keyCode === k.key)) { if (k.mods && (k.mods.length > 0)) { var val = 0; for (var i = 0; i < k.mods.length; i++) { if (this.browser.mac) { if (k.mods[i] == 'ctrl') { k.mods[i] = 'meta'; } } if (e[k.mods[i] + 'Key'] === true) { val++; } } if (val === k.mods.length) { ret = true; } } else { ret = true; } } //YAHOO.log('Shortcut Key Check: (' + k.key + ') return: ' + ret, 'info', 'SimpleEditor'); return ret; }, /** * @private * @property _keyMap * @description Named key maps for various actions in the Editor. Example: CLOSE_WINDOW: { key: 87, mods: ['shift', 'ctrl'] }. * This entry shows that when key 87 (W) is found with the modifiers of shift and control, the window will close. You can customize this object to tweak keyboard shortcuts. * @type {Object/Mixed} */ _keyMap: { SELECT_ALL: { key: 65, //A key mods: ['ctrl'] }, CLOSE_WINDOW: { key: 87, //W key mods: ['shift', 'ctrl'] }, FOCUS_TOOLBAR: { key: 27, mods: ['shift'] }, FOCUS_AFTER: { key: 27 }, FONT_SIZE_UP: { key: 38, mods: ['shift', 'ctrl'] }, FONT_SIZE_DOWN: { key: 40, mods: ['shift', 'ctrl'] }, CREATE_LINK: { key: 76, mods: ['shift', 'ctrl'] }, BOLD: { key: 66, mods: ['shift', 'ctrl'] }, ITALIC: { key: 73, mods: ['shift', 'ctrl'] }, UNDERLINE: { key: 85, mods: ['shift', 'ctrl'] }, UNDO: { key: 90, mods: ['ctrl'] }, REDO: { key: 90, mods: ['shift', 'ctrl'] }, JUSTIFY_LEFT: { key: 219, mods: ['shift', 'ctrl'] }, JUSTIFY_CENTER: { key: 220, mods: ['shift', 'ctrl'] }, JUSTIFY_RIGHT: { key: 221, mods: ['shift', 'ctrl'] } }, /** * @private * @method _cleanClassName * @description Makes a useable classname from dynamic data, by dropping it to lowercase and replacing spaces with -'s. * @param {String} str The classname to clean up * @return {String} */ _cleanClassName: function(str) { return str.replace(/ /g, '-').toLowerCase(); }, /** * @property _textarea * @description Flag to determine if we are using a textarea or an HTML Node. * @type Boolean */ _textarea: null, /** * @property _docType * @description The DOCTYPE to use in the editable container. * @type String */ _docType: '', /** * @property editorDirty * @description This flag will be set when certain things in the Editor happen. It is to be used by the developer to check to see if content has changed. * @type Boolean */ editorDirty: null, /** * @property _defaultCSS * @description The default CSS used in the config for 'css'. This way you can add to the config like this: { css: YAHOO.widget.SimpleEditor.prototype._defaultCSS + 'ADD MYY CSS HERE' } * @type String */ _defaultCSS: 'html { height: 95%; } body { padding: 7px; background-color: #fff; font: 13px/1.22 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small; } a, a:visited, a:hover { color: blue !important; text-decoration: underline !important; cursor: text !important; } .warning-localfile { border-bottom: 1px dashed red !important; } .yui-busy { cursor: wait !important; } img.selected { border: 2px dotted #808080; } img { cursor: pointer !important; border: none; } body.ptags.webkit div.yui-wk-p { margin: 11px 0; } body.ptags.webkit div.yui-wk-div { margin: 0; }', /** * @property _defaultToolbar * @private * @description Default toolbar config. * @type Object */ _defaultToolbar: null, /** * @property _lastButton * @private * @description The last button pressed, so we don't disable it. * @type Object */ _lastButton: null, /** * @property _baseHREF * @private * @description The base location of the editable page (this page) so that relative paths for image work. * @type String */ _baseHREF: function() { var href = document.location.href; if (href.indexOf('?') !== -1) { //Remove the query string href = href.substring(0, href.indexOf('?')); } href = href.substring(0, href.lastIndexOf('/')) + '/'; return href; }(), /** * @property _lastImage * @private * @description Safari reference for the last image selected (for styling as selected). * @type HTMLElement */ _lastImage: null, /** * @property _blankImageLoaded * @private * @description Don't load the blank image more than once.. * @type Boolean */ _blankImageLoaded: null, /** * @property _fixNodesTimer * @private * @description Holder for the fixNodes timer * @type Date */ _fixNodesTimer: null, /** * @property _nodeChangeTimer * @private * @description Holds a reference to the nodeChange setTimeout call * @type Number */ _nodeChangeTimer: null, /** * @property _nodeChangeDelayTimer * @private * @description Holds a reference to the nodeChangeDelay setTimeout call * @type Number */ _nodeChangeDelayTimer: null, /** * @property _lastNodeChangeEvent * @private * @description Flag to determine the last event that fired a node change * @type Event */ _lastNodeChangeEvent: null, /** * @property _lastNodeChange * @private * @description Flag to determine when the last node change was fired * @type Date */ _lastNodeChange: 0, /** * @property _rendered * @private * @description Flag to determine if editor has been rendered or not * @type Boolean */ _rendered: null, /** * @property DOMReady * @private * @description Flag to determine if DOM is ready or not * @type Boolean */ DOMReady: null, /** * @property _selection * @private * @description Holder for caching iframe selections * @type Object */ _selection: null, /** * @property _mask * @private * @description DOM Element holder for the editor Mask when disabled * @type Object */ _mask: null, /** * @property _showingHiddenElements * @private * @description Status of the hidden elements button * @type Boolean */ _showingHiddenElements: null, /** * @property currentWindow * @description A reference to the currently open EditorWindow * @type Object */ currentWindow: null, /** * @property currentEvent * @description A reference to the current editor event * @type Event */ currentEvent: null, /** * @property operaEvent * @private * @description setTimeout holder for Opera and Image DoubleClick event.. * @type Object */ operaEvent: null, /** * @property currentFont * @description A reference to the last font selected from the Toolbar * @type HTMLElement */ currentFont: null, /** * @property currentElement * @description A reference to the current working element in the editor * @type Array */ currentElement: null, /** * @property dompath * @description A reference to the dompath container for writing the current working dom path to. * @type HTMLElement */ dompath: null, /** * @property beforeElement * @description A reference to the H2 placed before the editor for Accessibilty. * @type HTMLElement */ beforeElement: null, /** * @property afterElement * @description A reference to the H2 placed after the editor for Accessibilty. * @type HTMLElement */ afterElement: null, /** * @property invalidHTML * @description Contains a list of HTML elements that are invalid inside the editor. They will be removed when they are found. If you set the value of a key to "{ keepContents: true }", then the element will be replaced with a yui-non span to be filtered out when cleanHTML is called. The only tag that is ignored here is the span tag as it will force the Editor into a loop and freeze the browser. However.. all of these tags will be removed in the cleanHTML routine. * @type Object */ invalidHTML: { form: true, input: true, button: true, select: true, link: true, html: true, body: true, iframe: true, script: true, style: true, textarea: true }, /** * @property toolbar * @description Local property containing the YAHOO.widget.Toolbar instance * @type YAHOO.widget.Toolbar */ toolbar: null, /** * @private * @property _contentTimer * @description setTimeout holder for documentReady check */ _contentTimer: null, /** * @private * @property _contentTimerMax * @description The number of times the loaded content should be checked before giving up. Default: 500 */ _contentTimerMax: 500, /** * @private * @property _contentTimerCounter * @description Counter to check the number of times the body is polled for before giving up * @type Number */ _contentTimerCounter: 0, /** * @private * @property _disabled * @description The Toolbar items that should be disabled if there is no selection present in the editor. * @type Array */ _disabled: [ 'createlink', 'fontname', 'fontsize', 'forecolor', 'backcolor' ], /** * @private * @property _alwaysDisabled * @description The Toolbar items that should ALWAYS be disabled event if there is a selection present in the editor. * @type Object */ _alwaysDisabled: { undo: true, redo: true }, /** * @private * @property _alwaysEnabled * @description The Toolbar items that should ALWAYS be enabled event if there isn't a selection present in the editor. * @type Object */ _alwaysEnabled: { }, /** * @private * @property _semantic * @description The Toolbar commands that we should attempt to make tags out of instead of using styles. * @type Object */ _semantic: { 'bold': true, 'italic' : true, 'underline' : true }, /** * @private * @property _tag2cmd * @description A tag map of HTML tags to convert to the different types of commands so we can select the proper toolbar button. * @type Object */ _tag2cmd: { 'b': 'bold', 'strong': 'bold', 'i': 'italic', 'em': 'italic', 'u': 'underline', 'sup': 'superscript', 'sub': 'subscript', 'img': 'insertimage', 'a' : 'createlink', 'ul' : 'insertunorderedlist', 'ol' : 'insertorderedlist' }, /** * @private _createIframe * @description Creates the DOM and YUI Element for the iFrame editor area. * @param {String} id The string ID to prefix the iframe with * @return {Object} iFrame object */ _createIframe: function() { var ifrmDom = document.createElement('iframe'); ifrmDom.id = this.get('id') + '_editor'; var config = { border: '0', frameBorder: '0', marginWidth: '0', marginHeight: '0', leftMargin: '0', topMargin: '0', allowTransparency: 'true', width: '100%' }; if (this.get('autoHeight')) { config.scrolling = 'no'; } for (var i in config) { if (Lang.hasOwnProperty(config, i)) { ifrmDom.setAttribute(i, config[i]); } } var isrc = 'javascript:;'; if (this.browser.ie) { //isrc = 'about:blank'; //TODO - Check this, I have changed it before.. isrc = 'javascript:false;'; } ifrmDom.setAttribute('src', isrc); var ifrm = new YAHOO.util.Element(ifrmDom); ifrm.setStyle('visibility', 'hidden'); return ifrm; }, /** * @private _isElement * @description Checks to see if an Element reference is a valid one and has a certain tag type * @param {HTMLElement} el The element to check * @param {String} tag The tag that the element needs to be * @return {Boolean} */ _isElement: function(el, tag) { if (el && el.tagName && (el.tagName.toLowerCase() == tag)) { return true; } if (el && el.getAttribute && (el.getAttribute('tag') == tag)) { return true; } return false; }, /** * @private _hasParent * @description Checks to see if an Element reference or one of it's parents is a valid one and has a certain tag type * @param {HTMLElement} el The element to check * @param {String} tag The tag that the element needs to be * @return HTMLElement */ _hasParent: function(el, tag) { if (!el || !el.parentNode) { return false; } while (el.parentNode) { if (this._isElement(el, tag)) { return el; } if (el.parentNode) { el = el.parentNode; } else { return false; } } return false; }, /** * @private * @method _getDoc * @description Get the Document of the IFRAME * @return {Object} */ _getDoc: function() { var value = false; try { if (this.get('iframe').get('element').contentWindow.document) { value = this.get('iframe').get('element').contentWindow.document; return value; } } catch (e) { return false; } }, /** * @private * @method _getWindow * @description Get the Window of the IFRAME * @return {Object} */ _getWindow: function() { return this.get('iframe').get('element').contentWindow; }, /** * @method focus * @description Attempt to set the focus of the iframes window. */ focus: function() { this._getWindow().focus(); }, /** * @private * @depreciated - This should not be used, moved to this.focus(); * @method _focusWindow * @description Attempt to set the focus of the iframes window. */ _focusWindow: function() { YAHOO.log('_focusWindow: depreciated in favor of this.focus()', 'warn', 'Editor'); this.focus(); }, /** * @private * @method _hasSelection * @description Determines if there is a selection in the editor document. * @return {Boolean} */ _hasSelection: function() { var sel = this._getSelection(); var range = this._getRange(); var hasSel = false; if (!sel || !range) { return hasSel; } //Internet Explorer if (this.browser.ie) { if (range.text) { hasSel = true; } if (range.html) { hasSel = true; } } else { if (this.browser.webkit) { if (sel+'' !== '') { hasSel = true; } } else { if (sel && (sel.toString() !== '') && (sel !== undefined)) { hasSel = true; } } } return hasSel; }, /** * @private * @method _getSelection * @description Handles the different selection objects across the A-Grade list. * @return {Object} Selection Object */ _getSelection: function() { var _sel = null; if (this._getDoc() && this._getWindow()) { if (this._getDoc().selection &&! this.browser.opera) { _sel = this._getDoc().selection; } else { _sel = this._getWindow().getSelection(); } //Handle Safari's lack of Selection Object if (this.browser.webkit) { if (_sel.baseNode) { this._selection = {}; this._selection.baseNode = _sel.baseNode; this._selection.baseOffset = _sel.baseOffset; this._selection.extentNode = _sel.extentNode; this._selection.extentOffset = _sel.extentOffset; } else if (this._selection !== null) { _sel = this._getWindow().getSelection(); _sel.setBaseAndExtent( this._selection.baseNode, this._selection.baseOffset, this._selection.extentNode, this._selection.extentOffset); this._selection = null; } } } return _sel; }, /** * @private * @method _selectNode * @description Places the highlight around a given node * @param {HTMLElement} node The node to select */ _selectNode: function(node, collapse) { if (!node) { return false; } var sel = this._getSelection(), range = null; if (this.browser.ie) { try { //IE freaks out here sometimes.. range = this._getDoc().body.createTextRange(); range.moveToElementText(node); range.select(); } catch (e) { YAHOO.log('IE failed to select element: ' + node.tagName, 'warn', 'SimpleEditor'); } } else if (this.browser.webkit) { if (collapse) { sel.setBaseAndExtent(node, 1, node, node.innerText.length); } else { sel.setBaseAndExtent(node, 0, node, node.innerText.length); } } else if (this.browser.opera) { sel = this._getWindow().getSelection(); range = this._getDoc().createRange(); range.selectNode(node); sel.removeAllRanges(); sel.addRange(range); } else { range = this._getDoc().createRange(); range.selectNodeContents(node); sel.removeAllRanges(); sel.addRange(range); } //TODO - Check Performance this.nodeChange(); }, /** * @private * @method _getRange * @description Handles the different range objects across the A-Grade list. * @return {Object} Range Object */ _getRange: function() { var sel = this._getSelection(); if (sel === null) { return null; } if (this.browser.webkit && !sel.getRangeAt) { var _range = this._getDoc().createRange(); try { _range.setStart(sel.anchorNode, sel.anchorOffset); _range.setEnd(sel.focusNode, sel.focusOffset); } catch (e) { _range = this._getWindow().getSelection()+''; } return _range; } if (this.browser.ie) { try { return sel.createRange(); } catch (e2) { return null; } } if (sel.rangeCount > 0) { return sel.getRangeAt(0); } return null; }, /** * @private * @method _setDesignMode * @description Sets the designMode property of the iFrame document's body. * @param {String} state This should be either on or off */ _setDesignMode: function(state) { if (this.get('setDesignMode')) { try { this._getDoc().designMode = ((state.toLowerCase() == 'off') ? 'off' : 'on'); } catch(e) { } } }, /** * @private * @method _toggleDesignMode * @description Toggles the designMode property of the iFrame document on and off. * @return {String} The state that it was set to. */ _toggleDesignMode: function() { YAHOO.log('It is not recommended to use this method and it will be depreciated.', 'warn', 'SimpleEditor'); var _dMode = this._getDoc().designMode, _state = ((_dMode.toLowerCase() == 'on') ? 'off' : 'on'); this._setDesignMode(_state); return _state; }, /** * @private * @property _focused * @description Holder for trapping focus/blur state and prevent double events * @type Boolean */ _focused: null, /** * @private * @method _handleFocus * @description Handles the focus of the iframe. Note, this is window focus event, not an Editor focus event. * @param {Event} e The DOM Event */ _handleFocus: function(e) { if (!this._focused) { //YAHOO.log('Editor Window Focused', 'info', 'SimpleEditor'); this._focused = true; this.fireEvent('editorWindowFocus', { type: 'editorWindowFocus', target: this }); } }, /** * @private * @method _handleBlur * @description Handles the blur of the iframe. Note, this is window blur event, not an Editor blur event. * @param {Event} e The DOM Event */ _handleBlur: function(e) { if (this._focused) { //YAHOO.log('Editor Window Blurred', 'info', 'SimpleEditor'); this._focused = false; this.fireEvent('editorWindowBlur', { type: 'editorWindowBlur', target: this }); } }, /** * @private * @method _initEditorEvents * @description This method sets up the listeners on the Editors document. */ _initEditorEvents: function() { //Setup Listeners on iFrame var doc = this._getDoc(), win = this._getWindow(); Event.on(doc, 'mouseup', this._handleMouseUp, this, true); Event.on(doc, 'mousedown', this._handleMouseDown, this, true); Event.on(doc, 'click', this._handleClick, this, true); Event.on(doc, 'dblclick', this._handleDoubleClick, this, true); Event.on(doc, 'keypress', this._handleKeyPress, this, true); Event.on(doc, 'keyup', this._handleKeyUp, this, true); Event.on(doc, 'keydown', this._handleKeyDown, this, true); /* TODO -- Everyone but Opera works here.. Event.on(doc, 'paste', function() { YAHOO.log('PASTE', 'info', 'SimpleEditor'); }, this, true); */ //Focus and blur.. Event.on(win, 'focus', this._handleFocus, this, true); Event.on(win, 'blur', this._handleBlur, this, true); }, /** * @private * @method _removeEditorEvents * @description This method removes the listeners on the Editors document (for disabling). */ _removeEditorEvents: function() { //Remove Listeners on iFrame var doc = this._getDoc(), win = this._getWindow(); Event.removeListener(doc, 'mouseup', this._handleMouseUp, this, true); Event.removeListener(doc, 'mousedown', this._handleMouseDown, this, true); Event.removeListener(doc, 'click', this._handleClick, this, true); Event.removeListener(doc, 'dblclick', this._handleDoubleClick, this, true); Event.removeListener(doc, 'keypress', this._handleKeyPress, this, true); Event.removeListener(doc, 'keyup', this._handleKeyUp, this, true); Event.removeListener(doc, 'keydown', this._handleKeyDown, this, true); //Focus and blur.. Event.removeListener(win, 'focus', this._handleFocus, this, true); Event.removeListener(win, 'blur', this._handleBlur, this, true); }, _fixWebkitDivs: function() { if (this.browser.webkit) { var divs = this._getDoc().body.getElementsByTagName('div'); Dom.addClass(divs, 'yui-wk-div'); } }, /** * @private * @method _initEditor * @param {Boolean} raw Don't add events. * @description This method is fired from _checkLoaded when the document is ready. It turns on designMode and set's up the listeners. */ _initEditor: function(raw) { if (this._editorInit) { return; } this._editorInit = true; if (this.browser.ie) { this._getDoc().body.style.margin = '0'; } if (!this.get('disabled')) { this._setDesignMode('on'); this._contentTimerCounter = 0; } if (!this._getDoc().body) { YAHOO.log('Body is null, check again', 'error', 'SimpleEditor'); this._contentTimerCounter = 0; this._editorInit = false; this._checkLoaded(); return false; } YAHOO.log('editorLoaded', 'info', 'SimpleEditor'); if (!raw) { this.toolbar.on('buttonClick', this._handleToolbarClick, this, true); } if (!this.get('disabled')) { this._initEditorEvents(); this.toolbar.set('disabled', false); } if (raw) { this.fireEvent('editorContentReloaded', { type: 'editorreloaded', target: this }); } else { this.fireEvent('editorContentLoaded', { type: 'editorLoaded', target: this }); } this._fixWebkitDivs(); if (this.get('dompath')) { YAHOO.log('Delayed DomPath write', 'info', 'SimpleEditor'); var self = this; setTimeout(function() { self._writeDomPath.call(self); self._setupResize.call(self); }, 150); } var br = []; for (var i in this.browser) { if (this.browser[i]) { br.push(i); } } if (this.get('ptags')) { br.push('ptags'); } Dom.addClass(this._getDoc().body, br.join(' ')); this.nodeChange(true); }, /** * @private * @method _checkLoaded * @param {Boolean} raw Don't add events. * @description Called from a setTimeout loop to check if the iframes body.onload event has fired, then it will init the editor. */ _checkLoaded: function(raw) { this._editorInit = false; this._contentTimerCounter++; if (this._contentTimer) { clearTimeout(this._contentTimer); } if (this._contentTimerCounter > this._contentTimerMax) { YAHOO.log('ERROR: Body Did Not load', 'error', 'SimpleEditor'); return false; } var init = false; try { if (this._getDoc() && this._getDoc().body) { if (this.browser.ie) { if (this._getDoc().body.readyState == 'complete') { init = true; } } else { if (this._getDoc().body._rteLoaded === true) { init = true; } } } } catch (e) { init = false; YAHOO.log('checking body (e)' + e, 'error', 'SimpleEditor'); } if (init === true) { //The onload event has fired, clean up after ourselves and fire the _initEditor method YAHOO.log('Firing _initEditor', 'info', 'SimpleEditor'); this._initEditor(raw); } else { var self = this; this._contentTimer = setTimeout(function() { self._checkLoaded.call(self, raw); }, 20); } }, /** * @private * @method _setInitialContent * @param {Boolean} raw Don't add events. * @description This method will open the iframes content document and write the textareas value into it, then start the body.onload checking. */ _setInitialContent: function(raw) { YAHOO.log('Populating editor body with contents of the text area', 'info', 'SimpleEditor'); var value = ((this._textarea) ? this.get('element').value : this.get('element').innerHTML), doc = null; if (value === '') { value = '
                  '; } var html = Lang.substitute(this.get('html'), { TITLE: this.STR_TITLE, CONTENT: this._cleanIncomingHTML(value), CSS: this.get('css'), HIDDEN_CSS: ((this.get('hiddencss')) ? this.get('hiddencss') : '/* No Hidden CSS */'), EXTRA_CSS: ((this.get('extracss')) ? this.get('extracss') : '/* No Extra CSS */') }), check = true; html = html.replace(/RIGHT_BRACKET/gi, '{'); html = html.replace(/LEFT_BRACKET/gi, '}'); if (document.compatMode != 'BackCompat') { YAHOO.log('Adding Doctype to editable area', 'info', 'SimpleEditor'); html = this._docType + "\n" + html; } else { YAHOO.log('DocType skipped because we are in BackCompat Mode.', 'warn', 'SimpleEditor'); } if (this.browser.ie || this.browser.webkit || this.browser.opera || (navigator.userAgent.indexOf('Firefox/1.5') != -1)) { //Firefox 1.5 doesn't like setting designMode on an document created with a data url try { //Adobe AIR Code if (this.browser.air) { doc = this._getDoc().implementation.createHTMLDocument(); var origDoc = this._getDoc(); origDoc.open(); origDoc.close(); doc.open(); doc.write(html); doc.close(); var node = origDoc.importNode(doc.getElementsByTagName("html")[0], true); origDoc.replaceChild(node, origDoc.getElementsByTagName("html")[0]); origDoc.body._rteLoaded = true; } else { doc = this._getDoc(); doc.open(); doc.write(html); doc.close(); } } catch (e) { YAHOO.log('Setting doc failed.. (_setInitialContent)', 'error', 'SimpleEditor'); //Safari will only be here if we are hidden check = false; } } else { //This keeps Firefox 2 from writing the iframe to history preserving the back buttons functionality this.get('iframe').get('element').src = 'data:text/html;charset=utf-8,' + encodeURIComponent(html); } this.get('iframe').setStyle('visibility', ''); if (check) { this._checkLoaded(raw); } }, /** * @private * @method _setMarkupType * @param {String} action The action to take. Possible values are: css, default or semantic * @description This method will turn on/off the useCSS execCommand. */ _setMarkupType: function(action) { switch (this.get('markup')) { case 'css': this._setEditorStyle(true); break; case 'default': this._setEditorStyle(false); break; case 'semantic': case 'xhtml': if (this._semantic[action]) { this._setEditorStyle(false); } else { this._setEditorStyle(true); } break; } }, /** * Set the editor to use CSS instead of HTML * @param {Booleen} stat True/False */ _setEditorStyle: function(stat) { try { this._getDoc().execCommand('useCSS', false, !stat); } catch (ex) { } }, /** * @private * @method _getSelectedElement * @description This method will attempt to locate the element that was last interacted with, either via selection, location or event. * @return {HTMLElement} The currently selected element. */ _getSelectedElement: function() { var doc = this._getDoc(), range = null, sel = null, elm = null, check = true; if (this.browser.ie) { this.currentEvent = this._getWindow().event; //Event utility assumes window.event, so we need to reset it to this._getWindow().event; range = this._getRange(); if (range) { elm = range.item ? range.item(0) : range.parentElement(); if (this._hasSelection()) { //TODO //WTF.. Why can't I get an element reference here?!??! } if (elm === doc.body) { elm = null; } } if ((this.currentEvent !== null) && (this.currentEvent.keyCode === 0)) { elm = Event.getTarget(this.currentEvent); } } else { sel = this._getSelection(); range = this._getRange(); if (!sel || !range) { return null; } //TODO if (!this._hasSelection() && this.browser.webkit3) { //check = false; } if (this.browser.gecko) { //Added in 2.6.0 if (range.startContainer) { if (range.startContainer.nodeType === 3) { elm = range.startContainer.parentNode; } else if (range.startContainer.nodeType === 1) { elm = range.startContainer; } //Added in 2.7.0 if (this.currentEvent) { var tar = Event.getTarget(this.currentEvent); if (!this._isElement(tar, 'html')) { if (elm !== tar) { elm = tar; } } } } } if (check) { if (sel.anchorNode && (sel.anchorNode.nodeType == 3)) { if (sel.anchorNode.parentNode) { //next check parentNode elm = sel.anchorNode.parentNode; } if (sel.anchorNode.nextSibling != sel.focusNode.nextSibling) { elm = sel.anchorNode.nextSibling; } } if (this._isElement(elm, 'br')) { elm = null; } if (!elm) { elm = range.commonAncestorContainer; if (!range.collapsed) { if (range.startContainer == range.endContainer) { if (range.startOffset - range.endOffset < 2) { if (range.startContainer.hasChildNodes()) { elm = range.startContainer.childNodes[range.startOffset]; } } } } } } } if (this.currentEvent !== null) { try { switch (this.currentEvent.type) { case 'click': case 'mousedown': case 'mouseup': if (this.browser.webkit) { elm = Event.getTarget(this.currentEvent); } break; default: //Do nothing break; } } catch (e) { YAHOO.log('Firefox 1.5 errors here: ' + e, 'error', 'SimpleEditor'); } } else if ((this.currentElement && this.currentElement[0]) && (!this.browser.ie)) { //TODO is this still needed? //elm = this.currentElement[0]; } if (this.browser.opera || this.browser.webkit) { if (this.currentEvent && !elm) { elm = YAHOO.util.Event.getTarget(this.currentEvent); } } if (!elm || !elm.tagName) { elm = doc.body; } if (this._isElement(elm, 'html')) { //Safari sometimes gives us the HTML node back.. elm = doc.body; } if (this._isElement(elm, 'body')) { //make sure that body means this body not the parent.. elm = doc.body; } if (elm && !elm.parentNode) { //Not in document elm = doc.body; } if (elm === undefined) { elm = null; } return elm; }, /** * @private * @method _getDomPath * @description This method will attempt to build the DOM path from the currently selected element. * @param HTMLElement el The element to start with, if not provided _getSelectedElement is used * @return {Array} An array of node references that will create the DOM Path. */ _getDomPath: function(el) { if (!el) { el = this._getSelectedElement(); } var domPath = []; while (el !== null) { if (el.ownerDocument != this._getDoc()) { el = null; break; } //Check to see if we get el.nodeName and nodeType if (el.nodeName && el.nodeType && (el.nodeType == 1)) { domPath[domPath.length] = el; } if (this._isElement(el, 'body')) { break; } el = el.parentNode; } if (domPath.length === 0) { if (this._getDoc() && this._getDoc().body) { domPath[0] = this._getDoc().body; } } return domPath.reverse(); }, /** * @private * @method _writeDomPath * @description Write the current DOM path out to the dompath container below the editor. */ _writeDomPath: function() { var path = this._getDomPath(), pathArr = [], classPath = '', pathStr = ''; for (var i = 0; i < path.length; i++) { var tag = path[i].tagName.toLowerCase(); if ((tag == 'ol') && (path[i].type)) { tag += ':' + path[i].type; } if (Dom.hasClass(path[i], 'yui-tag')) { tag = path[i].getAttribute('tag'); } if ((this.get('markup') == 'semantic') || (this.get('markup') == 'xhtml')) { switch (tag) { case 'b': tag = 'strong'; break; case 'i': tag = 'em'; break; } } if (!Dom.hasClass(path[i], 'yui-non')) { if (Dom.hasClass(path[i], 'yui-tag')) { pathStr = tag; } else { classPath = ((path[i].className !== '') ? '.' + path[i].className.replace(/ /g, '.') : ''); if ((classPath.indexOf('yui') != -1) || (classPath.toLowerCase().indexOf('apple-style-span') != -1)) { classPath = ''; } pathStr = tag + ((path[i].id) ? '#' + path[i].id : '') + classPath; } switch (tag) { case 'body': pathStr = 'body'; break; case 'a': if (path[i].getAttribute('href', 2)) { pathStr += ':' + path[i].getAttribute('href', 2).replace('mailto:', '').replace('http:/'+'/', '').replace('https:/'+'/', ''); //May need to add others here ftp } break; case 'img': var h = path[i].height; var w = path[i].width; if (path[i].style.height) { h = parseInt(path[i].style.height, 10); } if (path[i].style.width) { w = parseInt(path[i].style.width, 10); } pathStr += '(' + w + 'x' + h + ')'; break; } if (pathStr.length > 10) { pathStr = '' + pathStr.substring(0, 10) + '...' + ''; } else { pathStr = '' + pathStr + ''; } pathArr[pathArr.length] = pathStr; } } var str = pathArr.join(' ' + this.SEP_DOMPATH + ' '); //Prevent flickering if (this.dompath.innerHTML != str) { this.dompath.innerHTML = str; } }, /** * @private * @method _fixNodes * @description Fix href and imgs as well as remove invalid HTML. */ _fixNodes: function() { try { var doc = this._getDoc(), els = []; for (var v in this.invalidHTML) { if (YAHOO.lang.hasOwnProperty(this.invalidHTML, v)) { if (v.toLowerCase() != 'span') { var tags = doc.body.getElementsByTagName(v); if (tags.length) { for (var i = 0; i < tags.length; i++) { els.push(tags[i]); } } } } } for (var h = 0; h < els.length; h++) { if (els[h].parentNode) { if (Lang.isObject(this.invalidHTML[els[h].tagName.toLowerCase()]) && this.invalidHTML[els[h].tagName.toLowerCase()].keepContents) { this._swapEl(els[h], 'span', function(el) { el.className = 'yui-non'; }); } else { els[h].parentNode.removeChild(els[h]); } } } var imgs = this._getDoc().getElementsByTagName('img'); Dom.addClass(imgs, 'yui-img'); } catch(e) {} }, /** * @private * @method _isNonEditable * @param Event ev The Dom event being checked * @description Method is called at the beginning of all event handlers to check if this element or a parent element has the class yui-noedit (this.CLASS_NOEDIT) applied. * If it does, then this method will stop the event and return true. The event handlers will then return false and stop the nodeChange from occuring. This method will also * disable and enable the Editor's toolbar based on the noedit state. * @return Boolean */ _isNonEditable: function(ev) { if (this.get('allowNoEdit')) { var el = Event.getTarget(ev); if (this._isElement(el, 'html')) { el = null; } var path = this._getDomPath(el); for (var i = (path.length - 1); i > -1; i--) { if (Dom.hasClass(path[i], this.CLASS_NOEDIT)) { //if (this.toolbar.get('disabled') === false) { // this.toolbar.set('disabled', true); //} try { this._getDoc().execCommand('enableObjectResizing', false, 'false'); } catch (e) {} this.nodeChange(); Event.stopEvent(ev); YAHOO.log('CLASS_NOEDIT found in DOM Path, stopping event', 'info', 'SimpleEditor'); return true; } } //if (this.toolbar.get('disabled') === true) { //Should only happen once.. //this.toolbar.set('disabled', false); try { this._getDoc().execCommand('enableObjectResizing', false, 'true'); } catch (e2) {} //} } return false; }, /** * @private * @method _setCurrentEvent * @param {Event} ev The event to cache * @description Sets the current event property */ _setCurrentEvent: function(ev) { this.currentEvent = ev; }, /** * @private * @method _handleClick * @param {Event} ev The event we are working on. * @description Handles all click events inside the iFrame document. */ _handleClick: function(ev) { var ret = this.fireEvent('beforeEditorClick', { type: 'beforeEditorClick', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); if (this.currentWindow) { this.closeWindow(); } if (this.currentWindow) { this.closeWindow(); } if (this.browser.webkit) { var tar =Event.getTarget(ev); if (this._isElement(tar, 'a') || this._isElement(tar.parentNode, 'a')) { Event.stopEvent(ev); this.nodeChange(); } } else { this.nodeChange(); } this.fireEvent('editorClick', { type: 'editorClick', target: this, ev: ev }); }, /** * @private * @method _handleMouseUp * @param {Event} ev The event we are working on. * @description Handles all mouseup events inside the iFrame document. */ _handleMouseUp: function(ev) { var ret = this.fireEvent('beforeEditorMouseUp', { type: 'beforeEditorMouseUp', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } //Don't set current event for mouseup. //It get's fired after a menu is closed and gives up a bogus event to work with //this._setCurrentEvent(ev); var self = this; if (this.browser.opera) { /* * @knownissue Opera appears to stop the MouseDown, Click and DoubleClick events on an image inside of a document with designMode on.. * @browser Opera * @description This work around traps the MouseUp event and sets a timer to check if another MouseUp event fires in so many seconds. If another event is fired, they we internally fire the DoubleClick event. */ var sel = Event.getTarget(ev); if (this._isElement(sel, 'img')) { this.nodeChange(); if (this.operaEvent) { clearTimeout(this.operaEvent); this.operaEvent = null; this._handleDoubleClick(ev); } else { this.operaEvent = window.setTimeout(function() { self.operaEvent = false; }, 700); } } } //This will stop Safari from selecting the entire document if you select all the text in the editor if (this.browser.webkit || this.browser.opera) { if (this.browser.webkit) { Event.stopEvent(ev); } } this.nodeChange(); this.fireEvent('editorMouseUp', { type: 'editorMouseUp', target: this, ev: ev }); }, /** * @private * @method _handleMouseDown * @param {Event} ev The event we are working on. * @description Handles all mousedown events inside the iFrame document. */ _handleMouseDown: function(ev) { var ret = this.fireEvent('beforeEditorMouseDown', { type: 'beforeEditorMouseDown', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); var sel = Event.getTarget(ev); if (this.browser.webkit && this._hasSelection()) { var _sel = this._getSelection(); if (!this.browser.webkit3) { _sel.collapse(true); } else { _sel.collapseToStart(); } } if (this.browser.webkit && this._lastImage) { Dom.removeClass(this._lastImage, 'selected'); this._lastImage = null; } if (this._isElement(sel, 'img') || this._isElement(sel, 'a')) { if (this.browser.webkit) { Event.stopEvent(ev); if (this._isElement(sel, 'img')) { Dom.addClass(sel, 'selected'); this._lastImage = sel; } } if (this.currentWindow) { this.closeWindow(); } this.nodeChange(); } this.fireEvent('editorMouseDown', { type: 'editorMouseDown', target: this, ev: ev }); }, /** * @private * @method _handleDoubleClick * @param {Event} ev The event we are working on. * @description Handles all doubleclick events inside the iFrame document. */ _handleDoubleClick: function(ev) { var ret = this.fireEvent('beforeEditorDoubleClick', { type: 'beforeEditorDoubleClick', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); var sel = Event.getTarget(ev); if (this._isElement(sel, 'img')) { this.currentElement[0] = sel; this.toolbar.fireEvent('insertimageClick', { type: 'insertimageClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); } else if (this._hasParent(sel, 'a')) { //Handle elements inside an a this.currentElement[0] = this._hasParent(sel, 'a'); this.toolbar.fireEvent('createlinkClick', { type: 'createlinkClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); } this.nodeChange(); this.fireEvent('editorDoubleClick', { type: 'editorDoubleClick', target: this, ev: ev }); }, /** * @private * @method _handleKeyUp * @param {Event} ev The event we are working on. * @description Handles all keyup events inside the iFrame document. */ _handleKeyUp: function(ev) { var ret = this.fireEvent('beforeEditorKeyUp', { type: 'beforeEditorKeyUp', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._storeUndo(); this._setCurrentEvent(ev); switch (ev.keyCode) { case this._keyMap.SELECT_ALL.key: if (this._checkKey(this._keyMap.SELECT_ALL, ev)) { this.nodeChange(); } break; case 32: //Space Bar case 35: //End case 36: //Home case 37: //Left Arrow case 38: //Up Arrow case 39: //Right Arrow case 40: //Down Arrow case 46: //Forward Delete case 8: //Delete case this._keyMap.CLOSE_WINDOW.key: //W key if window is open if ((ev.keyCode == this._keyMap.CLOSE_WINDOW.key) && this.currentWindow) { if (this._checkKey(this._keyMap.CLOSE_WINDOW, ev)) { this.closeWindow(); } } else { if (!this.browser.ie) { if (this._nodeChangeTimer) { clearTimeout(this._nodeChangeTimer); } var self = this; this._nodeChangeTimer = setTimeout(function() { self._nodeChangeTimer = null; self.nodeChange.call(self); }, 100); } else { this.nodeChange(); } this.editorDirty = true; } break; } this.fireEvent('editorKeyUp', { type: 'editorKeyUp', target: this, ev: ev }); }, /** * @private * @method _handleKeyPress * @param {Event} ev The event we are working on. * @description Handles all keypress events inside the iFrame document. */ _handleKeyPress: function(ev) { var ret = this.fireEvent('beforeEditorKeyPress', { type: 'beforeEditorKeyPress', target: this, ev: ev }); if (ret === false) { return false; } if (this.get('allowNoEdit')) { //if (ev && ev.keyCode && ((ev.keyCode == 46) || ev.keyCode == 63272)) { if (ev && ev.keyCode && (ev.keyCode == 63272)) { //Forward delete key YAHOO.log('allowNoEdit is set, forward delete key has been disabled', 'warn', 'SimpleEditor'); Event.stopEvent(ev); } } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); this._storeUndo(); if (this.browser.opera) { if (ev.keyCode === 13) { var tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { this.execCommand('inserthtml', '
                  '); Event.stopEvent(ev); } } } if (this.browser.webkit) { if (!this.browser.webkit3) { if (ev.keyCode && (ev.keyCode == 122) && (ev.metaKey)) { //This is CMD + z (for undo) if (this._hasParent(this._getSelectedElement(), 'li')) { YAHOO.log('We are in an LI and we found CMD + z, stopping the event', 'warn', 'SimpleEditor'); Event.stopEvent(ev); } } } this._listFix(ev); } this._fixListDupIds(); this.fireEvent('editorKeyPress', { type: 'editorKeyPress', target: this, ev: ev }); }, /** * @private * @method _handleKeyDown * @param {Event} ev The event we are working on. * @description Handles all keydown events inside the iFrame document. */ _handleKeyDown: function(ev) { var ret = this.fireEvent('beforeEditorKeyDown', { type: 'beforeEditorKeyDown', target: this, ev: ev }); if (ret === false) { return false; } var tar = null, _range = null; if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); if (this.currentWindow) { this.closeWindow(); } if (this.currentWindow) { this.closeWindow(); } var doExec = false, action = null, value = null, exec = false; //YAHOO.log('keyCode: ' + ev.keyCode, 'info', 'SimpleEditor'); switch (ev.keyCode) { case this._keyMap.FOCUS_TOOLBAR.key: if (this._checkKey(this._keyMap.FOCUS_TOOLBAR, ev)) { var h = this.toolbar.getElementsByTagName('h2')[0]; if (h && h.firstChild) { h.firstChild.focus(); } } else if (this._checkKey(this._keyMap.FOCUS_AFTER, ev)) { //Focus After Element - Esc this.afterElement.focus(); } Event.stopEvent(ev); doExec = false; break; //case 76: //L case this._keyMap.CREATE_LINK.key: //L if (this._hasSelection()) { if (this._checkKey(this._keyMap.CREATE_LINK, ev)) { var makeLink = true; if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('createlink')) { YAHOO.log('Toolbar Button for (createlink) was not found, skipping exec.', 'info', 'SimpleEditor'); makeLink = false; } } if (makeLink) { this.execCommand('createlink', ''); this.toolbar.fireEvent('createlinkClick', { type: 'createlinkClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); doExec = false; } } } break; //case 90: //Z case this._keyMap.UNDO.key: case this._keyMap.REDO.key: if (this._checkKey(this._keyMap.REDO, ev)) { action = 'redo'; doExec = true; } else if (this._checkKey(this._keyMap.UNDO, ev)) { action = 'undo'; doExec = true; } break; //case 66: //B case this._keyMap.BOLD.key: if (this._checkKey(this._keyMap.BOLD, ev)) { action = 'bold'; doExec = true; } break; case this._keyMap.FONT_SIZE_UP.key: case this._keyMap.FONT_SIZE_DOWN.key: var uk = false, dk = false; if (this._checkKey(this._keyMap.FONT_SIZE_UP, ev)) { uk = true; } if (this._checkKey(this._keyMap.FONT_SIZE_DOWN, ev)) { dk = true; } if (uk || dk) { var fs_button = this.toolbar.getButtonByValue('fontsize'), label = parseInt(fs_button.get('label'), 10), newValue = (label + 1); if (dk) { newValue = (label - 1); } action = 'fontsize'; value = newValue + 'px'; doExec = true; } break; //case 73: //I case this._keyMap.ITALIC.key: if (this._checkKey(this._keyMap.ITALIC, ev)) { action = 'italic'; doExec = true; } break; //case 85: //U case this._keyMap.UNDERLINE.key: if (this._checkKey(this._keyMap.UNDERLINE, ev)) { action = 'underline'; doExec = true; } break; case 9: if (this.browser.ie) { //Insert a tab in Internet Explorer _range = this._getRange(); tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { if (_range) { _range.pasteHTML('    '); _range.collapse(false); _range.select(); } Event.stopEvent(ev); } } //Firefox 3 code if (this.browser.gecko > 1.8) { tar = this._getSelectedElement(); if (this._isElement(tar, 'li')) { if (ev.shiftKey) { this._getDoc().execCommand('outdent', null, ''); } else { this._getDoc().execCommand('indent', null, ''); } } else if (!this._hasSelection()) { this.execCommand('inserthtml', '    '); } Event.stopEvent(ev); } break; case 13: var p = null, i = 0; if (this.get('ptags') && !ev.shiftKey) { if (this.browser.gecko) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { if (this._hasParent(tar, 'p')) { p = this._getDoc().createElement('p'); p.innerHTML = ' '; Dom.insertAfter(p, tar); this._selectNode(p.firstChild); } else if (this._isElement(tar, 'body')) { this.execCommand('insertparagraph', null); var ps = this._getDoc().body.getElementsByTagName('p'); for (i = 0; i < ps.length; i++) { if (ps[i].getAttribute('_moz_dirty') !== null) { p = this._getDoc().createElement('p'); p.innerHTML = ' '; Dom.insertAfter(p, ps[i]); this._selectNode(p.firstChild); ps[i].removeAttribute('_moz_dirty'); } } } else { YAHOO.log('Something went wrong with paragraphs, please file a bug!!', 'error', 'SimpleEditor'); doExec = true; action = 'insertparagraph'; } Event.stopEvent(ev); } } if (this.browser.webkit) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { this.execCommand('insertparagraph', null); var divs = this._getDoc().body.getElementsByTagName('div'); for (i = 0; i < divs.length; i++) { if (!Dom.hasClass(divs[i], 'yui-wk-div')) { Dom.addClass(divs[i], 'yui-wk-p'); } } Event.stopEvent(ev); } } } else { if (this.browser.webkit) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { if (this.browser.webkit4) { this.execCommand('insertlinebreak'); } else { this.execCommand('inserthtml', ''); var holder = this._getDoc().getElementById('yui-br'), br = this._getDoc().createElement('br'), caret = this._getDoc().createElement('span'); holder.parentNode.replaceChild(br, holder); caret.className = 'yui-non'; caret.innerHTML = ' '; Dom.insertAfter(caret, br); this._selectNode(caret); } Event.stopEvent(ev); } } if (this.browser.ie) { YAHOO.log('Stopping P tags', 'info', 'SimpleEditor'); //Insert a
                  instead of a

                  in Internet Explorer _range = this._getRange(); tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { if (_range) { _range.pasteHTML('
                  '); _range.collapse(false); _range.select(); } Event.stopEvent(ev); } } } break; } if (this.browser.ie) { this._listFix(ev); } if (doExec && action) { this.execCommand(action, value); Event.stopEvent(ev); this.nodeChange(); } this._storeUndo(); this.fireEvent('editorKeyDown', { type: 'editorKeyDown', target: this, ev: ev }); }, /** * @private * @property _fixListRunning * @type Boolean * @description Keeps more than one _fixListDupIds from running at the same time. */ _fixListRunning: null, /** * @private * @method _fixListDupIds * @description Some browsers will duplicate the id of an LI when created in designMode. * This method will fix the duplicate id issue. However it will only preserve the first element * in the document list with the unique id. */ _fixListDupIds: function() { if (this._fixListRunning) { return false; } if (this._getDoc()) { this._fixListRunning = true; var lis = this._getDoc().body.getElementsByTagName('li'), i = 0, ids = {}; for (i = 0; i < lis.length; i++) { if (lis[i].id) { if (ids[lis[i].id]) { lis[i].id = ''; } ids[lis[i].id] = true; } } this._fixListRunning = false; } }, /** * @private * @method _listFix * @param {Event} ev The event we are working on. * @description Handles the Enter key, Tab Key and Shift + Tab keys for List Items. */ _listFix: function(ev) { //YAHOO.log('Lists Fix (' + ev.keyCode + ')', 'info', 'SimpleEditor'); var testLi = null, par = null, preContent = false, range = null; //Enter Key if (this.browser.webkit) { if (ev.keyCode && (ev.keyCode == 13)) { if (this._hasParent(this._getSelectedElement(), 'li')) { var tar = this._hasParent(this._getSelectedElement(), 'li'); if (tar.previousSibling) { if (tar.firstChild && (tar.firstChild.length == 1)) { this._selectNode(tar); } } } } } //Shift + Tab Key if (ev.keyCode && ((!this.browser.webkit3 && (ev.keyCode == 25)) || ((this.browser.webkit3 || !this.browser.webkit) && ((ev.keyCode == 9) && ev.shiftKey)))) { testLi = this._getSelectedElement(); if (this._hasParent(testLi, 'li')) { testLi = this._hasParent(testLi, 'li'); YAHOO.log('We have a SHIFT tab in an LI, reverse it..', 'info', 'SimpleEditor'); if (this._hasParent(testLi, 'ul') || this._hasParent(testLi, 'ol')) { YAHOO.log('We have a double parent, move up a level', 'info', 'SimpleEditor'); par = this._hasParent(testLi, 'ul'); if (!par) { par = this._hasParent(testLi, 'ol'); } //YAHOO.log(par.previousSibling + ' :: ' + par.previousSibling.innerHTML); if (this._isElement(par.previousSibling, 'li')) { par.removeChild(testLi); par.parentNode.insertBefore(testLi, par.nextSibling); if (this.browser.ie) { range = this._getDoc().body.createTextRange(); range.moveToElementText(testLi); range.collapse(false); range.select(); } if (this.browser.webkit) { this._selectNode(testLi.firstChild); } Event.stopEvent(ev); } } } } //Tab Key if (ev.keyCode && ((ev.keyCode == 9) && (!ev.shiftKey))) { YAHOO.log('List Fix - Tab', 'info', 'SimpleEditor'); var preLi = this._getSelectedElement(); if (this._hasParent(preLi, 'li')) { preContent = this._hasParent(preLi, 'li').innerHTML; } //YAHOO.log('preLI: ' + preLi.tagName + ' :: ' + preLi.innerHTML); if (this.browser.webkit) { this._getDoc().execCommand('inserttext', false, '\t'); } testLi = this._getSelectedElement(); if (this._hasParent(testLi, 'li')) { YAHOO.log('We have a tab in an LI', 'info', 'SimpleEditor'); par = this._hasParent(testLi, 'li'); YAHOO.log('parLI: ' + par.tagName + ' :: ' + par.innerHTML); var newUl = this._getDoc().createElement(par.parentNode.tagName.toLowerCase()); if (this.browser.webkit) { var span = Dom.getElementsByClassName('Apple-tab-span', 'span', par); //Remove the span element that Safari puts in if (span[0]) { par.removeChild(span[0]); par.innerHTML = Lang.trim(par.innerHTML); //Put the HTML from the LI into this new LI if (preContent) { par.innerHTML = '' + preContent + ' '; } else { par.innerHTML = '  '; } } } else { if (preContent) { par.innerHTML = preContent + ' '; } else { par.innerHTML = ' '; } } par.parentNode.replaceChild(newUl, par); newUl.appendChild(par); if (this.browser.webkit) { this._getSelection().setBaseAndExtent(par.firstChild, 1, par.firstChild, par.firstChild.innerText.length); if (!this.browser.webkit3) { par.parentNode.parentNode.style.display = 'list-item'; setTimeout(function() { par.parentNode.parentNode.style.display = 'block'; }, 1); } } else if (this.browser.ie) { range = this._getDoc().body.createTextRange(); range.moveToElementText(par); range.collapse(false); range.select(); } else { this._selectNode(par); } Event.stopEvent(ev); } if (this.browser.webkit) { Event.stopEvent(ev); } this.nodeChange(); } }, /** * @method nodeChange * @param {Boolean} force Optional paramenter to skip the threshold counter * @description Handles setting up the toolbar buttons, getting the Dom path, fixing nodes. */ nodeChange: function(force) { var NCself = this; this._storeUndo(); if (this.get('nodeChangeDelay')) { this._nodeChangeDelayTimer = window.setTimeout(function() { NCself._nodeChangeDelayTimer = null; NCself._nodeChange.apply(NCself, arguments); }, 0); } else { this._nodeChange(); } }, /** * @private * @method _nodeChange * @param {Boolean} force Optional paramenter to skip the threshold counter * @description Fired from nodeChange in a setTimeout. */ _nodeChange: function(force) { var threshold = parseInt(this.get('nodeChangeThreshold'), 10), thisNodeChange = Math.round(new Date().getTime() / 1000), self = this; if (force === true) { this._lastNodeChange = 0; } if ((this._lastNodeChange + threshold) < thisNodeChange) { if (this._fixNodesTimer === null) { this._fixNodesTimer = window.setTimeout(function() { self._fixNodes.call(self); self._fixNodesTimer = null; }, 0); } } this._lastNodeChange = thisNodeChange; if (this.currentEvent) { try { this._lastNodeChangeEvent = this.currentEvent.type; } catch (e) {} } var beforeNodeChange = this.fireEvent('beforeNodeChange', { type: 'beforeNodeChange', target: this }); if (beforeNodeChange === false) { return false; } if (this.get('dompath')) { window.setTimeout(function() { self._writeDomPath.call(self); }, 0); } //Check to see if we are disabled before continuing if (!this.get('disabled')) { if (this.STOP_NODE_CHANGE) { //Reset this var for next action this.STOP_NODE_CHANGE = false; return false; } else { var sel = this._getSelection(), range = this._getRange(), el = this._getSelectedElement(), fn_button = this.toolbar.getButtonByValue('fontname'), fs_button = this.toolbar.getButtonByValue('fontsize'), undo_button = this.toolbar.getButtonByValue('undo'), redo_button = this.toolbar.getButtonByValue('redo'); //Handle updating the toolbar with active buttons var _ex = {}; if (this._lastButton) { _ex[this._lastButton.id] = true; //this._lastButton = null; } if (!this._isElement(el, 'body')) { if (fn_button) { _ex[fn_button.get('id')] = true; } if (fs_button) { _ex[fs_button.get('id')] = true; } } if (redo_button) { delete _ex[redo_button.get('id')]; } this.toolbar.resetAllButtons(_ex); //Handle disabled buttons for (var d = 0; d < this._disabled.length; d++) { var _button = this.toolbar.getButtonByValue(this._disabled[d]); if (_button && _button.get) { if (this._lastButton && (_button.get('id') === this._lastButton.id)) { //Skip } else { if (!this._hasSelection() && !this.get('insert')) { switch (this._disabled[d]) { case 'fontname': case 'fontsize': break; default: //No Selection - disable this.toolbar.disableButton(_button); } } else { if (!this._alwaysDisabled[this._disabled[d]]) { this.toolbar.enableButton(_button); } } if (!this._alwaysEnabled[this._disabled[d]]) { this.toolbar.deselectButton(_button); } } } } var path = this._getDomPath(); var tag = null, cmd = null; for (var i = 0; i < path.length; i++) { tag = path[i].tagName.toLowerCase(); if (path[i].getAttribute('tag')) { tag = path[i].getAttribute('tag').toLowerCase(); } cmd = this._tag2cmd[tag]; if (cmd === undefined) { cmd = []; } if (!Lang.isArray(cmd)) { cmd = [cmd]; } //Bold and Italic styles if (path[i].style.fontWeight.toLowerCase() == 'bold') { cmd[cmd.length] = 'bold'; } if (path[i].style.fontStyle.toLowerCase() == 'italic') { cmd[cmd.length] = 'italic'; } if (path[i].style.textDecoration.toLowerCase() == 'underline') { cmd[cmd.length] = 'underline'; } if (path[i].style.textDecoration.toLowerCase() == 'line-through') { cmd[cmd.length] = 'strikethrough'; } if (cmd.length > 0) { for (var j = 0; j < cmd.length; j++) { this.toolbar.selectButton(cmd[j]); this.toolbar.enableButton(cmd[j]); } } //Handle Alignment switch (path[i].style.textAlign.toLowerCase()) { case 'left': case 'right': case 'center': case 'justify': var alignType = path[i].style.textAlign.toLowerCase(); if (path[i].style.textAlign.toLowerCase() == 'justify') { alignType = 'full'; } this.toolbar.selectButton('justify' + alignType); this.toolbar.enableButton('justify' + alignType); break; } } //After for loop //Reset Font Family and Size to the inital configs if (fn_button) { var family = fn_button._configs.label._initialConfig.value; fn_button.set('label', '' + family + ''); this._updateMenuChecked('fontname', family); } if (fs_button) { fs_button.set('label', fs_button._configs.label._initialConfig.value); } var hd_button = this.toolbar.getButtonByValue('heading'); if (hd_button) { hd_button.set('label', hd_button._configs.label._initialConfig.value); this._updateMenuChecked('heading', 'none'); } var img_button = this.toolbar.getButtonByValue('insertimage'); if (img_button && this.currentWindow && (this.currentWindow.name == 'insertimage')) { this.toolbar.disableButton(img_button); } if (this._lastButton && this._lastButton.isSelected) { this.toolbar.deselectButton(this._lastButton.id); } this._undoNodeChange(); } } this.fireEvent('afterNodeChange', { type: 'afterNodeChange', target: this }); }, /** * @private * @method _updateMenuChecked * @param {Object} button The command identifier of the button you want to check * @param {String} value The value of the menu item you want to check * @param {YAHOO.widget.Toolbar} The Toolbar instance the button belongs to (defaults to this.toolbar) * @description Gets the menu from a button instance, if the menu is not rendered it will render it. It will then search the menu for the specified value, unchecking all other items and checking the specified on. */ _updateMenuChecked: function(button, value, tbar) { if (!tbar) { tbar = this.toolbar; } var _button = tbar.getButtonByValue(button); _button.checkValue(value); }, /** * @private * @method _handleToolbarClick * @param {Event} ev The event that triggered the button click * @description This is an event handler attached to the Toolbar's buttonClick event. It will fire execCommand with the command identifier from the Toolbar Button. */ _handleToolbarClick: function(ev) { var value = ''; var str = ''; var cmd = ev.button.value; if (ev.button.menucmd) { value = cmd; cmd = ev.button.menucmd; } this._lastButton = ev.button; if (this.STOP_EXEC_COMMAND) { YAHOO.log('execCommand skipped because we found the STOP_EXEC_COMMAND flag set to true', 'warn', 'SimpleEditor'); YAHOO.log('NOEXEC::execCommand::(' + cmd + '), (' + value + ')', 'warn', 'SimpleEditor'); this.STOP_EXEC_COMMAND = false; return false; } else { this.execCommand(cmd, value); if (!this.browser.webkit) { var Fself = this; setTimeout(function() { Fself.focus.call(Fself); }, 5); } } Event.stopEvent(ev); }, /** * @private * @method _setupAfterElement * @description Creates the accessibility h2 header and places it after the iframe in the Dom for navigation. */ _setupAfterElement: function() { if (!this.beforeElement) { this.beforeElement = document.createElement('h2'); this.beforeElement.className = 'yui-editor-skipheader'; this.beforeElement.tabIndex = '-1'; this.beforeElement.innerHTML = this.STR_BEFORE_EDITOR; this.get('element_cont').get('firstChild').insertBefore(this.beforeElement, this.toolbar.get('nextSibling')); } if (!this.afterElement) { this.afterElement = document.createElement('h2'); this.afterElement.className = 'yui-editor-skipheader'; this.afterElement.tabIndex = '-1'; this.afterElement.innerHTML = this.STR_LEAVE_EDITOR; this.get('element_cont').get('firstChild').appendChild(this.afterElement); } }, /** * @private * @method _disableEditor * @param {Boolean} disabled Pass true to disable, false to enable * @description Creates a mask to place over the Editor. */ _disableEditor: function(disabled) { var iframe, par, html, height; if (!this.get('disabled_iframe')) { iframe = this._createIframe(); iframe.set('id', 'disabled_' + this.get('iframe').get('id')); iframe.setStyle('height', '100%'); iframe.setStyle('display', 'none'); iframe.setStyle('visibility', 'visible'); this.set('disabled_iframe', iframe); par = this.get('iframe').get('parentNode'); par.appendChild(iframe.get('element')); } if (!iframe) { iframe = this.get('disabled_iframe'); } if (disabled) { this._orgIframe = this.get('iframe'); if (this.toolbar) { this.toolbar.set('disabled', true); } html = this.getEditorHTML(); height = this.get('iframe').get('offsetHeight'); iframe.setStyle('visibility', ''); iframe.setStyle('position', ''); iframe.setStyle('top', ''); iframe.setStyle('left', ''); this._orgIframe.setStyle('visibility', 'hidden'); this._orgIframe.setStyle('position', 'absolute'); this._orgIframe.setStyle('top', '-99999px'); this._orgIframe.setStyle('left', '-99999px'); this.set('iframe', iframe); this._setInitialContent(true); if (!this._mask) { this._mask = document.createElement('DIV'); Dom.addClass(this._mask, 'yui-editor-masked'); if (this.browser.ie) { this._mask.style.height = height + 'px'; } this.get('iframe').get('parentNode').appendChild(this._mask); } this.on('editorContentReloaded', function() { this._getDoc().body._rteLoaded = false; this.setEditorHTML(html); iframe.setStyle('display', 'block'); this.unsubscribeAll('editorContentReloaded'); }); } else { if (this._mask) { this._mask.parentNode.removeChild(this._mask); this._mask = null; if (this.toolbar) { this.toolbar.set('disabled', false); } iframe.setStyle('visibility', 'hidden'); iframe.setStyle('position', 'absolute'); iframe.setStyle('top', '-99999px'); iframe.setStyle('left', '-99999px'); this._orgIframe.setStyle('visibility', ''); this._orgIframe.setStyle('position', ''); this._orgIframe.setStyle('top', ''); this._orgIframe.setStyle('left', ''); this.set('iframe', this._orgIframe); this.focus(); var self = this; window.setTimeout(function() { self.nodeChange.call(self); }, 100); } } }, /** * @property SEP_DOMPATH * @description The value to place in between the Dom path items * @type String */ SEP_DOMPATH: '<', /** * @property STR_LEAVE_EDITOR * @description The accessibility string for the element after the iFrame * @type String */ STR_LEAVE_EDITOR: 'You have left the Rich Text Editor.', /** * @property STR_BEFORE_EDITOR * @description The accessibility string for the element before the iFrame * @type String */ STR_BEFORE_EDITOR: 'This text field can contain stylized text and graphics. To cycle through all formatting options, use the keyboard shortcut Shift + Escape to place focus on the toolbar and navigate between options with your arrow keys. To exit this text editor use the Escape key and continue tabbing.

                  Common formatting keyboard shortcuts:

                  • Control Shift B sets text to bold
                  • Control Shift I sets text to italic
                  • Control Shift U underlines text
                  • Control Shift L adds an HTML link
                  ', /** * @property STR_TITLE * @description The Title of the HTML document that is created in the iFrame * @type String */ STR_TITLE: 'Rich Text Area.', /** * @property STR_IMAGE_HERE * @description The text to place in the URL textbox when using the blankimage. * @type String */ STR_IMAGE_HERE: 'Image URL Here', /** * @property STR_IMAGE_URL * @description The label string for Image URL * @type String */ STR_IMAGE_URL: 'Image URL', /** * @property STR_LINK_URL * @description The label string for the Link URL. * @type String */ STR_LINK_URL: 'Link URL', /** * @protected * @property STOP_EXEC_COMMAND * @description Set to true when you want the default execCommand function to not process anything * @type Boolean */ STOP_EXEC_COMMAND: false, /** * @protected * @property STOP_NODE_CHANGE * @description Set to true when you want the default nodeChange function to not process anything * @type Boolean */ STOP_NODE_CHANGE: false, /** * @protected * @property CLASS_NOEDIT * @description CSS class applied to elements that are not editable. * @type String */ CLASS_NOEDIT: 'yui-noedit', /** * @protected * @property CLASS_CONTAINER * @description Default CSS class to apply to the editors container element * @type String */ CLASS_CONTAINER: 'yui-editor-container', /** * @protected * @property CLASS_EDITABLE * @description Default CSS class to apply to the editors iframe element * @type String */ CLASS_EDITABLE: 'yui-editor-editable', /** * @protected * @property CLASS_EDITABLE_CONT * @description Default CSS class to apply to the editors iframe's parent element * @type String */ CLASS_EDITABLE_CONT: 'yui-editor-editable-container', /** * @protected * @property CLASS_PREFIX * @description Default prefix for dynamically created class names * @type String */ CLASS_PREFIX: 'yui-editor', /** * @property browser * @description Standard browser detection * @type Object */ browser: function() { var br = YAHOO.env.ua; //Check for webkit3 if (br.webkit >= 420) { br.webkit3 = br.webkit; } else { br.webkit3 = 0; } if (br.webkit >= 530) { br.webkit4 = br.webkit; } else { br.webkit4 = 0; } br.mac = false; //Check for Mac if (navigator.userAgent.indexOf('Macintosh') !== -1) { br.mac = true; } return br; }(), /** * @method init * @description The Editor class' initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.log('init', 'info', 'SimpleEditor'); if (!this._defaultToolbar) { this._defaultToolbar = { collapse: true, titlebar: 'Text Editing Tools', draggable: false, buttons: [ { group: 'fontstyle', label: 'Font Name and Size', buttons: [ { type: 'select', label: 'Arial', value: 'fontname', disabled: true, menu: [ { text: 'Arial', checked: true }, { text: 'Arial Black' }, { text: 'Comic Sans MS' }, { text: 'Courier New' }, { text: 'Lucida Console' }, { text: 'Tahoma' }, { text: 'Times New Roman' }, { text: 'Trebuchet MS' }, { text: 'Verdana' } ] }, { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true } ] }, { type: 'separator' }, { group: 'textstyle', label: 'Font Style', buttons: [ { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' }, { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' }, { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' }, { type: 'push', label: 'Strike Through', value: 'strikethrough' }, { type: 'separator' }, { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true }, { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true } ] }, { type: 'separator' }, { group: 'indentlist', label: 'Lists', buttons: [ { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' }, { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' } ] }, { type: 'separator' }, { group: 'insertitem', label: 'Insert Item', buttons: [ { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true }, { type: 'push', label: 'Insert Image', value: 'insertimage' } ] } ] }; } YAHOO.widget.SimpleEditor.superclass.init.call(this, p_oElement, p_oAttributes); YAHOO.widget.EditorInfo._instances[this.get('id')] = this; this.currentElement = []; this.on('contentReady', function() { this.DOMReady = true; this.fireQueue(); }, this, true); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the editor. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the editor. */ initAttributes: function(attr) { YAHOO.widget.SimpleEditor.superclass.initAttributes.call(this, attr); var self = this; /** * @config setDesignMode * @description Should the Editor set designMode on the document. Default: true. * @default true * @type Boolean */ this.setAttributeConfig('setDesignMode', { value: ((attr.setDesignMode === false) ? false : true) }); /** * @config nodeChangeDelay * @description Do we wrap the nodeChange method in a timeout for performance. Default: true. * @default true * @type Boolean */ this.setAttributeConfig('nodeChangeDelay', { value: ((attr.nodeChangeDelay === false) ? false : true) }); /** * @config maxUndo * @description The max number of undo levels to store. * @default 30 * @type Number */ this.setAttributeConfig('maxUndo', { writeOnce: true, value: attr.maxUndo || 30 }); /** * @config ptags * @description If true, the editor uses <P> tags instead of <br> tags. (Use Shift + Enter to get a <br>) * @default false * @type Boolean */ this.setAttributeConfig('ptags', { writeOnce: true, value: attr.ptags || false }); /** * @config insert * @description If true, selection is not required for: fontname, fontsize, forecolor, backcolor. * @default false * @type Boolean */ this.setAttributeConfig('insert', { writeOnce: true, value: attr.insert || false, method: function(insert) { if (insert) { var buttons = { fontname: true, fontsize: true, forecolor: true, backcolor: true }; var tmp = this._defaultToolbar.buttons; for (var i = 0; i < tmp.length; i++) { if (tmp[i].buttons) { for (var a = 0; a < tmp[i].buttons.length; a++) { if (tmp[i].buttons[a].value) { if (buttons[tmp[i].buttons[a].value]) { delete tmp[i].buttons[a].disabled; } } } } } } } }); /** * @config container * @description Used when dynamically creating the Editor from Javascript with no default textarea. * We will create one and place it in this container. If no container is passed we will append to document.body. * @default false * @type HTMLElement */ this.setAttributeConfig('container', { writeOnce: true, value: attr.container || false }); /** * @config plainText * @description Process the inital textarea data as if it was plain text. Accounting for spaces, tabs and line feeds. * @default false * @type Boolean */ this.setAttributeConfig('plainText', { writeOnce: true, value: attr.plainText || false }); /** * @private * @config iframe * @description Internal config for holding the iframe element. * @default null * @type HTMLElement */ this.setAttributeConfig('iframe', { value: null }); /** * @private * @config disabled_iframe * @description Internal config for holding the iframe element used when disabling the Editor. * @default null * @type HTMLElement */ this.setAttributeConfig('disabled_iframe', { value: null }); /** * @private * @depreciated - No longer used, should use this.get('element') * @config textarea * @description Internal config for holding the textarea element (replaced with element). * @default null * @type HTMLElement */ this.setAttributeConfig('textarea', { value: null, writeOnce: true }); /** * @config nodeChangeThreshold * @description The number of seconds that need to be in between nodeChange processing * @default 3 * @type Number */ this.setAttributeConfig('nodeChangeThreshold', { value: attr.nodeChangeThreshold || 3, validator: YAHOO.lang.isNumber }); /** * @config allowNoEdit * @description Should the editor check for non-edit fields. It should be noted that this technique is not perfect. If the user does the right things, they will still be able to make changes. * Such as highlighting an element below and above the content and hitting a toolbar button or a shortcut key. * @default false * @type Boolean */ this.setAttributeConfig('allowNoEdit', { value: attr.allowNoEdit || false, validator: YAHOO.lang.isBoolean }); /** * @config limitCommands * @description Should the Editor limit the allowed execCommands to the ones available in the toolbar. If true, then execCommand and keyboard shortcuts will fail if they are not defined in the toolbar. * @default false * @type Boolean */ this.setAttributeConfig('limitCommands', { value: attr.limitCommands || false, validator: YAHOO.lang.isBoolean }); /** * @config element_cont * @description Internal config for the editors container * @default false * @type HTMLElement */ this.setAttributeConfig('element_cont', { value: attr.element_cont }); /** * @private * @config editor_wrapper * @description The outter wrapper for the entire editor. * @default null * @type HTMLElement */ this.setAttributeConfig('editor_wrapper', { value: attr.editor_wrapper || null, writeOnce: true }); /** * @attribute height * @description The height of the editor iframe container, not including the toolbar.. * @default Best guessed size of the textarea, for best results use CSS to style the height of the textarea or pass it in as an argument * @type String */ this.setAttributeConfig('height', { value: attr.height || Dom.getStyle(self.get('element'), 'height'), method: function(height) { if (this._rendered) { //We have been rendered, change the height if (this.get('animate')) { var anim = new YAHOO.util.Anim(this.get('iframe').get('parentNode'), { height: { to: parseInt(height, 10) } }, 0.5); anim.animate(); } else { Dom.setStyle(this.get('iframe').get('parentNode'), 'height', height); } } } }); /** * @config autoHeight * @description Remove the scrollbars from the edit area and resize it to fit the content. It will not go any lower than the current config height. * @default false * @type Boolean || Number */ this.setAttributeConfig('autoHeight', { value: attr.autoHeight || false, method: function(a) { if (a) { if (this.get('iframe')) { this.get('iframe').get('element').setAttribute('scrolling', 'no'); } this.on('afterNodeChange', this._handleAutoHeight, this, true); this.on('editorKeyDown', this._handleAutoHeight, this, true); this.on('editorKeyPress', this._handleAutoHeight, this, true); } else { if (this.get('iframe')) { this.get('iframe').get('element').setAttribute('scrolling', 'auto'); } this.unsubscribe('afterNodeChange', this._handleAutoHeight); this.unsubscribe('editorKeyDown', this._handleAutoHeight); this.unsubscribe('editorKeyPress', this._handleAutoHeight); } } }); /** * @attribute width * @description The width of the editor container. * @default Best guessed size of the textarea, for best results use CSS to style the width of the textarea or pass it in as an argument * @type String */ this.setAttributeConfig('width', { value: attr.width || Dom.getStyle(this.get('element'), 'width'), method: function(width) { if (this._rendered) { //We have been rendered, change the width if (this.get('animate')) { var anim = new YAHOO.util.Anim(this.get('element_cont').get('element'), { width: { to: parseInt(width, 10) } }, 0.5); anim.animate(); } else { this.get('element_cont').setStyle('width', width); } } } }); /** * @attribute blankimage * @description The URL for the image placeholder to put in when inserting an image. * @default The yahooapis.com address for the current release + 'assets/blankimage.png' * @type String */ this.setAttributeConfig('blankimage', { value: attr.blankimage || this._getBlankImage() }); /** * @attribute css * @description The Base CSS used to format the content of the editor * @default
                  html {
                                  height: 95%;
                              }
                              body {
                                  height: 100%;
                                  padding: 7px; background-color: #fff; font:13px/1.22 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;
                              }
                              a {
                                  color: blue;
                                  text-decoration: underline;
                                  cursor: pointer;
                              }
                              .warning-localfile {
                                  border-bottom: 1px dashed red !important;
                              }
                              .yui-busy {
                                  cursor: wait !important;
                              }
                              img.selected { //Safari image selection
                                  border: 2px dotted #808080;
                              }
                              img {
                                  cursor: pointer !important;
                                  border: none;
                              }
                              
                  * @type String */ this.setAttributeConfig('css', { value: attr.css || this._defaultCSS, writeOnce: true }); /** * @attribute html * @description The default HTML to be written to the iframe document before the contents are loaded (Note that the DOCTYPE attr will be added at render item) * @default This HTML requires a few things if you are to override:

                  {TITLE}, {CSS}, {HIDDEN_CSS}, {EXTRA_CSS} and {CONTENT} need to be there, they are passed to YAHOO.lang.substitute to be replace with other strings.

                  onload="document.body._rteLoaded = true;" : the onload statement must be there or the editor will not finish loading.

                                  <html>
                                      <head>
                                          <title>{TITLE}</title>
                                          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                                          <style>
                                          {CSS}
                                          </style>
                                          <style>
                                          {HIDDEN_CSS}
                                          </style>
                                          <style>
                                          {EXTRA_CSS}
                                          </style>
                                      </head>
                                  <body onload="document.body._rteLoaded = true;">
                                  {CONTENT}
                                  </body>
                                  </html>
                                  
                  * @type String */ this.setAttributeConfig('html', { value: attr.html || '{TITLE}{CONTENT}', writeOnce: true }); /** * @attribute extracss * @description Extra user defined css to load after the default SimpleEditor CSS * @default '' * @type String */ this.setAttributeConfig('extracss', { value: attr.extracss || '', writeOnce: true }); /** * @attribute handleSubmit * @description Config handles if the editor will attach itself to the textareas parent form's submit handler. If it is set to true, the editor will attempt to attach a submit listener to the textareas parent form. Then it will trigger the editors save handler and place the new content back into the text area before the form is submitted. * @default false * @type Boolean */ this.setAttributeConfig('handleSubmit', { value: attr.handleSubmit || false, method: function(exec) { if (this.get('element').form) { if (!this._formButtons) { this._formButtons = []; } if (exec) { Event.on(this.get('element').form, 'submit', this._handleFormSubmit, this, true); var i = this.get('element').form.getElementsByTagName('input'); for (var s = 0; s < i.length; s++) { var type = i[s].getAttribute('type'); if (type && (type.toLowerCase() == 'submit')) { Event.on(i[s], 'click', this._handleFormButtonClick, this, true); this._formButtons[this._formButtons.length] = i[s]; } } } else { Event.removeListener(this.get('element').form, 'submit', this._handleFormSubmit); if (this._formButtons) { Event.removeListener(this._formButtons, 'click', this._handleFormButtonClick); } } } } }); /** * @attribute disabled * @description This will toggle the editor's disabled state. When the editor is disabled, designMode is turned off and a mask is placed over the iframe so no interaction can take place. All Toolbar buttons are also disabled so they cannot be used. * @default false * @type Boolean */ this.setAttributeConfig('disabled', { value: false, method: function(disabled) { if (this._rendered) { this._disableEditor(disabled); } } }); /** * @config saveEl * @description When save HTML is called, this element will be updated as well as the source of data. * @default element * @type HTMLElement */ this.setAttributeConfig('saveEl', { value: this.get('element') }); /** * @config toolbar_cont * @description Internal config for the toolbars container * @default false * @type Boolean */ this.setAttributeConfig('toolbar_cont', { value: null, writeOnce: true }); /** * @attribute toolbar * @description The default toolbar config. * @type Object */ this.setAttributeConfig('toolbar', { value: attr.toolbar || this._defaultToolbar, writeOnce: true, method: function(toolbar) { if (!toolbar.buttonType) { toolbar.buttonType = this._defaultToolbar.buttonType; } this._defaultToolbar = toolbar; } }); /** * @attribute animate * @description Should the editor animate window movements * @default false unless Animation is found, then true * @type Boolean */ this.setAttributeConfig('animate', { value: ((attr.animate) ? ((YAHOO.util.Anim) ? true : false) : false), validator: function(value) { var ret = true; if (!YAHOO.util.Anim) { ret = false; } return ret; } }); /** * @config panel * @description A reference to the panel we are using for windows. * @default false * @type Boolean */ this.setAttributeConfig('panel', { value: null, writeOnce: true, validator: function(value) { var ret = true; if (!YAHOO.widget.Overlay) { ret = false; } return ret; } }); /** * @attribute focusAtStart * @description Should we focus the window when the content is ready? * @default false * @type Boolean */ this.setAttributeConfig('focusAtStart', { value: attr.focusAtStart || false, writeOnce: true, method: function(fs) { if (fs) { this.on('editorContentLoaded', function() { var self = this; setTimeout(function() { self.focus.call(self); self.editorDirty = false; }, 400); }, this, true); } } }); /** * @attribute dompath * @description Toggle the display of the current Dom path below the editor * @default false * @type Boolean */ this.setAttributeConfig('dompath', { value: attr.dompath || false, method: function(dompath) { if (dompath && !this.dompath) { this.dompath = document.createElement('DIV'); this.dompath.id = this.get('id') + '_dompath'; Dom.addClass(this.dompath, 'dompath'); this.get('element_cont').get('firstChild').appendChild(this.dompath); if (this.get('iframe')) { this._writeDomPath(); } } else if (!dompath && this.dompath) { this.dompath.parentNode.removeChild(this.dompath); this.dompath = null; } } }); /** * @attribute markup * @description Should we try to adjust the markup for the following types: semantic, css, default or xhtml * @default "semantic" * @type String */ this.setAttributeConfig('markup', { value: attr.markup || 'semantic', validator: function(markup) { switch (markup.toLowerCase()) { case 'semantic': case 'css': case 'default': case 'xhtml': return true; } return false; } }); /** * @attribute removeLineBreaks * @description Should we remove linebreaks and extra spaces on cleanup * @default false * @type Boolean */ this.setAttributeConfig('removeLineBreaks', { value: attr.removeLineBreaks || false, validator: YAHOO.lang.isBoolean }); /** * @config drag * @description Set this config to make the Editor draggable, pass 'proxy' to make use YAHOO.util.DDProxy. * @type {Boolean/String} */ this.setAttributeConfig('drag', { writeOnce: true, value: attr.drag || false }); /** * @config resize * @description Set this to true to make the Editor Resizable with YAHOO.util.Resize. The default config is available: myEditor._resizeConfig * Animation will be ignored while performing this resize to allow for the dynamic change in size of the toolbar. * @type Boolean */ this.setAttributeConfig('resize', { writeOnce: true, value: attr.resize || false }); /** * @config filterWord * @description Attempt to filter out MS Word HTML from the Editor's output. * @type Boolean */ this.setAttributeConfig('filterWord', { value: attr.filterWord || false, validator: YAHOO.lang.isBoolean }); }, /** * @private * @method _getBlankImage * @description Retrieves the full url of the image to use as the blank image. * @return {String} The URL to the blank image */ _getBlankImage: function() { if (!this.DOMReady) { this._queue[this._queue.length] = ['_getBlankImage', arguments]; return ''; } var img = ''; if (!this._blankImageLoaded) { if (YAHOO.widget.EditorInfo.blankImage) { this.set('blankimage', YAHOO.widget.EditorInfo.blankImage); this._blankImageLoaded = true; } else { var div = document.createElement('div'); div.style.position = 'absolute'; div.style.top = '-9999px'; div.style.left = '-9999px'; div.className = this.CLASS_PREFIX + '-blankimage'; document.body.appendChild(div); img = YAHOO.util.Dom.getStyle(div, 'background-image'); img = img.replace('url(', '').replace(')', '').replace(/"/g, ''); //Adobe AIR Code img = img.replace('app:/', ''); this.set('blankimage', img); this._blankImageLoaded = true; div.parentNode.removeChild(div); YAHOO.widget.EditorInfo.blankImage = img; } } else { img = this.get('blankimage'); } return img; }, /** * @private * @method _handleAutoHeight * @description Handles resizing the editor's height based on the content */ _handleAutoHeight: function() { var doc = this._getDoc(), body = doc.body, docEl = doc.documentElement; var height = parseInt(Dom.getStyle(this.get('editor_wrapper'), 'height'), 10); var newHeight = body.scrollHeight; if (this.browser.webkit) { newHeight = docEl.scrollHeight; } if (newHeight < parseInt(this.get('height'), 10)) { newHeight = parseInt(this.get('height'), 10); } if ((height != newHeight) && (newHeight >= parseInt(this.get('height'), 10))) { var anim = this.get('animate'); this.set('animate', false); this.set('height', newHeight + 'px'); this.set('animate', anim); if (this.browser.ie) { //Internet Explorer needs this this.get('iframe').setStyle('height', '99%'); this.get('iframe').setStyle('zoom', '1'); var self = this; window.setTimeout(function() { self.get('iframe').setStyle('height', '100%'); }, 1); } } }, /** * @private * @property _formButtons * @description Array of buttons that are in the Editor's parent form (for handleSubmit) * @type Array */ _formButtons: null, /** * @private * @property _formButtonClicked * @description The form button that was clicked to submit the form. * @type HTMLElement */ _formButtonClicked: null, /** * @private * @method _handleFormButtonClick * @description The click listener assigned to each submit button in the Editor's parent form. * @param {Event} ev The click event */ _handleFormButtonClick: function(ev) { var tar = Event.getTarget(ev); this._formButtonClicked = tar; }, /** * @private * @method _handleFormSubmit * @description Handles the form submission. * @param {Object} ev The Form Submit Event */ _handleFormSubmit: function(ev) { this.saveHTML(); var form = this.get('element').form, tar = this._formButtonClicked || false; Event.removeListener(form, 'submit', this._handleFormSubmit); if (YAHOO.env.ua.ie) { //form.fireEvent("onsubmit"); if (tar && !tar.disabled) { tar.click(); } } else { // Gecko, Opera, and Safari if (tar && !tar.disabled) { tar.click(); } var oEvent = document.createEvent("HTMLEvents"); oEvent.initEvent("submit", true, true); form.dispatchEvent(oEvent); if (YAHOO.env.ua.webkit) { if (YAHOO.lang.isFunction(form.submit)) { form.submit(); } } } //2.6.0 //Removed this, not need since removing Safari 2.x //Event.stopEvent(ev); }, /** * @private * @method _handleFontSize * @description Handles the font size button in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleFontSize: function(o) { var button = this.toolbar.getButtonById(o.button.id); var value = button.get('label') + 'px'; this.execCommand('fontsize', value); return false; }, /** * @private * @description Handles the colorpicker buttons in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleColorPicker: function(o) { var cmd = o.button; var value = '#' + o.color; if ((cmd == 'forecolor') || (cmd == 'backcolor')) { this.execCommand(cmd, value); } }, /** * @private * @method _handleAlign * @description Handles the alignment buttons in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleAlign: function(o) { var cmd = null; for (var i = 0; i < o.button.menu.length; i++) { if (o.button.menu[i].value == o.button.value) { cmd = o.button.menu[i].value; } } var value = this._getSelection(); this.execCommand(cmd, value); return false; }, /** * @private * @method _handleAfterNodeChange * @description Fires after a nodeChange happens to setup the things that where reset on the node change (button state). */ _handleAfterNodeChange: function() { var path = this._getDomPath(), elm = null, family = null, fontsize = null, validFont = false, fn_button = this.toolbar.getButtonByValue('fontname'), fs_button = this.toolbar.getButtonByValue('fontsize'), hd_button = this.toolbar.getButtonByValue('heading'); for (var i = 0; i < path.length; i++) { elm = path[i]; var tag = elm.tagName.toLowerCase(); if (elm.getAttribute('tag')) { tag = elm.getAttribute('tag'); } family = elm.getAttribute('face'); if (Dom.getStyle(elm, 'font-family')) { family = Dom.getStyle(elm, 'font-family'); //Adobe AIR Code family = family.replace(/'/g, ''); } if (tag.substring(0, 1) == 'h') { if (hd_button) { for (var h = 0; h < hd_button._configs.menu.value.length; h++) { if (hd_button._configs.menu.value[h].value.toLowerCase() == tag) { hd_button.set('label', hd_button._configs.menu.value[h].text); } } this._updateMenuChecked('heading', tag); } } } if (fn_button) { for (var b = 0; b < fn_button._configs.menu.value.length; b++) { if (family && fn_button._configs.menu.value[b].text.toLowerCase() == family.toLowerCase()) { validFont = true; family = fn_button._configs.menu.value[b].text; //Put the proper menu name in the button } } if (!validFont) { family = fn_button._configs.label._initialConfig.value; } var familyLabel = '' + family + ''; if (fn_button.get('label') != familyLabel) { fn_button.set('label', familyLabel); this._updateMenuChecked('fontname', family); } } if (fs_button) { fontsize = parseInt(Dom.getStyle(elm, 'fontSize'), 10); if ((fontsize === null) || isNaN(fontsize)) { fontsize = fs_button._configs.label._initialConfig.value; } fs_button.set('label', ''+fontsize); } if (!this._isElement(elm, 'body') && !this._isElement(elm, 'img')) { this.toolbar.enableButton(fn_button); this.toolbar.enableButton(fs_button); this.toolbar.enableButton('forecolor'); this.toolbar.enableButton('backcolor'); } if (this._isElement(elm, 'img')) { if (YAHOO.widget.Overlay) { this.toolbar.enableButton('createlink'); } } if (this._hasParent(elm, 'blockquote')) { this.toolbar.selectButton('indent'); this.toolbar.disableButton('indent'); this.toolbar.enableButton('outdent'); } if (this._hasParent(elm, 'ol') || this._hasParent(elm, 'ul')) { this.toolbar.disableButton('indent'); } this._lastButton = null; }, /** * @private * @method _handleInsertImageClick * @description Opens the Image Properties Window when the insert Image button is clicked or an Image is Double Clicked. */ _handleInsertImageClick: function() { if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('insertimage')) { YAHOO.log('Toolbar Button for (insertimage) was not found, skipping exec.', 'info', 'SimpleEditor'); return false; } } this.toolbar.set('disabled', true); //Disable the toolbar when the prompt is showing var _handleAEC = function() { var el = this.currentElement[0], src = 'http://'; if (!el) { el = this._getSelectedElement(); } if (el) { if (el.getAttribute('src')) { src = el.getAttribute('src', 2); if (src.indexOf(this.get('blankimage')) != -1) { src = this.STR_IMAGE_HERE; } } } var str = prompt(this.STR_IMAGE_URL + ': ', src); if ((str !== '') && (str !== null)) { el.setAttribute('src', str); } else if (str === '') { el.parentNode.removeChild(el); this.currentElement = []; this.nodeChange(); } else if ((str === null)) { src = el.getAttribute('src', 2); if (src.indexOf(this.get('blankimage')) != -1) { el.parentNode.removeChild(el); this.currentElement = []; this.nodeChange(); } } this.closeWindow(); this.toolbar.set('disabled', false); this.unsubscribe('afterExecCommand', _handleAEC, this, true); }; this.on('afterExecCommand', _handleAEC, this, true); }, /** * @private * @method _handleInsertImageWindowClose * @description Handles the closing of the Image Properties Window. */ _handleInsertImageWindowClose: function() { this.nodeChange(); }, /** * @private * @method _isLocalFile * @param {String} url THe url/string to check * @description Checks to see if a string (href or img src) is possibly a local file reference.. */ _isLocalFile: function(url) { if ((url) && (url !== '') && ((url.indexOf('file:/') != -1) || (url.indexOf(':\\') != -1))) { return true; } return false; }, /** * @private * @method _handleCreateLinkClick * @description Handles the opening of the Link Properties Window when the Create Link button is clicked or an href is doubleclicked. */ _handleCreateLinkClick: function() { if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('createlink')) { YAHOO.log('Toolbar Button for (createlink) was not found, skipping exec.', 'info', 'SimpleEditor'); return false; } } this.toolbar.set('disabled', true); //Disable the toolbar when the prompt is showing var _handleAEC = function() { var el = this.currentElement[0], url = ''; if (el) { if (el.getAttribute('href', 2) !== null) { url = el.getAttribute('href', 2); } } var str = prompt(this.STR_LINK_URL + ': ', url); if ((str !== '') && (str !== null)) { var urlValue = str; if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { //Found an @ sign, prefix with mailto: urlValue = 'mailto:' + urlValue; } else { /* :// not found adding */ if (urlValue.substring(0, 1) != '#') { //urlValue = 'http:/'+'/' + urlValue; } } } el.setAttribute('href', urlValue); } else if (str !== null) { var _span = this._getDoc().createElement('span'); _span.innerHTML = el.innerHTML; Dom.addClass(_span, 'yui-non'); el.parentNode.replaceChild(_span, el); } this.closeWindow(); this.toolbar.set('disabled', false); this.unsubscribe('afterExecCommand', _handleAEC, this, true); }; this.on('afterExecCommand', _handleAEC, this); }, /** * @private * @method _handleCreateLinkWindowClose * @description Handles the closing of the Link Properties Window. */ _handleCreateLinkWindowClose: function() { this.nodeChange(); this.currentElement = []; }, /** * @method render * @description Calls the private method _render in a setTimeout to allow for other things on the page to continue to load. */ render: function() { if (this._rendered) { return false; } YAHOO.log('Render', 'info', 'SimpleEditor'); if (!this.DOMReady) { YAHOO.log('!DOMReady', 'info', 'SimpleEditor'); this._queue[this._queue.length] = ['render', arguments]; return false; } if (this.get('element')) { if (this.get('element').tagName) { this._textarea = true; if (this.get('element').tagName.toLowerCase() !== 'textarea') { this._textarea = false; } } else { YAHOO.log('No Valid Element', 'error', 'SimpleEditor'); return false; } } else { YAHOO.log('No Element', 'error', 'SimpleEditor'); return false; } this._rendered = true; var self = this; window.setTimeout(function() { self._render.call(self); }, 4); }, /** * @private * @method _render * @description Causes the toolbar and the editor to render and replace the textarea. */ _render: function() { var self = this; this.set('textarea', this.get('element')); this.get('element_cont').setStyle('display', 'none'); this.get('element_cont').addClass(this.CLASS_CONTAINER); this.set('iframe', this._createIframe()); window.setTimeout(function() { self._setInitialContent.call(self); }, 10); this.get('editor_wrapper').appendChild(this.get('iframe').get('element')); if (this.get('disabled')) { this._disableEditor(true); } var tbarConf = this.get('toolbar'); //Create Toolbar instance if (tbarConf instanceof Toolbar) { this.toolbar = tbarConf; //Set the toolbar to disabled until content is loaded this.toolbar.set('disabled', true); } else { //Set the toolbar to disabled until content is loaded tbarConf.disabled = true; this.toolbar = new Toolbar(this.get('toolbar_cont'), tbarConf); } YAHOO.log('fireEvent::toolbarLoaded', 'info', 'SimpleEditor'); this.fireEvent('toolbarLoaded', { type: 'toolbarLoaded', target: this.toolbar }); this.toolbar.on('toolbarCollapsed', function() { if (this.currentWindow) { this.moveWindow(); } }, this, true); this.toolbar.on('toolbarExpanded', function() { if (this.currentWindow) { this.moveWindow(); } }, this, true); this.toolbar.on('fontsizeClick', this._handleFontSize, this, true); this.toolbar.on('colorPickerClicked', function(o) { this._handleColorPicker(o); return false; //Stop the buttonClick event }, this, true); this.toolbar.on('alignClick', this._handleAlign, this, true); this.on('afterNodeChange', this._handleAfterNodeChange, this, true); this.toolbar.on('insertimageClick', this._handleInsertImageClick, this, true); this.on('windowinsertimageClose', this._handleInsertImageWindowClose, this, true); this.toolbar.on('createlinkClick', this._handleCreateLinkClick, this, true); this.on('windowcreatelinkClose', this._handleCreateLinkWindowClose, this, true); //Replace Textarea with editable area this.get('parentNode').replaceChild(this.get('element_cont').get('element'), this.get('element')); this.setStyle('visibility', 'hidden'); this.setStyle('position', 'absolute'); this.setStyle('top', '-9999px'); this.setStyle('left', '-9999px'); this.get('element_cont').appendChild(this.get('element')); this.get('element_cont').setStyle('display', 'block'); Dom.addClass(this.get('iframe').get('parentNode'), this.CLASS_EDITABLE_CONT); this.get('iframe').addClass(this.CLASS_EDITABLE); //Set height and width of editor container this.get('element_cont').setStyle('width', this.get('width')); Dom.setStyle(this.get('iframe').get('parentNode'), 'height', this.get('height')); this.get('iframe').setStyle('width', '100%'); //WIDTH this.get('iframe').setStyle('height', '100%'); this._setupDD(); window.setTimeout(function() { self._setupAfterElement.call(self); }, 0); this.fireEvent('afterRender', { type: 'afterRender', target: this }); }, /** * @method execCommand * @param {String} action The "execCommand" action to try to execute (Example: bold, insertimage, inserthtml) * @param {String} value (optional) The value for a given action such as action: fontname value: 'Verdana' * @description This method attempts to try and level the differences in the various browsers and their support for execCommand actions */ execCommand: function(action, value) { var beforeExec = this.fireEvent('beforeExecCommand', { type: 'beforeExecCommand', target: this, args: arguments }); if ((beforeExec === false) || (this.STOP_EXEC_COMMAND)) { this.STOP_EXEC_COMMAND = false; return false; } this._lastCommand = action; this._setMarkupType(action); if (this.browser.ie) { this._getWindow().focus(); } var exec = true; if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue(action)) { YAHOO.log('Toolbar Button for (' + action + ') was not found, skipping exec.', 'info', 'SimpleEditor'); exec = false; } } this.editorDirty = true; if ((typeof this['cmd_' + action.toLowerCase()] == 'function') && exec) { YAHOO.log('Found execCommand override method: (cmd_' + action.toLowerCase() + ')', 'info', 'SimpleEditor'); var retValue = this['cmd_' + action.toLowerCase()](value); exec = retValue[0]; if (retValue[1]) { action = retValue[1]; } if (retValue[2]) { value = retValue[2]; } } if (exec) { YAHOO.log('execCommand::(' + action + '), (' + value + ')', 'info', 'SimpleEditor'); try { this._getDoc().execCommand(action, false, value); } catch(e) { YAHOO.log('execCommand Failed', 'error', 'SimpleEditor'); } } else { YAHOO.log('OVERRIDE::execCommand::(' + action + '),(' + value + ') skipped', 'warn', 'SimpleEditor'); } this.on('afterExecCommand', function() { this.unsubscribeAll('afterExecCommand'); this.nodeChange(); }, this, true); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); }, /* {{{ Command Overrides */ /** * @method cmd_bold * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('bold') is used. */ cmd_bold: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span') && this._hasSelection()) { if (el.style.fontWeight == 'bold') { el.style.fontWeight = ''; var b = this._getDoc().createElement('b'), par = el.parentNode; par.replaceChild(b, el); b.appendChild(el); } } } return [true]; }, /** * @method cmd_italic * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('italic') is used. */ cmd_italic: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span') && this._hasSelection()) { if (el.style.fontStyle == 'italic') { el.style.fontStyle = ''; var i = this._getDoc().createElement('i'), par = el.parentNode; par.replaceChild(i, el); i.appendChild(el); } } } return [true]; }, /** * @method cmd_underline * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('underline') is used. */ cmd_underline: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span')) { if (el.style.textDecoration == 'underline') { el.style.textDecoration = 'none'; } else { el.style.textDecoration = 'underline'; } return [false]; } } return [true]; }, /** * @method cmd_backcolor * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('backcolor') is used. */ cmd_backcolor: function(value) { var exec = true, el = this._getSelectedElement(), action = 'backcolor'; if (this.browser.gecko || this.browser.opera) { this._setEditorStyle(true); action = 'hilitecolor'; } if (!this._isElement(el, 'body') && !this._hasSelection()) { el.style.backgroundColor = value; this._selectNode(el); exec = false; } else { if (this.get('insert')) { el = this._createInsertElement({ backgroundColor: value }); } else { this._createCurrentElement('span', { backgroundColor: value, color: el.style.color, fontSize: el.style.fontSize, fontFamily: el.style.fontFamily }); this._selectNode(this.currentElement[0]); } exec = false; } return [exec, action]; }, /** * @method cmd_forecolor * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('forecolor') is used. */ cmd_forecolor: function(value) { var exec = true, el = this._getSelectedElement(); if (!this._isElement(el, 'body') && !this._hasSelection()) { Dom.setStyle(el, 'color', value); this._selectNode(el); exec = false; } else { if (this.get('insert')) { el = this._createInsertElement({ color: value }); } else { this._createCurrentElement('span', { color: value, fontSize: el.style.fontSize, fontFamily: el.style.fontFamily, backgroundColor: el.style.backgroundColor }); this._selectNode(this.currentElement[0]); } exec = false; } return [exec]; }, /** * @method cmd_unlink * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('unlink') is used. */ cmd_unlink: function(value) { this._swapEl(this.currentElement[0], 'span', function(el) { el.className = 'yui-non'; }); return [false]; }, /** * @method cmd_createlink * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('createlink') is used. */ cmd_createlink: function(value) { var el = this._getSelectedElement(), _a = null; if (this._hasParent(el, 'a')) { this.currentElement[0] = this._hasParent(el, 'a'); } else if (this._isElement(el, 'li')) { _a = this._getDoc().createElement('a'); _a.innerHTML = el.innerHTML; el.innerHTML = ''; el.appendChild(_a); this.currentElement[0] = _a; } else if (!this._isElement(el, 'a')) { this._createCurrentElement('a'); _a = this._swapEl(this.currentElement[0], 'a'); this.currentElement[0] = _a; } else { this.currentElement[0] = el; } return [false]; }, /** * @method cmd_insertimage * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertimage') is used. */ cmd_insertimage: function(value) { var exec = true, _img = null, action = 'insertimage', el = this._getSelectedElement(); if (value === '') { value = this.get('blankimage'); } /* * @knownissue Safari Cursor Position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ YAHOO.log('InsertImage: ' + el.tagName, 'info', 'SimpleEditor'); if (this._isElement(el, 'img')) { this.currentElement[0] = el; exec = false; } else { if (this._getDoc().queryCommandEnabled(action)) { this._getDoc().execCommand(action, false, value); var imgs = this._getDoc().getElementsByTagName('img'); for (var i = 0; i < imgs.length; i++) { if (!YAHOO.util.Dom.hasClass(imgs[i], 'yui-img')) { YAHOO.util.Dom.addClass(imgs[i], 'yui-img'); this.currentElement[0] = imgs[i]; } } exec = false; } else { if (el == this._getDoc().body) { _img = this._getDoc().createElement('img'); _img.setAttribute('src', value); YAHOO.util.Dom.addClass(_img, 'yui-img'); this._getDoc().body.appendChild(_img); } else { this._createCurrentElement('img'); _img = this._getDoc().createElement('img'); _img.setAttribute('src', value); YAHOO.util.Dom.addClass(_img, 'yui-img'); this.currentElement[0].parentNode.replaceChild(_img, this.currentElement[0]); } this.currentElement[0] = _img; exec = false; } } return [exec]; }, /** * @method cmd_inserthtml * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('inserthtml') is used. */ cmd_inserthtml: function(value) { var exec = true, action = 'inserthtml', _span = null, _range = null; /* * @knownissue Safari cursor position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ if (this.browser.webkit && !this._getDoc().queryCommandEnabled(action)) { YAHOO.log('More Safari DOM tricks (inserthtml)', 'info', 'EditorSafari'); this._createCurrentElement('img'); _span = this._getDoc().createElement('span'); _span.innerHTML = value; this.currentElement[0].parentNode.replaceChild(_span, this.currentElement[0]); exec = false; } else if (this.browser.ie) { _range = this._getRange(); if (_range.item) { _range.item(0).outerHTML = value; } else { _range.pasteHTML(value); } exec = false; } return [exec]; }, /** * @method cmd_list * @param tag The tag of the list you want to create (eg, ul or ol) * @description This is a combined execCommand override method. It is called from the cmd_insertorderedlist and cmd_insertunorderedlist methods. */ cmd_list: function(tag) { var exec = true, list = null, li = 0, el = null, str = '', selEl = this._getSelectedElement(), action = 'insertorderedlist'; if (tag == 'ul') { action = 'insertunorderedlist'; } /* * @knownissue Safari 2.+ doesn't support ordered and unordered lists * @browser Safari 2.x * The issue with this workaround is that when applied to a set of text * that has BR's in it, Safari may or may not pick up the individual items as * list items. This is fixed in WebKit (Safari 3) * 2.6.0: Seems there are still some issues with List Creation and Safari 3, reverting to previously working Safari 2.x code */ //if ((this.browser.webkit && !this._getDoc().queryCommandEnabled(action))) { if ((this.browser.webkit && !this.browser.webkit4) || (this.browser.opera)) { if (this._isElement(selEl, 'li') && this._isElement(selEl.parentNode, tag)) { YAHOO.log('We already have a list, undo it', 'info', 'SimpleEditor'); el = selEl.parentNode; list = this._getDoc().createElement('span'); YAHOO.util.Dom.addClass(list, 'yui-non'); str = ''; var lis = el.getElementsByTagName('li'), p_tag = ((this.browser.opera && this.get('ptags')) ? 'p' : 'div'); for (li = 0; li < lis.length; li++) { str += '<' + p_tag + '>' + lis[li].innerHTML + ''; } list.innerHTML = str; this.currentElement[0] = el; this.currentElement[0].parentNode.replaceChild(list, this.currentElement[0]); } else { YAHOO.log('Create list item', 'info', 'SimpleEditor'); this._createCurrentElement(tag.toLowerCase()); list = this._getDoc().createElement(tag); for (li = 0; li < this.currentElement.length; li++) { var newli = this._getDoc().createElement('li'); newli.innerHTML = this.currentElement[li].innerHTML + '  '; list.appendChild(newli); if (li > 0) { this.currentElement[li].parentNode.removeChild(this.currentElement[li]); } } var b_tag = ((this.browser.opera) ? '
                  ' : '
                  '), items = list.firstChild.innerHTML.split(b_tag), i, item; if (items.length > 0) { list.innerHTML = ''; for (i = 0; i < items.length; i++) { item = this._getDoc().createElement('li'); item.innerHTML = items[i]; list.appendChild(item); } } this.currentElement[0].parentNode.replaceChild(list, this.currentElement[0]); this.currentElement[0] = list; var _h = this.currentElement[0].firstChild; _h = Dom.getElementsByClassName('yui-non', 'span', _h)[0]; if (this.browser.webkit) { this._getSelection().setBaseAndExtent(_h, 1, _h, _h.innerText.length); } } exec = false; } else { el = this._getSelectedElement(); YAHOO.log(el.tagName); if (this._isElement(el, 'li') && this._isElement(el.parentNode, tag) || (this.browser.ie && this._isElement(this._getRange().parentElement, 'li')) || (this.browser.ie && this._isElement(el, 'ul')) || (this.browser.ie && this._isElement(el, 'ol'))) { //we are in a list.. YAHOO.log('We already have a list, undo it', 'info', 'SimpleEditor'); if (this.browser.ie) { if ((this.browser.ie && this._isElement(el, 'ul')) || (this.browser.ie && this._isElement(el, 'ol'))) { el = el.getElementsByTagName('li')[0]; } YAHOO.log('Undo IE', 'info', 'SimpleEditor'); str = ''; var lis2 = el.parentNode.getElementsByTagName('li'); for (var j = 0; j < lis2.length; j++) { str += lis2[j].innerHTML + '
                  '; } var newEl = this._getDoc().createElement('span'); newEl.innerHTML = str; el.parentNode.parentNode.replaceChild(newEl, el.parentNode); } else { this.nodeChange(); this._getDoc().execCommand(action, '', el.parentNode); this.nodeChange(); } exec = false; } if (this.browser.opera) { var self = this; window.setTimeout(function() { var liso = self._getDoc().getElementsByTagName('li'); for (var i = 0; i < liso.length; i++) { if (liso[i].innerHTML.toLowerCase() == '
                  ') { liso[i].parentNode.parentNode.removeChild(liso[i].parentNode); } } },30); } if (this.browser.ie && exec) { var html = ''; if (this._getRange().html) { html = '
                • ' + this._getRange().html+ '
                • '; } else { var t = this._getRange().text.split('\n'); if (t.length > 1) { html = ''; for (var ie = 0; ie < t.length; ie++) { html += '
                • ' + t[ie] + '
                • '; } } else { var txt = this._getRange().text; if (txt === '') { html = '
                • ' + txt + '
                • '; } else { html = '
                • ' + txt + '
                • '; } } } this._getRange().pasteHTML('<' + tag + '>' + html + ''); var new_item = this._getDoc().getElementById('new_list_item'); if (new_item) { var range = this._getDoc().body.createTextRange(); range.moveToElementText(new_item); range.collapse(false); range.select(); new_item.id = ''; } exec = false; } } return exec; }, /** * @method cmd_insertorderedlist * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertorderedlist ') is used. */ cmd_insertorderedlist: function(value) { return [this.cmd_list('ol')]; }, /** * @method cmd_insertunorderedlist * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertunorderedlist') is used. */ cmd_insertunorderedlist: function(value) { return [this.cmd_list('ul')]; }, /** * @method cmd_fontname * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('fontname') is used. */ cmd_fontname: function(value) { var exec = true, selEl = this._getSelectedElement(); this.currentFont = value; if (selEl && selEl.tagName && !this._hasSelection() && !this._isElement(selEl, 'body') && !this.get('insert')) { YAHOO.util.Dom.setStyle(selEl, 'font-family', value); exec = false; } else if (this.get('insert') && !this._hasSelection()) { YAHOO.log('No selection and no selected element and we are in insert mode', 'info', 'SimpleEditor'); var el = this._createInsertElement({ fontFamily: value }); exec = false; } return [exec]; }, /** * @method cmd_fontsize * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('fontsize') is used. */ cmd_fontsize: function(value) { var el = null, go = true; el = this._getSelectedElement(); if (this.browser.webkit) { if (this.currentElement[0]) { if (el == this.currentElement[0]) { go = false; YAHOO.util.Dom.setStyle(el, 'fontSize', value); this._selectNode(el); this.currentElement[0] = el; } } } if (go) { if (!this._isElement(this._getSelectedElement(), 'body') && (!this._hasSelection())) { el = this._getSelectedElement(); YAHOO.util.Dom.setStyle(el, 'fontSize', value); if (this.get('insert') && this.browser.ie) { var r = this._getRange(); r.collapse(false); r.select(); } else { this._selectNode(el); } } else if (this.currentElement && (this.currentElement.length > 0) && (!this._hasSelection()) && (!this.get('insert'))) { YAHOO.util.Dom.setStyle(this.currentElement, 'fontSize', value); } else { if (this.get('insert') && !this._hasSelection()) { el = this._createInsertElement({ fontSize: value }); this.currentElement[0] = el; this._selectNode(this.currentElement[0]); } else { this._createCurrentElement('span', {'fontSize': value, fontFamily: el.style.fontFamily, color: el.style.color, backgroundColor: el.style.backgroundColor }); this._selectNode(this.currentElement[0]); } } } return [false]; }, /* }}} */ /** * @private * @method _swapEl * @param {HTMLElement} el The element to swap with * @param {String} tagName The tagname of the element that you wish to create * @param {Function} callback (optional) A function to run on the element after it is created, but before it is replaced. An element reference is passed to this function. * @description This function will create a new element in the DOM and populate it with the contents of another element. Then it will assume it's place. */ _swapEl: function(el, tagName, callback) { var _el = this._getDoc().createElement(tagName); if (el) { _el.innerHTML = el.innerHTML; } if (typeof callback == 'function') { callback.call(this, _el); } if (el) { el.parentNode.replaceChild(_el, el); } return _el; }, /** * @private * @method _createInsertElement * @description Creates a new "currentElement" then adds some text (and other things) to make it selectable and stylable. Then the user can continue typing. * @param {Object} css (optional) Object literal containing styles to apply to the new element. * @return {HTMLElement} */ _createInsertElement: function(css) { this._createCurrentElement('span', css); var el = this.currentElement[0]; if (this.browser.webkit) { //Little Safari Hackery here.. el.innerHTML = ' '; el = el.firstChild; this._getSelection().setBaseAndExtent(el, 1, el, el.innerText.length); } else if (this.browser.ie || this.browser.opera) { el.innerHTML = ' '; } this.focus(); this._selectNode(el, true); return el; }, /** * @private * @method _createCurrentElement * @param {String} tagName (optional defaults to a) The tagname of the element that you wish to create * @param {Object} tagStyle (optional) Object literal containing styles to apply to the new element. * @description This is a work around for the various browser issues with execCommand. This method will run execCommand('fontname', false, 'yui-tmp') on the given selection. * It will then search the document for an element with the font-family set to yui-tmp and replace that with another span that has other information in it, then assign the new span to the * this.currentElement array, so we now have element references to the elements that were just modified. At this point we can use standard DOM manipulation to change them as we see fit. */ _createCurrentElement: function(tagName, tagStyle) { tagName = ((tagName) ? tagName : 'a'); var tar = null, el = [], _doc = this._getDoc(); if (this.currentFont) { if (!tagStyle) { tagStyle = {}; } tagStyle.fontFamily = this.currentFont; this.currentFont = null; } this.currentElement = []; var _elCreate = function(tagName, tagStyle) { var el = null; tagName = ((tagName) ? tagName : 'span'); tagName = tagName.toLowerCase(); switch (tagName) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': el = _doc.createElement(tagName); break; default: el = _doc.createElement(tagName); if (tagName === 'span') { YAHOO.util.Dom.addClass(el, 'yui-tag-' + tagName); YAHOO.util.Dom.addClass(el, 'yui-tag'); el.setAttribute('tag', tagName); } for (var k in tagStyle) { if (YAHOO.lang.hasOwnProperty(tagStyle, k)) { el.style[k] = tagStyle[k]; } } break; } return el; }; if (!this._hasSelection()) { if (this._getDoc().queryCommandEnabled('insertimage')) { this._getDoc().execCommand('insertimage', false, 'yui-tmp-img'); var imgs = this._getDoc().getElementsByTagName('img'); for (var j = 0; j < imgs.length; j++) { if (imgs[j].getAttribute('src', 2) == 'yui-tmp-img') { el = _elCreate(tagName, tagStyle); imgs[j].parentNode.replaceChild(el, imgs[j]); this.currentElement[this.currentElement.length] = el; } } } else { if (this.currentEvent) { tar = YAHOO.util.Event.getTarget(this.currentEvent); } else { //For Safari.. tar = this._getDoc().body; } } if (tar) { /* * @knownissue Safari Cursor Position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ el = _elCreate(tagName, tagStyle); if (this._isElement(tar, 'body') || this._isElement(tar, 'html')) { if (this._isElement(tar, 'html')) { tar = this._getDoc().body; } tar.appendChild(el); } else if (tar.nextSibling) { tar.parentNode.insertBefore(el, tar.nextSibling); } else { tar.parentNode.appendChild(el); } //this.currentElement = el; this.currentElement[this.currentElement.length] = el; this.currentEvent = null; if (this.browser.webkit) { //Force Safari to focus the new element this._getSelection().setBaseAndExtent(el, 0, el, 0); if (this.browser.webkit3) { this._getSelection().collapseToStart(); } else { this._getSelection().collapse(true); } } } } else { //Force CSS Styling for this action... this._setEditorStyle(true); this._getDoc().execCommand('fontname', false, 'yui-tmp'); var _tmp = [], __tmp, __els = ['font', 'span', 'i', 'b', 'u']; if (!this._isElement(this._getSelectedElement(), 'body')) { __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().tagName); __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().parentNode.tagName); } for (var _els = 0; _els < __els.length; _els++) { var _tmp1 = this._getDoc().getElementsByTagName(__els[_els]); for (var e = 0; e < _tmp1.length; e++) { _tmp[_tmp.length] = _tmp1[e]; } } for (var i = 0; i < _tmp.length; i++) { if ((YAHOO.util.Dom.getStyle(_tmp[i], 'font-family') == 'yui-tmp') || (_tmp[i].face && (_tmp[i].face == 'yui-tmp'))) { if (tagName !== 'span') { el = _elCreate(tagName, tagStyle); } else { el = _elCreate(_tmp[i].tagName, tagStyle); } el.innerHTML = _tmp[i].innerHTML; if (this._isElement(_tmp[i], 'ol') || (this._isElement(_tmp[i], 'ul'))) { var fc = _tmp[i].getElementsByTagName('li')[0]; _tmp[i].style.fontFamily = 'inherit'; fc.style.fontFamily = 'inherit'; el.innerHTML = fc.innerHTML; fc.innerHTML = ''; fc.appendChild(el); this.currentElement[this.currentElement.length] = el; } else if (this._isElement(_tmp[i], 'li')) { _tmp[i].innerHTML = ''; _tmp[i].appendChild(el); _tmp[i].style.fontFamily = 'inherit'; this.currentElement[this.currentElement.length] = el; } else { if (_tmp[i].parentNode) { _tmp[i].parentNode.replaceChild(el, _tmp[i]); this.currentElement[this.currentElement.length] = el; this.currentEvent = null; if (this.browser.webkit) { //Force Safari to focus the new element this._getSelection().setBaseAndExtent(el, 0, el, 0); if (this.browser.webkit3) { this._getSelection().collapseToStart(); } else { this._getSelection().collapse(true); } } if (this.browser.ie && tagStyle && tagStyle.fontSize) { this._getSelection().empty(); } if (this.browser.gecko) { this._getSelection().collapseToStart(); } } } } } var len = this.currentElement.length; for (var o = 0; o < len; o++) { if ((o + 1) != len) { //Skip the last one in the list if (this.currentElement[o] && this.currentElement[o].nextSibling) { if (this._isElement(this.currentElement[o], 'br')) { this.currentElement[this.currentElement.length] = this.currentElement[o].nextSibling; } } } } } }, /** * @method saveHTML * @description Cleans the HTML with the cleanHTML method then places that string back into the textarea. * @return String */ saveHTML: function() { var html = this.cleanHTML(); if (this._textarea) { this.get('element').value = html; } else { this.get('element').innerHTML = html; } if (this.get('saveEl') !== this.get('element')) { var out = this.get('saveEl'); if (Lang.isString(out)) { out = Dom.get(out); } if (out) { if (out.tagName.toLowerCase() === 'textarea') { out.value = html; } else { out.innerHTML = html; } } } return html; }, /** * @method setEditorHTML * @param {String} incomingHTML The html content to load into the editor * @description Loads HTML into the editors body */ setEditorHTML: function(incomingHTML) { var html = this._cleanIncomingHTML(incomingHTML); html = html.replace(/RIGHT_BRACKET/gi, '{'); html = html.replace(/LEFT_BRACKET/gi, '}'); this._getDoc().body.innerHTML = html; this.nodeChange(); }, /** * @method getEditorHTML * @description Gets the unprocessed/unfiltered HTML from the editor */ getEditorHTML: function() { try { var b = this._getDoc().body; if (b === null) { YAHOO.log('Body is null, returning null.', 'error', 'SimpleEditor'); return null; } return this._getDoc().body.innerHTML; } catch (e) { return ''; } }, /** * @method show * @description This method needs to be called if the Editor was hidden (like in a TabView or Panel). It is used to reset the editor after being in a container that was set to display none. */ show: function() { if (this.browser.gecko) { this._setDesignMode('on'); this.focus(); } if (this.browser.webkit) { var self = this; window.setTimeout(function() { self._setInitialContent.call(self); }, 10); } //Adding this will close all other Editor window's when showing this one. if (this.currentWindow) { this.closeWindow(); } //Put the iframe back in place this.get('iframe').setStyle('position', 'static'); this.get('iframe').setStyle('left', ''); }, /** * @method hide * @description This method needs to be called if the Editor is to be hidden (like in a TabView or Panel). It should be called to clear timeouts and close open editor windows. */ hide: function() { //Adding this will close all other Editor window's. if (this.currentWindow) { this.closeWindow(); } if (this._fixNodesTimer) { clearTimeout(this._fixNodesTimer); this._fixNodesTimer = null; } if (this._nodeChangeTimer) { clearTimeout(this._nodeChangeTimer); this._nodeChangeTimer = null; } this._lastNodeChange = 0; //Move the iframe off of the screen, so that in containers with visiblity hidden, IE will not cover other elements. this.get('iframe').setStyle('position', 'absolute'); this.get('iframe').setStyle('left', '-9999px'); }, /** * @method _cleanIncomingHTML * @param {String} html The unfiltered HTML * @description Process the HTML with a few regexes to clean it up and stabilize the input * @return {String} The filtered HTML */ _cleanIncomingHTML: function(html) { html = html.replace(/{/gi, 'RIGHT_BRACKET'); html = html.replace(/}/gi, 'LEFT_BRACKET'); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/strong>/gi, '
                  '); //replace embed before em check html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/embed>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/em>/gi, ''); html = html.replace(/_moz_dirty=""/gi, ''); //Put embed tags back in.. html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/YUI_EMBED>/gi, ''); if (this.get('plainText')) { YAHOO.log('Filtering as plain text', 'info', 'SimpleEditor'); html = html.replace(/\n/g, '
                  ').replace(/\r/g, '
                  '); html = html.replace(/ /gi, '  '); //Replace all double spaces html = html.replace(/\t/gi, '    '); //Replace all tabs } //Removing Script Tags from the Editor html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/script([^>]*)>/gi, ''); html = html.replace(/<script([^>]*)>/gi, ''); html = html.replace(/<\/script([^>]*)>/gi, ''); //Replace the line feeds html = html.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\r/g, ''); //Remove Bad HTML elements (used to be script nodes) html = html.replace(new RegExp(']*)>(.*?)<\/bad>', 'gi'), ''); //Replace the lines feeds html = html.replace(//g, '\n'); return html; }, /** * @method cleanHTML * @param {String} html The unfiltered HTML * @description Process the HTML with a few regexes to clean it up and stabilize the output * @return {String} The filtered HTML */ cleanHTML: function(html) { //Start Filtering Output //Begin RegExs.. if (!html) { html = this.getEditorHTML(); } var markup = this.get('markup'); //Make some backups... html = this.pre_filter_linebreaks(html, markup); //Filter MS Word html = this.filter_msword(html); html = html.replace(/]*)\/>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/]*)\/>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/ul>/gi, '<\/YUI_UL>'); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/blockquote>/gi, '<\/YUI_BQ>'); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/embed>/gi, '<\/YUI_EMBED>'); //Convert b and i tags to strong and em tags if ((markup == 'semantic') || (markup == 'xhtml')) { //html = html.replace(/]*)?>/gi, ""); html = html.replace(/]*)>/gi, ""); html = html.replace(/<\/i>/gi, ''); //html = html.replace(/]*)?>/gi, ""); html = html.replace(/]*)>/gi, ""); html = html.replace(/<\/b>/gi, ''); } html = html.replace(/_moz_dirty=""/gi, ''); //normalize strikethrough html = html.replace(//gi, '/span>'); //Case Changing if (this.browser.ie) { html = html.replace(/text-decoration/gi, 'text-decoration'); html = html.replace(/font-weight/gi, 'font-weight'); html = html.replace(/_width="([^>]*)"/gi, ''); html = html.replace(/_height="([^>]*)"/gi, ''); //Cleanup Image URL's var url = this._baseHREF.replace(/\//gi, '\\/'), re = new RegExp('src="' + url, 'gi'); html = html.replace(re, 'src="'); } html = html.replace(//gi, ''); html = html.replace(//gi, ''); if ((markup == 'semantic') || (markup == 'xhtml') || (markup == 'css')) { html = html.replace(new RegExp(']*)face="([^>]*)">(.*?)<\/font>', 'gi'), '$3'); html = html.replace(/([^>]*)<\/span>', 'gi'), '$1'); html = html.replace(new RegExp('([^>]*)<\/span>', 'gi'), '$1'); } html = html.replace(/\/u>/gi, '/span>'); if (markup == 'css') { html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/em>/gi, ''); html = html.replace(/]*)>/gi, ''); html = html.replace(/<\/strong>/gi, ''); html = html.replace(//gi, '/span>'); html = html.replace(//gi, '/span>'); } html = html.replace(/ /gi, ' '); //Replace all double spaces and replace with a single } else { html = html.replace(//gi, '/u>'); } html = html.replace(/]*)>/gi, ''); html = html.replace(/\/ol>/gi, '/ol>'); html = html.replace(/
                • /gi, '/li>'); html = this.filter_safari(html); html = this.filter_internals(html); html = this.filter_all_rgb(html); //Replace our backups with the real thing html = this.post_filter_linebreaks(html, markup); if (markup == 'xhtml') { html = html.replace(/]*)>/g, ''); html = html.replace(/]*)>/g, ''); } else { html = html.replace(/]*)>/g, ''); html = html.replace(/]*)>/g, ''); } html = html.replace(/]*)>/g, ''); html = html.replace(/<\/YUI_UL>/g, '<\/ul>'); html = this.filter_invalid_lists(html); html = html.replace(/]*)>/g, ''); html = html.replace(/<\/YUI_BQ>/g, '<\/blockquote>'); html = html.replace(/]*)>/g, ''); html = html.replace(/<\/YUI_EMBED>/g, '<\/embed>'); //This should fix &'s in URL's html = html.replace(/ & /gi, ' YUI_AMP '); html = html.replace(/ &/gi, ' YUI_AMP_F '); html = html.replace(/& /gi, ' YUI_AMP_R '); html = html.replace(/&/gi, '&'); html = html.replace(/ YUI_AMP /gi, ' & '); html = html.replace(/ YUI_AMP_F /gi, ' &'); html = html.replace(/ YUI_AMP_R /gi, '& '); //Trim the output, removing whitespace from the beginning and end html = YAHOO.lang.trim(html); if (this.get('removeLineBreaks')) { html = html.replace(/\n/g, '').replace(/\r/g, ''); html = html.replace(/ /gi, ' '); //Replace all double spaces and replace with a single } for (var v in this.invalidHTML) { if (YAHOO.lang.hasOwnProperty(this.invalidHTML, v)) { if (Lang.isObject(v) && v.keepContents) { html = html.replace(new RegExp('<' + v + '([^>]*)>(.*?)<\/' + v + '>', 'gi'), '$1'); } else { html = html.replace(new RegExp('<' + v + '([^>]*)>(.*?)<\/' + v + '>', 'gi'), ''); } } } /* LATER -- Add DOM manipulation console.log(html); var frag = document.createDocumentFragment(); frag.innerHTML = html; var ps = frag.getElementsByTagName('p'), len = ps.length; for (var i = 0; i < len; i++) { var ps2 = ps[i].getElementsByTagName('p'); if (ps2.length) { } } html = frag.innerHTML; console.log(html); */ this.fireEvent('cleanHTML', { type: 'cleanHTML', target: this, html: html }); return html; }, /** * @method filter_msword * @param String html The HTML string to filter * @description Filters out msword html attributes and other junk. Activate with filterWord: true in config */ filter_msword: function(html) { if (!this.get('filterWord')) { return html; } //Remove the ms o: tags html = html.replace(/\s*<\/o:p>/g, ''); html = html.replace(/[\s\S]*?<\/o:p>/g, ' '); //Remove the ms w: tags html = html.replace( /]*>[\s\S]*?<\/w:[^>]*>/gi, ''); //Remove mso-? styles. html = html.replace( /\s*mso-[^:]+:[^;"]+;?/gi, ''); //Remove more bogus MS styles. html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, ''); html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\""); html = html.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, ''); html = html.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\""); html = html.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\""); html = html.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ); html = html.replace( /\s*tab-stops:[^;"]*;?/gi, ''); html = html.replace( /\s*tab-stops:[^"]*/gi, ''); //Remove XML declarations html = html.replace(/<\\?\?xml[^>]*>/gi, ''); //Remove lang html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3"); //Remove language tags html = html.replace( /<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, "<$1$3"); //Remove onmouseover and onmouseout events (from MS Word comments effect) html = html.replace( /<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3"); html = html.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3"); return html; }, /** * @method filter_invalid_lists * @param String html The HTML string to filter * @description Filters invalid ol and ul list markup, converts this:
                  1. ..
                  to this:
                  1. ..
                • */ filter_invalid_lists: function(html) { html = html.replace(/<\/li>\n/gi, ''); html = html.replace(/<\/li>
                    /gi, '
                    1. '); html = html.replace(/<\/ol>/gi, '
                  1. '); html = html.replace(/<\/ol><\/li>\n/gi, "
                  "); html = html.replace(/<\/li>
                    /gi, '
                    • '); html = html.replace(/<\/ul>/gi, '
                  • '); html = html.replace(/<\/ul><\/li>\n?/gi, "
                  "); html = html.replace(/<\/li>/gi, ""); html = html.replace(/<\/ol>/gi, "
            "); html = html.replace(/
              /gi, "
                "); html = html.replace(/
                  /gi, "
                    "); return html; }, /** * @method filter_safari * @param String html The HTML string to filter * @description Filters strings specific to Safari * @return String */ filter_safari: function(html) { if (this.browser.webkit) { // html = html.replace(/([^>])<\/span>/gi, '    '); html = html.replace(/Apple-style-span/gi, ''); html = html.replace(/style="line-height: normal;"/gi, ''); html = html.replace(/yui-wk-div/gi, ''); html = html.replace(/yui-wk-p/gi, ''); //Remove bogus LI's html = html.replace(/
                  • <\/li>/gi, ''); html = html.replace(/
                  • <\/li>/gi, ''); html = html.replace(/
                  • <\/li>/gi, ''); //Remove bogus DIV's - updated from just removing the div's to replacing /div with a break if (this.get('ptags')) { html = html.replace(/]*)>/g, ''); html = html.replace(/<\/div>/gi, '

                    '); } else { //html = html.replace(/
                    /gi, '
                    '); html = html.replace(/]*)>([ tnr]*)<\/div>/gi, '
                    '); html = html.replace(/<\/div>/gi, ''); } } return html; }, /** * @method filter_internals * @param String html The HTML string to filter * @description Filters internal RTE strings and bogus attrs we don't want * @return String */ filter_internals: function(html) { html = html.replace(/\r/g, ''); //Fix stuff we don't want html = html.replace(/<\/?(body|head|html)[^>]*>/gi, ''); //Fix last BR in LI html = html.replace(/<\/li>/gi, '
                  • '); html = html.replace(/yui-tag-span/gi, ''); html = html.replace(/yui-tag/gi, ''); html = html.replace(/yui-non/gi, ''); html = html.replace(/yui-img/gi, ''); html = html.replace(/ tag="span"/gi, ''); html = html.replace(/ class=""/gi, ''); html = html.replace(/ style=""/gi, ''); html = html.replace(/ class=" "/gi, ''); html = html.replace(/ class=" "/gi, ''); html = html.replace(/ target=""/gi, ''); html = html.replace(/ title=""/gi, ''); if (this.browser.ie) { html = html.replace(/ class= /gi, ''); html = html.replace(/ class= >/gi, ''); } return html; }, /** * @method filter_all_rgb * @param String str The HTML string to filter * @description Converts all RGB color strings found in passed string to a hex color, example: style="color: rgb(0, 255, 0)" converts to style="color: #00ff00" * @return String */ filter_all_rgb: function(str) { var exp = new RegExp("rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)", "gi"); var arr = str.match(exp); if (Lang.isArray(arr)) { for (var i = 0; i < arr.length; i++) { var color = this.filter_rgb(arr[i]); str = str.replace(arr[i].toString(), color); } } return str; }, /** * @method filter_rgb * @param String css The CSS string containing rgb(#,#,#); * @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00 * @return String */ filter_rgb: function(css) { if (css.toLowerCase().indexOf('rgb') != -1) { var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"); var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','); if (rgb.length == 5) { var r = parseInt(rgb[1], 10).toString(16); var g = parseInt(rgb[2], 10).toString(16); var b = parseInt(rgb[3], 10).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; css = "#" + r + g + b; } } return css; }, /** * @method pre_filter_linebreaks * @param String html The HTML to filter * @param String markup The markup type to filter to * @description HTML Pre Filter * @return String */ pre_filter_linebreaks: function(html, markup) { if (this.browser.webkit) { html = html.replace(/
                    /gi, ''); html = html.replace(/
                    /gi, ''); } html = html.replace(/
                    /gi, ''); html = html.replace(/
                    /gi, ''); html = html.replace(//gi, ''); html = html.replace(/
                    /gi, ''); html = html.replace(/
                    <\/div>/gi, ''); html = html.replace(/

                    ( | )<\/p>/g, ''); html = html.replace(/


                     <\/p>/gi, ''); html = html.replace(/

                     <\/p>/gi, ''); //Fix last BR html = html.replace(/$/, ''); //Fix last BR in P html = html.replace(/<\/p>/g, '

                    '); if (this.browser.ie) { html = html.replace(/    /g, '\t'); } return html; }, /** * @method post_filter_linebreaks * @param String html The HTML to filter * @param String markup The markup type to filter to * @description HTML Pre Filter * @return String */ post_filter_linebreaks: function(html, markup) { if (markup == 'xhtml') { html = html.replace(//g, '
                    '); } else { html = html.replace(//g, '
                    '); } return html; }, /** * @method clearEditorDoc * @description Clear the doc of the Editor */ clearEditorDoc: function() { this._getDoc().body.innerHTML = ' '; }, /** * @method openWindow * @description Override Method for Advanced Editor */ openWindow: function(win) { }, /** * @method moveWindow * @description Override Method for Advanced Editor */ moveWindow: function() { }, /** * @private * @method _closeWindow * @description Override Method for Advanced Editor */ _closeWindow: function() { }, /** * @method closeWindow * @description Override Method for Advanced Editor */ closeWindow: function() { //this.unsubscribeAll('afterExecCommand'); this.toolbar.resetAllButtons(); this.focus(); }, /** * @method destroy * @description Destroys the editor, all of it's elements and objects. * @return {Boolean} */ destroy: function() { if (this._nodeChangeDelayTimer) { clearTimeout(this._nodeChangeDelayTimer); } this.hide(); YAHOO.log('Destroying Editor', 'warn', 'SimpleEditor'); if (this.resize) { YAHOO.log('Destroying Resize', 'warn', 'SimpleEditor'); this.resize.destroy(); } if (this.dd) { YAHOO.log('Unreg DragDrop Instance', 'warn', 'SimpleEditor'); this.dd.unreg(); } if (this.get('panel')) { YAHOO.log('Destroying Editor Panel', 'warn', 'SimpleEditor'); this.get('panel').destroy(); } this.saveHTML(); this.toolbar.destroy(); YAHOO.log('Restoring TextArea', 'info', 'SimpleEditor'); this.setStyle('visibility', 'visible'); this.setStyle('position', 'static'); this.setStyle('top', ''); this.setStyle('left', ''); var textArea = this.get('element'); this.get('element_cont').get('parentNode').replaceChild(textArea, this.get('element_cont').get('element')); this.get('element_cont').get('element').innerHTML = ''; this.set('handleSubmit', false); //Remove the submit handler return true; }, /** * @method toString * @description Returns a string representing the editor. * @return {String} */ toString: function() { var str = 'SimpleEditor'; if (this.get && this.get('element_cont')) { str = 'SimpleEditor (#' + this.get('element_cont').get('id') + ')' + ((this.get('disabled') ? ' Disabled' : '')); } return str; } }); /** * @event toolbarLoaded * @description Event is fired during the render process directly after the Toolbar is loaded. Allowing you to attach events to the toolbar. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event cleanHTML * @description Event is fired after the cleanHTML method is called. * @type YAHOO.util.CustomEvent */ /** * @event afterRender * @description Event is fired after the render process finishes. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorContentLoaded * @description Event is fired after the editor iframe's document fully loads and fires it's onload event. From here you can start injecting your own things into the document. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeNodeChange * @description Event fires at the beginning of the nodeChange process. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event afterNodeChange * @description Event fires at the end of the nodeChange process. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeExecCommand * @description Event fires at the beginning of the execCommand process. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event afterExecCommand * @description Event fires at the end of the execCommand process. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorMouseUp * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorMouseDown * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorDoubleClick * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorClick * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyUp * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyPress * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyDown * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See Element.addListener for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorMouseUp * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorMouseDown * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorDoubleClick * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorClick * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyUp * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyPress * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyDown * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event editorWindowFocus * @description Fires when the iframe is focused. Note, this is window focus event, not an Editor focus event. * @type YAHOO.util.CustomEvent */ /** * @event editorWindowBlur * @description Fires when the iframe is blurred. Note, this is window blur event, not an Editor blur event. * @type YAHOO.util.CustomEvent */ /** * @description Singleton object used to track the open window objects and panels across the various open editors * @class EditorInfo * @static */ YAHOO.widget.EditorInfo = { /** * @private * @property _instances * @description A reference to all editors on the page. * @type Object */ _instances: {}, /** * @private * @property blankImage * @description A reference to the blankImage url * @type String */ blankImage: '', /** * @private * @property window * @description A reference to the currently open window object in any editor on the page. * @type Object YAHOO.widget.EditorWindow */ window: {}, /** * @private * @property panel * @description A reference to the currently open panel in any editor on the page. * @type Object YAHOO.widget.Overlay */ panel: null, /** * @method getEditorById * @description Returns a reference to the Editor object associated with the given textarea * @param {String/HTMLElement} id The id or reference of the textarea to return the Editor instance of * @return Object YAHOO.widget.Editor */ getEditorById: function(id) { if (!YAHOO.lang.isString(id)) { //Not a string, assume a node Reference id = id.id; } if (this._instances[id]) { return this._instances[id]; } return false; }, /** * @method saveAll * @description Saves all Editor instances on the page. If a form reference is passed, only Editor's bound to this form will be saved. * @param {HTMLElement} form The form to check if this Editor instance belongs to */ saveAll: function(form) { var i, e, items = YAHOO.widget.EditorInfo._instances; if (form) { for (i in items) { if (Lang.hasOwnProperty(items, i)) { e = items[i]; if (e.get('element').form && (e.get('element').form == form)) { e.saveHTML(); } } } } else { for (i in items) { if (Lang.hasOwnProperty(items, i)) { items[i].saveHTML(); } } } }, /** * @method toString * @description Returns a string representing the EditorInfo. * @return {String} */ toString: function() { var len = 0; for (var i in this._instances) { if (Lang.hasOwnProperty(this._instances, i)) { len++; } } return 'Editor Info (' + len + ' registered intance' + ((len > 1) ? 's' : '') + ')'; } }; })(); YAHOO.register("simpleeditor", YAHOO.widget.SimpleEditor, {version: "2.9.0", build: "2800"}); }, '2.9.0' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-skin-sam-simpleeditor", "yui2-event", "yui2-element"], "optional": ["yui2-containercore", "yui2-dragdrop", "yui2-skin-sam-button", "yui2-skin-sam-menu", "yui2-menu", "yui2-button", "yui2-animation"]}); PK\a'+G+""; this._titlebar.appendChild(F);A.on(F.firstChild,"click",function(H){A.stopEvent(H);});A.on([F,F.firstChild],"focus",function(){this._handleFocus();},this,true);}if(this.get("firstChild")){this.insertBefore(this._titlebar,this.get("firstChild"));}else{this.appendChild(this._titlebar);}if(this.get("collapse")){this.set("collapse",true);}}else{if(this._titlebar){if(this._titlebar&&this._titlebar.parentNode){this._titlebar.parentNode.removeChild(this._titlebar);}}}}});this.setAttributeConfig("collapse",{value:false,method:function(H){if(this._titlebar){var G=null;var F=C.getElementsByClassName("collapse","span",this._titlebar);if(H){if(F.length>0){return true;}G=document.createElement("SPAN");G.innerHTML="X";G.title=this.STR_COLLAPSE;C.addClass(G,"collapse");this._titlebar.appendChild(G);A.addListener(G,"click",function(){if(C.hasClass(this.get("cont").parentNode,"yui-toolbar-container-collapsed")){this.collapse(false);}else{this.collapse();}},this,true);}else{G=C.getElementsByClassName("collapse","span",this._titlebar);if(G[0]){if(C.hasClass(this.get("cont").parentNode,"yui-toolbar-container-collapsed")){this.collapse(false);}G[0].parentNode.removeChild(G[0]);}}}}});this.setAttributeConfig("draggable",{value:(E.draggable||false),method:function(F){if(F&&!this.get("titlebar")){if(!this._dragHandle){this._dragHandle=document.createElement("SPAN");this._dragHandle.innerHTML="|";this._dragHandle.setAttribute("title","Click to drag the toolbar");this._dragHandle.id=this.get("id")+"_draghandle";C.addClass(this._dragHandle,this.CLASS_DRAGHANDLE);if(this.get("cont").hasChildNodes()){this.get("cont").insertBefore(this._dragHandle,this.get("cont").firstChild);}else{this.get("cont").appendChild(this._dragHandle);}this.dd=new YAHOO.util.DD(this.get("id"));this.dd.setHandleElId(this._dragHandle.id);}}else{if(this._dragHandle){this._dragHandle.parentNode.removeChild(this._dragHandle);this._dragHandle=null;this.dd=null;}}if(this._titlebar){if(F){this.dd=new YAHOO.util.DD(this.get("id"));this.dd.setHandleElId(this._titlebar);C.addClass(this._titlebar,"draggable");}else{C.removeClass(this._titlebar,"draggable");if(this.dd){this.dd.unreg();this.dd=null;}}}},validator:function(G){var F=true;if(!YAHOO.util.DD){F=false;}return F;}});},addButtonGroup:function(J){if(!this.get("element")){this._queue[this._queue.length]=["addButtonGroup",arguments];return false;}if(!this.hasClass(this.CLASS_PREFIX+"-grouped")){this.addClass(this.CLASS_PREFIX+"-grouped");}var L=document.createElement("DIV");C.addClass(L,this.CLASS_PREFIX+"-group");C.addClass(L,this.CLASS_PREFIX+"-group-"+J.group);if(J.label){var F=document.createElement("h3");F.innerHTML=J.label;L.appendChild(F);}if(!this.get("grouplabels")){C.addClass(this.get("cont"),this.CLASS_PREFIX,"-nogrouplabels");}this.get("cont").appendChild(L);var I=document.createElement("ul");L.appendChild(I);if(!this._buttonGroupList){this._buttonGroupList={};}this._buttonGroupList[J.group]=I;var K=[],H;for(var G=0;G'+F.replace("#","")+"";}}G+="X";window.setTimeout(function(){E.innerHTML=G;},0);A.on(E,"mouseover",function(M){var K=this._colorPicker;var L=K.getElementsByTagName("em")[0];var J=K.getElementsByTagName("strong")[0];var I=A.getTarget(M);if(I.tagName.toLowerCase()=="a"){L.style.backgroundColor=I.style.backgroundColor;J.innerHTML=this._colorData["#"+I.innerHTML]+"
                    "+I.innerHTML;}},this,true);A.on(E,"focus",function(I){A.stopEvent(I);});A.on(E,"click",function(I){A.stopEvent(I);});A.on(E,"mousedown",function(J){A.stopEvent(J);var I=A.getTarget(J);if(I.tagName.toLowerCase()=="a"){var L=this.fireEvent("colorPickerClicked",{type:"colorPickerClicked",target:this,button:this._colorPicker._button,color:I.innerHTML,colorName:this._colorData["#"+I.innerHTML]});if(L!==false){var K={color:I.innerHTML,colorName:this._colorData["#"+I.innerHTML],value:this._colorPicker._button};this.fireEvent("buttonClick",{type:"buttonClick",target:this.get("element"),button:K});}this.getButtonByValue(this._colorPicker._button).getMenu().hide();}},this,true);},_resetColorPicker:function(){var F=this._colorPicker.getElementsByTagName("em")[0];var E=this._colorPicker.getElementsByTagName("strong")[0];F.style.backgroundColor="transparent";E.innerHTML="";},_makeColorButton:function(E){if(!this._colorPicker){this._createColorPicker(this.get("id"));}E.type="color";E.menu=new YAHOO.widget.Overlay(this.get("id")+"_"+E.value+"_menu",{visible:false,position:"absolute",iframe:true});E.menu.setBody("");E.menu.render(this.get("cont"));C.addClass(E.menu.element,"yui-button-menu");C.addClass(E.menu.element,"yui-color-button-menu");E.menu.beforeShowEvent.subscribe(function(){E.menu.cfg.setProperty("zindex",5);E.menu.cfg.setProperty("context",[this.getButtonById(E.id).get("element"),"tl","bl"]);this._resetColorPicker();var F=this._colorPicker;if(F.parentNode){F.parentNode.removeChild(F);}E.menu.setBody("");E.menu.appendToBody(F);this._colorPicker.style.display="block";},this,true);return E;},_makeSpinButton:function(R,L){R.addClass(this.CLASS_PREFIX+"-spinbutton");var S=this,N=R._button.parentNode.parentNode,I=L.range,H=document.createElement("a"),G=document.createElement("a");H.href="#";G.href="#";H.tabIndex="-1";G.tabIndex="-1";H.className="up";H.title=this.STR_SPIN_UP;H.innerHTML=this.STR_SPIN_UP;G.className="down";G.title=this.STR_SPIN_DOWN;G.innerHTML=this.STR_SPIN_DOWN;N.appendChild(H);N.appendChild(G);var M=YAHOO.lang.substitute(this.STR_SPIN_LABEL,{VALUE:R.get("label")});R.set("title",M);var Q=function(T){T=((TI[1])?I[1]:T);return T;};var P=this.browser;var F=false;var K=this.STR_SPIN_LABEL;if(this._titlebar&&this._titlebar.firstChild){F=this._titlebar.firstChild;}var E=function(U){YAHOO.util.Event.stopEvent(U);if(!R.get("disabled")&&(U.keyCode!=9)){var V=parseInt(R.get("label"),10);V++;V=Q(V);R.set("label",""+V);var T=YAHOO.lang.substitute(K,{VALUE:R.get("label")});R.set("title",T);if(!P.webkit&&F){}S._buttonClick(U,L);}};var O=function(U){YAHOO.util.Event.stopEvent(U);if(!R.get("disabled")&&(U.keyCode!=9)){var V=parseInt(R.get("label"),10);V--;V=Q(V);R.set("label",""+V);var T=YAHOO.lang.substitute(K,{VALUE:R.get("label")}); R.set("title",T);if(!P.webkit&&F){}S._buttonClick(U,L);}};var J=function(T){if(T.keyCode==38){E(T);}else{if(T.keyCode==40){O(T);}else{if(T.keyCode==107&&T.shiftKey){E(T);}else{if(T.keyCode==109&&T.shiftKey){O(T);}}}}};R.on("keydown",J,this,true);A.on(H,"mousedown",function(T){A.stopEvent(T);},this,true);A.on(G,"mousedown",function(T){A.stopEvent(T);},this,true);A.on(H,"click",E,this,true);A.on(G,"click",O,this,true);},_buttonClick:function(L,F){var E=true;if(L&&L.type=="keypress"){if(L.keyCode==9){E=false;}else{if((L.keyCode===13)||(L.keyCode===0)||(L.keyCode===32)){}else{E=false;}}}if(E){var N=true,H=false;F.isSelected=this.isSelected(F.id);if(F.value){H=this.fireEvent(F.value+"Click",{type:F.value+"Click",target:this.get("element"),button:F});if(H===false){N=false;}}if(F.menucmd&&N){H=this.fireEvent(F.menucmd+"Click",{type:F.menucmd+"Click",target:this.get("element"),button:F});if(H===false){N=false;}}if(N){this.fireEvent("buttonClick",{type:"buttonClick",target:this.get("element"),button:F});}if(F.type=="select"){var K=this.getButtonById(F.id);if(K.buttonType=="rich"){var J=F.value;for(var I=0;I'+J+"");var M=K.getMenu().getItems();for(var G=0;G(this._buttonList.length-1)){this._navCounter=0;}if(this._navCounter<0){this._navCounter=(this._buttonList.length-1);}if(this._buttonList[this._navCounter]){var E=this._buttonList[this._navCounter].get("element");if(this.browser.ie){E=this._buttonList[this._navCounter].get("element").getElementsByTagName("a")[0];}if(this._buttonList[this._navCounter].get("disabled")){this._navigateButtons(F);}else{E.focus();}}break;}},_handleFocus:function(){if(!this._keyNav){var E="keypress";if(this.browser.ie){E="keydown";}A.on(this.get("element"),E,this._navigateButtons,this,true);this._keyNav=true;this._navCounter=-1;}},getButtonById:function(G){var E=this._buttonList.length;for(var F=0;F'+H[E]._oText.nodeValue+"");}else{H[E].cfg.setProperty("checked",false);}}}}}else{return false;}},deselectButton:function(F){var E=B.call(this,F);if(E){E.removeClass("yui-button-selected");E.removeClass("yui-button-"+E.get("value")+"-selected");E.removeClass("yui-button-hover");E._selected=false;}else{return false;}},deselectAllButtons:function(){var E=this._buttonList.length;for(var F=0;F0)){var I=0;for(var G=0;G',editorDirty:null,_defaultCSS:"html { height: 95%; } body { padding: 7px; background-color: #fff; font: 13px/1.22 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small; } a, a:visited, a:hover { color: blue !important; text-decoration: underline !important; cursor: text !important; } .warning-localfile { border-bottom: 1px dashed red !important; } .yui-busy { cursor: wait !important; } img.selected { border: 2px dotted #808080; } img { cursor: pointer !important; border: none; } body.ptags.webkit div.yui-wk-p { margin: 11px 0; } body.ptags.webkit div.yui-wk-div { margin: 0; }",_defaultToolbar:null,_lastButton:null,_baseHREF:function(){var E=document.location.href;if(E.indexOf("?")!==-1){E=E.substring(0,E.indexOf("?"));}E=E.substring(0,E.lastIndexOf("/"))+"/";return E;}(),_lastImage:null,_blankImageLoaded:null,_fixNodesTimer:null,_nodeChangeTimer:null,_nodeChangeDelayTimer:null,_lastNodeChangeEvent:null,_lastNodeChange:0,_rendered:null,DOMReady:null,_selection:null,_mask:null,_showingHiddenElements:null,currentWindow:null,currentEvent:null,operaEvent:null,currentFont:null,currentElement:null,dompath:null,beforeElement:null,afterElement:null,invalidHTML:{form:true,input:true,button:true,select:true,link:true,html:true,body:true,iframe:true,script:true,style:true,textarea:true},toolbar:null,_contentTimer:null,_contentTimerMax:500,_contentTimerCounter:0,_disabled:["createlink","fontname","fontsize","forecolor","backcolor"],_alwaysDisabled:{undo:true,redo:true},_alwaysEnabled:{},_semantic:{"bold":true,"italic":true,"underline":true},_tag2cmd:{"b":"bold","strong":"bold","i":"italic","em":"italic","u":"underline","sup":"superscript","sub":"subscript","img":"insertimage","a":"createlink","ul":"insertunorderedlist","ol":"insertorderedlist"},_createIframe:function(){var I=document.createElement("iframe");I.id=this.get("id")+"_editor";var G={border:"0",frameBorder:"0",marginWidth:"0",marginHeight:"0",leftMargin:"0",topMargin:"0",allowTransparency:"true",width:"100%"};if(this.get("autoHeight")){G.scrolling="no";}for(var H in G){if(D.hasOwnProperty(G,H)){I.setAttribute(H,G[H]);}}var F="javascript:;";if(this.browser.ie){F="javascript:false;";}I.setAttribute("src",F);var E=new YAHOO.util.Element(I);E.setStyle("visibility","hidden");return E;},_isElement:function(F,E){if(F&&F.tagName&&(F.tagName.toLowerCase()==E)){return true;}if(F&&F.getAttribute&&(F.getAttribute("tag")==E)){return true; }return false;},_hasParent:function(F,E){if(!F||!F.parentNode){return false;}while(F.parentNode){if(this._isElement(F,E)){return F;}if(F.parentNode){F=F.parentNode;}else{return false;}}return false;},_getDoc:function(){var E=false;try{if(this.get("iframe").get("element").contentWindow.document){E=this.get("iframe").get("element").contentWindow.document;return E;}}catch(F){return false;}},_getWindow:function(){return this.get("iframe").get("element").contentWindow;},focus:function(){this._getWindow().focus();},_focusWindow:function(){this.focus();},_hasSelection:function(){var G=this._getSelection();var E=this._getRange();var F=false;if(!G||!E){return F;}if(this.browser.ie){if(E.text){F=true;}if(E.html){F=true;}}else{if(this.browser.webkit){if(G+""!==""){F=true;}}else{if(G&&(G.toString()!=="")&&(G!==undefined)){F=true;}}}return F;},_getSelection:function(){var E=null;if(this._getDoc()&&this._getWindow()){if(this._getDoc().selection&&!this.browser.opera){E=this._getDoc().selection;}else{E=this._getWindow().getSelection();}if(this.browser.webkit){if(E.baseNode){this._selection={};this._selection.baseNode=E.baseNode;this._selection.baseOffset=E.baseOffset;this._selection.extentNode=E.extentNode;this._selection.extentOffset=E.extentOffset;}else{if(this._selection!==null){E=this._getWindow().getSelection();E.setBaseAndExtent(this._selection.baseNode,this._selection.baseOffset,this._selection.extentNode,this._selection.extentOffset);this._selection=null;}}}}return E;},_selectNode:function(F,I){if(!F){return false;}var G=this._getSelection(),E=null;if(this.browser.ie){try{E=this._getDoc().body.createTextRange();E.moveToElementText(F);E.select();}catch(H){}}else{if(this.browser.webkit){if(I){G.setBaseAndExtent(F,1,F,F.innerText.length);}else{G.setBaseAndExtent(F,0,F,F.innerText.length);}}else{if(this.browser.opera){G=this._getWindow().getSelection();E=this._getDoc().createRange();E.selectNode(F);G.removeAllRanges();G.addRange(E);}else{E=this._getDoc().createRange();E.selectNodeContents(F);G.removeAllRanges();G.addRange(E);}}}this.nodeChange();},_getRange:function(){var E=this._getSelection();if(E===null){return null;}if(this.browser.webkit&&!E.getRangeAt){var H=this._getDoc().createRange();try{H.setStart(E.anchorNode,E.anchorOffset);H.setEnd(E.focusNode,E.focusOffset);}catch(G){H=this._getWindow().getSelection()+"";}return H;}if(this.browser.ie){try{return E.createRange();}catch(F){return null;}}if(E.rangeCount>0){return E.getRangeAt(0);}return null;},_setDesignMode:function(E){if(this.get("setDesignMode")){try{this._getDoc().designMode=((E.toLowerCase()=="off")?"off":"on");}catch(F){}}},_toggleDesignMode:function(){var F=this._getDoc().designMode,E=((F.toLowerCase()=="on")?"off":"on");this._setDesignMode(E);return E;},_focused:null,_handleFocus:function(E){if(!this._focused){this._focused=true;this.fireEvent("editorWindowFocus",{type:"editorWindowFocus",target:this});}},_handleBlur:function(E){if(this._focused){this._focused=false;this.fireEvent("editorWindowBlur",{type:"editorWindowBlur",target:this});}},_initEditorEvents:function(){var F=this._getDoc(),E=this._getWindow();A.on(F,"mouseup",this._handleMouseUp,this,true);A.on(F,"mousedown",this._handleMouseDown,this,true);A.on(F,"click",this._handleClick,this,true);A.on(F,"dblclick",this._handleDoubleClick,this,true);A.on(F,"keypress",this._handleKeyPress,this,true);A.on(F,"keyup",this._handleKeyUp,this,true);A.on(F,"keydown",this._handleKeyDown,this,true);A.on(E,"focus",this._handleFocus,this,true);A.on(E,"blur",this._handleBlur,this,true);},_removeEditorEvents:function(){var F=this._getDoc(),E=this._getWindow();A.removeListener(F,"mouseup",this._handleMouseUp,this,true);A.removeListener(F,"mousedown",this._handleMouseDown,this,true);A.removeListener(F,"click",this._handleClick,this,true);A.removeListener(F,"dblclick",this._handleDoubleClick,this,true);A.removeListener(F,"keypress",this._handleKeyPress,this,true);A.removeListener(F,"keyup",this._handleKeyUp,this,true);A.removeListener(F,"keydown",this._handleKeyDown,this,true);A.removeListener(E,"focus",this._handleFocus,this,true);A.removeListener(E,"blur",this._handleBlur,this,true);},_fixWebkitDivs:function(){if(this.browser.webkit){var E=this._getDoc().body.getElementsByTagName("div");C.addClass(E,"yui-wk-div");}},_initEditor:function(F){if(this._editorInit){return;}this._editorInit=true;if(this.browser.ie){this._getDoc().body.style.margin="0";}if(!this.get("disabled")){this._setDesignMode("on");this._contentTimerCounter=0;}if(!this._getDoc().body){this._contentTimerCounter=0;this._editorInit=false;this._checkLoaded();return false;}if(!F){this.toolbar.on("buttonClick",this._handleToolbarClick,this,true);}if(!this.get("disabled")){this._initEditorEvents();this.toolbar.set("disabled",false);}if(F){this.fireEvent("editorContentReloaded",{type:"editorreloaded",target:this});}else{this.fireEvent("editorContentLoaded",{type:"editorLoaded",target:this});}this._fixWebkitDivs();if(this.get("dompath")){var E=this;setTimeout(function(){E._writeDomPath.call(E);E._setupResize.call(E);},150);}var H=[];for(var G in this.browser){if(this.browser[G]){H.push(G);}}if(this.get("ptags")){H.push("ptags");}C.addClass(this._getDoc().body,H.join(" "));this.nodeChange(true);},_checkLoaded:function(F){this._editorInit=false;this._contentTimerCounter++;if(this._contentTimer){clearTimeout(this._contentTimer);}if(this._contentTimerCounter>this._contentTimerMax){return false;}var H=false;try{if(this._getDoc()&&this._getDoc().body){if(this.browser.ie){if(this._getDoc().body.readyState=="complete"){H=true;}}else{if(this._getDoc().body._rteLoaded===true){H=true;}}}}catch(G){H=false;}if(H===true){this._initEditor(F);}else{var E=this;this._contentTimer=setTimeout(function(){E._checkLoaded.call(E,F);},20);}},_setInitialContent:function(F){var I=((this._textarea)?this.get("element").value:this.get("element").innerHTML),K=null;if(I===""){I="
                    ";}var G=D.substitute(this.get("html"),{TITLE:this.STR_TITLE,CONTENT:this._cleanIncomingHTML(I),CSS:this.get("css"),HIDDEN_CSS:((this.get("hiddencss"))?this.get("hiddencss"):"/* No Hidden CSS */"),EXTRA_CSS:((this.get("extracss"))?this.get("extracss"):"/* No Extra CSS */")}),E=true; G=G.replace(/RIGHT_BRACKET/gi,"{");G=G.replace(/LEFT_BRACKET/gi,"}");if(document.compatMode!="BackCompat"){G=this._docType+"\n"+G;}else{}if(this.browser.ie||this.browser.webkit||this.browser.opera||(navigator.userAgent.indexOf("Firefox/1.5")!=-1)){try{if(this.browser.air){K=this._getDoc().implementation.createHTMLDocument();var L=this._getDoc();L.open();L.close();K.open();K.write(G);K.close();var H=L.importNode(K.getElementsByTagName("html")[0],true);L.replaceChild(H,L.getElementsByTagName("html")[0]);L.body._rteLoaded=true;}else{K=this._getDoc();K.open();K.write(G);K.close();}}catch(J){E=false;}}else{this.get("iframe").get("element").src="data:text/html;charset=utf-8,"+encodeURIComponent(G);}this.get("iframe").setStyle("visibility","");if(E){this._checkLoaded(F);}},_setMarkupType:function(E){switch(this.get("markup")){case"css":this._setEditorStyle(true);break;case"default":this._setEditorStyle(false);break;case"semantic":case"xhtml":if(this._semantic[E]){this._setEditorStyle(false);}else{this._setEditorStyle(true);}break;}},_setEditorStyle:function(F){try{this._getDoc().execCommand("useCSS",false,!F);}catch(E){}},_getSelectedElement:function(){var J=this._getDoc(),G=null,H=null,K=null,F=true;if(this.browser.ie){this.currentEvent=this._getWindow().event;G=this._getRange();if(G){K=G.item?G.item(0):G.parentElement();if(this._hasSelection()){}if(K===J.body){K=null;}}if((this.currentEvent!==null)&&(this.currentEvent.keyCode===0)){K=A.getTarget(this.currentEvent);}}else{H=this._getSelection();G=this._getRange();if(!H||!G){return null;}if(!this._hasSelection()&&this.browser.webkit3){}if(this.browser.gecko){if(G.startContainer){if(G.startContainer.nodeType===3){K=G.startContainer.parentNode;}else{if(G.startContainer.nodeType===1){K=G.startContainer;}}if(this.currentEvent){var E=A.getTarget(this.currentEvent);if(!this._isElement(E,"html")){if(K!==E){K=E;}}}}}if(F){if(H.anchorNode&&(H.anchorNode.nodeType==3)){if(H.anchorNode.parentNode){K=H.anchorNode.parentNode;}if(H.anchorNode.nextSibling!=H.focusNode.nextSibling){K=H.anchorNode.nextSibling;}}if(this._isElement(K,"br")){K=null;}if(!K){K=G.commonAncestorContainer;if(!G.collapsed){if(G.startContainer==G.endContainer){if(G.startOffset-G.endOffset<2){if(G.startContainer.hasChildNodes()){K=G.startContainer.childNodes[G.startOffset];}}}}}}}if(this.currentEvent!==null){try{switch(this.currentEvent.type){case"click":case"mousedown":case"mouseup":if(this.browser.webkit){K=A.getTarget(this.currentEvent);}break;default:break;}}catch(I){}}else{if((this.currentElement&&this.currentElement[0])&&(!this.browser.ie)){}}if(this.browser.opera||this.browser.webkit){if(this.currentEvent&&!K){K=YAHOO.util.Event.getTarget(this.currentEvent);}}if(!K||!K.tagName){K=J.body;}if(this._isElement(K,"html")){K=J.body;}if(this._isElement(K,"body")){K=J.body;}if(K&&!K.parentNode){K=J.body;}if(K===undefined){K=null;}return K;},_getDomPath:function(E){if(!E){E=this._getSelectedElement();}var F=[];while(E!==null){if(E.ownerDocument!=this._getDoc()){E=null;break;}if(E.nodeName&&E.nodeType&&(E.nodeType==1)){F[F.length]=E;}if(this._isElement(E,"body")){break;}E=E.parentNode;}if(F.length===0){if(this._getDoc()&&this._getDoc().body){F[0]=this._getDoc().body;}}return F.reverse();},_writeDomPath:function(){var K=this._getDomPath(),I=[],G="",L="";for(var E=0;E10){L=''+L.substring(0,10)+"..."+"";}else{L=''+L+"";}I[I.length]=L;}}var H=I.join(" "+this.SEP_DOMPATH+" ");if(this.dompath.innerHTML!=H){this.dompath.innerHTML=H;}},_fixNodes:function(){try{var K=this._getDoc(),H=[];for(var E in this.invalidHTML){if(YAHOO.lang.hasOwnProperty(this.invalidHTML,E)){if(E.toLowerCase()!="span"){var F=K.body.getElementsByTagName(E);if(F.length){for(var G=0;G-1;E--){if(C.hasClass(J[E],this.CLASS_NOEDIT)){try{this._getDoc().execCommand("enableObjectResizing",false,"false");}catch(I){}this.nodeChange();A.stopEvent(G);return true;}}try{this._getDoc().execCommand("enableObjectResizing",false,"true");}catch(H){}}return false;},_setCurrentEvent:function(E){this.currentEvent=E;},_handleClick:function(G){var F=this.fireEvent("beforeEditorClick",{type:"beforeEditorClick",target:this,ev:G});if(F===false){return false;}if(this._isNonEditable(G)){return false;}this._setCurrentEvent(G);if(this.currentWindow){this.closeWindow();}if(this.currentWindow){this.closeWindow();}if(this.browser.webkit){var E=A.getTarget(G);if(this._isElement(E,"a")||this._isElement(E.parentNode,"a")){A.stopEvent(G);this.nodeChange();}}else{this.nodeChange(); }this.fireEvent("editorClick",{type:"editorClick",target:this,ev:G});},_handleMouseUp:function(G){var F=this.fireEvent("beforeEditorMouseUp",{type:"beforeEditorMouseUp",target:this,ev:G});if(F===false){return false;}if(this._isNonEditable(G)){return false;}var E=this;if(this.browser.opera){var H=A.getTarget(G);if(this._isElement(H,"img")){this.nodeChange();if(this.operaEvent){clearTimeout(this.operaEvent);this.operaEvent=null;this._handleDoubleClick(G);}else{this.operaEvent=window.setTimeout(function(){E.operaEvent=false;},700);}}}if(this.browser.webkit||this.browser.opera){if(this.browser.webkit){A.stopEvent(G);}}this.nodeChange();this.fireEvent("editorMouseUp",{type:"editorMouseUp",target:this,ev:G});},_handleMouseDown:function(F){var E=this.fireEvent("beforeEditorMouseDown",{type:"beforeEditorMouseDown",target:this,ev:F});if(E===false){return false;}if(this._isNonEditable(F)){return false;}this._setCurrentEvent(F);var G=A.getTarget(F);if(this.browser.webkit&&this._hasSelection()){var H=this._getSelection();if(!this.browser.webkit3){H.collapse(true);}else{H.collapseToStart();}}if(this.browser.webkit&&this._lastImage){C.removeClass(this._lastImage,"selected");this._lastImage=null;}if(this._isElement(G,"img")||this._isElement(G,"a")){if(this.browser.webkit){A.stopEvent(F);if(this._isElement(G,"img")){C.addClass(G,"selected");this._lastImage=G;}}if(this.currentWindow){this.closeWindow();}this.nodeChange();}this.fireEvent("editorMouseDown",{type:"editorMouseDown",target:this,ev:F});},_handleDoubleClick:function(F){var E=this.fireEvent("beforeEditorDoubleClick",{type:"beforeEditorDoubleClick",target:this,ev:F});if(E===false){return false;}if(this._isNonEditable(F)){return false;}this._setCurrentEvent(F);var G=A.getTarget(F);if(this._isElement(G,"img")){this.currentElement[0]=G;this.toolbar.fireEvent("insertimageClick",{type:"insertimageClick",target:this.toolbar});this.fireEvent("afterExecCommand",{type:"afterExecCommand",target:this});}else{if(this._hasParent(G,"a")){this.currentElement[0]=this._hasParent(G,"a");this.toolbar.fireEvent("createlinkClick",{type:"createlinkClick",target:this.toolbar});this.fireEvent("afterExecCommand",{type:"afterExecCommand",target:this});}}this.nodeChange();this.fireEvent("editorDoubleClick",{type:"editorDoubleClick",target:this,ev:F});},_handleKeyUp:function(G){var F=this.fireEvent("beforeEditorKeyUp",{type:"beforeEditorKeyUp",target:this,ev:G});if(F===false){return false;}if(this._isNonEditable(G)){return false;}this._storeUndo();this._setCurrentEvent(G);switch(G.keyCode){case this._keyMap.SELECT_ALL.key:if(this._checkKey(this._keyMap.SELECT_ALL,G)){this.nodeChange();}break;case 32:case 35:case 36:case 37:case 38:case 39:case 40:case 46:case 8:case this._keyMap.CLOSE_WINDOW.key:if((G.keyCode==this._keyMap.CLOSE_WINDOW.key)&&this.currentWindow){if(this._checkKey(this._keyMap.CLOSE_WINDOW,G)){this.closeWindow();}}else{if(!this.browser.ie){if(this._nodeChangeTimer){clearTimeout(this._nodeChangeTimer);}var E=this;this._nodeChangeTimer=setTimeout(function(){E._nodeChangeTimer=null;E.nodeChange.call(E);},100);}else{this.nodeChange();}this.editorDirty=true;}break;}this.fireEvent("editorKeyUp",{type:"editorKeyUp",target:this,ev:G});},_handleKeyPress:function(G){var F=this.fireEvent("beforeEditorKeyPress",{type:"beforeEditorKeyPress",target:this,ev:G});if(F===false){return false;}if(this.get("allowNoEdit")){if(G&&G.keyCode&&(G.keyCode==63272)){A.stopEvent(G);}}if(this._isNonEditable(G)){return false;}this._setCurrentEvent(G);this._storeUndo();if(this.browser.opera){if(G.keyCode===13){var E=this._getSelectedElement();if(!this._isElement(E,"li")){this.execCommand("inserthtml","
                    ");A.stopEvent(G);}}}if(this.browser.webkit){if(!this.browser.webkit3){if(G.keyCode&&(G.keyCode==122)&&(G.metaKey)){if(this._hasParent(this._getSelectedElement(),"li")){A.stopEvent(G);}}}this._listFix(G);}this._fixListDupIds();this.fireEvent("editorKeyPress",{type:"editorKeyPress",target:this,ev:G});},_handleKeyDown:function(X){var Z=this.fireEvent("beforeEditorKeyDown",{type:"beforeEditorKeyDown",target:this,ev:X});if(Z===false){return false;}var U=null,E=null;if(this._isNonEditable(X)){return false;}this._setCurrentEvent(X);if(this.currentWindow){this.closeWindow();}if(this.currentWindow){this.closeWindow();}var N=false,S=null,P=null,R=false;switch(X.keyCode){case this._keyMap.FOCUS_TOOLBAR.key:if(this._checkKey(this._keyMap.FOCUS_TOOLBAR,X)){var W=this.toolbar.getElementsByTagName("h2")[0];if(W&&W.firstChild){W.firstChild.focus();}}else{if(this._checkKey(this._keyMap.FOCUS_AFTER,X)){this.afterElement.focus();}}A.stopEvent(X);N=false;break;case this._keyMap.CREATE_LINK.key:if(this._hasSelection()){if(this._checkKey(this._keyMap.CREATE_LINK,X)){var F=true;if(this.get("limitCommands")){if(!this.toolbar.getButtonByValue("createlink")){F=false;}}if(F){this.execCommand("createlink","");this.toolbar.fireEvent("createlinkClick",{type:"createlinkClick",target:this.toolbar});this.fireEvent("afterExecCommand",{type:"afterExecCommand",target:this});N=false;}}}break;case this._keyMap.UNDO.key:case this._keyMap.REDO.key:if(this._checkKey(this._keyMap.REDO,X)){S="redo";N=true;}else{if(this._checkKey(this._keyMap.UNDO,X)){S="undo";N=true;}}break;case this._keyMap.BOLD.key:if(this._checkKey(this._keyMap.BOLD,X)){S="bold";N=true;}break;case this._keyMap.FONT_SIZE_UP.key:case this._keyMap.FONT_SIZE_DOWN.key:var K=false,T=false;if(this._checkKey(this._keyMap.FONT_SIZE_UP,X)){K=true;}if(this._checkKey(this._keyMap.FONT_SIZE_DOWN,X)){T=true;}if(K||T){var H=this.toolbar.getButtonByValue("fontsize"),G=parseInt(H.get("label"),10),I=(G+1);if(T){I=(G-1);}S="fontsize";P=I+"px";N=true;}break;case this._keyMap.ITALIC.key:if(this._checkKey(this._keyMap.ITALIC,X)){S="italic";N=true;}break;case this._keyMap.UNDERLINE.key:if(this._checkKey(this._keyMap.UNDERLINE,X)){S="underline";N=true;}break;case 9:if(this.browser.ie){E=this._getRange();U=this._getSelectedElement();if(!this._isElement(U,"li")){if(E){E.pasteHTML("    "); E.collapse(false);E.select();}A.stopEvent(X);}}if(this.browser.gecko>1.8){U=this._getSelectedElement();if(this._isElement(U,"li")){if(X.shiftKey){this._getDoc().execCommand("outdent",null,"");}else{this._getDoc().execCommand("indent",null,"");}}else{if(!this._hasSelection()){this.execCommand("inserthtml","    ");}}A.stopEvent(X);}break;case 13:var M=null,V=0;if(this.get("ptags")&&!X.shiftKey){if(this.browser.gecko){U=this._getSelectedElement();if(!this._hasParent(U,"li")){if(this._hasParent(U,"p")){M=this._getDoc().createElement("p");M.innerHTML=" ";C.insertAfter(M,U);this._selectNode(M.firstChild);}else{if(this._isElement(U,"body")){this.execCommand("insertparagraph",null);var O=this._getDoc().body.getElementsByTagName("p");for(V=0;V');var L=this._getDoc().getElementById("yui-br"),Y=this._getDoc().createElement("br"),J=this._getDoc().createElement("span");L.parentNode.replaceChild(Y,L);J.className="yui-non";J.innerHTML=" ";C.insertAfter(J,Y);this._selectNode(J);}A.stopEvent(X);}}if(this.browser.ie){E=this._getRange();U=this._getSelectedElement();if(!this._isElement(U,"li")){if(E){E.pasteHTML("
                    ");E.collapse(false);E.select();}A.stopEvent(X);}}}break;}if(this.browser.ie){this._listFix(X);}if(N&&S){this.execCommand(S,P);A.stopEvent(X);this.nodeChange();}this._storeUndo();this.fireEvent("editorKeyDown",{type:"editorKeyDown",target:this,ev:X});},_fixListRunning:null,_fixListDupIds:function(){if(this._fixListRunning){return false;}if(this._getDoc()){this._fixListRunning=true;var E=this._getDoc().body.getElementsByTagName("li"),F=0,G={};for(F=0;F'+E+" ";}else{I.innerHTML='  ';}}}else{if(E){I.innerHTML=E+" ";}else{I.innerHTML=" ";}}I.parentNode.replaceChild(J,I);J.appendChild(I);if(this.browser.webkit){this._getSelection().setBaseAndExtent(I.firstChild,1,I.firstChild,I.firstChild.innerText.length);if(!this.browser.webkit3){I.parentNode.parentNode.style.display="list-item";setTimeout(function(){I.parentNode.parentNode.style.display="block";},1);}}else{if(this.browser.ie){G=this._getDoc().body.createTextRange();G.moveToElementText(I);G.collapse(false);G.select();}else{this._selectNode(I);}}A.stopEvent(K);}if(this.browser.webkit){A.stopEvent(K);}this.nodeChange();}},nodeChange:function(E){var F=this;this._storeUndo();if(this.get("nodeChangeDelay")){this._nodeChangeDelayTimer=window.setTimeout(function(){F._nodeChangeDelayTimer=null;F._nodeChange.apply(F,arguments);},0);}else{this._nodeChange();}},_nodeChange:function(F){var H=parseInt(this.get("nodeChangeThreshold"),10),O=Math.round(new Date().getTime()/1000),R=this;if(F===true){this._lastNodeChange=0;}if((this._lastNodeChange+H)0){for(var V=0;V'+Y+"");this._updateMenuChecked("fontname",Y);}if(L){L.set("label",L._configs.label._initialConfig.value);}var K=this.toolbar.getButtonByValue("heading");if(K){K.set("label",K._configs.label._initialConfig.value);this._updateMenuChecked("heading","none");}var I=this.toolbar.getButtonByValue("insertimage");if(I&&this.currentWindow&&(this.currentWindow.name=="insertimage")){this.toolbar.disableButton(I);}if(this._lastButton&&this._lastButton.isSelected){this.toolbar.deselectButton(this._lastButton.id);}this._undoNodeChange();}}this.fireEvent("afterNodeChange",{type:"afterNodeChange",target:this});},_updateMenuChecked:function(E,F,H){if(!H){H=this.toolbar;}var G=H.getButtonByValue(E);G.checkValue(F);},_handleToolbarClick:function(F){var H="";var I="";var G=F.button.value;if(F.button.menucmd){H=G;G=F.button.menucmd;}this._lastButton=F.button;if(this.STOP_EXEC_COMMAND){this.STOP_EXEC_COMMAND=false;return false;}else{this.execCommand(G,H);if(!this.browser.webkit){var E=this;setTimeout(function(){E.focus.call(E);},5);}}A.stopEvent(F);},_setupAfterElement:function(){if(!this.beforeElement){this.beforeElement=document.createElement("h2");this.beforeElement.className="yui-editor-skipheader";this.beforeElement.tabIndex="-1";this.beforeElement.innerHTML=this.STR_BEFORE_EDITOR;this.get("element_cont").get("firstChild").insertBefore(this.beforeElement,this.toolbar.get("nextSibling"));}if(!this.afterElement){this.afterElement=document.createElement("h2");this.afterElement.className="yui-editor-skipheader";this.afterElement.tabIndex="-1";this.afterElement.innerHTML=this.STR_LEAVE_EDITOR;this.get("element_cont").get("firstChild").appendChild(this.afterElement);}},_disableEditor:function(J){var I,H,G,E;if(!this.get("disabled_iframe")){I=this._createIframe();I.set("id","disabled_"+this.get("iframe").get("id"));I.setStyle("height","100%");I.setStyle("display","none");I.setStyle("visibility","visible");this.set("disabled_iframe",I);H=this.get("iframe").get("parentNode");H.appendChild(I.get("element"));}if(!I){I=this.get("disabled_iframe");}if(J){this._orgIframe=this.get("iframe");if(this.toolbar){this.toolbar.set("disabled",true);}G=this.getEditorHTML();E=this.get("iframe").get("offsetHeight");I.setStyle("visibility","");I.setStyle("position","");I.setStyle("top","");I.setStyle("left","");this._orgIframe.setStyle("visibility","hidden");this._orgIframe.setStyle("position","absolute");this._orgIframe.setStyle("top","-99999px");this._orgIframe.setStyle("left","-99999px");this.set("iframe",I);this._setInitialContent(true);if(!this._mask){this._mask=document.createElement("DIV");C.addClass(this._mask,"yui-editor-masked");if(this.browser.ie){this._mask.style.height=E+"px";}this.get("iframe").get("parentNode").appendChild(this._mask);}this.on("editorContentReloaded",function(){this._getDoc().body._rteLoaded=false;this.setEditorHTML(G);I.setStyle("display","block");this.unsubscribeAll("editorContentReloaded");});}else{if(this._mask){this._mask.parentNode.removeChild(this._mask);this._mask=null;if(this.toolbar){this.toolbar.set("disabled",false);}I.setStyle("visibility","hidden");I.setStyle("position","absolute");I.setStyle("top","-99999px");I.setStyle("left","-99999px");this._orgIframe.setStyle("visibility","");this._orgIframe.setStyle("position","");this._orgIframe.setStyle("top","");this._orgIframe.setStyle("left","");this.set("iframe",this._orgIframe);this.focus();var F=this;window.setTimeout(function(){F.nodeChange.call(F);},100);}}},SEP_DOMPATH:"<",STR_LEAVE_EDITOR:"You have left the Rich Text Editor.",STR_BEFORE_EDITOR:"This text field can contain stylized text and graphics. To cycle through all formatting options, use the keyboard shortcut Shift + Escape to place focus on the toolbar and navigate between options with your arrow keys. To exit this text editor use the Escape key and continue tabbing.

                    Common formatting keyboard shortcuts:

                    • Control Shift B sets text to bold
                    • Control Shift I sets text to italic
                    • Control Shift U underlines text
                    • Control Shift L adds an HTML link
                    ",STR_TITLE:"Rich Text Area.",STR_IMAGE_HERE:"Image URL Here",STR_IMAGE_URL:"Image URL",STR_LINK_URL:"Link URL",STOP_EXEC_COMMAND:false,STOP_NODE_CHANGE:false,CLASS_NOEDIT:"yui-noedit",CLASS_CONTAINER:"yui-editor-container",CLASS_EDITABLE:"yui-editor-editable",CLASS_EDITABLE_CONT:"yui-editor-editable-container",CLASS_PREFIX:"yui-editor",browser:function(){var E=YAHOO.env.ua; if(E.webkit>=420){E.webkit3=E.webkit;}else{E.webkit3=0;}if(E.webkit>=530){E.webkit4=E.webkit;}else{E.webkit4=0;}E.mac=false;if(navigator.userAgent.indexOf("Macintosh")!==-1){E.mac=true;}return E;}(),init:function(F,E){if(!this._defaultToolbar){this._defaultToolbar={collapse:true,titlebar:"Text Editing Tools",draggable:false,buttons:[{group:"fontstyle",label:"Font Name and Size",buttons:[{type:"select",label:"Arial",value:"fontname",disabled:true,menu:[{text:"Arial",checked:true},{text:"Arial Black"},{text:"Comic Sans MS"},{text:"Courier New"},{text:"Lucida Console"},{text:"Tahoma"},{text:"Times New Roman"},{text:"Trebuchet MS"},{text:"Verdana"}]},{type:"spin",label:"13",value:"fontsize",range:[9,75],disabled:true}]},{type:"separator"},{group:"textstyle",label:"Font Style",buttons:[{type:"push",label:"Bold CTRL + SHIFT + B",value:"bold"},{type:"push",label:"Italic CTRL + SHIFT + I",value:"italic"},{type:"push",label:"Underline CTRL + SHIFT + U",value:"underline"},{type:"push",label:"Strike Through",value:"strikethrough"},{type:"separator"},{type:"color",label:"Font Color",value:"forecolor",disabled:true},{type:"color",label:"Background Color",value:"backcolor",disabled:true}]},{type:"separator"},{group:"indentlist",label:"Lists",buttons:[{type:"push",label:"Create an Unordered List",value:"insertunorderedlist"},{type:"push",label:"Create an Ordered List",value:"insertorderedlist"}]},{type:"separator"},{group:"insertitem",label:"Insert Item",buttons:[{type:"push",label:"HTML Link CTRL + SHIFT + L",value:"createlink",disabled:true},{type:"push",label:"Insert Image",value:"insertimage"}]}]};}YAHOO.widget.SimpleEditor.superclass.init.call(this,F,E);YAHOO.widget.EditorInfo._instances[this.get("id")]=this;this.currentElement=[];this.on("contentReady",function(){this.DOMReady=true;this.fireQueue();},this,true);},initAttributes:function(E){YAHOO.widget.SimpleEditor.superclass.initAttributes.call(this,E);var F=this;this.setAttributeConfig("setDesignMode",{value:((E.setDesignMode===false)?false:true)});this.setAttributeConfig("nodeChangeDelay",{value:((E.nodeChangeDelay===false)?false:true)});this.setAttributeConfig("maxUndo",{writeOnce:true,value:E.maxUndo||30});this.setAttributeConfig("ptags",{writeOnce:true,value:E.ptags||false});this.setAttributeConfig("insert",{writeOnce:true,value:E.insert||false,method:function(K){if(K){var J={fontname:true,fontsize:true,forecolor:true,backcolor:true};var I=this._defaultToolbar.buttons;for(var H=0;H{TITLE}{CONTENT}',writeOnce:true});this.setAttributeConfig("extracss",{value:E.extracss||"",writeOnce:true});this.setAttributeConfig("handleSubmit",{value:E.handleSubmit||false,method:function(G){if(this.get("element").form){if(!this._formButtons){this._formButtons=[];}if(G){A.on(this.get("element").form,"submit",this._handleFormSubmit,this,true);var H=this.get("element").form.getElementsByTagName("input");for(var J=0;J=parseInt(this.get("height"),10))){var I=this.get("animate");this.set("animate",false);this.set("height",G+"px");this.set("animate",I);if(this.browser.ie){this.get("iframe").setStyle("height","99%");this.get("iframe").setStyle("zoom","1");var H=this;window.setTimeout(function(){H.get("iframe").setStyle("height","100%");},1);}}},_formButtons:null,_formButtonClicked:null,_handleFormButtonClick:function(F){var E=A.getTarget(F);this._formButtonClicked=E;},_handleFormSubmit:function(H){this.saveHTML();var G=this.get("element").form,E=this._formButtonClicked||false;A.removeListener(G,"submit",this._handleFormSubmit);if(YAHOO.env.ua.ie){if(E&&!E.disabled){E.click();}}else{if(E&&!E.disabled){E.click();}var F=document.createEvent("HTMLEvents");F.initEvent("submit",true,true);G.dispatchEvent(F);if(YAHOO.env.ua.webkit){if(YAHOO.lang.isFunction(G.submit)){G.submit();}}}},_handleFontSize:function(G){var E=this.toolbar.getButtonById(G.button.id);var F=E.get("label")+"px";this.execCommand("fontsize",F);return false;},_handleColorPicker:function(G){var F=G.button;var E="#"+G.color;if((F=="forecolor")||(F=="backcolor")){this.execCommand(F,E);}},_handleAlign:function(H){var G=null;for(var E=0;E'+H+"";if(J.get("label")!=N){J.set("label",N);this._updateMenuChecked("fontname",H);}}if(K){M=parseInt(C.getStyle(L,"fontSize"),10);if((M===null)||isNaN(M)){M=K._configs.label._initialConfig.value;}K.set("label",""+M);}if(!this._isElement(L,"body")&&!this._isElement(L,"img")){this.toolbar.enableButton(J);this.toolbar.enableButton(K);this.toolbar.enableButton("forecolor");this.toolbar.enableButton("backcolor");}if(this._isElement(L,"img")){if(YAHOO.widget.Overlay){this.toolbar.enableButton("createlink");}}if(this._hasParent(L,"blockquote")){this.toolbar.selectButton("indent");this.toolbar.disableButton("indent");this.toolbar.enableButton("outdent");}if(this._hasParent(L,"ol")||this._hasParent(L,"ul")){this.toolbar.disableButton("indent");}this._lastButton=null;},_handleInsertImageClick:function(){if(this.get("limitCommands")){if(!this.toolbar.getButtonByValue("insertimage")){return false; }}this.toolbar.set("disabled",true);var E=function(){var F=this.currentElement[0],H="http://";if(!F){F=this._getSelectedElement();}if(F){if(F.getAttribute("src")){H=F.getAttribute("src",2);if(H.indexOf(this.get("blankimage"))!=-1){H=this.STR_IMAGE_HERE;}}}var G=prompt(this.STR_IMAGE_URL+": ",H);if((G!=="")&&(G!==null)){F.setAttribute("src",G);}else{if(G===""){F.parentNode.removeChild(F);this.currentElement=[];this.nodeChange();}else{if((G===null)){H=F.getAttribute("src",2);if(H.indexOf(this.get("blankimage"))!=-1){F.parentNode.removeChild(F);this.currentElement=[];this.nodeChange();}}}}this.closeWindow();this.toolbar.set("disabled",false);this.unsubscribe("afterExecCommand",E,this,true);};this.on("afterExecCommand",E,this,true);},_handleInsertImageWindowClose:function(){this.nodeChange();},_isLocalFile:function(E){if((E)&&(E!=="")&&((E.indexOf("file:/")!=-1)||(E.indexOf(":\\")!=-1))){return true;}return false;},_handleCreateLinkClick:function(){if(this.get("limitCommands")){if(!this.toolbar.getButtonByValue("createlink")){return false;}}this.toolbar.set("disabled",true);var E=function(){var H=this.currentElement[0],G="";if(H){if(H.getAttribute("href",2)!==null){G=H.getAttribute("href",2);}}var J=prompt(this.STR_LINK_URL+": ",G);if((J!=="")&&(J!==null)){var I=J;if((I.indexOf(":/"+"/")==-1)&&(I.substring(0,1)!="/")&&(I.substring(0,6).toLowerCase()!="mailto")){if((I.indexOf("@")!=-1)&&(I.substring(0,6).toLowerCase()!="mailto")){I="mailto:"+I;}else{if(I.substring(0,1)!="#"){}}}H.setAttribute("href",I);}else{if(J!==null){var F=this._getDoc().createElement("span");F.innerHTML=H.innerHTML;C.addClass(F,"yui-non");H.parentNode.replaceChild(F,H);}}this.closeWindow();this.toolbar.set("disabled",false);this.unsubscribe("afterExecCommand",E,this,true);};this.on("afterExecCommand",E,this);},_handleCreateLinkWindowClose:function(){this.nodeChange();this.currentElement=[];},render:function(){if(this._rendered){return false;}if(!this.DOMReady){this._queue[this._queue.length]=["render",arguments];return false;}if(this.get("element")){if(this.get("element").tagName){this._textarea=true;if(this.get("element").tagName.toLowerCase()!=="textarea"){this._textarea=false;}}else{return false;}}else{return false;}this._rendered=true;var E=this;window.setTimeout(function(){E._render.call(E);},4);},_render:function(){var E=this;this.set("textarea",this.get("element"));this.get("element_cont").setStyle("display","none");this.get("element_cont").addClass(this.CLASS_CONTAINER);this.set("iframe",this._createIframe());window.setTimeout(function(){E._setInitialContent.call(E);},10);this.get("editor_wrapper").appendChild(this.get("iframe").get("element"));if(this.get("disabled")){this._disableEditor(true);}var F=this.get("toolbar");if(F instanceof B){this.toolbar=F;this.toolbar.set("disabled",true);}else{F.disabled=true;this.toolbar=new B(this.get("toolbar_cont"),F);}this.fireEvent("toolbarLoaded",{type:"toolbarLoaded",target:this.toolbar});this.toolbar.on("toolbarCollapsed",function(){if(this.currentWindow){this.moveWindow();}},this,true);this.toolbar.on("toolbarExpanded",function(){if(this.currentWindow){this.moveWindow();}},this,true);this.toolbar.on("fontsizeClick",this._handleFontSize,this,true);this.toolbar.on("colorPickerClicked",function(G){this._handleColorPicker(G);return false;},this,true);this.toolbar.on("alignClick",this._handleAlign,this,true);this.on("afterNodeChange",this._handleAfterNodeChange,this,true);this.toolbar.on("insertimageClick",this._handleInsertImageClick,this,true);this.on("windowinsertimageClose",this._handleInsertImageWindowClose,this,true);this.toolbar.on("createlinkClick",this._handleCreateLinkClick,this,true);this.on("windowcreatelinkClose",this._handleCreateLinkWindowClose,this,true);this.get("parentNode").replaceChild(this.get("element_cont").get("element"),this.get("element"));this.setStyle("visibility","hidden");this.setStyle("position","absolute");this.setStyle("top","-9999px");this.setStyle("left","-9999px");this.get("element_cont").appendChild(this.get("element"));this.get("element_cont").setStyle("display","block");C.addClass(this.get("iframe").get("parentNode"),this.CLASS_EDITABLE_CONT);this.get("iframe").addClass(this.CLASS_EDITABLE);this.get("element_cont").setStyle("width",this.get("width"));C.setStyle(this.get("iframe").get("parentNode"),"height",this.get("height"));this.get("iframe").setStyle("width","100%");this.get("iframe").setStyle("height","100%");this._setupDD();window.setTimeout(function(){E._setupAfterElement.call(E);},0);this.fireEvent("afterRender",{type:"afterRender",target:this});},execCommand:function(G,F){var J=this.fireEvent("beforeExecCommand",{type:"beforeExecCommand",target:this,args:arguments});if((J===false)||(this.STOP_EXEC_COMMAND)){this.STOP_EXEC_COMMAND=false;return false;}this._lastCommand=G;this._setMarkupType(G);if(this.browser.ie){this._getWindow().focus();}var E=true;if(this.get("limitCommands")){if(!this.toolbar.getButtonByValue(G)){E=false;}}this.editorDirty=true;if((typeof this["cmd_"+G.toLowerCase()]=="function")&&E){var I=this["cmd_"+G.toLowerCase()](F);E=I[0];if(I[1]){G=I[1];}if(I[2]){F=I[2];}}if(E){try{this._getDoc().execCommand(G,false,F);}catch(H){}}else{}this.on("afterExecCommand",function(){this.unsubscribeAll("afterExecCommand");this.nodeChange();},this,true);this.fireEvent("afterExecCommand",{type:"afterExecCommand",target:this});},cmd_bold:function(H){if(!this.browser.webkit){var G=this._getSelectedElement();if(G&&this._isElement(G,"span")&&this._hasSelection()){if(G.style.fontWeight=="bold"){G.style.fontWeight="";var E=this._getDoc().createElement("b"),F=G.parentNode;F.replaceChild(E,G);E.appendChild(G);}}}return[true];},cmd_italic:function(H){if(!this.browser.webkit){var G=this._getSelectedElement();if(G&&this._isElement(G,"span")&&this._hasSelection()){if(G.style.fontStyle=="italic"){G.style.fontStyle="";var E=this._getDoc().createElement("i"),F=G.parentNode;F.replaceChild(E,G);E.appendChild(G);}}}return[true];},cmd_underline:function(F){if(!this.browser.webkit){var E=this._getSelectedElement(); if(E&&this._isElement(E,"span")){if(E.style.textDecoration=="underline"){E.style.textDecoration="none";}else{E.style.textDecoration="underline";}return[false];}}return[true];},cmd_backcolor:function(H){var E=true,F=this._getSelectedElement(),G="backcolor";if(this.browser.gecko||this.browser.opera){this._setEditorStyle(true);G="hilitecolor";}if(!this._isElement(F,"body")&&!this._hasSelection()){F.style.backgroundColor=H;this._selectNode(F);E=false;}else{if(this.get("insert")){F=this._createInsertElement({backgroundColor:H});}else{this._createCurrentElement("span",{backgroundColor:H,color:F.style.color,fontSize:F.style.fontSize,fontFamily:F.style.fontFamily});this._selectNode(this.currentElement[0]);}E=false;}return[E,G];},cmd_forecolor:function(G){var E=true,F=this._getSelectedElement();if(!this._isElement(F,"body")&&!this._hasSelection()){C.setStyle(F,"color",G);this._selectNode(F);E=false;}else{if(this.get("insert")){F=this._createInsertElement({color:G});}else{this._createCurrentElement("span",{color:G,fontSize:F.style.fontSize,fontFamily:F.style.fontFamily,backgroundColor:F.style.backgroundColor});this._selectNode(this.currentElement[0]);}E=false;}return[E];},cmd_unlink:function(E){this._swapEl(this.currentElement[0],"span",function(F){F.className="yui-non";});return[false];},cmd_createlink:function(G){var F=this._getSelectedElement(),E=null;if(this._hasParent(F,"a")){this.currentElement[0]=this._hasParent(F,"a");}else{if(this._isElement(F,"li")){E=this._getDoc().createElement("a");E.innerHTML=F.innerHTML;F.innerHTML="";F.appendChild(E);this.currentElement[0]=E;}else{if(!this._isElement(F,"a")){this._createCurrentElement("a");E=this._swapEl(this.currentElement[0],"a");this.currentElement[0]=E;}else{this.currentElement[0]=F;}}}return[false];},cmd_insertimage:function(J){var E=true,F=null,I="insertimage",H=this._getSelectedElement();if(J===""){J=this.get("blankimage");}if(this._isElement(H,"img")){this.currentElement[0]=H;E=false;}else{if(this._getDoc().queryCommandEnabled(I)){this._getDoc().execCommand(I,false,J);var K=this._getDoc().getElementsByTagName("img");for(var G=0;G"+F[N].innerHTML+"";}Z.innerHTML=U;this.currentElement[0]=G;this.currentElement[0].parentNode.replaceChild(Z,this.currentElement[0]);}else{this._createCurrentElement(d.toLowerCase());Z=this._getDoc().createElement(d);for(N=0;N  ';Z.appendChild(K);if(N>0){this.currentElement[N].parentNode.removeChild(this.currentElement[N]);}}var T=((this.browser.opera)?"
                    ":"
                    "),S=Z.firstChild.innerHTML.split(T),Y,a;if(S.length>0){Z.innerHTML="";for(Y=0;Y";}var b=this._getDoc().createElement("span");b.innerHTML=U;G.parentNode.parentNode.replaceChild(b,G.parentNode);}else{this.nodeChange();this._getDoc().execCommand(W,"",G.parentNode);this.nodeChange();}V=false;}if(this.browser.opera){var R=this;window.setTimeout(function(){var e=R._getDoc().getElementsByTagName("li");for(var f=0;f"){e[f].parentNode.parentNode.removeChild(e[f].parentNode);}}},30);}if(this.browser.ie&&V){var L="";if(this._getRange().html){L="
                  • "+this._getRange().html+"
                  • ";}else{var M=this._getRange().text.split("\n");if(M.length>1){L="";for(var Q=0;Q"+M[Q]+"";}}else{var P=this._getRange().text;if(P===""){L='
                  • '+P+"
                  • ";}else{L="
                  • "+P+"
                  • ";}}}this._getRange().pasteHTML("<"+d+">"+L+"");var E=this._getDoc().getElementById("new_list_item");if(E){var O=this._getDoc().body.createTextRange(); O.moveToElementText(E);O.collapse(false);O.select();E.id="";}V=false;}}return V;},cmd_insertorderedlist:function(E){return[this.cmd_list("ol")];},cmd_insertunorderedlist:function(E){return[this.cmd_list("ul")];},cmd_fontname:function(H){var E=true,G=this._getSelectedElement();this.currentFont=H;if(G&&G.tagName&&!this._hasSelection()&&!this._isElement(G,"body")&&!this.get("insert")){YAHOO.util.Dom.setStyle(G,"font-family",H);E=false;}else{if(this.get("insert")&&!this._hasSelection()){var F=this._createInsertElement({fontFamily:H});E=false;}}return[E];},cmd_fontsize:function(H){var E=null,G=true;E=this._getSelectedElement();if(this.browser.webkit){if(this.currentElement[0]){if(E==this.currentElement[0]){G=false;YAHOO.util.Dom.setStyle(E,"fontSize",H);this._selectNode(E);this.currentElement[0]=E;}}}if(G){if(!this._isElement(this._getSelectedElement(),"body")&&(!this._hasSelection())){E=this._getSelectedElement();YAHOO.util.Dom.setStyle(E,"fontSize",H);if(this.get("insert")&&this.browser.ie){var F=this._getRange();F.collapse(false);F.select();}else{this._selectNode(E);}}else{if(this.currentElement&&(this.currentElement.length>0)&&(!this._hasSelection())&&(!this.get("insert"))){YAHOO.util.Dom.setStyle(this.currentElement,"fontSize",H);}else{if(this.get("insert")&&!this._hasSelection()){E=this._createInsertElement({fontSize:H});this.currentElement[0]=E;this._selectNode(this.currentElement[0]);}else{this._createCurrentElement("span",{"fontSize":H,fontFamily:E.style.fontFamily,color:E.style.color,backgroundColor:E.style.backgroundColor});this._selectNode(this.currentElement[0]);}}}}return[false];},_swapEl:function(F,E,H){var G=this._getDoc().createElement(E);if(F){G.innerHTML=F.innerHTML;}if(typeof H=="function"){H.call(this,G);}if(F){F.parentNode.replaceChild(G,F);}return G;},_createInsertElement:function(E){this._createCurrentElement("span",E);var F=this.currentElement[0];if(this.browser.webkit){F.innerHTML=' ';F=F.firstChild;this._getSelection().setBaseAndExtent(F,1,F,F.innerText.length);}else{if(this.browser.ie||this.browser.opera){F.innerHTML=" ";}}this.focus();this._selectNode(F,true);return F;},_createCurrentElement:function(G,J){G=((G)?G:"a");var R=null,F=[],H=this._getDoc();if(this.currentFont){if(!J){J={};}J.fontFamily=this.currentFont;this.currentFont=null;}this.currentElement=[];var M=function(X,Z){var Y=null;X=((X)?X:"span");X=X.toLowerCase();switch(X){case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":Y=H.createElement(X);break;default:Y=H.createElement(X);if(X==="span"){YAHOO.util.Dom.addClass(Y,"yui-tag-"+X);YAHOO.util.Dom.addClass(Y,"yui-tag");Y.setAttribute("tag",X);}for(var W in Z){if(YAHOO.lang.hasOwnProperty(Z,W)){Y.style[W]=Z[W];}}break;}return Y;};if(!this._hasSelection()){if(this._getDoc().queryCommandEnabled("insertimage")){this._getDoc().execCommand("insertimage",false,"yui-tmp-img");var L=this._getDoc().getElementsByTagName("img");for(var Q=0;Q]*)>/gi,"");E=E.replace(/<\/strong>/gi,"
                    ");E=E.replace(/]*)>/gi,"");E=E.replace(/<\/embed>/gi,"");E=E.replace(/]*)>/gi,"");E=E.replace(/<\/em>/gi,"
                    ");E=E.replace(/_moz_dirty=""/gi,"");E=E.replace(/]*)>/gi,"");E=E.replace(/<\/YUI_EMBED>/gi,"");if(this.get("plainText")){E=E.replace(/\n/g,"
                    ").replace(/\r/g,"
                    ");E=E.replace(/ /gi,"  ");E=E.replace(/\t/gi,"    ");}E=E.replace(/]*)>/gi,"");E=E.replace(/<\/script([^>]*)>/gi,"");E=E.replace(/<script([^>]*)>/gi,"");E=E.replace(/<\/script([^>]*)>/gi,"");E=E.replace(/\r\n/g,"").replace(/\n/g,"").replace(/\r/g,"");E=E.replace(new RegExp("]*)>(.*?)","gi"),"");E=E.replace(//g,"\n");return E;},cleanHTML:function(H){if(!H){H=this.getEditorHTML();}var F=this.get("markup");H=this.pre_filter_linebreaks(H,F);H=this.filter_msword(H);H=H.replace(/]*)\/>/gi,"");H=H.replace(/]*)>/gi,"");H=H.replace(/]*)\/>/gi,"");H=H.replace(/]*)>/gi,"");H=H.replace(/]*)>/gi,"");H=H.replace(/<\/ul>/gi,"");H=H.replace(/]*)>/gi,"");H=H.replace(/<\/blockquote>/gi,"");H=H.replace(/]*)>/gi,"");H=H.replace(/<\/embed>/gi,"");if((F=="semantic")||(F=="xhtml")){H=H.replace(/]*)>/gi,"");H=H.replace(/<\/i>/gi,"");H=H.replace(/]*)>/gi,"");H=H.replace(/<\/b>/gi,"");}H=H.replace(/_moz_dirty=""/gi,"");H=H.replace(//gi,"/span>");if(this.browser.ie){H=H.replace(/text-decoration/gi,"text-decoration");H=H.replace(/font-weight/gi,"font-weight");H=H.replace(/_width="([^>]*)"/gi,"");H=H.replace(/_height="([^>]*)"/gi,"");var G=this._baseHREF.replace(/\//gi,"\\/"),I=new RegExp('src="'+G,"gi");H=H.replace(I,'src="');}H=H.replace(//gi,"");H=H.replace(//gi,"");if((F=="semantic")||(F=="xhtml")||(F=="css")){H=H.replace(new RegExp(']*)face="([^>]*)">(.*?)',"gi"),'$3');H=H.replace(/([^>]*)',"gi"),"$1");H=H.replace(new RegExp('([^>]*)',"gi"),"$1");}H=H.replace(/\/u>/gi,"/span>");if(F=="css"){H=H.replace(/]*)>/gi,"");H=H.replace(/<\/em>/gi,"");H=H.replace(/]*)>/gi,"");H=H.replace(/<\/strong>/gi,"");H=H.replace(//gi,"/span>");H=H.replace(//gi,"/span>");}H=H.replace(/ /gi," ");}else{H=H.replace(//gi,"/u>");}H=H.replace(/]*)>/gi,"");H=H.replace(/\/ol>/gi,"/ol>");H=H.replace(/
                  • /gi,"/li>");H=this.filter_safari(H);H=this.filter_internals(H);H=this.filter_all_rgb(H);H=this.post_filter_linebreaks(H,F);if(F=="xhtml"){H=H.replace(/]*)>/g,"");H=H.replace(/]*)>/g,"");}else{H=H.replace(/]*)>/g,"");H=H.replace(/]*)>/g,"");}H=H.replace(/]*)>/g,"");H=H.replace(/<\/YUI_UL>/g,"
                  ");H=this.filter_invalid_lists(H);H=H.replace(/]*)>/g,"");H=H.replace(/<\/YUI_BQ>/g,"");H=H.replace(/]*)>/g,"");H=H.replace(/<\/YUI_EMBED>/g,"");H=H.replace(/ & /gi," YUI_AMP ");H=H.replace(/ &/gi," YUI_AMP_F ");H=H.replace(/& /gi," YUI_AMP_R ");H=H.replace(/&/gi,"&");H=H.replace(/ YUI_AMP /gi," & ");H=H.replace(/ YUI_AMP_F /gi," &");H=H.replace(/ YUI_AMP_R /gi,"& ");H=YAHOO.lang.trim(H);if(this.get("removeLineBreaks")){H=H.replace(/\n/g,"").replace(/\r/g,"");H=H.replace(/ /gi," ");}for(var E in this.invalidHTML){if(YAHOO.lang.hasOwnProperty(this.invalidHTML,E)){if(D.isObject(E)&&E.keepContents){H=H.replace(new RegExp("<"+E+"([^>]*)>(.*?)","gi"),"$1");}else{H=H.replace(new RegExp("<"+E+"([^>]*)>(.*?)","gi"),"");}}}this.fireEvent("cleanHTML",{type:"cleanHTML",target:this,html:H});return H;},filter_msword:function(E){if(!this.get("filterWord")){return E;}E=E.replace(/\s*<\/o:p>/g,"");E=E.replace(/[\s\S]*?<\/o:p>/g," ");E=E.replace(/]*>[\s\S]*?<\/w:[^>]*>/gi,"");E=E.replace(/\s*mso-[^:]+:[^;"]+;?/gi,"");E=E.replace(/\s*MARGIN: 0cm 0cm 0pt\s*;/gi,"");E=E.replace(/\s*MARGIN: 0cm 0cm 0pt\s*"/gi,'"');E=E.replace(/\s*TEXT-INDENT: 0cm\s*;/gi,"");E=E.replace(/\s*TEXT-INDENT: 0cm\s*"/gi,'"');E=E.replace(/\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi,'"'); E=E.replace(/\s*FONT-VARIANT: [^\s;]+;?"/gi,'"');E=E.replace(/\s*tab-stops:[^;"]*;?/gi,"");E=E.replace(/\s*tab-stops:[^"]*/gi,"");E=E.replace(/<\\?\?xml[^>]*>/gi,"");E=E.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi,"<$1$3");E=E.replace(/<(\w[^>]*) language=([^ |>]*)([^>]*)/gi,"<$1$3");E=E.replace(/<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi,"<$1$3");E=E.replace(/<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi,"<$1$3");return E;},filter_invalid_lists:function(E){E=E.replace(/<\/li>\n/gi,"");E=E.replace(/<\/li>
                    /gi,"
                    1. ");E=E.replace(/<\/ol>/gi,"
                  1. ");E=E.replace(/<\/ol><\/li>\n/gi,"
                  ");E=E.replace(/<\/li>
                    /gi,"
                    • ");E=E.replace(/<\/ul>/gi,"
                  • ");E=E.replace(/<\/ul><\/li>\n?/gi,"
                  ");E=E.replace(/<\/li>/gi,"");E=E.replace(/<\/ol>/gi,"
              ");E=E.replace(/
                /gi,"
                  ");E=E.replace(/
                    /gi,"
                      ");return E;},filter_safari:function(E){if(this.browser.webkit){E=E.replace(/([^>])<\/span>/gi,"    ");E=E.replace(/Apple-style-span/gi,"");E=E.replace(/style="line-height: normal;"/gi,"");E=E.replace(/yui-wk-div/gi,"");E=E.replace(/yui-wk-p/gi,"");E=E.replace(/
                    • <\/li>/gi,"");E=E.replace(/
                    • <\/li>/gi,"");E=E.replace(/
                    • <\/li>/gi,"");if(this.get("ptags")){E=E.replace(/]*)>/g,"");E=E.replace(/<\/div>/gi,"

                      ");}else{E=E.replace(/]*)>([ tnr]*)<\/div>/gi,"
                      ");E=E.replace(/<\/div>/gi,"");}}return E;},filter_internals:function(E){E=E.replace(/\r/g,"");E=E.replace(/<\/?(body|head|html)[^>]*>/gi,"");E=E.replace(/<\/li>/gi,"
                    • ");E=E.replace(/yui-tag-span/gi,"");E=E.replace(/yui-tag/gi,"");E=E.replace(/yui-non/gi,"");E=E.replace(/yui-img/gi,"");E=E.replace(/ tag="span"/gi,"");E=E.replace(/ class=""/gi,"");E=E.replace(/ style=""/gi,"");E=E.replace(/ class=" "/gi,"");E=E.replace(/ class=" "/gi,"");E=E.replace(/ target=""/gi,"");E=E.replace(/ title=""/gi,"");if(this.browser.ie){E=E.replace(/ class= /gi,"");E=E.replace(/ class= >/gi,"");}return E;},filter_all_rgb:function(I){var H=new RegExp("rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)","gi");var E=I.match(H);if(D.isArray(E)){for(var G=0;G/gi,"");F=F.replace(/
                      /gi,"");}F=F.replace(/
                      /gi,"");F=F.replace(/
                      /gi,"");F=F.replace(//gi,"");F=F.replace(/
                      /gi,"");F=F.replace(/
                      <\/div>/gi,"");F=F.replace(/

                      ( | )<\/p>/g,"");F=F.replace(/


                       <\/p>/gi,"");F=F.replace(/

                       <\/p>/gi,"");F=F.replace(/$/,"");F=F.replace(/<\/p>/g,"

                      ");if(this.browser.ie){F=F.replace(/    /g,"\t");}return F;},post_filter_linebreaks:function(F,E){if(E=="xhtml"){F=F.replace(//g,"
                      ");}else{F=F.replace(//g,"
                      ");}return F;},clearEditorDoc:function(){this._getDoc().body.innerHTML=" ";},openWindow:function(E){},moveWindow:function(){},_closeWindow:function(){},closeWindow:function(){this.toolbar.resetAllButtons();this.focus();},destroy:function(){if(this._nodeChangeDelayTimer){clearTimeout(this._nodeChangeDelayTimer);}this.hide();if(this.resize){this.resize.destroy();}if(this.dd){this.dd.unreg();}if(this.get("panel")){this.get("panel").destroy();}this.saveHTML();this.toolbar.destroy();this.setStyle("visibility","visible");this.setStyle("position","static");this.setStyle("top","");this.setStyle("left","");var E=this.get("element");this.get("element_cont").get("parentNode").replaceChild(E,this.get("element_cont").get("element"));this.get("element_cont").get("element").innerHTML="";this.set("handleSubmit",false);return true;},toString:function(){var E="SimpleEditor";if(this.get&&this.get("element_cont")){E="SimpleEditor (#"+this.get("element_cont").get("id")+")"+((this.get("disabled")?" Disabled":""));}return E;}});YAHOO.widget.EditorInfo={_instances:{},blankImage:"",window:{},panel:null,getEditorById:function(E){if(!YAHOO.lang.isString(E)){E=E.id;}if(this._instances[E]){return this._instances[E];}return false;},saveAll:function(G){var F,H,E=YAHOO.widget.EditorInfo._instances;if(G){for(F in E){if(D.hasOwnProperty(E,F)){H=E[F];if(H.get("element").form&&(H.get("element").form==G)){H.saveHTML();}}}}else{for(F in E){if(D.hasOwnProperty(E,F)){E[F].saveHTML();}}}},toString:function(){var E=0;for(var F in this._instances){if(D.hasOwnProperty(this._instances,F)){E++;}}return"Editor Info ("+E+" registered intance"+((E>1)?"s":"")+")";}};})();YAHOO.register("simpleeditor",YAHOO.widget.SimpleEditor,{version:"2.9.0",build:"2800"}); }, '2.9.0' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-skin-sam-simpleeditor", "yui2-event", "yui2-element"], "optional": ["yui2-containercore", "yui2-dragdrop", "yui2-skin-sam-button", "yui2-skin-sam-menu", "yui2-menu", "yui2-button", "yui2-animation"]}); PK\9Pf]]/2in3/2.9.0/build/yui2-treeview/yui2-treeview.jsnu[YUI.add('yui2-treeview', function(Y) { var YAHOO = Y.YUI2; /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ (function () { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, Widget = YAHOO.widget; /** * The treeview widget is a generic tree building tool. * @module treeview * @title TreeView Widget * @requires yahoo, dom, event * @optional animation, json, calendar * @namespace YAHOO.widget */ /** * Contains the tree view state data and the root node. * * @class TreeView * @uses YAHOO.util.EventProvider * @constructor * @param {string|HTMLElement} id The id of the element, or the element itself that the tree will be inserted into. * Existing markup in this element, if valid, will be used to build the tree * @param {Array|Object|String} oConfig (optional) If present, it will be used to build the tree via method buildTreeFromObject * */ YAHOO.widget.TreeView = function(id, oConfig) { if (id) { this.init(id); } if (oConfig) { this.buildTreeFromObject(oConfig); } else if (Lang.trim(this._el.innerHTML)) { this.buildTreeFromMarkup(id); } }; var TV = Widget.TreeView; TV.prototype = { /** * The id of tree container element * @property id * @type String */ id: null, /** * The host element for this tree * @property _el * @private * @type HTMLelement */ _el: null, /** * Flat collection of all nodes in this tree. This is a sparse * array, so the length property can't be relied upon for a * node count for the tree. * @property _nodes * @type Node[] * @private */ _nodes: null, /** * We lock the tree control while waiting for the dynamic loader to return * @property locked * @type boolean */ locked: false, /** * The animation to use for expanding children, if any * @property _expandAnim * @type string * @private */ _expandAnim: null, /** * The animation to use for collapsing children, if any * @property _collapseAnim * @type string * @private */ _collapseAnim: null, /** * The current number of animations that are executing * @property _animCount * @type int * @private */ _animCount: 0, /** * The maximum number of animations to run at one time. * @property maxAnim * @type int */ maxAnim: 2, /** * Whether there is any subscriber to dblClickEvent * @property _hasDblClickSubscriber * @type boolean * @private */ _hasDblClickSubscriber: false, /** * Stores the timer used to check for double clicks * @property _dblClickTimer * @type window.timer object * @private */ _dblClickTimer: null, /** * A reference to the Node currently having the focus or null if none. * @property currentFocus * @type YAHOO.widget.Node */ currentFocus: null, /** * If true, only one Node can be highlighted at a time * @property singleNodeHighlight * @type boolean * @default false */ singleNodeHighlight: false, /** * A reference to the Node that is currently highlighted. * It is only meaningful if singleNodeHighlight is enabled * @property _currentlyHighlighted * @type YAHOO.widget.Node * @default null * @private */ _currentlyHighlighted: null, /** * Sets up the animation for expanding children * @method setExpandAnim * @param {string} type the type of animation (acceptable values defined * in YAHOO.widget.TVAnim) */ setExpandAnim: function(type) { this._expandAnim = (Widget.TVAnim.isValid(type)) ? type : null; }, /** * Sets up the animation for collapsing children * @method setCollapseAnim * @param {string} type of animation (acceptable values defined in * YAHOO.widget.TVAnim) */ setCollapseAnim: function(type) { this._collapseAnim = (Widget.TVAnim.isValid(type)) ? type : null; }, /** * Perform the expand animation if configured, or just show the * element if not configured or too many animations are in progress * @method animateExpand * @param el {HTMLElement} the element to animate * @param node {YAHOO.util.Node} the node that was expanded * @return {boolean} true if animation could be invoked, false otherwise */ animateExpand: function(el, node) { if (this._expandAnim && this._animCount < this.maxAnim) { // this.locked = true; var tree = this; var a = Widget.TVAnim.getAnim(this._expandAnim, el, function() { tree.expandComplete(node); }); if (a) { ++this._animCount; this.fireEvent("animStart", { "node": node, "type": "expand" }); a.animate(); } return true; } return false; }, /** * Perform the collapse animation if configured, or just show the * element if not configured or too many animations are in progress * @method animateCollapse * @param el {HTMLElement} the element to animate * @param node {YAHOO.util.Node} the node that was expanded * @return {boolean} true if animation could be invoked, false otherwise */ animateCollapse: function(el, node) { if (this._collapseAnim && this._animCount < this.maxAnim) { // this.locked = true; var tree = this; var a = Widget.TVAnim.getAnim(this._collapseAnim, el, function() { tree.collapseComplete(node); }); if (a) { ++this._animCount; this.fireEvent("animStart", { "node": node, "type": "collapse" }); a.animate(); } return true; } return false; }, /** * Function executed when the expand animation completes * @method expandComplete */ expandComplete: function(node) { --this._animCount; this.fireEvent("animComplete", { "node": node, "type": "expand" }); // this.locked = false; }, /** * Function executed when the collapse animation completes * @method collapseComplete */ collapseComplete: function(node) { --this._animCount; this.fireEvent("animComplete", { "node": node, "type": "collapse" }); // this.locked = false; }, /** * Initializes the tree * @method init * @parm {string|HTMLElement} id the id of the element that will hold the tree * @private */ init: function(id) { this._el = Dom.get(id); this.id = Dom.generateId(this._el,"yui-tv-auto-id-"); /** * When animation is enabled, this event fires when the animation * starts * @event animStart * @type CustomEvent * @param {YAHOO.widget.Node} oArgs.node the node that is expanding/collapsing * @param {String} oArgs.type the type of animation ("expand" or "collapse") */ this.createEvent("animStart", this); /** * When animation is enabled, this event fires when the animation * completes * @event animComplete * @type CustomEvent * @param {YAHOO.widget.Node} oArgs.node the node that is expanding/collapsing * @param {String} oArgs.type the type of animation ("expand" or "collapse") */ this.createEvent("animComplete", this); /** * Fires when a node is going to be collapsed. Return false to stop * the collapse. * @event collapse * @type CustomEvent * @param {YAHOO.widget.Node} node the node that is collapsing */ this.createEvent("collapse", this); /** * Fires after a node is successfully collapsed. This event will not fire * if the "collapse" event was cancelled. * @event collapseComplete * @type CustomEvent * @param {YAHOO.widget.Node} node the node that was collapsed */ this.createEvent("collapseComplete", this); /** * Fires when a node is going to be expanded. Return false to stop * the collapse. * @event expand * @type CustomEvent * @param {YAHOO.widget.Node} node the node that is expanding */ this.createEvent("expand", this); /** * Fires after a node is successfully expanded. This event will not fire * if the "expand" event was cancelled. * @event expandComplete * @type CustomEvent * @param {YAHOO.widget.Node} node the node that was expanded */ this.createEvent("expandComplete", this); /** * Fires when the Enter key is pressed on a node that has the focus * @event enterKeyPressed * @type CustomEvent * @param {YAHOO.widget.Node} node the node that has the focus */ this.createEvent("enterKeyPressed", this); /** * Fires when the label in a TextNode or MenuNode or content in an HTMLNode receives a Click. * The listener may return false to cancel toggling and focusing on the node. * @event clickEvent * @type CustomEvent * @param oArgs.event {HTMLEvent} The event object * @param oArgs.node {YAHOO.widget.Node} node the node that was clicked */ this.createEvent("clickEvent", this); /** * Fires when the focus receives the focus, when it changes from a Node * to another Node or when it is completely lost (blurred) * @event focusChanged * @type CustomEvent * @param oArgs.oldNode {YAHOO.widget.Node} Node that had the focus or null if none * @param oArgs.newNode {YAHOO.widget.Node} Node that receives the focus or null if none */ this.createEvent('focusChanged',this); /** * Fires when the label in a TextNode or MenuNode or content in an HTMLNode receives a double Click * @event dblClickEvent * @type CustomEvent * @param oArgs.event {HTMLEvent} The event object * @param oArgs.node {YAHOO.widget.Node} node the node that was clicked */ var self = this; this.createEvent("dblClickEvent", { scope:this, onSubscribeCallback: function() { self._hasDblClickSubscriber = true; } }); /** * Custom event that is fired when the text node label is clicked. * The node clicked is provided as an argument * * @event labelClick * @type CustomEvent * @param {YAHOO.widget.Node} node the node clicked * @deprecated use clickEvent or dblClickEvent */ this.createEvent("labelClick", this); /** * Custom event fired when the highlight of a node changes. * The node that triggered the change is provided as an argument: * The status of the highlight can be checked in * nodeRef.highlightState. * Depending on nodeRef.propagateHighlight, other nodes might have changed * @event highlightEvent * @type CustomEvent * @param node {YAHOO.widget.Node} the node that started the change in highlighting state */ this.createEvent("highlightEvent",this); this._nodes = []; // store a global reference TV.trees[this.id] = this; // Set up the root node this.root = new Widget.RootNode(this); var LW = Widget.LogWriter; if (this._initEditor) { this._initEditor(); } // YAHOO.util.Event.onContentReady(this.id, this.handleAvailable, this, true); // YAHOO.util.Event.on(this.id, "click", this.handleClick, this, true); }, //handleAvailable: function() { //var Event = YAHOO.util.Event; //Event.on(this.id, //}, /** * Builds the TreeView from an object. * This is the method called by the constructor to build the tree when it has a second argument. * A tree can be described by an array of objects, each object corresponding to a node. * Node descriptions may contain values for any property of a node plus the following extra properties:
                        *
                      • type: can be one of the following:
                          *
                        • A shortname for a node type ('text','menu','html')
                        • *
                        • The name of a Node class under YAHOO.widget ('TextNode', 'MenuNode', 'DateNode', etc)
                        • *
                        • a reference to an actual class: YAHOO.widget.DateNode
                        • *
                      • *
                      • children: an array containing further node definitions
                      * A string instead of an object will produce a node of type 'text' with the given string as its label. * @method buildTreeFromObject * @param oConfig {Array|Object|String} array containing a full description of the tree. * An object or a string will be turned into an array with the given object or string as its only element. * */ buildTreeFromObject: function (oConfig) { var build = function (parent, oConfig) { var i, item, node, children, type, NodeType, ThisType; for (i = 0; i < oConfig.length; i++) { item = oConfig[i]; if (Lang.isString(item)) { node = new Widget.TextNode(item, parent); } else if (Lang.isObject(item)) { children = item.children; delete item.children; type = item.type || 'text'; delete item.type; switch (Lang.isString(type) && type.toLowerCase()) { case 'text': node = new Widget.TextNode(item, parent); break; case 'menu': node = new Widget.MenuNode(item, parent); break; case 'html': node = new Widget.HTMLNode(item, parent); break; default: if (Lang.isString(type)) { NodeType = Widget[type]; } else { NodeType = type; } if (Lang.isObject(NodeType)) { for (ThisType = NodeType; ThisType && ThisType !== Widget.Node; ThisType = ThisType.superclass.constructor) {} if (ThisType) { node = new NodeType(item, parent); } else { } } else { } } if (children) { build(node,children); } } else { } } }; if (!Lang.isArray(oConfig)) { oConfig = [oConfig]; } build(this.root,oConfig); }, /** * Builds the TreeView from existing markup. Markup should consist of <UL> or <OL> elements containing <LI> elements. * Each <LI> can have one element used as label and a second optional element which is to be a <UL> or <OL> * containing nested nodes. * Depending on what the first element of the <LI> element is, the following Nodes will be created:
                        *
                      • plain text: a regular TextNode
                      • *
                      • anchor <A>: a TextNode with its href and target taken from the anchor
                      • *
                      • anything else: an HTMLNode
                      * Only the first outermost (un-)ordered list in the markup and its children will be parsed. * Nodes will be collapsed unless an <LI> tag has a className called 'expanded'. * All other className attributes will be copied over to the Node className property. * If the <LI> element contains an attribute called yuiConfig, its contents should be a JSON-encoded object * as the one used in method buildTreeFromObject. * @method buildTreeFromMarkup * @param id {string|HTMLElement} The id of the element that contains the markup or a reference to it. */ buildTreeFromMarkup: function (id) { var build = function (markup) { var el, child, branch = [], config = {}, label, yuiConfig; // Dom's getFirstChild and getNextSibling skip over text elements for (el = Dom.getFirstChild(markup); el; el = Dom.getNextSibling(el)) { switch (el.tagName.toUpperCase()) { case 'LI': label = ''; config = { expanded: Dom.hasClass(el,'expanded'), title: el.title || el.alt || null, className: Lang.trim(el.className.replace(/\bexpanded\b/,'')) || null }; // I cannot skip over text elements here because I want them for labels child = el.firstChild; if (child.nodeType == 3) { // nodes with only whitespace, tabs and new lines don't count, they are probably just formatting. label = Lang.trim(child.nodeValue.replace(/[\n\t\r]*/g,'')); if (label) { config.type = 'text'; config.label = label; } else { child = Dom.getNextSibling(child); } } if (!label) { if (child.tagName.toUpperCase() == 'A') { config.type = 'text'; config.label = child.innerHTML; config.href = child.href; config.target = child.target; config.title = child.title || child.alt || config.title; } else { config.type = 'html'; var d = document.createElement('div'); d.appendChild(child.cloneNode(true)); config.html = d.innerHTML; config.hasIcon = true; } } // see if after the label it has a further list which will become children of this node. child = Dom.getNextSibling(child); switch (child && child.tagName.toUpperCase()) { case 'UL': case 'OL': config.children = build(child); break; } // if there are further elements or text, it will be ignored. if (YAHOO.lang.JSON) { yuiConfig = el.getAttribute('yuiConfig'); if (yuiConfig) { yuiConfig = YAHOO.lang.JSON.parse(yuiConfig); config = YAHOO.lang.merge(config,yuiConfig); } } branch.push(config); break; case 'UL': case 'OL': config = { type: 'text', label: '', children: build(child) }; branch.push(config); break; } } return branch; }; var markup = Dom.getChildrenBy(Dom.get(id),function (el) { var tag = el.tagName.toUpperCase(); return tag == 'UL' || tag == 'OL'; }); if (markup.length) { this.buildTreeFromObject(build(markup[0])); } else { } }, /** * Returns the TD element where the event has occurred * @method _getEventTargetTdEl * @private */ _getEventTargetTdEl: function (ev) { var target = Event.getTarget(ev); // go up looking for a TD with a className with a ygtv prefix while (target && !(target.tagName.toUpperCase() == 'TD' && Dom.hasClass(target.parentNode,'ygtvrow'))) { target = Dom.getAncestorByTagName(target,'td'); } if (Lang.isNull(target)) { return null; } // If it is a spacer cell, do nothing if (/\bygtv(blank)?depthcell/.test(target.className)) { return null;} // If it has an id, search for the node number and see if it belongs to a node in this tree. if (target.id) { var m = target.id.match(/\bygtv([^\d]*)(.*)/); if (m && m[2] && this._nodes[m[2]]) { return target; } } return null; }, /** * Event listener for click events * @method _onClickEvent * @private */ _onClickEvent: function (ev) { var self = this, td = this._getEventTargetTdEl(ev), node, target, toggle = function (force) { node.focus(); if (force || !node.href) { node.toggle(); try { Event.preventDefault(ev); } catch (e) { // @TODO // For some reason IE8 is providing an event object with // most of the fields missing, but only when clicking on // the node's label, and only when working with inline // editing. This generates a "Member not found" error // in that browser. Determine if this is a browser // bug, or a problem with this code. Already checked to // see if the problem has to do with access the event // in the outer scope, and that isn't the problem. // Maybe the markup for inline editing is broken. } } }; if (!td) { return; } node = this.getNodeByElement(td); if (!node) { return; } // exception to handle deprecated event labelClick // @TODO take another look at this deprecation. It is common for people to // only be interested in the label click, so why make them have to test // the node type to figure out whether the click was on the label? target = Event.getTarget(ev); if (Dom.hasClass(target, node.labelStyle) || Dom.getAncestorByClassName(target,node.labelStyle)) { this.fireEvent('labelClick',node); } // http://yuilibrary.com/projects/yui2/ticket/2528946 // Ensures that any open editor is closed. // Since the editor is in a separate source which might not be included, // we first need to ensure we have the _closeEditor method available if (this._closeEditor) { this._closeEditor(false); } // If it is a toggle cell, toggle if (/\bygtv[tl][mp]h?h?/.test(td.className)) { toggle(true); } else { if (this._dblClickTimer) { window.clearTimeout(this._dblClickTimer); this._dblClickTimer = null; } else { if (this._hasDblClickSubscriber) { this._dblClickTimer = window.setTimeout(function () { self._dblClickTimer = null; if (self.fireEvent('clickEvent', {event:ev,node:node}) !== false) { toggle(); } }, 200); } else { if (self.fireEvent('clickEvent', {event:ev,node:node}) !== false) { toggle(); } } } } }, /** * Event listener for double-click events * @method _onDblClickEvent * @private */ _onDblClickEvent: function (ev) { if (!this._hasDblClickSubscriber) { return; } var td = this._getEventTargetTdEl(ev); if (!td) {return;} if (!(/\bygtv[tl][mp]h?h?/.test(td.className))) { this.fireEvent('dblClickEvent', {event:ev, node:this.getNodeByElement(td)}); if (this._dblClickTimer) { window.clearTimeout(this._dblClickTimer); this._dblClickTimer = null; } } }, /** * Event listener for mouse over events * @method _onMouseOverEvent * @private */ _onMouseOverEvent:function (ev) { var target; if ((target = this._getEventTargetTdEl(ev)) && (target = this.getNodeByElement(target)) && (target = target.getToggleEl())) { target.className = target.className.replace(/\bygtv([lt])([mp])\b/gi,'ygtv$1$2h'); } }, /** * Event listener for mouse out events * @method _onMouseOutEvent * @private */ _onMouseOutEvent: function (ev) { var target; if ((target = this._getEventTargetTdEl(ev)) && (target = this.getNodeByElement(target)) && (target = target.getToggleEl())) { target.className = target.className.replace(/\bygtv([lt])([mp])h\b/gi,'ygtv$1$2'); } }, /** * Event listener for key down events * @method _onKeyDownEvent * @private */ _onKeyDownEvent: function (ev) { var target = Event.getTarget(ev), node = this.getNodeByElement(target), newNode = node, KEY = YAHOO.util.KeyListener.KEY; switch(ev.keyCode) { case KEY.UP: do { if (newNode.previousSibling) { newNode = newNode.previousSibling; } else { newNode = newNode.parent; } } while (newNode && !newNode._canHaveFocus()); if (newNode) { newNode.focus(); } Event.preventDefault(ev); break; case KEY.DOWN: do { if (newNode.nextSibling) { newNode = newNode.nextSibling; } else { newNode.expand(); newNode = (newNode.children.length || null) && newNode.children[0]; } } while (newNode && !newNode._canHaveFocus); if (newNode) { newNode.focus();} Event.preventDefault(ev); break; case KEY.LEFT: do { if (newNode.parent) { newNode = newNode.parent; } else { newNode = newNode.previousSibling; } } while (newNode && !newNode._canHaveFocus()); if (newNode) { newNode.focus();} Event.preventDefault(ev); break; case KEY.RIGHT: var self = this, moveFocusRight, focusOnExpand = function (newNode) { self.unsubscribe('expandComplete',focusOnExpand); moveFocusRight(newNode); }; moveFocusRight = function (newNode) { do { if (newNode.isDynamic() && !newNode.childrenRendered) { self.subscribe('expandComplete',focusOnExpand); newNode.expand(); newNode = null; break; } else { newNode.expand(); if (newNode.children.length) { newNode = newNode.children[0]; } else { newNode = newNode.nextSibling; } } } while (newNode && !newNode._canHaveFocus()); if (newNode) { newNode.focus();} }; moveFocusRight(newNode); Event.preventDefault(ev); break; case KEY.ENTER: if (node.href) { if (node.target) { window.open(node.href,node.target); } else { window.location(node.href); } } else { node.toggle(); } this.fireEvent('enterKeyPressed',node); Event.preventDefault(ev); break; case KEY.HOME: newNode = this.getRoot(); if (newNode.children.length) {newNode = newNode.children[0];} if (newNode._canHaveFocus()) { newNode.focus(); } Event.preventDefault(ev); break; case KEY.END: newNode = newNode.parent.children; newNode = newNode[newNode.length -1]; if (newNode._canHaveFocus()) { newNode.focus(); } Event.preventDefault(ev); break; // case KEY.PAGE_UP: // break; // case KEY.PAGE_DOWN: // break; case 107: // plus key case 187: // plus key if (ev.shiftKey) { node.parent.expandAll(); } else { node.expand(); } break; case 109: // minus key case 189: // minus key if (ev.shiftKey) { node.parent.collapseAll(); } else { node.collapse(); } break; default: break; } }, /** * Renders the tree boilerplate and visible nodes * @method render */ render: function() { var html = this.root.getHtml(), el = this.getEl(); el.innerHTML = html; if (!this._hasEvents) { Event.on(el, 'click', this._onClickEvent, this, true); Event.on(el, 'dblclick', this._onDblClickEvent, this, true); Event.on(el, 'mouseover', this._onMouseOverEvent, this, true); Event.on(el, 'mouseout', this._onMouseOutEvent, this, true); Event.on(el, 'keydown', this._onKeyDownEvent, this, true); } this._hasEvents = true; }, /** * Returns the tree's host element * @method getEl * @return {HTMLElement} the host element */ getEl: function() { if (! this._el) { this._el = Dom.get(this.id); } return this._el; }, /** * Nodes register themselves with the tree instance when they are created. * @method regNode * @param node {Node} the node to register * @private */ regNode: function(node) { this._nodes[node.index] = node; }, /** * Returns the root node of this tree * @method getRoot * @return {Node} the root node */ getRoot: function() { return this.root; }, /** * Configures this tree to dynamically load all child data * @method setDynamicLoad * @param {function} fnDataLoader the function that will be called to get the data * @param iconMode {int} configures the icon that is displayed when a dynamic * load node is expanded the first time without children. By default, the * "collapse" icon will be used. If set to 1, the leaf node icon will be * displayed. */ setDynamicLoad: function(fnDataLoader, iconMode) { this.root.setDynamicLoad(fnDataLoader, iconMode); }, /** * Expands all child nodes. Note: this conflicts with the "multiExpand" * node property. If expand all is called in a tree with nodes that * do not allow multiple siblings to be displayed, only the last sibling * will be expanded. * @method expandAll */ expandAll: function() { if (!this.locked) { this.root.expandAll(); } }, /** * Collapses all expanded child nodes in the entire tree. * @method collapseAll */ collapseAll: function() { if (!this.locked) { this.root.collapseAll(); } }, /** * Returns a node in the tree that has the specified index (this index * is created internally, so this function probably will only be used * in html generated for a given node.) * @method getNodeByIndex * @param {int} nodeIndex the index of the node wanted * @return {Node} the node with index=nodeIndex, null if no match */ getNodeByIndex: function(nodeIndex) { var n = this._nodes[nodeIndex]; return (n) ? n : null; }, /** * Returns a node that has a matching property and value in the data * object that was passed into its constructor. * @method getNodeByProperty * @param {object} property the property to search (usually a string) * @param {object} value the value we want to find (usuall an int or string) * @return {Node} the matching node, null if no match */ getNodeByProperty: function(property, value) { for (var i in this._nodes) { if (this._nodes.hasOwnProperty(i)) { var n = this._nodes[i]; if ((property in n && n[property] == value) || (n.data && value == n.data[property])) { return n; } } } return null; }, /** * Returns a collection of nodes that have a matching property * and value in the data object that was passed into its constructor. * @method getNodesByProperty * @param {object} property the property to search (usually a string) * @param {object} value the value we want to find (usuall an int or string) * @return {Array} the matching collection of nodes, null if no match */ getNodesByProperty: function(property, value) { var values = []; for (var i in this._nodes) { if (this._nodes.hasOwnProperty(i)) { var n = this._nodes[i]; if ((property in n && n[property] == value) || (n.data && value == n.data[property])) { values.push(n); } } } return (values.length) ? values : null; }, /** * Returns a collection of nodes that have passed the test function * passed as its only argument. * The function will receive a reference to each node to be tested. * @method getNodesBy * @param {function} a boolean function that receives a Node instance and returns true to add the node to the results list * @return {Array} the matching collection of nodes, null if no match */ getNodesBy: function(fn) { var values = []; for (var i in this._nodes) { if (this._nodes.hasOwnProperty(i)) { var n = this._nodes[i]; if (fn(n)) { values.push(n); } } } return (values.length) ? values : null; }, /** * Returns the treeview node reference for an ancestor element * of the node, or null if it is not contained within any node * in this tree. * @method getNodeByElement * @param el {HTMLElement} the element to test * @return {YAHOO.widget.Node} a node reference or null */ getNodeByElement: function(el) { var p=el, m, re=/ygtv([^\d]*)(.*)/; do { if (p && p.id) { m = p.id.match(re); if (m && m[2]) { return this.getNodeByIndex(m[2]); } } p = p.parentNode; if (!p || !p.tagName) { break; } } while (p.id !== this.id && p.tagName.toLowerCase() !== "body"); return null; }, /** * When in singleNodeHighlight it returns the node highlighted * or null if none. Returns null if singleNodeHighlight is false. * @method getHighlightedNode * @return {YAHOO.widget.Node} a node reference or null */ getHighlightedNode: function() { return this._currentlyHighlighted; }, /** * Removes the node and its children, and optionally refreshes the * branch of the tree that was affected. * @method removeNode * @param {Node} node to remove * @param {boolean} autoRefresh automatically refreshes branch if true * @return {boolean} False is there was a problem, true otherwise. */ removeNode: function(node, autoRefresh) { // Don't delete the root node if (node.isRoot()) { return false; } // Get the branch that we may need to refresh var p = node.parent; if (p.parent) { p = p.parent; } // Delete the node and its children this._deleteNode(node); // Refresh the parent of the parent if (autoRefresh && p && p.childrenRendered) { p.refresh(); } return true; }, /** * wait until the animation is complete before deleting * to avoid javascript errors * @method _removeChildren_animComplete * @param o the custom event payload * @private */ _removeChildren_animComplete: function(o) { this.unsubscribe(this._removeChildren_animComplete); this.removeChildren(o.node); }, /** * Deletes this nodes child collection, recursively. Also collapses * the node, and resets the dynamic load flag. The primary use for * this method is to purge a node and allow it to fetch its data * dynamically again. * @method removeChildren * @param {Node} node the node to purge */ removeChildren: function(node) { if (node.expanded) { // wait until the animation is complete before deleting to // avoid javascript errors if (this._collapseAnim) { this.subscribe("animComplete", this._removeChildren_animComplete, this, true); Widget.Node.prototype.collapse.call(node); return; } node.collapse(); } while (node.children.length) { this._deleteNode(node.children[0]); } if (node.isRoot()) { Widget.Node.prototype.expand.call(node); } node.childrenRendered = false; node.dynamicLoadComplete = false; node.updateIcon(); }, /** * Deletes the node and recurses children * @method _deleteNode * @private */ _deleteNode: function(node) { // Remove all the child nodes first this.removeChildren(node); // Remove the node from the tree this.popNode(node); }, /** * Removes the node from the tree, preserving the child collection * to make it possible to insert the branch into another part of the * tree, or another tree. * @method popNode * @param {Node} node to remove */ popNode: function(node) { var p = node.parent; // Update the parent's collection of children var a = []; for (var i=0, len=p.children.length;i
                    * @property highlightState * @type integer * @default 0 */ highlightState: 0, /** * Tells whether highlighting will be propagated up to the parents of the clicked node * @property propagateHighlightUp * @type boolean * @default false */ propagateHighlightUp: false, /** * Tells whether highlighting will be propagated down to the children of the clicked node * @property propagateHighlightDown * @type boolean * @default false */ propagateHighlightDown: false, /** * User-defined className to be added to the Node * @property className * @type string * @default null */ className: null, /** * The node type * @property _type * @private * @type string * @default "Node" */ _type: "Node", /* spacerPath: "http://l.yimg.com/a/i/space.gif", expandedText: "Expanded", collapsedText: "Collapsed", loadingText: "Loading", */ /** * Initializes this node, gets some of the properties from the parent * @method init * @param oData {object} a string or object containing the data that will * be used to render this node * @param oParent {Node} this node's parent node * @param expanded {boolean} the initial expanded/collapsed state */ init: function(oData, oParent, expanded) { this.data = {}; this.children = []; this.index = YAHOO.widget.TreeView.nodeCount; ++YAHOO.widget.TreeView.nodeCount; this.contentElId = "ygtvcontentel" + this.index; if (Lang.isObject(oData)) { for (var property in oData) { if (oData.hasOwnProperty(property)) { if (property.charAt(0) != '_' && !Lang.isUndefined(this[property]) && !Lang.isFunction(this[property]) ) { this[property] = oData[property]; } else { this.data[property] = oData[property]; } } } } if (!Lang.isUndefined(expanded) ) { this.expanded = expanded; } /** * The parentChange event is fired when a parent element is applied * to the node. This is useful if you need to apply tree-level * properties to a tree that need to happen if a node is moved from * one tree to another. * * @event parentChange * @type CustomEvent */ this.createEvent("parentChange", this); // oParent should never be null except when we create the root node. if (oParent) { oParent.appendChild(this); } }, /** * Certain properties for the node cannot be set until the parent * is known. This is called after the node is inserted into a tree. * the parent is also applied to this node's children in order to * make it possible to move a branch from one tree to another. * @method applyParent * @param {Node} parentNode this node's parent node * @return {boolean} true if the application was successful */ applyParent: function(parentNode) { if (!parentNode) { return false; } this.tree = parentNode.tree; this.parent = parentNode; this.depth = parentNode.depth + 1; // @todo why was this put here. This causes new nodes added at the // root level to lose the menu behavior. // if (! this.multiExpand) { // this.multiExpand = parentNode.multiExpand; // } this.tree.regNode(this); parentNode.childrenRendered = false; // cascade update existing children for (var i=0, len=this.children.length;i 0 || (checkForLazyLoad && this.isDynamic() && !this.dynamicLoadComplete) ); } }, /** * Expands if node is collapsed, collapses otherwise. * @method toggle */ toggle: function() { if (!this.tree.locked && ( this.hasChildren(true) || this.isDynamic()) ) { if (this.expanded) { this.collapse(); } else { this.expand(); } } }, /** * Returns the markup for this node and its children. * @method getHtml * @return {string} the markup for this node and its expanded children. */ getHtml: function() { this.childrenRendered = false; return ['
                    ' ,this.getNodeHtml() , this.getChildrenHtml() ,'
                    '].join(""); }, /** * Called when first rendering the tree. We always build the div that will * contain this nodes children, but we don't render the children themselves * unless this node is expanded. * @method getChildrenHtml * @return {string} the children container div html and any expanded children * @private */ getChildrenHtml: function() { var sb = []; sb[sb.length] = '
                    = this.depth || depth < 0) { return null; } var p = this.parent; while (p.depth > depth) { p = p.parent; } return p; }, /** * Returns the css class for the spacer at the specified depth for * this node. If this node's ancestor at the specified depth * has a next sibling the presentation is different than if it * does not have a next sibling * @method getDepthStyle * @param {int} depth the depth of the ancestor. * @return {string} the css class for the spacer */ getDepthStyle: function(depth) { return (this.getAncestor(depth).nextSibling) ? "ygtvdepthcell" : "ygtvblankdepthcell"; }, /** * Get the markup for the node. This may be overrided so that we can * support different types of nodes. * @method getNodeHtml * @return {string} The HTML that will render this node. */ getNodeHtml: function() { var sb = []; sb[sb.length] = ''; for (var i=0;i
                    '; } if (this.hasIcon && this.hasChildren()) { sb[sb.length] = '
                    '; } else { sb[sb.length] = ''; } sb[sb.length] = '
                     
                    0; }, /** * Removes the focus of previously selected Node * @method _removeFocus * @private */ _removeFocus:function () { if (this._focusedItem) { Event.removeListener(this._focusedItem,'blur'); this._focusedItem = null; } var el; while ((el = this._focusHighlightedItems.shift())) { // yes, it is meant as an assignment, really Dom.removeClass(el,YAHOO.widget.TreeView.FOCUS_CLASS_NAME ); } }, /** * Sets the focus on the node element. * It will only be able to set the focus on nodes that have anchor elements in it. * Toggle or branch icons have anchors and can be focused on. * If will fail in nodes that have no anchor * @method focus * @return {boolean} success */ focus: function () { var focused = false, self = this; if (this.tree.currentFocus) { this.tree.currentFocus._removeFocus(); } var expandParent = function (node) { if (node.parent) { expandParent(node.parent); node.parent.expand(); } }; expandParent(this); Dom.getElementsBy ( function (el) { return (/ygtv(([tl][pmn]h?)|(content))/).test(el.className); } , 'td' , self.getEl().firstChild , function (el) { Dom.addClass(el, YAHOO.widget.TreeView.FOCUS_CLASS_NAME ); if (!focused) { var aEl = el.getElementsByTagName('a'); if (aEl.length) { aEl = aEl[0]; aEl.focus(); self._focusedItem = aEl; Event.on(aEl,'blur',function () { self.tree.fireEvent('focusChanged',{oldNode:self.tree.currentFocus,newNode:null}); self.tree.currentFocus = null; self._removeFocus(); }); focused = true; } } self._focusHighlightedItems.push(el); } ); if (focused) { this.tree.fireEvent('focusChanged',{oldNode:this.tree.currentFocus,newNode:this}); this.tree.currentFocus = this; } else { this.tree.fireEvent('focusChanged',{oldNode:self.tree.currentFocus,newNode:null}); this.tree.currentFocus = null; this._removeFocus(); } return focused; }, /** * Count of nodes in a branch * @method getNodeCount * @return {int} number of nodes in the branch */ getNodeCount: function() { for (var i = 0, count = 0;i< this.children.length;i++) { count += this.children[i].getNodeCount(); } return count + 1; }, /** * Returns an object which could be used to build a tree out of this node and its children. * It can be passed to the tree constructor to reproduce this node as a tree. * It will return false if the node or any children loads dynamically, regardless of whether it is loaded or not. * @method getNodeDefinition * @return {Object | false} definition of the tree or false if the node or any children is defined as dynamic */ getNodeDefinition: function() { if (this.isDynamic()) { return false; } var def, defs = Lang.merge(this.data), children = []; if (this.expanded) {defs.expanded = this.expanded; } if (!this.multiExpand) { defs.multiExpand = this.multiExpand; } if (this.renderHidden) { defs.renderHidden = this.renderHidden; } if (!this.hasIcon) { defs.hasIcon = this.hasIcon; } if (this.nowrap) { defs.nowrap = this.nowrap; } if (this.className) { defs.className = this.className; } if (this.editable) { defs.editable = this.editable; } if (!this.enableHighlight) { defs.enableHighlight = this.enableHighlight; } if (this.highlightState) { defs.highlightState = this.highlightState; } if (this.propagateHighlightUp) { defs.propagateHighlightUp = this.propagateHighlightUp; } if (this.propagateHighlightDown) { defs.propagateHighlightDown = this.propagateHighlightDown; } defs.type = this._type; for (var i = 0; i < this.children.length;i++) { def = this.children[i].getNodeDefinition(); if (def === false) { return false;} children.push(def); } if (children.length) { defs.children = children; } return defs; }, /** * Generates the link that will invoke this node's toggle method * @method getToggleLink * @return {string} the javascript url for toggling this node */ getToggleLink: function() { return 'return false;'; }, /** * Sets the value of property for this node and all loaded descendants. * Only public and defined properties can be set, not methods. * Values for unknown properties will be assigned to the refNode.data object * @method setNodesProperty * @param name {string} Name of the property to be set * @param value {any} value to be set * @param refresh {boolean} if present and true, it does a refresh */ setNodesProperty: function(name, value, refresh) { if (name.charAt(0) != '_' && !Lang.isUndefined(this[name]) && !Lang.isFunction(this[name]) ) { this[name] = value; } else { this.data[name] = value; } for (var i = 0; i < this.children.length;i++) { this.children[i].setNodesProperty(name,value); } if (refresh) { this.refresh(); } }, /** * Toggles the highlighted state of a Node * @method toggleHighlight */ toggleHighlight: function() { if (this.enableHighlight) { // unhighlights only if fully highligthed. For not or partially highlighted it will highlight if (this.highlightState == 1) { this.unhighlight(); } else { this.highlight(); } } }, /** * Turns highlighting on node. * @method highlight * @param _silent {boolean} optional, don't fire the highlightEvent */ highlight: function(_silent) { if (this.enableHighlight) { if (this.tree.singleNodeHighlight) { if (this.tree._currentlyHighlighted) { this.tree._currentlyHighlighted.unhighlight(_silent); } this.tree._currentlyHighlighted = this; } this.highlightState = 1; this._setHighlightClassName(); if (!this.tree.singleNodeHighlight) { if (this.propagateHighlightDown) { for (var i = 0;i < this.children.length;i++) { this.children[i].highlight(true); } } if (this.propagateHighlightUp) { if (this.parent) { this.parent._childrenHighlighted(); } } } if (!_silent) { this.tree.fireEvent('highlightEvent',this); } } }, /** * Turns highlighting off a node. * @method unhighlight * @param _silent {boolean} optional, don't fire the highlightEvent */ unhighlight: function(_silent) { if (this.enableHighlight) { // might have checked singleNodeHighlight but it wouldn't really matter either way this.tree._currentlyHighlighted = null; this.highlightState = 0; this._setHighlightClassName(); if (!this.tree.singleNodeHighlight) { if (this.propagateHighlightDown) { for (var i = 0;i < this.children.length;i++) { this.children[i].unhighlight(true); } } if (this.propagateHighlightUp) { if (this.parent) { this.parent._childrenHighlighted(); } } } if (!_silent) { this.tree.fireEvent('highlightEvent',this); } } }, /** * Checks whether all or part of the children of a node are highlighted and * sets the node highlight to full, none or partial highlight. * If set to propagate it will further call the parent * @method _childrenHighlighted * @private */ _childrenHighlighted: function() { var yes = false, no = false; if (this.enableHighlight) { for (var i = 0;i < this.children.length;i++) { switch(this.children[i].highlightState) { case 0: no = true; break; case 1: yes = true; break; case 2: yes = no = true; break; } } if (yes && no) { this.highlightState = 2; } else if (yes) { this.highlightState = 1; } else { this.highlightState = 0; } this._setHighlightClassName(); if (this.propagateHighlightUp) { if (this.parent) { this.parent._childrenHighlighted(); } } } }, /** * Changes the classNames on the toggle and content containers to reflect the current highlighting * @method _setHighlightClassName * @private */ _setHighlightClassName: function() { var el = Dom.get('ygtvtableel' + this.index); if (el) { el.className = el.className.replace(/\bygtv-highlight\d\b/gi,'ygtv-highlight' + this.highlightState); } } }; YAHOO.augment(YAHOO.widget.Node, YAHOO.util.EventProvider); })(); /** * A custom YAHOO.widget.Node that handles the unique nature of * the virtual, presentationless root node. * @namespace YAHOO.widget * @class RootNode * @extends YAHOO.widget.Node * @param oTree {YAHOO.widget.TreeView} The tree instance this node belongs to * @constructor */ YAHOO.widget.RootNode = function(oTree) { // Initialize the node with null params. The root node is a // special case where the node has no presentation. So we have // to alter the standard properties a bit. this.init(null, null, true); /* * For the root node, we get the tree reference from as a param * to the constructor instead of from the parent element. */ this.tree = oTree; }; YAHOO.extend(YAHOO.widget.RootNode, YAHOO.widget.Node, { /** * The node type * @property _type * @type string * @private * @default "RootNode" */ _type: "RootNode", // overrides YAHOO.widget.Node getNodeHtml: function() { return ""; }, toString: function() { return this._type; }, loadComplete: function() { this.tree.draw(); }, /** * Count of nodes in tree. * It overrides Nodes.getNodeCount because the root node should not be counted. * @method getNodeCount * @return {int} number of nodes in the tree */ getNodeCount: function() { for (var i = 0, count = 0;i< this.children.length;i++) { count += this.children[i].getNodeCount(); } return count; }, /** * Returns an object which could be used to build a tree out of this node and its children. * It can be passed to the tree constructor to reproduce this node as a tree. * Since the RootNode is automatically created by treeView, * its own definition is excluded from the returned node definition * which only contains its children. * @method getNodeDefinition * @return {Object | false} definition of the tree or false if any child node is defined as dynamic */ getNodeDefinition: function() { for (var def, defs = [], i = 0; i < this.children.length;i++) { def = this.children[i].getNodeDefinition(); if (def === false) { return false;} defs.push(def); } return defs; }, collapse: function() {}, expand: function() {}, getSiblings: function() { return null; }, focus: function () {} }); (function () { var Dom = YAHOO.util.Dom, Lang = YAHOO.lang, Event = YAHOO.util.Event; /** * The default node presentation. The first parameter should be * either a string that will be used as the node's label, or an object * that has at least a string property called label. By default, clicking the * label will toggle the expanded/collapsed state of the node. By * setting the href property of the instance, this behavior can be * changed so that the label will go to the specified href. * @namespace YAHOO.widget * @class TextNode * @extends YAHOO.widget.Node * @constructor * @param oData {object} a string or object containing the data that will * be used to render this node. * Providing a string is the same as providing an object with a single property named label. * All values in the oData will be used to set equally named properties in the node * as long as the node does have such properties, they are not undefined, private or functions. * All attributes are made available in noderef.data, which * can be used to store custom attributes. TreeView.getNode(s)ByProperty * can be used to retrieve a node by one of the attributes. * @param oParent {YAHOO.widget.Node} this node's parent node * @param expanded {boolean} the initial expanded/collapsed state (deprecated; use oData.expanded) */ YAHOO.widget.TextNode = function(oData, oParent, expanded) { if (oData) { if (Lang.isString(oData)) { oData = { label: oData }; } this.init(oData, oParent, expanded); this.setUpLabel(oData); } }; YAHOO.extend(YAHOO.widget.TextNode, YAHOO.widget.Node, { /** * The CSS class for the label href. Defaults to ygtvlabel, but can be * overridden to provide a custom presentation for a specific node. * @property labelStyle * @type string */ labelStyle: "ygtvlabel", /** * The derived element id of the label for this node * @property labelElId * @type string */ labelElId: null, /** * The text for the label. It is assumed that the oData parameter will * either be a string that will be used as the label, or an object that * has a property called "label" that we will use. * @property label * @type string */ label: null, /** * The text for the title (tooltip) for the label element * @property title * @type string */ title: null, /** * The href for the node's label. If one is not specified, the href will * be set so that it toggles the node. * @property href * @type string */ href: null, /** * The label href target, defaults to current window * @property target * @type string */ target: "_self", /** * The node type * @property _type * @private * @type string * @default "TextNode" */ _type: "TextNode", /** * Sets up the node label * @method setUpLabel * @param oData string containing the label, or an object with a label property */ setUpLabel: function(oData) { if (Lang.isString(oData)) { oData = { label: oData }; } else { if (oData.style) { this.labelStyle = oData.style; } } this.label = oData.label; this.labelElId = "ygtvlabelel" + this.index; }, /** * Returns the label element * @for YAHOO.widget.TextNode * @method getLabelEl * @return {object} the element */ getLabelEl: function() { return Dom.get(this.labelElId); }, // overrides YAHOO.widget.Node getContentHtml: function() { var sb = []; sb[sb.length] = this.href ? '':''; return sb.join(""); }, /** * Returns an object which could be used to build a tree out of this node and its children. * It can be passed to the tree constructor to reproduce this node as a tree. * It will return false if the node or any descendant loads dynamically, regardless of whether it is loaded or not. * @method getNodeDefinition * @return {Object | false} definition of the tree or false if this node or any descendant is defined as dynamic */ getNodeDefinition: function() { var def = YAHOO.widget.TextNode.superclass.getNodeDefinition.call(this); if (def === false) { return false; } // Node specific properties def.label = this.label; if (this.labelStyle != 'ygtvlabel') { def.style = this.labelStyle; } if (this.title) { def.title = this.title; } if (this.href) { def.href = this.href; } if (this.target != '_self') { def.target = this.target; } return def; }, toString: function() { return YAHOO.widget.TextNode.superclass.toString.call(this) + ": " + this.label; }, // deprecated onLabelClick: function() { return false; }, refresh: function() { YAHOO.widget.TextNode.superclass.refresh.call(this); var label = this.getLabelEl(); label.innerHTML = this.label; if (label.tagName.toUpperCase() == 'A') { label.href = this.href; label.target = this.target; } } }); })(); /** * A menu-specific implementation that differs from TextNode in that only * one sibling can be expanded at a time. * @namespace YAHOO.widget * @class MenuNode * @extends YAHOO.widget.TextNode * @param oData {object} a string or object containing the data that will * be used to render this node. * Providing a string is the same as providing an object with a single property named label. * All values in the oData will be used to set equally named properties in the node * as long as the node does have such properties, they are not undefined, private or functions. * All attributes are made available in noderef.data, which * can be used to store custom attributes. TreeView.getNode(s)ByProperty * can be used to retrieve a node by one of the attributes. * @param oParent {YAHOO.widget.Node} this node's parent node * @param expanded {boolean} the initial expanded/collapsed state (deprecated; use oData.expanded) * @constructor */ YAHOO.widget.MenuNode = function(oData, oParent, expanded) { YAHOO.widget.MenuNode.superclass.constructor.call(this,oData,oParent,expanded); /* * Menus usually allow only one branch to be open at a time. */ this.multiExpand = false; }; YAHOO.extend(YAHOO.widget.MenuNode, YAHOO.widget.TextNode, { /** * The node type * @property _type * @private * @default "MenuNode" */ _type: "MenuNode" }); (function () { var Dom = YAHOO.util.Dom, Lang = YAHOO.lang, Event = YAHOO.util.Event; /** * This implementation takes either a string or object for the * oData argument. If is it a string, it will use it for the display * of this node (and it can contain any html code). If the parameter * is an object,it looks for a parameter called "html" that will be * used for this node's display. * @namespace YAHOO.widget * @class HTMLNode * @extends YAHOO.widget.Node * @constructor * @param oData {object} a string or object containing the data that will * be used to render this node. * Providing a string is the same as providing an object with a single property named html. * All values in the oData will be used to set equally named properties in the node * as long as the node does have such properties, they are not undefined, private or functions. * All other attributes are made available in noderef.data, which * can be used to store custom attributes. TreeView.getNode(s)ByProperty * can be used to retrieve a node by one of the attributes. * @param oParent {YAHOO.widget.Node} this node's parent node * @param expanded {boolean} the initial expanded/collapsed state (deprecated; use oData.expanded) * @param hasIcon {boolean} specifies whether or not leaf nodes should * be rendered with or without a horizontal line and/or toggle icon. If the icon * is not displayed, the content fills the space it would have occupied. * This option operates independently of the leaf node presentation logic * for dynamic nodes. * (deprecated; use oData.hasIcon) */ var HN = function(oData, oParent, expanded, hasIcon) { if (oData) { this.init(oData, oParent, expanded); this.initContent(oData, hasIcon); } }; YAHOO.widget.HTMLNode = HN; YAHOO.extend(HN, YAHOO.widget.Node, { /** * The CSS class for the html content container. Defaults to ygtvhtml, but * can be overridden to provide a custom presentation for a specific node. * @property contentStyle * @type string */ contentStyle: "ygtvhtml", /** * The HTML content to use for this node's display * @property html * @type string */ html: null, /** * The node type * @property _type * @private * @type string * @default "HTMLNode" */ _type: "HTMLNode", /** * Sets up the node label * @method initContent * @param oData {object} An html string or object containing an html property * @param hasIcon {boolean} determines if the node will be rendered with an * icon or not */ initContent: function(oData, hasIcon) { this.setHtml(oData); this.contentElId = "ygtvcontentel" + this.index; if (!Lang.isUndefined(hasIcon)) { this.hasIcon = hasIcon; } }, /** * Synchronizes the node.html, and the node's content * @method setHtml * @param o {object |string | HTMLElement } An html string, an object containing an html property or an HTML element */ setHtml: function(o) { this.html = (Lang.isObject(o) && 'html' in o) ? o.html : o; var el = this.getContentEl(); if (el) { if (o.nodeType && o.nodeType == 1 && o.tagName) { el.innerHTML = ""; } else { el.innerHTML = this.html; } } }, // overrides YAHOO.widget.Node // If property html is a string, it sets the innerHTML for the node // If it is an HTMLElement, it defers appending it to the tree until the HTML basic structure is built getContentHtml: function() { if (typeof this.html === "string") { return this.html; } else { HN._deferredNodes.push(this); if (!HN._timer) { HN._timer = window.setTimeout(function () { var n; while((n = HN._deferredNodes.pop())) { n.getContentEl().appendChild(n.html); } HN._timer = null; },0); } return ""; } }, /** * Returns an object which could be used to build a tree out of this node and its children. * It can be passed to the tree constructor to reproduce this node as a tree. * It will return false if any node loads dynamically, regardless of whether it is loaded or not. * @method getNodeDefinition * @return {Object | false} definition of the tree or false if any node is defined as dynamic */ getNodeDefinition: function() { var def = HN.superclass.getNodeDefinition.call(this); if (def === false) { return false; } def.html = this.html; return def; } }); /** * An array of HTMLNodes created with HTML Elements that had their rendering * deferred until the basic tree structure is rendered. * @property _deferredNodes * @type YAHOO.widget.HTMLNode[] * @default [] * @private * @static */ HN._deferredNodes = []; /** * A system timer value used to mark whether a deferred operation is pending. * @property _timer * @type System Timer * @default null * @private * @static */ HN._timer = null; })(); (function () { var Dom = YAHOO.util.Dom, Lang = YAHOO.lang, Event = YAHOO.util.Event, Calendar = YAHOO.widget.Calendar; /** * A Date-specific implementation that differs from TextNode in that it uses * YAHOO.widget.Calendar as an in-line editor, if available * If Calendar is not available, it behaves as a plain TextNode. * @namespace YAHOO.widget * @class DateNode * @extends YAHOO.widget.TextNode * @param oData {object} a string or object containing the data that will * be used to render this node. * Providing a string is the same as providing an object with a single property named label. * All values in the oData will be used to set equally named properties in the node * as long as the node does have such properties, they are not undefined, private nor functions. * All attributes are made available in noderef.data, which * can be used to store custom attributes. TreeView.getNode(s)ByProperty * can be used to retrieve a node by one of the attributes. * @param oParent {YAHOO.widget.Node} this node's parent node * @param expanded {boolean} the initial expanded/collapsed state (deprecated; use oData.expanded) * @constructor */ YAHOO.widget.DateNode = function(oData, oParent, expanded) { YAHOO.widget.DateNode.superclass.constructor.call(this,oData, oParent, expanded); }; YAHOO.extend(YAHOO.widget.DateNode, YAHOO.widget.TextNode, { /** * The node type * @property _type * @type string * @private * @default "DateNode" */ _type: "DateNode", /** * Configuration object for the Calendar editor, if used. * See http://developer.yahoo.com/yui/calendar/#internationalization * @property calendarConfig */ calendarConfig: null, /** * If YAHOO.widget.Calendar is available, it will pop up a Calendar to enter a new date. Otherwise, it falls back to a plain <input> textbox * @method fillEditorContainer * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @return void */ fillEditorContainer: function (editorData) { var cal, container = editorData.inputContainer; if (Lang.isUndefined(Calendar)) { Dom.replaceClass(editorData.editorPanel,'ygtv-edit-DateNode','ygtv-edit-TextNode'); YAHOO.widget.DateNode.superclass.fillEditorContainer.call(this, editorData); return; } if (editorData.nodeType != this._type) { editorData.nodeType = this._type; editorData.saveOnEnter = false; editorData.node.destroyEditorContents(editorData); editorData.inputObject = cal = new Calendar(container.appendChild(document.createElement('div'))); if (this.calendarConfig) { cal.cfg.applyConfig(this.calendarConfig,true); cal.cfg.fireQueue(); } cal.selectEvent.subscribe(function () { this.tree._closeEditor(true); },this,true); } else { cal = editorData.inputObject; } editorData.oldValue = this.label; cal.cfg.setProperty("selected",this.label, false); var delim = cal.cfg.getProperty('DATE_FIELD_DELIMITER'); var pageDate = this.label.split(delim); cal.cfg.setProperty('pagedate',pageDate[cal.cfg.getProperty('MDY_MONTH_POSITION') -1] + delim + pageDate[cal.cfg.getProperty('MDY_YEAR_POSITION') -1]); cal.cfg.fireQueue(); cal.render(); cal.oDomContainer.focus(); }, /** * Returns the value from the input element. * Overrides Node.getEditorValue. * @method getEditorValue * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @return {string} date entered */ getEditorValue: function (editorData) { if (Lang.isUndefined(Calendar)) { return editorData.inputElement.value; } else { var cal = editorData.inputObject, date = cal.getSelectedDates()[0], dd = []; dd[cal.cfg.getProperty('MDY_DAY_POSITION') -1] = date.getDate(); dd[cal.cfg.getProperty('MDY_MONTH_POSITION') -1] = date.getMonth() + 1; dd[cal.cfg.getProperty('MDY_YEAR_POSITION') -1] = date.getFullYear(); return dd.join(cal.cfg.getProperty('DATE_FIELD_DELIMITER')); } }, /** * Finally displays the newly entered date in the tree. * Overrides Node.displayEditedValue. * @method displayEditedValue * @param value {HTML} date to be displayed and stored in the node. * This data is added to the node unescaped via the innerHTML property. * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information */ displayEditedValue: function (value,editorData) { var node = editorData.node; node.label = value; node.getLabelEl().innerHTML = value; }, /** * Returns an object which could be used to build a tree out of this node and its children. * It can be passed to the tree constructor to reproduce this node as a tree. * It will return false if the node or any descendant loads dynamically, regardless of whether it is loaded or not. * @method getNodeDefinition * @return {Object | false} definition of the node or false if this node or any descendant is defined as dynamic */ getNodeDefinition: function() { var def = YAHOO.widget.DateNode.superclass.getNodeDefinition.call(this); if (def === false) { return false; } if (this.calendarConfig) { def.calendarConfig = this.calendarConfig; } return def; } }); })(); (function () { var Dom = YAHOO.util.Dom, Lang = YAHOO.lang, Event = YAHOO.util.Event, TV = YAHOO.widget.TreeView, TVproto = TV.prototype; /** * An object to store information used for in-line editing * for all Nodes of all TreeViews. It contains: *
                      *
                    • active {boolean}, whether there is an active cell editor
                    • *
                    • whoHasIt {YAHOO.widget.TreeView} TreeView instance that is currently using the editor
                    • *
                    • nodeType {string} value of static Node._type property, allows reuse of input element if node is of the same type.
                    • *
                    • editorPanel {HTMLelement (<div>)} element holding the in-line editor
                    • *
                    • inputContainer {HTMLelement (<div>)} element which will hold the type-specific input element(s) to be filled by the fillEditorContainer method
                    • *
                    • buttonsContainer {HTMLelement (<div>)} element which holds the <button> elements for Ok/Cancel. If you don't want any of the buttons, hide it via CSS styles, don't destroy it
                    • *
                    • node {YAHOO.widget.Node} reference to the Node being edited
                    • *
                    • saveOnEnter {boolean}, whether the Enter key should be accepted as a Save command (Esc. is always taken as Cancel), disable for multi-line input elements
                    • *
                    • oldValue {any} value before editing
                    • *
                    * Editors are free to use this object to store additional data. * @property editorData * @static * @for YAHOO.widget.TreeView */ TV.editorData = { active:false, whoHasIt:null, // which TreeView has it nodeType:null, editorPanel:null, inputContainer:null, buttonsContainer:null, node:null, // which Node is being edited saveOnEnter:true, oldValue:undefined // Each node type is free to add its own properties to this as it sees fit. }; /** * Validator function for edited data, called from the TreeView instance scope, * receives the arguments (newValue, oldValue, nodeInstance) * and returns either the validated (or type-converted) value or undefined. * An undefined return will prevent the editor from closing * @property validator * @type function * @default null * @for YAHOO.widget.TreeView */ TVproto.validator = null; /** * Entry point for initializing the editing plug-in. * TreeView will call this method on initializing if it exists * @method _initEditor * @for YAHOO.widget.TreeView * @private */ TVproto._initEditor = function () { /** * Fires when the user clicks on the ok button of a node editor * @event editorSaveEvent * @type CustomEvent * @param oArgs.newValue {mixed} the new value just entered * @param oArgs.oldValue {mixed} the value originally in the tree * @param oArgs.node {YAHOO.widget.Node} the node that has the focus * @for YAHOO.widget.TreeView */ this.createEvent("editorSaveEvent", this); /** * Fires when the user clicks on the cancel button of a node editor * @event editorCancelEvent * @type CustomEvent * @param {YAHOO.widget.Node} node the node that has the focus * @for YAHOO.widget.TreeView */ this.createEvent("editorCancelEvent", this); }; /** * Entry point of the editing plug-in. * TreeView will call this method if it exists when a node label is clicked * @method _nodeEditing * @param node {YAHOO.widget.Node} the node to be edited * @return {Boolean} true to indicate that the node is editable and prevent any further bubbling of the click. * @for YAHOO.widget.TreeView * @private */ TVproto._nodeEditing = function (node) { if (node.fillEditorContainer && node.editable) { var ed, topLeft, buttons, button, editorData = TV.editorData; editorData.active = true; editorData.whoHasIt = this; if (!editorData.nodeType) { // Fixes: http://yuilibrary.com/projects/yui2/ticket/2528945 editorData.editorPanel = ed = this.getEl().appendChild(document.createElement('div')); Dom.addClass(ed,'ygtv-label-editor'); ed.tabIndex = 0; buttons = editorData.buttonsContainer = ed.appendChild(document.createElement('div')); Dom.addClass(buttons,'ygtv-button-container'); button = buttons.appendChild(document.createElement('button')); Dom.addClass(button,'ygtvok'); button.innerHTML = ' '; button = buttons.appendChild(document.createElement('button')); Dom.addClass(button,'ygtvcancel'); button.innerHTML = ' '; Event.on(buttons, 'click', function (ev) { var target = Event.getTarget(ev), editorData = TV.editorData, node = editorData.node, self = editorData.whoHasIt; if (Dom.hasClass(target,'ygtvok')) { Event.stopEvent(ev); self._closeEditor(true); } if (Dom.hasClass(target,'ygtvcancel')) { Event.stopEvent(ev); self._closeEditor(false); } }); editorData.inputContainer = ed.appendChild(document.createElement('div')); Dom.addClass(editorData.inputContainer,'ygtv-input'); Event.on(ed,'keydown',function (ev) { var editorData = TV.editorData, KEY = YAHOO.util.KeyListener.KEY, self = editorData.whoHasIt; switch (ev.keyCode) { case KEY.ENTER: Event.stopEvent(ev); if (editorData.saveOnEnter) { self._closeEditor(true); } break; case KEY.ESCAPE: Event.stopEvent(ev); self._closeEditor(false); break; } }); } else { ed = editorData.editorPanel; } editorData.node = node; if (editorData.nodeType) { Dom.removeClass(ed,'ygtv-edit-' + editorData.nodeType); } Dom.addClass(ed,' ygtv-edit-' + node._type); // Fixes: http://yuilibrary.com/projects/yui2/ticket/2528945 Dom.setStyle(ed,'display','block'); Dom.setXY(ed,Dom.getXY(node.getContentEl())); // up to here ed.focus(); node.fillEditorContainer(editorData); return true; // If inline editor available, don't do anything else. } }; /** * Method to be associated with an event (clickEvent, dblClickEvent or enterKeyPressed) to pop up the contents editor * It calls the corresponding node editNode method. * @method onEventEditNode * @param oArgs {object} Object passed as arguments to TreeView event listeners * @for YAHOO.widget.TreeView */ TVproto.onEventEditNode = function (oArgs) { if (oArgs instanceof YAHOO.widget.Node) { oArgs.editNode(); } else if (oArgs.node instanceof YAHOO.widget.Node) { oArgs.node.editNode(); } return false; }; /** * Method to be called when the inline editing is finished and the editor is to be closed * @method _closeEditor * @param save {Boolean} true if the edited value is to be saved, false if discarded * @private * @for YAHOO.widget.TreeView */ TVproto._closeEditor = function (save) { var ed = TV.editorData, node = ed.node, close = true; // http://yuilibrary.com/projects/yui2/ticket/2528946 // _closeEditor might now be called at any time, even when there is no label editor open // so we need to ensure there is one. if (!node || !ed.active) { return; } if (save) { close = ed.node.saveEditorValue(ed) !== false; } else { this.fireEvent( 'editorCancelEvent', node); } if (close) { Dom.setStyle(ed.editorPanel,'display','none'); ed.active = false; node.focus(); } }; /** * Entry point for TreeView's destroy method to destroy whatever the editing plug-in has created * @method _destroyEditor * @private * @for YAHOO.widget.TreeView */ TVproto._destroyEditor = function() { var ed = TV.editorData; if (ed && ed.nodeType && (!ed.active || ed.whoHasIt === this)) { Event.removeListener(ed.editorPanel,'keydown'); Event.removeListener(ed.buttonContainer,'click'); ed.node.destroyEditorContents(ed); document.body.removeChild(ed.editorPanel); ed.nodeType = ed.editorPanel = ed.inputContainer = ed.buttonsContainer = ed.whoHasIt = ed.node = null; ed.active = false; } }; var Nproto = YAHOO.widget.Node.prototype; /** * Signals if the label is editable. (Ignored on TextNodes with href set.) * @property editable * @type boolean * @for YAHOO.widget.Node */ Nproto.editable = false; /** * pops up the contents editor, if there is one and the node is declared editable * @method editNode * @for YAHOO.widget.Node */ Nproto.editNode = function () { this.tree._nodeEditing(this); }; /** Placeholder for a function that should provide the inline node label editor. * Leaving it set to null will indicate that this node type is not editable. * It should be overridden by nodes that provide inline editing. * The Node-specific editing element (input box, textarea or whatever) should be inserted into editorData.inputContainer. * @method fillEditorContainer * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @return void * @for YAHOO.widget.Node */ Nproto.fillEditorContainer = null; /** * Node-specific destroy function to empty the contents of the inline editor panel. * This function is the worst case alternative that will purge all possible events and remove the editor contents. * Method Event.purgeElement is somewhat costly so if it can be replaced by specifc Event.removeListeners, it is better to do so. * @method destroyEditorContents * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @for YAHOO.widget.Node */ Nproto.destroyEditorContents = function (editorData) { // In the worst case, if the input editor (such as the Calendar) has no destroy method // we can only try to remove all possible events on it. Event.purgeElement(editorData.inputContainer,true); editorData.inputContainer.innerHTML = ''; }; /** * Saves the value entered into the editor. * @method saveEditorValue * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @return {false or none} a return of exactly false will prevent the editor from closing * @for YAHOO.widget.Node */ Nproto.saveEditorValue = function (editorData) { var node = editorData.node, value, validator = node.tree.validator; value = this.getEditorValue(editorData); if (Lang.isFunction(validator)) { value = validator(value,editorData.oldValue,node); if (Lang.isUndefined(value)) { return false; } } if (this.tree.fireEvent( 'editorSaveEvent', { newValue:value, oldValue:editorData.oldValue, node:node }) !== false) { this.displayEditedValue(value,editorData); } }; /** * Returns the value(s) from the input element(s) . * Should be overridden by each node type. * @method getEditorValue * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @return {any} value entered * @for YAHOO.widget.Node */ Nproto.getEditorValue = function (editorData) { }; /** * Finally displays the newly edited value(s) in the tree. * Should be overridden by each node type. * @method displayEditedValue * @param value {HTML} value to be displayed and stored in the node * This data is added to the node unescaped via the innerHTML property. * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @for YAHOO.widget.Node */ Nproto.displayEditedValue = function (value,editorData) { }; var TNproto = YAHOO.widget.TextNode.prototype; /** * Places an <input> textbox in the input container and loads the label text into it. * @method fillEditorContainer * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @return void * @for YAHOO.widget.TextNode */ TNproto.fillEditorContainer = function (editorData) { var input; // If last node edited is not of the same type as this one, delete it and fill it with our editor if (editorData.nodeType != this._type) { editorData.nodeType = this._type; editorData.saveOnEnter = true; editorData.node.destroyEditorContents(editorData); editorData.inputElement = input = editorData.inputContainer.appendChild(document.createElement('input')); } else { // if the last node edited was of the same time, reuse the input element. input = editorData.inputElement; } editorData.oldValue = this.label; input.value = this.label; input.focus(); input.select(); }; /** * Returns the value from the input element. * Overrides Node.getEditorValue. * @method getEditorValue * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @return {string} value entered * @for YAHOO.widget.TextNode */ TNproto.getEditorValue = function (editorData) { return editorData.inputElement.value; }; /** * Finally displays the newly edited value in the tree. * Overrides Node.displayEditedValue. * @method displayEditedValue * @param value {string} value to be displayed and stored in the node * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @for YAHOO.widget.TextNode */ TNproto.displayEditedValue = function (value,editorData) { var node = editorData.node; node.label = value; node.getLabelEl().innerHTML = value; }; /** * Destroys the contents of the inline editor panel. * Overrides Node.destroyEditorContent. * Since we didn't set any event listeners on this inline editor, it is more efficient to avoid the generic method in Node. * @method destroyEditorContents * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information * @for YAHOO.widget.TextNode */ TNproto.destroyEditorContents = function (editorData) { editorData.inputContainer.innerHTML = ''; }; })(); /** * A static factory class for tree view expand/collapse animations * @class TVAnim * @static */ YAHOO.widget.TVAnim = function() { return { /** * Constant for the fade in animation * @property FADE_IN * @type string * @static */ FADE_IN: "TVFadeIn", /** * Constant for the fade out animation * @property FADE_OUT * @type string * @static */ FADE_OUT: "TVFadeOut", /** * Returns a ygAnim instance of the given type * @method getAnim * @param type {string} the type of animation * @param el {HTMLElement} the element to element (probably the children div) * @param callback {function} function to invoke when the animation is done. * @return {YAHOO.util.Animation} the animation instance * @static */ getAnim: function(type, el, callback) { if (YAHOO.widget[type]) { return new YAHOO.widget[type](el, callback); } else { return null; } }, /** * Returns true if the specified animation class is available * @method isValid * @param type {string} the type of animation * @return {boolean} true if valid, false if not * @static */ isValid: function(type) { return (YAHOO.widget[type]); } }; } (); /** * A 1/2 second fade-in animation. * @class TVFadeIn * @constructor * @param el {HTMLElement} the element to animate * @param callback {function} function to invoke when the animation is finished */ YAHOO.widget.TVFadeIn = function(el, callback) { /** * The element to animate * @property el * @type HTMLElement */ this.el = el; /** * the callback to invoke when the animation is complete * @property callback * @type function */ this.callback = callback; }; YAHOO.widget.TVFadeIn.prototype = { /** * Performs the animation * @method animate */ animate: function() { var tvanim = this; var s = this.el.style; s.opacity = 0.1; s.filter = "alpha(opacity=10)"; s.display = ""; var dur = 0.4; var a = new YAHOO.util.Anim(this.el, {opacity: {from: 0.1, to: 1, unit:""}}, dur); a.onComplete.subscribe( function() { tvanim.onComplete(); } ); a.animate(); }, /** * Clean up and invoke callback * @method onComplete */ onComplete: function() { this.callback(); }, /** * toString * @method toString * @return {string} the string representation of the instance */ toString: function() { return "TVFadeIn"; } }; /** * A 1/2 second fade out animation. * @class TVFadeOut * @constructor * @param el {HTMLElement} the element to animate * @param callback {Function} function to invoke when the animation is finished */ YAHOO.widget.TVFadeOut = function(el, callback) { /** * The element to animate * @property el * @type HTMLElement */ this.el = el; /** * the callback to invoke when the animation is complete * @property callback * @type function */ this.callback = callback; }; YAHOO.widget.TVFadeOut.prototype = { /** * Performs the animation * @method animate */ animate: function() { var tvanim = this; var dur = 0.4; var a = new YAHOO.util.Anim(this.el, {opacity: {from: 1, to: 0.1, unit:""}}, dur); a.onComplete.subscribe( function() { tvanim.onComplete(); } ); a.animate(); }, /** * Clean up and invoke callback * @method onComplete */ onComplete: function() { var s = this.el.style; s.display = "none"; s.opacity = 1; s.filter = "alpha(opacity=100)"; this.callback(); }, /** * toString * @method toString * @return {string} the string representation of the instance */ toString: function() { return "TVFadeOut"; } }; YAHOO.register("treeview", YAHOO.widget.TreeView, {version: "2.9.0", build: "2800"}); }, '2.9.0' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-event", "yui2-skin-sam-treeview"], "optional": ["yui2-skin-sam-calendar", "yui2-calendar", "yui2-animation"]}); PK\yRvv32in3/2.9.0/build/yui2-treeview/yui2-treeview-min.jsnu[YUI.add("yui2-treeview",function(b){var a=b.YUI2;(function(){var f=a.util.Dom,d=a.util.Event,h=a.lang,g=a.widget;a.widget.TreeView=function(j,i){if(j){this.init(j)}if(i){this.buildTreeFromObject(i)}else{if(h.trim(this._el.innerHTML)){this.buildTreeFromMarkup(j)}}};var e=g.TreeView;e.prototype={id:null,_el:null,_nodes:null,locked:false,_expandAnim:null,_collapseAnim:null,_animCount:0,maxAnim:2,_hasDblClickSubscriber:false,_dblClickTimer:null,currentFocus:null,singleNodeHighlight:false,_currentlyHighlighted:null,setExpandAnim:function(i){this._expandAnim=(g.TVAnim.isValid(i))?i:null},setCollapseAnim:function(i){this._collapseAnim=(g.TVAnim.isValid(i))?i:null},animateExpand:function(k,l){if(this._expandAnim&&this._animCount0||(f&&this.isDynamic()&&!this.dynamicLoadComplete))}},toggle:function(){if(!this.tree.locked&&(this.hasChildren(true)||this.isDynamic())){if(this.expanded){this.collapse()}else{this.expand()}}},getHtml:function(){this.childrenRendered=false;return['
                    ',this.getNodeHtml(),this.getChildrenHtml(),"
                    "].join("")},getChildrenHtml:function(){var f=[];f[f.length]='
                    ";return f.join("")},renderChildren:function(){var f=this;if(this.isDynamic()&&!this.dynamicLoadComplete){this.isLoading=true;this.tree.locked=true;if(this.dataLoader){setTimeout(function(){f.dataLoader(f,function(){f.loadComplete()})},10)}else{if(this.tree.root.dataLoader){setTimeout(function(){f.tree.root.dataLoader(f,function(){f.loadComplete()})},10)}else{return"Error: data loader not found or not specified."}}return""}else{return this.completeRender()}},completeRender:function(){var g=[];for(var f=0;f=this.depth||g<0){return null}var f=this.parent;while(f.depth>g){f=f.parent}return f},getDepthStyle:function(f){return(this.getAncestor(f).nextSibling)?"ygtvdepthcell":"ygtvblankdepthcell"},getNodeHtml:function(){var g=[];g[g.length]='
                    '}if(this.hasIcon&&this.hasChildren()){g[g.length]=''}else{g[g.length]=''}g[g.length]='
                     
                    ";return g.join("")},getContentHtml:function(){return""},refresh:function(){this.getChildrenEl().innerHTML=this.completeRender();if(this.hasIcon){var f=this.getToggleEl();if(f){f.className=f.className.replace(/\bygtv[lt][nmp]h*\b/gi,this.getStyle())}}},toString:function(){return this._type+" ("+this.index+")"},_focusHighlightedItems:[],_focusedItem:null,_canHaveFocus:function(){return this.getEl().getElementsByTagName("a").length>0},_removeFocus:function(){if(this._focusedItem){c.removeListener(this._focusedItem,"blur");this._focusedItem=null}var f;while((f=this._focusHighlightedItems.shift())){d.removeClass(f,a.widget.TreeView.FOCUS_CLASS_NAME)}},focus:function(){var h=false,f=this;if(this.tree.currentFocus){this.tree.currentFocus._removeFocus()}var g=function(i){if(i.parent){g(i.parent);i.parent.expand()}};g(this);d.getElementsBy(function(i){return(/ygtv(([tl][pmn]h?)|(content))/).test(i.className)},"td",f.getEl().firstChild,function(j){d.addClass(j,a.widget.TreeView.FOCUS_CLASS_NAME);if(!h){var i=j.getElementsByTagName("a");if(i.length){i=i[0];i.focus();f._focusedItem=i;c.on(i,"blur",function(){f.tree.fireEvent("focusChanged",{oldNode:f.tree.currentFocus,newNode:null});f.tree.currentFocus=null;f._removeFocus()});h=true}}f._focusHighlightedItems.push(j)});if(h){this.tree.fireEvent("focusChanged",{oldNode:this.tree.currentFocus,newNode:this});this.tree.currentFocus=this}else{this.tree.fireEvent("focusChanged",{oldNode:f.tree.currentFocus,newNode:null});this.tree.currentFocus=null;this._removeFocus()}return h},getNodeCount:function(){for(var f=0,g=0;f":"";return f.join("")},getNodeDefinition:function(){var f=a.widget.TextNode.superclass.getNodeDefinition.call(this);if(f===false){return false}f.label=this.label;if(this.labelStyle!="ygtvlabel"){f.style=this.labelStyle}if(this.title){f.title=this.title}if(this.href){f.href=this.href}if(this.target!="_self"){f.target=this.target}return f},toString:function(){return a.widget.TextNode.superclass.toString.call(this)+": "+this.label},onLabelClick:function(){return false},refresh:function(){a.widget.TextNode.superclass.refresh.call(this);var f=this.getLabelEl();f.innerHTML=this.label;if(f.tagName.toUpperCase()=="A"){f.href=this.href;f.target=this.target}}})})();a.widget.MenuNode=function(e,d,c){a.widget.MenuNode.superclass.constructor.call(this,e,d,c);this.multiExpand=false};a.extend(a.widget.MenuNode,a.widget.TextNode,{_type:"MenuNode"});(function(){var d=a.util.Dom,e=a.lang,c=a.util.Event;var f=function(j,i,h,g){if(j){this.init(j,i,h);this.initContent(j,g)}};a.widget.HTMLNode=f;a.extend(f,a.widget.Node,{contentStyle:"ygtvhtml",html:null,_type:"HTMLNode",initContent:function(h,g){this.setHtml(h);this.contentElId="ygtvcontentel"+this.index;if(!e.isUndefined(g)){this.hasIcon=g}},setHtml:function(h){this.html=(e.isObject(h)&&"html" in h)?h.html:h;var g=this.getContentEl();if(g){if(h.nodeType&&h.nodeType==1&&h.tagName){g.innerHTML=""}else{g.innerHTML=this.html}}},getContentHtml:function(){if(typeof this.html==="string"){return this.html}else{f._deferredNodes.push(this);if(!f._timer){f._timer=window.setTimeout(function(){var g;while((g=f._deferredNodes.pop())){g.getContentEl().appendChild(g.html)}f._timer=null},0)}return""}},getNodeDefinition:function(){var g=f.superclass.getNodeDefinition.call(this);if(g===false){return false}g.html=this.html;return g}});f._deferredNodes=[];f._timer=null})();(function(){var d=a.util.Dom,e=a.lang,c=a.util.Event,f=a.widget.Calendar;a.widget.DateNode=function(i,h,g){a.widget.DateNode.superclass.constructor.call(this,i,h,g)};a.extend(a.widget.DateNode,a.widget.TextNode,{_type:"DateNode",calendarConfig:null,fillEditorContainer:function(i){var j,h=i.inputContainer;if(e.isUndefined(f)){d.replaceClass(i.editorPanel,"ygtv-edit-DateNode","ygtv-edit-TextNode");a.widget.DateNode.superclass.fillEditorContainer.call(this,i);return}if(i.nodeType!=this._type){i.nodeType=this._type;i.saveOnEnter=false;i.node.destroyEditorContents(i);i.inputObject=j=new f(h.appendChild(document.createElement("div")));if(this.calendarConfig){j.cfg.applyConfig(this.calendarConfig,true);j.cfg.fireQueue()}j.selectEvent.subscribe(function(){this.tree._closeEditor(true)},this,true)}else{j=i.inputObject}i.oldValue=this.label;j.cfg.setProperty("selected",this.label,false);var k=j.cfg.getProperty("DATE_FIELD_DELIMITER");var g=this.label.split(k);j.cfg.setProperty("pagedate",g[j.cfg.getProperty("MDY_MONTH_POSITION")-1]+k+g[j.cfg.getProperty("MDY_YEAR_POSITION")-1]);j.cfg.fireQueue();j.render();j.oDomContainer.focus()},getEditorValue:function(h){if(e.isUndefined(f)){return h.inputElement.value}else{var j=h.inputObject,i=j.getSelectedDates()[0],g=[];g[j.cfg.getProperty("MDY_DAY_POSITION")-1]=i.getDate();g[j.cfg.getProperty("MDY_MONTH_POSITION")-1]=i.getMonth()+1;g[j.cfg.getProperty("MDY_YEAR_POSITION")-1]=i.getFullYear();return g.join(j.cfg.getProperty("DATE_FIELD_DELIMITER"))}},displayEditedValue:function(i,g){var h=g.node;h.label=i;h.getLabelEl().innerHTML=i},getNodeDefinition:function(){var g=a.widget.DateNode.superclass.getNodeDefinition.call(this);if(g===false){return false}if(this.calendarConfig){g.calendarConfig=this.calendarConfig}return g}})})();(function(){var g=a.util.Dom,h=a.lang,d=a.util.Event,f=a.widget.TreeView,e=f.prototype;f.editorData={active:false,whoHasIt:null,nodeType:null,editorPanel:null,inputContainer:null,buttonsContainer:null,node:null,saveOnEnter:true,oldValue:undefined};e.validator=null;e._initEditor=function(){this.createEvent("editorSaveEvent",this);this.createEvent("editorCancelEvent",this)};e._nodeEditing=function(o){if(o.fillEditorContainer&&o.editable){var k,m,n,l,j=f.editorData;j.active=true;j.whoHasIt=this;if(!j.nodeType){j.editorPanel=k=this.getEl().appendChild(document.createElement("div"));g.addClass(k,"ygtv-label-editor");k.tabIndex=0;n=j.buttonsContainer=k.appendChild(document.createElement("div"));g.addClass(n,"ygtv-button-container");l=n.appendChild(document.createElement("button"));g.addClass(l,"ygtvok");l.innerHTML=" ";l=n.appendChild(document.createElement("button"));g.addClass(l,"ygtvcancel");l.innerHTML=" ";d.on(n,"click",function(s){var t=d.getTarget(s),q=f.editorData,r=q.node,p=q.whoHasIt;if(g.hasClass(t,"ygtvok")){d.stopEvent(s);p._closeEditor(true)}if(g.hasClass(t,"ygtvcancel")){d.stopEvent(s);p._closeEditor(false)}});j.inputContainer=k.appendChild(document.createElement("div"));g.addClass(j.inputContainer,"ygtv-input");d.on(k,"keydown",function(s){var r=f.editorData,p=a.util.KeyListener.KEY,q=r.whoHasIt;switch(s.keyCode){case p.ENTER:d.stopEvent(s);if(r.saveOnEnter){q._closeEditor(true)}break;case p.ESCAPE:d.stopEvent(s);q._closeEditor(false);break}})}else{k=j.editorPanel}j.node=o;if(j.nodeType){g.removeClass(k,"ygtv-edit-"+j.nodeType)}g.addClass(k," ygtv-edit-"+o._type);g.setStyle(k,"display","block");g.setXY(k,g.getXY(o.getContentEl()));k.focus();o.fillEditorContainer(j);return true}};e.onEventEditNode=function(j){if(j instanceof a.widget.Node){j.editNode()}else{if(j.node instanceof a.widget.Node){j.node.editNode()}}return false};e._closeEditor=function(l){var j=f.editorData,k=j.node,m=true;if(!k||!j.active){return}if(l){m=j.node.saveEditorValue(j)!==false}else{this.fireEvent("editorCancelEvent",k)}if(m){g.setStyle(j.editorPanel,"display","none");j.active=false;k.focus()}};e._destroyEditor=function(){var j=f.editorData;if(j&&j.nodeType&&(!j.active||j.whoHasIt===this)){d.removeListener(j.editorPanel,"keydown");d.removeListener(j.buttonContainer,"click");j.node.destroyEditorContents(j);document.body.removeChild(j.editorPanel);j.nodeType=j.editorPanel=j.inputContainer=j.buttonsContainer=j.whoHasIt=j.node=null;j.active=false}};var i=a.widget.Node.prototype;i.editable=false;i.editNode=function(){this.tree._nodeEditing(this)};i.fillEditorContainer=null;i.destroyEditorContents=function(j){d.purgeElement(j.inputContainer,true);j.inputContainer.innerHTML=""};i.saveEditorValue=function(j){var l=j.node,m,k=l.tree.validator;m=this.getEditorValue(j);if(h.isFunction(k)){m=k(m,j.oldValue,l);if(h.isUndefined(m)){return false}}if(this.tree.fireEvent("editorSaveEvent",{newValue:m,oldValue:j.oldValue,node:l})!==false){this.displayEditedValue(m,j)}};i.getEditorValue=function(j){};i.displayEditedValue=function(k,j){};var c=a.widget.TextNode.prototype;c.fillEditorContainer=function(k){var j;if(k.nodeType!=this._type){k.nodeType=this._type;k.saveOnEnter=true;k.node.destroyEditorContents(k);k.inputElement=j=k.inputContainer.appendChild(document.createElement("input"))}else{j=k.inputElement}k.oldValue=this.label;j.value=this.label;j.focus();j.select()};c.getEditorValue=function(j){return j.inputElement.value};c.displayEditedValue=function(l,j){var k=j.node;k.label=l;k.getLabelEl().innerHTML=l};c.destroyEditorContents=function(j){j.inputContainer.innerHTML=""}})();a.widget.TVAnim=function(){return{FADE_IN:"TVFadeIn",FADE_OUT:"TVFadeOut",getAnim:function(d,c,e){if(a.widget[d]){return new a.widget[d](c,e)}else{return null}},isValid:function(c){return(a.widget[c])}}}();a.widget.TVFadeIn=function(c,d){this.el=c;this.callback=d};a.widget.TVFadeIn.prototype={animate:function(){var f=this;var e=this.el.style;e.opacity=0.1;e.filter="alpha(opacity=10)";e.display="";var d=0.4;var c=new a.util.Anim(this.el,{opacity:{from:0.1,to:1,unit:""}},d);c.onComplete.subscribe(function(){f.onComplete()});c.animate()},onComplete:function(){this.callback()},toString:function(){return"TVFadeIn"}};a.widget.TVFadeOut=function(c,d){this.el=c;this.callback=d};a.widget.TVFadeOut.prototype={animate:function(){var e=this;var d=0.4;var c=new a.util.Anim(this.el,{opacity:{from:1,to:0.1,unit:""}},d);c.onComplete.subscribe(function(){e.onComplete()});c.animate()},onComplete:function(){var c=this.el.style;c.display="none";c.opacity=1;c.filter="alpha(opacity=100)";this.callback()},toString:function(){return"TVFadeOut"}};a.register("treeview",a.widget.TreeView,{version:"2.9.0",build:"2800"})},"2.9.0",{requires:["yui2-yahoo","yui2-dom","yui2-event","yui2-skin-sam-treeview"],optional:["yui2-skin-sam-calendar","yui2-calendar","yui2-animation"]}); PK\52in3/2.9.0/build/yui2-treeview/yui2-treeview-debug.jsnu[YUI.add('yui2-treeview', function(Y) { var YAHOO = Y.YUI2; /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ (function () { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, Widget = YAHOO.widget; /** * The treeview widget is a generic tree building tool. * @module treeview * @title TreeView Widget * @requires yahoo, dom, event * @optional animation, json, calendar * @namespace YAHOO.widget */ /** * Contains the tree view state data and the root node. * * @class TreeView * @uses YAHOO.util.EventProvider * @constructor * @param {string|HTMLElement} id The id of the element, or the element itself that the tree will be inserted into. * Existing markup in this element, if valid, will be used to build the tree * @param {Array|Object|String} oConfig (optional) If present, it will be used to build the tree via method buildTreeFromObject * */ YAHOO.widget.TreeView = function(id, oConfig) { if (id) { this.init(id); } if (oConfig) { this.buildTreeFromObject(oConfig); } else if (Lang.trim(this._el.innerHTML)) { this.buildTreeFromMarkup(id); } }; var TV = Widget.TreeView; TV.prototype = { /** * The id of tree container element * @property id * @type String */ id: null, /** * The host element for this tree * @property _el * @private * @type HTMLelement */ _el: null, /** * Flat collection of all nodes in this tree. This is a sparse * array, so the length property can't be relied upon for a * node count for the tree. * @property _nodes * @type Node[] * @private */ _nodes: null, /** * We lock the tree control while waiting for the dynamic loader to return * @property locked * @type boolean */ locked: false, /** * The animation to use for expanding children, if any * @property _expandAnim * @type string * @private */ _expandAnim: null, /** * The animation to use for collapsing children, if any * @property _collapseAnim * @type string * @private */ _collapseAnim: null, /** * The current number of animations that are executing * @property _animCount * @type int * @private */ _animCount: 0, /** * The maximum number of animations to run at one time. * @property maxAnim * @type int */ maxAnim: 2, /** * Whether there is any subscriber to dblClickEvent * @property _hasDblClickSubscriber * @type boolean * @private */ _hasDblClickSubscriber: false, /** * Stores the timer used to check for double clicks * @property _dblClickTimer * @type window.timer object * @private */ _dblClickTimer: null, /** * A reference to the Node currently having the focus or null if none. * @property currentFocus * @type YAHOO.widget.Node */ currentFocus: null, /** * If true, only one Node can be highlighted at a time * @property singleNodeHighlight * @type boolean * @default false */ singleNodeHighlight: false, /** * A reference to the Node that is currently highlighted. * It is only meaningful if singleNodeHighlight is enabled * @property _currentlyHighlighted * @type YAHOO.widget.Node * @default null * @private */ _currentlyHighlighted: null, /** * Sets up the animation for expanding children * @method setExpandAnim * @param {string} type the type of animation (acceptable values defined * in YAHOO.widget.TVAnim) */ setExpandAnim: function(type) { this._expandAnim = (Widget.TVAnim.isValid(type)) ? type : null; }, /** * Sets up the animation for collapsing children * @method setCollapseAnim * @param {string} type of animation (acceptable values defined in * YAHOO.widget.TVAnim) */ setCollapseAnim: function(type) { this._collapseAnim = (Widget.TVAnim.isValid(type)) ? type : null; }, /** * Perform the expand animation if configured, or just show the * element if not configured or too many animations are in progress * @method animateExpand * @param el {HTMLElement} the element to animate * @param node {YAHOO.util.Node} the node that was expanded * @return {boolean} true if animation could be invoked, false otherwise */ animateExpand: function(el, node) { this.logger.log("animating expand"); if (this._expandAnim && this._animCount < this.maxAnim) { // this.locked = true; var tree = this; var a = Widget.TVAnim.getAnim(this._expandAnim, el, function() { tree.expandComplete(node); }); if (a) { ++this._animCount; this.fireEvent("animStart", { "node": node, "type": "expand" }); a.animate(); } return true; } return false; }, /** * Perform the collapse animation if configured, or just show the * element if not configured or too many animations are in progress * @method animateCollapse * @param el {HTMLElement} the element to animate * @param node {YAHOO.util.Node} the node that was expanded * @return {boolean} true if animation could be invoked, false otherwise */ animateCollapse: function(el, node) { this.logger.log("animating collapse"); if (this._collapseAnim && this._animCount < this.maxAnim) { // this.locked = true; var tree = this; var a = Widget.TVAnim.getAnim(this._collapseAnim, el, function() { tree.collapseComplete(node); }); if (a) { ++this._animCount; this.fireEvent("animStart", { "node": node, "type": "collapse" }); a.animate(); } return true; } return false; }, /** * Function executed when the expand animation completes * @method expandComplete */ expandComplete: function(node) { this.logger.log("expand complete: " + this.id); --this._animCount; this.fireEvent("animComplete", { "node": node, "type": "expand" }); // this.locked = false; }, /** * Function executed when the collapse animation completes * @method collapseComplete */ collapseComplete: function(node) { this.logger.log("collapse complete: " + this.id); --this._animCount; this.fireEvent("animComplete", { "node": node, "type": "collapse" }); // this.locked = false; }, /** * Initializes the tree * @method init * @parm {string|HTMLElement} id the id of the element that will hold the tree * @private */ init: function(id) { this._el = Dom.get(id); this.id = Dom.generateId(this._el,"yui-tv-auto-id-"); /** * When animation is enabled, this event fires when the animation * starts * @event animStart * @type CustomEvent * @param {YAHOO.widget.Node} oArgs.node the node that is expanding/collapsing * @param {String} oArgs.type the type of animation ("expand" or "collapse") */ this.createEvent("animStart", this); /** * When animation is enabled, this event fires when the animation * completes * @event animComplete * @type CustomEvent * @param {YAHOO.widget.Node} oArgs.node the node that is expanding/collapsing * @param {String} oArgs.type the type of animation ("expand" or "collapse") */ this.createEvent("animComplete", this); /** * Fires when a node is going to be collapsed. Return false to stop * the collapse. * @event collapse * @type CustomEvent * @param {YAHOO.widget.Node} node the node that is collapsing */ this.createEvent("collapse", this); /** * Fires after a node is successfully collapsed. This event will not fire * if the "collapse" event was cancelled. * @event collapseComplete * @type CustomEvent * @param {YAHOO.widget.Node} node the node that was collapsed */ this.createEvent("collapseComplete", this); /** * Fires when a node is going to be expanded. Return false to stop * the collapse. * @event expand * @type CustomEvent * @param {YAHOO.widget.Node} node the node that is expanding */ this.createEvent("expand", this); /** * Fires after a node is successfully expanded. This event will not fire * if the "expand" event was cancelled. * @event expandComplete * @type CustomEvent * @param {YAHOO.widget.Node} node the node that was expanded */ this.createEvent("expandComplete", this); /** * Fires when the Enter key is pressed on a node that has the focus * @event enterKeyPressed * @type CustomEvent * @param {YAHOO.widget.Node} node the node that has the focus */ this.createEvent("enterKeyPressed", this); /** * Fires when the label in a TextNode or MenuNode or content in an HTMLNode receives a Click. * The listener may return false to cancel toggling and focusing on the node. * @event clickEvent * @type CustomEvent * @param oArgs.event {HTMLEvent} The event object * @param oArgs.node {YAHOO.widget.Node} node the node that was clicked */ this.createEvent("clickEvent", this); /** * Fires when the focus receives the focus, when it changes from a Node * to another Node or when it is completely lost (blurred) * @event focusChanged * @type CustomEvent * @param oArgs.oldNode {YAHOO.widget.Node} Node that had the focus or null if none * @param oArgs.newNode {YAHOO.widget.Node} Node that receives the focus or null if none */ this.createEvent('focusChanged',this); /** * Fires when the label in a TextNode or MenuNode or content in an HTMLNode receives a double Click * @event dblClickEvent * @type CustomEvent * @param oArgs.event {HTMLEvent} The event object * @param oArgs.node {YAHOO.widget.Node} node the node that was clicked */ var self = this; this.createEvent("dblClickEvent", { scope:this, onSubscribeCallback: function() { self._hasDblClickSubscriber = true; } }); /** * Custom event that is fired when the text node label is clicked. * The node clicked is provided as an argument * * @event labelClick * @type CustomEvent * @param {YAHOO.widget.Node} node the node clicked * @deprecated use clickEvent or dblClickEvent */ this.createEvent("labelClick", this); /** * Custom event fired when the highlight of a node changes. * The node that triggered the change is provided as an argument: * The status of the highlight can be checked in * nodeRef.highlightState. * Depending on nodeRef.propagateHighlight, other nodes might have changed * @event highlightEvent * @type CustomEvent * @param node {YAHOO.widget.Node} the node that started the change in highlighting state */ this.createEvent("highlightEvent",this); this._nodes = []; // store a global reference TV.trees[this.id] = this; // Set up the root node this.root = new Widget.RootNode(this); var LW = Widget.LogWriter; this.logger = (LW) ? new LW(this.toString()) : YAHOO; this.logger.log("tree init: " + this.id); if (this._initEditor) { this._initEditor(); } // YAHOO.util.Event.onContentReady(this.id, this.handleAvailable, this, true); // YAHOO.util.Event.on(this.id, "click", this.handleClick, this, true); }, //handleAvailable: function() { //var Event = YAHOO.util.Event; //Event.on(this.id, //}, /** * Builds the TreeView from an object. * This is the method called by the constructor to build the tree when it has a second argument. * A tree can be described by an array of objects, each object corresponding to a node. * Node descriptions may contain values for any property of a node plus the following extra properties:
                      *
                    • type: can be one of the following:
                        *
                      • A shortname for a node type ('text','menu','html')
                      • *
                      • The name of a Node class under YAHOO.widget ('TextNode', 'MenuNode', 'DateNode', etc)
                      • *
                      • a reference to an actual class: YAHOO.widget.DateNode
                      • *
                    • *
                    • children: an array containing further node definitions
                    * A string instead of an object will produce a node of type 'text' with the given string as its label. * @method buildTreeFromObject * @param oConfig {Array|Object|String} array containing a full description of the tree. * An object or a string will be turned into an array with the given object or string as its only element. * */ buildTreeFromObject: function (oConfig) { var logger = this.logger; logger.log('Building tree from object'); var build = function (parent, oConfig) { var i, item, node, children, type, NodeType, ThisType; for (i = 0; i < oConfig.length; i++) { item = oConfig[i]; if (Lang.isString(item)) { node = new Widget.TextNode(item, parent); } else if (Lang.isObject(item)) { children = item.children; delete item.children; type = item.type || 'text'; delete item.type; switch (Lang.isString(type) && type.toLowerCase()) { case 'text': node = new Widget.TextNode(item, parent); break; case 'menu': node = new Widget.MenuNode(item, parent); break; case 'html': node = new Widget.HTMLNode(item, parent); break; default: if (Lang.isString(type)) { NodeType = Widget[type]; } else { NodeType = type; } if (Lang.isObject(NodeType)) { for (ThisType = NodeType; ThisType && ThisType !== Widget.Node; ThisType = ThisType.superclass.constructor) {} if (ThisType) { node = new NodeType(item, parent); } else { logger.log('Invalid type in node definition: ' + type,'error'); } } else { logger.log('Invalid type in node definition: ' + type,'error'); } } if (children) { build(node,children); } } else { logger.log('Invalid node definition','error'); } } }; if (!Lang.isArray(oConfig)) { oConfig = [oConfig]; } build(this.root,oConfig); }, /** * Builds the TreeView from existing markup. Markup should consist of <UL> or <OL> elements containing <LI> elements. * Each <LI> can have one element used as label and a second optional element which is to be a <UL> or <OL> * containing nested nodes. * Depending on what the first element of the <LI> element is, the following Nodes will be created:
                      *
                    • plain text: a regular TextNode
                    • *
                    • anchor <A>: a TextNode with its href and target taken from the anchor
                    • *
                    • anything else: an HTMLNode
                    * Only the first outermost (un-)ordered list in the markup and its children will be parsed. * Nodes will be collapsed unless an <LI> tag has a className called 'expanded'. * All other className attributes will be copied over to the Node className property. * If the <LI> element contains an attribute called yuiConfig, its contents should be a JSON-encoded object * as the one used in method buildTreeFromObject. * @method buildTreeFromMarkup * @param id {string|HTMLElement} The id of the element that contains the markup or a reference to it. */ buildTreeFromMarkup: function (id) { this.logger.log('Building tree from existing markup'); var build = function (markup) { var el, child, branch = [], config = {}, label, yuiConfig; // Dom's getFirstChild and getNextSibling skip over text elements for (el = Dom.getFirstChild(markup); el; el = Dom.getNextSibling(el)) { switch (el.tagName.toUpperCase()) { case 'LI': label = ''; config = { expanded: Dom.hasClass(el,'expanded'), title: el.title || el.alt || null, className: Lang.trim(el.className.replace(/\bexpanded\b/,'')) || null }; // I cannot skip over text elements here because I want them for labels child = el.firstChild; if (child.nodeType == 3) { // nodes with only whitespace, tabs and new lines don't count, they are probably just formatting. label = Lang.trim(child.nodeValue.replace(/[\n\t\r]*/g,'')); if (label) { config.type = 'text'; config.label = label; } else { child = Dom.getNextSibling(child); } } if (!label) { if (child.tagName.toUpperCase() == 'A') { config.type = 'text'; config.label = child.innerHTML; config.href = child.href; config.target = child.target; config.title = child.title || child.alt || config.title; } else { config.type = 'html'; var d = document.createElement('div'); d.appendChild(child.cloneNode(true)); config.html = d.innerHTML; config.hasIcon = true; } } // see if after the label it has a further list which will become children of this node. child = Dom.getNextSibling(child); switch (child && child.tagName.toUpperCase()) { case 'UL': case 'OL': config.children = build(child); break; } // if there are further elements or text, it will be ignored. if (YAHOO.lang.JSON) { yuiConfig = el.getAttribute('yuiConfig'); if (yuiConfig) { yuiConfig = YAHOO.lang.JSON.parse(yuiConfig); config = YAHOO.lang.merge(config,yuiConfig); } } branch.push(config); break; case 'UL': case 'OL': this.logger.log('ULs or OLs can only contain LI elements, not other UL or OL. This will not work in some browsers','error'); config = { type: 'text', label: '', children: build(child) }; branch.push(config); break; } } return branch; }; var markup = Dom.getChildrenBy(Dom.get(id),function (el) { var tag = el.tagName.toUpperCase(); return tag == 'UL' || tag == 'OL'; }); if (markup.length) { this.buildTreeFromObject(build(markup[0])); } else { this.logger.log('Markup contains no UL or OL elements','warn'); } }, /** * Returns the TD element where the event has occurred * @method _getEventTargetTdEl * @private */ _getEventTargetTdEl: function (ev) { var target = Event.getTarget(ev); // go up looking for a TD with a className with a ygtv prefix while (target && !(target.tagName.toUpperCase() == 'TD' && Dom.hasClass(target.parentNode,'ygtvrow'))) { target = Dom.getAncestorByTagName(target,'td'); } if (Lang.isNull(target)) { return null; } // If it is a spacer cell, do nothing if (/\bygtv(blank)?depthcell/.test(target.className)) { return null;} // If it has an id, search for the node number and see if it belongs to a node in this tree. if (target.id) { var m = target.id.match(/\bygtv([^\d]*)(.*)/); if (m && m[2] && this._nodes[m[2]]) { return target; } } return null; }, /** * Event listener for click events * @method _onClickEvent * @private */ _onClickEvent: function (ev) { var self = this, td = this._getEventTargetTdEl(ev), node, target, toggle = function (force) { node.focus(); if (force || !node.href) { node.toggle(); try { Event.preventDefault(ev); } catch (e) { // @TODO // For some reason IE8 is providing an event object with // most of the fields missing, but only when clicking on // the node's label, and only when working with inline // editing. This generates a "Member not found" error // in that browser. Determine if this is a browser // bug, or a problem with this code. Already checked to // see if the problem has to do with access the event // in the outer scope, and that isn't the problem. // Maybe the markup for inline editing is broken. } } }; if (!td) { return; } node = this.getNodeByElement(td); if (!node) { return; } // exception to handle deprecated event labelClick // @TODO take another look at this deprecation. It is common for people to // only be interested in the label click, so why make them have to test // the node type to figure out whether the click was on the label? target = Event.getTarget(ev); if (Dom.hasClass(target, node.labelStyle) || Dom.getAncestorByClassName(target,node.labelStyle)) { this.logger.log("onLabelClick " + node.label); this.fireEvent('labelClick',node); } // http://yuilibrary.com/projects/yui2/ticket/2528946 // Ensures that any open editor is closed. // Since the editor is in a separate source which might not be included, // we first need to ensure we have the _closeEditor method available if (this._closeEditor) { this._closeEditor(false); } // If it is a toggle cell, toggle if (/\bygtv[tl][mp]h?h?/.test(td.className)) { toggle(true); } else { if (this._dblClickTimer) { window.clearTimeout(this._dblClickTimer); this._dblClickTimer = null; } else { if (this._hasDblClickSubscriber) { this._dblClickTimer = window.setTimeout(function () { self._dblClickTimer = null; if (self.fireEvent('clickEvent', {event:ev,node:node}) !== false) { toggle(); } }, 200); } else { if (self.fireEvent('clickEvent', {event:ev,node:node}) !== false) { toggle(); } } } } }, /** * Event listener for double-click events * @method _onDblClickEvent * @private */ _onDblClickEvent: function (ev) { if (!this._hasDblClickSubscriber) { return; } var td = this._getEventTargetTdEl(ev); if (!td) {return;} if (!(/\bygtv[tl][mp]h?h?/.test(td.className))) { this.fireEvent('dblClickEvent', {event:ev, node:this.getNodeByElement(td)}); if (this._dblClickTimer) { window.clearTimeout(this._dblClickTimer); this._dblClickTimer = null; } } }, /** * Event listener for mouse over events * @method _onMouseOverEvent * @private */ _onMouseOverEvent:function (ev) { var target; if ((target = this._getEventTargetTdEl(ev)) && (target = this.getNodeByElement(target)) && (target = target.getToggleEl())) { target.className = target.className.replace(/\bygtv([lt])([mp])\b/gi,'ygtv$1$2h'); } }, /** * Event listener for mouse out events * @method _onMouseOutEvent * @private */ _onMouseOutEvent: function (ev) { var target; if ((target = this._getEventTargetTdEl(ev)) && (target = this.getNodeByElement(target)) && (target = target.getToggleEl())) { target.className = target.className.replace(/\bygtv([lt])([mp])h\b/gi,'ygtv$1$2'); } }, /** * Event listener for key down events * @method _onKeyDownEvent * @private */ _onKeyDownEvent: function (ev) { var target = Event.getTarget(ev), node = this.getNodeByElement(target), newNode = node, KEY = YAHOO.util.KeyListener.KEY; switch(ev.keyCode) { case KEY.UP: this.logger.log('UP'); do { if (newNode.previousSibling) { newNode = newNode.previousSibling; } else { newNode = newNode.parent; } } while (newNode && !newNode._canHaveFocus()); if (newNode) { newNode.focus(); } Event.preventDefault(ev); break; case KEY.DOWN: this.logger.log('DOWN'); do { if (newNode.nextSibling) { newNode = newNode.nextSibling; } else { newNode.expand(); newNode = (newNode.children.length || null) && newNode.children[0]; } } while (newNode && !newNode._canHaveFocus); if (newNode) { newNode.focus();} Event.preventDefault(ev); break; case KEY.LEFT: this.logger.log('LEFT'); do { if (newNode.parent) { newNode = newNode.parent; } else { newNode = newNode.previousSibling; } } while (newNode && !newNode._canHaveFocus()); if (newNode) { newNode.focus();} Event.preventDefault(ev); break; case KEY.RIGHT: this.logger.log('RIGHT'); var self = this, moveFocusRight, focusOnExpand = function (newNode) { self.unsubscribe('expandComplete',focusOnExpand); moveFocusRight(newNode); }; moveFocusRight = function (newNode) { do { if (newNode.isDynamic() && !newNode.childrenRendered) { self.subscribe('expandComplete',focusOnExpand); newNode.expand(); newNode = null; break; } else { newNode.expand(); if (newNode.children.length) { newNode = newNode.children[0]; } else { newNode = newNode.nextSibling; } } } while (newNode && !newNode._canHaveFocus()); if (newNode) { newNode.focus();} }; moveFocusRight(newNode); Event.preventDefault(ev); break; case KEY.ENTER: this.logger.log('ENTER: ' + newNode.href); if (node.href) { if (node.target) { window.open(node.href,node.target); } else { window.location(node.href); } } else { node.toggle(); } this.fireEvent('enterKeyPressed',node); Event.preventDefault(ev); break; case KEY.HOME: this.logger.log('HOME'); newNode = this.getRoot(); if (newNode.children.length) {newNode = newNode.children[0];} if (newNode._canHaveFocus()) { newNode.focus(); } Event.preventDefault(ev); break; case KEY.END: this.logger.log('END'); newNode = newNode.parent.children; newNode = newNode[newNode.length -1]; if (newNode._canHaveFocus()) { newNode.focus(); } Event.preventDefault(ev); break; // case KEY.PAGE_UP: // this.logger.log('PAGE_UP'); // break; // case KEY.PAGE_DOWN: // this.logger.log('PAGE_DOWN'); // break; case 107: // plus key case 187: // plus key if (ev.shiftKey) { this.logger.log('Shift-PLUS'); node.parent.expandAll(); } else { this.logger.log('PLUS'); node.expand(); } break; case 109: // minus key case 189: // minus key if (ev.shiftKey) { this.logger.log('Shift-MINUS'); node.parent.collapseAll(); } else { this.logger.log('MINUS'); node.collapse(); } break; default: break; } }, /** * Renders the tree boilerplate and visible nodes * @method render */ render: function() { var html = this.root.getHtml(), el = this.getEl(); el.innerHTML = html; if (!this._hasEvents) { Event.on(el, 'click', this._onClickEvent, this, true); Event.on(el, 'dblclick', this._onDblClickEvent, this, true); Event.on(el, 'mouseover', this._onMouseOverEvent, this, true); Event.on(el, 'mouseout', this._onMouseOutEvent, this, true); Event.on(el, 'keydown', this._onKeyDownEvent, this, true); } this._hasEvents = true; }, /** * Returns the tree's host element * @method getEl * @return {HTMLElement} the host element */ getEl: function() { if (! this._el) { this._el = Dom.get(this.id); } return this._el; }, /** * Nodes register themselves with the tree instance when they are created. * @method regNode * @param node {Node} the node to register * @private */ regNode: function(node) { this._nodes[node.index] = node; }, /** * Returns the root node of this tree * @method getRoot * @return {Node} the root node */ getRoot: function() { return this.root; }, /** * Configures this tree to dynamically load all child data * @method setDynamicLoad * @param {function} fnDataLoader the function that will be called to get the data * @param iconMode {int} configures the icon that is displayed when a dynamic * load node is expanded the first time without children. By default, the * "collapse" icon will be used. If set to 1, the leaf node icon will be * displayed. */ setDynamicLoad: function(fnDataLoader, iconMode) { this.root.setDynamicLoad(fnDataLoader, iconMode); }, /** * Expands all child nodes. Note: this conflicts with the "multiExpand" * node property. If expand all is called in a tree with nodes that * do not allow multiple siblings to be displayed, only the last sibling * will be expanded. * @method expandAll */ expandAll: function() { if (!this.locked) { this.root.expandAll(); } }, /** * Collapses all expanded child nodes in the entire tree. * @method collapseAll */ collapseAll: function() { if (!this.locked) { this.root.collapseAll(); } }, /** * Returns a node in the tree that has the specified index (this index * is created internally, so this function probably will only be used * in html generated for a given node.) * @method getNodeByIndex * @param {int} nodeIndex the index of the node wanted * @return {Node} the node with index=nodeIndex, null if no match */ getNodeByIndex: function(nodeIndex) { var n = this._nodes[nodeIndex]; return (n) ? n : null; }, /** * Returns a node that has a matching property and value in the data * object that was passed into its constructor. * @method getNodeByProperty * @param {object} property the property to search (usually a string) * @param {object} value the value we want to find (usuall an int or string) * @return {Node} the matching node, null if no match */ getNodeByProperty: function(property, value) { for (var i in this._nodes) { if (this._nodes.hasOwnProperty(i)) { var n = this._nodes[i]; if ((property in n && n[property] == value) || (n.data && value == n.data[property])) { return n; } } } return null; }, /** * Returns a collection of nodes that have a matching property * and value in the data object that was passed into its constructor. * @method getNodesByProperty * @param {object} property the property to search (usually a string) * @param {object} value the value we want to find (usuall an int or string) * @return {Array} the matching collection of nodes, null if no match */ getNodesByProperty: function(property, value) { var values = []; for (var i in this._nodes) { if (this._nodes.hasOwnProperty(i)) { var n = this._nodes[i]; if ((property in n && n[property] == value) || (n.data && value == n.data[property])) { values.push(n); } } } return (values.length) ? values : null; }, /** * Returns a collection of nodes that have passed the test function * passed as its only argument. * The function will receive a reference to each node to be tested. * @method getNodesBy * @param {function} a boolean function that receives a Node instance and returns true to add the node to the results list * @return {Array} the matching collection of nodes, null if no match */ getNodesBy: function(fn) { var values = []; for (var i in this._nodes) { if (this._nodes.hasOwnProperty(i)) { var n = this._nodes[i]; if (fn(n)) { values.push(n); } } } return (values.length) ? values : null; }, /** * Returns the treeview node reference for an ancestor element * of the node, or null if it is not contained within any node * in this tree. * @method getNodeByElement * @param el {HTMLElement} the element to test * @return {YAHOO.widget.Node} a node reference or null */ getNodeByElement: function(el) { var p=el, m, re=/ygtv([^\d]*)(.*)/; do { if (p && p.id) { m = p.id.match(re); if (m && m[2]) { return this.getNodeByIndex(m[2]); } } p = p.parentNode; if (!p || !p.tagName) { break; } } while (p.id !== this.id && p.tagName.toLowerCase() !== "body"); return null; }, /** * When in singleNodeHighlight it returns the node highlighted * or null if none. Returns null if singleNodeHighlight is false. * @method getHighlightedNode * @return {YAHOO.widget.Node} a node reference or null */ getHighlightedNode: function() { return this._currentlyHighlighted; }, /** * Removes the node and its children, and optionally refreshes the * branch of the tree that was affected. * @method removeNode * @param {Node} node to remove * @param {boolean} autoRefresh automatically refreshes branch if true * @return {boolean} False is there was a problem, true otherwise. */ removeNode: function(node, autoRefresh) { // Don't delete the root node if (node.isRoot()) { return false; } // Get the branch that we may need to refresh var p = node.parent; if (p.parent) { p = p.parent; } // Delete the node and its children this._deleteNode(node); // Refresh the parent of the parent if (autoRefresh && p && p.childrenRendered) { p.refresh(); } return true; }, /** * wait until the animation is complete before deleting * to avoid javascript errors * @method _removeChildren_animComplete * @param o the custom event payload * @private */ _removeChildren_animComplete: function(o) { this.unsubscribe(this._removeChildren_animComplete); this.removeChildren(o.node); }, /** * Deletes this nodes child collection, recursively. Also collapses * the node, and resets the dynamic load flag. The primary use for * this method is to purge a node and allow it to fetch its data * dynamically again. * @method removeChildren * @param {Node} node the node to purge */ removeChildren: function(node) { if (node.expanded) { // wait until the animation is complete before deleting to // avoid javascript errors if (this._collapseAnim) { this.subscribe("animComplete", this._removeChildren_animComplete, this, true); Widget.Node.prototype.collapse.call(node); return; } node.collapse(); } this.logger.log("Removing children for " + node); while (node.children.length) { this._deleteNode(node.children[0]); } if (node.isRoot()) { Widget.Node.prototype.expand.call(node); } node.childrenRendered = false; node.dynamicLoadComplete = false; node.updateIcon(); }, /** * Deletes the node and recurses children * @method _deleteNode * @private */ _deleteNode: function(node) { // Remove all the child nodes first this.removeChildren(node); // Remove the node from the tree this.popNode(node); }, /** * Removes the node from the tree, preserving the child collection * to make it possible to insert the branch into another part of the * tree, or another tree. * @method popNode * @param {Node} node to remove */ popNode: function(node) { var p = node.parent; // Update the parent's collection of children var a = []; for (var i=0, len=p.children.length;i