4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
17 window["undefined"] = window["undefined"];
21 * Roo core utilities and functions.
26 * Copies all the properties of config to obj.
27 * @param {Object} obj The receiver of the properties
28 * @param {Object} config The source of the properties
29 * @param {Object} defaults A different object that will also be applied for default values
30 * @return {Object} returns obj
35 Roo.apply = function(o, c, defaults){
37 // no "this" reference for friendly out of scope calls
38 Roo.apply(o, defaults);
40 if(o && c && typeof c == 'object'){
51 var ua = navigator.userAgent.toLowerCase();
53 var isStrict = document.compatMode == "CSS1Compat",
54 isOpera = ua.indexOf("opera") > -1,
55 isSafari = (/webkit|khtml/).test(ua),
56 isFirefox = ua.indexOf("firefox") > -1,
57 isIE = ua.indexOf("msie") > -1,
58 isIE7 = ua.indexOf("msie 7") > -1,
59 isIE11 = /trident.*rv\:11\./.test(ua),
60 isEdge = ua.indexOf("edge") > -1,
61 isGecko = !isSafari && ua.indexOf("gecko") > -1,
62 isBorderBox = isIE && !isStrict,
63 isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
64 isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
65 isLinux = (ua.indexOf("linux") != -1),
66 isSecure = window.location.href.toLowerCase().indexOf("https") === 0,
67 isIOS = /iphone|ipad/.test(ua),
68 isAndroid = /android/.test(ua),
69 isTouch = (function() {
71 if (ua.indexOf('chrome') != -1 && ua.indexOf('android') == -1) {
72 window.addEventListener('touchstart', function __set_has_touch__ () {
74 window.removeEventListener('touchstart', __set_has_touch__);
76 return false; // no touch on chrome!?
78 document.createEvent("TouchEvent");
85 // remove css image flicker
88 document.execCommand("BackgroundImageCache", false, true);
94 * True if the browser is in strict mode
99 * True if the page is running over SSL
104 * True when the document is fully initialized and ready for action
109 * Turn on debugging output (currently only the factory uses this)
116 * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
119 enableGarbageCollector : true,
122 * True to automatically purge event listeners after uncaching an element (defaults to false).
123 * Note: this only happens if enableGarbageCollector is true.
126 enableListenerCollection:false,
129 * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
130 * the IE insecure content warning (defaults to javascript:false).
133 SSL_SECURE_URL : "javascript:false",
136 * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
137 * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
140 BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
142 emptyFn : function(){},
145 * Copies all the properties of config to obj if they don't already exist.
146 * @param {Object} obj The receiver of the properties
147 * @param {Object} config The source of the properties
148 * @return {Object} returns obj
150 applyIf : function(o, c){
153 if(typeof o[p] == "undefined"){ o[p] = c[p]; }
160 * Applies event listeners to elements by selectors when the document is ready.
161 * The event name is specified with an @ suffix.
164 // add a listener for click on all anchors in element with id foo
165 '#foo a@click' : function(e, t){
169 // add the same listener to multiple selectors (separated by comma BEFORE the @)
170 '#foo a, #bar span.some-class@mouseover' : function(){
175 * @param {Object} obj The list of behaviors to apply
177 addBehaviors : function(o){
179 Roo.onReady(function(){
184 var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
186 var parts = b.split('@');
187 if(parts[1]){ // for Object prototype breakers
190 cache[s] = Roo.select(s);
192 cache[s].on(parts[1], o[b]);
199 * Generates unique ids. If the element already has an id, it is unchanged
200 * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
201 * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
202 * @return {String} The generated Id.
204 id : function(el, prefix){
205 prefix = prefix || "roo-gen";
207 var id = prefix + (++idSeed);
208 return el ? (el.id ? el.id : (el.id = id)) : id;
213 * Extends one class with another class and optionally overrides members with the passed literal. This class
214 * also adds the function "override()" to the class that can be used to override
215 * members on an instance.
216 * @param {Object} subclass The class inheriting the functionality
217 * @param {Object} superclass The class being extended
218 * @param {Object} overrides (optional) A literal with members
223 var io = function(o){
228 return function(sb, sp, overrides){
229 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
232 sb = function(){sp.apply(this, arguments);};
234 var F = function(){}, sbp, spp = sp.prototype;
236 sbp = sb.prototype = new F();
240 if(spp.constructor == Object.prototype.constructor){
245 sb.override = function(o){
249 Roo.override(sb, overrides);
255 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
257 Roo.override(MyClass, {
258 newMethod1: function(){
261 newMethod2: function(foo){
266 * @param {Object} origclass The class to override
267 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
268 * containing one or more methods.
271 override : function(origclass, overrides){
273 var p = origclass.prototype;
274 for(var method in overrides){
275 p[method] = overrides[method];
280 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
282 Roo.namespace('Company', 'Company.data');
283 Company.Widget = function() { ... }
284 Company.data.CustomStore = function(config) { ... }
286 * @param {String} namespace1
287 * @param {String} namespace2
288 * @param {String} etc
291 namespace : function(){
292 var a=arguments, o=null, i, j, d, rt;
293 for (i=0; i<a.length; ++i) {
297 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
298 for (j=1; j<d.length; ++j) {
299 o[d[j]]=o[d[j]] || {};
305 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
307 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
308 Roo.factory(conf, Roo.data);
310 * @param {String} classname
311 * @param {String} namespace (optional)
315 factory : function(c, ns)
317 // no xtype, no ns or c.xns - or forced off by c.xns
318 if (!c.xtype || (!ns && !c.xns) || (c.xns === false)) { // not enough info...
321 ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
322 if (c.constructor == ns[c.xtype]) {// already created...
326 if (Roo.debug) { Roo.log("Roo.Factory(" + c.xtype + ")"); }
327 var ret = new ns[c.xtype](c);
331 c.xns = false; // prevent recursion..
335 * Logs to console if it can.
337 * @param {String|Object} string
342 if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
349 * Takes an object and converts it to an encoded URL. e.g. Roo.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2". Optionally, property values can be arrays, instead of keys and the resulting string that's returned will contain a name/value pair for each array value.
353 urlEncode : function(o){
359 var ov = o[key], k = Roo.encodeURIComponent(key);
360 var type = typeof ov;
361 if(type == 'undefined'){
363 }else if(type != "function" && type != "object"){
364 buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
365 }else if(ov instanceof Array){
367 for(var i = 0, len = ov.length; i < len; i++) {
368 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
379 * Safe version of encodeURIComponent
380 * @param {String} data
384 encodeURIComponent : function (data)
387 return encodeURIComponent(data);
388 } catch(e) {} // should be an uri encode error.
390 if (data == '' || data == null){
393 // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
394 function nibble_to_hex(nibble){
395 var chars = '0123456789ABCDEF';
396 return chars.charAt(nibble);
398 data = data.toString();
400 for(var i=0; i<data.length; i++){
401 var c = data.charCodeAt(i);
402 var bs = new Array();
405 bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
406 bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
407 bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
408 bs[3] = 0x80 | (c & 0x3F);
409 }else if (c > 0x800){
411 bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
412 bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
413 bs[2] = 0x80 | (c & 0x3F);
416 bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
417 bs[1] = 0x80 | (c & 0x3F);
422 for(var j=0; j<bs.length; j++){
424 var hex = nibble_to_hex((b & 0xF0) >>> 4)
425 + nibble_to_hex(b &0x0F);
434 * Takes an encoded URL and and converts it to an object. e.g. Roo.urlDecode("foo=1&bar=2"); would return {foo: 1, bar: 2} or Roo.urlDecode("foo=1&bar=2&bar=3&bar=4", true); would return {foo: 1, bar: [2, 3, 4]}.
435 * @param {String} string
436 * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
437 * @return {Object} A literal with members
439 urlDecode : function(string, overwrite){
440 if(!string || !string.length){
444 var pairs = string.split('&');
445 var pair, name, value;
446 for(var i = 0, len = pairs.length; i < len; i++){
447 pair = pairs[i].split('=');
448 name = decodeURIComponent(pair[0]);
449 value = decodeURIComponent(pair[1]);
450 if(overwrite !== true){
451 if(typeof obj[name] == "undefined"){
453 }else if(typeof obj[name] == "string"){
454 obj[name] = [obj[name]];
455 obj[name].push(value);
457 obj[name].push(value);
467 * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
468 * passed array is not really an array, your function is called once with it.
469 * The supplied function is called with (Object item, Number index, Array allItems).
470 * @param {Array/NodeList/Mixed} array
471 * @param {Function} fn
472 * @param {Object} scope
474 each : function(array, fn, scope){
475 if(typeof array.length == "undefined" || typeof array == "string"){
478 for(var i = 0, len = array.length; i < len; i++){
479 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
484 combine : function(){
485 var as = arguments, l = as.length, r = [];
486 for(var i = 0; i < l; i++){
488 if(a instanceof Array){
490 }else if(a.length !== undefined && !a.substr){
491 r = r.concat(Array.prototype.slice.call(a, 0));
500 * Escapes the passed string for use in a regular expression
501 * @param {String} str
504 escapeRe : function(s) {
505 return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
509 callback : function(cb, scope, args, delay){
510 if(typeof cb == "function"){
512 cb.defer(delay, scope, args || []);
514 cb.apply(scope, args || []);
520 * Return the dom node for the passed string (id), dom node, or Roo.Element
521 * @param {String/HTMLElement/Roo.Element} el
522 * @return HTMLElement
524 getDom : function(el){
528 return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
532 * Shorthand for {@link Roo.ComponentMgr#get}
534 * @return Roo.Component
536 getCmp : function(id){
537 return Roo.ComponentMgr.get(id);
540 num : function(v, defaultValue){
541 if(typeof v != 'number'){
547 destroy : function(){
548 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
552 as.removeAllListeners();
556 if(typeof as.purgeListeners == 'function'){
559 if(typeof as.destroy == 'function'){
566 // inpired by a similar function in mootools library
568 * Returns the type of object that is passed in. If the object passed in is null or undefined it
569 * return false otherwise it returns one of the following values:<ul>
570 * <li><b>string</b>: If the object passed is a string</li>
571 * <li><b>number</b>: If the object passed is a number</li>
572 * <li><b>boolean</b>: If the object passed is a boolean value</li>
573 * <li><b>function</b>: If the object passed is a function reference</li>
574 * <li><b>object</b>: If the object passed is an object</li>
575 * <li><b>array</b>: If the object passed is an array</li>
576 * <li><b>regexp</b>: If the object passed is a regular expression</li>
577 * <li><b>element</b>: If the object passed is a DOM Element</li>
578 * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
579 * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
580 * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
581 * @param {Mixed} object
585 if(o === undefined || o === null){
592 if(t == 'object' && o.nodeName) {
594 case 1: return 'element';
595 case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
598 if(t == 'object' || t == 'function') {
599 switch(o.constructor) {
600 case Array: return 'array';
601 case RegExp: return 'regexp';
603 if(typeof o.length == 'number' && typeof o.item == 'function') {
611 * Returns true if the passed value is null, undefined or an empty string (optional).
612 * @param {Mixed} value The value to test
613 * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
616 isEmpty : function(v, allowBlank){
617 return v === null || v === undefined || (!allowBlank ? v === '' : false);
625 isFirefox : isFirefox,
637 isBorderBox : isBorderBox,
639 isWindows : isWindows,
647 isAndroid : isAndroid,
652 * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
653 * you may want to set this to true.
656 useShims : ((isIE && !isIE7) || (isGecko && isMac)),
661 * Selects a single element as a Roo Element
662 * This is about as close as you can get to jQuery's $('do crazy stuff')
663 * @param {String} selector The selector/xpath query
664 * @param {Node} root (optional) The start of the query (defaults to document).
665 * @return {Roo.Element}
667 selectNode : function(selector, root)
669 var node = Roo.DomQuery.selectNode(selector,root);
670 return node ? Roo.get(node) : new Roo.Element(false);
673 * Find the current bootstrap width Grid size
674 * Note xs is the default for smaller.. - this is currently used by grids to render correct columns
675 * @returns {String} (xs|sm|md|lg|xl)
678 getGridSize : function()
680 var w = Roo.lib.Dom.getViewWidth();
701 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
702 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout",
705 "Roo.bootstrap.dash");
708 * Ext JS Library 1.1.1
709 * Copyright(c) 2006-2007, Ext JS, LLC.
711 * Originally Released Under LGPL - original licence link has changed is not relivant.
714 * <script type="text/javascript">
718 // wrappedn so fnCleanup is not in global scope...
720 function fnCleanUp() {
721 var p = Function.prototype;
722 delete p.createSequence;
724 delete p.createDelegate;
725 delete p.createCallback;
726 delete p.createInterceptor;
728 window.detachEvent("onunload", fnCleanUp);
730 window.attachEvent("onunload", fnCleanUp);
737 * These functions are available on every Function object (any JavaScript function).
739 Roo.apply(Function.prototype, {
741 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
742 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
743 * Will create a function that is bound to those 2 args.
744 * @return {Function} The new function
746 createCallback : function(/*args...*/){
747 // make args available, in function below
748 var args = arguments;
751 return method.apply(window, args);
756 * Creates a delegate (callback) that sets the scope to obj.
757 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
758 * Will create a function that is automatically scoped to this.
759 * @param {Object} obj (optional) The object for which the scope is set
760 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
761 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
762 * if a number the args are inserted at the specified position
763 * @return {Function} The new function
765 createDelegate : function(obj, args, appendArgs){
768 var callArgs = args || arguments;
769 if(appendArgs === true){
770 callArgs = Array.prototype.slice.call(arguments, 0);
771 callArgs = callArgs.concat(args);
772 }else if(typeof appendArgs == "number"){
773 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
774 var applyArgs = [appendArgs, 0].concat(args); // create method call params
775 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
777 return method.apply(obj || window, callArgs);
782 * Calls this function after the number of millseconds specified.
783 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
784 * @param {Object} obj (optional) The object for which the scope is set
785 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
786 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
787 * if a number the args are inserted at the specified position
788 * @return {Number} The timeout id that can be used with clearTimeout
790 defer : function(millis, obj, args, appendArgs){
791 var fn = this.createDelegate(obj, args, appendArgs);
793 return setTimeout(fn, millis);
799 * Create a combined function call sequence of the original function + the passed function.
800 * The resulting function returns the results of the original function.
801 * The passed fcn is called with the parameters of the original function
802 * @param {Function} fcn The function to sequence
803 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
804 * @return {Function} The new function
806 createSequence : function(fcn, scope){
807 if(typeof fcn != "function"){
812 var retval = method.apply(this || window, arguments);
813 fcn.apply(scope || this || window, arguments);
819 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
820 * The resulting function returns the results of the original function.
821 * The passed fcn is called with the parameters of the original function.
823 * @param {Function} fcn The function to call before the original
824 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
825 * @return {Function} The new function
827 createInterceptor : function(fcn, scope){
828 if(typeof fcn != "function"){
835 if(fcn.apply(scope || this || window, arguments) === false){
838 return method.apply(this || window, arguments);
844 * Ext JS Library 1.1.1
845 * Copyright(c) 2006-2007, Ext JS, LLC.
847 * Originally Released Under LGPL - original licence link has changed is not relivant.
850 * <script type="text/javascript">
853 Roo.applyIf(String, {
858 * Escapes the passed string for ' and \
859 * @param {String} string The string to escape
860 * @return {String} The escaped string
863 escape : function(string) {
864 return string.replace(/('|\\)/g, "\\$1");
868 * Pads the left side of a string with a specified character. This is especially useful
869 * for normalizing number and date strings. Example usage:
871 var s = String.leftPad('123', 5, '0');
872 // s now contains the string: '00123'
874 * @param {String} string The original string
875 * @param {Number} size The total length of the output string
876 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
877 * @return {String} The padded string
880 leftPad : function (val, size, ch) {
881 var result = new String(val);
882 if(ch === null || ch === undefined || ch === '') {
885 while (result.length < size) {
886 result = ch + result;
892 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
893 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
895 var cls = 'my-class', text = 'Some text';
896 var s = String.format('<div class="{0}">{1}</div>', cls, text);
897 // s now contains the string: '<div class="my-class">Some text</div>'
899 * @param {String} string The tokenized string to be formatted
900 * @param {String} value1 The value to replace token {0}
901 * @param {String} value2 Etc...
902 * @return {String} The formatted string
905 format : function(format){
906 var args = Array.prototype.slice.call(arguments, 1);
907 return format.replace(/\{(\d+)\}/g, function(m, i){
908 return Roo.util.Format.htmlEncode(args[i]);
916 * Utility function that allows you to easily switch a string between two alternating values. The passed value
917 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
918 * they are already different, the first value passed in is returned. Note that this method returns the new value
919 * but does not change the current string.
921 // alternate sort directions
922 sort = sort.toggle('ASC', 'DESC');
924 // instead of conditional logic:
925 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
927 * @param {String} value The value to compare to the current string
928 * @param {String} other The new value to use if the string already equals the first value passed in
929 * @return {String} The new value
932 String.prototype.toggle = function(value, other){
933 return this == value ? other : value;
938 * Remove invalid unicode characters from a string
940 * @return {String} The clean string
942 String.prototype.unicodeClean = function () {
943 return this.replace(/[\s\S]/g,
944 function(character) {
945 if (character.charCodeAt()< 256) {
949 encodeURIComponent(character);
960 * Ext JS Library 1.1.1
961 * Copyright(c) 2006-2007, Ext JS, LLC.
963 * Originally Released Under LGPL - original licence link has changed is not relivant.
966 * <script type="text/javascript">
972 Roo.applyIf(Number.prototype, {
974 * Checks whether or not the current number is within a desired range. If the number is already within the
975 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
976 * exceeded. Note that this method returns the constrained value but does not change the current number.
977 * @param {Number} min The minimum number in the range
978 * @param {Number} max The maximum number in the range
979 * @return {Number} The constrained value if outside the range, otherwise the current value
981 constrain : function(min, max){
982 return Math.min(Math.max(this, min), max);
986 * Ext JS Library 1.1.1
987 * Copyright(c) 2006-2007, Ext JS, LLC.
989 * Originally Released Under LGPL - original licence link has changed is not relivant.
992 * <script type="text/javascript">
997 Roo.applyIf(Array.prototype, {
1000 * Checks whether or not the specified object exists in the array.
1001 * @param {Object} o The object to check for
1002 * @return {Number} The index of o in the array (or -1 if it is not found)
1004 indexOf : function(o){
1005 for (var i = 0, len = this.length; i < len; i++){
1006 if(this[i] == o) { return i; }
1012 * Removes the specified object from the array. If the object is not found nothing happens.
1013 * @param {Object} o The object to remove
1015 remove : function(o){
1016 var index = this.indexOf(o);
1018 this.splice(index, 1);
1022 * Map (JS 1.6 compatibility)
1023 * @param {Function} function to call
1025 map : function(fun )
1027 var len = this.length >>> 0;
1028 if (typeof fun != "function") {
1029 throw new TypeError();
1031 var res = new Array(len);
1032 var thisp = arguments[1];
1033 for (var i = 0; i < len; i++)
1036 res[i] = fun.call(thisp, this[i], i, this);
1044 * @param {Array} o The array to compare to
1045 * @returns {Boolean} true if the same
1047 equals : function(b)
1049 // https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
1056 if (this.length !== b.length) {
1060 // sort?? a.sort().equals(b.sort());
1062 for (var i = 0; i < this.length; ++i) {
1063 if (this[i] !== b[i]) {
1075 * Ext JS Library 1.1.1
1076 * Copyright(c) 2006-2007, Ext JS, LLC.
1078 * Originally Released Under LGPL - original licence link has changed is not relivant.
1081 * <script type="text/javascript">
1087 * The date parsing and format syntax is a subset of
1088 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
1089 * supported will provide results equivalent to their PHP versions.
1091 * Following is the list of all currently supported formats:
1094 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
1096 Format Output Description
1097 ------ ---------- --------------------------------------------------------------
1098 d 10 Day of the month, 2 digits with leading zeros
1099 D Wed A textual representation of a day, three letters
1100 j 10 Day of the month without leading zeros
1101 l Wednesday A full textual representation of the day of the week
1102 S th English ordinal day of month suffix, 2 chars (use with j)
1103 w 3 Numeric representation of the day of the week
1104 z 9 The julian date, or day of the year (0-365)
1105 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1106 F January A full textual representation of the month
1107 m 01 Numeric representation of a month, with leading zeros
1108 M Jan Month name abbreviation, three letters
1109 n 1 Numeric representation of a month, without leading zeros
1110 t 31 Number of days in the given month
1111 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1112 Y 2007 A full numeric representation of a year, 4 digits
1113 y 07 A two digit representation of a year
1114 a pm Lowercase Ante meridiem and Post meridiem
1115 A PM Uppercase Ante meridiem and Post meridiem
1116 g 3 12-hour format of an hour without leading zeros
1117 G 15 24-hour format of an hour without leading zeros
1118 h 03 12-hour format of an hour with leading zeros
1119 H 15 24-hour format of an hour with leading zeros
1120 i 05 Minutes with leading zeros
1121 s 01 Seconds, with leading zeros
1122 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1123 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1124 T CST Timezone setting of the machine running the code
1125 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1128 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1130 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1131 document.write(dt.format('Y-m-d')); //2007-01-10
1132 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1133 document.write(dt.format('l, \\t\\he dS of F Y h:i:s A')); //Wednesday, the 10th of January 2007 03:05:01 PM
1136 * Here are some standard date/time patterns that you might find helpful. They
1137 * are not part of the source of Date.js, but to use them you can simply copy this
1138 * block of code into any script that is included after Date.js and they will also become
1139 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1142 ISO8601Long:"Y-m-d H:i:s",
1143 ISO8601Short:"Y-m-d",
1145 LongDate: "l, F d, Y",
1146 FullDateTime: "l, F d, Y g:i:s A",
1149 LongTime: "g:i:s A",
1150 SortableDateTime: "Y-m-d\\TH:i:s",
1151 UniversalSortableDateTime: "Y-m-d H:i:sO",
1158 var dt = new Date();
1159 document.write(dt.format(Date.patterns.ShortDate));
1164 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1165 * They generate precompiled functions from date formats instead of parsing and
1166 * processing the pattern every time you format a date. These functions are available
1167 * on every Date object (any javascript function).
1169 * The original article and download are here:
1170 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1177 Returns the number of milliseconds between this date and date
1178 @param {Date} date (optional) Defaults to now
1179 @return {Number} The diff in milliseconds
1180 @member Date getElapsed
1182 Date.prototype.getElapsed = function(date) {
1183 return Math.abs((date || new Date()).getTime()-this.getTime());
1185 // was in date file..
1189 Date.parseFunctions = {count:0};
1191 Date.parseRegexes = [];
1193 Date.formatFunctions = {count:0};
1196 Date.prototype.dateFormat = function(format) {
1197 if (Date.formatFunctions[format] == null) {
1198 Date.createNewFormat(format);
1200 var func = Date.formatFunctions[format];
1201 return this[func]();
1206 * Formats a date given the supplied format string
1207 * @param {String} format The format string
1208 * @return {String} The formatted date
1211 Date.prototype.format = Date.prototype.dateFormat;
1214 Date.createNewFormat = function(format) {
1215 var funcName = "format" + Date.formatFunctions.count++;
1216 Date.formatFunctions[format] = funcName;
1217 var code = "Date.prototype." + funcName + " = function(){return ";
1218 var special = false;
1220 for (var i = 0; i < format.length; ++i) {
1221 ch = format.charAt(i);
1222 if (!special && ch == "\\") {
1227 code += "'" + String.escape(ch) + "' + ";
1230 code += Date.getFormatCode(ch);
1233 /** eval:var:zzzzzzzzzzzzz */
1234 eval(code.substring(0, code.length - 3) + ";}");
1238 Date.getFormatCode = function(character) {
1239 switch (character) {
1241 return "String.leftPad(this.getDate(), 2, '0') + ";
1243 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1245 return "this.getDate() + ";
1247 return "Date.dayNames[this.getDay()] + ";
1249 return "this.getSuffix() + ";
1251 return "this.getDay() + ";
1253 return "this.getDayOfYear() + ";
1255 return "this.getWeekOfYear() + ";
1257 return "Date.monthNames[this.getMonth()] + ";
1259 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1261 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1263 return "(this.getMonth() + 1) + ";
1265 return "this.getDaysInMonth() + ";
1267 return "(this.isLeapYear() ? 1 : 0) + ";
1269 return "this.getFullYear() + ";
1271 return "('' + this.getFullYear()).substring(2, 4) + ";
1273 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1275 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1277 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1279 return "this.getHours() + ";
1281 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1283 return "String.leftPad(this.getHours(), 2, '0') + ";
1285 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1287 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1289 return "this.getGMTOffset() + ";
1291 return "this.getGMTColonOffset() + ";
1293 return "this.getTimezone() + ";
1295 return "(this.getTimezoneOffset() * -60) + ";
1297 return "'" + String.escape(character) + "' + ";
1302 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1303 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1304 * the date format that is not specified will default to the current date value for that part. Time parts can also
1305 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1306 * string or the parse operation will fail.
1309 //dt = Fri May 25 2007 (current date)
1310 var dt = new Date();
1312 //dt = Thu May 25 2006 (today's month/day in 2006)
1313 dt = Date.parseDate("2006", "Y");
1315 //dt = Sun Jan 15 2006 (all date parts specified)
1316 dt = Date.parseDate("2006-1-15", "Y-m-d");
1318 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1319 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1321 * @param {String} input The unparsed date as a string
1322 * @param {String} format The format the date is in
1323 * @return {Date} The parsed date
1326 Date.parseDate = function(input, format) {
1327 if (Date.parseFunctions[format] == null) {
1328 Date.createParser(format);
1330 var func = Date.parseFunctions[format];
1331 return Date[func](input);
1337 Date.createParser = function(format) {
1338 var funcName = "parse" + Date.parseFunctions.count++;
1339 var regexNum = Date.parseRegexes.length;
1340 var currentGroup = 1;
1341 Date.parseFunctions[format] = funcName;
1343 var code = "Date." + funcName + " = function(input){\n"
1344 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1345 + "var d = new Date();\n"
1346 + "y = d.getFullYear();\n"
1347 + "m = d.getMonth();\n"
1348 + "d = d.getDate();\n"
1349 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1350 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1351 + "if (results && results.length > 0) {";
1354 var special = false;
1356 for (var i = 0; i < format.length; ++i) {
1357 ch = format.charAt(i);
1358 if (!special && ch == "\\") {
1363 regex += String.escape(ch);
1366 var obj = Date.formatCodeToRegex(ch, currentGroup);
1367 currentGroup += obj.g;
1369 if (obj.g && obj.c) {
1375 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1376 + "{v = new Date(y, m, d, h, i, s);}\n"
1377 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1378 + "{v = new Date(y, m, d, h, i);}\n"
1379 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1380 + "{v = new Date(y, m, d, h);}\n"
1381 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1382 + "{v = new Date(y, m, d);}\n"
1383 + "else if (y >= 0 && m >= 0)\n"
1384 + "{v = new Date(y, m);}\n"
1385 + "else if (y >= 0)\n"
1386 + "{v = new Date(y);}\n"
1387 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1388 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1389 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1392 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1393 /** eval:var:zzzzzzzzzzzzz */
1398 Date.formatCodeToRegex = function(character, currentGroup) {
1399 switch (character) {
1403 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1406 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1407 s:"(\\d{1,2})"}; // day of month without leading zeroes
1410 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1411 s:"(\\d{2})"}; // day of month with leading zeroes
1415 s:"(?:" + Date.dayNames.join("|") + ")"};
1419 s:"(?:st|nd|rd|th)"};
1434 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1435 s:"(" + Date.monthNames.join("|") + ")"};
1438 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1439 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1442 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1443 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1446 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1447 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1458 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1462 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1463 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1467 c:"if (results[" + currentGroup + "] == 'am') {\n"
1468 + "if (h == 12) { h = 0; }\n"
1469 + "} else { if (h < 12) { h += 12; }}",
1473 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1474 + "if (h == 12) { h = 0; }\n"
1475 + "} else { if (h < 12) { h += 12; }}",
1480 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1481 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1485 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1486 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1489 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1493 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1498 "o = results[", currentGroup, "];\n",
1499 "var sn = o.substring(0,1);\n", // get + / - sign
1500 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1501 "var mn = o.substring(3,5) % 60;\n", // get minutes
1502 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1503 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1505 s:"([+\-]\\d{2,4})"};
1511 "o = results[", currentGroup, "];\n",
1512 "var sn = o.substring(0,1);\n",
1513 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1514 "var mn = o.substring(4,6) % 60;\n",
1515 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1516 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1522 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1525 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1526 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1527 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1531 s:String.escape(character)};
1536 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1537 * @return {String} The abbreviated timezone name (e.g. 'CST')
1539 Date.prototype.getTimezone = function() {
1540 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1544 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1545 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1547 Date.prototype.getGMTOffset = function() {
1548 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1549 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1550 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1554 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1555 * @return {String} 2-characters representing hours and 2-characters representing minutes
1556 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1558 Date.prototype.getGMTColonOffset = function() {
1559 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1560 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1562 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1566 * Get the numeric day number of the year, adjusted for leap year.
1567 * @return {Number} 0 through 364 (365 in leap years)
1569 Date.prototype.getDayOfYear = function() {
1571 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1572 for (var i = 0; i < this.getMonth(); ++i) {
1573 num += Date.daysInMonth[i];
1575 return num + this.getDate() - 1;
1579 * Get the string representation of the numeric week number of the year
1580 * (equivalent to the format specifier 'W').
1581 * @return {String} '00' through '52'
1583 Date.prototype.getWeekOfYear = function() {
1584 // Skip to Thursday of this week
1585 var now = this.getDayOfYear() + (4 - this.getDay());
1586 // Find the first Thursday of the year
1587 var jan1 = new Date(this.getFullYear(), 0, 1);
1588 var then = (7 - jan1.getDay() + 4);
1589 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1593 * Whether or not the current date is in a leap year.
1594 * @return {Boolean} True if the current date is in a leap year, else false
1596 Date.prototype.isLeapYear = function() {
1597 var year = this.getFullYear();
1598 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1602 * Get the first day of the current month, adjusted for leap year. The returned value
1603 * is the numeric day index within the week (0-6) which can be used in conjunction with
1604 * the {@link #monthNames} array to retrieve the textual day name.
1607 var dt = new Date('1/10/2007');
1608 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1610 * @return {Number} The day number (0-6)
1612 Date.prototype.getFirstDayOfMonth = function() {
1613 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1614 return (day < 0) ? (day + 7) : day;
1618 * Get the last day of the current month, adjusted for leap year. The returned value
1619 * is the numeric day index within the week (0-6) which can be used in conjunction with
1620 * the {@link #monthNames} array to retrieve the textual day name.
1623 var dt = new Date('1/10/2007');
1624 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1626 * @return {Number} The day number (0-6)
1628 Date.prototype.getLastDayOfMonth = function() {
1629 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1630 return (day < 0) ? (day + 7) : day;
1635 * Get the first date of this date's month
1638 Date.prototype.getFirstDateOfMonth = function() {
1639 return new Date(this.getFullYear(), this.getMonth(), 1);
1643 * Get the last date of this date's month
1646 Date.prototype.getLastDateOfMonth = function() {
1647 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1650 * Get the number of days in the current month, adjusted for leap year.
1651 * @return {Number} The number of days in the month
1653 Date.prototype.getDaysInMonth = function() {
1654 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1655 return Date.daysInMonth[this.getMonth()];
1659 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1660 * @return {String} 'st, 'nd', 'rd' or 'th'
1662 Date.prototype.getSuffix = function() {
1663 switch (this.getDate()) {
1680 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1683 * An array of textual month names.
1684 * Override these values for international dates, for example...
1685 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1704 * An array of textual day names.
1705 * Override these values for international dates, for example...
1706 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1722 Date.monthNumbers = {
1737 * Creates and returns a new Date instance with the exact same date value as the called instance.
1738 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1739 * variable will also be changed. When the intention is to create a new variable that will not
1740 * modify the original instance, you should create a clone.
1742 * Example of correctly cloning a date:
1745 var orig = new Date('10/1/2006');
1748 document.write(orig); //returns 'Thu Oct 05 2006'!
1751 var orig = new Date('10/1/2006');
1752 var copy = orig.clone();
1754 document.write(orig); //returns 'Thu Oct 01 2006'
1756 * @return {Date} The new Date instance
1758 Date.prototype.clone = function() {
1759 return new Date(this.getTime());
1763 * Clears any time information from this date
1764 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1765 @return {Date} this or the clone
1767 Date.prototype.clearTime = function(clone){
1769 return this.clone().clearTime();
1774 this.setMilliseconds(0);
1779 // safari setMonth is broken -- check that this is only donw once...
1780 if(Roo.isSafari && typeof(Date.brokenSetMonth) == 'undefined'){
1781 Date.brokenSetMonth = Date.prototype.setMonth;
1782 Date.prototype.setMonth = function(num){
1784 var n = Math.ceil(-num);
1785 var back_year = Math.ceil(n/12);
1786 var month = (n % 12) ? 12 - n % 12 : 0 ;
1787 this.setFullYear(this.getFullYear() - back_year);
1788 return Date.brokenSetMonth.call(this, month);
1790 return Date.brokenSetMonth.apply(this, arguments);
1795 /** Date interval constant
1799 /** Date interval constant
1803 /** Date interval constant
1807 /** Date interval constant
1811 /** Date interval constant
1815 /** Date interval constant
1819 /** Date interval constant
1825 * Provides a convenient method of performing basic date arithmetic. This method
1826 * does not modify the Date instance being called - it creates and returns
1827 * a new Date instance containing the resulting date value.
1832 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1833 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1835 //Negative values will subtract correctly:
1836 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1837 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1839 //You can even chain several calls together in one line!
1840 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1841 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1844 * @param {String} interval A valid date interval enum value
1845 * @param {Number} value The amount to add to the current date
1846 * @return {Date} The new Date instance
1848 Date.prototype.add = function(interval, value){
1849 var d = this.clone();
1850 if (!interval || value === 0) { return d; }
1851 switch(interval.toLowerCase()){
1853 d.setMilliseconds(this.getMilliseconds() + value);
1856 d.setSeconds(this.getSeconds() + value);
1859 d.setMinutes(this.getMinutes() + value);
1862 d.setHours(this.getHours() + value);
1865 d.setDate(this.getDate() + value);
1868 var day = this.getDate();
1870 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1873 d.setMonth(this.getMonth() + value);
1876 d.setFullYear(this.getFullYear() + value);
1882 * @class Roo.lib.Dom
1886 * Dom utils (from YIU afaik)
1892 * Get the view width
1893 * @param {Boolean} full True will get the full document, otherwise it's the view width
1894 * @return {Number} The width
1897 getViewWidth : function(full) {
1898 return full ? this.getDocumentWidth() : this.getViewportWidth();
1901 * Get the view height
1902 * @param {Boolean} full True will get the full document, otherwise it's the view height
1903 * @return {Number} The height
1905 getViewHeight : function(full) {
1906 return full ? this.getDocumentHeight() : this.getViewportHeight();
1909 * Get the Full Document height
1910 * @return {Number} The height
1912 getDocumentHeight: function() {
1913 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1914 return Math.max(scrollHeight, this.getViewportHeight());
1917 * Get the Full Document width
1918 * @return {Number} The width
1920 getDocumentWidth: function() {
1921 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1922 return Math.max(scrollWidth, this.getViewportWidth());
1925 * Get the Window Viewport height
1926 * @return {Number} The height
1928 getViewportHeight: function() {
1929 var height = self.innerHeight;
1930 var mode = document.compatMode;
1932 if ((mode || Roo.isIE) && !Roo.isOpera) {
1933 height = (mode == "CSS1Compat") ?
1934 document.documentElement.clientHeight :
1935 document.body.clientHeight;
1941 * Get the Window Viewport width
1942 * @return {Number} The width
1944 getViewportWidth: function() {
1945 var width = self.innerWidth;
1946 var mode = document.compatMode;
1948 if (mode || Roo.isIE) {
1949 width = (mode == "CSS1Compat") ?
1950 document.documentElement.clientWidth :
1951 document.body.clientWidth;
1956 isAncestor : function(p, c) {
1963 if (p.contains && !Roo.isSafari) {
1964 return p.contains(c);
1965 } else if (p.compareDocumentPosition) {
1966 return !!(p.compareDocumentPosition(c) & 16);
1968 var parent = c.parentNode;
1973 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1976 parent = parent.parentNode;
1982 getRegion : function(el) {
1983 return Roo.lib.Region.getRegion(el);
1986 getY : function(el) {
1987 return this.getXY(el)[1];
1990 getX : function(el) {
1991 return this.getXY(el)[0];
1994 getXY : function(el) {
1995 var p, pe, b, scroll, bd = document.body;
1996 el = Roo.getDom(el);
1997 var fly = Roo.lib.AnimBase.fly;
1998 if (el.getBoundingClientRect) {
1999 b = el.getBoundingClientRect();
2000 scroll = fly(document).getScroll();
2001 return [b.left + scroll.left, b.top + scroll.top];
2007 var hasAbsolute = fly(el).getStyle("position") == "absolute";
2014 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
2021 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
2022 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
2029 if (p != el && pe.getStyle('overflow') != 'visible') {
2037 if (Roo.isSafari && hasAbsolute) {
2042 if (Roo.isGecko && !hasAbsolute) {
2044 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
2045 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
2049 while (p && p != bd) {
2050 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
2062 setXY : function(el, xy) {
2063 el = Roo.fly(el, '_setXY');
2065 var pts = el.translatePoints(xy);
2066 if (xy[0] !== false) {
2067 el.dom.style.left = pts.left + "px";
2069 if (xy[1] !== false) {
2070 el.dom.style.top = pts.top + "px";
2074 setX : function(el, x) {
2075 this.setXY(el, [x, false]);
2078 setY : function(el, y) {
2079 this.setXY(el, [false, y]);
2083 * Portions of this file are based on pieces of Yahoo User Interface Library
2084 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2085 * YUI licensed under the BSD License:
2086 * http://developer.yahoo.net/yui/license.txt
2087 * <script type="text/javascript">
2091 Roo.lib.Event = function() {
2092 var loadComplete = false;
2094 var unloadListeners = [];
2096 var onAvailStack = [];
2098 var lastError = null;
2111 startInterval: function() {
2112 if (!this._interval) {
2114 var callback = function() {
2115 self._tryPreloadAttach();
2117 this._interval = setInterval(callback, this.POLL_INTERVAL);
2122 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2123 onAvailStack.push({ id: p_id,
2126 override: p_override,
2127 checkReady: false });
2129 retryCount = this.POLL_RETRYS;
2130 this.startInterval();
2134 addListener: function(el, eventName, fn) {
2135 el = Roo.getDom(el);
2140 if ("unload" == eventName) {
2141 unloadListeners[unloadListeners.length] =
2142 [el, eventName, fn];
2146 var wrappedFn = function(e) {
2147 return fn(Roo.lib.Event.getEvent(e));
2150 var li = [el, eventName, fn, wrappedFn];
2152 var index = listeners.length;
2153 listeners[index] = li;
2155 this.doAdd(el, eventName, wrappedFn, false);
2161 removeListener: function(el, eventName, fn) {
2164 el = Roo.getDom(el);
2167 return this.purgeElement(el, false, eventName);
2171 if ("unload" == eventName) {
2173 for (i = 0,len = unloadListeners.length; i < len; i++) {
2174 var li = unloadListeners[i];
2177 li[1] == eventName &&
2179 unloadListeners.splice(i, 1);
2187 var cacheItem = null;
2190 var index = arguments[3];
2192 if ("undefined" == typeof index) {
2193 index = this._getCacheIndex(el, eventName, fn);
2197 cacheItem = listeners[index];
2200 if (!el || !cacheItem) {
2204 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2206 delete listeners[index][this.WFN];
2207 delete listeners[index][this.FN];
2208 listeners.splice(index, 1);
2215 getTarget: function(ev, resolveTextNode) {
2216 ev = ev.browserEvent || ev;
2217 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2218 var t = ev.target || ev.srcElement;
2219 return this.resolveTextNode(t);
2223 resolveTextNode: function(node) {
2224 if (Roo.isSafari && node && 3 == node.nodeType) {
2225 return node.parentNode;
2232 getPageX: function(ev) {
2233 ev = ev.browserEvent || ev;
2234 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2236 if (!x && 0 !== x) {
2237 x = ev.clientX || 0;
2240 x += this.getScroll()[1];
2248 getPageY: function(ev) {
2249 ev = ev.browserEvent || ev;
2250 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2252 if (!y && 0 !== y) {
2253 y = ev.clientY || 0;
2256 y += this.getScroll()[0];
2265 getXY: function(ev) {
2266 ev = ev.browserEvent || ev;
2267 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2268 return [this.getPageX(ev), this.getPageY(ev)];
2272 getRelatedTarget: function(ev) {
2273 ev = ev.browserEvent || ev;
2274 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2275 var t = ev.relatedTarget;
2277 if (ev.type == "mouseout") {
2279 } else if (ev.type == "mouseover") {
2284 return this.resolveTextNode(t);
2288 getTime: function(ev) {
2289 ev = ev.browserEvent || ev;
2290 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2292 var t = new Date().getTime();
2296 this.lastError = ex;
2305 stopEvent: function(ev) {
2306 this.stopPropagation(ev);
2307 this.preventDefault(ev);
2311 stopPropagation: function(ev) {
2312 ev = ev.browserEvent || ev;
2313 if (ev.stopPropagation) {
2314 ev.stopPropagation();
2316 ev.cancelBubble = true;
2321 preventDefault: function(ev) {
2322 ev = ev.browserEvent || ev;
2323 if(ev.preventDefault) {
2324 ev.preventDefault();
2326 ev.returnValue = false;
2331 getEvent: function(e) {
2332 var ev = e || window.event;
2334 var c = this.getEvent.caller;
2336 ev = c.arguments[0];
2337 if (ev && Event == ev.constructor) {
2347 getCharCode: function(ev) {
2348 ev = ev.browserEvent || ev;
2349 return ev.charCode || ev.keyCode || 0;
2353 _getCacheIndex: function(el, eventName, fn) {
2354 for (var i = 0,len = listeners.length; i < len; ++i) {
2355 var li = listeners[i];
2357 li[this.FN] == fn &&
2358 li[this.EL] == el &&
2359 li[this.TYPE] == eventName) {
2371 getEl: function(id) {
2372 return document.getElementById(id);
2376 clearCache: function() {
2380 _load: function(e) {
2381 loadComplete = true;
2382 var EU = Roo.lib.Event;
2386 EU.doRemove(window, "load", EU._load);
2391 _tryPreloadAttach: function() {
2400 var tryAgain = !loadComplete;
2402 tryAgain = (retryCount > 0);
2407 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2408 var item = onAvailStack[i];
2410 var el = this.getEl(item.id);
2413 if (!item.checkReady ||
2416 (document && document.body)) {
2419 if (item.override) {
2420 if (item.override === true) {
2423 scope = item.override;
2426 item.fn.call(scope, item.obj);
2427 onAvailStack[i] = null;
2430 notAvail.push(item);
2435 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2439 this.startInterval();
2441 clearInterval(this._interval);
2442 this._interval = null;
2445 this.locked = false;
2452 purgeElement: function(el, recurse, eventName) {
2453 var elListeners = this.getListeners(el, eventName);
2455 for (var i = 0,len = elListeners.length; i < len; ++i) {
2456 var l = elListeners[i];
2457 this.removeListener(el, l.type, l.fn);
2461 if (recurse && el && el.childNodes) {
2462 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2463 this.purgeElement(el.childNodes[i], recurse, eventName);
2469 getListeners: function(el, eventName) {
2470 var results = [], searchLists;
2472 searchLists = [listeners, unloadListeners];
2473 } else if (eventName == "unload") {
2474 searchLists = [unloadListeners];
2476 searchLists = [listeners];
2479 for (var j = 0; j < searchLists.length; ++j) {
2480 var searchList = searchLists[j];
2481 if (searchList && searchList.length > 0) {
2482 for (var i = 0,len = searchList.length; i < len; ++i) {
2483 var l = searchList[i];
2484 if (l && l[this.EL] === el &&
2485 (!eventName || eventName === l[this.TYPE])) {
2490 adjust: l[this.ADJ_SCOPE],
2498 return (results.length) ? results : null;
2502 _unload: function(e) {
2504 var EU = Roo.lib.Event, i, j, l, len, index;
2506 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2507 l = unloadListeners[i];
2510 if (l[EU.ADJ_SCOPE]) {
2511 if (l[EU.ADJ_SCOPE] === true) {
2514 scope = l[EU.ADJ_SCOPE];
2517 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2518 unloadListeners[i] = null;
2524 unloadListeners = null;
2526 if (listeners && listeners.length > 0) {
2527 j = listeners.length;
2530 l = listeners[index];
2532 EU.removeListener(l[EU.EL], l[EU.TYPE],
2542 EU.doRemove(window, "unload", EU._unload);
2547 getScroll: function() {
2548 var dd = document.documentElement, db = document.body;
2549 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2550 return [dd.scrollTop, dd.scrollLeft];
2552 return [db.scrollTop, db.scrollLeft];
2559 doAdd: function () {
2560 if (window.addEventListener) {
2561 return function(el, eventName, fn, capture) {
2562 el.addEventListener(eventName, fn, (capture));
2564 } else if (window.attachEvent) {
2565 return function(el, eventName, fn, capture) {
2566 el.attachEvent("on" + eventName, fn);
2575 doRemove: function() {
2576 if (window.removeEventListener) {
2577 return function (el, eventName, fn, capture) {
2578 el.removeEventListener(eventName, fn, (capture));
2580 } else if (window.detachEvent) {
2581 return function (el, eventName, fn) {
2582 el.detachEvent("on" + eventName, fn);
2594 var E = Roo.lib.Event;
2595 E.on = E.addListener;
2596 E.un = E.removeListener;
2598 if (document && document.body) {
2601 E.doAdd(window, "load", E._load);
2603 E.doAdd(window, "unload", E._unload);
2604 E._tryPreloadAttach();
2611 * @class Roo.lib.Ajax
2613 * provide a simple Ajax request utility functions
2615 * Portions of this file are based on pieces of Yahoo User Interface Library
2616 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2617 * YUI licensed under the BSD License:
2618 * http://developer.yahoo.net/yui/license.txt
2619 * <script type="text/javascript">
2627 request : function(method, uri, cb, data, options) {
2629 var hs = options.headers;
2632 if(hs.hasOwnProperty(h)){
2633 this.initHeader(h, hs[h], false);
2637 if(options.xmlData){
2638 this.initHeader('Content-Type', 'text/xml', false);
2640 data = options.xmlData;
2644 return this.asyncRequest(method, uri, cb, data);
2650 * @param {DomForm} form element
2651 * @return {String} urlencode form output.
2653 serializeForm : function(form) {
2654 if(typeof form == 'string') {
2655 form = (document.getElementById(form) || document.forms[form]);
2658 var el, name, val, disabled, data = '', hasSubmit = false;
2659 for (var i = 0; i < form.elements.length; i++) {
2660 el = form.elements[i];
2661 disabled = form.elements[i].disabled;
2662 name = form.elements[i].name;
2663 val = form.elements[i].value;
2665 if (!disabled && name){
2669 case 'select-multiple':
2670 for (var j = 0; j < el.options.length; j++) {
2671 if (el.options[j].selected) {
2673 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2676 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2684 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2697 if(hasSubmit == false) {
2698 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2703 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2708 data = data.substr(0, data.length - 1);
2716 useDefaultHeader:true,
2718 defaultPostHeader:'application/x-www-form-urlencoded',
2720 useDefaultXhrHeader:true,
2722 defaultXhrHeader:'XMLHttpRequest',
2724 hasDefaultHeaders:true,
2736 setProgId:function(id)
2738 this.activeX.unshift(id);
2741 setDefaultPostHeader:function(b)
2743 this.useDefaultHeader = b;
2746 setDefaultXhrHeader:function(b)
2748 this.useDefaultXhrHeader = b;
2751 setPollingInterval:function(i)
2753 if (typeof i == 'number' && isFinite(i)) {
2754 this.pollInterval = i;
2758 createXhrObject:function(transactionId)
2764 http = new XMLHttpRequest();
2766 obj = { conn:http, tId:transactionId };
2770 for (var i = 0; i < this.activeX.length; ++i) {
2774 http = new ActiveXObject(this.activeX[i]);
2776 obj = { conn:http, tId:transactionId };
2789 getConnectionObject:function()
2792 var tId = this.transactionId;
2796 o = this.createXhrObject(tId);
2798 this.transactionId++;
2809 asyncRequest:function(method, uri, callback, postData)
2811 var o = this.getConnectionObject();
2817 o.conn.open(method, uri, true);
2819 if (this.useDefaultXhrHeader) {
2820 if (!this.defaultHeaders['X-Requested-With']) {
2821 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2825 if(postData && this.useDefaultHeader){
2826 this.initHeader('Content-Type', this.defaultPostHeader);
2829 if (this.hasDefaultHeaders || this.hasHeaders) {
2833 this.handleReadyState(o, callback);
2834 o.conn.send(postData || null);
2840 handleReadyState:function(o, callback)
2844 if (callback && callback.timeout) {
2846 this.timeout[o.tId] = window.setTimeout(function() {
2847 oConn.abort(o, callback, true);
2848 }, callback.timeout);
2851 this.poll[o.tId] = window.setInterval(
2853 if (o.conn && o.conn.readyState == 4) {
2854 window.clearInterval(oConn.poll[o.tId]);
2855 delete oConn.poll[o.tId];
2857 if(callback && callback.timeout) {
2858 window.clearTimeout(oConn.timeout[o.tId]);
2859 delete oConn.timeout[o.tId];
2862 oConn.handleTransactionResponse(o, callback);
2865 , this.pollInterval);
2868 handleTransactionResponse:function(o, callback, isAbort)
2872 this.releaseObject(o);
2876 var httpStatus, responseObject;
2880 if (o.conn.status !== undefined && o.conn.status != 0) {
2881 httpStatus = o.conn.status;
2893 if (httpStatus >= 200 && httpStatus < 300) {
2894 responseObject = this.createResponseObject(o, callback.argument);
2895 if (callback.success) {
2896 if (!callback.scope) {
2897 callback.success(responseObject);
2902 callback.success.apply(callback.scope, [responseObject]);
2907 switch (httpStatus) {
2915 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2916 if (callback.failure) {
2917 if (!callback.scope) {
2918 callback.failure(responseObject);
2921 callback.failure.apply(callback.scope, [responseObject]);
2926 responseObject = this.createResponseObject(o, callback.argument);
2927 if (callback.failure) {
2928 if (!callback.scope) {
2929 callback.failure(responseObject);
2932 callback.failure.apply(callback.scope, [responseObject]);
2938 this.releaseObject(o);
2939 responseObject = null;
2942 createResponseObject:function(o, callbackArg)
2949 var headerStr = o.conn.getAllResponseHeaders();
2950 var header = headerStr.split('\n');
2951 for (var i = 0; i < header.length; i++) {
2952 var delimitPos = header[i].indexOf(':');
2953 if (delimitPos != -1) {
2954 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2962 obj.status = o.conn.status;
2963 obj.statusText = o.conn.statusText;
2964 obj.getResponseHeader = headerObj;
2965 obj.getAllResponseHeaders = headerStr;
2966 obj.responseText = o.conn.responseText;
2967 obj.responseXML = o.conn.responseXML;
2969 if (typeof callbackArg !== undefined) {
2970 obj.argument = callbackArg;
2976 createExceptionObject:function(tId, callbackArg, isAbort)
2979 var COMM_ERROR = 'communication failure';
2980 var ABORT_CODE = -1;
2981 var ABORT_ERROR = 'transaction aborted';
2987 obj.status = ABORT_CODE;
2988 obj.statusText = ABORT_ERROR;
2991 obj.status = COMM_CODE;
2992 obj.statusText = COMM_ERROR;
2996 obj.argument = callbackArg;
3002 initHeader:function(label, value, isDefault)
3004 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
3006 if (headerObj[label] === undefined) {
3007 headerObj[label] = value;
3012 headerObj[label] = value + "," + headerObj[label];
3016 this.hasDefaultHeaders = true;
3019 this.hasHeaders = true;
3024 setHeader:function(o)
3026 if (this.hasDefaultHeaders) {
3027 for (var prop in this.defaultHeaders) {
3028 if (this.defaultHeaders.hasOwnProperty(prop)) {
3029 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
3034 if (this.hasHeaders) {
3035 for (var prop in this.headers) {
3036 if (this.headers.hasOwnProperty(prop)) {
3037 o.conn.setRequestHeader(prop, this.headers[prop]);
3041 this.hasHeaders = false;
3045 resetDefaultHeaders:function() {
3046 delete this.defaultHeaders;
3047 this.defaultHeaders = {};
3048 this.hasDefaultHeaders = false;
3051 abort:function(o, callback, isTimeout)
3053 if(this.isCallInProgress(o)) {
3055 window.clearInterval(this.poll[o.tId]);
3056 delete this.poll[o.tId];
3058 delete this.timeout[o.tId];
3061 this.handleTransactionResponse(o, callback, true);
3071 isCallInProgress:function(o)
3074 return o.conn.readyState != 4 && o.conn.readyState != 0;
3083 releaseObject:function(o)
3092 'MSXML2.XMLHTTP.3.0',
3100 * Portions of this file are based on pieces of Yahoo User Interface Library
3101 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3102 * YUI licensed under the BSD License:
3103 * http://developer.yahoo.net/yui/license.txt
3104 * <script type="text/javascript">
3108 Roo.lib.Region = function(t, r, b, l) {
3118 Roo.lib.Region.prototype = {
3119 contains : function(region) {
3120 return ( region.left >= this.left &&
3121 region.right <= this.right &&
3122 region.top >= this.top &&
3123 region.bottom <= this.bottom );
3127 getArea : function() {
3128 return ( (this.bottom - this.top) * (this.right - this.left) );
3131 intersect : function(region) {
3132 var t = Math.max(this.top, region.top);
3133 var r = Math.min(this.right, region.right);
3134 var b = Math.min(this.bottom, region.bottom);
3135 var l = Math.max(this.left, region.left);
3137 if (b >= t && r >= l) {
3138 return new Roo.lib.Region(t, r, b, l);
3143 union : function(region) {
3144 var t = Math.min(this.top, region.top);
3145 var r = Math.max(this.right, region.right);
3146 var b = Math.max(this.bottom, region.bottom);
3147 var l = Math.min(this.left, region.left);
3149 return new Roo.lib.Region(t, r, b, l);
3152 adjust : function(t, l, b, r) {
3161 Roo.lib.Region.getRegion = function(el) {
3162 var p = Roo.lib.Dom.getXY(el);
3165 var r = p[0] + el.offsetWidth;
3166 var b = p[1] + el.offsetHeight;
3169 return new Roo.lib.Region(t, r, b, l);
3172 * Portions of this file are based on pieces of Yahoo User Interface Library
3173 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3174 * YUI licensed under the BSD License:
3175 * http://developer.yahoo.net/yui/license.txt
3176 * <script type="text/javascript">
3179 //@@dep Roo.lib.Region
3182 Roo.lib.Point = function(x, y) {
3183 if (x instanceof Array) {
3187 this.x = this.right = this.left = this[0] = x;
3188 this.y = this.top = this.bottom = this[1] = y;
3191 Roo.lib.Point.prototype = new Roo.lib.Region();
3193 * Portions of this file are based on pieces of Yahoo User Interface Library
3194 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3195 * YUI licensed under the BSD License:
3196 * http://developer.yahoo.net/yui/license.txt
3197 * <script type="text/javascript">
3204 scroll : function(el, args, duration, easing, cb, scope) {
3205 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3208 motion : function(el, args, duration, easing, cb, scope) {
3209 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3212 color : function(el, args, duration, easing, cb, scope) {
3213 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3216 run : function(el, args, duration, easing, cb, scope, type) {
3217 type = type || Roo.lib.AnimBase;
3218 if (typeof easing == "string") {
3219 easing = Roo.lib.Easing[easing];
3221 var anim = new type(el, args, duration, easing);
3222 anim.animateX(function() {
3223 Roo.callback(cb, scope);
3229 * Portions of this file are based on pieces of Yahoo User Interface Library
3230 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3231 * YUI licensed under the BSD License:
3232 * http://developer.yahoo.net/yui/license.txt
3233 * <script type="text/javascript">
3241 if (!libFlyweight) {
3242 libFlyweight = new Roo.Element.Flyweight();
3244 libFlyweight.dom = el;
3245 return libFlyweight;
3248 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3252 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3254 this.init(el, attributes, duration, method);
3258 Roo.lib.AnimBase.fly = fly;
3262 Roo.lib.AnimBase.prototype = {
3264 toString: function() {
3265 var el = this.getEl();
3266 var id = el.id || el.tagName;
3267 return ("Anim " + id);
3271 noNegatives: /width|height|opacity|padding/i,
3272 offsetAttribute: /^((width|height)|(top|left))$/,
3273 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3274 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3278 doMethod: function(attr, start, end) {
3279 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3283 setAttribute: function(attr, val, unit) {
3284 if (this.patterns.noNegatives.test(attr)) {
3285 val = (val > 0) ? val : 0;
3288 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3292 getAttribute: function(attr) {
3293 var el = this.getEl();
3294 var val = fly(el).getStyle(attr);
3296 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3297 return parseFloat(val);
3300 var a = this.patterns.offsetAttribute.exec(attr) || [];
3301 var pos = !!( a[3] );
3302 var box = !!( a[2] );
3305 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3306 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3315 getDefaultUnit: function(attr) {
3316 if (this.patterns.defaultUnit.test(attr)) {
3323 animateX : function(callback, scope) {
3324 var f = function() {
3325 this.onComplete.removeListener(f);
3326 if (typeof callback == "function") {
3327 callback.call(scope || this, this);
3330 this.onComplete.addListener(f, this);
3335 setRuntimeAttribute: function(attr) {
3338 var attributes = this.attributes;
3340 this.runtimeAttributes[attr] = {};
3342 var isset = function(prop) {
3343 return (typeof prop !== 'undefined');
3346 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3350 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3353 if (isset(attributes[attr]['to'])) {
3354 end = attributes[attr]['to'];
3355 } else if (isset(attributes[attr]['by'])) {
3356 if (start.constructor == Array) {
3358 for (var i = 0, len = start.length; i < len; ++i) {
3359 end[i] = start[i] + attributes[attr]['by'][i];
3362 end = start + attributes[attr]['by'];
3366 this.runtimeAttributes[attr].start = start;
3367 this.runtimeAttributes[attr].end = end;
3370 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3374 init: function(el, attributes, duration, method) {
3376 var isAnimated = false;
3379 var startTime = null;
3382 var actualFrames = 0;
3385 el = Roo.getDom(el);
3388 this.attributes = attributes || {};
3391 this.duration = duration || 1;
3394 this.method = method || Roo.lib.Easing.easeNone;
3397 this.useSeconds = true;
3400 this.currentFrame = 0;
3403 this.totalFrames = Roo.lib.AnimMgr.fps;
3406 this.getEl = function() {
3411 this.isAnimated = function() {
3416 this.getStartTime = function() {
3420 this.runtimeAttributes = {};
3423 this.animate = function() {
3424 if (this.isAnimated()) {
3428 this.currentFrame = 0;
3430 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3432 Roo.lib.AnimMgr.registerElement(this);
3436 this.stop = function(finish) {
3438 this.currentFrame = this.totalFrames;
3439 this._onTween.fire();
3441 Roo.lib.AnimMgr.stop(this);
3444 var onStart = function() {
3445 this.onStart.fire();
3447 this.runtimeAttributes = {};
3448 for (var attr in this.attributes) {
3449 this.setRuntimeAttribute(attr);
3454 startTime = new Date();
3458 var onTween = function() {
3460 duration: new Date() - this.getStartTime(),
3461 currentFrame: this.currentFrame
3464 data.toString = function() {
3466 'duration: ' + data.duration +
3467 ', currentFrame: ' + data.currentFrame
3471 this.onTween.fire(data);
3473 var runtimeAttributes = this.runtimeAttributes;
3475 for (var attr in runtimeAttributes) {
3476 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3482 var onComplete = function() {
3483 var actual_duration = (new Date() - startTime) / 1000 ;
3486 duration: actual_duration,
3487 frames: actualFrames,
3488 fps: actualFrames / actual_duration
3491 data.toString = function() {
3493 'duration: ' + data.duration +
3494 ', frames: ' + data.frames +
3495 ', fps: ' + data.fps
3501 this.onComplete.fire(data);
3505 this._onStart = new Roo.util.Event(this);
3506 this.onStart = new Roo.util.Event(this);
3507 this.onTween = new Roo.util.Event(this);
3508 this._onTween = new Roo.util.Event(this);
3509 this.onComplete = new Roo.util.Event(this);
3510 this._onComplete = new Roo.util.Event(this);
3511 this._onStart.addListener(onStart);
3512 this._onTween.addListener(onTween);
3513 this._onComplete.addListener(onComplete);
3518 * Portions of this file are based on pieces of Yahoo User Interface Library
3519 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3520 * YUI licensed under the BSD License:
3521 * http://developer.yahoo.net/yui/license.txt
3522 * <script type="text/javascript">
3526 Roo.lib.AnimMgr = new function() {
3543 this.registerElement = function(tween) {
3544 queue[queue.length] = tween;
3546 tween._onStart.fire();
3551 this.unRegister = function(tween, index) {
3552 tween._onComplete.fire();
3553 index = index || getIndex(tween);
3555 queue.splice(index, 1);
3559 if (tweenCount <= 0) {
3565 this.start = function() {
3566 if (thread === null) {
3567 thread = setInterval(this.run, this.delay);
3572 this.stop = function(tween) {
3574 clearInterval(thread);
3576 for (var i = 0, len = queue.length; i < len; ++i) {
3577 if (queue[0].isAnimated()) {
3578 this.unRegister(queue[0], 0);
3587 this.unRegister(tween);
3592 this.run = function() {
3593 for (var i = 0, len = queue.length; i < len; ++i) {
3594 var tween = queue[i];
3595 if (!tween || !tween.isAnimated()) {
3599 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3601 tween.currentFrame += 1;
3603 if (tween.useSeconds) {
3604 correctFrame(tween);
3606 tween._onTween.fire();
3609 Roo.lib.AnimMgr.stop(tween, i);
3614 var getIndex = function(anim) {
3615 for (var i = 0, len = queue.length; i < len; ++i) {
3616 if (queue[i] == anim) {
3624 var correctFrame = function(tween) {
3625 var frames = tween.totalFrames;
3626 var frame = tween.currentFrame;
3627 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3628 var elapsed = (new Date() - tween.getStartTime());
3631 if (elapsed < tween.duration * 1000) {
3632 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3634 tweak = frames - (frame + 1);
3636 if (tweak > 0 && isFinite(tweak)) {
3637 if (tween.currentFrame + tweak >= frames) {
3638 tweak = frames - (frame + 1);
3641 tween.currentFrame += tweak;
3647 * Portions of this file are based on pieces of Yahoo User Interface Library
3648 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3649 * YUI licensed under the BSD License:
3650 * http://developer.yahoo.net/yui/license.txt
3651 * <script type="text/javascript">
3654 Roo.lib.Bezier = new function() {
3656 this.getPosition = function(points, t) {
3657 var n = points.length;
3660 for (var i = 0; i < n; ++i) {
3661 tmp[i] = [points[i][0], points[i][1]];
3664 for (var j = 1; j < n; ++j) {
3665 for (i = 0; i < n - j; ++i) {
3666 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3667 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3671 return [ tmp[0][0], tmp[0][1] ];
3677 * @class Roo.lib.Color
3679 * An abstract Color implementation. Concrete Color implementations should use
3680 * an instance of this function as their prototype, and implement the getRGB and
3681 * getHSL functions. getRGB should return an object representing the RGB
3682 * components of this Color, with the red, green, and blue components in the
3683 * range [0,255] and the alpha component in the range [0,100]. getHSL should
3684 * return an object representing the HSL components of this Color, with the hue
3685 * component in the range [0,360), the saturation and lightness components in
3686 * the range [0,100], and the alpha component in the range [0,1].
3691 * Functions for Color handling and processing.
3693 * http://www.safalra.com/web-design/javascript/Color-handling-and-processing/
3695 * The author of this program, Safalra (Stephen Morley), irrevocably releases all
3696 * rights to this program, with the intention of it becoming part of the public
3697 * domain. Because this program is released into the public domain, it comes with
3698 * no warranty either expressed or implied, to the extent permitted by law.
3700 * For more free and public domain JavaScript code by the same author, visit:
3701 * http://www.safalra.com/web-design/javascript/
3704 Roo.lib.Color = function() { }
3707 Roo.apply(Roo.lib.Color.prototype, {
3715 * @return {Object} an object representing the RGBA components of this Color. The red,
3716 * green, and blue components are converted to integers in the range [0,255].
3717 * The alpha is a value in the range [0,1].
3719 getIntegerRGB : function(){
3721 // get the RGB components of this Color
3722 var rgb = this.getRGB();
3724 // return the integer components
3726 'r' : Math.round(rgb.r),
3727 'g' : Math.round(rgb.g),
3728 'b' : Math.round(rgb.b),
3736 * @return {Object} an object representing the RGBA components of this Color. The red,
3737 * green, and blue components are converted to numbers in the range [0,100].
3738 * The alpha is a value in the range [0,1].
3740 getPercentageRGB : function(){
3742 // get the RGB components of this Color
3743 var rgb = this.getRGB();
3745 // return the percentage components
3747 'r' : 100 * rgb.r / 255,
3748 'g' : 100 * rgb.g / 255,
3749 'b' : 100 * rgb.b / 255,
3756 * getCSSHexadecimalRGB
3757 * @return {String} a string representing this Color as a CSS hexadecimal RGB Color
3758 * value - that is, a string of the form #RRGGBB where each of RR, GG, and BB
3759 * are two-digit hexadecimal numbers.
3761 getCSSHexadecimalRGB : function()
3764 // get the integer RGB components
3765 var rgb = this.getIntegerRGB();
3767 // determine the hexadecimal equivalents
3768 var r16 = rgb.r.toString(16);
3769 var g16 = rgb.g.toString(16);
3770 var b16 = rgb.b.toString(16);
3772 // return the CSS RGB Color value
3774 + (r16.length == 2 ? r16 : '0' + r16)
3775 + (g16.length == 2 ? g16 : '0' + g16)
3776 + (b16.length == 2 ? b16 : '0' + b16);
3782 * @return {String} a string representing this Color as a CSS integer RGB Color
3783 * value - that is, a string of the form rgb(r,g,b) where each of r, g, and b
3784 * are integers in the range [0,255].
3786 getCSSIntegerRGB : function(){
3788 // get the integer RGB components
3789 var rgb = this.getIntegerRGB();
3791 // return the CSS RGB Color value
3792 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
3798 * @return {String} Returns a string representing this Color as a CSS integer RGBA Color
3799 * value - that is, a string of the form rgba(r,g,b,a) where each of r, g, and
3800 * b are integers in the range [0,255] and a is in the range [0,1].
3802 getCSSIntegerRGBA : function(){
3804 // get the integer RGB components
3805 var rgb = this.getIntegerRGB();
3807 // return the CSS integer RGBA Color value
3808 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')';
3813 * getCSSPercentageRGB
3814 * @return {String} a string representing this Color as a CSS percentage RGB Color
3815 * value - that is, a string of the form rgb(r%,g%,b%) where each of r, g, and
3816 * b are in the range [0,100].
3818 getCSSPercentageRGB : function(){
3820 // get the percentage RGB components
3821 var rgb = this.getPercentageRGB();
3823 // return the CSS RGB Color value
3824 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%)';
3829 * getCSSPercentageRGBA
3830 * @return {String} a string representing this Color as a CSS percentage RGBA Color
3831 * value - that is, a string of the form rgba(r%,g%,b%,a) where each of r, g,
3832 * and b are in the range [0,100] and a is in the range [0,1].
3834 getCSSPercentageRGBA : function(){
3836 // get the percentage RGB components
3837 var rgb = this.getPercentageRGB();
3839 // return the CSS percentage RGBA Color value
3840 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%,' + rgb.a + ')';
3846 * @return {String} a string representing this Color as a CSS HSL Color value - that
3847 * is, a string of the form hsl(h,s%,l%) where h is in the range [0,100] and
3848 * s and l are in the range [0,100].
3850 getCSSHSL : function(){
3852 // get the HSL components
3853 var hsl = this.getHSL();
3855 // return the CSS HSL Color value
3856 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)';
3862 * @return {String} a string representing this Color as a CSS HSLA Color value - that
3863 * is, a string of the form hsla(h,s%,l%,a) where h is in the range [0,100],
3864 * s and l are in the range [0,100], and a is in the range [0,1].
3866 getCSSHSLA : function(){
3868 // get the HSL components
3869 var hsl = this.getHSL();
3871 // return the CSS HSL Color value
3872 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%,' + hsl.a + ')';
3877 * Sets the Color of the specified node to this Color. This functions sets
3878 * the CSS 'color' property for the node. The parameter is:
3880 * @param {DomElement} node - the node whose Color should be set
3882 setNodeColor : function(node){
3884 // set the Color of the node
3885 node.style.color = this.getCSSHexadecimalRGB();
3890 * Sets the background Color of the specified node to this Color. This
3891 * functions sets the CSS 'background-color' property for the node. The
3894 * @param {DomElement} node - the node whose background Color should be set
3896 setNodeBackgroundColor : function(node){
3898 // set the background Color of the node
3899 node.style.backgroundColor = this.getCSSHexadecimalRGB();
3902 // convert between formats..
3905 var r = this.getIntegerRGB();
3906 return new Roo.lib.RGBColor(r.r,r.g,r.b,r.a);
3911 var hsl = this.getHSL();
3912 // return the CSS HSL Color value
3913 return new Roo.lib.HSLColor(hsl.h, hsl.s, hsl.l , hsl.a );
3919 var rgb = this.toRGB();
3920 var hsv = rgb.getHSV();
3921 // return the CSS HSL Color value
3922 return new Roo.lib.HSVColor(hsv.h, hsv.s, hsv.v , hsv.a );
3926 // modify v = 0 ... 1 (eg. 0.5)
3927 saturate : function(v)
3929 var rgb = this.toRGB();
3930 var hsv = rgb.getHSV();
3931 return new Roo.lib.HSVColor(hsv.h, hsv.s * v, hsv.v , hsv.a );
3939 * @return {Object} the RGB and alpha components of this Color as an object with r,
3940 * g, b, and a properties. r, g, and b are in the range [0,255] and a is in
3945 // return the RGB components
3957 * @return {Object} the HSV and alpha components of this Color as an object with h,
3958 * s, v, and a properties. h is in the range [0,360), s and v are in the range
3959 * [0,100], and a is in the range [0,1].
3964 // calculate the HSV components if necessary
3965 if (this.hsv == null) {
3966 this.calculateHSV();
3969 // return the HSV components
3981 * @return {Object} the HSL and alpha components of this Color as an object with h,
3982 * s, l, and a properties. h is in the range [0,360), s and l are in the range
3983 * [0,100], and a is in the range [0,1].
3985 getHSL : function(){
3988 // calculate the HSV components if necessary
3989 if (this.hsl == null) { this.calculateHSL(); }
3991 // return the HSL components
4006 * @class Roo.lib.RGBColor
4007 * @extends Roo.lib.Color
4008 * Creates a Color specified in the RGB Color space, with an optional alpha
4009 * component. The parameters are:
4013 * @param {Number} r - the red component, clipped to the range [0,255]
4014 * @param {Number} g - the green component, clipped to the range [0,255]
4015 * @param {Number} b - the blue component, clipped to the range [0,255]
4016 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4017 * optional and defaults to 1
4019 Roo.lib.RGBColor = function (r, g, b, a){
4021 // store the alpha component after clipping it if necessary
4022 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4024 // store the RGB components after clipping them if necessary
4027 'r' : Math.max(0, Math.min(255, r)),
4028 'g' : Math.max(0, Math.min(255, g)),
4029 'b' : Math.max(0, Math.min(255, b))
4032 // initialise the HSV and HSL components to null
4036 * //private returns the HSV or HSL hue component of this RGBColor. The hue is in the
4037 * range [0,360). The parameters are:
4039 * maximum - the maximum of the RGB component values
4040 * range - the range of the RGB component values
4045 // this does an 'exteds'
4046 Roo.extend(Roo.lib.RGBColor, Roo.lib.Color, {
4049 getHue : function(maximum, range)
4053 // check whether the range is zero
4056 // set the hue to zero (any hue is acceptable as the Color is grey)
4061 // determine which of the components has the highest value and set the hue
4064 // red has the highest value
4066 var hue = (rgb.g - rgb.b) / range * 60;
4067 if (hue < 0) { hue += 360; }
4070 // green has the highest value
4072 var hue = (rgb.b - rgb.r) / range * 60 + 120;
4075 // blue has the highest value
4077 var hue = (rgb.r - rgb.g) / range * 60 + 240;
4089 /* //private Calculates and stores the HSV components of this RGBColor so that they can
4090 * be returned be the getHSV function.
4092 calculateHSV : function(){
4094 // get the maximum and range of the RGB component values
4095 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4096 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4098 // store the HSV components
4101 'h' : this.getHue(maximum, range),
4102 's' : (maximum == 0 ? 0 : 100 * range / maximum),
4103 'v' : maximum / 2.55
4108 /* //private Calculates and stores the HSL components of this RGBColor so that they can
4109 * be returned be the getHSL function.
4111 calculateHSL : function(){
4113 // get the maximum and range of the RGB component values
4114 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4115 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4117 // determine the lightness in the range [0,1]
4118 var l = maximum / 255 - range / 510;
4120 // store the HSL components
4123 'h' : this.getHue(maximum, range),
4124 's' : (range == 0 ? 0 : range / 2.55 / (l < 0.5 ? l * 2 : 2 - l * 2)),
4133 * @class Roo.lib.HSVColor
4134 * @extends Roo.lib.Color
4135 * Creates a Color specified in the HSV Color space, with an optional alpha
4136 * component. The parameters are:
4139 * @param {Number} h - the hue component, wrapped to the range [0,360)
4140 * @param {Number} s - the saturation component, clipped to the range [0,100]
4141 * @param {Number} v - the value component, clipped to the range [0,100]
4142 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4143 * optional and defaults to 1
4145 Roo.lib.HSVColor = function (h, s, v, a){
4147 // store the alpha component after clipping it if necessary
4148 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4150 // store the HSV components after clipping or wrapping them if necessary
4153 'h' : (h % 360 + 360) % 360,
4154 's' : Math.max(0, Math.min(100, s)),
4155 'v' : Math.max(0, Math.min(100, v))
4158 // initialise the RGB and HSL components to null
4163 Roo.extend(Roo.lib.HSVColor, Roo.lib.Color, {
4164 /* Calculates and stores the RGB components of this HSVColor so that they can
4165 * be returned be the getRGB function.
4167 calculateRGB: function ()
4170 // check whether the saturation is zero
4173 // set the Color to the appropriate shade of grey
4180 // set some temporary values
4181 var f = hsv.h / 60 - Math.floor(hsv.h / 60);
4182 var p = hsv.v * (1 - hsv.s / 100);
4183 var q = hsv.v * (1 - hsv.s / 100 * f);
4184 var t = hsv.v * (1 - hsv.s / 100 * (1 - f));
4186 // set the RGB Color components to their temporary values
4187 switch (Math.floor(hsv.h / 60)){
4188 case 0: var r = hsv.v; var g = t; var b = p; break;
4189 case 1: var r = q; var g = hsv.v; var b = p; break;
4190 case 2: var r = p; var g = hsv.v; var b = t; break;
4191 case 3: var r = p; var g = q; var b = hsv.v; break;
4192 case 4: var r = t; var g = p; var b = hsv.v; break;
4193 case 5: var r = hsv.v; var g = p; var b = q; break;
4198 // store the RGB components
4208 /* Calculates and stores the HSL components of this HSVColor so that they can
4209 * be returned be the getHSL function.
4211 calculateHSL : function (){
4214 // determine the lightness in the range [0,100]
4215 var l = (2 - hsv.s / 100) * hsv.v / 2;
4217 // store the HSL components
4221 's' : hsv.s * hsv.v / (l < 50 ? l * 2 : 200 - l * 2),
4225 // correct a division-by-zero error
4226 if (isNaN(hsl.s)) { hsl.s = 0; }
4235 * @class Roo.lib.HSLColor
4236 * @extends Roo.lib.Color
4239 * Creates a Color specified in the HSL Color space, with an optional alpha
4240 * component. The parameters are:
4242 * @param {Number} h - the hue component, wrapped to the range [0,360)
4243 * @param {Number} s - the saturation component, clipped to the range [0,100]
4244 * @param {Number} l - the lightness component, clipped to the range [0,100]
4245 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4246 * optional and defaults to 1
4249 Roo.lib.HSLColor = function(h, s, l, a){
4251 // store the alpha component after clipping it if necessary
4252 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4254 // store the HSL components after clipping or wrapping them if necessary
4257 'h' : (h % 360 + 360) % 360,
4258 's' : Math.max(0, Math.min(100, s)),
4259 'l' : Math.max(0, Math.min(100, l))
4262 // initialise the RGB and HSV components to null
4265 Roo.extend(Roo.lib.HSLColor, Roo.lib.Color, {
4267 /* Calculates and stores the RGB components of this HSLColor so that they can
4268 * be returned be the getRGB function.
4270 calculateRGB: function (){
4272 // check whether the saturation is zero
4273 if (this.hsl.s == 0){
4275 // store the RGB components representing the appropriate shade of grey
4278 'r' : this.hsl.l * 2.55,
4279 'g' : this.hsl.l * 2.55,
4280 'b' : this.hsl.l * 2.55
4285 // set some temporary values
4286 var p = this.hsl.l < 50
4287 ? this.hsl.l * (1 + hsl.s / 100)
4288 : this.hsl.l + hsl.s - hsl.l * hsl.s / 100;
4289 var q = 2 * hsl.l - p;
4291 // initialise the RGB components
4294 'r' : (h + 120) / 60 % 6,
4296 'b' : (h + 240) / 60 % 6
4299 // loop over the RGB components
4300 for (var key in this.rgb){
4302 // ensure that the property is not inherited from the root object
4303 if (this.rgb.hasOwnProperty(key)){
4305 // set the component to its value in the range [0,100]
4306 if (this.rgb[key] < 1){
4307 this.rgb[key] = q + (p - q) * this.rgb[key];
4308 }else if (this.rgb[key] < 3){
4310 }else if (this.rgb[key] < 4){
4311 this.rgb[key] = q + (p - q) * (4 - this.rgb[key]);
4316 // set the component to its value in the range [0,255]
4317 this.rgb[key] *= 2.55;
4327 /* Calculates and stores the HSV components of this HSLColor so that they can
4328 * be returned be the getHSL function.
4330 calculateHSV : function(){
4332 // set a temporary value
4333 var t = this.hsl.s * (this.hsl.l < 50 ? this.hsl.l : 100 - this.hsl.l) / 100;
4335 // store the HSV components
4339 's' : 200 * t / (this.hsl.l + t),
4340 'v' : t + this.hsl.l
4343 // correct a division-by-zero error
4344 if (isNaN(this.hsv.s)) { this.hsv.s = 0; }
4351 * Portions of this file are based on pieces of Yahoo User Interface Library
4352 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4353 * YUI licensed under the BSD License:
4354 * http://developer.yahoo.net/yui/license.txt
4355 * <script type="text/javascript">
4360 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
4361 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
4364 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
4366 var fly = Roo.lib.AnimBase.fly;
4368 var superclass = Y.ColorAnim.superclass;
4369 var proto = Y.ColorAnim.prototype;
4371 proto.toString = function() {
4372 var el = this.getEl();
4373 var id = el.id || el.tagName;
4374 return ("ColorAnim " + id);
4377 proto.patterns.color = /color$/i;
4378 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
4379 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
4380 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
4381 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
4384 proto.parseColor = function(s) {
4385 if (s.length == 3) {
4389 var c = this.patterns.hex.exec(s);
4390 if (c && c.length == 4) {
4391 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
4394 c = this.patterns.rgb.exec(s);
4395 if (c && c.length == 4) {
4396 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
4399 c = this.patterns.hex3.exec(s);
4400 if (c && c.length == 4) {
4401 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
4406 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
4407 proto.getAttribute = function(attr) {
4408 var el = this.getEl();
4409 if (this.patterns.color.test(attr)) {
4410 var val = fly(el).getStyle(attr);
4412 if (this.patterns.transparent.test(val)) {
4413 var parent = el.parentNode;
4414 val = fly(parent).getStyle(attr);
4416 while (parent && this.patterns.transparent.test(val)) {
4417 parent = parent.parentNode;
4418 val = fly(parent).getStyle(attr);
4419 if (parent.tagName.toUpperCase() == 'HTML') {
4425 val = superclass.getAttribute.call(this, attr);
4430 proto.getAttribute = function(attr) {
4431 var el = this.getEl();
4432 if (this.patterns.color.test(attr)) {
4433 var val = fly(el).getStyle(attr);
4435 if (this.patterns.transparent.test(val)) {
4436 var parent = el.parentNode;
4437 val = fly(parent).getStyle(attr);
4439 while (parent && this.patterns.transparent.test(val)) {
4440 parent = parent.parentNode;
4441 val = fly(parent).getStyle(attr);
4442 if (parent.tagName.toUpperCase() == 'HTML') {
4448 val = superclass.getAttribute.call(this, attr);
4454 proto.doMethod = function(attr, start, end) {
4457 if (this.patterns.color.test(attr)) {
4459 for (var i = 0, len = start.length; i < len; ++i) {
4460 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
4463 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
4466 val = superclass.doMethod.call(this, attr, start, end);
4472 proto.setRuntimeAttribute = function(attr) {
4473 superclass.setRuntimeAttribute.call(this, attr);
4475 if (this.patterns.color.test(attr)) {
4476 var attributes = this.attributes;
4477 var start = this.parseColor(this.runtimeAttributes[attr].start);
4478 var end = this.parseColor(this.runtimeAttributes[attr].end);
4480 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
4481 end = this.parseColor(attributes[attr].by);
4483 for (var i = 0, len = start.length; i < len; ++i) {
4484 end[i] = start[i] + end[i];
4488 this.runtimeAttributes[attr].start = start;
4489 this.runtimeAttributes[attr].end = end;
4495 * Portions of this file are based on pieces of Yahoo User Interface Library
4496 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4497 * YUI licensed under the BSD License:
4498 * http://developer.yahoo.net/yui/license.txt
4499 * <script type="text/javascript">
4505 easeNone: function (t, b, c, d) {
4506 return c * t / d + b;
4510 easeIn: function (t, b, c, d) {
4511 return c * (t /= d) * t + b;
4515 easeOut: function (t, b, c, d) {
4516 return -c * (t /= d) * (t - 2) + b;
4520 easeBoth: function (t, b, c, d) {
4521 if ((t /= d / 2) < 1) {
4522 return c / 2 * t * t + b;
4525 return -c / 2 * ((--t) * (t - 2) - 1) + b;
4529 easeInStrong: function (t, b, c, d) {
4530 return c * (t /= d) * t * t * t + b;
4534 easeOutStrong: function (t, b, c, d) {
4535 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
4539 easeBothStrong: function (t, b, c, d) {
4540 if ((t /= d / 2) < 1) {
4541 return c / 2 * t * t * t * t + b;
4544 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
4549 elasticIn: function (t, b, c, d, a, p) {
4553 if ((t /= d) == 1) {
4560 if (!a || a < Math.abs(c)) {
4565 var s = p / (2 * Math.PI) * Math.asin(c / a);
4568 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4572 elasticOut: function (t, b, c, d, a, p) {
4576 if ((t /= d) == 1) {
4583 if (!a || a < Math.abs(c)) {
4588 var s = p / (2 * Math.PI) * Math.asin(c / a);
4591 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
4595 elasticBoth: function (t, b, c, d, a, p) {
4600 if ((t /= d / 2) == 2) {
4608 if (!a || a < Math.abs(c)) {
4613 var s = p / (2 * Math.PI) * Math.asin(c / a);
4617 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
4618 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4620 return a * Math.pow(2, -10 * (t -= 1)) *
4621 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
4626 backIn: function (t, b, c, d, s) {
4627 if (typeof s == 'undefined') {
4630 return c * (t /= d) * t * ((s + 1) * t - s) + b;
4634 backOut: function (t, b, c, d, s) {
4635 if (typeof s == 'undefined') {
4638 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
4642 backBoth: function (t, b, c, d, s) {
4643 if (typeof s == 'undefined') {
4647 if ((t /= d / 2 ) < 1) {
4648 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
4650 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
4654 bounceIn: function (t, b, c, d) {
4655 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
4659 bounceOut: function (t, b, c, d) {
4660 if ((t /= d) < (1 / 2.75)) {
4661 return c * (7.5625 * t * t) + b;
4662 } else if (t < (2 / 2.75)) {
4663 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
4664 } else if (t < (2.5 / 2.75)) {
4665 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
4667 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
4671 bounceBoth: function (t, b, c, d) {
4673 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
4675 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
4678 * Portions of this file are based on pieces of Yahoo User Interface Library
4679 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4680 * YUI licensed under the BSD License:
4681 * http://developer.yahoo.net/yui/license.txt
4682 * <script type="text/javascript">
4686 Roo.lib.Motion = function(el, attributes, duration, method) {
4688 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
4692 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
4696 var superclass = Y.Motion.superclass;
4697 var proto = Y.Motion.prototype;
4699 proto.toString = function() {
4700 var el = this.getEl();
4701 var id = el.id || el.tagName;
4702 return ("Motion " + id);
4705 proto.patterns.points = /^points$/i;
4707 proto.setAttribute = function(attr, val, unit) {
4708 if (this.patterns.points.test(attr)) {
4709 unit = unit || 'px';
4710 superclass.setAttribute.call(this, 'left', val[0], unit);
4711 superclass.setAttribute.call(this, 'top', val[1], unit);
4713 superclass.setAttribute.call(this, attr, val, unit);
4717 proto.getAttribute = function(attr) {
4718 if (this.patterns.points.test(attr)) {
4720 superclass.getAttribute.call(this, 'left'),
4721 superclass.getAttribute.call(this, 'top')
4724 val = superclass.getAttribute.call(this, attr);
4730 proto.doMethod = function(attr, start, end) {
4733 if (this.patterns.points.test(attr)) {
4734 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
4735 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
4737 val = superclass.doMethod.call(this, attr, start, end);
4742 proto.setRuntimeAttribute = function(attr) {
4743 if (this.patterns.points.test(attr)) {
4744 var el = this.getEl();
4745 var attributes = this.attributes;
4747 var control = attributes['points']['control'] || [];
4751 if (control.length > 0 && !(control[0] instanceof Array)) {
4752 control = [control];
4755 for (i = 0,len = control.length; i < len; ++i) {
4756 tmp[i] = control[i];
4761 Roo.fly(el).position();
4763 if (isset(attributes['points']['from'])) {
4764 Roo.lib.Dom.setXY(el, attributes['points']['from']);
4767 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
4770 start = this.getAttribute('points');
4773 if (isset(attributes['points']['to'])) {
4774 end = translateValues.call(this, attributes['points']['to'], start);
4776 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4777 for (i = 0,len = control.length; i < len; ++i) {
4778 control[i] = translateValues.call(this, control[i], start);
4782 } else if (isset(attributes['points']['by'])) {
4783 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
4785 for (i = 0,len = control.length; i < len; ++i) {
4786 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4790 this.runtimeAttributes[attr] = [start];
4792 if (control.length > 0) {
4793 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4796 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4799 superclass.setRuntimeAttribute.call(this, attr);
4803 var translateValues = function(val, start) {
4804 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4805 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4810 var isset = function(prop) {
4811 return (typeof prop !== 'undefined');
4815 * Portions of this file are based on pieces of Yahoo User Interface Library
4816 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4817 * YUI licensed under the BSD License:
4818 * http://developer.yahoo.net/yui/license.txt
4819 * <script type="text/javascript">
4823 Roo.lib.Scroll = function(el, attributes, duration, method) {
4825 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4829 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4833 var superclass = Y.Scroll.superclass;
4834 var proto = Y.Scroll.prototype;
4836 proto.toString = function() {
4837 var el = this.getEl();
4838 var id = el.id || el.tagName;
4839 return ("Scroll " + id);
4842 proto.doMethod = function(attr, start, end) {
4845 if (attr == 'scroll') {
4847 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4848 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4852 val = superclass.doMethod.call(this, attr, start, end);
4857 proto.getAttribute = function(attr) {
4859 var el = this.getEl();
4861 if (attr == 'scroll') {
4862 val = [ el.scrollLeft, el.scrollTop ];
4864 val = superclass.getAttribute.call(this, attr);
4870 proto.setAttribute = function(attr, val, unit) {
4871 var el = this.getEl();
4873 if (attr == 'scroll') {
4874 el.scrollLeft = val[0];
4875 el.scrollTop = val[1];
4877 superclass.setAttribute.call(this, attr, val, unit);
4883 * Ext JS Library 1.1.1
4884 * Copyright(c) 2006-2007, Ext JS, LLC.
4886 * Originally Released Under LGPL - original licence link has changed is not relivant.
4889 * <script type="text/javascript">
4893 // nasty IE9 hack - what a pile of crap that is..
4895 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4896 Range.prototype.createContextualFragment = function (html) {
4897 var doc = window.document;
4898 var container = doc.createElement("div");
4899 container.innerHTML = html;
4900 var frag = doc.createDocumentFragment(), n;
4901 while ((n = container.firstChild)) {
4902 frag.appendChild(n);
4909 * @class Roo.DomHelper
4910 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4911 * For more information see <a href="http://web.archive.org/web/20071221063734/http://www.jackslocum.com/blog/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">this blog post with examples</a>.
4914 Roo.DomHelper = function(){
4915 var tempTableEl = null;
4916 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4917 var tableRe = /^table|tbody|tr|td$/i;
4919 // build as innerHTML where available
4921 var createHtml = function(o){
4922 if(typeof o == 'string'){
4931 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") { continue; }
4932 if(attr == "style"){
4934 if(typeof s == "function"){
4937 if(typeof s == "string"){
4938 b += ' style="' + s + '"';
4939 }else if(typeof s == "object"){
4942 if(typeof s[key] != "function"){
4943 b += key + ":" + s[key] + ";";
4950 b += ' class="' + o["cls"] + '"';
4951 }else if(attr == "htmlFor"){
4952 b += ' for="' + o["htmlFor"] + '"';
4954 b += " " + attr + '="' + o[attr] + '"';
4958 if(emptyTags.test(o.tag)){
4962 var cn = o.children || o.cn;
4964 //http://bugs.kde.org/show_bug.cgi?id=71506
4965 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4966 for(var i = 0, len = cn.length; i < len; i++) {
4967 b += createHtml(cn[i], b);
4970 b += createHtml(cn, b);
4976 b += "</" + o.tag + ">";
4983 var createDom = function(o, parentNode){
4985 // defininition craeted..
4987 if (o.ns && o.ns != 'html') {
4989 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
4990 xmlns[o.ns] = o.xmlns;
4993 if (typeof(xmlns[o.ns]) == 'undefined') {
4994 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
5000 if (typeof(o) == 'string') {
5001 return parentNode.appendChild(document.createTextNode(o));
5003 o.tag = o.tag || div;
5004 if (o.ns && Roo.isIE) {
5006 o.tag = o.ns + ':' + o.tag;
5009 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
5010 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
5013 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
5014 attr == "style" || typeof o[attr] == "function") { continue; }
5016 if(attr=="cls" && Roo.isIE){
5017 el.className = o["cls"];
5019 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
5025 Roo.DomHelper.applyStyles(el, o.style);
5026 var cn = o.children || o.cn;
5028 //http://bugs.kde.org/show_bug.cgi?id=71506
5029 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5030 for(var i = 0, len = cn.length; i < len; i++) {
5031 createDom(cn[i], el);
5038 el.innerHTML = o.html;
5041 parentNode.appendChild(el);
5046 var ieTable = function(depth, s, h, e){
5047 tempTableEl.innerHTML = [s, h, e].join('');
5048 var i = -1, el = tempTableEl;
5049 while(++i < depth && el.firstChild){
5055 // kill repeat to save bytes
5059 tbe = '</tbody>'+te,
5065 * Nasty code for IE's broken table implementation
5067 var insertIntoTable = function(tag, where, el, html){
5069 tempTableEl = document.createElement('div');
5074 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
5077 if(where == 'beforebegin'){
5081 before = el.nextSibling;
5084 node = ieTable(4, trs, html, tre);
5086 else if(tag == 'tr'){
5087 if(where == 'beforebegin'){
5090 node = ieTable(3, tbs, html, tbe);
5091 } else if(where == 'afterend'){
5092 before = el.nextSibling;
5094 node = ieTable(3, tbs, html, tbe);
5095 } else{ // INTO a TR
5096 if(where == 'afterbegin'){
5097 before = el.firstChild;
5099 node = ieTable(4, trs, html, tre);
5101 } else if(tag == 'tbody'){
5102 if(where == 'beforebegin'){
5105 node = ieTable(2, ts, html, te);
5106 } else if(where == 'afterend'){
5107 before = el.nextSibling;
5109 node = ieTable(2, ts, html, te);
5111 if(where == 'afterbegin'){
5112 before = el.firstChild;
5114 node = ieTable(3, tbs, html, tbe);
5117 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
5120 if(where == 'afterbegin'){
5121 before = el.firstChild;
5123 node = ieTable(2, ts, html, te);
5125 el.insertBefore(node, before);
5130 /** True to force the use of DOM instead of html fragments @type Boolean */
5134 * Returns the markup for the passed Element(s) config
5135 * @param {Object} o The Dom object spec (and children)
5138 markup : function(o){
5139 return createHtml(o);
5143 * Applies a style specification to an element
5144 * @param {String/HTMLElement} el The element to apply styles to
5145 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
5146 * a function which returns such a specification.
5148 applyStyles : function(el, styles){
5151 if(typeof styles == "string"){
5152 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
5154 while ((matches = re.exec(styles)) != null){
5155 el.setStyle(matches[1], matches[2]);
5157 }else if (typeof styles == "object"){
5158 for (var style in styles){
5159 el.setStyle(style, styles[style]);
5161 }else if (typeof styles == "function"){
5162 Roo.DomHelper.applyStyles(el, styles.call());
5168 * Inserts an HTML fragment into the Dom
5169 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
5170 * @param {HTMLElement} el The context element
5171 * @param {String} html The HTML fragmenet
5172 * @return {HTMLElement} The new node
5174 insertHtml : function(where, el, html){
5175 where = where.toLowerCase();
5176 if(el.insertAdjacentHTML){
5177 if(tableRe.test(el.tagName)){
5179 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
5185 el.insertAdjacentHTML('BeforeBegin', html);
5186 return el.previousSibling;
5188 el.insertAdjacentHTML('AfterBegin', html);
5189 return el.firstChild;
5191 el.insertAdjacentHTML('BeforeEnd', html);
5192 return el.lastChild;
5194 el.insertAdjacentHTML('AfterEnd', html);
5195 return el.nextSibling;
5197 throw 'Illegal insertion point -> "' + where + '"';
5199 var range = el.ownerDocument.createRange();
5203 range.setStartBefore(el);
5204 frag = range.createContextualFragment(html);
5205 el.parentNode.insertBefore(frag, el);
5206 return el.previousSibling;
5209 range.setStartBefore(el.firstChild);
5210 frag = range.createContextualFragment(html);
5211 el.insertBefore(frag, el.firstChild);
5212 return el.firstChild;
5214 el.innerHTML = html;
5215 return el.firstChild;
5219 range.setStartAfter(el.lastChild);
5220 frag = range.createContextualFragment(html);
5221 el.appendChild(frag);
5222 return el.lastChild;
5224 el.innerHTML = html;
5225 return el.lastChild;
5228 range.setStartAfter(el);
5229 frag = range.createContextualFragment(html);
5230 el.parentNode.insertBefore(frag, el.nextSibling);
5231 return el.nextSibling;
5233 throw 'Illegal insertion point -> "' + where + '"';
5237 * Creates new Dom element(s) and inserts them before el
5238 * @param {String/HTMLElement/Element} el The context element
5239 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5240 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5241 * @return {HTMLElement/Roo.Element} The new node
5243 insertBefore : function(el, o, returnElement){
5244 return this.doInsert(el, o, returnElement, "beforeBegin");
5248 * Creates new Dom element(s) and inserts them after el
5249 * @param {String/HTMLElement/Element} el The context element
5250 * @param {Object} o The Dom object spec (and children)
5251 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5252 * @return {HTMLElement/Roo.Element} The new node
5254 insertAfter : function(el, o, returnElement){
5255 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
5259 * Creates new Dom element(s) and inserts them as the first child of el
5260 * @param {String/HTMLElement/Element} el The context element
5261 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5262 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5263 * @return {HTMLElement/Roo.Element} The new node
5265 insertFirst : function(el, o, returnElement){
5266 return this.doInsert(el, o, returnElement, "afterBegin");
5270 doInsert : function(el, o, returnElement, pos, sibling){
5271 el = Roo.getDom(el);
5273 if(this.useDom || o.ns){
5274 newNode = createDom(o, null);
5275 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
5277 var html = createHtml(o);
5278 newNode = this.insertHtml(pos, el, html);
5280 return returnElement ? Roo.get(newNode, true) : newNode;
5284 * Creates new Dom element(s) and appends them to el
5285 * @param {String/HTMLElement/Element} el The context element
5286 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5287 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5288 * @return {HTMLElement/Roo.Element} The new node
5290 append : function(el, o, returnElement){
5291 el = Roo.getDom(el);
5293 if(this.useDom || o.ns){
5294 newNode = createDom(o, null);
5295 el.appendChild(newNode);
5297 var html = createHtml(o);
5298 newNode = this.insertHtml("beforeEnd", el, html);
5300 return returnElement ? Roo.get(newNode, true) : newNode;
5304 * Creates new Dom element(s) and overwrites the contents of el with them
5305 * @param {String/HTMLElement/Element} el The context element
5306 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5307 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5308 * @return {HTMLElement/Roo.Element} The new node
5310 overwrite : function(el, o, returnElement){
5311 el = Roo.getDom(el);
5314 while (el.childNodes.length) {
5315 el.removeChild(el.firstChild);
5319 el.innerHTML = createHtml(o);
5322 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5326 * Creates a new Roo.DomHelper.Template from the Dom object spec
5327 * @param {Object} o The Dom object spec (and children)
5328 * @return {Roo.DomHelper.Template} The new template
5330 createTemplate : function(o){
5331 var html = createHtml(o);
5332 return new Roo.Template(html);
5338 * Ext JS Library 1.1.1
5339 * Copyright(c) 2006-2007, Ext JS, LLC.
5341 * Originally Released Under LGPL - original licence link has changed is not relivant.
5344 * <script type="text/javascript">
5348 * @class Roo.Template
5349 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
5350 * For a list of available format functions, see {@link Roo.util.Format}.<br />
5353 var t = new Roo.Template({
5354 html : '<div name="{id}">' +
5355 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
5357 myformat: function (value, allValues) {
5358 return 'XX' + value;
5361 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
5363 * For more information see this blog post with examples:
5364 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
5365 - Create Elements using DOM, HTML fragments and Templates</a>.
5367 * @param {Object} cfg - Configuration object.
5369 Roo.Template = function(cfg){
5371 if(cfg instanceof Array){
5373 }else if(arguments.length > 1){
5374 cfg = Array.prototype.join.call(arguments, "");
5378 if (typeof(cfg) == 'object') {
5389 Roo.Template.prototype = {
5392 * @cfg {Function} onLoad Called after the template has been loaded and complied (usually from a remove source)
5398 * @cfg {String} url The Url to load the template from. beware if you are loading from a url, the data may not be ready if you use it instantly..
5399 * it should be fixed so that template is observable...
5403 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
5411 * Returns an HTML fragment of this template with the specified values applied.
5412 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
5413 * @return {String} The HTML fragment
5418 applyTemplate : function(values){
5419 //Roo.log(["applyTemplate", values]);
5423 return this.compiled(values);
5425 var useF = this.disableFormats !== true;
5426 var fm = Roo.util.Format, tpl = this;
5427 var fn = function(m, name, format, args){
5429 if(format.substr(0, 5) == "this."){
5430 return tpl.call(format.substr(5), values[name], values);
5433 // quoted values are required for strings in compiled templates,
5434 // but for non compiled we need to strip them
5435 // quoted reversed for jsmin
5436 var re = /^\s*['"](.*)["']\s*$/;
5437 args = args.split(',');
5438 for(var i = 0, len = args.length; i < len; i++){
5439 args[i] = args[i].replace(re, "$1");
5441 args = [values[name]].concat(args);
5443 args = [values[name]];
5445 return fm[format].apply(fm, args);
5448 return values[name] !== undefined ? values[name] : "";
5451 return this.html.replace(this.re, fn);
5469 this.loading = true;
5470 this.compiled = false;
5472 var cx = new Roo.data.Connection();
5476 success : function (response) {
5480 _t.set(response.responseText,true);
5486 failure : function(response) {
5487 Roo.log("Template failed to load from " + _t.url);
5494 * Sets the HTML used as the template and optionally compiles it.
5495 * @param {String} html
5496 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
5497 * @return {Roo.Template} this
5499 set : function(html, compile){
5501 this.compiled = false;
5509 * True to disable format functions (defaults to false)
5512 disableFormats : false,
5515 * The regular expression used to match template variables
5519 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
5522 * Compiles the template into an internal function, eliminating the RegEx overhead.
5523 * @return {Roo.Template} this
5525 compile : function(){
5526 var fm = Roo.util.Format;
5527 var useF = this.disableFormats !== true;
5528 var sep = Roo.isGecko ? "+" : ",";
5529 var fn = function(m, name, format, args){
5531 args = args ? ',' + args : "";
5532 if(format.substr(0, 5) != "this."){
5533 format = "fm." + format + '(';
5535 format = 'this.call("'+ format.substr(5) + '", ';
5539 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
5541 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
5544 // branched to use + in gecko and [].join() in others
5546 body = "this.compiled = function(values){ return '" +
5547 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
5550 body = ["this.compiled = function(values){ return ['"];
5551 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
5552 body.push("'].join('');};");
5553 body = body.join('');
5563 // private function used to call members
5564 call : function(fnName, value, allValues){
5565 return this[fnName](value, allValues);
5569 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
5570 * @param {String/HTMLElement/Roo.Element} el The context element
5571 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
5572 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5573 * @return {HTMLElement/Roo.Element} The new node or Element
5575 insertFirst: function(el, values, returnElement){
5576 return this.doInsert('afterBegin', el, values, returnElement);
5580 * Applies the supplied values to the template and inserts the new node(s) before el.
5581 * @param {String/HTMLElement/Roo.Element} el The context element
5582 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
5583 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5584 * @return {HTMLElement/Roo.Element} The new node or Element
5586 insertBefore: function(el, values, returnElement){
5587 return this.doInsert('beforeBegin', el, values, returnElement);
5591 * Applies the supplied values to the template and inserts the new node(s) after el.
5592 * @param {String/HTMLElement/Roo.Element} el The context element
5593 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
5594 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5595 * @return {HTMLElement/Roo.Element} The new node or Element
5597 insertAfter : function(el, values, returnElement){
5598 return this.doInsert('afterEnd', el, values, returnElement);
5602 * Applies the supplied values to the template and appends the new node(s) to el.
5603 * @param {String/HTMLElement/Roo.Element} el The context element
5604 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
5605 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5606 * @return {HTMLElement/Roo.Element} The new node or Element
5608 append : function(el, values, returnElement){
5609 return this.doInsert('beforeEnd', el, values, returnElement);
5612 doInsert : function(where, el, values, returnEl){
5613 el = Roo.getDom(el);
5614 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
5615 return returnEl ? Roo.get(newNode, true) : newNode;
5619 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
5620 * @param {String/HTMLElement/Roo.Element} el The context element
5621 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
5622 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5623 * @return {HTMLElement/Roo.Element} The new node or Element
5625 overwrite : function(el, values, returnElement){
5626 el = Roo.getDom(el);
5627 el.innerHTML = this.applyTemplate(values);
5628 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5632 * Alias for {@link #applyTemplate}
5635 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
5638 Roo.DomHelper.Template = Roo.Template;
5641 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
5642 * @param {String/HTMLElement} el A DOM element or its id
5643 * @returns {Roo.Template} The created template
5646 Roo.Template.from = function(el){
5647 el = Roo.getDom(el);
5648 return new Roo.Template(el.value || el.innerHTML);
5651 * Ext JS Library 1.1.1
5652 * Copyright(c) 2006-2007, Ext JS, LLC.
5654 * Originally Released Under LGPL - original licence link has changed is not relivant.
5657 * <script type="text/javascript">
5662 * This is code is also distributed under MIT license for use
5663 * with jQuery and prototype JavaScript libraries.
5666 * @class Roo.DomQuery
5667 Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in).
5669 DomQuery supports most of the <a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/">CSS3 selectors spec</a>, along with some custom selectors and basic XPath.</p>
5672 All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example "div.foo:nth-child(odd)[@foo=bar].bar:first" would be a perfectly valid selector. Node filters are processed in the order in which they appear, which allows you to optimize your queries for your document structure.
5674 <h4>Element Selectors:</h4>
5676 <li> <b>*</b> any element</li>
5677 <li> <b>E</b> an element with the tag E</li>
5678 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
5679 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
5680 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
5681 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
5683 <h4>Attribute Selectors:</h4>
5684 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
5686 <li> <b>E[foo]</b> has an attribute "foo"</li>
5687 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
5688 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
5689 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
5690 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
5691 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
5692 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
5694 <h4>Pseudo Classes:</h4>
5696 <li> <b>E:first-child</b> E is the first child of its parent</li>
5697 <li> <b>E:last-child</b> E is the last child of its parent</li>
5698 <li> <b>E:nth-child(<i>n</i>)</b> E is the <i>n</i>th child of its parent (1 based as per the spec)</li>
5699 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
5700 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
5701 <li> <b>E:only-child</b> E is the only child of its parent</li>
5702 <li> <b>E:checked</b> E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) </li>
5703 <li> <b>E:first</b> the first E in the resultset</li>
5704 <li> <b>E:last</b> the last E in the resultset</li>
5705 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
5706 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
5707 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
5708 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
5709 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
5710 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
5711 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
5712 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
5713 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
5715 <h4>CSS Value Selectors:</h4>
5717 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
5718 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
5719 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
5720 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
5721 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
5722 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
5726 Roo.DomQuery = function(){
5727 var cache = {}, simpleCache = {}, valueCache = {};
5728 var nonSpace = /\S/;
5729 var trimRe = /^\s+|\s+$/g;
5730 var tplRe = /\{(\d+)\}/g;
5731 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
5732 var tagTokenRe = /^(#)?([\w-\*]+)/;
5733 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
5735 function child(p, index){
5737 var n = p.firstChild;
5739 if(n.nodeType == 1){
5750 while((n = n.nextSibling) && n.nodeType != 1);
5755 while((n = n.previousSibling) && n.nodeType != 1);
5759 function children(d){
5760 var n = d.firstChild, ni = -1;
5762 var nx = n.nextSibling;
5763 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
5773 function byClassName(c, a, v){
5777 var r = [], ri = -1, cn;
5778 for(var i = 0, ci; ci = c[i]; i++){
5782 ( (ci instanceof SVGElement) ? ci.className.baseVal : ci.className)
5783 +' ').indexOf(v) != -1){
5790 function attrValue(n, attr){
5791 if(!n.tagName && typeof n.length != "undefined"){
5800 if(attr == "class" || attr == "className"){
5801 return (n instanceof SVGElement) ? n.className.baseVal : n.className;
5803 return n.getAttribute(attr) || n[attr];
5807 function getNodes(ns, mode, tagName){
5808 var result = [], ri = -1, cs;
5812 tagName = tagName || "*";
5813 if(typeof ns.getElementsByTagName != "undefined"){
5817 for(var i = 0, ni; ni = ns[i]; i++){
5818 cs = ni.getElementsByTagName(tagName);
5819 for(var j = 0, ci; ci = cs[j]; j++){
5823 }else if(mode == "/" || mode == ">"){
5824 var utag = tagName.toUpperCase();
5825 for(var i = 0, ni, cn; ni = ns[i]; i++){
5826 cn = ni.children || ni.childNodes;
5827 for(var j = 0, cj; cj = cn[j]; j++){
5828 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5833 }else if(mode == "+"){
5834 var utag = tagName.toUpperCase();
5835 for(var i = 0, n; n = ns[i]; i++){
5836 while((n = n.nextSibling) && n.nodeType != 1);
5837 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5841 }else if(mode == "~"){
5842 for(var i = 0, n; n = ns[i]; i++){
5843 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5852 function concat(a, b){
5856 for(var i = 0, l = b.length; i < l; i++){
5862 function byTag(cs, tagName){
5863 if(cs.tagName || cs == document){
5869 var r = [], ri = -1;
5870 tagName = tagName.toLowerCase();
5871 for(var i = 0, ci; ci = cs[i]; i++){
5872 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
5879 function byId(cs, attr, id){
5880 if(cs.tagName || cs == document){
5886 var r = [], ri = -1;
5887 for(var i = 0,ci; ci = cs[i]; i++){
5888 if(ci && ci.id == id){
5896 function byAttribute(cs, attr, value, op, custom){
5897 var r = [], ri = -1, st = custom=="{";
5898 var f = Roo.DomQuery.operators[op];
5899 for(var i = 0, ci; ci = cs[i]; i++){
5902 a = Roo.DomQuery.getStyle(ci, attr);
5904 else if(attr == "class" || attr == "className"){
5905 a = (ci instanceof SVGElement) ? ci.className.baseVal : ci.className;
5906 }else if(attr == "for"){
5908 }else if(attr == "href"){
5909 a = ci.getAttribute("href", 2);
5911 a = ci.getAttribute(attr);
5913 if((f && f(a, value)) || (!f && a)){
5920 function byPseudo(cs, name, value){
5921 return Roo.DomQuery.pseudos[name](cs, value);
5924 // This is for IE MSXML which does not support expandos.
5925 // IE runs the same speed using setAttribute, however FF slows way down
5926 // and Safari completely fails so they need to continue to use expandos.
5927 var isIE = window.ActiveXObject ? true : false;
5929 // this eval is stop the compressor from
5930 // renaming the variable to something shorter
5932 /** eval:var:batch */
5937 function nodupIEXml(cs){
5939 cs[0].setAttribute("_nodup", d);
5941 for(var i = 1, len = cs.length; i < len; i++){
5943 if(!c.getAttribute("_nodup") != d){
5944 c.setAttribute("_nodup", d);
5948 for(var i = 0, len = cs.length; i < len; i++){
5949 cs[i].removeAttribute("_nodup");
5958 var len = cs.length, c, i, r = cs, cj, ri = -1;
5959 if(!len || typeof cs.nodeType != "undefined" || len == 1){
5962 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
5963 return nodupIEXml(cs);
5967 for(i = 1; c = cs[i]; i++){
5972 for(var j = 0; j < i; j++){
5975 for(j = i+1; cj = cs[j]; j++){
5987 function quickDiffIEXml(c1, c2){
5989 for(var i = 0, len = c1.length; i < len; i++){
5990 c1[i].setAttribute("_qdiff", d);
5993 for(var i = 0, len = c2.length; i < len; i++){
5994 if(c2[i].getAttribute("_qdiff") != d){
5995 r[r.length] = c2[i];
5998 for(var i = 0, len = c1.length; i < len; i++){
5999 c1[i].removeAttribute("_qdiff");
6004 function quickDiff(c1, c2){
6005 var len1 = c1.length;
6009 if(isIE && c1[0].selectSingleNode){
6010 return quickDiffIEXml(c1, c2);
6013 for(var i = 0; i < len1; i++){
6017 for(var i = 0, len = c2.length; i < len; i++){
6018 if(c2[i]._qdiff != d){
6019 r[r.length] = c2[i];
6025 function quickId(ns, mode, root, id){
6027 var d = root.ownerDocument || root;
6028 return d.getElementById(id);
6030 ns = getNodes(ns, mode, "*");
6031 return byId(ns, null, id);
6035 getStyle : function(el, name){
6036 return Roo.fly(el).getStyle(name);
6039 * Compiles a selector/xpath query into a reusable function. The returned function
6040 * takes one parameter "root" (optional), which is the context node from where the query should start.
6041 * @param {String} selector The selector/xpath query
6042 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
6043 * @return {Function}
6045 compile : function(path, type){
6046 type = type || "select";
6048 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
6049 var q = path, mode, lq;
6050 var tk = Roo.DomQuery.matchers;
6051 var tklen = tk.length;
6054 // accept leading mode switch
6055 var lmode = q.match(modeRe);
6056 if(lmode && lmode[1]){
6057 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
6058 q = q.replace(lmode[1], "");
6060 // strip leading slashes
6061 while(path.substr(0, 1)=="/"){
6062 path = path.substr(1);
6065 while(q && lq != q){
6067 var tm = q.match(tagTokenRe);
6068 if(type == "select"){
6071 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
6073 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
6075 q = q.replace(tm[0], "");
6076 }else if(q.substr(0, 1) != '@'){
6077 fn[fn.length] = 'n = getNodes(n, mode, "*");';
6082 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
6084 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
6086 q = q.replace(tm[0], "");
6089 while(!(mm = q.match(modeRe))){
6090 var matched = false;
6091 for(var j = 0; j < tklen; j++){
6093 var m = q.match(t.re);
6095 fn[fn.length] = t.select.replace(tplRe, function(x, i){
6098 q = q.replace(m[0], "");
6103 // prevent infinite loop on bad selector
6105 throw 'Error parsing selector, parsing failed at "' + q + '"';
6109 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
6110 q = q.replace(mm[1], "");
6113 fn[fn.length] = "return nodup(n);\n}";
6116 * list of variables that need from compression as they are used by eval.
6126 * eval:var:byClassName
6128 * eval:var:byAttribute
6129 * eval:var:attrValue
6137 * Selects a group of elements.
6138 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
6139 * @param {Node} root (optional) The start of the query (defaults to document).
6142 select : function(path, root, type){
6143 if(!root || root == document){
6146 if(typeof root == "string"){
6147 root = document.getElementById(root);
6149 var paths = path.split(",");
6151 for(var i = 0, len = paths.length; i < len; i++){
6152 var p = paths[i].replace(trimRe, "");
6154 cache[p] = Roo.DomQuery.compile(p);
6156 throw p + " is not a valid selector";
6159 var result = cache[p](root);
6160 if(result && result != document){
6161 results = results.concat(result);
6164 if(paths.length > 1){
6165 return nodup(results);
6171 * Selects a single element.
6172 * @param {String} selector The selector/xpath query
6173 * @param {Node} root (optional) The start of the query (defaults to document).
6176 selectNode : function(path, root){
6177 return Roo.DomQuery.select(path, root)[0];
6181 * Selects the value of a node, optionally replacing null with the defaultValue.
6182 * @param {String} selector The selector/xpath query
6183 * @param {Node} root (optional) The start of the query (defaults to document).
6184 * @param {String} defaultValue
6186 selectValue : function(path, root, defaultValue){
6187 path = path.replace(trimRe, "");
6188 if(!valueCache[path]){
6189 valueCache[path] = Roo.DomQuery.compile(path, "select");
6191 var n = valueCache[path](root);
6192 n = n[0] ? n[0] : n;
6193 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
6194 return ((v === null||v === undefined||v==='') ? defaultValue : v);
6198 * Selects the value of a node, parsing integers and floats.
6199 * @param {String} selector The selector/xpath query
6200 * @param {Node} root (optional) The start of the query (defaults to document).
6201 * @param {Number} defaultValue
6204 selectNumber : function(path, root, defaultValue){
6205 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
6206 return parseFloat(v);
6210 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
6211 * @param {String/HTMLElement/Array} el An element id, element or array of elements
6212 * @param {String} selector The simple selector to test
6215 is : function(el, ss){
6216 if(typeof el == "string"){
6217 el = document.getElementById(el);
6219 var isArray = (el instanceof Array);
6220 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
6221 return isArray ? (result.length == el.length) : (result.length > 0);
6225 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
6226 * @param {Array} el An array of elements to filter
6227 * @param {String} selector The simple selector to test
6228 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
6229 * the selector instead of the ones that match
6232 filter : function(els, ss, nonMatches){
6233 ss = ss.replace(trimRe, "");
6234 if(!simpleCache[ss]){
6235 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
6237 var result = simpleCache[ss](els);
6238 return nonMatches ? quickDiff(result, els) : result;
6242 * Collection of matching regular expressions and code snippets.
6246 select: 'n = byClassName(n, null, " {1} ");'
6248 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
6249 select: 'n = byPseudo(n, "{1}", "{2}");'
6251 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
6252 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
6255 select: 'n = byId(n, null, "{1}");'
6258 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
6263 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
6264 * New operators can be added as long as the match the format <i>c</i>= where <i>c</i> is any character other than space, > <.
6267 "=" : function(a, v){
6270 "!=" : function(a, v){
6273 "^=" : function(a, v){
6274 return a && a.substr(0, v.length) == v;
6276 "$=" : function(a, v){
6277 return a && a.substr(a.length-v.length) == v;
6279 "*=" : function(a, v){
6280 return a && a.indexOf(v) !== -1;
6282 "%=" : function(a, v){
6283 return (a % v) == 0;
6285 "|=" : function(a, v){
6286 return a && (a == v || a.substr(0, v.length+1) == v+'-');
6288 "~=" : function(a, v){
6289 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
6294 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
6295 * and the argument (if any) supplied in the selector.
6298 "first-child" : function(c){
6299 var r = [], ri = -1, n;
6300 for(var i = 0, ci; ci = n = c[i]; i++){
6301 while((n = n.previousSibling) && n.nodeType != 1);
6309 "last-child" : function(c){
6310 var r = [], ri = -1, n;
6311 for(var i = 0, ci; ci = n = c[i]; i++){
6312 while((n = n.nextSibling) && n.nodeType != 1);
6320 "nth-child" : function(c, a) {
6321 var r = [], ri = -1;
6322 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
6323 var f = (m[1] || 1) - 0, l = m[2] - 0;
6324 for(var i = 0, n; n = c[i]; i++){
6325 var pn = n.parentNode;
6326 if (batch != pn._batch) {
6328 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
6329 if(cn.nodeType == 1){
6336 if (l == 0 || n.nodeIndex == l){
6339 } else if ((n.nodeIndex + l) % f == 0){
6347 "only-child" : function(c){
6348 var r = [], ri = -1;;
6349 for(var i = 0, ci; ci = c[i]; i++){
6350 if(!prev(ci) && !next(ci)){
6357 "empty" : function(c){
6358 var r = [], ri = -1;
6359 for(var i = 0, ci; ci = c[i]; i++){
6360 var cns = ci.childNodes, j = 0, cn, empty = true;
6363 if(cn.nodeType == 1 || cn.nodeType == 3){
6375 "contains" : function(c, v){
6376 var r = [], ri = -1;
6377 for(var i = 0, ci; ci = c[i]; i++){
6378 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
6385 "nodeValue" : function(c, v){
6386 var r = [], ri = -1;
6387 for(var i = 0, ci; ci = c[i]; i++){
6388 if(ci.firstChild && ci.firstChild.nodeValue == v){
6395 "checked" : function(c){
6396 var r = [], ri = -1;
6397 for(var i = 0, ci; ci = c[i]; i++){
6398 if(ci.checked == true){
6405 "not" : function(c, ss){
6406 return Roo.DomQuery.filter(c, ss, true);
6409 "odd" : function(c){
6410 return this["nth-child"](c, "odd");
6413 "even" : function(c){
6414 return this["nth-child"](c, "even");
6417 "nth" : function(c, a){
6418 return c[a-1] || [];
6421 "first" : function(c){
6425 "last" : function(c){
6426 return c[c.length-1] || [];
6429 "has" : function(c, ss){
6430 var s = Roo.DomQuery.select;
6431 var r = [], ri = -1;
6432 for(var i = 0, ci; ci = c[i]; i++){
6433 if(s(ss, ci).length > 0){
6440 "next" : function(c, ss){
6441 var is = Roo.DomQuery.is;
6442 var r = [], ri = -1;
6443 for(var i = 0, ci; ci = c[i]; i++){
6452 "prev" : function(c, ss){
6453 var is = Roo.DomQuery.is;
6454 var r = [], ri = -1;
6455 for(var i = 0, ci; ci = c[i]; i++){
6468 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
6469 * @param {String} path The selector/xpath query
6470 * @param {Node} root (optional) The start of the query (defaults to document).
6475 Roo.query = Roo.DomQuery.select;
6478 * Ext JS Library 1.1.1
6479 * Copyright(c) 2006-2007, Ext JS, LLC.
6481 * Originally Released Under LGPL - original licence link has changed is not relivant.
6484 * <script type="text/javascript">
6488 * @class Roo.util.Observable
6489 * Base class that provides a common interface for publishing events. Subclasses are expected to
6490 * to have a property "events" with all the events defined.<br>
6493 Employee = function(name){
6500 Roo.extend(Employee, Roo.util.Observable);
6502 * @param {Object} config properties to use (incuding events / listeners)
6505 Roo.util.Observable = function(cfg){
6508 this.addEvents(cfg.events || {});
6510 delete cfg.events; // make sure
6513 Roo.apply(this, cfg);
6516 this.on(this.listeners);
6517 delete this.listeners;
6520 Roo.util.Observable.prototype = {
6522 * @cfg {Object} listeners list of events and functions to call for this object,
6526 'click' : function(e) {
6536 * Fires the specified event with the passed parameters (minus the event name).
6537 * @param {String} eventName
6538 * @param {Object...} args Variable number of parameters are passed to handlers
6539 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
6541 fireEvent : function(){
6542 var ce = this.events[arguments[0].toLowerCase()];
6543 if(typeof ce == "object"){
6544 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
6551 filterOptRe : /^(?:scope|delay|buffer|single)$/,
6554 * Appends an event handler to this component
6555 * @param {String} eventName The type of event to listen for
6556 * @param {Function} handler The method the event invokes
6557 * @param {Object} scope (optional) The scope in which to execute the handler
6558 * function. The handler function's "this" context.
6559 * @param {Object} options (optional) An object containing handler configuration
6560 * properties. This may contain any of the following properties:<ul>
6561 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6562 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6563 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6564 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6565 * by the specified number of milliseconds. If the event fires again within that time, the original
6566 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6569 * <b>Combining Options</b><br>
6570 * Using the options argument, it is possible to combine different types of listeners:<br>
6572 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
6574 el.on('click', this.onClick, this, {
6581 * <b>Attaching multiple handlers in 1 call</b><br>
6582 * The method also allows for a single argument to be passed which is a config object containing properties
6583 * which specify multiple handlers.
6592 fn: this.onMouseOver,
6596 fn: this.onMouseOut,
6602 * Or a shorthand syntax which passes the same scope object to all handlers:
6605 'click': this.onClick,
6606 'mouseover': this.onMouseOver,
6607 'mouseout': this.onMouseOut,
6612 addListener : function(eventName, fn, scope, o){
6613 if(typeof eventName == "object"){
6616 if(this.filterOptRe.test(e)){
6619 if(typeof o[e] == "function"){
6621 this.addListener(e, o[e], o.scope, o);
6623 // individual options
6624 this.addListener(e, o[e].fn, o[e].scope, o[e]);
6629 o = (!o || typeof o == "boolean") ? {} : o;
6630 eventName = eventName.toLowerCase();
6631 var ce = this.events[eventName] || true;
6632 if(typeof ce == "boolean"){
6633 ce = new Roo.util.Event(this, eventName);
6634 this.events[eventName] = ce;
6636 ce.addListener(fn, scope, o);
6640 * Removes a listener
6641 * @param {String} eventName The type of event to listen for
6642 * @param {Function} handler The handler to remove
6643 * @param {Object} scope (optional) The scope (this object) for the handler
6645 removeListener : function(eventName, fn, scope){
6646 var ce = this.events[eventName.toLowerCase()];
6647 if(typeof ce == "object"){
6648 ce.removeListener(fn, scope);
6653 * Removes all listeners for this object
6655 purgeListeners : function(){
6656 for(var evt in this.events){
6657 if(typeof this.events[evt] == "object"){
6658 this.events[evt].clearListeners();
6663 relayEvents : function(o, events){
6664 var createHandler = function(ename){
6667 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
6670 for(var i = 0, len = events.length; i < len; i++){
6671 var ename = events[i];
6672 if(!this.events[ename]){
6673 this.events[ename] = true;
6675 o.on(ename, createHandler(ename), this);
6680 * Used to define events on this Observable
6681 * @param {Object} object The object with the events defined
6683 addEvents : function(o){
6687 Roo.applyIf(this.events, o);
6691 * Checks to see if this object has any listeners for a specified event
6692 * @param {String} eventName The name of the event to check for
6693 * @return {Boolean} True if the event is being listened for, else false
6695 hasListener : function(eventName){
6696 var e = this.events[eventName];
6697 return typeof e == "object" && e.listeners.length > 0;
6701 * Appends an event handler to this element (shorthand for addListener)
6702 * @param {String} eventName The type of event to listen for
6703 * @param {Function} handler The method the event invokes
6704 * @param {Object} scope (optional) The scope in which to execute the handler
6705 * function. The handler function's "this" context.
6706 * @param {Object} options (optional)
6709 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
6711 * Removes a listener (shorthand for removeListener)
6712 * @param {String} eventName The type of event to listen for
6713 * @param {Function} handler The handler to remove
6714 * @param {Object} scope (optional) The scope (this object) for the handler
6717 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
6720 * Starts capture on the specified Observable. All events will be passed
6721 * to the supplied function with the event name + standard signature of the event
6722 * <b>before</b> the event is fired. If the supplied function returns false,
6723 * the event will not fire.
6724 * @param {Observable} o The Observable to capture
6725 * @param {Function} fn The function to call
6726 * @param {Object} scope (optional) The scope (this object) for the fn
6729 Roo.util.Observable.capture = function(o, fn, scope){
6730 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
6734 * Removes <b>all</b> added captures from the Observable.
6735 * @param {Observable} o The Observable to release
6738 Roo.util.Observable.releaseCapture = function(o){
6739 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
6744 var createBuffered = function(h, o, scope){
6745 var task = new Roo.util.DelayedTask();
6747 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
6751 var createSingle = function(h, e, fn, scope){
6753 e.removeListener(fn, scope);
6754 return h.apply(scope, arguments);
6758 var createDelayed = function(h, o, scope){
6760 var args = Array.prototype.slice.call(arguments, 0);
6761 setTimeout(function(){
6762 h.apply(scope, args);
6767 Roo.util.Event = function(obj, name){
6770 this.listeners = [];
6773 Roo.util.Event.prototype = {
6774 addListener : function(fn, scope, options){
6775 var o = options || {};
6776 scope = scope || this.obj;
6777 if(!this.isListening(fn, scope)){
6778 var l = {fn: fn, scope: scope, options: o};
6781 h = createDelayed(h, o, scope);
6784 h = createSingle(h, this, fn, scope);
6787 h = createBuffered(h, o, scope);
6790 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
6791 this.listeners.push(l);
6793 this.listeners = this.listeners.slice(0);
6794 this.listeners.push(l);
6799 findListener : function(fn, scope){
6800 scope = scope || this.obj;
6801 var ls = this.listeners;
6802 for(var i = 0, len = ls.length; i < len; i++){
6804 if(l.fn == fn && l.scope == scope){
6811 isListening : function(fn, scope){
6812 return this.findListener(fn, scope) != -1;
6815 removeListener : function(fn, scope){
6817 if((index = this.findListener(fn, scope)) != -1){
6819 this.listeners.splice(index, 1);
6821 this.listeners = this.listeners.slice(0);
6822 this.listeners.splice(index, 1);
6829 clearListeners : function(){
6830 this.listeners = [];
6834 var ls = this.listeners, scope, len = ls.length;
6837 var args = Array.prototype.slice.call(arguments, 0);
6838 for(var i = 0; i < len; i++){
6840 if(l.fireFn.apply(l.scope||this.obj||window, args) === false){
6841 this.firing = false;
6845 this.firing = false;
6852 * Copyright(c) 2007-2017, Roo J Solutions Ltd
6859 * @class Roo.Document
6860 * @extends Roo.util.Observable
6861 * This is a convience class to wrap up the main document loading code.. , rather than adding Roo.onReady(......)
6863 * @param {Object} config the methods and properties of the 'base' class for the application.
6865 * Generic Page handler - implement this to start your app..
6868 * MyProject = new Roo.Document({
6870 'load' : true // your events..
6873 'ready' : function() {
6874 // fired on Roo.onReady()
6879 Roo.Document = function(cfg) {
6884 Roo.util.Observable.call(this,cfg);
6888 Roo.onReady(function() {
6889 _this.fireEvent('ready');
6895 Roo.extend(Roo.Document, Roo.util.Observable, {});/*
6897 * Ext JS Library 1.1.1
6898 * Copyright(c) 2006-2007, Ext JS, LLC.
6900 * Originally Released Under LGPL - original licence link has changed is not relivant.
6903 * <script type="text/javascript">
6907 * @class Roo.EventManager
6908 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
6909 * several useful events directly.
6910 * See {@link Roo.EventObject} for more details on normalized event objects.
6913 Roo.EventManager = function(){
6914 var docReadyEvent, docReadyProcId, docReadyState = false;
6915 var resizeEvent, resizeTask, textEvent, textSize;
6916 var E = Roo.lib.Event;
6917 var D = Roo.lib.Dom;
6922 var fireDocReady = function(){
6924 docReadyState = true;
6927 clearInterval(docReadyProcId);
6929 if(Roo.isGecko || Roo.isOpera) {
6930 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
6933 var defer = document.getElementById("ie-deferred-loader");
6935 defer.onreadystatechange = null;
6936 defer.parentNode.removeChild(defer);
6940 docReadyEvent.fire();
6941 docReadyEvent.clearListeners();
6946 var initDocReady = function(){
6947 docReadyEvent = new Roo.util.Event();
6948 if(Roo.isGecko || Roo.isOpera) {
6949 document.addEventListener("DOMContentLoaded", fireDocReady, false);
6951 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
6952 var defer = document.getElementById("ie-deferred-loader");
6953 defer.onreadystatechange = function(){
6954 if(this.readyState == "complete"){
6958 }else if(Roo.isSafari){
6959 docReadyProcId = setInterval(function(){
6960 var rs = document.readyState;
6961 if(rs == "complete") {
6966 // no matter what, make sure it fires on load
6967 E.on(window, "load", fireDocReady);
6970 var createBuffered = function(h, o){
6971 var task = new Roo.util.DelayedTask(h);
6973 // create new event object impl so new events don't wipe out properties
6974 e = new Roo.EventObjectImpl(e);
6975 task.delay(o.buffer, h, null, [e]);
6979 var createSingle = function(h, el, ename, fn){
6981 Roo.EventManager.removeListener(el, ename, fn);
6986 var createDelayed = function(h, o){
6988 // create new event object impl so new events don't wipe out properties
6989 e = new Roo.EventObjectImpl(e);
6990 setTimeout(function(){
6995 var transitionEndVal = false;
6997 var transitionEnd = function()
6999 if (transitionEndVal) {
7000 return transitionEndVal;
7002 var el = document.createElement('div');
7004 var transEndEventNames = {
7005 WebkitTransition : 'webkitTransitionEnd',
7006 MozTransition : 'transitionend',
7007 OTransition : 'oTransitionEnd otransitionend',
7008 transition : 'transitionend'
7011 for (var name in transEndEventNames) {
7012 if (el.style[name] !== undefined) {
7013 transitionEndVal = transEndEventNames[name];
7014 return transitionEndVal ;
7021 var listen = function(element, ename, opt, fn, scope)
7023 var o = (!opt || typeof opt == "boolean") ? {} : opt;
7024 fn = fn || o.fn; scope = scope || o.scope;
7025 var el = Roo.getDom(element);
7029 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
7032 if (ename == 'transitionend') {
7033 ename = transitionEnd();
7035 var h = function(e){
7036 e = Roo.EventObject.setEvent(e);
7039 t = e.getTarget(o.delegate, el);
7046 if(o.stopEvent === true){
7049 if(o.preventDefault === true){
7052 if(o.stopPropagation === true){
7053 e.stopPropagation();
7056 if(o.normalized === false){
7060 fn.call(scope || el, e, t, o);
7063 h = createDelayed(h, o);
7066 h = createSingle(h, el, ename, fn);
7069 h = createBuffered(h, o);
7072 fn._handlers = fn._handlers || [];
7075 fn._handlers.push([Roo.id(el), ename, h]);
7079 E.on(el, ename, h); // this adds the actuall listener to the object..
7082 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
7083 el.addEventListener("DOMMouseScroll", h, false);
7084 E.on(window, 'unload', function(){
7085 el.removeEventListener("DOMMouseScroll", h, false);
7088 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7089 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
7094 var stopListening = function(el, ename, fn){
7095 var id = Roo.id(el), hds = fn._handlers, hd = fn;
7097 for(var i = 0, len = hds.length; i < len; i++){
7099 if(h[0] == id && h[1] == ename){
7106 E.un(el, ename, hd);
7107 el = Roo.getDom(el);
7108 if(ename == "mousewheel" && el.addEventListener){
7109 el.removeEventListener("DOMMouseScroll", hd, false);
7111 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7112 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
7116 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
7123 * @scope Roo.EventManager
7128 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
7129 * object with a Roo.EventObject
7130 * @param {Function} fn The method the event invokes
7131 * @param {Object} scope An object that becomes the scope of the handler
7132 * @param {boolean} override If true, the obj passed in becomes
7133 * the execution scope of the listener
7134 * @return {Function} The wrapped function
7137 wrap : function(fn, scope, override){
7139 Roo.EventObject.setEvent(e);
7140 fn.call(override ? scope || window : window, Roo.EventObject, scope);
7145 * Appends an event handler to an element (shorthand for addListener)
7146 * @param {String/HTMLElement} element The html element or id to assign the
7147 * @param {String} eventName The type of event to listen for
7148 * @param {Function} handler The method the event invokes
7149 * @param {Object} scope (optional) The scope in which to execute the handler
7150 * function. The handler function's "this" context.
7151 * @param {Object} options (optional) An object containing handler configuration
7152 * properties. This may contain any of the following properties:<ul>
7153 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7154 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7155 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7156 * <li>preventDefault {Boolean} True to prevent the default action</li>
7157 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7158 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7159 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7160 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7161 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7162 * by the specified number of milliseconds. If the event fires again within that time, the original
7163 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7166 * <b>Combining Options</b><br>
7167 * Using the options argument, it is possible to combine different types of listeners:<br>
7169 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7171 el.on('click', this.onClick, this, {
7178 * <b>Attaching multiple handlers in 1 call</b><br>
7179 * The method also allows for a single argument to be passed which is a config object containing properties
7180 * which specify multiple handlers.
7190 fn: this.onMouseOver
7199 * Or a shorthand syntax:<br>
7202 'click' : this.onClick,
7203 'mouseover' : this.onMouseOver,
7204 'mouseout' : this.onMouseOut
7208 addListener : function(element, eventName, fn, scope, options){
7209 if(typeof eventName == "object"){
7215 if(typeof o[e] == "function"){
7217 listen(element, e, o, o[e], o.scope);
7219 // individual options
7220 listen(element, e, o[e]);
7225 return listen(element, eventName, options, fn, scope);
7229 * Removes an event handler
7231 * @param {String/HTMLElement} element The id or html element to remove the
7233 * @param {String} eventName The type of event
7234 * @param {Function} fn
7235 * @return {Boolean} True if a listener was actually removed
7237 removeListener : function(element, eventName, fn){
7238 return stopListening(element, eventName, fn);
7242 * Fires when the document is ready (before onload and before images are loaded). Can be
7243 * accessed shorthanded Roo.onReady().
7244 * @param {Function} fn The method the event invokes
7245 * @param {Object} scope An object that becomes the scope of the handler
7246 * @param {boolean} options
7248 onDocumentReady : function(fn, scope, options){
7249 if(docReadyState){ // if it already fired
7250 docReadyEvent.addListener(fn, scope, options);
7251 docReadyEvent.fire();
7252 docReadyEvent.clearListeners();
7258 docReadyEvent.addListener(fn, scope, options);
7262 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
7263 * @param {Function} fn The method the event invokes
7264 * @param {Object} scope An object that becomes the scope of the handler
7265 * @param {boolean} options
7267 onWindowResize : function(fn, scope, options){
7269 resizeEvent = new Roo.util.Event();
7270 resizeTask = new Roo.util.DelayedTask(function(){
7271 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7273 E.on(window, "resize", function()
7275 // it seems that even chrome likes to have a slight delay here.
7277 resizeTask.delay(50);
7279 // resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7283 resizeEvent.addListener(fn, scope, options);
7287 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
7288 * @param {Function} fn The method the event invokes
7289 * @param {Object} scope An object that becomes the scope of the handler
7290 * @param {boolean} options
7292 onTextResize : function(fn, scope, options){
7294 textEvent = new Roo.util.Event();
7295 var textEl = new Roo.Element(document.createElement('div'));
7296 textEl.dom.className = 'x-text-resize';
7297 textEl.dom.innerHTML = 'X';
7298 textEl.appendTo(document.body);
7299 textSize = textEl.dom.offsetHeight;
7300 setInterval(function(){
7301 if(textEl.dom.offsetHeight != textSize){
7302 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
7304 }, this.textResizeInterval);
7306 textEvent.addListener(fn, scope, options);
7310 * Removes the passed window resize listener.
7311 * @param {Function} fn The method the event invokes
7312 * @param {Object} scope The scope of handler
7314 removeResizeListener : function(fn, scope){
7316 resizeEvent.removeListener(fn, scope);
7321 fireResize : function(){
7323 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7327 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
7331 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
7333 textResizeInterval : 50
7338 * @scopeAlias pub=Roo.EventManager
7342 * Appends an event handler to an element (shorthand for addListener)
7343 * @param {String/HTMLElement} element The html element or id to assign the
7344 * @param {String} eventName The type of event to listen for
7345 * @param {Function} handler The method the event invokes
7346 * @param {Object} scope (optional) The scope in which to execute the handler
7347 * function. The handler function's "this" context.
7348 * @param {Object} options (optional) An object containing handler configuration
7349 * properties. This may contain any of the following properties:<ul>
7350 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7351 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7352 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7353 * <li>preventDefault {Boolean} True to prevent the default action</li>
7354 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7355 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7356 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7357 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7358 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7359 * by the specified number of milliseconds. If the event fires again within that time, the original
7360 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7363 * <b>Combining Options</b><br>
7364 * Using the options argument, it is possible to combine different types of listeners:<br>
7366 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7368 el.on('click', this.onClick, this, {
7375 * <b>Attaching multiple handlers in 1 call</b><br>
7376 * The method also allows for a single argument to be passed which is a config object containing properties
7377 * which specify multiple handlers.
7387 fn: this.onMouseOver
7396 * Or a shorthand syntax:<br>
7399 'click' : this.onClick,
7400 'mouseover' : this.onMouseOver,
7401 'mouseout' : this.onMouseOut
7405 pub.on = pub.addListener;
7406 pub.un = pub.removeListener;
7408 pub.stoppedMouseDownEvent = new Roo.util.Event();
7412 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
7413 * @param {Function} fn The method the event invokes
7414 * @param {Object} scope An object that becomes the scope of the handler
7415 * @param {boolean} override If true, the obj passed in becomes
7416 * the execution scope of the listener
7420 Roo.onReady = Roo.EventManager.onDocumentReady;
7422 Roo.onReady(function(){
7423 var bd = Roo.get(document.body);
7428 : Roo.isIE11 ? "roo-ie11"
7429 : Roo.isEdge ? "roo-edge"
7430 : Roo.isGecko ? "roo-gecko"
7431 : Roo.isOpera ? "roo-opera"
7432 : Roo.isSafari ? "roo-safari" : ""];
7435 cls.push("roo-mac");
7438 cls.push("roo-linux");
7441 cls.push("roo-ios");
7444 cls.push("roo-touch");
7446 if(Roo.isBorderBox){
7447 cls.push('roo-border-box');
7449 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
7450 var p = bd.dom.parentNode;
7452 p.className += ' roo-strict';
7455 bd.addClass(cls.join(' '));
7459 * @class Roo.EventObject
7460 * EventObject exposes the Yahoo! UI Event functionality directly on the object
7461 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
7464 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
7466 var target = e.getTarget();
7469 var myDiv = Roo.get("myDiv");
7470 myDiv.on("click", handleClick);
7472 Roo.EventManager.on("myDiv", 'click', handleClick);
7473 Roo.EventManager.addListener("myDiv", 'click', handleClick);
7477 Roo.EventObject = function(){
7479 var E = Roo.lib.Event;
7481 // safari keypress events for special keys return bad keycodes
7484 63235 : 39, // right
7487 63276 : 33, // page up
7488 63277 : 34, // page down
7489 63272 : 46, // delete
7494 // normalize button clicks
7495 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
7496 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
7498 Roo.EventObjectImpl = function(e){
7500 this.setEvent(e.browserEvent || e);
7503 Roo.EventObjectImpl.prototype = {
7505 * Used to fix doc tools.
7506 * @scope Roo.EventObject.prototype
7512 /** The normal browser event */
7513 browserEvent : null,
7514 /** The button pressed in a mouse event */
7516 /** True if the shift key was down during the event */
7518 /** True if the control key was down during the event */
7520 /** True if the alt key was down during the event */
7579 setEvent : function(e){
7580 if(e == this || (e && e.browserEvent)){ // already wrapped
7583 this.browserEvent = e;
7585 // normalize buttons
7586 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
7587 if(e.type == 'click' && this.button == -1){
7591 this.shiftKey = e.shiftKey;
7592 // mac metaKey behaves like ctrlKey
7593 this.ctrlKey = e.ctrlKey || e.metaKey;
7594 this.altKey = e.altKey;
7595 // in getKey these will be normalized for the mac
7596 this.keyCode = e.keyCode;
7597 // keyup warnings on firefox.
7598 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
7599 // cache the target for the delayed and or buffered events
7600 this.target = E.getTarget(e);
7602 this.xy = E.getXY(e);
7605 this.shiftKey = false;
7606 this.ctrlKey = false;
7607 this.altKey = false;
7617 * Stop the event (preventDefault and stopPropagation)
7619 stopEvent : function(){
7620 if(this.browserEvent){
7621 if(this.browserEvent.type == 'mousedown'){
7622 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7624 E.stopEvent(this.browserEvent);
7629 * Prevents the browsers default handling of the event.
7631 preventDefault : function(){
7632 if(this.browserEvent){
7633 E.preventDefault(this.browserEvent);
7638 isNavKeyPress : function(){
7639 var k = this.keyCode;
7640 k = Roo.isSafari ? (safariKeys[k] || k) : k;
7641 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
7644 isSpecialKey : function(){
7645 var k = this.keyCode;
7646 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
7647 (k == 16) || (k == 17) ||
7648 (k >= 18 && k <= 20) ||
7649 (k >= 33 && k <= 35) ||
7650 (k >= 36 && k <= 39) ||
7651 (k >= 44 && k <= 45);
7654 * Cancels bubbling of the event.
7656 stopPropagation : function(){
7657 if(this.browserEvent){
7658 if(this.type == 'mousedown'){
7659 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7661 E.stopPropagation(this.browserEvent);
7666 * Gets the key code for the event.
7669 getCharCode : function(){
7670 return this.charCode || this.keyCode;
7674 * Returns a normalized keyCode for the event.
7675 * @return {Number} The key code
7677 getKey : function(){
7678 var k = this.keyCode || this.charCode;
7679 return Roo.isSafari ? (safariKeys[k] || k) : k;
7683 * Gets the x coordinate of the event.
7686 getPageX : function(){
7691 * Gets the y coordinate of the event.
7694 getPageY : function(){
7699 * Gets the time of the event.
7702 getTime : function(){
7703 if(this.browserEvent){
7704 return E.getTime(this.browserEvent);
7710 * Gets the page coordinates of the event.
7711 * @return {Array} The xy values like [x, y]
7718 * Gets the target for the event.
7719 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
7720 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7721 search as a number or element (defaults to 10 || document.body)
7722 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7723 * @return {HTMLelement}
7725 getTarget : function(selector, maxDepth, returnEl){
7726 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
7729 * Gets the related target.
7730 * @return {HTMLElement}
7732 getRelatedTarget : function(){
7733 if(this.browserEvent){
7734 return E.getRelatedTarget(this.browserEvent);
7740 * Normalizes mouse wheel delta across browsers
7741 * @return {Number} The delta
7743 getWheelDelta : function(){
7744 var e = this.browserEvent;
7746 if(e.wheelDelta){ /* IE/Opera. */
7747 delta = e.wheelDelta/120;
7748 }else if(e.detail){ /* Mozilla case. */
7749 delta = -e.detail/3;
7755 * Returns true if the control, meta, shift or alt key was pressed during this event.
7758 hasModifier : function(){
7759 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
7763 * Returns true if the target of this event equals el or is a child of el
7764 * @param {String/HTMLElement/Element} el
7765 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
7768 within : function(el, related){
7769 var t = this[related ? "getRelatedTarget" : "getTarget"]();
7770 return t && Roo.fly(el).contains(t);
7773 getPoint : function(){
7774 return new Roo.lib.Point(this.xy[0], this.xy[1]);
7778 return new Roo.EventObjectImpl();
7783 * Ext JS Library 1.1.1
7784 * Copyright(c) 2006-2007, Ext JS, LLC.
7786 * Originally Released Under LGPL - original licence link has changed is not relivant.
7789 * <script type="text/javascript">
7793 // was in Composite Element!??!?!
7796 var D = Roo.lib.Dom;
7797 var E = Roo.lib.Event;
7798 var A = Roo.lib.Anim;
7800 // local style camelizing for speed
7802 var camelRe = /(-[a-z])/gi;
7803 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
7804 var view = document.defaultView;
7807 * @class Roo.Element
7808 * Represents an Element in the DOM.<br><br>
7811 var el = Roo.get("my-div");
7814 var el = getEl("my-div");
7816 // or with a DOM element
7817 var el = Roo.get(myDivElement);
7819 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
7820 * each call instead of constructing a new one.<br><br>
7821 * <b>Animations</b><br />
7822 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
7823 * should either be a boolean (true) or an object literal with animation options. The animation options are:
7825 Option Default Description
7826 --------- -------- ---------------------------------------------
7827 duration .35 The duration of the animation in seconds
7828 easing easeOut The YUI easing method
7829 callback none A function to execute when the anim completes
7830 scope this The scope (this) of the callback function
7832 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
7833 * manipulate the animation. Here's an example:
7835 var el = Roo.get("my-div");
7840 // default animation
7841 el.setWidth(100, true);
7843 // animation with some options set
7850 // using the "anim" property to get the Anim object
7856 el.setWidth(100, opt);
7858 if(opt.anim.isAnimated()){
7862 * <b> Composite (Collections of) Elements</b><br />
7863 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
7864 * @constructor Create a new Element directly.
7865 * @param {String/HTMLElement} element
7866 * @param {Boolean} forceNew (optional) By default the constructor checks to see if there is already an instance of this element in the cache and if there is it returns the same instance. This will skip that check (useful for extending this class).
7868 Roo.Element = function(element, forceNew)
7870 var dom = typeof element == "string" ?
7871 document.getElementById(element) : element;
7873 this.listeners = {};
7875 if(!dom){ // invalid id/element
7879 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
7880 return Roo.Element.cache[id];
7890 * The DOM element ID
7893 this.id = id || Roo.id(dom);
7895 return this; // assumed for cctor?
7898 var El = Roo.Element;
7902 * The element's default display mode (defaults to "")
7905 originalDisplay : "",
7908 // note this is overridden in BS version..
7911 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
7917 * Sets the element's visibility mode. When setVisible() is called it
7918 * will use this to determine whether to set the visibility or the display property.
7919 * @param visMode Element.VISIBILITY or Element.DISPLAY
7920 * @return {Roo.Element} this
7922 setVisibilityMode : function(visMode){
7923 this.visibilityMode = visMode;
7927 * Convenience method for setVisibilityMode(Element.DISPLAY)
7928 * @param {String} display (optional) What to set display to when visible
7929 * @return {Roo.Element} this
7931 enableDisplayMode : function(display){
7932 this.setVisibilityMode(El.DISPLAY);
7933 if(typeof display != "undefined") { this.originalDisplay = display; }
7938 * Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
7939 * @param {String} selector The simple selector to test
7940 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7941 search as a number or element (defaults to 10 || document.body)
7942 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7943 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7945 findParent : function(simpleSelector, maxDepth, returnEl){
7946 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
7947 maxDepth = maxDepth || 50;
7948 if(typeof maxDepth != "number"){
7949 stopEl = Roo.getDom(maxDepth);
7952 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
7953 if(dq.is(p, simpleSelector)){
7954 return returnEl ? Roo.get(p) : p;
7964 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
7965 * @param {String} selector The simple selector to test
7966 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7967 search as a number or element (defaults to 10 || document.body)
7968 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7969 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7971 findParentNode : function(simpleSelector, maxDepth, returnEl){
7972 var p = Roo.fly(this.dom.parentNode, '_internal');
7973 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
7977 * Looks at the scrollable parent element
7979 findScrollableParent : function()
7981 var overflowRegex = /(auto|scroll)/;
7983 if(this.getStyle('position') === 'fixed'){
7984 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
7987 var excludeStaticParent = this.getStyle('position') === "absolute";
7989 for (var parent = this; (parent = Roo.get(parent.dom.parentNode));){
7991 if (excludeStaticParent && parent.getStyle('position') === "static") {
7995 if (overflowRegex.test(parent.getStyle('overflow') + parent.getStyle('overflow-x') + parent.getStyle('overflow-y'))){
7999 if(parent.dom.nodeName.toLowerCase() == 'body'){
8000 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8004 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8008 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
8009 * This is a shortcut for findParentNode() that always returns an Roo.Element.
8010 * @param {String} selector The simple selector to test
8011 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8012 search as a number or element (defaults to 10 || document.body)
8013 * @return {Roo.Element} The matching DOM node (or null if no match was found)
8015 up : function(simpleSelector, maxDepth){
8016 return this.findParentNode(simpleSelector, maxDepth, true);
8022 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
8023 * @param {String} selector The simple selector to test
8024 * @return {Boolean} True if this element matches the selector, else false
8026 is : function(simpleSelector){
8027 return Roo.DomQuery.is(this.dom, simpleSelector);
8031 * Perform animation on this element.
8032 * @param {Object} args The YUI animation control args
8033 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
8034 * @param {Function} onComplete (optional) Function to call when animation completes
8035 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
8036 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
8037 * @return {Roo.Element} this
8039 animate : function(args, duration, onComplete, easing, animType){
8040 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
8045 * @private Internal animation call
8047 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
8048 animType = animType || 'run';
8050 var anim = Roo.lib.Anim[animType](
8052 (opt.duration || defaultDur) || .35,
8053 (opt.easing || defaultEase) || 'easeOut',
8055 Roo.callback(cb, this);
8056 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
8064 // private legacy anim prep
8065 preanim : function(a, i){
8066 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
8070 * Removes worthless text nodes
8071 * @param {Boolean} forceReclean (optional) By default the element
8072 * keeps track if it has been cleaned already so
8073 * you can call this over and over. However, if you update the element and
8074 * need to force a reclean, you can pass true.
8076 clean : function(forceReclean){
8077 if(this.isCleaned && forceReclean !== true){
8081 var d = this.dom, n = d.firstChild, ni = -1;
8083 var nx = n.nextSibling;
8084 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
8091 this.isCleaned = true;
8096 calcOffsetsTo : function(el){
8099 var restorePos = false;
8100 if(el.getStyle('position') == 'static'){
8101 el.position('relative');
8106 while(op && op != d && op.tagName != 'HTML'){
8109 op = op.offsetParent;
8112 el.position('static');
8118 * Scrolls this element into view within the passed container.
8119 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
8120 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
8121 * @return {Roo.Element} this
8123 scrollIntoView : function(container, hscroll){
8124 var c = Roo.getDom(container) || document.body;
8127 var o = this.calcOffsetsTo(c),
8130 b = t+el.offsetHeight,
8131 r = l+el.offsetWidth;
8133 var ch = c.clientHeight;
8134 var ct = parseInt(c.scrollTop, 10);
8135 var cl = parseInt(c.scrollLeft, 10);
8137 var cr = cl + c.clientWidth;
8145 if(hscroll !== false){
8149 c.scrollLeft = r-c.clientWidth;
8156 scrollChildIntoView : function(child, hscroll){
8157 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
8161 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
8162 * the new height may not be available immediately.
8163 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
8164 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
8165 * @param {Function} onComplete (optional) Function to call when animation completes
8166 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
8167 * @return {Roo.Element} this
8169 autoHeight : function(animate, duration, onComplete, easing){
8170 var oldHeight = this.getHeight();
8172 this.setHeight(1); // force clipping
8173 setTimeout(function(){
8174 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
8176 this.setHeight(height);
8178 if(typeof onComplete == "function"){
8182 this.setHeight(oldHeight); // restore original height
8183 this.setHeight(height, animate, duration, function(){
8185 if(typeof onComplete == "function") { onComplete(); }
8186 }.createDelegate(this), easing);
8188 }.createDelegate(this), 0);
8193 * Returns true if this element is an ancestor of the passed element
8194 * @param {HTMLElement/String} el The element to check
8195 * @return {Boolean} True if this element is an ancestor of el, else false
8197 contains : function(el){
8198 if(!el){return false;}
8199 return D.isAncestor(this.dom, el.dom ? el.dom : el);
8203 * Checks whether the element is currently visible using both visibility and display properties.
8204 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
8205 * @return {Boolean} True if the element is currently visible, else false
8207 isVisible : function(deep) {
8208 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
8209 if(deep !== true || !vis){
8212 var p = this.dom.parentNode;
8213 while(p && p.tagName.toLowerCase() != "body"){
8214 if(!Roo.fly(p, '_isVisible').isVisible()){
8223 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
8224 * @param {String} selector The CSS selector
8225 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
8226 * @return {CompositeElement/CompositeElementLite} The composite element
8228 select : function(selector, unique){
8229 return El.select(selector, unique, this.dom);
8233 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
8234 * @param {String} selector The CSS selector
8235 * @return {Array} An array of the matched nodes
8237 query : function(selector, unique){
8238 return Roo.DomQuery.select(selector, this.dom);
8242 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
8243 * @param {String} selector The CSS selector
8244 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8245 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8247 child : function(selector, returnDom){
8248 var n = Roo.DomQuery.selectNode(selector, this.dom);
8249 return returnDom ? n : Roo.get(n);
8253 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
8254 * @param {String} selector The CSS selector
8255 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8256 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8258 down : function(selector, returnDom){
8259 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
8260 return returnDom ? n : Roo.get(n);
8264 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
8265 * @param {String} group The group the DD object is member of
8266 * @param {Object} config The DD config object
8267 * @param {Object} overrides An object containing methods to override/implement on the DD object
8268 * @return {Roo.dd.DD} The DD object
8270 initDD : function(group, config, overrides){
8271 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
8272 return Roo.apply(dd, overrides);
8276 * Initializes a {@link Roo.dd.DDProxy} object for this element.
8277 * @param {String} group The group the DDProxy object is member of
8278 * @param {Object} config The DDProxy config object
8279 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
8280 * @return {Roo.dd.DDProxy} The DDProxy object
8282 initDDProxy : function(group, config, overrides){
8283 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
8284 return Roo.apply(dd, overrides);
8288 * Initializes a {@link Roo.dd.DDTarget} object for this element.
8289 * @param {String} group The group the DDTarget object is member of
8290 * @param {Object} config The DDTarget config object
8291 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
8292 * @return {Roo.dd.DDTarget} The DDTarget object
8294 initDDTarget : function(group, config, overrides){
8295 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
8296 return Roo.apply(dd, overrides);
8300 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
8301 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
8302 * @param {Boolean} visible Whether the element is visible
8303 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8304 * @return {Roo.Element} this
8306 setVisible : function(visible, animate){
8308 if(this.visibilityMode == El.DISPLAY){
8309 this.setDisplayed(visible);
8312 this.dom.style.visibility = visible ? "visible" : "hidden";
8315 // closure for composites
8317 var visMode = this.visibilityMode;
8319 this.setOpacity(.01);
8320 this.setVisible(true);
8322 this.anim({opacity: { to: (visible?1:0) }},
8323 this.preanim(arguments, 1),
8324 null, .35, 'easeIn', function(){
8326 if(visMode == El.DISPLAY){
8327 dom.style.display = "none";
8329 dom.style.visibility = "hidden";
8331 Roo.get(dom).setOpacity(1);
8339 * Returns true if display is not "none"
8342 isDisplayed : function() {
8343 return this.getStyle("display") != "none";
8347 * Toggles the element's visibility or display, depending on visibility mode.
8348 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8349 * @return {Roo.Element} this
8351 toggle : function(animate){
8352 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
8357 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
8358 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
8359 * @return {Roo.Element} this
8361 setDisplayed : function(value) {
8362 if(typeof value == "boolean"){
8363 value = value ? this.originalDisplay : "none";
8365 this.setStyle("display", value);
8370 * Tries to focus the element. Any exceptions are caught and ignored.
8371 * @return {Roo.Element} this
8373 focus : function() {
8381 * Tries to blur the element. Any exceptions are caught and ignored.
8382 * @return {Roo.Element} this
8392 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
8393 * @param {String/Array} className The CSS class to add, or an array of classes
8394 * @return {Roo.Element} this
8396 addClass : function(className){
8397 if(className instanceof Array){
8398 for(var i = 0, len = className.length; i < len; i++) {
8399 this.addClass(className[i]);
8402 if(className && !this.hasClass(className)){
8403 if (this.dom instanceof SVGElement) {
8404 this.dom.className.baseVal =this.dom.className.baseVal + " " + className;
8406 this.dom.className = this.dom.className + " " + className;
8414 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
8415 * @param {String/Array} className The CSS class to add, or an array of classes
8416 * @return {Roo.Element} this
8418 radioClass : function(className){
8419 var siblings = this.dom.parentNode.childNodes;
8420 for(var i = 0; i < siblings.length; i++) {
8421 var s = siblings[i];
8422 if(s.nodeType == 1){
8423 Roo.get(s).removeClass(className);
8426 this.addClass(className);
8431 * Removes one or more CSS classes from the element.
8432 * @param {String/Array} className The CSS class to remove, or an array of classes
8433 * @return {Roo.Element} this
8435 removeClass : function(className){
8437 var cn = this.dom instanceof SVGElement ? this.dom.className.baseVal : this.dom.className;
8438 if(!className || !cn){
8441 if(className instanceof Array){
8442 for(var i = 0, len = className.length; i < len; i++) {
8443 this.removeClass(className[i]);
8446 if(this.hasClass(className)){
8447 var re = this.classReCache[className];
8449 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
8450 this.classReCache[className] = re;
8452 if (this.dom instanceof SVGElement) {
8453 this.dom.className.baseVal = cn.replace(re, " ");
8455 this.dom.className = cn.replace(re, " ");
8466 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
8467 * @param {String} className The CSS class to toggle
8468 * @return {Roo.Element} this
8470 toggleClass : function(className){
8471 if(this.hasClass(className)){
8472 this.removeClass(className);
8474 this.addClass(className);
8480 * Checks if the specified CSS class exists on this element's DOM node.
8481 * @param {String} className The CSS class to check for
8482 * @return {Boolean} True if the class exists, else false
8484 hasClass : function(className){
8485 if (this.dom instanceof SVGElement) {
8486 return className && (' '+this.dom.className.baseVal +' ').indexOf(' '+className+' ') != -1;
8488 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
8492 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
8493 * @param {String} oldClassName The CSS class to replace
8494 * @param {String} newClassName The replacement CSS class
8495 * @return {Roo.Element} this
8497 replaceClass : function(oldClassName, newClassName){
8498 this.removeClass(oldClassName);
8499 this.addClass(newClassName);
8504 * Returns an object with properties matching the styles requested.
8505 * For example, el.getStyles('color', 'font-size', 'width') might return
8506 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
8507 * @param {String} style1 A style name
8508 * @param {String} style2 A style name
8509 * @param {String} etc.
8510 * @return {Object} The style object
8512 getStyles : function(){
8513 var a = arguments, len = a.length, r = {};
8514 for(var i = 0; i < len; i++){
8515 r[a[i]] = this.getStyle(a[i]);
8521 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
8522 * @param {String} property The style property whose value is returned.
8523 * @return {String} The current value of the style property for this element.
8525 getStyle : function(){
8526 return view && view.getComputedStyle ?
8528 var el = this.dom, v, cs, camel;
8529 if(prop == 'float'){
8532 if(el.style && (v = el.style[prop])){
8535 if(cs = view.getComputedStyle(el, "")){
8536 if(!(camel = propCache[prop])){
8537 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8544 var el = this.dom, v, cs, camel;
8545 if(prop == 'opacity'){
8546 if(typeof el.style.filter == 'string'){
8547 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
8549 var fv = parseFloat(m[1]);
8551 return fv ? fv / 100 : 0;
8556 }else if(prop == 'float'){
8557 prop = "styleFloat";
8559 if(!(camel = propCache[prop])){
8560 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8562 if(v = el.style[camel]){
8565 if(cs = el.currentStyle){
8573 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
8574 * @param {String/Object} property The style property to be set, or an object of multiple styles.
8575 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
8576 * @return {Roo.Element} this
8578 setStyle : function(prop, value){
8579 if(typeof prop == "string"){
8581 if (prop == 'float') {
8582 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
8587 if(!(camel = propCache[prop])){
8588 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8591 if(camel == 'opacity') {
8592 this.setOpacity(value);
8594 this.dom.style[camel] = value;
8597 for(var style in prop){
8598 if(typeof prop[style] != "function"){
8599 this.setStyle(style, prop[style]);
8607 * More flexible version of {@link #setStyle} for setting style properties.
8608 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
8609 * a function which returns such a specification.
8610 * @return {Roo.Element} this
8612 applyStyles : function(style){
8613 Roo.DomHelper.applyStyles(this.dom, style);
8618 * Gets the current X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8619 * @return {Number} The X position of the element
8622 return D.getX(this.dom);
8626 * Gets the current Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8627 * @return {Number} The Y position of the element
8630 return D.getY(this.dom);
8634 * Gets the current position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8635 * @return {Array} The XY position of the element
8638 return D.getXY(this.dom);
8642 * Sets the X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8643 * @param {Number} The X position of the element
8644 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8645 * @return {Roo.Element} this
8647 setX : function(x, animate){
8649 D.setX(this.dom, x);
8651 this.setXY([x, this.getY()], this.preanim(arguments, 1));
8657 * Sets the Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8658 * @param {Number} The Y position of the element
8659 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8660 * @return {Roo.Element} this
8662 setY : function(y, animate){
8664 D.setY(this.dom, y);
8666 this.setXY([this.getX(), y], this.preanim(arguments, 1));
8672 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
8673 * @param {String} left The left CSS property value
8674 * @return {Roo.Element} this
8676 setLeft : function(left){
8677 this.setStyle("left", this.addUnits(left));
8682 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
8683 * @param {String} top The top CSS property value
8684 * @return {Roo.Element} this
8686 setTop : function(top){
8687 this.setStyle("top", this.addUnits(top));
8692 * Sets the element's CSS right style.
8693 * @param {String} right The right CSS property value
8694 * @return {Roo.Element} this
8696 setRight : function(right){
8697 this.setStyle("right", this.addUnits(right));
8702 * Sets the element's CSS bottom style.
8703 * @param {String} bottom The bottom CSS property value
8704 * @return {Roo.Element} this
8706 setBottom : function(bottom){
8707 this.setStyle("bottom", this.addUnits(bottom));
8712 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8713 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8714 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
8715 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8716 * @return {Roo.Element} this
8718 setXY : function(pos, animate){
8720 D.setXY(this.dom, pos);
8722 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
8728 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8729 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8730 * @param {Number} x X value for new position (coordinates are page-based)
8731 * @param {Number} y Y value for new position (coordinates are page-based)
8732 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8733 * @return {Roo.Element} this
8735 setLocation : function(x, y, animate){
8736 this.setXY([x, y], this.preanim(arguments, 2));
8741 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8742 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8743 * @param {Number} x X value for new position (coordinates are page-based)
8744 * @param {Number} y Y value for new position (coordinates are page-based)
8745 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8746 * @return {Roo.Element} this
8748 moveTo : function(x, y, animate){
8749 this.setXY([x, y], this.preanim(arguments, 2));
8754 * Returns the region of the given element.
8755 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
8756 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
8758 getRegion : function(){
8759 return D.getRegion(this.dom);
8763 * Returns the offset height of the element
8764 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
8765 * @return {Number} The element's height
8767 getHeight : function(contentHeight){
8768 var h = this.dom.offsetHeight || 0;
8769 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
8773 * Returns the offset width of the element
8774 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
8775 * @return {Number} The element's width
8777 getWidth : function(contentWidth){
8778 var w = this.dom.offsetWidth || 0;
8779 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
8783 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
8784 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
8785 * if a height has not been set using CSS.
8788 getComputedHeight : function(){
8789 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
8791 h = parseInt(this.getStyle('height'), 10) || 0;
8792 if(!this.isBorderBox()){
8793 h += this.getFrameWidth('tb');
8800 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
8801 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
8802 * if a width has not been set using CSS.
8805 getComputedWidth : function(){
8806 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
8808 w = parseInt(this.getStyle('width'), 10) || 0;
8809 if(!this.isBorderBox()){
8810 w += this.getFrameWidth('lr');
8817 * Returns the size of the element.
8818 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
8819 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
8821 getSize : function(contentSize){
8822 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
8826 * Returns the width and height of the viewport.
8827 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
8829 getViewSize : function(){
8830 var d = this.dom, doc = document, aw = 0, ah = 0;
8831 if(d == doc || d == doc.body){
8832 return {width : D.getViewWidth(), height: D.getViewHeight()};
8835 width : d.clientWidth,
8836 height: d.clientHeight
8842 * Returns the value of the "value" attribute
8843 * @param {Boolean} asNumber true to parse the value as a number
8844 * @return {String/Number}
8846 getValue : function(asNumber){
8847 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
8851 adjustWidth : function(width){
8852 if(typeof width == "number"){
8853 if(this.autoBoxAdjust && !this.isBorderBox()){
8854 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8864 adjustHeight : function(height){
8865 if(typeof height == "number"){
8866 if(this.autoBoxAdjust && !this.isBorderBox()){
8867 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8877 * Set the width of the element
8878 * @param {Number} width The new width
8879 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8880 * @return {Roo.Element} this
8882 setWidth : function(width, animate){
8883 width = this.adjustWidth(width);
8885 this.dom.style.width = this.addUnits(width);
8887 this.anim({width: {to: width}}, this.preanim(arguments, 1));
8893 * Set the height of the element
8894 * @param {Number} height The new height
8895 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8896 * @return {Roo.Element} this
8898 setHeight : function(height, animate){
8899 height = this.adjustHeight(height);
8901 this.dom.style.height = this.addUnits(height);
8903 this.anim({height: {to: height}}, this.preanim(arguments, 1));
8909 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
8910 * @param {Number} width The new width
8911 * @param {Number} height The new height
8912 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8913 * @return {Roo.Element} this
8915 setSize : function(width, height, animate){
8916 if(typeof width == "object"){ // in case of object from getSize()
8917 height = width.height; width = width.width;
8919 width = this.adjustWidth(width); height = this.adjustHeight(height);
8921 this.dom.style.width = this.addUnits(width);
8922 this.dom.style.height = this.addUnits(height);
8924 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
8930 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
8931 * @param {Number} x X value for new position (coordinates are page-based)
8932 * @param {Number} y Y value for new position (coordinates are page-based)
8933 * @param {Number} width The new width
8934 * @param {Number} height The new height
8935 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8936 * @return {Roo.Element} this
8938 setBounds : function(x, y, width, height, animate){
8940 this.setSize(width, height);
8941 this.setLocation(x, y);
8943 width = this.adjustWidth(width); height = this.adjustHeight(height);
8944 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
8945 this.preanim(arguments, 4), 'motion');
8951 * Sets the element's position and size the the specified region. If animation is true then width, height, x and y will be animated concurrently.
8952 * @param {Roo.lib.Region} region The region to fill
8953 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8954 * @return {Roo.Element} this
8956 setRegion : function(region, animate){
8957 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
8962 * Appends an event handler
8964 * @param {String} eventName The type of event to append
8965 * @param {Function} fn The method the event invokes
8966 * @param {Object} scope (optional) The scope (this object) of the fn
8967 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
8969 addListener : function(eventName, fn, scope, options)
8971 if (eventName == 'dblclick') { // doublclick (touchstart) - faked on touch.
8972 this.addListener('touchstart', this.onTapHandler, this);
8975 // we need to handle a special case where dom element is a svg element.
8976 // in this case we do not actua
8981 if (this.dom instanceof SVGElement && !(this.dom instanceof SVGSVGElement)) {
8982 if (typeof(this.listeners[eventName]) == 'undefined') {
8983 this.listeners[eventName] = new Roo.util.Event(this, eventName);
8985 this.listeners[eventName].addListener(fn, scope, options);
8990 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
8995 onTapHandler : function(event)
8997 if(!this.tapedTwice) {
8998 this.tapedTwice = true;
9000 setTimeout( function() {
9001 s.tapedTwice = false;
9005 event.preventDefault();
9006 var revent = new MouseEvent('dblclick', {
9012 this.dom.dispatchEvent(revent);
9013 //action on double tap goes below
9018 * Removes an event handler from this element
9019 * @param {String} eventName the type of event to remove
9020 * @param {Function} fn the method the event invokes
9021 * @param {Function} scope (needed for svg fake listeners)
9022 * @return {Roo.Element} this
9024 removeListener : function(eventName, fn, scope){
9025 Roo.EventManager.removeListener(this.dom, eventName, fn);
9026 if (typeof(this.listeners) == 'undefined' || typeof(this.listeners[eventName]) == 'undefined') {
9029 this.listeners[eventName].removeListener(fn, scope);
9034 * Removes all previous added listeners from this element
9035 * @return {Roo.Element} this
9037 removeAllListeners : function(){
9038 E.purgeElement(this.dom);
9039 this.listeners = {};
9043 relayEvent : function(eventName, observable){
9044 this.on(eventName, function(e){
9045 observable.fireEvent(eventName, e);
9051 * Set the opacity of the element
9052 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
9053 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9054 * @return {Roo.Element} this
9056 setOpacity : function(opacity, animate){
9058 var s = this.dom.style;
9061 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
9062 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
9064 s.opacity = opacity;
9067 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
9073 * Gets the left X coordinate
9074 * @param {Boolean} local True to get the local css position instead of page coordinate
9077 getLeft : function(local){
9081 return parseInt(this.getStyle("left"), 10) || 0;
9086 * Gets the right X coordinate of the element (element X position + element width)
9087 * @param {Boolean} local True to get the local css position instead of page coordinate
9090 getRight : function(local){
9092 return this.getX() + this.getWidth();
9094 return (this.getLeft(true) + this.getWidth()) || 0;
9099 * Gets the top Y coordinate
9100 * @param {Boolean} local True to get the local css position instead of page coordinate
9103 getTop : function(local) {
9107 return parseInt(this.getStyle("top"), 10) || 0;
9112 * Gets the bottom Y coordinate of the element (element Y position + element height)
9113 * @param {Boolean} local True to get the local css position instead of page coordinate
9116 getBottom : function(local){
9118 return this.getY() + this.getHeight();
9120 return (this.getTop(true) + this.getHeight()) || 0;
9125 * Initializes positioning on this element. If a desired position is not passed, it will make the
9126 * the element positioned relative IF it is not already positioned.
9127 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
9128 * @param {Number} zIndex (optional) The zIndex to apply
9129 * @param {Number} x (optional) Set the page X position
9130 * @param {Number} y (optional) Set the page Y position
9132 position : function(pos, zIndex, x, y){
9134 if(this.getStyle('position') == 'static'){
9135 this.setStyle('position', 'relative');
9138 this.setStyle("position", pos);
9141 this.setStyle("z-index", zIndex);
9143 if(x !== undefined && y !== undefined){
9145 }else if(x !== undefined){
9147 }else if(y !== undefined){
9153 * Clear positioning back to the default when the document was loaded
9154 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
9155 * @return {Roo.Element} this
9157 clearPositioning : function(value){
9165 "position" : "static"
9171 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
9172 * snapshot before performing an update and then restoring the element.
9175 getPositioning : function(){
9176 var l = this.getStyle("left");
9177 var t = this.getStyle("top");
9179 "position" : this.getStyle("position"),
9181 "right" : l ? "" : this.getStyle("right"),
9183 "bottom" : t ? "" : this.getStyle("bottom"),
9184 "z-index" : this.getStyle("z-index")
9189 * Gets the width of the border(s) for the specified side(s)
9190 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9191 * passing lr would get the border (l)eft width + the border (r)ight width.
9192 * @return {Number} The width of the sides passed added together
9194 getBorderWidth : function(side){
9195 return this.addStyles(side, El.borders);
9199 * Gets the width of the padding(s) for the specified side(s)
9200 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9201 * passing lr would get the padding (l)eft + the padding (r)ight.
9202 * @return {Number} The padding of the sides passed added together
9204 getPadding : function(side){
9205 return this.addStyles(side, El.paddings);
9209 * Set positioning with an object returned by getPositioning().
9210 * @param {Object} posCfg
9211 * @return {Roo.Element} this
9213 setPositioning : function(pc){
9214 this.applyStyles(pc);
9215 if(pc.right == "auto"){
9216 this.dom.style.right = "";
9218 if(pc.bottom == "auto"){
9219 this.dom.style.bottom = "";
9225 fixDisplay : function(){
9226 if(this.getStyle("display") == "none"){
9227 this.setStyle("visibility", "hidden");
9228 this.setStyle("display", this.originalDisplay); // first try reverting to default
9229 if(this.getStyle("display") == "none"){ // if that fails, default to block
9230 this.setStyle("display", "block");
9236 * Quick set left and top adding default units
9237 * @param {String} left The left CSS property value
9238 * @param {String} top The top CSS property value
9239 * @return {Roo.Element} this
9241 setLeftTop : function(left, top){
9242 this.dom.style.left = this.addUnits(left);
9243 this.dom.style.top = this.addUnits(top);
9248 * Move this element relative to its current position.
9249 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9250 * @param {Number} distance How far to move the element in pixels
9251 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9252 * @return {Roo.Element} this
9254 move : function(direction, distance, animate){
9255 var xy = this.getXY();
9256 direction = direction.toLowerCase();
9260 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
9264 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
9269 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
9274 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
9281 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
9282 * @return {Roo.Element} this
9285 if(!this.isClipped){
9286 this.isClipped = true;
9287 this.originalClip = {
9288 "o": this.getStyle("overflow"),
9289 "x": this.getStyle("overflow-x"),
9290 "y": this.getStyle("overflow-y")
9292 this.setStyle("overflow", "hidden");
9293 this.setStyle("overflow-x", "hidden");
9294 this.setStyle("overflow-y", "hidden");
9300 * Return clipping (overflow) to original clipping before clip() was called
9301 * @return {Roo.Element} this
9303 unclip : function(){
9305 this.isClipped = false;
9306 var o = this.originalClip;
9307 if(o.o){this.setStyle("overflow", o.o);}
9308 if(o.x){this.setStyle("overflow-x", o.x);}
9309 if(o.y){this.setStyle("overflow-y", o.y);}
9316 * Gets the x,y coordinates specified by the anchor position on the element.
9317 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
9318 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
9319 * {width: (target width), height: (target height)} (defaults to the element's current size)
9320 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
9321 * @return {Array} [x, y] An array containing the element's x and y coordinates
9323 getAnchorXY : function(anchor, local, s){
9324 //Passing a different size is useful for pre-calculating anchors,
9325 //especially for anchored animations that change the el size.
9327 var w, h, vp = false;
9330 if(d == document.body || d == document){
9332 w = D.getViewWidth(); h = D.getViewHeight();
9334 w = this.getWidth(); h = this.getHeight();
9337 w = s.width; h = s.height;
9339 var x = 0, y = 0, r = Math.round;
9340 switch((anchor || "tl").toLowerCase()){
9382 var sc = this.getScroll();
9383 return [x + sc.left, y + sc.top];
9385 //Add the element's offset xy
9386 var o = this.getXY();
9387 return [x+o[0], y+o[1]];
9391 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
9392 * supported position values.
9393 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9394 * @param {String} position The position to align to.
9395 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9396 * @return {Array} [x, y]
9398 getAlignToXY : function(el, p, o)
9403 throw "Element.alignTo with an element that doesn't exist";
9405 var c = false; //constrain to viewport
9406 var p1 = "", p2 = "";
9413 }else if(p.indexOf("-") == -1){
9416 p = p.toLowerCase();
9417 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
9419 throw "Element.alignTo with an invalid alignment " + p;
9421 p1 = m[1]; p2 = m[2]; c = !!m[3];
9423 //Subtract the aligned el's internal xy from the target's offset xy
9424 //plus custom offset to get the aligned el's new offset xy
9425 var a1 = this.getAnchorXY(p1, true);
9426 var a2 = el.getAnchorXY(p2, false);
9427 var x = a2[0] - a1[0] + o[0];
9428 var y = a2[1] - a1[1] + o[1];
9430 //constrain the aligned el to viewport if necessary
9431 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
9432 // 5px of margin for ie
9433 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
9435 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
9436 //perpendicular to the vp border, allow the aligned el to slide on that border,
9437 //otherwise swap the aligned el to the opposite border of the target.
9438 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
9439 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
9440 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t") );
9441 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
9444 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
9445 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
9447 if((x+w) > dw + scrollX){
9448 x = swapX ? r.left-w : dw+scrollX-w;
9451 x = swapX ? r.right : scrollX;
9453 if((y+h) > dh + scrollY){
9454 y = swapY ? r.top-h : dh+scrollY-h;
9457 y = swapY ? r.bottom : scrollY;
9464 getConstrainToXY : function(){
9465 var os = {top:0, left:0, bottom:0, right: 0};
9467 return function(el, local, offsets, proposedXY){
9469 offsets = offsets ? Roo.applyIf(offsets, os) : os;
9471 var vw, vh, vx = 0, vy = 0;
9472 if(el.dom == document.body || el.dom == document){
9473 vw = Roo.lib.Dom.getViewWidth();
9474 vh = Roo.lib.Dom.getViewHeight();
9476 vw = el.dom.clientWidth;
9477 vh = el.dom.clientHeight;
9479 var vxy = el.getXY();
9485 var s = el.getScroll();
9487 vx += offsets.left + s.left;
9488 vy += offsets.top + s.top;
9490 vw -= offsets.right;
9491 vh -= offsets.bottom;
9496 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
9497 var x = xy[0], y = xy[1];
9498 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
9500 // only move it if it needs it
9503 // first validate right/bottom
9512 // then make sure top/left isn't negative
9521 return moved ? [x, y] : false;
9526 adjustForConstraints : function(xy, parent, offsets){
9527 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
9531 * Aligns this element with another element relative to the specified anchor points. If the other element is the
9532 * document it aligns it to the viewport.
9533 * The position parameter is optional, and can be specified in any one of the following formats:
9535 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
9536 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
9537 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
9538 * deprecated in favor of the newer two anchor syntax below</i>.</li>
9539 * <li><b>Two anchors</b>: If two values from the table below are passed separated by a dash, the first value is used as the
9540 * element's anchor point, and the second value is used as the target's anchor point.</li>
9542 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
9543 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
9544 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
9545 * that specified in order to enforce the viewport constraints.
9546 * Following are all of the supported anchor positions:
9549 ----- -----------------------------
9550 tl The top left corner (default)
9551 t The center of the top edge
9552 tr The top right corner
9553 l The center of the left edge
9554 c In the center of the element
9555 r The center of the right edge
9556 bl The bottom left corner
9557 b The center of the bottom edge
9558 br The bottom right corner
9562 // align el to other-el using the default positioning ("tl-bl", non-constrained)
9563 el.alignTo("other-el");
9565 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
9566 el.alignTo("other-el", "tr?");
9568 // align the bottom right corner of el with the center left edge of other-el
9569 el.alignTo("other-el", "br-l?");
9571 // align the center of el with the bottom left corner of other-el and
9572 // adjust the x position by -6 pixels (and the y position by 0)
9573 el.alignTo("other-el", "c-bl", [-6, 0]);
9575 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9576 * @param {String} position The position to align to.
9577 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9578 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9579 * @return {Roo.Element} this
9581 alignTo : function(element, position, offsets, animate){
9582 var xy = this.getAlignToXY(element, position, offsets);
9583 this.setXY(xy, this.preanim(arguments, 3));
9588 * Anchors an element to another element and realigns it when the window is resized.
9589 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9590 * @param {String} position The position to align to.
9591 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9592 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
9593 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
9594 * is a number, it is used as the buffer delay (defaults to 50ms).
9595 * @param {Function} callback The function to call after the animation finishes
9596 * @return {Roo.Element} this
9598 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
9599 var action = function(){
9600 this.alignTo(el, alignment, offsets, animate);
9601 Roo.callback(callback, this);
9603 Roo.EventManager.onWindowResize(action, this);
9604 var tm = typeof monitorScroll;
9605 if(tm != 'undefined'){
9606 Roo.EventManager.on(window, 'scroll', action, this,
9607 {buffer: tm == 'number' ? monitorScroll : 50});
9609 action.call(this); // align immediately
9613 * Clears any opacity settings from this element. Required in some cases for IE.
9614 * @return {Roo.Element} this
9616 clearOpacity : function(){
9617 if (window.ActiveXObject) {
9618 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
9619 this.dom.style.filter = "";
9622 this.dom.style.opacity = "";
9623 this.dom.style["-moz-opacity"] = "";
9624 this.dom.style["-khtml-opacity"] = "";
9630 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9631 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9632 * @return {Roo.Element} this
9634 hide : function(animate){
9635 this.setVisible(false, this.preanim(arguments, 0));
9640 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9641 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9642 * @return {Roo.Element} this
9644 show : function(animate){
9645 this.setVisible(true, this.preanim(arguments, 0));
9650 * @private Test if size has a unit, otherwise appends the default
9652 addUnits : function(size){
9653 return Roo.Element.addUnits(size, this.defaultUnit);
9657 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
9658 * @return {Roo.Element} this
9660 beginMeasure : function(){
9662 if(el.offsetWidth || el.offsetHeight){
9663 return this; // offsets work already
9666 var p = this.dom, b = document.body; // start with this element
9667 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
9668 var pe = Roo.get(p);
9669 if(pe.getStyle('display') == 'none'){
9670 changed.push({el: p, visibility: pe.getStyle("visibility")});
9671 p.style.visibility = "hidden";
9672 p.style.display = "block";
9676 this._measureChanged = changed;
9682 * Restores displays to before beginMeasure was called
9683 * @return {Roo.Element} this
9685 endMeasure : function(){
9686 var changed = this._measureChanged;
9688 for(var i = 0, len = changed.length; i < len; i++) {
9690 r.el.style.visibility = r.visibility;
9691 r.el.style.display = "none";
9693 this._measureChanged = null;
9699 * Update the innerHTML of this element, optionally searching for and processing scripts
9700 * @param {String} html The new HTML
9701 * @param {Boolean} loadScripts (optional) true to look for and process scripts
9702 * @param {Function} callback For async script loading you can be noticed when the update completes
9703 * @return {Roo.Element} this
9705 update : function(html, loadScripts, callback){
9706 if(typeof html == "undefined"){
9709 if(loadScripts !== true){
9710 this.dom.innerHTML = html;
9711 if(typeof callback == "function"){
9719 html += '<span id="' + id + '"></span>';
9721 E.onAvailable(id, function(){
9722 var hd = document.getElementsByTagName("head")[0];
9723 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
9724 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
9725 var typeRe = /\stype=([\'\"])(.*?)\1/i;
9728 while(match = re.exec(html)){
9729 var attrs = match[1];
9730 var srcMatch = attrs ? attrs.match(srcRe) : false;
9731 if(srcMatch && srcMatch[2]){
9732 var s = document.createElement("script");
9733 s.src = srcMatch[2];
9734 var typeMatch = attrs.match(typeRe);
9735 if(typeMatch && typeMatch[2]){
9736 s.type = typeMatch[2];
9739 }else if(match[2] && match[2].length > 0){
9740 if(window.execScript) {
9741 window.execScript(match[2]);
9749 window.eval(match[2]);
9753 var el = document.getElementById(id);
9754 if(el){el.parentNode.removeChild(el);}
9755 if(typeof callback == "function"){
9759 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
9764 * Direct access to the UpdateManager update() method (takes the same parameters).
9765 * @param {String/Function} url The url for this request or a function to call to get the url
9766 * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
9767 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
9768 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used url. If true, it will not store the url.
9769 * @return {Roo.Element} this
9772 var um = this.getUpdateManager();
9773 um.update.apply(um, arguments);
9778 * Gets this element's UpdateManager
9779 * @return {Roo.UpdateManager} The UpdateManager
9781 getUpdateManager : function(){
9782 if(!this.updateManager){
9783 this.updateManager = new Roo.UpdateManager(this);
9785 return this.updateManager;
9789 * Disables text selection for this element (normalized across browsers)
9790 * @return {Roo.Element} this
9792 unselectable : function(){
9793 this.dom.unselectable = "on";
9794 this.swallowEvent("selectstart", true);
9795 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
9796 this.addClass("x-unselectable");
9801 * Calculates the x, y to center this element on the screen
9802 * @return {Array} The x, y values [x, y]
9804 getCenterXY : function(){
9805 return this.getAlignToXY(document, 'c-c');
9809 * Centers the Element in either the viewport, or another Element.
9810 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
9812 center : function(centerIn){
9813 this.alignTo(centerIn || document, 'c-c');
9818 * Tests various css rules/browsers to determine if this element uses a border box
9821 isBorderBox : function(){
9822 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
9826 * Return a box {x, y, width, height} that can be used to set another elements
9827 * size/location to match this element.
9828 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
9829 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
9830 * @return {Object} box An object in the format {x, y, width, height}
9832 getBox : function(contentBox, local){
9837 var left = parseInt(this.getStyle("left"), 10) || 0;
9838 var top = parseInt(this.getStyle("top"), 10) || 0;
9841 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
9843 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
9845 var l = this.getBorderWidth("l")+this.getPadding("l");
9846 var r = this.getBorderWidth("r")+this.getPadding("r");
9847 var t = this.getBorderWidth("t")+this.getPadding("t");
9848 var b = this.getBorderWidth("b")+this.getPadding("b");
9849 bx = {x: xy[0]+l, y: xy[1]+t, 0: xy[0]+l, 1: xy[1]+t, width: w-(l+r), height: h-(t+b)};
9851 bx.right = bx.x + bx.width;
9852 bx.bottom = bx.y + bx.height;
9857 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
9858 for more information about the sides.
9859 * @param {String} sides
9862 getFrameWidth : function(sides, onlyContentBox){
9863 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
9867 * Sets the element's box. Use getBox() on another element to get a box obj. If animate is true then width, height, x and y will be animated concurrently.
9868 * @param {Object} box The box to fill {x, y, width, height}
9869 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
9870 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9871 * @return {Roo.Element} this
9873 setBox : function(box, adjust, animate){
9874 var w = box.width, h = box.height;
9875 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
9876 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
9877 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
9879 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
9884 * Forces the browser to repaint this element
9885 * @return {Roo.Element} this
9887 repaint : function(){
9889 this.addClass("x-repaint");
9890 setTimeout(function(){
9891 Roo.get(dom).removeClass("x-repaint");
9897 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
9898 * then it returns the calculated width of the sides (see getPadding)
9899 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
9900 * @return {Object/Number}
9902 getMargins : function(side){
9905 top: parseInt(this.getStyle("margin-top"), 10) || 0,
9906 left: parseInt(this.getStyle("margin-left"), 10) || 0,
9907 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
9908 right: parseInt(this.getStyle("margin-right"), 10) || 0
9911 return this.addStyles(side, El.margins);
9916 addStyles : function(sides, styles){
9918 for(var i = 0, len = sides.length; i < len; i++){
9919 v = this.getStyle(styles[sides.charAt(i)]);
9921 w = parseInt(v, 10);
9929 * Creates a proxy element of this element
9930 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
9931 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
9932 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
9933 * @return {Roo.Element} The new proxy element
9935 createProxy : function(config, renderTo, matchBox){
9937 renderTo = Roo.getDom(renderTo);
9939 renderTo = document.body;
9941 config = typeof config == "object" ?
9942 config : {tag : "div", cls: config};
9943 var proxy = Roo.DomHelper.append(renderTo, config, true);
9945 proxy.setBox(this.getBox());
9951 * Puts a mask over this element to disable user interaction. Requires core.css.
9952 * This method can only be applied to elements which accept child nodes.
9953 * @param {String} msg (optional) A message to display in the mask
9954 * @param {String} msgCls (optional) A css class to apply to the msg element - use no-spinner to hide the spinner on bootstrap
9955 * @return {Element} The mask element
9957 mask : function(msg, msgCls)
9959 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
9960 this.setStyle("position", "relative");
9963 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
9966 this.addClass("x-masked");
9967 this._mask.setDisplayed(true);
9972 while (dom && dom.style) {
9973 if (!isNaN(parseInt(dom.style.zIndex))) {
9974 z = Math.max(z, parseInt(dom.style.zIndex));
9976 dom = dom.parentNode;
9978 // if we are masking the body - then it hides everything..
9979 if (this.dom == document.body) {
9981 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
9982 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
9985 if(typeof msg == 'string'){
9987 this._maskMsg = Roo.DomHelper.append(this.dom, {
9988 cls: "roo-el-mask-msg",
9992 cls: 'fa fa-spinner fa-spin'
10000 var mm = this._maskMsg;
10001 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
10002 if (mm.dom.lastChild) { // weird IE issue?
10003 mm.dom.lastChild.innerHTML = msg;
10005 mm.setDisplayed(true);
10007 mm.setStyle('z-index', z + 102);
10009 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
10010 this._mask.setHeight(this.getHeight());
10012 this._mask.setStyle('z-index', z + 100);
10018 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
10019 * it is cached for reuse.
10021 unmask : function(removeEl){
10023 if(removeEl === true){
10024 this._mask.remove();
10027 this._maskMsg.remove();
10028 delete this._maskMsg;
10031 this._mask.setDisplayed(false);
10033 this._maskMsg.setDisplayed(false);
10037 this.removeClass("x-masked");
10041 * Returns true if this element is masked
10042 * @return {Boolean}
10044 isMasked : function(){
10045 return this._mask && this._mask.isVisible();
10049 * Creates an iframe shim for this element to keep selects and other windowed objects from
10051 * @return {Roo.Element} The new shim element
10053 createShim : function(){
10054 var el = document.createElement('iframe');
10055 el.frameBorder = 'no';
10056 el.className = 'roo-shim';
10057 if(Roo.isIE && Roo.isSecure){
10058 el.src = Roo.SSL_SECURE_URL;
10060 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
10061 shim.autoBoxAdjust = false;
10066 * Removes this element from the DOM and deletes it from the cache
10068 remove : function(){
10069 if(this.dom.parentNode){
10070 this.dom.parentNode.removeChild(this.dom);
10072 delete El.cache[this.dom.id];
10076 * Sets up event handlers to add and remove a css class when the mouse is over this element
10077 * @param {String} className
10078 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
10079 * mouseout events for children elements
10080 * @return {Roo.Element} this
10082 addClassOnOver : function(className, preventFlicker){
10083 this.on("mouseover", function(){
10084 Roo.fly(this, '_internal').addClass(className);
10086 var removeFn = function(e){
10087 if(preventFlicker !== true || !e.within(this, true)){
10088 Roo.fly(this, '_internal').removeClass(className);
10091 this.on("mouseout", removeFn, this.dom);
10096 * Sets up event handlers to add and remove a css class when this element has the focus
10097 * @param {String} className
10098 * @return {Roo.Element} this
10100 addClassOnFocus : function(className){
10101 this.on("focus", function(){
10102 Roo.fly(this, '_internal').addClass(className);
10104 this.on("blur", function(){
10105 Roo.fly(this, '_internal').removeClass(className);
10110 * Sets up event handlers to add and remove a css class when the mouse is down and then up on this element (a click effect)
10111 * @param {String} className
10112 * @return {Roo.Element} this
10114 addClassOnClick : function(className){
10115 var dom = this.dom;
10116 this.on("mousedown", function(){
10117 Roo.fly(dom, '_internal').addClass(className);
10118 var d = Roo.get(document);
10119 var fn = function(){
10120 Roo.fly(dom, '_internal').removeClass(className);
10121 d.removeListener("mouseup", fn);
10123 d.on("mouseup", fn);
10129 * Stops the specified event from bubbling and optionally prevents the default action
10130 * @param {String} eventName
10131 * @param {Boolean} preventDefault (optional) true to prevent the default action too
10132 * @return {Roo.Element} this
10134 swallowEvent : function(eventName, preventDefault){
10135 var fn = function(e){
10136 e.stopPropagation();
10137 if(preventDefault){
10138 e.preventDefault();
10141 if(eventName instanceof Array){
10142 for(var i = 0, len = eventName.length; i < len; i++){
10143 this.on(eventName[i], fn);
10147 this.on(eventName, fn);
10154 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
10157 * Sizes this element to its parent element's dimensions performing
10158 * neccessary box adjustments.
10159 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
10160 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
10161 * @return {Roo.Element} this
10163 fitToParent : function(monitorResize, targetParent) {
10164 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
10165 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
10166 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
10169 var p = Roo.get(targetParent || this.dom.parentNode);
10170 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
10171 if (monitorResize === true) {
10172 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
10173 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
10179 * Gets the next sibling, skipping text nodes
10180 * @return {HTMLElement} The next sibling or null
10182 getNextSibling : function(){
10183 var n = this.dom.nextSibling;
10184 while(n && n.nodeType != 1){
10191 * Gets the previous sibling, skipping text nodes
10192 * @return {HTMLElement} The previous sibling or null
10194 getPrevSibling : function(){
10195 var n = this.dom.previousSibling;
10196 while(n && n.nodeType != 1){
10197 n = n.previousSibling;
10204 * Appends the passed element(s) to this element
10205 * @param {String/HTMLElement/Array/Element/CompositeElement} el
10206 * @return {Roo.Element} this
10208 appendChild: function(el){
10215 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
10216 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
10217 * automatically generated with the specified attributes.
10218 * @param {HTMLElement} insertBefore (optional) a child element of this element
10219 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
10220 * @return {Roo.Element} The new child element
10222 createChild: function(config, insertBefore, returnDom){
10223 config = config || {tag:'div'};
10225 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
10227 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
10231 * Appends this element to the passed element
10232 * @param {String/HTMLElement/Element} el The new parent element
10233 * @return {Roo.Element} this
10235 appendTo: function(el){
10236 el = Roo.getDom(el);
10237 el.appendChild(this.dom);
10242 * Inserts this element before the passed element in the DOM
10243 * @param {String/HTMLElement/Element} el The element to insert before
10244 * @return {Roo.Element} this
10246 insertBefore: function(el){
10247 el = Roo.getDom(el);
10248 el.parentNode.insertBefore(this.dom, el);
10253 * Inserts this element after the passed element in the DOM
10254 * @param {String/HTMLElement/Element} el The element to insert after
10255 * @return {Roo.Element} this
10257 insertAfter: function(el){
10258 el = Roo.getDom(el);
10259 el.parentNode.insertBefore(this.dom, el.nextSibling);
10264 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
10265 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10266 * @return {Roo.Element} The new child
10268 insertFirst: function(el, returnDom){
10270 if(typeof el == 'object' && !el.nodeType){ // dh config
10271 return this.createChild(el, this.dom.firstChild, returnDom);
10273 el = Roo.getDom(el);
10274 this.dom.insertBefore(el, this.dom.firstChild);
10275 return !returnDom ? Roo.get(el) : el;
10280 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
10281 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10282 * @param {String} where (optional) 'before' or 'after' defaults to before
10283 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10284 * @return {Roo.Element} the inserted Element
10286 insertSibling: function(el, where, returnDom){
10287 where = where ? where.toLowerCase() : 'before';
10289 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
10291 if(typeof el == 'object' && !el.nodeType){ // dh config
10292 if(where == 'after' && !this.dom.nextSibling){
10293 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
10295 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
10299 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
10300 where == 'before' ? this.dom : this.dom.nextSibling);
10309 * Creates and wraps this element with another element
10310 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
10311 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10312 * @return {HTMLElement/Element} The newly created wrapper element
10314 wrap: function(config, returnDom){
10316 config = {tag: "div"};
10318 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
10319 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
10324 * Replaces the passed element with this element
10325 * @param {String/HTMLElement/Element} el The element to replace
10326 * @return {Roo.Element} this
10328 replace: function(el){
10330 this.insertBefore(el);
10336 * Inserts an html fragment into this element
10337 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
10338 * @param {String} html The HTML fragment
10339 * @param {Boolean} returnEl True to return an Roo.Element
10340 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
10342 insertHtml : function(where, html, returnEl){
10343 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
10344 return returnEl ? Roo.get(el) : el;
10348 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
10349 * @param {Object} o The object with the attributes
10350 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
10351 * @return {Roo.Element} this
10353 set : function(o, useSet){
10355 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
10356 for(var attr in o){
10357 if(attr == "style" || typeof o[attr] == "function") { continue; }
10359 el.className = o["cls"];
10362 el.setAttribute(attr, o[attr]);
10364 el[attr] = o[attr];
10369 Roo.DomHelper.applyStyles(el, o.style);
10375 * Convenience method for constructing a KeyMap
10376 * @param {Number/Array/Object/String} key Either a string with the keys to listen for, the numeric key code, array of key codes or an object with the following options:
10377 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
10378 * @param {Function} fn The function to call
10379 * @param {Object} scope (optional) The scope of the function
10380 * @return {Roo.KeyMap} The KeyMap created
10382 addKeyListener : function(key, fn, scope){
10384 if(typeof key != "object" || key instanceof Array){
10400 return new Roo.KeyMap(this, config);
10404 * Creates a KeyMap for this element
10405 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
10406 * @return {Roo.KeyMap} The KeyMap created
10408 addKeyMap : function(config){
10409 return new Roo.KeyMap(this, config);
10413 * Returns true if this element is scrollable.
10414 * @return {Boolean}
10416 isScrollable : function(){
10417 var dom = this.dom;
10418 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
10422 * Scrolls this element the specified scroll point. It does NOT do bounds checking so if you scroll to a weird value it will try to do it. For auto bounds checking, use scroll().
10423 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
10424 * @param {Number} value The new scroll value
10425 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10426 * @return {Element} this
10429 scrollTo : function(side, value, animate){
10430 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
10431 if(!animate || !A){
10432 this.dom[prop] = value;
10434 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
10435 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
10441 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
10442 * within this element's scrollable range.
10443 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
10444 * @param {Number} distance How far to scroll the element in pixels
10445 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10446 * @return {Boolean} Returns true if a scroll was triggered or false if the element
10447 * was scrolled as far as it could go.
10449 scroll : function(direction, distance, animate){
10450 if(!this.isScrollable()){
10454 var l = el.scrollLeft, t = el.scrollTop;
10455 var w = el.scrollWidth, h = el.scrollHeight;
10456 var cw = el.clientWidth, ch = el.clientHeight;
10457 direction = direction.toLowerCase();
10458 var scrolled = false;
10459 var a = this.preanim(arguments, 2);
10464 var v = Math.min(l + distance, w-cw);
10465 this.scrollTo("left", v, a);
10472 var v = Math.max(l - distance, 0);
10473 this.scrollTo("left", v, a);
10481 var v = Math.max(t - distance, 0);
10482 this.scrollTo("top", v, a);
10490 var v = Math.min(t + distance, h-ch);
10491 this.scrollTo("top", v, a);
10500 * Translates the passed page coordinates into left/top css values for this element
10501 * @param {Number/Array} x The page x or an array containing [x, y]
10502 * @param {Number} y The page y
10503 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
10505 translatePoints : function(x, y){
10506 if(typeof x == 'object' || x instanceof Array){
10507 y = x[1]; x = x[0];
10509 var p = this.getStyle('position');
10510 var o = this.getXY();
10512 var l = parseInt(this.getStyle('left'), 10);
10513 var t = parseInt(this.getStyle('top'), 10);
10516 l = (p == "relative") ? 0 : this.dom.offsetLeft;
10519 t = (p == "relative") ? 0 : this.dom.offsetTop;
10522 return {left: (x - o[0] + l), top: (y - o[1] + t)};
10526 * Returns the current scroll position of the element.
10527 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
10529 getScroll : function(){
10530 var d = this.dom, doc = document;
10531 if(d == doc || d == doc.body){
10532 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
10533 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
10534 return {left: l, top: t};
10536 return {left: d.scrollLeft, top: d.scrollTop};
10541 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
10542 * are convert to standard 6 digit hex color.
10543 * @param {String} attr The css attribute
10544 * @param {String} defaultValue The default value to use when a valid color isn't found
10545 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
10548 getColor : function(attr, defaultValue, prefix){
10549 var v = this.getStyle(attr);
10550 if(!v || v == "transparent" || v == "inherit") {
10551 return defaultValue;
10553 var color = typeof prefix == "undefined" ? "#" : prefix;
10554 if(v.substr(0, 4) == "rgb("){
10555 var rvs = v.slice(4, v.length -1).split(",");
10556 for(var i = 0; i < 3; i++){
10557 var h = parseInt(rvs[i]).toString(16);
10564 if(v.substr(0, 1) == "#"){
10565 if(v.length == 4) {
10566 for(var i = 1; i < 4; i++){
10567 var c = v.charAt(i);
10570 }else if(v.length == 7){
10571 color += v.substr(1);
10575 return(color.length > 5 ? color.toLowerCase() : defaultValue);
10579 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
10580 * gradient background, rounded corners and a 4-way shadow.
10581 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
10582 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
10583 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
10584 * @return {Roo.Element} this
10586 boxWrap : function(cls){
10587 cls = cls || 'x-box';
10588 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
10589 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
10594 * Returns the value of a namespaced attribute from the element's underlying DOM node.
10595 * @param {String} namespace The namespace in which to look for the attribute
10596 * @param {String} name The attribute name
10597 * @return {String} The attribute value
10599 getAttributeNS : Roo.isIE ? function(ns, name){
10601 var type = typeof d[ns+":"+name];
10602 if(type != 'undefined' && type != 'unknown'){
10603 return d[ns+":"+name];
10606 } : function(ns, name){
10608 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
10613 * Sets or Returns the value the dom attribute value
10614 * @param {String|Object} name The attribute name (or object to set multiple attributes)
10615 * @param {String} value (optional) The value to set the attribute to
10616 * @return {String} The attribute value
10618 attr : function(name){
10619 if (arguments.length > 1) {
10620 this.dom.setAttribute(name, arguments[1]);
10621 return arguments[1];
10623 if (typeof(name) == 'object') {
10624 for(var i in name) {
10625 this.attr(i, name[i]);
10631 if (!this.dom.hasAttribute(name)) {
10634 return this.dom.getAttribute(name);
10641 var ep = El.prototype;
10644 * Appends an event handler (Shorthand for addListener)
10645 * @param {String} eventName The type of event to append
10646 * @param {Function} fn The method the event invokes
10647 * @param {Object} scope (optional) The scope (this object) of the fn
10648 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
10651 ep.on = ep.addListener;
10652 // backwards compat
10653 ep.mon = ep.addListener;
10656 * Removes an event handler from this element (shorthand for removeListener)
10657 * @param {String} eventName the type of event to remove
10658 * @param {Function} fn the method the event invokes
10659 * @return {Roo.Element} this
10662 ep.un = ep.removeListener;
10665 * true to automatically adjust width and height settings for box-model issues (default to true)
10667 ep.autoBoxAdjust = true;
10670 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
10673 El.addUnits = function(v, defaultUnit){
10674 if(v === "" || v == "auto"){
10677 if(v === undefined){
10680 if(typeof v == "number" || !El.unitPattern.test(v)){
10681 return v + (defaultUnit || 'px');
10686 // special markup used throughout Roo when box wrapping elements
10687 El.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>';
10689 * Visibility mode constant - Use visibility to hide element
10695 * Visibility mode constant - Use display to hide element
10701 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
10702 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
10703 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
10715 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10716 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10717 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10718 * @return {Element} The Element object
10721 El.get = function(el){
10723 if(!el){ return null; }
10724 if(typeof el == "string"){ // element id
10725 if(!(elm = document.getElementById(el))){
10728 if(ex = El.cache[el]){
10731 ex = El.cache[el] = new El(elm);
10734 }else if(el.tagName){ // dom element
10738 if(ex = El.cache[id]){
10741 ex = El.cache[id] = new El(el);
10744 }else if(el instanceof El){
10746 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
10747 // catch case where it hasn't been appended
10748 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
10751 }else if(el.isComposite){
10753 }else if(el instanceof Array){
10754 return El.select(el);
10755 }else if(el == document){
10756 // create a bogus element object representing the document object
10758 var f = function(){};
10759 f.prototype = El.prototype;
10761 docEl.dom = document;
10769 El.uncache = function(el){
10770 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
10772 delete El.cache[a[i].id || a[i]];
10778 // Garbage collection - uncache elements/purge listeners on orphaned elements
10779 // so we don't hold a reference and cause the browser to retain them
10780 El.garbageCollect = function(){
10781 if(!Roo.enableGarbageCollector){
10782 clearInterval(El.collectorThread);
10785 for(var eid in El.cache){
10786 var el = El.cache[eid], d = el.dom;
10787 // -------------------------------------------------------
10788 // Determining what is garbage:
10789 // -------------------------------------------------------
10791 // dom node is null, definitely garbage
10792 // -------------------------------------------------------
10794 // no parentNode == direct orphan, definitely garbage
10795 // -------------------------------------------------------
10796 // !d.offsetParent && !document.getElementById(eid)
10797 // display none elements have no offsetParent so we will
10798 // also try to look it up by it's id. However, check
10799 // offsetParent first so we don't do unneeded lookups.
10800 // This enables collection of elements that are not orphans
10801 // directly, but somewhere up the line they have an orphan
10803 // -------------------------------------------------------
10804 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
10805 delete El.cache[eid];
10806 if(d && Roo.enableListenerCollection){
10812 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
10816 El.Flyweight = function(dom){
10819 El.Flyweight.prototype = El.prototype;
10821 El._flyweights = {};
10823 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10824 * the dom node can be overwritten by other code.
10825 * @param {String/HTMLElement} el The dom node or id
10826 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10827 * prevent conflicts (e.g. internally Roo uses "_internal")
10829 * @return {Element} The shared Element object
10831 El.fly = function(el, named){
10832 named = named || '_global';
10833 el = Roo.getDom(el);
10837 if(!El._flyweights[named]){
10838 El._flyweights[named] = new El.Flyweight();
10840 El._flyweights[named].dom = el;
10841 return El._flyweights[named];
10845 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10846 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10847 * Shorthand of {@link Roo.Element#get}
10848 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10849 * @return {Element} The Element object
10855 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10856 * the dom node can be overwritten by other code.
10857 * Shorthand of {@link Roo.Element#fly}
10858 * @param {String/HTMLElement} el The dom node or id
10859 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10860 * prevent conflicts (e.g. internally Roo uses "_internal")
10862 * @return {Element} The shared Element object
10868 // speedy lookup for elements never to box adjust
10869 var noBoxAdjust = Roo.isStrict ? {
10872 input:1, select:1, textarea:1
10874 if(Roo.isIE || Roo.isGecko){
10875 noBoxAdjust['button'] = 1;
10879 Roo.EventManager.on(window, 'unload', function(){
10881 delete El._flyweights;
10889 Roo.Element.selectorFunction = Roo.DomQuery.select;
10892 Roo.Element.select = function(selector, unique, root){
10894 if(typeof selector == "string"){
10895 els = Roo.Element.selectorFunction(selector, root);
10896 }else if(selector.length !== undefined){
10899 throw "Invalid selector";
10901 if(unique === true){
10902 return new Roo.CompositeElement(els);
10904 return new Roo.CompositeElementLite(els);
10908 * Selects elements based on the passed CSS selector to enable working on them as 1.
10909 * @param {String/Array} selector The CSS selector or an array of elements
10910 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
10911 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
10912 * @return {CompositeElementLite/CompositeElement}
10916 Roo.select = Roo.Element.select;
10933 * Ext JS Library 1.1.1
10934 * Copyright(c) 2006-2007, Ext JS, LLC.
10936 * Originally Released Under LGPL - original licence link has changed is not relivant.
10939 * <script type="text/javascript">
10944 //Notifies Element that fx methods are available
10945 Roo.enableFx = true;
10949 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
10950 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
10951 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
10952 * Element effects to work.</p><br/>
10954 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
10955 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
10956 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
10957 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
10958 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
10959 * expected results and should be done with care.</p><br/>
10961 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
10962 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
10965 ----- -----------------------------
10966 tl The top left corner
10967 t The center of the top edge
10968 tr The top right corner
10969 l The center of the left edge
10970 r The center of the right edge
10971 bl The bottom left corner
10972 b The center of the bottom edge
10973 br The bottom right corner
10975 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
10976 * below are common options that can be passed to any Fx method.</b>
10977 * @cfg {Function} callback A function called when the effect is finished
10978 * @cfg {Object} scope The scope of the effect function
10979 * @cfg {String} easing A valid Easing value for the effect
10980 * @cfg {String} afterCls A css class to apply after the effect
10981 * @cfg {Number} duration The length of time (in seconds) that the effect should last
10982 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
10983 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
10984 * effects that end with the element being visually hidden, ignored otherwise)
10985 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
10986 * a function which returns such a specification that will be applied to the Element after the effect finishes
10987 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
10988 * @cfg {Boolean} concurrent Whether to allow subsequently-queued effects to run at the same time as the current effect, or to ensure that they run in sequence
10989 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
10993 * Slides the element into view. An anchor point can be optionally passed to set the point of
10994 * origin for the slide effect. This function automatically handles wrapping the element with
10995 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
10998 // default: slide the element in from the top
11001 // custom: slide the element in from the right with a 2-second duration
11002 el.slideIn('r', { duration: 2 });
11004 // common config options shown with default values
11010 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11011 * @param {Object} options (optional) Object literal with any of the Fx config options
11012 * @return {Roo.Element} The Element
11014 slideIn : function(anchor, o){
11015 var el = this.getFxEl();
11018 el.queueFx(o, function(){
11020 anchor = anchor || "t";
11022 // fix display to visibility
11025 // restore values after effect
11026 var r = this.getFxRestore();
11027 var b = this.getBox();
11028 // fixed size for slide
11032 var wrap = this.fxWrap(r.pos, o, "hidden");
11034 var st = this.dom.style;
11035 st.visibility = "visible";
11036 st.position = "absolute";
11038 // clear out temp styles after slide and unwrap
11039 var after = function(){
11040 el.fxUnwrap(wrap, r.pos, o);
11041 st.width = r.width;
11042 st.height = r.height;
11045 // time to calc the positions
11046 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
11048 switch(anchor.toLowerCase()){
11050 wrap.setSize(b.width, 0);
11051 st.left = st.bottom = "0";
11055 wrap.setSize(0, b.height);
11056 st.right = st.top = "0";
11060 wrap.setSize(0, b.height);
11061 wrap.setX(b.right);
11062 st.left = st.top = "0";
11063 a = {width: bw, points: pt};
11066 wrap.setSize(b.width, 0);
11067 wrap.setY(b.bottom);
11068 st.left = st.top = "0";
11069 a = {height: bh, points: pt};
11072 wrap.setSize(0, 0);
11073 st.right = st.bottom = "0";
11074 a = {width: bw, height: bh};
11077 wrap.setSize(0, 0);
11078 wrap.setY(b.y+b.height);
11079 st.right = st.top = "0";
11080 a = {width: bw, height: bh, points: pt};
11083 wrap.setSize(0, 0);
11084 wrap.setXY([b.right, b.bottom]);
11085 st.left = st.top = "0";
11086 a = {width: bw, height: bh, points: pt};
11089 wrap.setSize(0, 0);
11090 wrap.setX(b.x+b.width);
11091 st.left = st.bottom = "0";
11092 a = {width: bw, height: bh, points: pt};
11095 this.dom.style.visibility = "visible";
11098 arguments.callee.anim = wrap.fxanim(a,
11108 * Slides the element out of view. An anchor point can be optionally passed to set the end point
11109 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
11110 * 'hidden') but block elements will still take up space in the document. The element must be removed
11111 * from the DOM using the 'remove' config option if desired. This function automatically handles
11112 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11115 // default: slide the element out to the top
11118 // custom: slide the element out to the right with a 2-second duration
11119 el.slideOut('r', { duration: 2 });
11121 // common config options shown with default values
11129 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11130 * @param {Object} options (optional) Object literal with any of the Fx config options
11131 * @return {Roo.Element} The Element
11133 slideOut : function(anchor, o){
11134 var el = this.getFxEl();
11137 el.queueFx(o, function(){
11139 anchor = anchor || "t";
11141 // restore values after effect
11142 var r = this.getFxRestore();
11144 var b = this.getBox();
11145 // fixed size for slide
11149 var wrap = this.fxWrap(r.pos, o, "visible");
11151 var st = this.dom.style;
11152 st.visibility = "visible";
11153 st.position = "absolute";
11157 var after = function(){
11159 el.setDisplayed(false);
11164 el.fxUnwrap(wrap, r.pos, o);
11166 st.width = r.width;
11167 st.height = r.height;
11172 var a, zero = {to: 0};
11173 switch(anchor.toLowerCase()){
11175 st.left = st.bottom = "0";
11176 a = {height: zero};
11179 st.right = st.top = "0";
11183 st.left = st.top = "0";
11184 a = {width: zero, points: {to:[b.right, b.y]}};
11187 st.left = st.top = "0";
11188 a = {height: zero, points: {to:[b.x, b.bottom]}};
11191 st.right = st.bottom = "0";
11192 a = {width: zero, height: zero};
11195 st.right = st.top = "0";
11196 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
11199 st.left = st.top = "0";
11200 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
11203 st.left = st.bottom = "0";
11204 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
11208 arguments.callee.anim = wrap.fxanim(a,
11218 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
11219 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
11220 * The element must be removed from the DOM using the 'remove' config option if desired.
11226 // common config options shown with default values
11234 * @param {Object} options (optional) Object literal with any of the Fx config options
11235 * @return {Roo.Element} The Element
11237 puff : function(o){
11238 var el = this.getFxEl();
11241 el.queueFx(o, function(){
11242 this.clearOpacity();
11245 // restore values after effect
11246 var r = this.getFxRestore();
11247 var st = this.dom.style;
11249 var after = function(){
11251 el.setDisplayed(false);
11258 el.setPositioning(r.pos);
11259 st.width = r.width;
11260 st.height = r.height;
11265 var width = this.getWidth();
11266 var height = this.getHeight();
11268 arguments.callee.anim = this.fxanim({
11269 width : {to: this.adjustWidth(width * 2)},
11270 height : {to: this.adjustHeight(height * 2)},
11271 points : {by: [-(width * .5), -(height * .5)]},
11273 fontSize: {to:200, unit: "%"}
11284 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
11285 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
11286 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
11292 // all config options shown with default values
11300 * @param {Object} options (optional) Object literal with any of the Fx config options
11301 * @return {Roo.Element} The Element
11303 switchOff : function(o){
11304 var el = this.getFxEl();
11307 el.queueFx(o, function(){
11308 this.clearOpacity();
11311 // restore values after effect
11312 var r = this.getFxRestore();
11313 var st = this.dom.style;
11315 var after = function(){
11317 el.setDisplayed(false);
11323 el.setPositioning(r.pos);
11324 st.width = r.width;
11325 st.height = r.height;
11330 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
11331 this.clearOpacity();
11335 points:{by:[0, this.getHeight() * .5]}
11336 }, o, 'motion', 0.3, 'easeIn', after);
11337 }).defer(100, this);
11344 * Highlights the Element by setting a color (applies to the background-color by default, but can be
11345 * changed using the "attr" config option) and then fading back to the original color. If no original
11346 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
11349 // default: highlight background to yellow
11352 // custom: highlight foreground text to blue for 2 seconds
11353 el.highlight("0000ff", { attr: 'color', duration: 2 });
11355 // common config options shown with default values
11356 el.highlight("ffff9c", {
11357 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
11358 endColor: (current color) or "ffffff",
11363 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
11364 * @param {Object} options (optional) Object literal with any of the Fx config options
11365 * @return {Roo.Element} The Element
11367 highlight : function(color, o){
11368 var el = this.getFxEl();
11371 el.queueFx(o, function(){
11372 color = color || "ffff9c";
11373 attr = o.attr || "backgroundColor";
11375 this.clearOpacity();
11378 var origColor = this.getColor(attr);
11379 var restoreColor = this.dom.style[attr];
11380 endColor = (o.endColor || origColor) || "ffffff";
11382 var after = function(){
11383 el.dom.style[attr] = restoreColor;
11388 a[attr] = {from: color, to: endColor};
11389 arguments.callee.anim = this.fxanim(a,
11399 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
11402 // default: a single light blue ripple
11405 // custom: 3 red ripples lasting 3 seconds total
11406 el.frame("ff0000", 3, { duration: 3 });
11408 // common config options shown with default values
11409 el.frame("C3DAF9", 1, {
11410 duration: 1 //duration of entire animation (not each individual ripple)
11411 // Note: Easing is not configurable and will be ignored if included
11414 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
11415 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
11416 * @param {Object} options (optional) Object literal with any of the Fx config options
11417 * @return {Roo.Element} The Element
11419 frame : function(color, count, o){
11420 var el = this.getFxEl();
11423 el.queueFx(o, function(){
11424 color = color || "#C3DAF9";
11425 if(color.length == 6){
11426 color = "#" + color;
11428 count = count || 1;
11429 duration = o.duration || 1;
11432 var b = this.getBox();
11433 var animFn = function(){
11434 var proxy = this.createProxy({
11437 visbility:"hidden",
11438 position:"absolute",
11439 "z-index":"35000", // yee haw
11440 border:"0px solid " + color
11443 var scale = Roo.isBorderBox ? 2 : 1;
11445 top:{from:b.y, to:b.y - 20},
11446 left:{from:b.x, to:b.x - 20},
11447 borderWidth:{from:0, to:10},
11448 opacity:{from:1, to:0},
11449 height:{from:b.height, to:(b.height + (20*scale))},
11450 width:{from:b.width, to:(b.width + (20*scale))}
11451 }, duration, function(){
11455 animFn.defer((duration/2)*1000, this);
11466 * Creates a pause before any subsequent queued effects begin. If there are
11467 * no effects queued after the pause it will have no effect.
11472 * @param {Number} seconds The length of time to pause (in seconds)
11473 * @return {Roo.Element} The Element
11475 pause : function(seconds){
11476 var el = this.getFxEl();
11479 el.queueFx(o, function(){
11480 setTimeout(function(){
11482 }, seconds * 1000);
11488 * Fade an element in (from transparent to opaque). The ending opacity can be specified
11489 * using the "endOpacity" config option.
11492 // default: fade in from opacity 0 to 100%
11495 // custom: fade in from opacity 0 to 75% over 2 seconds
11496 el.fadeIn({ endOpacity: .75, duration: 2});
11498 // common config options shown with default values
11500 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
11505 * @param {Object} options (optional) Object literal with any of the Fx config options
11506 * @return {Roo.Element} The Element
11508 fadeIn : function(o){
11509 var el = this.getFxEl();
11511 el.queueFx(o, function(){
11512 this.setOpacity(0);
11514 this.dom.style.visibility = 'visible';
11515 var to = o.endOpacity || 1;
11516 arguments.callee.anim = this.fxanim({opacity:{to:to}},
11517 o, null, .5, "easeOut", function(){
11519 this.clearOpacity();
11528 * Fade an element out (from opaque to transparent). The ending opacity can be specified
11529 * using the "endOpacity" config option.
11532 // default: fade out from the element's current opacity to 0
11535 // custom: fade out from the element's current opacity to 25% over 2 seconds
11536 el.fadeOut({ endOpacity: .25, duration: 2});
11538 // common config options shown with default values
11540 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
11547 * @param {Object} options (optional) Object literal with any of the Fx config options
11548 * @return {Roo.Element} The Element
11550 fadeOut : function(o){
11551 var el = this.getFxEl();
11553 el.queueFx(o, function(){
11554 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
11555 o, null, .5, "easeOut", function(){
11556 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
11557 this.dom.style.display = "none";
11559 this.dom.style.visibility = "hidden";
11561 this.clearOpacity();
11569 * Animates the transition of an element's dimensions from a starting height/width
11570 * to an ending height/width.
11573 // change height and width to 100x100 pixels
11574 el.scale(100, 100);
11576 // common config options shown with default values. The height and width will default to
11577 // the element's existing values if passed as null.
11580 [element's height], {
11585 * @param {Number} width The new width (pass undefined to keep the original width)
11586 * @param {Number} height The new height (pass undefined to keep the original height)
11587 * @param {Object} options (optional) Object literal with any of the Fx config options
11588 * @return {Roo.Element} The Element
11590 scale : function(w, h, o){
11591 this.shift(Roo.apply({}, o, {
11599 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
11600 * Any of these properties not specified in the config object will not be changed. This effect
11601 * requires that at least one new dimension, position or opacity setting must be passed in on
11602 * the config object in order for the function to have any effect.
11605 // slide the element horizontally to x position 200 while changing the height and opacity
11606 el.shift({ x: 200, height: 50, opacity: .8 });
11608 // common config options shown with default values.
11610 width: [element's width],
11611 height: [element's height],
11612 x: [element's x position],
11613 y: [element's y position],
11614 opacity: [element's opacity],
11619 * @param {Object} options Object literal with any of the Fx config options
11620 * @return {Roo.Element} The Element
11622 shift : function(o){
11623 var el = this.getFxEl();
11625 el.queueFx(o, function(){
11626 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
11627 if(w !== undefined){
11628 a.width = {to: this.adjustWidth(w)};
11630 if(h !== undefined){
11631 a.height = {to: this.adjustHeight(h)};
11633 if(x !== undefined || y !== undefined){
11635 x !== undefined ? x : this.getX(),
11636 y !== undefined ? y : this.getY()
11639 if(op !== undefined){
11640 a.opacity = {to: op};
11642 if(o.xy !== undefined){
11643 a.points = {to: o.xy};
11645 arguments.callee.anim = this.fxanim(a,
11646 o, 'motion', .35, "easeOut", function(){
11654 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
11655 * ending point of the effect.
11658 // default: slide the element downward while fading out
11661 // custom: slide the element out to the right with a 2-second duration
11662 el.ghost('r', { duration: 2 });
11664 // common config options shown with default values
11672 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
11673 * @param {Object} options (optional) Object literal with any of the Fx config options
11674 * @return {Roo.Element} The Element
11676 ghost : function(anchor, o){
11677 var el = this.getFxEl();
11680 el.queueFx(o, function(){
11681 anchor = anchor || "b";
11683 // restore values after effect
11684 var r = this.getFxRestore();
11685 var w = this.getWidth(),
11686 h = this.getHeight();
11688 var st = this.dom.style;
11690 var after = function(){
11692 el.setDisplayed(false);
11698 el.setPositioning(r.pos);
11699 st.width = r.width;
11700 st.height = r.height;
11705 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
11706 switch(anchor.toLowerCase()){
11733 arguments.callee.anim = this.fxanim(a,
11743 * Ensures that all effects queued after syncFx is called on the element are
11744 * run concurrently. This is the opposite of {@link #sequenceFx}.
11745 * @return {Roo.Element} The Element
11747 syncFx : function(){
11748 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11757 * Ensures that all effects queued after sequenceFx is called on the element are
11758 * run in sequence. This is the opposite of {@link #syncFx}.
11759 * @return {Roo.Element} The Element
11761 sequenceFx : function(){
11762 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11764 concurrent : false,
11771 nextFx : function(){
11772 var ef = this.fxQueue[0];
11779 * Returns true if the element has any effects actively running or queued, else returns false.
11780 * @return {Boolean} True if element has active effects, else false
11782 hasActiveFx : function(){
11783 return this.fxQueue && this.fxQueue[0];
11787 * Stops any running effects and clears the element's internal effects queue if it contains
11788 * any additional effects that haven't started yet.
11789 * @return {Roo.Element} The Element
11791 stopFx : function(){
11792 if(this.hasActiveFx()){
11793 var cur = this.fxQueue[0];
11794 if(cur && cur.anim && cur.anim.isAnimated()){
11795 this.fxQueue = [cur]; // clear out others
11796 cur.anim.stop(true);
11803 beforeFx : function(o){
11804 if(this.hasActiveFx() && !o.concurrent){
11815 * Returns true if the element is currently blocking so that no other effect can be queued
11816 * until this effect is finished, else returns false if blocking is not set. This is commonly
11817 * used to ensure that an effect initiated by a user action runs to completion prior to the
11818 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
11819 * @return {Boolean} True if blocking, else false
11821 hasFxBlock : function(){
11822 var q = this.fxQueue;
11823 return q && q[0] && q[0].block;
11827 queueFx : function(o, fn){
11831 if(!this.hasFxBlock()){
11832 Roo.applyIf(o, this.fxDefaults);
11834 var run = this.beforeFx(o);
11835 fn.block = o.block;
11836 this.fxQueue.push(fn);
11848 fxWrap : function(pos, o, vis){
11850 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
11853 wrapXY = this.getXY();
11855 var div = document.createElement("div");
11856 div.style.visibility = vis;
11857 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
11858 wrap.setPositioning(pos);
11859 if(wrap.getStyle("position") == "static"){
11860 wrap.position("relative");
11862 this.clearPositioning('auto');
11864 wrap.dom.appendChild(this.dom);
11866 wrap.setXY(wrapXY);
11873 fxUnwrap : function(wrap, pos, o){
11874 this.clearPositioning();
11875 this.setPositioning(pos);
11877 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
11883 getFxRestore : function(){
11884 var st = this.dom.style;
11885 return {pos: this.getPositioning(), width: st.width, height : st.height};
11889 afterFx : function(o){
11891 this.applyStyles(o.afterStyle);
11894 this.addClass(o.afterCls);
11896 if(o.remove === true){
11899 Roo.callback(o.callback, o.scope, [this]);
11901 this.fxQueue.shift();
11907 getFxEl : function(){ // support for composite element fx
11908 return Roo.get(this.dom);
11912 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
11913 animType = animType || 'run';
11915 var anim = Roo.lib.Anim[animType](
11917 (opt.duration || defaultDur) || .35,
11918 (opt.easing || defaultEase) || 'easeOut',
11920 Roo.callback(cb, this);
11929 // backwords compat
11930 Roo.Fx.resize = Roo.Fx.scale;
11932 //When included, Roo.Fx is automatically applied to Element so that all basic
11933 //effects are available directly via the Element API
11934 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
11936 * Ext JS Library 1.1.1
11937 * Copyright(c) 2006-2007, Ext JS, LLC.
11939 * Originally Released Under LGPL - original licence link has changed is not relivant.
11942 * <script type="text/javascript">
11947 * @class Roo.CompositeElement
11948 * Standard composite class. Creates a Roo.Element for every element in the collection.
11950 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
11951 * actions will be performed on all the elements in this collection.</b>
11953 * All methods return <i>this</i> and can be chained.
11955 var els = Roo.select("#some-el div.some-class", true);
11956 // or select directly from an existing element
11957 var el = Roo.get('some-el');
11958 el.select('div.some-class', true);
11960 els.setWidth(100); // all elements become 100 width
11961 els.hide(true); // all elements fade out and hide
11963 els.setWidth(100).hide(true);
11966 Roo.CompositeElement = function(els){
11967 this.elements = [];
11968 this.addElements(els);
11970 Roo.CompositeElement.prototype = {
11972 addElements : function(els){
11976 if(typeof els == "string"){
11977 els = Roo.Element.selectorFunction(els);
11979 var yels = this.elements;
11980 var index = yels.length-1;
11981 for(var i = 0, len = els.length; i < len; i++) {
11982 yels[++index] = Roo.get(els[i]);
11988 * Clears this composite and adds the elements returned by the passed selector.
11989 * @param {String/Array} els A string CSS selector, an array of elements or an element
11990 * @return {CompositeElement} this
11992 fill : function(els){
11993 this.elements = [];
11999 * Filters this composite to only elements that match the passed selector.
12000 * @param {String} selector A string CSS selector
12001 * @param {Boolean} inverse return inverse filter (not matches)
12002 * @return {CompositeElement} this
12004 filter : function(selector, inverse){
12006 inverse = inverse || false;
12007 this.each(function(el){
12008 var match = inverse ? !el.is(selector) : el.is(selector);
12010 els[els.length] = el.dom;
12017 invoke : function(fn, args){
12018 var els = this.elements;
12019 for(var i = 0, len = els.length; i < len; i++) {
12020 Roo.Element.prototype[fn].apply(els[i], args);
12025 * Adds elements to this composite.
12026 * @param {String/Array} els A string CSS selector, an array of elements or an element
12027 * @return {CompositeElement} this
12029 add : function(els){
12030 if(typeof els == "string"){
12031 this.addElements(Roo.Element.selectorFunction(els));
12032 }else if(els.length !== undefined){
12033 this.addElements(els);
12035 this.addElements([els]);
12040 * Calls the passed function passing (el, this, index) for each element in this composite.
12041 * @param {Function} fn The function to call
12042 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12043 * @return {CompositeElement} this
12045 each : function(fn, scope){
12046 var els = this.elements;
12047 for(var i = 0, len = els.length; i < len; i++){
12048 if(fn.call(scope || els[i], els[i], this, i) === false) {
12056 * Returns the Element object at the specified index
12057 * @param {Number} index
12058 * @return {Roo.Element}
12060 item : function(index){
12061 return this.elements[index] || null;
12065 * Returns the first Element
12066 * @return {Roo.Element}
12068 first : function(){
12069 return this.item(0);
12073 * Returns the last Element
12074 * @return {Roo.Element}
12077 return this.item(this.elements.length-1);
12081 * Returns the number of elements in this composite
12084 getCount : function(){
12085 return this.elements.length;
12089 * Returns true if this composite contains the passed element
12092 contains : function(el){
12093 return this.indexOf(el) !== -1;
12097 * Returns true if this composite contains the passed element
12100 indexOf : function(el){
12101 return this.elements.indexOf(Roo.get(el));
12106 * Removes the specified element(s).
12107 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
12108 * or an array of any of those.
12109 * @param {Boolean} removeDom (optional) True to also remove the element from the document
12110 * @return {CompositeElement} this
12112 removeElement : function(el, removeDom){
12113 if(el instanceof Array){
12114 for(var i = 0, len = el.length; i < len; i++){
12115 this.removeElement(el[i]);
12119 var index = typeof el == 'number' ? el : this.indexOf(el);
12122 var d = this.elements[index];
12126 d.parentNode.removeChild(d);
12129 this.elements.splice(index, 1);
12135 * Replaces the specified element with the passed element.
12136 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
12138 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
12139 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
12140 * @return {CompositeElement} this
12142 replaceElement : function(el, replacement, domReplace){
12143 var index = typeof el == 'number' ? el : this.indexOf(el);
12146 this.elements[index].replaceWith(replacement);
12148 this.elements.splice(index, 1, Roo.get(replacement))
12155 * Removes all elements.
12157 clear : function(){
12158 this.elements = [];
12162 Roo.CompositeElement.createCall = function(proto, fnName){
12163 if(!proto[fnName]){
12164 proto[fnName] = function(){
12165 return this.invoke(fnName, arguments);
12169 for(var fnName in Roo.Element.prototype){
12170 if(typeof Roo.Element.prototype[fnName] == "function"){
12171 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
12177 * Ext JS Library 1.1.1
12178 * Copyright(c) 2006-2007, Ext JS, LLC.
12180 * Originally Released Under LGPL - original licence link has changed is not relivant.
12183 * <script type="text/javascript">
12187 * @class Roo.CompositeElementLite
12188 * @extends Roo.CompositeElement
12189 * Flyweight composite class. Reuses the same Roo.Element for element operations.
12191 var els = Roo.select("#some-el div.some-class");
12192 // or select directly from an existing element
12193 var el = Roo.get('some-el');
12194 el.select('div.some-class');
12196 els.setWidth(100); // all elements become 100 width
12197 els.hide(true); // all elements fade out and hide
12199 els.setWidth(100).hide(true);
12200 </code></pre><br><br>
12201 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12202 * actions will be performed on all the elements in this collection.</b>
12204 Roo.CompositeElementLite = function(els){
12205 Roo.CompositeElementLite.superclass.constructor.call(this, els);
12206 this.el = new Roo.Element.Flyweight();
12208 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
12209 addElements : function(els){
12211 if(els instanceof Array){
12212 this.elements = this.elements.concat(els);
12214 var yels = this.elements;
12215 var index = yels.length-1;
12216 for(var i = 0, len = els.length; i < len; i++) {
12217 yels[++index] = els[i];
12223 invoke : function(fn, args){
12224 var els = this.elements;
12226 for(var i = 0, len = els.length; i < len; i++) {
12228 Roo.Element.prototype[fn].apply(el, args);
12233 * Returns a flyweight Element of the dom element object at the specified index
12234 * @param {Number} index
12235 * @return {Roo.Element}
12237 item : function(index){
12238 if(!this.elements[index]){
12241 this.el.dom = this.elements[index];
12245 // fixes scope with flyweight
12246 addListener : function(eventName, handler, scope, opt){
12247 var els = this.elements;
12248 for(var i = 0, len = els.length; i < len; i++) {
12249 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
12255 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
12256 * passed is the flyweight (shared) Roo.Element instance, so if you require a
12257 * a reference to the dom node, use el.dom.</b>
12258 * @param {Function} fn The function to call
12259 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12260 * @return {CompositeElement} this
12262 each : function(fn, scope){
12263 var els = this.elements;
12265 for(var i = 0, len = els.length; i < len; i++){
12267 if(fn.call(scope || el, el, this, i) === false){
12274 indexOf : function(el){
12275 return this.elements.indexOf(Roo.getDom(el));
12278 replaceElement : function(el, replacement, domReplace){
12279 var index = typeof el == 'number' ? el : this.indexOf(el);
12281 replacement = Roo.getDom(replacement);
12283 var d = this.elements[index];
12284 d.parentNode.insertBefore(replacement, d);
12285 d.parentNode.removeChild(d);
12287 this.elements.splice(index, 1, replacement);
12292 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
12296 * Ext JS Library 1.1.1
12297 * Copyright(c) 2006-2007, Ext JS, LLC.
12299 * Originally Released Under LGPL - original licence link has changed is not relivant.
12302 * <script type="text/javascript">
12308 * @class Roo.data.Connection
12309 * @extends Roo.util.Observable
12310 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
12311 * either to a configured URL, or to a URL specified at request time.
12313 * Requests made by this class are asynchronous, and will return immediately. No data from
12314 * the server will be available to the statement immediately following the {@link #request} call.
12315 * To process returned data, use a callback in the request options object, or an event listener.
12317 * Note: If you are doing a file upload, you will not get a normal response object sent back to
12318 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
12319 * The response object is created using the innerHTML of the IFRAME's document as the responseText
12320 * property and, if present, the IFRAME's XML document as the responseXML property.
12322 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
12323 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
12324 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
12325 * standard DOM methods.
12327 * @param {Object} config a configuration object.
12329 Roo.data.Connection = function(config){
12330 Roo.apply(this, config);
12333 * @event beforerequest
12334 * Fires before a network request is made to retrieve a data object.
12335 * @param {Connection} conn This Connection object.
12336 * @param {Object} options The options config object passed to the {@link #request} method.
12338 "beforerequest" : true,
12340 * @event requestcomplete
12341 * Fires if the request was successfully completed.
12342 * @param {Connection} conn This Connection object.
12343 * @param {Object} response The XHR object containing the response data.
12344 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12345 * @param {Object} options The options config object passed to the {@link #request} method.
12347 "requestcomplete" : true,
12349 * @event requestexception
12350 * Fires if an error HTTP status was returned from the server.
12351 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
12352 * @param {Connection} conn This Connection object.
12353 * @param {Object} response The XHR object containing the response data.
12354 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12355 * @param {Object} options The options config object passed to the {@link #request} method.
12357 "requestexception" : true
12359 Roo.data.Connection.superclass.constructor.call(this);
12362 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
12364 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12367 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12368 * extra parameters to each request made by this object. (defaults to undefined)
12371 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12372 * to each request made by this object. (defaults to undefined)
12375 * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
12378 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12382 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12388 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12391 disableCaching: true,
12394 * Sends an HTTP request to a remote server.
12395 * @param {Object} options An object which may contain the following properties:<ul>
12396 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
12397 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
12398 * request, a url encoded string or a function to call to get either.</li>
12399 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
12400 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
12401 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
12402 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
12403 * <li>options {Object} The parameter to the request call.</li>
12404 * <li>success {Boolean} True if the request succeeded.</li>
12405 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12407 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
12408 * The callback is passed the following parameters:<ul>
12409 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12410 * <li>options {Object} The parameter to the request call.</li>
12412 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
12413 * The callback is passed the following parameters:<ul>
12414 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12415 * <li>options {Object} The parameter to the request call.</li>
12417 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
12418 * for the callback function. Defaults to the browser window.</li>
12419 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
12420 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
12421 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
12422 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
12423 * params for the post data. Any params will be appended to the URL.</li>
12424 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
12426 * @return {Number} transactionId
12428 request : function(o){
12429 if(this.fireEvent("beforerequest", this, o) !== false){
12432 if(typeof p == "function"){
12433 p = p.call(o.scope||window, o);
12435 if(typeof p == "object"){
12436 p = Roo.urlEncode(o.params);
12438 if(this.extraParams){
12439 var extras = Roo.urlEncode(this.extraParams);
12440 p = p ? (p + '&' + extras) : extras;
12443 var url = o.url || this.url;
12444 if(typeof url == 'function'){
12445 url = url.call(o.scope||window, o);
12449 var form = Roo.getDom(o.form);
12450 url = url || form.action;
12452 var enctype = form.getAttribute("enctype");
12455 return this.doFormDataUpload(o, url);
12458 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
12459 return this.doFormUpload(o, p, url);
12461 var f = Roo.lib.Ajax.serializeForm(form);
12462 p = p ? (p + '&' + f) : f;
12465 if (!o.form && o.formData) {
12466 o.formData = o.formData === true ? new FormData() : o.formData;
12467 for (var k in o.params) {
12468 o.formData.append(k,o.params[k]);
12471 return this.doFormDataUpload(o, url);
12475 var hs = o.headers;
12476 if(this.defaultHeaders){
12477 hs = Roo.apply(hs || {}, this.defaultHeaders);
12484 success: this.handleResponse,
12485 failure: this.handleFailure,
12487 argument: {options: o},
12488 timeout : o.timeout || this.timeout
12491 var method = o.method||this.method||(p ? "POST" : "GET");
12493 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
12494 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
12497 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12501 }else if(this.autoAbort !== false){
12505 if((method == 'GET' && p) || o.xmlData){
12506 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
12509 Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
12510 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
12511 Roo.lib.Ajax.useDefaultHeader == true;
12512 return this.transId;
12514 Roo.callback(o.callback, o.scope, [o, null, null]);
12520 * Determine whether this object has a request outstanding.
12521 * @param {Number} transactionId (Optional) defaults to the last transaction
12522 * @return {Boolean} True if there is an outstanding request.
12524 isLoading : function(transId){
12526 return Roo.lib.Ajax.isCallInProgress(transId);
12528 return this.transId ? true : false;
12533 * Aborts any outstanding request.
12534 * @param {Number} transactionId (Optional) defaults to the last transaction
12536 abort : function(transId){
12537 if(transId || this.isLoading()){
12538 Roo.lib.Ajax.abort(transId || this.transId);
12543 handleResponse : function(response){
12544 this.transId = false;
12545 var options = response.argument.options;
12546 response.argument = options ? options.argument : null;
12547 this.fireEvent("requestcomplete", this, response, options);
12548 Roo.callback(options.success, options.scope, [response, options]);
12549 Roo.callback(options.callback, options.scope, [options, true, response]);
12553 handleFailure : function(response, e){
12554 this.transId = false;
12555 var options = response.argument.options;
12556 response.argument = options ? options.argument : null;
12557 this.fireEvent("requestexception", this, response, options, e);
12558 Roo.callback(options.failure, options.scope, [response, options]);
12559 Roo.callback(options.callback, options.scope, [options, false, response]);
12563 doFormUpload : function(o, ps, url){
12565 var frame = document.createElement('iframe');
12568 frame.className = 'x-hidden';
12570 frame.src = Roo.SSL_SECURE_URL;
12572 document.body.appendChild(frame);
12575 document.frames[id].name = id;
12578 var form = Roo.getDom(o.form);
12580 form.method = 'POST';
12581 form.enctype = form.encoding = 'multipart/form-data';
12587 if(ps){ // add dynamic params
12589 ps = Roo.urlDecode(ps, false);
12591 if(ps.hasOwnProperty(k)){
12592 hd = document.createElement('input');
12593 hd.type = 'hidden';
12596 form.appendChild(hd);
12603 var r = { // bogus response object
12608 r.argument = o ? o.argument : null;
12613 doc = frame.contentWindow.document;
12615 doc = (frame.contentDocument || window.frames[id].document);
12617 if(doc && doc.body){
12618 r.responseText = doc.body.innerHTML;
12620 if(doc && doc.XMLDocument){
12621 r.responseXML = doc.XMLDocument;
12623 r.responseXML = doc;
12630 Roo.EventManager.removeListener(frame, 'load', cb, this);
12632 this.fireEvent("requestcomplete", this, r, o);
12633 Roo.callback(o.success, o.scope, [r, o]);
12634 Roo.callback(o.callback, o.scope, [o, true, r]);
12636 setTimeout(function(){document.body.removeChild(frame);}, 100);
12639 Roo.EventManager.on(frame, 'load', cb, this);
12642 if(hiddens){ // remove dynamic params
12643 for(var i = 0, len = hiddens.length; i < len; i++){
12644 form.removeChild(hiddens[i]);
12648 // this is a 'formdata version???'
12651 doFormDataUpload : function(o, url)
12655 var form = Roo.getDom(o.form);
12656 form.enctype = form.encoding = 'multipart/form-data';
12657 formData = o.formData === true ? new FormData(form) : o.formData;
12659 formData = o.formData === true ? new FormData() : o.formData;
12664 success: this.handleResponse,
12665 failure: this.handleFailure,
12667 argument: {options: o},
12668 timeout : o.timeout || this.timeout
12671 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12675 }else if(this.autoAbort !== false){
12679 //Roo.lib.Ajax.defaultPostHeader = null;
12680 Roo.lib.Ajax.useDefaultHeader = false;
12681 this.transId = Roo.lib.Ajax.request( "POST", url, cb, formData, o);
12682 Roo.lib.Ajax.useDefaultHeader = true;
12690 * Ext JS Library 1.1.1
12691 * Copyright(c) 2006-2007, Ext JS, LLC.
12693 * Originally Released Under LGPL - original licence link has changed is not relivant.
12696 * <script type="text/javascript">
12700 * Global Ajax request class.
12703 * @extends Roo.data.Connection
12706 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
12707 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
12708 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
12709 * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
12710 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12711 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
12712 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12714 Roo.Ajax = new Roo.data.Connection({
12723 * Serialize the passed form into a url encoded string
12725 * @param {String/HTMLElement} form
12728 serializeForm : function(form){
12729 return Roo.lib.Ajax.serializeForm(form);
12733 * Ext JS Library 1.1.1
12734 * Copyright(c) 2006-2007, Ext JS, LLC.
12736 * Originally Released Under LGPL - original licence link has changed is not relivant.
12739 * <script type="text/javascript">
12744 * @class Roo.UpdateManager
12745 * @extends Roo.util.Observable
12746 * Provides AJAX-style update for Element object.<br><br>
12749 * // Get it from a Roo.Element object
12750 * var el = Roo.get("foo");
12751 * var mgr = el.getUpdateManager();
12752 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
12754 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
12756 * // or directly (returns the same UpdateManager instance)
12757 * var mgr = new Roo.UpdateManager("myElementId");
12758 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
12759 * mgr.on("update", myFcnNeedsToKnow);
12761 // short handed call directly from the element object
12762 Roo.get("foo").load({
12766 text: "Loading Foo..."
12770 * Create new UpdateManager directly.
12771 * @param {String/HTMLElement/Roo.Element} el The element to update
12772 * @param {Boolean} forceNew (optional) By default the constructor checks to see if the passed element already has an UpdateManager and if it does it returns the same instance. This will skip that check (useful for extending this class).
12774 Roo.UpdateManager = function(el, forceNew){
12776 if(!forceNew && el.updateManager){
12777 return el.updateManager;
12780 * The Element object
12781 * @type Roo.Element
12785 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
12788 this.defaultUrl = null;
12792 * @event beforeupdate
12793 * Fired before an update is made, return false from your handler and the update is cancelled.
12794 * @param {Roo.Element} el
12795 * @param {String/Object/Function} url
12796 * @param {String/Object} params
12798 "beforeupdate": true,
12801 * Fired after successful update is made.
12802 * @param {Roo.Element} el
12803 * @param {Object} oResponseObject The response Object
12808 * Fired on update failure.
12809 * @param {Roo.Element} el
12810 * @param {Object} oResponseObject The response Object
12814 var d = Roo.UpdateManager.defaults;
12816 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
12819 this.sslBlankUrl = d.sslBlankUrl;
12821 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
12824 this.disableCaching = d.disableCaching;
12826 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
12829 this.indicatorText = d.indicatorText;
12831 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
12834 this.showLoadIndicator = d.showLoadIndicator;
12836 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
12839 this.timeout = d.timeout;
12842 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
12845 this.loadScripts = d.loadScripts;
12848 * Transaction object of current executing transaction
12850 this.transaction = null;
12855 this.autoRefreshProcId = null;
12857 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
12860 this.refreshDelegate = this.refresh.createDelegate(this);
12862 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
12865 this.updateDelegate = this.update.createDelegate(this);
12867 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
12870 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
12874 this.successDelegate = this.processSuccess.createDelegate(this);
12878 this.failureDelegate = this.processFailure.createDelegate(this);
12880 if(!this.renderer){
12882 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
12884 this.renderer = new Roo.UpdateManager.BasicRenderer();
12887 Roo.UpdateManager.superclass.constructor.call(this);
12890 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
12892 * Get the Element this UpdateManager is bound to
12893 * @return {Roo.Element} The element
12895 getEl : function(){
12899 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
12900 * @param {Object/String/Function} url The url for this request or a function to call to get the url or a config object containing any of the following options:
12903 url: "your-url.php",<br/>
12904 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
12905 callback: yourFunction,<br/>
12906 scope: yourObject, //(optional scope) <br/>
12907 discardUrl: false, <br/>
12908 nocache: false,<br/>
12909 text: "Loading...",<br/>
12911 scripts: false<br/>
12914 * The only required property is url. The optional properties nocache, text and scripts
12915 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
12916 * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
12917 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
12918 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used url. If true, it will not store the url.
12920 update : function(url, params, callback, discardUrl){
12921 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
12922 var method = this.method,
12924 if(typeof url == "object"){ // must be config object
12927 params = params || cfg.params;
12928 callback = callback || cfg.callback;
12929 discardUrl = discardUrl || cfg.discardUrl;
12930 if(callback && cfg.scope){
12931 callback = callback.createDelegate(cfg.scope);
12933 if(typeof cfg.method != "undefined"){method = cfg.method;};
12934 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
12935 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
12936 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
12937 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
12939 this.showLoading();
12941 this.defaultUrl = url;
12943 if(typeof url == "function"){
12944 url = url.call(this);
12947 method = method || (params ? "POST" : "GET");
12948 if(method == "GET"){
12949 url = this.prepareUrl(url);
12952 var o = Roo.apply(cfg ||{}, {
12955 success: this.successDelegate,
12956 failure: this.failureDelegate,
12957 callback: undefined,
12958 timeout: (this.timeout*1000),
12959 argument: {"url": url, "form": null, "callback": callback, "params": params}
12961 Roo.log("updated manager called with timeout of " + o.timeout);
12962 this.transaction = Roo.Ajax.request(o);
12967 * Performs an async form post, updating this element with the response. If the form has the attribute enctype="multipart/form-data", it assumes it's a file upload.
12968 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
12969 * @param {String/HTMLElement} form The form Id or form element
12970 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
12971 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
12972 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
12974 formUpdate : function(form, url, reset, callback){
12975 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
12976 if(typeof url == "function"){
12977 url = url.call(this);
12979 form = Roo.getDom(form);
12980 this.transaction = Roo.Ajax.request({
12983 success: this.successDelegate,
12984 failure: this.failureDelegate,
12985 timeout: (this.timeout*1000),
12986 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
12988 this.showLoading.defer(1, this);
12993 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
12994 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
12996 refresh : function(callback){
12997 if(this.defaultUrl == null){
13000 this.update(this.defaultUrl, null, callback, true);
13004 * Set this element to auto refresh.
13005 * @param {Number} interval How often to update (in seconds).
13006 * @param {String/Function} url (optional) The url for this request or a function to call to get the url (Defaults to the last used url)
13007 * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "¶m1=1¶m2=2" or as an object {param1: 1, param2: 2}
13008 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13009 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
13011 startAutoRefresh : function(interval, url, params, callback, refreshNow){
13013 this.update(url || this.defaultUrl, params, callback, true);
13015 if(this.autoRefreshProcId){
13016 clearInterval(this.autoRefreshProcId);
13018 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
13022 * Stop auto refresh on this element.
13024 stopAutoRefresh : function(){
13025 if(this.autoRefreshProcId){
13026 clearInterval(this.autoRefreshProcId);
13027 delete this.autoRefreshProcId;
13031 isAutoRefreshing : function(){
13032 return this.autoRefreshProcId ? true : false;
13035 * Called to update the element to "Loading" state. Override to perform custom action.
13037 showLoading : function(){
13038 if(this.showLoadIndicator){
13039 this.el.update(this.indicatorText);
13044 * Adds unique parameter to query string if disableCaching = true
13047 prepareUrl : function(url){
13048 if(this.disableCaching){
13049 var append = "_dc=" + (new Date().getTime());
13050 if(url.indexOf("?") !== -1){
13051 url += "&" + append;
13053 url += "?" + append;
13062 processSuccess : function(response){
13063 this.transaction = null;
13064 if(response.argument.form && response.argument.reset){
13065 try{ // put in try/catch since some older FF releases had problems with this
13066 response.argument.form.reset();
13069 if(this.loadScripts){
13070 this.renderer.render(this.el, response, this,
13071 this.updateComplete.createDelegate(this, [response]));
13073 this.renderer.render(this.el, response, this);
13074 this.updateComplete(response);
13078 updateComplete : function(response){
13079 this.fireEvent("update", this.el, response);
13080 if(typeof response.argument.callback == "function"){
13081 response.argument.callback(this.el, true, response);
13088 processFailure : function(response){
13089 this.transaction = null;
13090 this.fireEvent("failure", this.el, response);
13091 if(typeof response.argument.callback == "function"){
13092 response.argument.callback(this.el, false, response);
13097 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
13098 * @param {Object} renderer The object implementing the render() method
13100 setRenderer : function(renderer){
13101 this.renderer = renderer;
13104 getRenderer : function(){
13105 return this.renderer;
13109 * Set the defaultUrl used for updates
13110 * @param {String/Function} defaultUrl The url or a function to call to get the url
13112 setDefaultUrl : function(defaultUrl){
13113 this.defaultUrl = defaultUrl;
13117 * Aborts the executing transaction
13119 abort : function(){
13120 if(this.transaction){
13121 Roo.Ajax.abort(this.transaction);
13126 * Returns true if an update is in progress
13127 * @return {Boolean}
13129 isUpdating : function(){
13130 if(this.transaction){
13131 return Roo.Ajax.isLoading(this.transaction);
13138 * @class Roo.UpdateManager.defaults
13139 * @static (not really - but it helps the doc tool)
13140 * The defaults collection enables customizing the default properties of UpdateManager
13142 Roo.UpdateManager.defaults = {
13144 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
13150 * True to process scripts by default (Defaults to false).
13153 loadScripts : false,
13156 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
13159 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
13161 * Whether to append unique parameter on get request to disable caching (Defaults to false).
13164 disableCaching : false,
13166 * Whether to show indicatorText when loading (Defaults to true).
13169 showLoadIndicator : true,
13171 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
13174 indicatorText : '<div class="loading-indicator">Loading...</div>'
13178 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
13180 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
13181 * @param {String/HTMLElement/Roo.Element} el The element to update
13182 * @param {String} url The url
13183 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
13184 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
13187 * @member Roo.UpdateManager
13189 Roo.UpdateManager.updateElement = function(el, url, params, options){
13190 var um = Roo.get(el, true).getUpdateManager();
13191 Roo.apply(um, options);
13192 um.update(url, params, options ? options.callback : null);
13194 // alias for backwards compat
13195 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
13197 * @class Roo.UpdateManager.BasicRenderer
13198 * Default Content renderer. Updates the elements innerHTML with the responseText.
13200 Roo.UpdateManager.BasicRenderer = function(){};
13202 Roo.UpdateManager.BasicRenderer.prototype = {
13204 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
13205 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
13206 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
13207 * @param {Roo.Element} el The element being rendered
13208 * @param {Object} response The YUI Connect response object
13209 * @param {UpdateManager} updateManager The calling update manager
13210 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
13212 render : function(el, response, updateManager, callback){
13213 el.update(response.responseText, updateManager.loadScripts, callback);
13219 * (c)) Alan Knowles
13225 * @class Roo.DomTemplate
13226 * @extends Roo.Template
13227 * An effort at a dom based template engine..
13229 * Similar to XTemplate, except it uses dom parsing to create the template..
13231 * Supported features:
13236 {a_variable} - output encoded.
13237 {a_variable.format:("Y-m-d")} - call a method on the variable
13238 {a_variable:raw} - unencoded output
13239 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
13240 {a_variable:this.method_on_template(...)} - call a method on the template object.
13245 <div roo-for="a_variable or condition.."></div>
13246 <div roo-if="a_variable or condition"></div>
13247 <div roo-exec="some javascript"></div>
13248 <div roo-name="named_template"></div>
13253 Roo.DomTemplate = function()
13255 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
13262 Roo.extend(Roo.DomTemplate, Roo.Template, {
13264 * id counter for sub templates.
13268 * flag to indicate if dom parser is inside a pre,
13269 * it will strip whitespace if not.
13274 * The various sub templates
13282 * basic tag replacing syntax
13285 * // you can fake an object call by doing this
13289 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
13290 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
13292 iterChild : function (node, method) {
13294 var oldPre = this.inPre;
13295 if (node.tagName == 'PRE') {
13298 for( var i = 0; i < node.childNodes.length; i++) {
13299 method.call(this, node.childNodes[i]);
13301 this.inPre = oldPre;
13307 * compile the template
13309 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
13312 compile: function()
13316 // covert the html into DOM...
13320 doc = document.implementation.createHTMLDocument("");
13321 doc.documentElement.innerHTML = this.html ;
13322 div = doc.documentElement;
13324 // old IE... - nasty -- it causes all sorts of issues.. with
13325 // images getting pulled from server..
13326 div = document.createElement('div');
13327 div.innerHTML = this.html;
13329 //doc.documentElement.innerHTML = htmlBody
13335 this.iterChild(div, function(n) {_t.compileNode(n, true); });
13337 var tpls = this.tpls;
13339 // create a top level template from the snippet..
13341 //Roo.log(div.innerHTML);
13348 body : div.innerHTML,
13361 Roo.each(tpls, function(tp){
13362 this.compileTpl(tp);
13363 this.tpls[tp.id] = tp;
13366 this.master = tpls[0];
13372 compileNode : function(node, istop) {
13377 // skip anything not a tag..
13378 if (node.nodeType != 1) {
13379 if (node.nodeType == 3 && !this.inPre) {
13380 // reduce white space..
13381 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
13404 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
13405 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
13406 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
13407 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
13413 // just itterate children..
13414 this.iterChild(node,this.compileNode);
13417 tpl.uid = this.id++;
13418 tpl.value = node.getAttribute('roo-' + tpl.attr);
13419 node.removeAttribute('roo-'+ tpl.attr);
13420 if (tpl.attr != 'name') {
13421 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
13422 node.parentNode.replaceChild(placeholder, node);
13425 var placeholder = document.createElement('span');
13426 placeholder.className = 'roo-tpl-' + tpl.value;
13427 node.parentNode.replaceChild(placeholder, node);
13430 // parent now sees '{domtplXXXX}
13431 this.iterChild(node,this.compileNode);
13433 // we should now have node body...
13434 var div = document.createElement('div');
13435 div.appendChild(node);
13437 // this has the unfortunate side effect of converting tagged attributes
13438 // eg. href="{...}" into %7C...%7D
13439 // this has been fixed by searching for those combo's although it's a bit hacky..
13442 tpl.body = div.innerHTML;
13449 switch (tpl.value) {
13450 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
13451 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
13452 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
13457 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13461 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13465 tpl.id = tpl.value; // replace non characters???
13471 this.tpls.push(tpl);
13481 * Compile a segment of the template into a 'sub-template'
13487 compileTpl : function(tpl)
13489 var fm = Roo.util.Format;
13490 var useF = this.disableFormats !== true;
13492 var sep = Roo.isGecko ? "+\n" : ",\n";
13494 var undef = function(str) {
13495 Roo.debug && Roo.log("Property not found :" + str);
13499 //Roo.log(tpl.body);
13503 var fn = function(m, lbrace, name, format, args)
13506 //Roo.log(arguments);
13507 args = args ? args.replace(/\\'/g,"'") : args;
13508 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
13509 if (typeof(format) == 'undefined') {
13510 format = 'htmlEncode';
13512 if (format == 'raw' ) {
13516 if(name.substr(0, 6) == 'domtpl'){
13517 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
13520 // build an array of options to determine if value is undefined..
13522 // basically get 'xxxx.yyyy' then do
13523 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
13524 // (function () { Roo.log("Property not found"); return ''; })() :
13529 Roo.each(name.split('.'), function(st) {
13530 lookfor += (lookfor.length ? '.': '') + st;
13531 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
13534 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
13537 if(format && useF){
13539 args = args ? ',' + args : "";
13541 if(format.substr(0, 5) != "this."){
13542 format = "fm." + format + '(';
13544 format = 'this.call("'+ format.substr(5) + '", ';
13548 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
13551 if (args && args.length) {
13552 // called with xxyx.yuu:(test,test)
13554 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
13556 // raw.. - :raw modifier..
13557 return "'"+ sep + udef_st + name + ")"+sep+"'";
13561 // branched to use + in gecko and [].join() in others
13563 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
13564 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
13567 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
13568 body.push(tpl.body.replace(/(\r\n|\n)/g,
13569 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
13570 body.push("'].join('');};};");
13571 body = body.join('');
13574 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
13576 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
13583 * same as applyTemplate, except it's done to one of the subTemplates
13584 * when using named templates, you can do:
13586 * var str = pl.applySubTemplate('your-name', values);
13589 * @param {Number} id of the template
13590 * @param {Object} values to apply to template
13591 * @param {Object} parent (normaly the instance of this object)
13593 applySubTemplate : function(id, values, parent)
13597 var t = this.tpls[id];
13601 if(t.ifCall && !t.ifCall.call(this, values, parent)){
13602 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
13606 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
13613 if(t.execCall && t.execCall.call(this, values, parent)){
13617 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13623 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
13624 parent = t.target ? values : parent;
13625 if(t.forCall && vs instanceof Array){
13627 for(var i = 0, len = vs.length; i < len; i++){
13629 buf[buf.length] = t.compiled.call(this, vs[i], parent);
13631 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13633 //Roo.log(t.compiled);
13637 return buf.join('');
13640 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13645 return t.compiled.call(this, vs, parent);
13647 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13649 //Roo.log(t.compiled);
13657 applyTemplate : function(values){
13658 return this.master.compiled.call(this, values, {});
13659 //var s = this.subs;
13662 apply : function(){
13663 return this.applyTemplate.apply(this, arguments);
13668 Roo.DomTemplate.from = function(el){
13669 el = Roo.getDom(el);
13670 return new Roo.Domtemplate(el.value || el.innerHTML);
13673 * Ext JS Library 1.1.1
13674 * Copyright(c) 2006-2007, Ext JS, LLC.
13676 * Originally Released Under LGPL - original licence link has changed is not relivant.
13679 * <script type="text/javascript">
13683 * @class Roo.util.DelayedTask
13684 * Provides a convenient method of performing setTimeout where a new
13685 * timeout cancels the old timeout. An example would be performing validation on a keypress.
13686 * You can use this class to buffer
13687 * the keypress events for a certain number of milliseconds, and perform only if they stop
13688 * for that amount of time.
13689 * @constructor The parameters to this constructor serve as defaults and are not required.
13690 * @param {Function} fn (optional) The default function to timeout
13691 * @param {Object} scope (optional) The default scope of that timeout
13692 * @param {Array} args (optional) The default Array of arguments
13694 Roo.util.DelayedTask = function(fn, scope, args){
13695 var id = null, d, t;
13697 var call = function(){
13698 var now = new Date().getTime();
13702 fn.apply(scope, args || []);
13706 * Cancels any pending timeout and queues a new one
13707 * @param {Number} delay The milliseconds to delay
13708 * @param {Function} newFn (optional) Overrides function passed to constructor
13709 * @param {Object} newScope (optional) Overrides scope passed to constructor
13710 * @param {Array} newArgs (optional) Overrides args passed to constructor
13712 this.delay = function(delay, newFn, newScope, newArgs){
13713 if(id && delay != d){
13717 t = new Date().getTime();
13719 scope = newScope || scope;
13720 args = newArgs || args;
13722 id = setInterval(call, d);
13727 * Cancel the last queued timeout
13729 this.cancel = function(){
13737 * Ext JS Library 1.1.1
13738 * Copyright(c) 2006-2007, Ext JS, LLC.
13740 * Originally Released Under LGPL - original licence link has changed is not relivant.
13743 * <script type="text/javascript">
13746 * @class Roo.util.TaskRunner
13747 * Manage background tasks - not sure why this is better that setInterval?
13752 Roo.util.TaskRunner = function(interval){
13753 interval = interval || 10;
13754 var tasks = [], removeQueue = [];
13756 var running = false;
13758 var stopThread = function(){
13764 var startThread = function(){
13767 id = setInterval(runTasks, interval);
13771 var removeTask = function(task){
13772 removeQueue.push(task);
13778 var runTasks = function(){
13779 if(removeQueue.length > 0){
13780 for(var i = 0, len = removeQueue.length; i < len; i++){
13781 tasks.remove(removeQueue[i]);
13784 if(tasks.length < 1){
13789 var now = new Date().getTime();
13790 for(var i = 0, len = tasks.length; i < len; ++i){
13792 var itime = now - t.taskRunTime;
13793 if(t.interval <= itime){
13794 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
13795 t.taskRunTime = now;
13796 if(rt === false || t.taskRunCount === t.repeat){
13801 if(t.duration && t.duration <= (now - t.taskStartTime)){
13808 * Queues a new task.
13809 * @param {Object} task
13811 * Task property : interval = how frequent to run.
13812 * Task object should implement
13814 * Task object may implement
13815 * function onStop()
13817 this.start = function(task){
13819 task.taskStartTime = new Date().getTime();
13820 task.taskRunTime = 0;
13821 task.taskRunCount = 0;
13827 * @param {Object} task
13829 this.stop = function(task){
13836 this.stopAll = function(){
13838 for(var i = 0, len = tasks.length; i < len; i++){
13839 if(tasks[i].onStop){
13848 Roo.TaskMgr = new Roo.util.TaskRunner();/*
13850 * Ext JS Library 1.1.1
13851 * Copyright(c) 2006-2007, Ext JS, LLC.
13853 * Originally Released Under LGPL - original licence link has changed is not relivant.
13856 * <script type="text/javascript">
13861 * @class Roo.util.MixedCollection
13862 * @extends Roo.util.Observable
13863 * A Collection class that maintains both numeric indexes and keys and exposes events.
13865 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
13866 * collection (defaults to false)
13867 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
13868 * and return the key value for that item. This is used when available to look up the key on items that
13869 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
13870 * equivalent to providing an implementation for the {@link #getKey} method.
13872 Roo.util.MixedCollection = function(allowFunctions, keyFn){
13880 * Fires when the collection is cleared.
13885 * Fires when an item is added to the collection.
13886 * @param {Number} index The index at which the item was added.
13887 * @param {Object} o The item added.
13888 * @param {String} key The key associated with the added item.
13893 * Fires when an item is replaced in the collection.
13894 * @param {String} key he key associated with the new added.
13895 * @param {Object} old The item being replaced.
13896 * @param {Object} new The new item.
13901 * Fires when an item is removed from the collection.
13902 * @param {Object} o The item being removed.
13903 * @param {String} key (optional) The key associated with the removed item.
13908 this.allowFunctions = allowFunctions === true;
13910 this.getKey = keyFn;
13912 Roo.util.MixedCollection.superclass.constructor.call(this);
13915 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
13916 allowFunctions : false,
13919 * Adds an item to the collection.
13920 * @param {String} key The key to associate with the item
13921 * @param {Object} o The item to add.
13922 * @return {Object} The item added.
13924 add : function(key, o){
13925 if(arguments.length == 1){
13927 key = this.getKey(o);
13929 if(typeof key == "undefined" || key === null){
13931 this.items.push(o);
13932 this.keys.push(null);
13934 var old = this.map[key];
13936 return this.replace(key, o);
13939 this.items.push(o);
13941 this.keys.push(key);
13943 this.fireEvent("add", this.length-1, o, key);
13948 * MixedCollection has a generic way to fetch keys if you implement getKey.
13951 var mc = new Roo.util.MixedCollection();
13952 mc.add(someEl.dom.id, someEl);
13953 mc.add(otherEl.dom.id, otherEl);
13957 var mc = new Roo.util.MixedCollection();
13958 mc.getKey = function(el){
13964 // or via the constructor
13965 var mc = new Roo.util.MixedCollection(false, function(el){
13971 * @param o {Object} The item for which to find the key.
13972 * @return {Object} The key for the passed item.
13974 getKey : function(o){
13979 * Replaces an item in the collection.
13980 * @param {String} key The key associated with the item to replace, or the item to replace.
13981 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
13982 * @return {Object} The new item.
13984 replace : function(key, o){
13985 if(arguments.length == 1){
13987 key = this.getKey(o);
13989 var old = this.item(key);
13990 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
13991 return this.add(key, o);
13993 var index = this.indexOfKey(key);
13994 this.items[index] = o;
13996 this.fireEvent("replace", key, old, o);
14001 * Adds all elements of an Array or an Object to the collection.
14002 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
14003 * an Array of values, each of which are added to the collection.
14005 addAll : function(objs){
14006 if(arguments.length > 1 || objs instanceof Array){
14007 var args = arguments.length > 1 ? arguments : objs;
14008 for(var i = 0, len = args.length; i < len; i++){
14012 for(var key in objs){
14013 if(this.allowFunctions || typeof objs[key] != "function"){
14014 this.add(key, objs[key]);
14021 * Executes the specified function once for every item in the collection, passing each
14022 * item as the first and only parameter. returning false from the function will stop the iteration.
14023 * @param {Function} fn The function to execute for each item.
14024 * @param {Object} scope (optional) The scope in which to execute the function.
14026 each : function(fn, scope){
14027 var items = [].concat(this.items); // each safe for removal
14028 for(var i = 0, len = items.length; i < len; i++){
14029 if(fn.call(scope || items[i], items[i], i, len) === false){
14036 * Executes the specified function once for every key in the collection, passing each
14037 * key, and its associated item as the first two parameters.
14038 * @param {Function} fn The function to execute for each item.
14039 * @param {Object} scope (optional) The scope in which to execute the function.
14041 eachKey : function(fn, scope){
14042 for(var i = 0, len = this.keys.length; i < len; i++){
14043 fn.call(scope || window, this.keys[i], this.items[i], i, len);
14048 * Returns the first item in the collection which elicits a true return value from the
14049 * passed selection function.
14050 * @param {Function} fn The selection function to execute for each item.
14051 * @param {Object} scope (optional) The scope in which to execute the function.
14052 * @return {Object} The first item in the collection which returned true from the selection function.
14054 find : function(fn, scope){
14055 for(var i = 0, len = this.items.length; i < len; i++){
14056 if(fn.call(scope || window, this.items[i], this.keys[i])){
14057 return this.items[i];
14064 * Inserts an item at the specified index in the collection.
14065 * @param {Number} index The index to insert the item at.
14066 * @param {String} key The key to associate with the new item, or the item itself.
14067 * @param {Object} o (optional) If the second parameter was a key, the new item.
14068 * @return {Object} The item inserted.
14070 insert : function(index, key, o){
14071 if(arguments.length == 2){
14073 key = this.getKey(o);
14075 if(index >= this.length){
14076 return this.add(key, o);
14079 this.items.splice(index, 0, o);
14080 if(typeof key != "undefined" && key != null){
14083 this.keys.splice(index, 0, key);
14084 this.fireEvent("add", index, o, key);
14089 * Removed an item from the collection.
14090 * @param {Object} o The item to remove.
14091 * @return {Object} The item removed.
14093 remove : function(o){
14094 return this.removeAt(this.indexOf(o));
14098 * Remove an item from a specified index in the collection.
14099 * @param {Number} index The index within the collection of the item to remove.
14101 removeAt : function(index){
14102 if(index < this.length && index >= 0){
14104 var o = this.items[index];
14105 this.items.splice(index, 1);
14106 var key = this.keys[index];
14107 if(typeof key != "undefined"){
14108 delete this.map[key];
14110 this.keys.splice(index, 1);
14111 this.fireEvent("remove", o, key);
14116 * Removed an item associated with the passed key fom the collection.
14117 * @param {String} key The key of the item to remove.
14119 removeKey : function(key){
14120 return this.removeAt(this.indexOfKey(key));
14124 * Returns the number of items in the collection.
14125 * @return {Number} the number of items in the collection.
14127 getCount : function(){
14128 return this.length;
14132 * Returns index within the collection of the passed Object.
14133 * @param {Object} o The item to find the index of.
14134 * @return {Number} index of the item.
14136 indexOf : function(o){
14137 if(!this.items.indexOf){
14138 for(var i = 0, len = this.items.length; i < len; i++){
14139 if(this.items[i] == o) {
14145 return this.items.indexOf(o);
14150 * Returns index within the collection of the passed key.
14151 * @param {String} key The key to find the index of.
14152 * @return {Number} index of the key.
14154 indexOfKey : function(key){
14155 if(!this.keys.indexOf){
14156 for(var i = 0, len = this.keys.length; i < len; i++){
14157 if(this.keys[i] == key) {
14163 return this.keys.indexOf(key);
14168 * Returns the item associated with the passed key OR index. Key has priority over index.
14169 * @param {String/Number} key The key or index of the item.
14170 * @return {Object} The item associated with the passed key.
14172 item : function(key){
14173 if (key === 'length') {
14176 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
14177 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
14181 * Returns the item at the specified index.
14182 * @param {Number} index The index of the item.
14185 itemAt : function(index){
14186 return this.items[index];
14190 * Returns the item associated with the passed key.
14191 * @param {String/Number} key The key of the item.
14192 * @return {Object} The item associated with the passed key.
14194 key : function(key){
14195 return this.map[key];
14199 * Returns true if the collection contains the passed Object as an item.
14200 * @param {Object} o The Object to look for in the collection.
14201 * @return {Boolean} True if the collection contains the Object as an item.
14203 contains : function(o){
14204 return this.indexOf(o) != -1;
14208 * Returns true if the collection contains the passed Object as a key.
14209 * @param {String} key The key to look for in the collection.
14210 * @return {Boolean} True if the collection contains the Object as a key.
14212 containsKey : function(key){
14213 return typeof this.map[key] != "undefined";
14217 * Removes all items from the collection.
14219 clear : function(){
14224 this.fireEvent("clear");
14228 * Returns the first item in the collection.
14229 * @return {Object} the first item in the collection..
14231 first : function(){
14232 return this.items[0];
14236 * Returns the last item in the collection.
14237 * @return {Object} the last item in the collection..
14240 return this.items[this.length-1];
14243 _sort : function(property, dir, fn){
14244 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
14245 fn = fn || function(a, b){
14248 var c = [], k = this.keys, items = this.items;
14249 for(var i = 0, len = items.length; i < len; i++){
14250 c[c.length] = {key: k[i], value: items[i], index: i};
14252 c.sort(function(a, b){
14253 var v = fn(a[property], b[property]) * dsc;
14255 v = (a.index < b.index ? -1 : 1);
14259 for(var i = 0, len = c.length; i < len; i++){
14260 items[i] = c[i].value;
14263 this.fireEvent("sort", this);
14267 * Sorts this collection with the passed comparison function
14268 * @param {String} direction (optional) "ASC" or "DESC"
14269 * @param {Function} fn (optional) comparison function
14271 sort : function(dir, fn){
14272 this._sort("value", dir, fn);
14276 * Sorts this collection by keys
14277 * @param {String} direction (optional) "ASC" or "DESC"
14278 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
14280 keySort : function(dir, fn){
14281 this._sort("key", dir, fn || function(a, b){
14282 return String(a).toUpperCase()-String(b).toUpperCase();
14287 * Returns a range of items in this collection
14288 * @param {Number} startIndex (optional) defaults to 0
14289 * @param {Number} endIndex (optional) default to the last item
14290 * @return {Array} An array of items
14292 getRange : function(start, end){
14293 var items = this.items;
14294 if(items.length < 1){
14297 start = start || 0;
14298 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
14301 for(var i = start; i <= end; i++) {
14302 r[r.length] = items[i];
14305 for(var i = start; i >= end; i--) {
14306 r[r.length] = items[i];
14313 * Filter the <i>objects</i> in this collection by a specific property.
14314 * Returns a new collection that has been filtered.
14315 * @param {String} property A property on your objects
14316 * @param {String/RegExp} value Either string that the property values
14317 * should start with or a RegExp to test against the property
14318 * @return {MixedCollection} The new filtered collection
14320 filter : function(property, value){
14321 if(!value.exec){ // not a regex
14322 value = String(value);
14323 if(value.length == 0){
14324 return this.clone();
14326 value = new RegExp("^" + Roo.escapeRe(value), "i");
14328 return this.filterBy(function(o){
14329 return o && value.test(o[property]);
14334 * Filter by a function. * Returns a new collection that has been filtered.
14335 * The passed function will be called with each
14336 * object in the collection. If the function returns true, the value is included
14337 * otherwise it is filtered.
14338 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
14339 * @param {Object} scope (optional) The scope of the function (defaults to this)
14340 * @return {MixedCollection} The new filtered collection
14342 filterBy : function(fn, scope){
14343 var r = new Roo.util.MixedCollection();
14344 r.getKey = this.getKey;
14345 var k = this.keys, it = this.items;
14346 for(var i = 0, len = it.length; i < len; i++){
14347 if(fn.call(scope||this, it[i], k[i])){
14348 r.add(k[i], it[i]);
14355 * Creates a duplicate of this collection
14356 * @return {MixedCollection}
14358 clone : function(){
14359 var r = new Roo.util.MixedCollection();
14360 var k = this.keys, it = this.items;
14361 for(var i = 0, len = it.length; i < len; i++){
14362 r.add(k[i], it[i]);
14364 r.getKey = this.getKey;
14369 * Returns the item associated with the passed key or index.
14371 * @param {String/Number} key The key or index of the item.
14372 * @return {Object} The item associated with the passed key.
14374 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
14376 * Ext JS Library 1.1.1
14377 * Copyright(c) 2006-2007, Ext JS, LLC.
14379 * Originally Released Under LGPL - original licence link has changed is not relivant.
14382 * <script type="text/javascript">
14385 * @class Roo.util.JSON
14386 * Modified version of Douglas Crockford"s json.js that doesn"t
14387 * mess with the Object prototype
14388 * http://www.json.org/js.html
14391 Roo.util.JSON = new (function(){
14392 var useHasOwn = {}.hasOwnProperty ? true : false;
14394 // crashes Safari in some instances
14395 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
14397 var pad = function(n) {
14398 return n < 10 ? "0" + n : n;
14411 var encodeString = function(s){
14412 if (/["\\\x00-\x1f]/.test(s)) {
14413 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
14418 c = b.charCodeAt();
14420 Math.floor(c / 16).toString(16) +
14421 (c % 16).toString(16);
14424 return '"' + s + '"';
14427 var encodeArray = function(o){
14428 var a = ["["], b, i, l = o.length, v;
14429 for (i = 0; i < l; i += 1) {
14431 switch (typeof v) {
14440 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
14448 var encodeDate = function(o){
14449 return '"' + o.getFullYear() + "-" +
14450 pad(o.getMonth() + 1) + "-" +
14451 pad(o.getDate()) + "T" +
14452 pad(o.getHours()) + ":" +
14453 pad(o.getMinutes()) + ":" +
14454 pad(o.getSeconds()) + '"';
14458 * Encodes an Object, Array or other value
14459 * @param {Mixed} o The variable to encode
14460 * @return {String} The JSON string
14462 this.encode = function(o)
14464 // should this be extended to fully wrap stringify..
14466 if(typeof o == "undefined" || o === null){
14468 }else if(o instanceof Array){
14469 return encodeArray(o);
14470 }else if(o instanceof Date){
14471 return encodeDate(o);
14472 }else if(typeof o == "string"){
14473 return encodeString(o);
14474 }else if(typeof o == "number"){
14475 return isFinite(o) ? String(o) : "null";
14476 }else if(typeof o == "boolean"){
14479 var a = ["{"], b, i, v;
14481 if(!useHasOwn || o.hasOwnProperty(i)) {
14483 switch (typeof v) {
14492 a.push(this.encode(i), ":",
14493 v === null ? "null" : this.encode(v));
14504 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
14505 * @param {String} json The JSON string
14506 * @return {Object} The resulting object
14508 this.decode = function(json){
14510 return /** eval:var:json */ eval("(" + json + ')');
14514 * Shorthand for {@link Roo.util.JSON#encode}
14515 * @member Roo encode
14517 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
14519 * Shorthand for {@link Roo.util.JSON#decode}
14520 * @member Roo decode
14522 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
14525 * Ext JS Library 1.1.1
14526 * Copyright(c) 2006-2007, Ext JS, LLC.
14528 * Originally Released Under LGPL - original licence link has changed is not relivant.
14531 * <script type="text/javascript">
14535 * @class Roo.util.Format
14536 * Reusable data formatting functions
14539 Roo.util.Format = function(){
14540 var trimRe = /^\s+|\s+$/g;
14543 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
14544 * @param {String} value The string to truncate
14545 * @param {Number} length The maximum length to allow before truncating
14546 * @return {String} The converted text
14548 ellipsis : function(value, len){
14549 if(value && value.length > len){
14550 return value.substr(0, len-3)+"...";
14556 * Checks a reference and converts it to empty string if it is undefined
14557 * @param {Mixed} value Reference to check
14558 * @return {Mixed} Empty string if converted, otherwise the original value
14560 undef : function(value){
14561 return typeof value != "undefined" ? value : "";
14565 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
14566 * @param {String} value The string to encode
14567 * @return {String} The encoded text
14569 htmlEncode : function(value){
14570 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
14574 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
14575 * @param {String} value The string to decode
14576 * @return {String} The decoded text
14578 htmlDecode : function(value){
14579 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
14583 * Trims any whitespace from either side of a string
14584 * @param {String} value The text to trim
14585 * @return {String} The trimmed text
14587 trim : function(value){
14588 return String(value).replace(trimRe, "");
14592 * Returns a substring from within an original string
14593 * @param {String} value The original text
14594 * @param {Number} start The start index of the substring
14595 * @param {Number} length The length of the substring
14596 * @return {String} The substring
14598 substr : function(value, start, length){
14599 return String(value).substr(start, length);
14603 * Converts a string to all lower case letters
14604 * @param {String} value The text to convert
14605 * @return {String} The converted text
14607 lowercase : function(value){
14608 return String(value).toLowerCase();
14612 * Converts a string to all upper case letters
14613 * @param {String} value The text to convert
14614 * @return {String} The converted text
14616 uppercase : function(value){
14617 return String(value).toUpperCase();
14621 * Converts the first character only of a string to upper case
14622 * @param {String} value The text to convert
14623 * @return {String} The converted text
14625 capitalize : function(value){
14626 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
14630 call : function(value, fn){
14631 if(arguments.length > 2){
14632 var args = Array.prototype.slice.call(arguments, 2);
14633 args.unshift(value);
14635 return /** eval:var:value */ eval(fn).apply(window, args);
14637 /** eval:var:value */
14638 return /** eval:var:value */ eval(fn).call(window, value);
14644 * safer version of Math.toFixed..??/
14645 * @param {Number/String} value The numeric value to format
14646 * @param {Number/String} value Decimal places
14647 * @return {String} The formatted currency string
14649 toFixed : function(v, n)
14651 // why not use to fixed - precision is buggered???
14653 return Math.round(v-0);
14655 var fact = Math.pow(10,n+1);
14656 v = (Math.round((v-0)*fact))/fact;
14657 var z = (''+fact).substring(2);
14658 if (v == Math.floor(v)) {
14659 return Math.floor(v) + '.' + z;
14662 // now just padd decimals..
14663 var ps = String(v).split('.');
14664 var fd = (ps[1] + z);
14665 var r = fd.substring(0,n);
14666 var rm = fd.substring(n);
14668 return ps[0] + '.' + r;
14670 r*=1; // turn it into a number;
14672 if (String(r).length != n) {
14675 r = String(r).substring(1); // chop the end off.
14678 return ps[0] + '.' + r;
14683 * Format a number as US currency
14684 * @param {Number/String} value The numeric value to format
14685 * @return {String} The formatted currency string
14687 usMoney : function(v){
14688 return '$' + Roo.util.Format.number(v);
14693 * eventually this should probably emulate php's number_format
14694 * @param {Number/String} value The numeric value to format
14695 * @param {Number} decimals number of decimal places
14696 * @param {String} delimiter for thousands (default comma)
14697 * @return {String} The formatted currency string
14699 number : function(v, decimals, thousandsDelimiter)
14701 // multiply and round.
14702 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
14703 thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
14705 var mul = Math.pow(10, decimals);
14706 var zero = String(mul).substring(1);
14707 v = (Math.round((v-0)*mul))/mul;
14709 // if it's '0' number.. then
14711 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
14713 var ps = v.split('.');
14716 var r = /(\d+)(\d{3})/;
14719 if(thousandsDelimiter.length != 0) {
14720 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
14725 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
14726 // does not have decimals
14727 (decimals ? ('.' + zero) : '');
14730 return whole + sub ;
14734 * Parse a value into a formatted date using the specified format pattern.
14735 * @param {Mixed} value The value to format
14736 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
14737 * @return {String} The formatted date string
14739 date : function(v, format){
14743 if(!(v instanceof Date)){
14744 v = new Date(Date.parse(v));
14746 return v.dateFormat(format || Roo.util.Format.defaults.date);
14750 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
14751 * @param {String} format Any valid date format string
14752 * @return {Function} The date formatting function
14754 dateRenderer : function(format){
14755 return function(v){
14756 return Roo.util.Format.date(v, format);
14761 stripTagsRE : /<\/?[^>]+>/gi,
14764 * Strips all HTML tags
14765 * @param {Mixed} value The text from which to strip tags
14766 * @return {String} The stripped text
14768 stripTags : function(v){
14769 return !v ? v : String(v).replace(this.stripTagsRE, "");
14773 * Size in Mb,Gb etc.
14774 * @param {Number} value The number to be formated
14775 * @param {number} decimals how many decimal places
14776 * @return {String} the formated string
14778 size : function(value, decimals)
14780 var sizes = ['b', 'k', 'M', 'G', 'T'];
14784 var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
14785 return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals) + sizes[i];
14792 Roo.util.Format.defaults = {
14796 * Ext JS Library 1.1.1
14797 * Copyright(c) 2006-2007, Ext JS, LLC.
14799 * Originally Released Under LGPL - original licence link has changed is not relivant.
14802 * <script type="text/javascript">
14809 * @class Roo.MasterTemplate
14810 * @extends Roo.Template
14811 * Provides a template that can have child templates. The syntax is:
14813 var t = new Roo.MasterTemplate(
14814 '<select name="{name}">',
14815 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
14818 t.add('options', {value: 'foo', text: 'bar'});
14819 // or you can add multiple child elements in one shot
14820 t.addAll('options', [
14821 {value: 'foo', text: 'bar'},
14822 {value: 'foo2', text: 'bar2'},
14823 {value: 'foo3', text: 'bar3'}
14825 // then append, applying the master template values
14826 t.append('my-form', {name: 'my-select'});
14828 * A name attribute for the child template is not required if you have only one child
14829 * template or you want to refer to them by index.
14831 Roo.MasterTemplate = function(){
14832 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
14833 this.originalHtml = this.html;
14835 var m, re = this.subTemplateRe;
14838 while(m = re.exec(this.html)){
14839 var name = m[1], content = m[2];
14844 tpl : new Roo.Template(content)
14847 st[name] = st[subIndex];
14849 st[subIndex].tpl.compile();
14850 st[subIndex].tpl.call = this.call.createDelegate(this);
14853 this.subCount = subIndex;
14856 Roo.extend(Roo.MasterTemplate, Roo.Template, {
14858 * The regular expression used to match sub templates
14862 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
14865 * Applies the passed values to a child template.
14866 * @param {String/Number} name (optional) The name or index of the child template
14867 * @param {Array/Object} values The values to be applied to the template
14868 * @return {MasterTemplate} this
14870 add : function(name, values){
14871 if(arguments.length == 1){
14872 values = arguments[0];
14875 var s = this.subs[name];
14876 s.buffer[s.buffer.length] = s.tpl.apply(values);
14881 * Applies all the passed values to a child template.
14882 * @param {String/Number} name (optional) The name or index of the child template
14883 * @param {Array} values The values to be applied to the template, this should be an array of objects.
14884 * @param {Boolean} reset (optional) True to reset the template first
14885 * @return {MasterTemplate} this
14887 fill : function(name, values, reset){
14889 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
14897 for(var i = 0, len = values.length; i < len; i++){
14898 this.add(name, values[i]);
14904 * Resets the template for reuse
14905 * @return {MasterTemplate} this
14907 reset : function(){
14909 for(var i = 0; i < this.subCount; i++){
14915 applyTemplate : function(values){
14917 var replaceIndex = -1;
14918 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
14919 return s[++replaceIndex].buffer.join("");
14921 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
14924 apply : function(){
14925 return this.applyTemplate.apply(this, arguments);
14928 compile : function(){return this;}
14932 * Alias for fill().
14935 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
14937 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
14938 * var tpl = Roo.MasterTemplate.from('element-id');
14939 * @param {String/HTMLElement} el
14940 * @param {Object} config
14943 Roo.MasterTemplate.from = function(el, config){
14944 el = Roo.getDom(el);
14945 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
14948 * Ext JS Library 1.1.1
14949 * Copyright(c) 2006-2007, Ext JS, LLC.
14951 * Originally Released Under LGPL - original licence link has changed is not relivant.
14954 * <script type="text/javascript">
14959 * @class Roo.util.CSS
14960 * Utility class for manipulating CSS rules
14964 Roo.util.CSS = function(){
14966 var doc = document;
14968 var camelRe = /(-[a-z])/gi;
14969 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
14973 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
14974 * tag and appended to the HEAD of the document.
14975 * @param {String|Object} cssText The text containing the css rules
14976 * @param {String} id An id to add to the stylesheet for later removal
14977 * @return {StyleSheet}
14979 createStyleSheet : function(cssText, id){
14981 var head = doc.getElementsByTagName("head")[0];
14982 var nrules = doc.createElement("style");
14983 nrules.setAttribute("type", "text/css");
14985 nrules.setAttribute("id", id);
14987 if (typeof(cssText) != 'string') {
14988 // support object maps..
14989 // not sure if this a good idea..
14990 // perhaps it should be merged with the general css handling
14991 // and handle js style props.
14992 var cssTextNew = [];
14993 for(var n in cssText) {
14995 for(var k in cssText[n]) {
14996 citems.push( k + ' : ' +cssText[n][k] + ';' );
14998 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
15001 cssText = cssTextNew.join("\n");
15007 head.appendChild(nrules);
15008 ss = nrules.styleSheet;
15009 ss.cssText = cssText;
15012 nrules.appendChild(doc.createTextNode(cssText));
15014 nrules.cssText = cssText;
15016 head.appendChild(nrules);
15017 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
15019 this.cacheStyleSheet(ss);
15024 * Removes a style or link tag by id
15025 * @param {String} id The id of the tag
15027 removeStyleSheet : function(id){
15028 var existing = doc.getElementById(id);
15030 existing.parentNode.removeChild(existing);
15035 * Dynamically swaps an existing stylesheet reference for a new one
15036 * @param {String} id The id of an existing link tag to remove
15037 * @param {String} url The href of the new stylesheet to include
15039 swapStyleSheet : function(id, url){
15040 this.removeStyleSheet(id);
15041 var ss = doc.createElement("link");
15042 ss.setAttribute("rel", "stylesheet");
15043 ss.setAttribute("type", "text/css");
15044 ss.setAttribute("id", id);
15045 ss.setAttribute("href", url);
15046 doc.getElementsByTagName("head")[0].appendChild(ss);
15050 * Refresh the rule cache if you have dynamically added stylesheets
15051 * @return {Object} An object (hash) of rules indexed by selector
15053 refreshCache : function(){
15054 return this.getRules(true);
15058 cacheStyleSheet : function(stylesheet){
15062 try{// try catch for cross domain access issue
15063 var ssRules = stylesheet.cssRules || stylesheet.rules;
15064 for(var j = ssRules.length-1; j >= 0; --j){
15065 rules[ssRules[j].selectorText] = ssRules[j];
15071 * Gets all css rules for the document
15072 * @param {Boolean} refreshCache true to refresh the internal cache
15073 * @return {Object} An object (hash) of rules indexed by selector
15075 getRules : function(refreshCache){
15076 if(rules == null || refreshCache){
15078 var ds = doc.styleSheets;
15079 for(var i =0, len = ds.length; i < len; i++){
15081 this.cacheStyleSheet(ds[i]);
15089 * Gets an an individual CSS rule by selector(s)
15090 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
15091 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
15092 * @return {CSSRule} The CSS rule or null if one is not found
15094 getRule : function(selector, refreshCache){
15095 var rs = this.getRules(refreshCache);
15096 if(!(selector instanceof Array)){
15097 return rs[selector];
15099 for(var i = 0; i < selector.length; i++){
15100 if(rs[selector[i]]){
15101 return rs[selector[i]];
15109 * Updates a rule property
15110 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
15111 * @param {String} property The css property
15112 * @param {String} value The new value for the property
15113 * @return {Boolean} true If a rule was found and updated
15115 updateRule : function(selector, property, value){
15116 if(!(selector instanceof Array)){
15117 var rule = this.getRule(selector);
15119 rule.style[property.replace(camelRe, camelFn)] = value;
15123 for(var i = 0; i < selector.length; i++){
15124 if(this.updateRule(selector[i], property, value)){
15134 * Ext JS Library 1.1.1
15135 * Copyright(c) 2006-2007, Ext JS, LLC.
15137 * Originally Released Under LGPL - original licence link has changed is not relivant.
15140 * <script type="text/javascript">
15146 * @class Roo.util.ClickRepeater
15147 * @extends Roo.util.Observable
15149 * A wrapper class which can be applied to any element. Fires a "click" event while the
15150 * mouse is pressed. The interval between firings may be specified in the config but
15151 * defaults to 10 milliseconds.
15153 * Optionally, a CSS class may be applied to the element during the time it is pressed.
15155 * @cfg {String/HTMLElement/Element} el The element to act as a button.
15156 * @cfg {Number} delay The initial delay before the repeating event begins firing.
15157 * Similar to an autorepeat key delay.
15158 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
15159 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
15160 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
15161 * "interval" and "delay" are ignored. "immediate" is honored.
15162 * @cfg {Boolean} preventDefault True to prevent the default click event
15163 * @cfg {Boolean} stopDefault True to stop the default click event
15166 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
15167 * 2007-02-02 jvs Renamed to ClickRepeater
15168 * 2007-02-03 jvs Modifications for FF Mac and Safari
15171 * @param {String/HTMLElement/Element} el The element to listen on
15172 * @param {Object} config
15174 Roo.util.ClickRepeater = function(el, config)
15176 this.el = Roo.get(el);
15177 this.el.unselectable();
15179 Roo.apply(this, config);
15184 * Fires when the mouse button is depressed.
15185 * @param {Roo.util.ClickRepeater} this
15187 "mousedown" : true,
15190 * Fires on a specified interval during the time the element is pressed.
15191 * @param {Roo.util.ClickRepeater} this
15196 * Fires when the mouse key is released.
15197 * @param {Roo.util.ClickRepeater} this
15202 this.el.on("mousedown", this.handleMouseDown, this);
15203 if(this.preventDefault || this.stopDefault){
15204 this.el.on("click", function(e){
15205 if(this.preventDefault){
15206 e.preventDefault();
15208 if(this.stopDefault){
15214 // allow inline handler
15216 this.on("click", this.handler, this.scope || this);
15219 Roo.util.ClickRepeater.superclass.constructor.call(this);
15222 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
15225 preventDefault : true,
15226 stopDefault : false,
15230 handleMouseDown : function(){
15231 clearTimeout(this.timer);
15233 if(this.pressClass){
15234 this.el.addClass(this.pressClass);
15236 this.mousedownTime = new Date();
15238 Roo.get(document).on("mouseup", this.handleMouseUp, this);
15239 this.el.on("mouseout", this.handleMouseOut, this);
15241 this.fireEvent("mousedown", this);
15242 this.fireEvent("click", this);
15244 this.timer = this.click.defer(this.delay || this.interval, this);
15248 click : function(){
15249 this.fireEvent("click", this);
15250 this.timer = this.click.defer(this.getInterval(), this);
15254 getInterval: function(){
15255 if(!this.accelerate){
15256 return this.interval;
15258 var pressTime = this.mousedownTime.getElapsed();
15259 if(pressTime < 500){
15261 }else if(pressTime < 1700){
15263 }else if(pressTime < 2600){
15265 }else if(pressTime < 3500){
15267 }else if(pressTime < 4400){
15269 }else if(pressTime < 5300){
15271 }else if(pressTime < 6200){
15279 handleMouseOut : function(){
15280 clearTimeout(this.timer);
15281 if(this.pressClass){
15282 this.el.removeClass(this.pressClass);
15284 this.el.on("mouseover", this.handleMouseReturn, this);
15288 handleMouseReturn : function(){
15289 this.el.un("mouseover", this.handleMouseReturn);
15290 if(this.pressClass){
15291 this.el.addClass(this.pressClass);
15297 handleMouseUp : function(){
15298 clearTimeout(this.timer);
15299 this.el.un("mouseover", this.handleMouseReturn);
15300 this.el.un("mouseout", this.handleMouseOut);
15301 Roo.get(document).un("mouseup", this.handleMouseUp);
15302 this.el.removeClass(this.pressClass);
15303 this.fireEvent("mouseup", this);
15306 * @class Roo.util.Clipboard
15312 Roo.util.Clipboard = {
15314 * Writes a string to the clipboard - using the Clipboard API if https, otherwise using text area.
15315 * @param {String} text to copy to clipboard
15317 write : function(text) {
15318 // navigator clipboard api needs a secure context (https)
15319 if (navigator.clipboard && window.isSecureContext) {
15320 // navigator clipboard api method'
15321 navigator.clipboard.writeText(text);
15324 // text area method
15325 var ta = document.createElement("textarea");
15327 // make the textarea out of viewport
15328 ta.style.position = "fixed";
15329 ta.style.left = "-999999px";
15330 ta.style.top = "-999999px";
15331 document.body.appendChild(ta);
15334 document.execCommand('copy');
15344 * Ext JS Library 1.1.1
15345 * Copyright(c) 2006-2007, Ext JS, LLC.
15347 * Originally Released Under LGPL - original licence link has changed is not relivant.
15350 * <script type="text/javascript">
15355 * @class Roo.KeyNav
15356 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
15357 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
15358 * way to implement custom navigation schemes for any UI component.</p>
15359 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
15360 * pageUp, pageDown, del, home, end. Usage:</p>
15362 var nav = new Roo.KeyNav("my-element", {
15363 "left" : function(e){
15364 this.moveLeft(e.ctrlKey);
15366 "right" : function(e){
15367 this.moveRight(e.ctrlKey);
15369 "enter" : function(e){
15376 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15377 * @param {Object} config The config
15379 Roo.KeyNav = function(el, config){
15380 this.el = Roo.get(el);
15381 Roo.apply(this, config);
15382 if(!this.disabled){
15383 this.disabled = true;
15388 Roo.KeyNav.prototype = {
15390 * @cfg {Boolean} disabled
15391 * True to disable this KeyNav instance (defaults to false)
15395 * @cfg {String} defaultEventAction
15396 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
15397 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
15398 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
15400 defaultEventAction: "stopEvent",
15402 * @cfg {Boolean} forceKeyDown
15403 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
15404 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
15405 * handle keydown instead of keypress.
15407 forceKeyDown : false,
15410 prepareEvent : function(e){
15411 var k = e.getKey();
15412 var h = this.keyToHandler[k];
15413 //if(h && this[h]){
15414 // e.stopPropagation();
15416 if(Roo.isSafari && h && k >= 37 && k <= 40){
15422 relay : function(e){
15423 var k = e.getKey();
15424 var h = this.keyToHandler[k];
15426 if(this.doRelay(e, this[h], h) !== true){
15427 e[this.defaultEventAction]();
15433 doRelay : function(e, h, hname){
15434 return h.call(this.scope || this, e);
15437 // possible handlers
15451 // quick lookup hash
15468 * Enable this KeyNav
15470 enable: function(){
15472 // ie won't do special keys on keypress, no one else will repeat keys with keydown
15473 // the EventObject will normalize Safari automatically
15474 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15475 this.el.on("keydown", this.relay, this);
15477 this.el.on("keydown", this.prepareEvent, this);
15478 this.el.on("keypress", this.relay, this);
15480 this.disabled = false;
15485 * Disable this KeyNav
15487 disable: function(){
15488 if(!this.disabled){
15489 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15490 this.el.un("keydown", this.relay);
15492 this.el.un("keydown", this.prepareEvent);
15493 this.el.un("keypress", this.relay);
15495 this.disabled = true;
15500 * Ext JS Library 1.1.1
15501 * Copyright(c) 2006-2007, Ext JS, LLC.
15503 * Originally Released Under LGPL - original licence link has changed is not relivant.
15506 * <script type="text/javascript">
15511 * @class Roo.KeyMap
15512 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
15513 * The constructor accepts the same config object as defined by {@link #addBinding}.
15514 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
15515 * combination it will call the function with this signature (if the match is a multi-key
15516 * combination the callback will still be called only once): (String key, Roo.EventObject e)
15517 * A KeyMap can also handle a string representation of keys.<br />
15520 // map one key by key code
15521 var map = new Roo.KeyMap("my-element", {
15522 key: 13, // or Roo.EventObject.ENTER
15527 // map multiple keys to one action by string
15528 var map = new Roo.KeyMap("my-element", {
15534 // map multiple keys to multiple actions by strings and array of codes
15535 var map = new Roo.KeyMap("my-element", [
15538 fn: function(){ alert("Return was pressed"); }
15541 fn: function(){ alert('a, b or c was pressed'); }
15546 fn: function(){ alert('Control + shift + tab was pressed.'); }
15550 * <b>Note: A KeyMap starts enabled</b>
15552 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15553 * @param {Object} config The config (see {@link #addBinding})
15554 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
15556 Roo.KeyMap = function(el, config, eventName){
15557 this.el = Roo.get(el);
15558 this.eventName = eventName || "keydown";
15559 this.bindings = [];
15561 this.addBinding(config);
15566 Roo.KeyMap.prototype = {
15568 * True to stop the event from bubbling and prevent the default browser action if the
15569 * key was handled by the KeyMap (defaults to false)
15575 * Add a new binding to this KeyMap. The following config object properties are supported:
15577 Property Type Description
15578 ---------- --------------- ----------------------------------------------------------------------
15579 key String/Array A single keycode or an array of keycodes to handle
15580 shift Boolean True to handle key only when shift is pressed (defaults to false)
15581 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
15582 alt Boolean True to handle key only when alt is pressed (defaults to false)
15583 fn Function The function to call when KeyMap finds the expected key combination
15584 scope Object The scope of the callback function
15590 var map = new Roo.KeyMap(document, {
15591 key: Roo.EventObject.ENTER,
15596 //Add a new binding to the existing KeyMap later
15604 * @param {Object/Array} config A single KeyMap config or an array of configs
15606 addBinding : function(config){
15607 if(config instanceof Array){
15608 for(var i = 0, len = config.length; i < len; i++){
15609 this.addBinding(config[i]);
15613 var keyCode = config.key,
15614 shift = config.shift,
15615 ctrl = config.ctrl,
15618 scope = config.scope;
15619 if(typeof keyCode == "string"){
15621 var keyString = keyCode.toUpperCase();
15622 for(var j = 0, len = keyString.length; j < len; j++){
15623 ks.push(keyString.charCodeAt(j));
15627 var keyArray = keyCode instanceof Array;
15628 var handler = function(e){
15629 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
15630 var k = e.getKey();
15632 for(var i = 0, len = keyCode.length; i < len; i++){
15633 if(keyCode[i] == k){
15634 if(this.stopEvent){
15637 fn.call(scope || window, k, e);
15643 if(this.stopEvent){
15646 fn.call(scope || window, k, e);
15651 this.bindings.push(handler);
15655 * Shorthand for adding a single key listener
15656 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
15657 * following options:
15658 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
15659 * @param {Function} fn The function to call
15660 * @param {Object} scope (optional) The scope of the function
15662 on : function(key, fn, scope){
15663 var keyCode, shift, ctrl, alt;
15664 if(typeof key == "object" && !(key instanceof Array)){
15683 handleKeyDown : function(e){
15684 if(this.enabled){ //just in case
15685 var b = this.bindings;
15686 for(var i = 0, len = b.length; i < len; i++){
15687 b[i].call(this, e);
15693 * Returns true if this KeyMap is enabled
15694 * @return {Boolean}
15696 isEnabled : function(){
15697 return this.enabled;
15701 * Enables this KeyMap
15703 enable: function(){
15705 this.el.on(this.eventName, this.handleKeyDown, this);
15706 this.enabled = true;
15711 * Disable this KeyMap
15713 disable: function(){
15715 this.el.removeListener(this.eventName, this.handleKeyDown, this);
15716 this.enabled = false;
15721 * Ext JS Library 1.1.1
15722 * Copyright(c) 2006-2007, Ext JS, LLC.
15724 * Originally Released Under LGPL - original licence link has changed is not relivant.
15727 * <script type="text/javascript">
15732 * @class Roo.util.TextMetrics
15733 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
15734 * wide, in pixels, a given block of text will be.
15737 Roo.util.TextMetrics = function(){
15741 * Measures the size of the specified text
15742 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
15743 * that can affect the size of the rendered text
15744 * @param {String} text The text to measure
15745 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15746 * in order to accurately measure the text height
15747 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15749 measure : function(el, text, fixedWidth){
15751 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
15754 shared.setFixedWidth(fixedWidth || 'auto');
15755 return shared.getSize(text);
15759 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
15760 * the overhead of multiple calls to initialize the style properties on each measurement.
15761 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
15762 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15763 * in order to accurately measure the text height
15764 * @return {Roo.util.TextMetrics.Instance} instance The new instance
15766 createInstance : function(el, fixedWidth){
15767 return Roo.util.TextMetrics.Instance(el, fixedWidth);
15773 * @class Roo.util.TextMetrics.Instance
15774 * Instance of TextMetrics Calcuation
15776 * Create a new TextMetrics Instance
15777 * @param {Object} bindto
15778 * @param {Boolean} fixedWidth
15781 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth)
15783 var ml = new Roo.Element(document.createElement('div'));
15784 document.body.appendChild(ml.dom);
15785 ml.position('absolute');
15786 ml.setLeftTop(-1000, -1000);
15790 ml.setWidth(fixedWidth);
15795 * Returns the size of the specified text based on the internal element's style and width properties
15796 * @param {String} text The text to measure
15797 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15799 getSize : function(text){
15801 var s = ml.getSize();
15807 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
15808 * that can affect the size of the rendered text
15809 * @param {String/HTMLElement} el The element, dom node or id
15811 bind : function(el){
15813 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
15818 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
15819 * to set a fixed width in order to accurately measure the text height.
15820 * @param {Number} width The width to set on the element
15822 setFixedWidth : function(width){
15823 ml.setWidth(width);
15827 * Returns the measured width of the specified text
15828 * @param {String} text The text to measure
15829 * @return {Number} width The width in pixels
15831 getWidth : function(text){
15832 ml.dom.style.width = 'auto';
15833 return this.getSize(text).width;
15837 * Returns the measured height of the specified text. For multiline text, be sure to call
15838 * {@link #setFixedWidth} if necessary.
15839 * @param {String} text The text to measure
15840 * @return {Number} height The height in pixels
15842 getHeight : function(text){
15843 return this.getSize(text).height;
15847 instance.bind(bindTo);
15852 // backwards compat
15853 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
15855 * Ext JS Library 1.1.1
15856 * Copyright(c) 2006-2007, Ext JS, LLC.
15858 * Originally Released Under LGPL - original licence link has changed is not relivant.
15861 * <script type="text/javascript">
15865 * @class Roo.state.Provider
15866 * Abstract base class for state provider implementations. This class provides methods
15867 * for encoding and decoding <b>typed</b> variables including dates and defines the
15868 * Provider interface.
15870 Roo.state.Provider = function(){
15872 * @event statechange
15873 * Fires when a state change occurs.
15874 * @param {Provider} this This state provider
15875 * @param {String} key The state key which was changed
15876 * @param {String} value The encoded value for the state
15879 "statechange": true
15882 Roo.state.Provider.superclass.constructor.call(this);
15884 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
15886 * Returns the current value for a key
15887 * @param {String} name The key name
15888 * @param {Mixed} defaultValue A default value to return if the key's value is not found
15889 * @return {Mixed} The state data
15891 get : function(name, defaultValue){
15892 return typeof this.state[name] == "undefined" ?
15893 defaultValue : this.state[name];
15897 * Clears a value from the state
15898 * @param {String} name The key name
15900 clear : function(name){
15901 delete this.state[name];
15902 this.fireEvent("statechange", this, name, null);
15906 * Sets the value for a key
15907 * @param {String} name The key name
15908 * @param {Mixed} value The value to set
15910 set : function(name, value){
15911 this.state[name] = value;
15912 this.fireEvent("statechange", this, name, value);
15916 * Decodes a string previously encoded with {@link #encodeValue}.
15917 * @param {String} value The value to decode
15918 * @return {Mixed} The decoded value
15920 decodeValue : function(cookie){
15921 var re = /^(a|n|d|b|s|o)\:(.*)$/;
15922 var matches = re.exec(unescape(cookie));
15923 if(!matches || !matches[1]) {
15924 return; // non state cookie
15926 var type = matches[1];
15927 var v = matches[2];
15930 return parseFloat(v);
15932 return new Date(Date.parse(v));
15937 var values = v.split("^");
15938 for(var i = 0, len = values.length; i < len; i++){
15939 all.push(this.decodeValue(values[i]));
15944 var values = v.split("^");
15945 for(var i = 0, len = values.length; i < len; i++){
15946 var kv = values[i].split("=");
15947 all[kv[0]] = this.decodeValue(kv[1]);
15956 * Encodes a value including type information. Decode with {@link #decodeValue}.
15957 * @param {Mixed} value The value to encode
15958 * @return {String} The encoded value
15960 encodeValue : function(v){
15962 if(typeof v == "number"){
15964 }else if(typeof v == "boolean"){
15965 enc = "b:" + (v ? "1" : "0");
15966 }else if(v instanceof Date){
15967 enc = "d:" + v.toGMTString();
15968 }else if(v instanceof Array){
15970 for(var i = 0, len = v.length; i < len; i++){
15971 flat += this.encodeValue(v[i]);
15977 }else if(typeof v == "object"){
15980 if(typeof v[key] != "function"){
15981 flat += key + "=" + this.encodeValue(v[key]) + "^";
15984 enc = "o:" + flat.substring(0, flat.length-1);
15988 return escape(enc);
15994 * Ext JS Library 1.1.1
15995 * Copyright(c) 2006-2007, Ext JS, LLC.
15997 * Originally Released Under LGPL - original licence link has changed is not relivant.
16000 * <script type="text/javascript">
16003 * @class Roo.state.Manager
16004 * This is the global state manager. By default all components that are "state aware" check this class
16005 * for state information if you don't pass them a custom state provider. In order for this class
16006 * to be useful, it must be initialized with a provider when your application initializes.
16008 // in your initialization function
16010 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
16012 // supposed you have a {@link Roo.BorderLayout}
16013 var layout = new Roo.BorderLayout(...);
16014 layout.restoreState();
16015 // or a {Roo.BasicDialog}
16016 var dialog = new Roo.BasicDialog(...);
16017 dialog.restoreState();
16021 Roo.state.Manager = function(){
16022 var provider = new Roo.state.Provider();
16026 * Configures the default state provider for your application
16027 * @param {Provider} stateProvider The state provider to set
16029 setProvider : function(stateProvider){
16030 provider = stateProvider;
16034 * Returns the current value for a key
16035 * @param {String} name The key name
16036 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
16037 * @return {Mixed} The state data
16039 get : function(key, defaultValue){
16040 return provider.get(key, defaultValue);
16044 * Sets the value for a key
16045 * @param {String} name The key name
16046 * @param {Mixed} value The state data
16048 set : function(key, value){
16049 provider.set(key, value);
16053 * Clears a value from the state
16054 * @param {String} name The key name
16056 clear : function(key){
16057 provider.clear(key);
16061 * Gets the currently configured state provider
16062 * @return {Provider} The state provider
16064 getProvider : function(){
16071 * Ext JS Library 1.1.1
16072 * Copyright(c) 2006-2007, Ext JS, LLC.
16074 * Originally Released Under LGPL - original licence link has changed is not relivant.
16077 * <script type="text/javascript">
16080 * @class Roo.state.CookieProvider
16081 * @extends Roo.state.Provider
16082 * The default Provider implementation which saves state via cookies.
16085 var cp = new Roo.state.CookieProvider({
16087 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
16088 domain: "roojs.com"
16090 Roo.state.Manager.setProvider(cp);
16092 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
16093 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
16094 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
16095 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
16096 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
16097 * domain the page is running on including the 'www' like 'www.roojs.com')
16098 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
16100 * Create a new CookieProvider
16101 * @param {Object} config The configuration object
16103 Roo.state.CookieProvider = function(config){
16104 Roo.state.CookieProvider.superclass.constructor.call(this);
16106 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
16107 this.domain = null;
16108 this.secure = false;
16109 Roo.apply(this, config);
16110 this.state = this.readCookies();
16113 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
16115 set : function(name, value){
16116 if(typeof value == "undefined" || value === null){
16120 this.setCookie(name, value);
16121 Roo.state.CookieProvider.superclass.set.call(this, name, value);
16125 clear : function(name){
16126 this.clearCookie(name);
16127 Roo.state.CookieProvider.superclass.clear.call(this, name);
16131 readCookies : function(){
16133 var c = document.cookie + ";";
16134 var re = /\s?(.*?)=(.*?);/g;
16136 while((matches = re.exec(c)) != null){
16137 var name = matches[1];
16138 var value = matches[2];
16139 if(name && name.substring(0,3) == "ys-"){
16140 cookies[name.substr(3)] = this.decodeValue(value);
16147 setCookie : function(name, value){
16148 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
16149 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
16150 ((this.path == null) ? "" : ("; path=" + this.path)) +
16151 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16152 ((this.secure == true) ? "; secure" : "");
16156 clearCookie : function(name){
16157 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
16158 ((this.path == null) ? "" : ("; path=" + this.path)) +
16159 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16160 ((this.secure == true) ? "; secure" : "");
16164 * Ext JS Library 1.1.1
16165 * Copyright(c) 2006-2007, Ext JS, LLC.
16167 * Originally Released Under LGPL - original licence link has changed is not relivant.
16170 * <script type="text/javascript">
16175 * @class Roo.ComponentMgr
16176 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
16179 Roo.ComponentMgr = function(){
16180 var all = new Roo.util.MixedCollection();
16184 * Registers a component.
16185 * @param {Roo.Component} c The component
16187 register : function(c){
16192 * Unregisters a component.
16193 * @param {Roo.Component} c The component
16195 unregister : function(c){
16200 * Returns a component by id
16201 * @param {String} id The component id
16203 get : function(id){
16204 return all.get(id);
16208 * Registers a function that will be called when a specified component is added to ComponentMgr
16209 * @param {String} id The component id
16210 * @param {Funtction} fn The callback function
16211 * @param {Object} scope The scope of the callback
16213 onAvailable : function(id, fn, scope){
16214 all.on("add", function(index, o){
16216 fn.call(scope || o, o);
16217 all.un("add", fn, scope);
16224 * Ext JS Library 1.1.1
16225 * Copyright(c) 2006-2007, Ext JS, LLC.
16227 * Originally Released Under LGPL - original licence link has changed is not relivant.
16230 * <script type="text/javascript">
16234 * @class Roo.Component
16235 * @extends Roo.util.Observable
16236 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
16237 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
16238 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
16239 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
16240 * All visual components (widgets) that require rendering into a layout should subclass Component.
16242 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
16243 * element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element
16244 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
16246 Roo.Component = function(config){
16247 config = config || {};
16248 if(config.tagName || config.dom || typeof config == "string"){ // element object
16249 config = {el: config, id: config.id || config};
16251 this.initialConfig = config;
16253 Roo.apply(this, config);
16257 * Fires after the component is disabled.
16258 * @param {Roo.Component} this
16263 * Fires after the component is enabled.
16264 * @param {Roo.Component} this
16268 * @event beforeshow
16269 * Fires before the component is shown. Return false to stop the show.
16270 * @param {Roo.Component} this
16275 * Fires after the component is shown.
16276 * @param {Roo.Component} this
16280 * @event beforehide
16281 * Fires before the component is hidden. Return false to stop the hide.
16282 * @param {Roo.Component} this
16287 * Fires after the component is hidden.
16288 * @param {Roo.Component} this
16292 * @event beforerender
16293 * Fires before the component is rendered. Return false to stop the render.
16294 * @param {Roo.Component} this
16296 beforerender : true,
16299 * Fires after the component is rendered.
16300 * @param {Roo.Component} this
16304 * @event beforedestroy
16305 * Fires before the component is destroyed. Return false to stop the destroy.
16306 * @param {Roo.Component} this
16308 beforedestroy : true,
16311 * Fires after the component is destroyed.
16312 * @param {Roo.Component} this
16317 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
16319 Roo.ComponentMgr.register(this);
16320 Roo.Component.superclass.constructor.call(this);
16321 this.initComponent();
16322 if(this.renderTo){ // not supported by all components yet. use at your own risk!
16323 this.render(this.renderTo);
16324 delete this.renderTo;
16329 Roo.Component.AUTO_ID = 1000;
16331 Roo.extend(Roo.Component, Roo.util.Observable, {
16333 * @scope Roo.Component.prototype
16335 * true if this component is hidden. Read-only.
16340 * true if this component is disabled. Read-only.
16345 * true if this component has been rendered. Read-only.
16349 /** @cfg {String} disableClass
16350 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
16352 disabledClass : "x-item-disabled",
16353 /** @cfg {Boolean} allowDomMove
16354 * Whether the component can move the Dom node when rendering (defaults to true).
16356 allowDomMove : true,
16357 /** @cfg {String} hideMode (display|visibility)
16358 * How this component should hidden. Supported values are
16359 * "visibility" (css visibility), "offsets" (negative offset position) and
16360 * "display" (css display) - defaults to "display".
16362 hideMode: 'display',
16365 ctype : "Roo.Component",
16368 * @cfg {String} actionMode
16369 * which property holds the element that used for hide() / show() / disable() / enable()
16370 * default is 'el' for forms you probably want to set this to fieldEl
16375 getActionEl : function(){
16376 return this[this.actionMode];
16379 initComponent : Roo.emptyFn,
16381 * If this is a lazy rendering component, render it to its container element.
16382 * @param {String/HTMLElement/Element} container (optional) The element this component should be rendered into. If it is being applied to existing markup, this should be left off.
16384 render : function(container, position){
16390 if(this.fireEvent("beforerender", this) === false){
16394 if(!container && this.el){
16395 this.el = Roo.get(this.el);
16396 container = this.el.dom.parentNode;
16397 this.allowDomMove = false;
16399 this.container = Roo.get(container);
16400 this.rendered = true;
16401 if(position !== undefined){
16402 if(typeof position == 'number'){
16403 position = this.container.dom.childNodes[position];
16405 position = Roo.getDom(position);
16408 this.onRender(this.container, position || null);
16410 this.el.addClass(this.cls);
16414 this.el.applyStyles(this.style);
16417 this.fireEvent("render", this);
16418 this.afterRender(this.container);
16431 // default function is not really useful
16432 onRender : function(ct, position){
16434 this.el = Roo.get(this.el);
16435 if(this.allowDomMove !== false){
16436 ct.dom.insertBefore(this.el.dom, position);
16442 getAutoCreate : function(){
16443 var cfg = typeof this.autoCreate == "object" ?
16444 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
16445 if(this.id && !cfg.id){
16452 afterRender : Roo.emptyFn,
16455 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
16456 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
16458 destroy : function(){
16459 if(this.fireEvent("beforedestroy", this) !== false){
16460 this.purgeListeners();
16461 this.beforeDestroy();
16463 this.el.removeAllListeners();
16465 if(this.actionMode == "container"){
16466 this.container.remove();
16470 Roo.ComponentMgr.unregister(this);
16471 this.fireEvent("destroy", this);
16476 beforeDestroy : function(){
16481 onDestroy : function(){
16486 * Returns the underlying {@link Roo.Element}.
16487 * @return {Roo.Element} The element
16489 getEl : function(){
16494 * Returns the id of this component.
16497 getId : function(){
16502 * Try to focus this component.
16503 * @param {Boolean} selectText True to also select the text in this component (if applicable)
16504 * @return {Roo.Component} this
16506 focus : function(selectText){
16509 if(selectText === true){
16510 this.el.dom.select();
16525 * Disable this component.
16526 * @return {Roo.Component} this
16528 disable : function(){
16532 this.disabled = true;
16533 this.fireEvent("disable", this);
16538 onDisable : function(){
16539 this.getActionEl().addClass(this.disabledClass);
16540 this.el.dom.disabled = true;
16544 * Enable this component.
16545 * @return {Roo.Component} this
16547 enable : function(){
16551 this.disabled = false;
16552 this.fireEvent("enable", this);
16557 onEnable : function(){
16558 this.getActionEl().removeClass(this.disabledClass);
16559 this.el.dom.disabled = false;
16563 * Convenience function for setting disabled/enabled by boolean.
16564 * @param {Boolean} disabled
16566 setDisabled : function(disabled){
16567 this[disabled ? "disable" : "enable"]();
16571 * Show this component.
16572 * @return {Roo.Component} this
16575 if(this.fireEvent("beforeshow", this) !== false){
16576 this.hidden = false;
16580 this.fireEvent("show", this);
16586 onShow : function(){
16587 var ae = this.getActionEl();
16588 if(this.hideMode == 'visibility'){
16589 ae.dom.style.visibility = "visible";
16590 }else if(this.hideMode == 'offsets'){
16591 ae.removeClass('x-hidden');
16593 ae.dom.style.display = "";
16598 * Hide this component.
16599 * @return {Roo.Component} this
16602 if(this.fireEvent("beforehide", this) !== false){
16603 this.hidden = true;
16607 this.fireEvent("hide", this);
16613 onHide : function(){
16614 var ae = this.getActionEl();
16615 if(this.hideMode == 'visibility'){
16616 ae.dom.style.visibility = "hidden";
16617 }else if(this.hideMode == 'offsets'){
16618 ae.addClass('x-hidden');
16620 ae.dom.style.display = "none";
16625 * Convenience function to hide or show this component by boolean.
16626 * @param {Boolean} visible True to show, false to hide
16627 * @return {Roo.Component} this
16629 setVisible: function(visible){
16639 * Returns true if this component is visible.
16641 isVisible : function(){
16642 return this.getActionEl().isVisible();
16645 cloneConfig : function(overrides){
16646 overrides = overrides || {};
16647 var id = overrides.id || Roo.id();
16648 var cfg = Roo.applyIf(overrides, this.initialConfig);
16649 cfg.id = id; // prevent dup id
16650 return new this.constructor(cfg);
16654 * Ext JS Library 1.1.1
16655 * Copyright(c) 2006-2007, Ext JS, LLC.
16657 * Originally Released Under LGPL - original licence link has changed is not relivant.
16660 * <script type="text/javascript">
16664 * @class Roo.BoxComponent
16665 * @extends Roo.Component
16666 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
16667 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
16668 * container classes should subclass BoxComponent so that they will work consistently when nested within other Roo
16669 * layout containers.
16671 * @param {Roo.Element/String/Object} config The configuration options.
16673 Roo.BoxComponent = function(config){
16674 Roo.Component.call(this, config);
16678 * Fires after the component is resized.
16679 * @param {Roo.Component} this
16680 * @param {Number} adjWidth The box-adjusted width that was set
16681 * @param {Number} adjHeight The box-adjusted height that was set
16682 * @param {Number} rawWidth The width that was originally specified
16683 * @param {Number} rawHeight The height that was originally specified
16688 * Fires after the component is moved.
16689 * @param {Roo.Component} this
16690 * @param {Number} x The new x position
16691 * @param {Number} y The new y position
16697 Roo.extend(Roo.BoxComponent, Roo.Component, {
16698 // private, set in afterRender to signify that the component has been rendered
16700 // private, used to defer height settings to subclasses
16701 deferHeight: false,
16702 /** @cfg {Number} width
16703 * width (optional) size of component
16705 /** @cfg {Number} height
16706 * height (optional) size of component
16710 * Sets the width and height of the component. This method fires the resize event. This method can accept
16711 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
16712 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
16713 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
16714 * @return {Roo.BoxComponent} this
16716 setSize : function(w, h){
16717 // support for standard size objects
16718 if(typeof w == 'object'){
16723 if(!this.boxReady){
16729 // prevent recalcs when not needed
16730 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
16733 this.lastSize = {width: w, height: h};
16735 var adj = this.adjustSize(w, h);
16736 var aw = adj.width, ah = adj.height;
16737 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
16738 var rz = this.getResizeEl();
16739 if(!this.deferHeight && aw !== undefined && ah !== undefined){
16740 rz.setSize(aw, ah);
16741 }else if(!this.deferHeight && ah !== undefined){
16743 }else if(aw !== undefined){
16746 this.onResize(aw, ah, w, h);
16747 this.fireEvent('resize', this, aw, ah, w, h);
16753 * Gets the current size of the component's underlying element.
16754 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
16756 getSize : function(){
16757 return this.el.getSize();
16761 * Gets the current XY position of the component's underlying element.
16762 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16763 * @return {Array} The XY position of the element (e.g., [100, 200])
16765 getPosition : function(local){
16766 if(local === true){
16767 return [this.el.getLeft(true), this.el.getTop(true)];
16769 return this.xy || this.el.getXY();
16773 * Gets the current box measurements of the component's underlying element.
16774 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16775 * @returns {Object} box An object in the format {x, y, width, height}
16777 getBox : function(local){
16778 var s = this.el.getSize();
16780 s.x = this.el.getLeft(true);
16781 s.y = this.el.getTop(true);
16783 var xy = this.xy || this.el.getXY();
16791 * Sets the current box measurements of the component's underlying element.
16792 * @param {Object} box An object in the format {x, y, width, height}
16793 * @returns {Roo.BoxComponent} this
16795 updateBox : function(box){
16796 this.setSize(box.width, box.height);
16797 this.setPagePosition(box.x, box.y);
16802 getResizeEl : function(){
16803 return this.resizeEl || this.el;
16807 getPositionEl : function(){
16808 return this.positionEl || this.el;
16812 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
16813 * This method fires the move event.
16814 * @param {Number} left The new left
16815 * @param {Number} top The new top
16816 * @returns {Roo.BoxComponent} this
16818 setPosition : function(x, y){
16821 if(!this.boxReady){
16824 var adj = this.adjustPosition(x, y);
16825 var ax = adj.x, ay = adj.y;
16827 var el = this.getPositionEl();
16828 if(ax !== undefined || ay !== undefined){
16829 if(ax !== undefined && ay !== undefined){
16830 el.setLeftTop(ax, ay);
16831 }else if(ax !== undefined){
16833 }else if(ay !== undefined){
16836 this.onPosition(ax, ay);
16837 this.fireEvent('move', this, ax, ay);
16843 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
16844 * This method fires the move event.
16845 * @param {Number} x The new x position
16846 * @param {Number} y The new y position
16847 * @returns {Roo.BoxComponent} this
16849 setPagePosition : function(x, y){
16852 if(!this.boxReady){
16855 if(x === undefined || y === undefined){ // cannot translate undefined points
16858 var p = this.el.translatePoints(x, y);
16859 this.setPosition(p.left, p.top);
16864 onRender : function(ct, position){
16865 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
16867 this.resizeEl = Roo.get(this.resizeEl);
16869 if(this.positionEl){
16870 this.positionEl = Roo.get(this.positionEl);
16875 afterRender : function(){
16876 Roo.BoxComponent.superclass.afterRender.call(this);
16877 this.boxReady = true;
16878 this.setSize(this.width, this.height);
16879 if(this.x || this.y){
16880 this.setPosition(this.x, this.y);
16882 if(this.pageX || this.pageY){
16883 this.setPagePosition(this.pageX, this.pageY);
16888 * Force the component's size to recalculate based on the underlying element's current height and width.
16889 * @returns {Roo.BoxComponent} this
16891 syncSize : function(){
16892 delete this.lastSize;
16893 this.setSize(this.el.getWidth(), this.el.getHeight());
16898 * Called after the component is resized, this method is empty by default but can be implemented by any
16899 * subclass that needs to perform custom logic after a resize occurs.
16900 * @param {Number} adjWidth The box-adjusted width that was set
16901 * @param {Number} adjHeight The box-adjusted height that was set
16902 * @param {Number} rawWidth The width that was originally specified
16903 * @param {Number} rawHeight The height that was originally specified
16905 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
16910 * Called after the component is moved, this method is empty by default but can be implemented by any
16911 * subclass that needs to perform custom logic after a move occurs.
16912 * @param {Number} x The new x position
16913 * @param {Number} y The new y position
16915 onPosition : function(x, y){
16920 adjustSize : function(w, h){
16921 if(this.autoWidth){
16924 if(this.autoHeight){
16927 return {width : w, height: h};
16931 adjustPosition : function(x, y){
16932 return {x : x, y: y};
16936 * Ext JS Library 1.1.1
16937 * Copyright(c) 2006-2007, Ext JS, LLC.
16939 * Originally Released Under LGPL - original licence link has changed is not relivant.
16942 * <script type="text/javascript">
16947 * @extends Roo.Element
16948 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
16949 * automatic maintaining of shadow/shim positions.
16950 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
16951 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
16952 * you can pass a string with a CSS class name. False turns off the shadow.
16953 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
16954 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
16955 * @cfg {String} cls CSS class to add to the element
16956 * @cfg {Number} zindex Starting z-index (defaults to 11000)
16957 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
16959 * @param {Object} config An object with config options.
16960 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
16963 Roo.Layer = function(config, existingEl){
16964 config = config || {};
16965 var dh = Roo.DomHelper;
16966 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
16968 this.dom = Roo.getDom(existingEl);
16971 var o = config.dh || {tag: "div", cls: "x-layer"};
16972 this.dom = dh.append(pel, o);
16975 this.addClass(config.cls);
16977 this.constrain = config.constrain !== false;
16978 this.visibilityMode = Roo.Element.VISIBILITY;
16980 this.id = this.dom.id = config.id;
16982 this.id = Roo.id(this.dom);
16984 this.zindex = config.zindex || this.getZIndex();
16985 this.position("absolute", this.zindex);
16987 this.shadowOffset = config.shadowOffset || 4;
16988 this.shadow = new Roo.Shadow({
16989 offset : this.shadowOffset,
16990 mode : config.shadow
16993 this.shadowOffset = 0;
16995 this.useShim = config.shim !== false && Roo.useShims;
16996 this.useDisplay = config.useDisplay;
17000 var supr = Roo.Element.prototype;
17002 // shims are shared among layer to keep from having 100 iframes
17005 Roo.extend(Roo.Layer, Roo.Element, {
17007 getZIndex : function(){
17008 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
17011 getShim : function(){
17018 var shim = shims.shift();
17020 shim = this.createShim();
17021 shim.enableDisplayMode('block');
17022 shim.dom.style.display = 'none';
17023 shim.dom.style.visibility = 'visible';
17025 var pn = this.dom.parentNode;
17026 if(shim.dom.parentNode != pn){
17027 pn.insertBefore(shim.dom, this.dom);
17029 shim.setStyle('z-index', this.getZIndex()-2);
17034 hideShim : function(){
17036 this.shim.setDisplayed(false);
17037 shims.push(this.shim);
17042 disableShadow : function(){
17044 this.shadowDisabled = true;
17045 this.shadow.hide();
17046 this.lastShadowOffset = this.shadowOffset;
17047 this.shadowOffset = 0;
17051 enableShadow : function(show){
17053 this.shadowDisabled = false;
17054 this.shadowOffset = this.lastShadowOffset;
17055 delete this.lastShadowOffset;
17063 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
17064 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
17065 sync : function(doShow){
17066 var sw = this.shadow;
17067 if(!this.updating && this.isVisible() && (sw || this.useShim)){
17068 var sh = this.getShim();
17070 var w = this.getWidth(),
17071 h = this.getHeight();
17073 var l = this.getLeft(true),
17074 t = this.getTop(true);
17076 if(sw && !this.shadowDisabled){
17077 if(doShow && !sw.isVisible()){
17080 sw.realign(l, t, w, h);
17086 // fit the shim behind the shadow, so it is shimmed too
17087 var a = sw.adjusts, s = sh.dom.style;
17088 s.left = (Math.min(l, l+a.l))+"px";
17089 s.top = (Math.min(t, t+a.t))+"px";
17090 s.width = (w+a.w)+"px";
17091 s.height = (h+a.h)+"px";
17098 sh.setLeftTop(l, t);
17105 destroy : function(){
17108 this.shadow.hide();
17110 this.removeAllListeners();
17111 var pn = this.dom.parentNode;
17113 pn.removeChild(this.dom);
17115 Roo.Element.uncache(this.id);
17118 remove : function(){
17123 beginUpdate : function(){
17124 this.updating = true;
17128 endUpdate : function(){
17129 this.updating = false;
17134 hideUnders : function(negOffset){
17136 this.shadow.hide();
17142 constrainXY : function(){
17143 if(this.constrain){
17144 var vw = Roo.lib.Dom.getViewWidth(),
17145 vh = Roo.lib.Dom.getViewHeight();
17146 var s = Roo.get(document).getScroll();
17148 var xy = this.getXY();
17149 var x = xy[0], y = xy[1];
17150 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
17151 // only move it if it needs it
17153 // first validate right/bottom
17154 if((x + w) > vw+s.left){
17155 x = vw - w - this.shadowOffset;
17158 if((y + h) > vh+s.top){
17159 y = vh - h - this.shadowOffset;
17162 // then make sure top/left isn't negative
17173 var ay = this.avoidY;
17174 if(y <= ay && (y+h) >= ay){
17180 supr.setXY.call(this, xy);
17186 isVisible : function(){
17187 return this.visible;
17191 showAction : function(){
17192 this.visible = true; // track visibility to prevent getStyle calls
17193 if(this.useDisplay === true){
17194 this.setDisplayed("");
17195 }else if(this.lastXY){
17196 supr.setXY.call(this, this.lastXY);
17197 }else if(this.lastLT){
17198 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
17203 hideAction : function(){
17204 this.visible = false;
17205 if(this.useDisplay === true){
17206 this.setDisplayed(false);
17208 this.setLeftTop(-10000,-10000);
17212 // overridden Element method
17213 setVisible : function(v, a, d, c, e){
17218 var cb = function(){
17223 }.createDelegate(this);
17224 supr.setVisible.call(this, true, true, d, cb, e);
17227 this.hideUnders(true);
17236 }.createDelegate(this);
17238 supr.setVisible.call(this, v, a, d, cb, e);
17247 storeXY : function(xy){
17248 delete this.lastLT;
17252 storeLeftTop : function(left, top){
17253 delete this.lastXY;
17254 this.lastLT = [left, top];
17258 beforeFx : function(){
17259 this.beforeAction();
17260 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
17264 afterFx : function(){
17265 Roo.Layer.superclass.afterFx.apply(this, arguments);
17266 this.sync(this.isVisible());
17270 beforeAction : function(){
17271 if(!this.updating && this.shadow){
17272 this.shadow.hide();
17276 // overridden Element method
17277 setLeft : function(left){
17278 this.storeLeftTop(left, this.getTop(true));
17279 supr.setLeft.apply(this, arguments);
17283 setTop : function(top){
17284 this.storeLeftTop(this.getLeft(true), top);
17285 supr.setTop.apply(this, arguments);
17289 setLeftTop : function(left, top){
17290 this.storeLeftTop(left, top);
17291 supr.setLeftTop.apply(this, arguments);
17295 setXY : function(xy, a, d, c, e){
17297 this.beforeAction();
17299 var cb = this.createCB(c);
17300 supr.setXY.call(this, xy, a, d, cb, e);
17307 createCB : function(c){
17318 // overridden Element method
17319 setX : function(x, a, d, c, e){
17320 this.setXY([x, this.getY()], a, d, c, e);
17323 // overridden Element method
17324 setY : function(y, a, d, c, e){
17325 this.setXY([this.getX(), y], a, d, c, e);
17328 // overridden Element method
17329 setSize : function(w, h, a, d, c, e){
17330 this.beforeAction();
17331 var cb = this.createCB(c);
17332 supr.setSize.call(this, w, h, a, d, cb, e);
17338 // overridden Element method
17339 setWidth : function(w, a, d, c, e){
17340 this.beforeAction();
17341 var cb = this.createCB(c);
17342 supr.setWidth.call(this, w, a, d, cb, e);
17348 // overridden Element method
17349 setHeight : function(h, a, d, c, e){
17350 this.beforeAction();
17351 var cb = this.createCB(c);
17352 supr.setHeight.call(this, h, a, d, cb, e);
17358 // overridden Element method
17359 setBounds : function(x, y, w, h, a, d, c, e){
17360 this.beforeAction();
17361 var cb = this.createCB(c);
17363 this.storeXY([x, y]);
17364 supr.setXY.call(this, [x, y]);
17365 supr.setSize.call(this, w, h, a, d, cb, e);
17368 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
17374 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
17375 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
17376 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
17377 * @param {Number} zindex The new z-index to set
17378 * @return {this} The Layer
17380 setZIndex : function(zindex){
17381 this.zindex = zindex;
17382 this.setStyle("z-index", zindex + 2);
17384 this.shadow.setZIndex(zindex + 1);
17387 this.shim.setStyle("z-index", zindex);
17392 * Original code for Roojs - LGPL
17393 * <script type="text/javascript">
17397 * @class Roo.XComponent
17398 * A delayed Element creator...
17399 * Or a way to group chunks of interface together.
17400 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
17401 * used in conjunction with XComponent.build() it will create an instance of each element,
17402 * then call addxtype() to build the User interface.
17404 * Mypart.xyx = new Roo.XComponent({
17406 parent : 'Mypart.xyz', // empty == document.element.!!
17410 disabled : function() {}
17412 tree : function() { // return an tree of xtype declared components
17416 xtype : 'NestedLayoutPanel',
17423 * It can be used to build a big heiracy, with parent etc.
17424 * or you can just use this to render a single compoent to a dom element
17425 * MYPART.render(Roo.Element | String(id) | dom_element )
17432 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
17433 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
17435 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
17437 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
17438 * - if mulitple topModules exist, the last one is defined as the top module.
17442 * When the top level or multiple modules are to embedded into a existing HTML page,
17443 * the parent element can container '#id' of the element where the module will be drawn.
17447 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
17448 * it relies more on a include mechanism, where sub modules are included into an outer page.
17449 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
17451 * Bootstrap Roo Included elements
17453 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
17454 * hence confusing the component builder as it thinks there are multiple top level elements.
17456 * String Over-ride & Translations
17458 * Our builder application writes all the strings as _strings and _named_strings. This is to enable the translation of elements,
17459 * and also the 'overlaying of string values - needed when different versions of the same application with different text content
17460 * are needed. @see Roo.XComponent.overlayString
17464 * @extends Roo.util.Observable
17466 * @param cfg {Object} configuration of component
17469 Roo.XComponent = function(cfg) {
17470 Roo.apply(this, cfg);
17474 * Fires when this the componnt is built
17475 * @param {Roo.XComponent} c the component
17480 this.region = this.region || 'center'; // default..
17481 Roo.XComponent.register(this);
17482 this.modules = false;
17483 this.el = false; // where the layout goes..
17487 Roo.extend(Roo.XComponent, Roo.util.Observable, {
17490 * The created element (with Roo.factory())
17491 * @type {Roo.Layout}
17497 * for BC - use el in new code
17498 * @type {Roo.Layout}
17504 * for BC - use el in new code
17505 * @type {Roo.Layout}
17510 * @cfg {Function|boolean} disabled
17511 * If this module is disabled by some rule, return true from the funtion
17516 * @cfg {String} parent
17517 * Name of parent element which it get xtype added to..
17522 * @cfg {String} order
17523 * Used to set the order in which elements are created (usefull for multiple tabs)
17528 * @cfg {String} name
17529 * String to display while loading.
17533 * @cfg {String} region
17534 * Region to render component to (defaults to center)
17539 * @cfg {Array} items
17540 * A single item array - the first element is the root of the tree..
17541 * It's done this way to stay compatible with the Xtype system...
17547 * The method that retuns the tree of parts that make up this compoennt
17554 * render element to dom or tree
17555 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
17558 render : function(el)
17562 var hp = this.parent ? 1 : 0;
17563 Roo.debug && Roo.log(this);
17565 var tree = this._tree ? this._tree() : this.tree();
17568 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
17569 // if parent is a '#.....' string, then let's use that..
17570 var ename = this.parent.substr(1);
17571 this.parent = false;
17572 Roo.debug && Roo.log(ename);
17574 case 'bootstrap-body':
17575 if (typeof(tree.el) != 'undefined' && tree.el == document.body) {
17576 // this is the BorderLayout standard?
17577 this.parent = { el : true };
17580 if (["Nest", "Content", "Grid", "Tree"].indexOf(tree.xtype) > -1) {
17581 // need to insert stuff...
17583 el : new Roo.bootstrap.layout.Border({
17584 el : document.body,
17590 tabPosition: 'top',
17591 //resizeTabs: true,
17592 alwaysShowTabs: true,
17602 if (typeof(Roo.bootstrap.Body) != 'undefined' ) {
17603 this.parent = { el : new Roo.bootstrap.Body() };
17604 Roo.debug && Roo.log("setting el to doc body");
17607 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
17611 this.parent = { el : true};
17614 el = Roo.get(ename);
17615 if (typeof(Roo.bootstrap) != 'undefined' && tree['|xns'] == 'Roo.bootstrap') {
17616 this.parent = { el : true};
17623 if (!el && !this.parent) {
17624 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
17629 Roo.debug && Roo.log("EL:");
17630 Roo.debug && Roo.log(el);
17631 Roo.debug && Roo.log("this.parent.el:");
17632 Roo.debug && Roo.log(this.parent.el);
17635 // altertive root elements ??? - we need a better way to indicate these.
17636 var is_alt = Roo.XComponent.is_alt ||
17637 (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
17638 (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
17639 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
17643 if (!this.parent && is_alt) {
17644 //el = Roo.get(document.body);
17645 this.parent = { el : true };
17650 if (!this.parent) {
17652 Roo.debug && Roo.log("no parent - creating one");
17654 el = el ? Roo.get(el) : false;
17656 if (typeof(Roo.BorderLayout) == 'undefined' ) {
17659 el : new Roo.bootstrap.layout.Border({
17660 el: el || document.body,
17666 tabPosition: 'top',
17667 //resizeTabs: true,
17668 alwaysShowTabs: false,
17671 overflow: 'visible'
17677 // it's a top level one..
17679 el : new Roo.BorderLayout(el || document.body, {
17684 tabPosition: 'top',
17685 //resizeTabs: true,
17686 alwaysShowTabs: el && hp? false : true,
17687 hideTabs: el || !hp ? true : false,
17695 if (!this.parent.el) {
17696 // probably an old style ctor, which has been disabled.
17700 // The 'tree' method is '_tree now'
17702 tree.region = tree.region || this.region;
17703 var is_body = false;
17704 if (this.parent.el === true) {
17705 // bootstrap... - body..
17709 this.parent.el = Roo.factory(tree);
17713 this.el = this.parent.el.addxtype(tree, undefined, is_body);
17714 this.fireEvent('built', this);
17716 this.panel = this.el;
17717 this.layout = this.panel.layout;
17718 this.parentLayout = this.parent.layout || false;
17724 Roo.apply(Roo.XComponent, {
17726 * @property hideProgress
17727 * true to disable the building progress bar.. usefull on single page renders.
17730 hideProgress : false,
17732 * @property buildCompleted
17733 * True when the builder has completed building the interface.
17736 buildCompleted : false,
17739 * @property topModule
17740 * the upper most module - uses document.element as it's constructor.
17747 * @property modules
17748 * array of modules to be created by registration system.
17749 * @type {Array} of Roo.XComponent
17754 * @property elmodules
17755 * array of modules to be created by which use #ID
17756 * @type {Array} of Roo.XComponent
17763 * Is an alternative Root - normally used by bootstrap or other systems,
17764 * where the top element in the tree can wrap 'body'
17765 * @type {boolean} (default false)
17770 * @property build_from_html
17771 * Build elements from html - used by bootstrap HTML stuff
17772 * - this is cleared after build is completed
17773 * @type {boolean} (default false)
17776 build_from_html : false,
17778 * Register components to be built later.
17780 * This solves the following issues
17781 * - Building is not done on page load, but after an authentication process has occured.
17782 * - Interface elements are registered on page load
17783 * - Parent Interface elements may not be loaded before child, so this handles that..
17790 module : 'Pman.Tab.projectMgr',
17792 parent : 'Pman.layout',
17793 disabled : false, // or use a function..
17796 * * @param {Object} details about module
17798 register : function(obj) {
17800 Roo.XComponent.event.fireEvent('register', obj);
17801 switch(typeof(obj.disabled) ) {
17807 if ( obj.disabled() ) {
17813 if (obj.disabled || obj.region == '#disabled') {
17819 this.modules.push(obj);
17823 * convert a string to an object..
17824 * eg. 'AAA.BBB' -> finds AAA.BBB
17828 toObject : function(str)
17830 if (!str || typeof(str) == 'object') {
17833 if (str.substring(0,1) == '#') {
17837 var ar = str.split('.');
17842 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
17844 throw "Module not found : " + str;
17848 throw "Module not found : " + str;
17850 Roo.each(ar, function(e) {
17851 if (typeof(o[e]) == 'undefined') {
17852 throw "Module not found : " + str;
17863 * move modules into their correct place in the tree..
17866 preBuild : function ()
17869 Roo.each(this.modules , function (obj)
17871 Roo.XComponent.event.fireEvent('beforebuild', obj);
17873 var opar = obj.parent;
17875 obj.parent = this.toObject(opar);
17877 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
17882 Roo.debug && Roo.log("GOT top level module");
17883 Roo.debug && Roo.log(obj);
17884 obj.modules = new Roo.util.MixedCollection(false,
17885 function(o) { return o.order + '' }
17887 this.topModule = obj;
17890 // parent is a string (usually a dom element name..)
17891 if (typeof(obj.parent) == 'string') {
17892 this.elmodules.push(obj);
17895 if (obj.parent.constructor != Roo.XComponent) {
17896 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
17898 if (!obj.parent.modules) {
17899 obj.parent.modules = new Roo.util.MixedCollection(false,
17900 function(o) { return o.order + '' }
17903 if (obj.parent.disabled) {
17904 obj.disabled = true;
17906 obj.parent.modules.add(obj);
17911 * make a list of modules to build.
17912 * @return {Array} list of modules.
17915 buildOrder : function()
17918 var cmp = function(a,b) {
17919 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
17921 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
17922 throw "No top level modules to build";
17925 // make a flat list in order of modules to build.
17926 var mods = this.topModule ? [ this.topModule ] : [];
17929 // elmodules (is a list of DOM based modules )
17930 Roo.each(this.elmodules, function(e) {
17932 if (!this.topModule &&
17933 typeof(e.parent) == 'string' &&
17934 e.parent.substring(0,1) == '#' &&
17935 Roo.get(e.parent.substr(1))
17938 _this.topModule = e;
17944 // add modules to their parents..
17945 var addMod = function(m) {
17946 Roo.debug && Roo.log("build Order: add: " + m.name);
17949 if (m.modules && !m.disabled) {
17950 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
17951 m.modules.keySort('ASC', cmp );
17952 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
17954 m.modules.each(addMod);
17956 Roo.debug && Roo.log("build Order: no child modules");
17958 // not sure if this is used any more..
17960 m.finalize.name = m.name + " (clean up) ";
17961 mods.push(m.finalize);
17965 if (this.topModule && this.topModule.modules) {
17966 this.topModule.modules.keySort('ASC', cmp );
17967 this.topModule.modules.each(addMod);
17973 * Build the registered modules.
17974 * @param {Object} parent element.
17975 * @param {Function} optional method to call after module has been added.
17979 build : function(opts)
17982 if (typeof(opts) != 'undefined') {
17983 Roo.apply(this,opts);
17987 var mods = this.buildOrder();
17989 //this.allmods = mods;
17990 //Roo.debug && Roo.log(mods);
17992 if (!mods.length) { // should not happen
17993 throw "NO modules!!!";
17997 var msg = "Building Interface...";
17998 // flash it up as modal - so we store the mask!?
17999 if (!this.hideProgress && Roo.MessageBox) {
18000 Roo.MessageBox.show({ title: 'loading' });
18001 Roo.MessageBox.show({
18002 title: "Please wait...",
18012 var total = mods.length;
18015 var progressRun = function() {
18016 if (!mods.length) {
18017 Roo.debug && Roo.log('hide?');
18018 if (!this.hideProgress && Roo.MessageBox) {
18019 Roo.MessageBox.hide();
18021 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
18023 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
18029 var m = mods.shift();
18032 Roo.debug && Roo.log(m);
18033 // not sure if this is supported any more.. - modules that are are just function
18034 if (typeof(m) == 'function') {
18036 return progressRun.defer(10, _this);
18040 msg = "Building Interface " + (total - mods.length) +
18042 (m.name ? (' - ' + m.name) : '');
18043 Roo.debug && Roo.log(msg);
18044 if (!_this.hideProgress && Roo.MessageBox) {
18045 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
18049 // is the module disabled?
18050 var disabled = (typeof(m.disabled) == 'function') ?
18051 m.disabled.call(m.module.disabled) : m.disabled;
18055 return progressRun(); // we do not update the display!
18063 // it's 10 on top level, and 1 on others??? why...
18064 return progressRun.defer(10, _this);
18067 progressRun.defer(1, _this);
18073 * Overlay a set of modified strings onto a component
18074 * This is dependant on our builder exporting the strings and 'named strings' elements.
18076 * @param {Object} element to overlay on - eg. Pman.Dialog.Login
18077 * @param {Object} associative array of 'named' string and it's new value.
18080 overlayStrings : function( component, strings )
18082 if (typeof(component['_named_strings']) == 'undefined') {
18083 throw "ERROR: component does not have _named_strings";
18085 for ( var k in strings ) {
18086 var md = typeof(component['_named_strings'][k]) == 'undefined' ? false : component['_named_strings'][k];
18087 if (md !== false) {
18088 component['_strings'][md] = strings[k];
18090 Roo.log('could not find named string: ' + k + ' in');
18091 Roo.log(component);
18106 * wrapper for event.on - aliased later..
18107 * Typically use to register a event handler for register:
18109 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
18118 Roo.XComponent.event = new Roo.util.Observable({
18122 * Fires when an Component is registered,
18123 * set the disable property on the Component to stop registration.
18124 * @param {Roo.XComponent} c the component being registerd.
18129 * @event beforebuild
18130 * Fires before each Component is built
18131 * can be used to apply permissions.
18132 * @param {Roo.XComponent} c the component being registerd.
18135 'beforebuild' : true,
18137 * @event buildcomplete
18138 * Fires on the top level element when all elements have been built
18139 * @param {Roo.XComponent} the top level component.
18141 'buildcomplete' : true
18146 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
18149 * marked - a markdown parser
18150 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
18151 * https://github.com/chjj/marked
18157 * Roo.Markdown - is a very crude wrapper around marked..
18161 * alert( Roo.Markdown.toHtml("Markdown *rocks*.") );
18163 * Note: move the sample code to the bottom of this
18164 * file before uncommenting it.
18169 Roo.Markdown.toHtml = function(text) {
18171 var c = new Roo.Markdown.marked.setOptions({
18172 renderer: new Roo.Markdown.marked.Renderer(),
18183 text = text.replace(/\\\n/g,' ');
18184 return Roo.Markdown.marked(text);
18189 // Wraps all "globals" so that the only thing
18190 // exposed is makeHtml().
18196 * eval:var:unescape
18204 var escape = function (html, encode) {
18206 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
18207 .replace(/</g, '<')
18208 .replace(/>/g, '>')
18209 .replace(/"/g, '"')
18210 .replace(/'/g, ''');
18213 var unescape = function (html) {
18214 // explicitly match decimal, hex, and named HTML entities
18215 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
18216 n = n.toLowerCase();
18217 if (n === 'colon') { return ':'; }
18218 if (n.charAt(0) === '#') {
18219 return n.charAt(1) === 'x'
18220 ? String.fromCharCode(parseInt(n.substring(2), 16))
18221 : String.fromCharCode(+n.substring(1));
18227 var replace = function (regex, opt) {
18228 regex = regex.source;
18230 return function self(name, val) {
18231 if (!name) { return new RegExp(regex, opt); }
18232 val = val.source || val;
18233 val = val.replace(/(^|[^\[])\^/g, '$1');
18234 regex = regex.replace(name, val);
18243 var noop = function () {}
18249 var merge = function (obj) {
18254 for (; i < arguments.length; i++) {
18255 target = arguments[i];
18256 for (key in target) {
18257 if (Object.prototype.hasOwnProperty.call(target, key)) {
18258 obj[key] = target[key];
18268 * Block-Level Grammar
18276 code: /^( {4}[^\n]+\n*)+/,
18278 hr: /^( *[-*_]){3,} *(?:\n+|$)/,
18279 heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
18281 lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
18282 blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
18283 list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
18284 html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
18285 def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
18287 paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
18291 block.bullet = /(?:[*+-]|\d+\.)/;
18292 block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
18293 block.item = replace(block.item, 'gm')
18294 (/bull/g, block.bullet)
18297 block.list = replace(block.list)
18298 (/bull/g, block.bullet)
18299 ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
18300 ('def', '\\n+(?=' + block.def.source + ')')
18303 block.blockquote = replace(block.blockquote)
18307 block._tag = '(?!(?:'
18308 + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
18309 + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
18310 + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
18312 block.html = replace(block.html)
18313 ('comment', /<!--[\s\S]*?-->/)
18314 ('closed', /<(tag)[\s\S]+?<\/\1>/)
18315 ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
18316 (/tag/g, block._tag)
18319 block.paragraph = replace(block.paragraph)
18321 ('heading', block.heading)
18322 ('lheading', block.lheading)
18323 ('blockquote', block.blockquote)
18324 ('tag', '<' + block._tag)
18329 * Normal Block Grammar
18332 block.normal = merge({}, block);
18335 * GFM Block Grammar
18338 block.gfm = merge({}, block.normal, {
18339 fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
18341 heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
18344 block.gfm.paragraph = replace(block.paragraph)
18346 + block.gfm.fences.source.replace('\\1', '\\2') + '|'
18347 + block.list.source.replace('\\1', '\\3') + '|')
18351 * GFM + Tables Block Grammar
18354 block.tables = merge({}, block.gfm, {
18355 nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
18356 table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
18363 var Lexer = function (options) {
18365 this.tokens.links = {};
18366 this.options = options || marked.defaults;
18367 this.rules = block.normal;
18369 if (this.options.gfm) {
18370 if (this.options.tables) {
18371 this.rules = block.tables;
18373 this.rules = block.gfm;
18379 * Expose Block Rules
18382 Lexer.rules = block;
18385 * Static Lex Method
18388 Lexer.lex = function(src, options) {
18389 var lexer = new Lexer(options);
18390 return lexer.lex(src);
18397 Lexer.prototype.lex = function(src) {
18399 .replace(/\r\n|\r/g, '\n')
18400 .replace(/\t/g, ' ')
18401 .replace(/\u00a0/g, ' ')
18402 .replace(/\u2424/g, '\n');
18404 return this.token(src, true);
18411 Lexer.prototype.token = function(src, top, bq) {
18412 var src = src.replace(/^ +$/gm, '')
18425 if (cap = this.rules.newline.exec(src)) {
18426 src = src.substring(cap[0].length);
18427 if (cap[0].length > 1) {
18435 if (cap = this.rules.code.exec(src)) {
18436 src = src.substring(cap[0].length);
18437 cap = cap[0].replace(/^ {4}/gm, '');
18440 text: !this.options.pedantic
18441 ? cap.replace(/\n+$/, '')
18448 if (cap = this.rules.fences.exec(src)) {
18449 src = src.substring(cap[0].length);
18459 if (cap = this.rules.heading.exec(src)) {
18460 src = src.substring(cap[0].length);
18463 depth: cap[1].length,
18469 // table no leading pipe (gfm)
18470 if (top && (cap = this.rules.nptable.exec(src))) {
18471 src = src.substring(cap[0].length);
18475 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18476 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18477 cells: cap[3].replace(/\n$/, '').split('\n')
18480 for (i = 0; i < item.align.length; i++) {
18481 if (/^ *-+: *$/.test(item.align[i])) {
18482 item.align[i] = 'right';
18483 } else if (/^ *:-+: *$/.test(item.align[i])) {
18484 item.align[i] = 'center';
18485 } else if (/^ *:-+ *$/.test(item.align[i])) {
18486 item.align[i] = 'left';
18488 item.align[i] = null;
18492 for (i = 0; i < item.cells.length; i++) {
18493 item.cells[i] = item.cells[i].split(/ *\| */);
18496 this.tokens.push(item);
18502 if (cap = this.rules.lheading.exec(src)) {
18503 src = src.substring(cap[0].length);
18506 depth: cap[2] === '=' ? 1 : 2,
18513 if (cap = this.rules.hr.exec(src)) {
18514 src = src.substring(cap[0].length);
18522 if (cap = this.rules.blockquote.exec(src)) {
18523 src = src.substring(cap[0].length);
18526 type: 'blockquote_start'
18529 cap = cap[0].replace(/^ *> ?/gm, '');
18531 // Pass `top` to keep the current
18532 // "toplevel" state. This is exactly
18533 // how markdown.pl works.
18534 this.token(cap, top, true);
18537 type: 'blockquote_end'
18544 if (cap = this.rules.list.exec(src)) {
18545 src = src.substring(cap[0].length);
18549 type: 'list_start',
18550 ordered: bull.length > 1
18553 // Get each top-level item.
18554 cap = cap[0].match(this.rules.item);
18560 for (; i < l; i++) {
18563 // Remove the list item's bullet
18564 // so it is seen as the next token.
18565 space = item.length;
18566 item = item.replace(/^ *([*+-]|\d+\.) +/, '');
18568 // Outdent whatever the
18569 // list item contains. Hacky.
18570 if (~item.indexOf('\n ')) {
18571 space -= item.length;
18572 item = !this.options.pedantic
18573 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
18574 : item.replace(/^ {1,4}/gm, '');
18577 // Determine whether the next list item belongs here.
18578 // Backpedal if it does not belong in this list.
18579 if (this.options.smartLists && i !== l - 1) {
18580 b = block.bullet.exec(cap[i + 1])[0];
18581 if (bull !== b && !(bull.length > 1 && b.length > 1)) {
18582 src = cap.slice(i + 1).join('\n') + src;
18587 // Determine whether item is loose or not.
18588 // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
18589 // for discount behavior.
18590 loose = next || /\n\n(?!\s*$)/.test(item);
18592 next = item.charAt(item.length - 1) === '\n';
18593 if (!loose) { loose = next; }
18598 ? 'loose_item_start'
18599 : 'list_item_start'
18603 this.token(item, false, bq);
18606 type: 'list_item_end'
18618 if (cap = this.rules.html.exec(src)) {
18619 src = src.substring(cap[0].length);
18621 type: this.options.sanitize
18624 pre: !this.options.sanitizer
18625 && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
18632 if ((!bq && top) && (cap = this.rules.def.exec(src))) {
18633 src = src.substring(cap[0].length);
18634 this.tokens.links[cap[1].toLowerCase()] = {
18642 if (top && (cap = this.rules.table.exec(src))) {
18643 src = src.substring(cap[0].length);
18647 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18648 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18649 cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
18652 for (i = 0; i < item.align.length; i++) {
18653 if (/^ *-+: *$/.test(item.align[i])) {
18654 item.align[i] = 'right';
18655 } else if (/^ *:-+: *$/.test(item.align[i])) {
18656 item.align[i] = 'center';
18657 } else if (/^ *:-+ *$/.test(item.align[i])) {
18658 item.align[i] = 'left';
18660 item.align[i] = null;
18664 for (i = 0; i < item.cells.length; i++) {
18665 item.cells[i] = item.cells[i]
18666 .replace(/^ *\| *| *\| *$/g, '')
18670 this.tokens.push(item);
18675 // top-level paragraph
18676 if (top && (cap = this.rules.paragraph.exec(src))) {
18677 src = src.substring(cap[0].length);
18680 text: cap[1].charAt(cap[1].length - 1) === '\n'
18681 ? cap[1].slice(0, -1)
18688 if (cap = this.rules.text.exec(src)) {
18689 // Top-level should never reach here.
18690 src = src.substring(cap[0].length);
18700 Error('Infinite loop on byte: ' + src.charCodeAt(0));
18704 return this.tokens;
18708 * Inline-Level Grammar
18712 escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
18713 autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
18715 tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
18716 link: /^!?\[(inside)\]\(href\)/,
18717 reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
18718 nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
18719 strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
18720 em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
18721 code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
18722 br: /^ {2,}\n(?!\s*$)/,
18724 text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
18727 inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
18728 inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
18730 inline.link = replace(inline.link)
18731 ('inside', inline._inside)
18732 ('href', inline._href)
18735 inline.reflink = replace(inline.reflink)
18736 ('inside', inline._inside)
18740 * Normal Inline Grammar
18743 inline.normal = merge({}, inline);
18746 * Pedantic Inline Grammar
18749 inline.pedantic = merge({}, inline.normal, {
18750 strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
18751 em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
18755 * GFM Inline Grammar
18758 inline.gfm = merge({}, inline.normal, {
18759 escape: replace(inline.escape)('])', '~|])')(),
18760 url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
18761 del: /^~~(?=\S)([\s\S]*?\S)~~/,
18762 text: replace(inline.text)
18764 ('|', '|https?://|')
18769 * GFM + Line Breaks Inline Grammar
18772 inline.breaks = merge({}, inline.gfm, {
18773 br: replace(inline.br)('{2,}', '*')(),
18774 text: replace(inline.gfm.text)('{2,}', '*')()
18778 * Inline Lexer & Compiler
18781 var InlineLexer = function (links, options) {
18782 this.options = options || marked.defaults;
18783 this.links = links;
18784 this.rules = inline.normal;
18785 this.renderer = this.options.renderer || new Renderer;
18786 this.renderer.options = this.options;
18790 Error('Tokens array requires a `links` property.');
18793 if (this.options.gfm) {
18794 if (this.options.breaks) {
18795 this.rules = inline.breaks;
18797 this.rules = inline.gfm;
18799 } else if (this.options.pedantic) {
18800 this.rules = inline.pedantic;
18805 * Expose Inline Rules
18808 InlineLexer.rules = inline;
18811 * Static Lexing/Compiling Method
18814 InlineLexer.output = function(src, links, options) {
18815 var inline = new InlineLexer(links, options);
18816 return inline.output(src);
18823 InlineLexer.prototype.output = function(src) {
18832 if (cap = this.rules.escape.exec(src)) {
18833 src = src.substring(cap[0].length);
18839 if (cap = this.rules.autolink.exec(src)) {
18840 src = src.substring(cap[0].length);
18841 if (cap[2] === '@') {
18842 text = cap[1].charAt(6) === ':'
18843 ? this.mangle(cap[1].substring(7))
18844 : this.mangle(cap[1]);
18845 href = this.mangle('mailto:') + text;
18847 text = escape(cap[1]);
18850 out += this.renderer.link(href, null, text);
18855 if (!this.inLink && (cap = this.rules.url.exec(src))) {
18856 src = src.substring(cap[0].length);
18857 text = escape(cap[1]);
18859 out += this.renderer.link(href, null, text);
18864 if (cap = this.rules.tag.exec(src)) {
18865 if (!this.inLink && /^<a /i.test(cap[0])) {
18866 this.inLink = true;
18867 } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
18868 this.inLink = false;
18870 src = src.substring(cap[0].length);
18871 out += this.options.sanitize
18872 ? this.options.sanitizer
18873 ? this.options.sanitizer(cap[0])
18880 if (cap = this.rules.link.exec(src)) {
18881 src = src.substring(cap[0].length);
18882 this.inLink = true;
18883 out += this.outputLink(cap, {
18887 this.inLink = false;
18892 if ((cap = this.rules.reflink.exec(src))
18893 || (cap = this.rules.nolink.exec(src))) {
18894 src = src.substring(cap[0].length);
18895 link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
18896 link = this.links[link.toLowerCase()];
18897 if (!link || !link.href) {
18898 out += cap[0].charAt(0);
18899 src = cap[0].substring(1) + src;
18902 this.inLink = true;
18903 out += this.outputLink(cap, link);
18904 this.inLink = false;
18909 if (cap = this.rules.strong.exec(src)) {
18910 src = src.substring(cap[0].length);
18911 out += this.renderer.strong(this.output(cap[2] || cap[1]));
18916 if (cap = this.rules.em.exec(src)) {
18917 src = src.substring(cap[0].length);
18918 out += this.renderer.em(this.output(cap[2] || cap[1]));
18923 if (cap = this.rules.code.exec(src)) {
18924 src = src.substring(cap[0].length);
18925 out += this.renderer.codespan(escape(cap[2], true));
18930 if (cap = this.rules.br.exec(src)) {
18931 src = src.substring(cap[0].length);
18932 out += this.renderer.br();
18937 if (cap = this.rules.del.exec(src)) {
18938 src = src.substring(cap[0].length);
18939 out += this.renderer.del(this.output(cap[1]));
18944 if (cap = this.rules.text.exec(src)) {
18945 src = src.substring(cap[0].length);
18946 out += this.renderer.text(escape(this.smartypants(cap[0])));
18952 Error('Infinite loop on byte: ' + src.charCodeAt(0));
18963 InlineLexer.prototype.outputLink = function(cap, link) {
18964 var href = escape(link.href)
18965 , title = link.title ? escape(link.title) : null;
18967 return cap[0].charAt(0) !== '!'
18968 ? this.renderer.link(href, title, this.output(cap[1]))
18969 : this.renderer.image(href, title, escape(cap[1]));
18973 * Smartypants Transformations
18976 InlineLexer.prototype.smartypants = function(text) {
18977 if (!this.options.smartypants) { return text; }
18980 .replace(/---/g, '\u2014')
18982 .replace(/--/g, '\u2013')
18984 .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
18985 // closing singles & apostrophes
18986 .replace(/'/g, '\u2019')
18988 .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
18990 .replace(/"/g, '\u201d')
18992 .replace(/\.{3}/g, '\u2026');
18999 InlineLexer.prototype.mangle = function(text) {
19000 if (!this.options.mangle) { return text; }
19006 for (; i < l; i++) {
19007 ch = text.charCodeAt(i);
19008 if (Math.random() > 0.5) {
19009 ch = 'x' + ch.toString(16);
19011 out += '&#' + ch + ';';
19022 * eval:var:Renderer
19025 var Renderer = function (options) {
19026 this.options = options || {};
19029 Renderer.prototype.code = function(code, lang, escaped) {
19030 if (this.options.highlight) {
19031 var out = this.options.highlight(code, lang);
19032 if (out != null && out !== code) {
19037 // hack!!! - it's already escapeD?
19042 return '<pre><code>'
19043 + (escaped ? code : escape(code, true))
19044 + '\n</code></pre>';
19047 return '<pre><code class="'
19048 + this.options.langPrefix
19049 + escape(lang, true)
19051 + (escaped ? code : escape(code, true))
19052 + '\n</code></pre>\n';
19055 Renderer.prototype.blockquote = function(quote) {
19056 return '<blockquote>\n' + quote + '</blockquote>\n';
19059 Renderer.prototype.html = function(html) {
19063 Renderer.prototype.heading = function(text, level, raw) {
19067 + this.options.headerPrefix
19068 + raw.toLowerCase().replace(/[^\w]+/g, '-')
19076 Renderer.prototype.hr = function() {
19077 return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
19080 Renderer.prototype.list = function(body, ordered) {
19081 var type = ordered ? 'ol' : 'ul';
19082 return '<' + type + '>\n' + body + '</' + type + '>\n';
19085 Renderer.prototype.listitem = function(text) {
19086 return '<li>' + text + '</li>\n';
19089 Renderer.prototype.paragraph = function(text) {
19090 return '<p>' + text + '</p>\n';
19093 Renderer.prototype.table = function(header, body) {
19094 return '<table class="table table-striped">\n'
19104 Renderer.prototype.tablerow = function(content) {
19105 return '<tr>\n' + content + '</tr>\n';
19108 Renderer.prototype.tablecell = function(content, flags) {
19109 var type = flags.header ? 'th' : 'td';
19110 var tag = flags.align
19111 ? '<' + type + ' style="text-align:' + flags.align + '">'
19112 : '<' + type + '>';
19113 return tag + content + '</' + type + '>\n';
19116 // span level renderer
19117 Renderer.prototype.strong = function(text) {
19118 return '<strong>' + text + '</strong>';
19121 Renderer.prototype.em = function(text) {
19122 return '<em>' + text + '</em>';
19125 Renderer.prototype.codespan = function(text) {
19126 return '<code>' + text + '</code>';
19129 Renderer.prototype.br = function() {
19130 return this.options.xhtml ? '<br/>' : '<br>';
19133 Renderer.prototype.del = function(text) {
19134 return '<del>' + text + '</del>';
19137 Renderer.prototype.link = function(href, title, text) {
19138 if (this.options.sanitize) {
19140 var prot = decodeURIComponent(unescape(href))
19141 .replace(/[^\w:]/g, '')
19146 if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
19150 var out = '<a href="' + href + '"';
19152 out += ' title="' + title + '"';
19154 out += '>' + text + '</a>';
19158 Renderer.prototype.image = function(href, title, text) {
19159 var out = '<img src="' + href + '" alt="' + text + '"';
19161 out += ' title="' + title + '"';
19163 out += this.options.xhtml ? '/>' : '>';
19167 Renderer.prototype.text = function(text) {
19172 * Parsing & Compiling
19178 var Parser= function (options) {
19181 this.options = options || marked.defaults;
19182 this.options.renderer = this.options.renderer || new Renderer;
19183 this.renderer = this.options.renderer;
19184 this.renderer.options = this.options;
19188 * Static Parse Method
19191 Parser.parse = function(src, options, renderer) {
19192 var parser = new Parser(options, renderer);
19193 return parser.parse(src);
19200 Parser.prototype.parse = function(src) {
19201 this.inline = new InlineLexer(src.links, this.options, this.renderer);
19202 this.tokens = src.reverse();
19205 while (this.next()) {
19216 Parser.prototype.next = function() {
19217 return this.token = this.tokens.pop();
19221 * Preview Next Token
19224 Parser.prototype.peek = function() {
19225 return this.tokens[this.tokens.length - 1] || 0;
19229 * Parse Text Tokens
19232 Parser.prototype.parseText = function() {
19233 var body = this.token.text;
19235 while (this.peek().type === 'text') {
19236 body += '\n' + this.next().text;
19239 return this.inline.output(body);
19243 * Parse Current Token
19246 Parser.prototype.tok = function() {
19247 switch (this.token.type) {
19252 return this.renderer.hr();
19255 return this.renderer.heading(
19256 this.inline.output(this.token.text),
19261 return this.renderer.code(this.token.text,
19263 this.token.escaped);
19276 for (i = 0; i < this.token.header.length; i++) {
19277 flags = { header: true, align: this.token.align[i] };
19278 cell += this.renderer.tablecell(
19279 this.inline.output(this.token.header[i]),
19280 { header: true, align: this.token.align[i] }
19283 header += this.renderer.tablerow(cell);
19285 for (i = 0; i < this.token.cells.length; i++) {
19286 row = this.token.cells[i];
19289 for (j = 0; j < row.length; j++) {
19290 cell += this.renderer.tablecell(
19291 this.inline.output(row[j]),
19292 { header: false, align: this.token.align[j] }
19296 body += this.renderer.tablerow(cell);
19298 return this.renderer.table(header, body);
19300 case 'blockquote_start': {
19303 while (this.next().type !== 'blockquote_end') {
19304 body += this.tok();
19307 return this.renderer.blockquote(body);
19309 case 'list_start': {
19311 , ordered = this.token.ordered;
19313 while (this.next().type !== 'list_end') {
19314 body += this.tok();
19317 return this.renderer.list(body, ordered);
19319 case 'list_item_start': {
19322 while (this.next().type !== 'list_item_end') {
19323 body += this.token.type === 'text'
19328 return this.renderer.listitem(body);
19330 case 'loose_item_start': {
19333 while (this.next().type !== 'list_item_end') {
19334 body += this.tok();
19337 return this.renderer.listitem(body);
19340 var html = !this.token.pre && !this.options.pedantic
19341 ? this.inline.output(this.token.text)
19343 return this.renderer.html(html);
19345 case 'paragraph': {
19346 return this.renderer.paragraph(this.inline.output(this.token.text));
19349 return this.renderer.paragraph(this.parseText());
19361 var marked = function (src, opt, callback) {
19362 if (callback || typeof opt === 'function') {
19368 opt = merge({}, marked.defaults, opt || {});
19370 var highlight = opt.highlight
19376 tokens = Lexer.lex(src, opt)
19378 return callback(e);
19381 pending = tokens.length;
19385 var done = function(err) {
19387 opt.highlight = highlight;
19388 return callback(err);
19394 out = Parser.parse(tokens, opt);
19399 opt.highlight = highlight;
19403 : callback(null, out);
19406 if (!highlight || highlight.length < 3) {
19410 delete opt.highlight;
19412 if (!pending) { return done(); }
19414 for (; i < tokens.length; i++) {
19416 if (token.type !== 'code') {
19417 return --pending || done();
19419 return highlight(token.text, token.lang, function(err, code) {
19420 if (err) { return done(err); }
19421 if (code == null || code === token.text) {
19422 return --pending || done();
19425 token.escaped = true;
19426 --pending || done();
19434 if (opt) { opt = merge({}, marked.defaults, opt); }
19435 return Parser.parse(Lexer.lex(src, opt), opt);
19437 e.message += '\nPlease report this to https://github.com/chjj/marked.';
19438 if ((opt || marked.defaults).silent) {
19439 return '<p>An error occured:</p><pre>'
19440 + escape(e.message + '', true)
19452 marked.setOptions = function(opt) {
19453 merge(marked.defaults, opt);
19457 marked.defaults = {
19468 langPrefix: 'lang-',
19469 smartypants: false,
19471 renderer: new Renderer,
19479 marked.Parser = Parser;
19480 marked.parser = Parser.parse;
19482 marked.Renderer = Renderer;
19484 marked.Lexer = Lexer;
19485 marked.lexer = Lexer.lex;
19487 marked.InlineLexer = InlineLexer;
19488 marked.inlineLexer = InlineLexer.output;
19490 marked.parse = marked;
19492 Roo.Markdown.marked = marked;
19496 * Ext JS Library 1.1.1
19497 * Copyright(c) 2006-2007, Ext JS, LLC.
19499 * Originally Released Under LGPL - original licence link has changed is not relivant.
19502 * <script type="text/javascript">
19508 * These classes are derivatives of the similarly named classes in the YUI Library.
19509 * The original license:
19510 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
19511 * Code licensed under the BSD License:
19512 * http://developer.yahoo.net/yui/license.txt
19517 var Event=Roo.EventManager;
19518 var Dom=Roo.lib.Dom;
19521 * @class Roo.dd.DragDrop
19522 * @extends Roo.util.Observable
19523 * Defines the interface and base operation of items that that can be
19524 * dragged or can be drop targets. It was designed to be extended, overriding
19525 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
19526 * Up to three html elements can be associated with a DragDrop instance:
19528 * <li>linked element: the element that is passed into the constructor.
19529 * This is the element which defines the boundaries for interaction with
19530 * other DragDrop objects.</li>
19531 * <li>handle element(s): The drag operation only occurs if the element that
19532 * was clicked matches a handle element. By default this is the linked
19533 * element, but there are times that you will want only a portion of the
19534 * linked element to initiate the drag operation, and the setHandleElId()
19535 * method provides a way to define this.</li>
19536 * <li>drag element: this represents the element that would be moved along
19537 * with the cursor during a drag operation. By default, this is the linked
19538 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
19539 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
19542 * This class should not be instantiated until the onload event to ensure that
19543 * the associated elements are available.
19544 * The following would define a DragDrop obj that would interact with any
19545 * other DragDrop obj in the "group1" group:
19547 * dd = new Roo.dd.DragDrop("div1", "group1");
19549 * Since none of the event handlers have been implemented, nothing would
19550 * actually happen if you were to run the code above. Normally you would
19551 * override this class or one of the default implementations, but you can
19552 * also override the methods you want on an instance of the class...
19554 * dd.onDragDrop = function(e, id) {
19555 * alert("dd was dropped on " + id);
19559 * @param {String} id of the element that is linked to this instance
19560 * @param {String} sGroup the group of related DragDrop objects
19561 * @param {object} config an object containing configurable attributes
19562 * Valid properties for DragDrop:
19563 * padding, isTarget, maintainOffset, primaryButtonOnly
19565 Roo.dd.DragDrop = function(id, sGroup, config) {
19567 this.init(id, sGroup, config);
19572 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
19575 * The id of the element associated with this object. This is what we
19576 * refer to as the "linked element" because the size and position of
19577 * this element is used to determine when the drag and drop objects have
19585 * Configuration attributes passed into the constructor
19592 * The id of the element that will be dragged. By default this is same
19593 * as the linked element , but could be changed to another element. Ex:
19595 * @property dragElId
19602 * the id of the element that initiates the drag operation. By default
19603 * this is the linked element, but could be changed to be a child of this
19604 * element. This lets us do things like only starting the drag when the
19605 * header element within the linked html element is clicked.
19606 * @property handleElId
19613 * An associative array of HTML tags that will be ignored if clicked.
19614 * @property invalidHandleTypes
19615 * @type {string: string}
19617 invalidHandleTypes: null,
19620 * An associative array of ids for elements that will be ignored if clicked
19621 * @property invalidHandleIds
19622 * @type {string: string}
19624 invalidHandleIds: null,
19627 * An indexted array of css class names for elements that will be ignored
19629 * @property invalidHandleClasses
19632 invalidHandleClasses: null,
19635 * The linked element's absolute X position at the time the drag was
19637 * @property startPageX
19644 * The linked element's absolute X position at the time the drag was
19646 * @property startPageY
19653 * The group defines a logical collection of DragDrop objects that are
19654 * related. Instances only get events when interacting with other
19655 * DragDrop object in the same group. This lets us define multiple
19656 * groups using a single DragDrop subclass if we want.
19658 * @type {string: string}
19663 * Individual drag/drop instances can be locked. This will prevent
19664 * onmousedown start drag.
19672 * Lock this instance
19675 lock: function() { this.locked = true; },
19678 * Unlock this instace
19681 unlock: function() { this.locked = false; },
19684 * By default, all insances can be a drop target. This can be disabled by
19685 * setting isTarget to false.
19692 * The padding configured for this drag and drop object for calculating
19693 * the drop zone intersection with this object.
19700 * Cached reference to the linked element
19701 * @property _domRef
19707 * Internal typeof flag
19708 * @property __ygDragDrop
19711 __ygDragDrop: true,
19714 * Set to true when horizontal contraints are applied
19715 * @property constrainX
19722 * Set to true when vertical contraints are applied
19723 * @property constrainY
19730 * The left constraint
19738 * The right constraint
19746 * The up constraint
19755 * The down constraint
19763 * Maintain offsets when we resetconstraints. Set to true when you want
19764 * the position of the element relative to its parent to stay the same
19765 * when the page changes
19767 * @property maintainOffset
19770 maintainOffset: false,
19773 * Array of pixel locations the element will snap to if we specified a
19774 * horizontal graduation/interval. This array is generated automatically
19775 * when you define a tick interval.
19782 * Array of pixel locations the element will snap to if we specified a
19783 * vertical graduation/interval. This array is generated automatically
19784 * when you define a tick interval.
19791 * By default the drag and drop instance will only respond to the primary
19792 * button click (left button for a right-handed mouse). Set to true to
19793 * allow drag and drop to start with any mouse click that is propogated
19795 * @property primaryButtonOnly
19798 primaryButtonOnly: true,
19801 * The availabe property is false until the linked dom element is accessible.
19802 * @property available
19808 * By default, drags can only be initiated if the mousedown occurs in the
19809 * region the linked element is. This is done in part to work around a
19810 * bug in some browsers that mis-report the mousedown if the previous
19811 * mouseup happened outside of the window. This property is set to true
19812 * if outer handles are defined.
19814 * @property hasOuterHandles
19818 hasOuterHandles: false,
19821 * Code that executes immediately before the startDrag event
19822 * @method b4StartDrag
19825 b4StartDrag: function(x, y) { },
19828 * Abstract method called after a drag/drop object is clicked
19829 * and the drag or mousedown time thresholds have beeen met.
19830 * @method startDrag
19831 * @param {int} X click location
19832 * @param {int} Y click location
19834 startDrag: function(x, y) { /* override this */ },
19837 * Code that executes immediately before the onDrag event
19841 b4Drag: function(e) { },
19844 * Abstract method called during the onMouseMove event while dragging an
19847 * @param {Event} e the mousemove event
19849 onDrag: function(e) { /* override this */ },
19852 * Abstract method called when this element fist begins hovering over
19853 * another DragDrop obj
19854 * @method onDragEnter
19855 * @param {Event} e the mousemove event
19856 * @param {String|DragDrop[]} id In POINT mode, the element
19857 * id this is hovering over. In INTERSECT mode, an array of one or more
19858 * dragdrop items being hovered over.
19860 onDragEnter: function(e, id) { /* override this */ },
19863 * Code that executes immediately before the onDragOver event
19864 * @method b4DragOver
19867 b4DragOver: function(e) { },
19870 * Abstract method called when this element is hovering over another
19872 * @method onDragOver
19873 * @param {Event} e the mousemove event
19874 * @param {String|DragDrop[]} id In POINT mode, the element
19875 * id this is hovering over. In INTERSECT mode, an array of dd items
19876 * being hovered over.
19878 onDragOver: function(e, id) { /* override this */ },
19881 * Code that executes immediately before the onDragOut event
19882 * @method b4DragOut
19885 b4DragOut: function(e) { },
19888 * Abstract method called when we are no longer hovering over an element
19889 * @method onDragOut
19890 * @param {Event} e the mousemove event
19891 * @param {String|DragDrop[]} id In POINT mode, the element
19892 * id this was hovering over. In INTERSECT mode, an array of dd items
19893 * that the mouse is no longer over.
19895 onDragOut: function(e, id) { /* override this */ },
19898 * Code that executes immediately before the onDragDrop event
19899 * @method b4DragDrop
19902 b4DragDrop: function(e) { },
19905 * Abstract method called when this item is dropped on another DragDrop
19907 * @method onDragDrop
19908 * @param {Event} e the mouseup event
19909 * @param {String|DragDrop[]} id In POINT mode, the element
19910 * id this was dropped on. In INTERSECT mode, an array of dd items this
19913 onDragDrop: function(e, id) { /* override this */ },
19916 * Abstract method called when this item is dropped on an area with no
19918 * @method onInvalidDrop
19919 * @param {Event} e the mouseup event
19921 onInvalidDrop: function(e) { /* override this */ },
19924 * Code that executes immediately before the endDrag event
19925 * @method b4EndDrag
19928 b4EndDrag: function(e) { },
19931 * Fired when we are done dragging the object
19933 * @param {Event} e the mouseup event
19935 endDrag: function(e) { /* override this */ },
19938 * Code executed immediately before the onMouseDown event
19939 * @method b4MouseDown
19940 * @param {Event} e the mousedown event
19943 b4MouseDown: function(e) { },
19946 * Event handler that fires when a drag/drop obj gets a mousedown
19947 * @method onMouseDown
19948 * @param {Event} e the mousedown event
19950 onMouseDown: function(e) { /* override this */ },
19953 * Event handler that fires when a drag/drop obj gets a mouseup
19954 * @method onMouseUp
19955 * @param {Event} e the mouseup event
19957 onMouseUp: function(e) { /* override this */ },
19960 * Override the onAvailable method to do what is needed after the initial
19961 * position was determined.
19962 * @method onAvailable
19964 onAvailable: function () {
19968 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
19971 defaultPadding : {left:0, right:0, top:0, bottom:0},
19974 * Initializes the drag drop object's constraints to restrict movement to a certain element.
19978 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
19979 { dragElId: "existingProxyDiv" });
19980 dd.startDrag = function(){
19981 this.constrainTo("parent-id");
19984 * Or you can initalize it using the {@link Roo.Element} object:
19986 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
19987 startDrag : function(){
19988 this.constrainTo("parent-id");
19992 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
19993 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
19994 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
19995 * an object containing the sides to pad. For example: {right:10, bottom:10}
19996 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
19998 constrainTo : function(constrainTo, pad, inContent){
19999 if(typeof pad == "number"){
20000 pad = {left: pad, right:pad, top:pad, bottom:pad};
20002 pad = pad || this.defaultPadding;
20003 var b = Roo.get(this.getEl()).getBox();
20004 var ce = Roo.get(constrainTo);
20005 var s = ce.getScroll();
20006 var c, cd = ce.dom;
20007 if(cd == document.body){
20008 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
20011 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
20015 var topSpace = b.y - c.y;
20016 var leftSpace = b.x - c.x;
20018 this.resetConstraints();
20019 this.setXConstraint(leftSpace - (pad.left||0), // left
20020 c.width - leftSpace - b.width - (pad.right||0) //right
20022 this.setYConstraint(topSpace - (pad.top||0), //top
20023 c.height - topSpace - b.height - (pad.bottom||0) //bottom
20028 * Returns a reference to the linked element
20030 * @return {HTMLElement} the html element
20032 getEl: function() {
20033 if (!this._domRef) {
20034 this._domRef = Roo.getDom(this.id);
20037 return this._domRef;
20041 * Returns a reference to the actual element to drag. By default this is
20042 * the same as the html element, but it can be assigned to another
20043 * element. An example of this can be found in Roo.dd.DDProxy
20044 * @method getDragEl
20045 * @return {HTMLElement} the html element
20047 getDragEl: function() {
20048 return Roo.getDom(this.dragElId);
20052 * Sets up the DragDrop object. Must be called in the constructor of any
20053 * Roo.dd.DragDrop subclass
20055 * @param id the id of the linked element
20056 * @param {String} sGroup the group of related items
20057 * @param {object} config configuration attributes
20059 init: function(id, sGroup, config) {
20060 this.initTarget(id, sGroup, config);
20061 if (!Roo.isTouch) {
20062 Event.on(this.id, "mousedown", this.handleMouseDown, this);
20064 Event.on(this.id, "touchstart", this.handleMouseDown, this);
20065 // Event.on(this.id, "selectstart", Event.preventDefault);
20069 * Initializes Targeting functionality only... the object does not
20070 * get a mousedown handler.
20071 * @method initTarget
20072 * @param id the id of the linked element
20073 * @param {String} sGroup the group of related items
20074 * @param {object} config configuration attributes
20076 initTarget: function(id, sGroup, config) {
20078 // configuration attributes
20079 this.config = config || {};
20081 // create a local reference to the drag and drop manager
20082 this.DDM = Roo.dd.DDM;
20083 // initialize the groups array
20086 // assume that we have an element reference instead of an id if the
20087 // parameter is not a string
20088 if (typeof id !== "string") {
20095 // add to an interaction group
20096 this.addToGroup((sGroup) ? sGroup : "default");
20098 // We don't want to register this as the handle with the manager
20099 // so we just set the id rather than calling the setter.
20100 this.handleElId = id;
20102 // the linked element is the element that gets dragged by default
20103 this.setDragElId(id);
20105 // by default, clicked anchors will not start drag operations.
20106 this.invalidHandleTypes = { A: "A" };
20107 this.invalidHandleIds = {};
20108 this.invalidHandleClasses = [];
20110 this.applyConfig();
20112 this.handleOnAvailable();
20116 * Applies the configuration parameters that were passed into the constructor.
20117 * This is supposed to happen at each level through the inheritance chain. So
20118 * a DDProxy implentation will execute apply config on DDProxy, DD, and
20119 * DragDrop in order to get all of the parameters that are available in
20121 * @method applyConfig
20123 applyConfig: function() {
20125 // configurable properties:
20126 // padding, isTarget, maintainOffset, primaryButtonOnly
20127 this.padding = this.config.padding || [0, 0, 0, 0];
20128 this.isTarget = (this.config.isTarget !== false);
20129 this.maintainOffset = (this.config.maintainOffset);
20130 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
20135 * Executed when the linked element is available
20136 * @method handleOnAvailable
20139 handleOnAvailable: function() {
20140 this.available = true;
20141 this.resetConstraints();
20142 this.onAvailable();
20146 * Configures the padding for the target zone in px. Effectively expands
20147 * (or reduces) the virtual object size for targeting calculations.
20148 * Supports css-style shorthand; if only one parameter is passed, all sides
20149 * will have that padding, and if only two are passed, the top and bottom
20150 * will have the first param, the left and right the second.
20151 * @method setPadding
20152 * @param {int} iTop Top pad
20153 * @param {int} iRight Right pad
20154 * @param {int} iBot Bot pad
20155 * @param {int} iLeft Left pad
20157 setPadding: function(iTop, iRight, iBot, iLeft) {
20158 // this.padding = [iLeft, iRight, iTop, iBot];
20159 if (!iRight && 0 !== iRight) {
20160 this.padding = [iTop, iTop, iTop, iTop];
20161 } else if (!iBot && 0 !== iBot) {
20162 this.padding = [iTop, iRight, iTop, iRight];
20164 this.padding = [iTop, iRight, iBot, iLeft];
20169 * Stores the initial placement of the linked element.
20170 * @method setInitialPosition
20171 * @param {int} diffX the X offset, default 0
20172 * @param {int} diffY the Y offset, default 0
20174 setInitPosition: function(diffX, diffY) {
20175 var el = this.getEl();
20177 if (!this.DDM.verifyEl(el)) {
20181 var dx = diffX || 0;
20182 var dy = diffY || 0;
20184 var p = Dom.getXY( el );
20186 this.initPageX = p[0] - dx;
20187 this.initPageY = p[1] - dy;
20189 this.lastPageX = p[0];
20190 this.lastPageY = p[1];
20193 this.setStartPosition(p);
20197 * Sets the start position of the element. This is set when the obj
20198 * is initialized, the reset when a drag is started.
20199 * @method setStartPosition
20200 * @param pos current position (from previous lookup)
20203 setStartPosition: function(pos) {
20204 var p = pos || Dom.getXY( this.getEl() );
20205 this.deltaSetXY = null;
20207 this.startPageX = p[0];
20208 this.startPageY = p[1];
20212 * Add this instance to a group of related drag/drop objects. All
20213 * instances belong to at least one group, and can belong to as many
20214 * groups as needed.
20215 * @method addToGroup
20216 * @param sGroup {string} the name of the group
20218 addToGroup: function(sGroup) {
20219 this.groups[sGroup] = true;
20220 this.DDM.regDragDrop(this, sGroup);
20224 * Remove's this instance from the supplied interaction group
20225 * @method removeFromGroup
20226 * @param {string} sGroup The group to drop
20228 removeFromGroup: function(sGroup) {
20229 if (this.groups[sGroup]) {
20230 delete this.groups[sGroup];
20233 this.DDM.removeDDFromGroup(this, sGroup);
20237 * Allows you to specify that an element other than the linked element
20238 * will be moved with the cursor during a drag
20239 * @method setDragElId
20240 * @param id {string} the id of the element that will be used to initiate the drag
20242 setDragElId: function(id) {
20243 this.dragElId = id;
20247 * Allows you to specify a child of the linked element that should be
20248 * used to initiate the drag operation. An example of this would be if
20249 * you have a content div with text and links. Clicking anywhere in the
20250 * content area would normally start the drag operation. Use this method
20251 * to specify that an element inside of the content div is the element
20252 * that starts the drag operation.
20253 * @method setHandleElId
20254 * @param id {string} the id of the element that will be used to
20255 * initiate the drag.
20257 setHandleElId: function(id) {
20258 if (typeof id !== "string") {
20261 this.handleElId = id;
20262 this.DDM.regHandle(this.id, id);
20266 * Allows you to set an element outside of the linked element as a drag
20268 * @method setOuterHandleElId
20269 * @param id the id of the element that will be used to initiate the drag
20271 setOuterHandleElId: function(id) {
20272 if (typeof id !== "string") {
20275 Event.on(id, "mousedown",
20276 this.handleMouseDown, this);
20277 this.setHandleElId(id);
20279 this.hasOuterHandles = true;
20283 * Remove all drag and drop hooks for this element
20286 unreg: function() {
20287 Event.un(this.id, "mousedown",
20288 this.handleMouseDown);
20289 Event.un(this.id, "touchstart",
20290 this.handleMouseDown);
20291 this._domRef = null;
20292 this.DDM._remove(this);
20295 destroy : function(){
20300 * Returns true if this instance is locked, or the drag drop mgr is locked
20301 * (meaning that all drag/drop is disabled on the page.)
20303 * @return {boolean} true if this obj or all drag/drop is locked, else
20306 isLocked: function() {
20307 return (this.DDM.isLocked() || this.locked);
20311 * Fired when this object is clicked
20312 * @method handleMouseDown
20314 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
20317 handleMouseDown: function(e, oDD){
20319 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
20320 //Roo.log('not touch/ button !=0');
20323 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
20324 return; // double touch..
20328 if (this.isLocked()) {
20329 //Roo.log('locked');
20333 this.DDM.refreshCache(this.groups);
20334 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
20335 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
20336 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
20337 //Roo.log('no outer handes or not over target');
20340 // Roo.log('check validator');
20341 if (this.clickValidator(e)) {
20342 // Roo.log('validate success');
20343 // set the initial element position
20344 this.setStartPosition();
20347 this.b4MouseDown(e);
20348 this.onMouseDown(e);
20350 this.DDM.handleMouseDown(e, this);
20352 this.DDM.stopEvent(e);
20360 clickValidator: function(e) {
20361 var target = e.getTarget();
20362 return ( this.isValidHandleChild(target) &&
20363 (this.id == this.handleElId ||
20364 this.DDM.handleWasClicked(target, this.id)) );
20368 * Allows you to specify a tag name that should not start a drag operation
20369 * when clicked. This is designed to facilitate embedding links within a
20370 * drag handle that do something other than start the drag.
20371 * @method addInvalidHandleType
20372 * @param {string} tagName the type of element to exclude
20374 addInvalidHandleType: function(tagName) {
20375 var type = tagName.toUpperCase();
20376 this.invalidHandleTypes[type] = type;
20380 * Lets you to specify an element id for a child of a drag handle
20381 * that should not initiate a drag
20382 * @method addInvalidHandleId
20383 * @param {string} id the element id of the element you wish to ignore
20385 addInvalidHandleId: function(id) {
20386 if (typeof id !== "string") {
20389 this.invalidHandleIds[id] = id;
20393 * Lets you specify a css class of elements that will not initiate a drag
20394 * @method addInvalidHandleClass
20395 * @param {string} cssClass the class of the elements you wish to ignore
20397 addInvalidHandleClass: function(cssClass) {
20398 this.invalidHandleClasses.push(cssClass);
20402 * Unsets an excluded tag name set by addInvalidHandleType
20403 * @method removeInvalidHandleType
20404 * @param {string} tagName the type of element to unexclude
20406 removeInvalidHandleType: function(tagName) {
20407 var type = tagName.toUpperCase();
20408 // this.invalidHandleTypes[type] = null;
20409 delete this.invalidHandleTypes[type];
20413 * Unsets an invalid handle id
20414 * @method removeInvalidHandleId
20415 * @param {string} id the id of the element to re-enable
20417 removeInvalidHandleId: function(id) {
20418 if (typeof id !== "string") {
20421 delete this.invalidHandleIds[id];
20425 * Unsets an invalid css class
20426 * @method removeInvalidHandleClass
20427 * @param {string} cssClass the class of the element(s) you wish to
20430 removeInvalidHandleClass: function(cssClass) {
20431 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
20432 if (this.invalidHandleClasses[i] == cssClass) {
20433 delete this.invalidHandleClasses[i];
20439 * Checks the tag exclusion list to see if this click should be ignored
20440 * @method isValidHandleChild
20441 * @param {HTMLElement} node the HTMLElement to evaluate
20442 * @return {boolean} true if this is a valid tag type, false if not
20444 isValidHandleChild: function(node) {
20447 // var n = (node.nodeName == "#text") ? node.parentNode : node;
20450 nodeName = node.nodeName.toUpperCase();
20452 nodeName = node.nodeName;
20454 valid = valid && !this.invalidHandleTypes[nodeName];
20455 valid = valid && !this.invalidHandleIds[node.id];
20457 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
20458 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
20467 * Create the array of horizontal tick marks if an interval was specified
20468 * in setXConstraint().
20469 * @method setXTicks
20472 setXTicks: function(iStartX, iTickSize) {
20474 this.xTickSize = iTickSize;
20478 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
20480 this.xTicks[this.xTicks.length] = i;
20485 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
20487 this.xTicks[this.xTicks.length] = i;
20492 this.xTicks.sort(this.DDM.numericSort) ;
20496 * Create the array of vertical tick marks if an interval was specified in
20497 * setYConstraint().
20498 * @method setYTicks
20501 setYTicks: function(iStartY, iTickSize) {
20503 this.yTickSize = iTickSize;
20507 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
20509 this.yTicks[this.yTicks.length] = i;
20514 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
20516 this.yTicks[this.yTicks.length] = i;
20521 this.yTicks.sort(this.DDM.numericSort) ;
20525 * By default, the element can be dragged any place on the screen. Use
20526 * this method to limit the horizontal travel of the element. Pass in
20527 * 0,0 for the parameters if you want to lock the drag to the y axis.
20528 * @method setXConstraint
20529 * @param {int} iLeft the number of pixels the element can move to the left
20530 * @param {int} iRight the number of pixels the element can move to the
20532 * @param {int} iTickSize optional parameter for specifying that the
20534 * should move iTickSize pixels at a time.
20536 setXConstraint: function(iLeft, iRight, iTickSize) {
20537 this.leftConstraint = iLeft;
20538 this.rightConstraint = iRight;
20540 this.minX = this.initPageX - iLeft;
20541 this.maxX = this.initPageX + iRight;
20542 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
20544 this.constrainX = true;
20548 * Clears any constraints applied to this instance. Also clears ticks
20549 * since they can't exist independent of a constraint at this time.
20550 * @method clearConstraints
20552 clearConstraints: function() {
20553 this.constrainX = false;
20554 this.constrainY = false;
20559 * Clears any tick interval defined for this instance
20560 * @method clearTicks
20562 clearTicks: function() {
20563 this.xTicks = null;
20564 this.yTicks = null;
20565 this.xTickSize = 0;
20566 this.yTickSize = 0;
20570 * By default, the element can be dragged any place on the screen. Set
20571 * this to limit the vertical travel of the element. Pass in 0,0 for the
20572 * parameters if you want to lock the drag to the x axis.
20573 * @method setYConstraint
20574 * @param {int} iUp the number of pixels the element can move up
20575 * @param {int} iDown the number of pixels the element can move down
20576 * @param {int} iTickSize optional parameter for specifying that the
20577 * element should move iTickSize pixels at a time.
20579 setYConstraint: function(iUp, iDown, iTickSize) {
20580 this.topConstraint = iUp;
20581 this.bottomConstraint = iDown;
20583 this.minY = this.initPageY - iUp;
20584 this.maxY = this.initPageY + iDown;
20585 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
20587 this.constrainY = true;
20592 * resetConstraints must be called if you manually reposition a dd element.
20593 * @method resetConstraints
20594 * @param {boolean} maintainOffset
20596 resetConstraints: function() {
20599 // Maintain offsets if necessary
20600 if (this.initPageX || this.initPageX === 0) {
20601 // figure out how much this thing has moved
20602 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
20603 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
20605 this.setInitPosition(dx, dy);
20607 // This is the first time we have detected the element's position
20609 this.setInitPosition();
20612 if (this.constrainX) {
20613 this.setXConstraint( this.leftConstraint,
20614 this.rightConstraint,
20618 if (this.constrainY) {
20619 this.setYConstraint( this.topConstraint,
20620 this.bottomConstraint,
20626 * Normally the drag element is moved pixel by pixel, but we can specify
20627 * that it move a number of pixels at a time. This method resolves the
20628 * location when we have it set up like this.
20630 * @param {int} val where we want to place the object
20631 * @param {int[]} tickArray sorted array of valid points
20632 * @return {int} the closest tick
20635 getTick: function(val, tickArray) {
20638 // If tick interval is not defined, it is effectively 1 pixel,
20639 // so we return the value passed to us.
20641 } else if (tickArray[0] >= val) {
20642 // The value is lower than the first tick, so we return the first
20644 return tickArray[0];
20646 for (var i=0, len=tickArray.length; i<len; ++i) {
20648 if (tickArray[next] && tickArray[next] >= val) {
20649 var diff1 = val - tickArray[i];
20650 var diff2 = tickArray[next] - val;
20651 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
20655 // The value is larger than the last tick, so we return the last
20657 return tickArray[tickArray.length - 1];
20664 * @return {string} string representation of the dd obj
20666 toString: function() {
20667 return ("DragDrop " + this.id);
20675 * Ext JS Library 1.1.1
20676 * Copyright(c) 2006-2007, Ext JS, LLC.
20678 * Originally Released Under LGPL - original licence link has changed is not relivant.
20681 * <script type="text/javascript">
20686 * The drag and drop utility provides a framework for building drag and drop
20687 * applications. In addition to enabling drag and drop for specific elements,
20688 * the drag and drop elements are tracked by the manager class, and the
20689 * interactions between the various elements are tracked during the drag and
20690 * the implementing code is notified about these important moments.
20693 // Only load the library once. Rewriting the manager class would orphan
20694 // existing drag and drop instances.
20695 if (!Roo.dd.DragDropMgr) {
20698 * @class Roo.dd.DragDropMgr
20699 * DragDropMgr is a singleton that tracks the element interaction for
20700 * all DragDrop items in the window. Generally, you will not call
20701 * this class directly, but it does have helper methods that could
20702 * be useful in your DragDrop implementations.
20705 Roo.dd.DragDropMgr = function() {
20707 var Event = Roo.EventManager;
20712 * Two dimensional Array of registered DragDrop objects. The first
20713 * dimension is the DragDrop item group, the second the DragDrop
20716 * @type {string: string}
20723 * Array of element ids defined as drag handles. Used to determine
20724 * if the element that generated the mousedown event is actually the
20725 * handle and not the html element itself.
20726 * @property handleIds
20727 * @type {string: string}
20734 * the DragDrop object that is currently being dragged
20735 * @property dragCurrent
20743 * the DragDrop object(s) that are being hovered over
20744 * @property dragOvers
20752 * the X distance between the cursor and the object being dragged
20761 * the Y distance between the cursor and the object being dragged
20770 * Flag to determine if we should prevent the default behavior of the
20771 * events we define. By default this is true, but this can be set to
20772 * false if you need the default behavior (not recommended)
20773 * @property preventDefault
20777 preventDefault: true,
20780 * Flag to determine if we should stop the propagation of the events
20781 * we generate. This is true by default but you may want to set it to
20782 * false if the html element contains other features that require the
20784 * @property stopPropagation
20788 stopPropagation: true,
20791 * Internal flag that is set to true when drag and drop has been
20793 * @property initialized
20800 * All drag and drop can be disabled.
20808 * Called the first time an element is registered.
20814 this.initialized = true;
20818 * In point mode, drag and drop interaction is defined by the
20819 * location of the cursor during the drag/drop
20827 * In intersect mode, drag and drop interactio nis defined by the
20828 * overlap of two or more drag and drop objects.
20829 * @property INTERSECT
20836 * The current drag and drop mode. Default: POINT
20844 * Runs method on all drag and drop objects
20845 * @method _execOnAll
20849 _execOnAll: function(sMethod, args) {
20850 for (var i in this.ids) {
20851 for (var j in this.ids[i]) {
20852 var oDD = this.ids[i][j];
20853 if (! this.isTypeOfDD(oDD)) {
20856 oDD[sMethod].apply(oDD, args);
20862 * Drag and drop initialization. Sets up the global event handlers
20867 _onLoad: function() {
20871 if (!Roo.isTouch) {
20872 Event.on(document, "mouseup", this.handleMouseUp, this, true);
20873 Event.on(document, "mousemove", this.handleMouseMove, this, true);
20875 Event.on(document, "touchend", this.handleMouseUp, this, true);
20876 Event.on(document, "touchmove", this.handleMouseMove, this, true);
20878 Event.on(window, "unload", this._onUnload, this, true);
20879 Event.on(window, "resize", this._onResize, this, true);
20880 // Event.on(window, "mouseout", this._test);
20885 * Reset constraints on all drag and drop objs
20886 * @method _onResize
20890 _onResize: function(e) {
20891 this._execOnAll("resetConstraints", []);
20895 * Lock all drag and drop functionality
20899 lock: function() { this.locked = true; },
20902 * Unlock all drag and drop functionality
20906 unlock: function() { this.locked = false; },
20909 * Is drag and drop locked?
20911 * @return {boolean} True if drag and drop is locked, false otherwise.
20914 isLocked: function() { return this.locked; },
20917 * Location cache that is set for all drag drop objects when a drag is
20918 * initiated, cleared when the drag is finished.
20919 * @property locationCache
20926 * Set useCache to false if you want to force object the lookup of each
20927 * drag and drop linked element constantly during a drag.
20928 * @property useCache
20935 * The number of pixels that the mouse needs to move after the
20936 * mousedown before the drag is initiated. Default=3;
20937 * @property clickPixelThresh
20941 clickPixelThresh: 3,
20944 * The number of milliseconds after the mousedown event to initiate the
20945 * drag if we don't get a mouseup event. Default=1000
20946 * @property clickTimeThresh
20950 clickTimeThresh: 350,
20953 * Flag that indicates that either the drag pixel threshold or the
20954 * mousdown time threshold has been met
20955 * @property dragThreshMet
20960 dragThreshMet: false,
20963 * Timeout used for the click time threshold
20964 * @property clickTimeout
20969 clickTimeout: null,
20972 * The X position of the mousedown event stored for later use when a
20973 * drag threshold is met.
20982 * The Y position of the mousedown event stored for later use when a
20983 * drag threshold is met.
20992 * Each DragDrop instance must be registered with the DragDropMgr.
20993 * This is executed in DragDrop.init()
20994 * @method regDragDrop
20995 * @param {DragDrop} oDD the DragDrop object to register
20996 * @param {String} sGroup the name of the group this element belongs to
20999 regDragDrop: function(oDD, sGroup) {
21000 if (!this.initialized) { this.init(); }
21002 if (!this.ids[sGroup]) {
21003 this.ids[sGroup] = {};
21005 this.ids[sGroup][oDD.id] = oDD;
21009 * Removes the supplied dd instance from the supplied group. Executed
21010 * by DragDrop.removeFromGroup, so don't call this function directly.
21011 * @method removeDDFromGroup
21015 removeDDFromGroup: function(oDD, sGroup) {
21016 if (!this.ids[sGroup]) {
21017 this.ids[sGroup] = {};
21020 var obj = this.ids[sGroup];
21021 if (obj && obj[oDD.id]) {
21022 delete obj[oDD.id];
21027 * Unregisters a drag and drop item. This is executed in
21028 * DragDrop.unreg, use that method instead of calling this directly.
21033 _remove: function(oDD) {
21034 for (var g in oDD.groups) {
21035 if (g && this.ids[g][oDD.id]) {
21036 delete this.ids[g][oDD.id];
21039 delete this.handleIds[oDD.id];
21043 * Each DragDrop handle element must be registered. This is done
21044 * automatically when executing DragDrop.setHandleElId()
21045 * @method regHandle
21046 * @param {String} sDDId the DragDrop id this element is a handle for
21047 * @param {String} sHandleId the id of the element that is the drag
21051 regHandle: function(sDDId, sHandleId) {
21052 if (!this.handleIds[sDDId]) {
21053 this.handleIds[sDDId] = {};
21055 this.handleIds[sDDId][sHandleId] = sHandleId;
21059 * Utility function to determine if a given element has been
21060 * registered as a drag drop item.
21061 * @method isDragDrop
21062 * @param {String} id the element id to check
21063 * @return {boolean} true if this element is a DragDrop item,
21067 isDragDrop: function(id) {
21068 return ( this.getDDById(id) ) ? true : false;
21072 * Returns the drag and drop instances that are in all groups the
21073 * passed in instance belongs to.
21074 * @method getRelated
21075 * @param {DragDrop} p_oDD the obj to get related data for
21076 * @param {boolean} bTargetsOnly if true, only return targetable objs
21077 * @return {DragDrop[]} the related instances
21080 getRelated: function(p_oDD, bTargetsOnly) {
21082 for (var i in p_oDD.groups) {
21083 for (j in this.ids[i]) {
21084 var dd = this.ids[i][j];
21085 if (! this.isTypeOfDD(dd)) {
21088 if (!bTargetsOnly || dd.isTarget) {
21089 oDDs[oDDs.length] = dd;
21098 * Returns true if the specified dd target is a legal target for
21099 * the specifice drag obj
21100 * @method isLegalTarget
21101 * @param {DragDrop} the drag obj
21102 * @param {DragDrop} the target
21103 * @return {boolean} true if the target is a legal target for the
21107 isLegalTarget: function (oDD, oTargetDD) {
21108 var targets = this.getRelated(oDD, true);
21109 for (var i=0, len=targets.length;i<len;++i) {
21110 if (targets[i].id == oTargetDD.id) {
21119 * My goal is to be able to transparently determine if an object is
21120 * typeof DragDrop, and the exact subclass of DragDrop. typeof
21121 * returns "object", oDD.constructor.toString() always returns
21122 * "DragDrop" and not the name of the subclass. So for now it just
21123 * evaluates a well-known variable in DragDrop.
21124 * @method isTypeOfDD
21125 * @param {Object} the object to evaluate
21126 * @return {boolean} true if typeof oDD = DragDrop
21129 isTypeOfDD: function (oDD) {
21130 return (oDD && oDD.__ygDragDrop);
21134 * Utility function to determine if a given element has been
21135 * registered as a drag drop handle for the given Drag Drop object.
21137 * @param {String} id the element id to check
21138 * @return {boolean} true if this element is a DragDrop handle, false
21142 isHandle: function(sDDId, sHandleId) {
21143 return ( this.handleIds[sDDId] &&
21144 this.handleIds[sDDId][sHandleId] );
21148 * Returns the DragDrop instance for a given id
21149 * @method getDDById
21150 * @param {String} id the id of the DragDrop object
21151 * @return {DragDrop} the drag drop object, null if it is not found
21154 getDDById: function(id) {
21155 for (var i in this.ids) {
21156 if (this.ids[i][id]) {
21157 return this.ids[i][id];
21164 * Fired after a registered DragDrop object gets the mousedown event.
21165 * Sets up the events required to track the object being dragged
21166 * @method handleMouseDown
21167 * @param {Event} e the event
21168 * @param oDD the DragDrop object being dragged
21172 handleMouseDown: function(e, oDD) {
21174 Roo.QuickTips.disable();
21176 this.currentTarget = e.getTarget();
21178 this.dragCurrent = oDD;
21180 var el = oDD.getEl();
21182 // track start position
21183 this.startX = e.getPageX();
21184 this.startY = e.getPageY();
21186 this.deltaX = this.startX - el.offsetLeft;
21187 this.deltaY = this.startY - el.offsetTop;
21189 this.dragThreshMet = false;
21191 this.clickTimeout = setTimeout(
21193 var DDM = Roo.dd.DDM;
21194 DDM.startDrag(DDM.startX, DDM.startY);
21196 this.clickTimeThresh );
21200 * Fired when either the drag pixel threshol or the mousedown hold
21201 * time threshold has been met.
21202 * @method startDrag
21203 * @param x {int} the X position of the original mousedown
21204 * @param y {int} the Y position of the original mousedown
21207 startDrag: function(x, y) {
21208 clearTimeout(this.clickTimeout);
21209 if (this.dragCurrent) {
21210 this.dragCurrent.b4StartDrag(x, y);
21211 this.dragCurrent.startDrag(x, y);
21213 this.dragThreshMet = true;
21217 * Internal function to handle the mouseup event. Will be invoked
21218 * from the context of the document.
21219 * @method handleMouseUp
21220 * @param {Event} e the event
21224 handleMouseUp: function(e) {
21227 Roo.QuickTips.enable();
21229 if (! this.dragCurrent) {
21233 clearTimeout(this.clickTimeout);
21235 if (this.dragThreshMet) {
21236 this.fireEvents(e, true);
21246 * Utility to stop event propagation and event default, if these
21247 * features are turned on.
21248 * @method stopEvent
21249 * @param {Event} e the event as returned by this.getEvent()
21252 stopEvent: function(e){
21253 if(this.stopPropagation) {
21254 e.stopPropagation();
21257 if (this.preventDefault) {
21258 e.preventDefault();
21263 * Internal function to clean up event handlers after the drag
21264 * operation is complete
21266 * @param {Event} e the event
21270 stopDrag: function(e) {
21271 // Fire the drag end event for the item that was dragged
21272 if (this.dragCurrent) {
21273 if (this.dragThreshMet) {
21274 this.dragCurrent.b4EndDrag(e);
21275 this.dragCurrent.endDrag(e);
21278 this.dragCurrent.onMouseUp(e);
21281 this.dragCurrent = null;
21282 this.dragOvers = {};
21286 * Internal function to handle the mousemove event. Will be invoked
21287 * from the context of the html element.
21289 * @TODO figure out what we can do about mouse events lost when the
21290 * user drags objects beyond the window boundary. Currently we can
21291 * detect this in internet explorer by verifying that the mouse is
21292 * down during the mousemove event. Firefox doesn't give us the
21293 * button state on the mousemove event.
21294 * @method handleMouseMove
21295 * @param {Event} e the event
21299 handleMouseMove: function(e) {
21300 if (! this.dragCurrent) {
21304 // var button = e.which || e.button;
21306 // check for IE mouseup outside of page boundary
21307 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
21309 return this.handleMouseUp(e);
21312 if (!this.dragThreshMet) {
21313 var diffX = Math.abs(this.startX - e.getPageX());
21314 var diffY = Math.abs(this.startY - e.getPageY());
21315 if (diffX > this.clickPixelThresh ||
21316 diffY > this.clickPixelThresh) {
21317 this.startDrag(this.startX, this.startY);
21321 if (this.dragThreshMet) {
21322 this.dragCurrent.b4Drag(e);
21323 this.dragCurrent.onDrag(e);
21324 if(!this.dragCurrent.moveOnly){
21325 this.fireEvents(e, false);
21335 * Iterates over all of the DragDrop elements to find ones we are
21336 * hovering over or dropping on
21337 * @method fireEvents
21338 * @param {Event} e the event
21339 * @param {boolean} isDrop is this a drop op or a mouseover op?
21343 fireEvents: function(e, isDrop) {
21344 var dc = this.dragCurrent;
21346 // If the user did the mouse up outside of the window, we could
21347 // get here even though we have ended the drag.
21348 if (!dc || dc.isLocked()) {
21352 var pt = e.getPoint();
21354 // cache the previous dragOver array
21360 var enterEvts = [];
21362 // Check to see if the object(s) we were hovering over is no longer
21363 // being hovered over so we can fire the onDragOut event
21364 for (var i in this.dragOvers) {
21366 var ddo = this.dragOvers[i];
21368 if (! this.isTypeOfDD(ddo)) {
21372 if (! this.isOverTarget(pt, ddo, this.mode)) {
21373 outEvts.push( ddo );
21376 oldOvers[i] = true;
21377 delete this.dragOvers[i];
21380 for (var sGroup in dc.groups) {
21382 if ("string" != typeof sGroup) {
21386 for (i in this.ids[sGroup]) {
21387 var oDD = this.ids[sGroup][i];
21388 if (! this.isTypeOfDD(oDD)) {
21392 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
21393 if (this.isOverTarget(pt, oDD, this.mode)) {
21394 // look for drop interactions
21396 dropEvts.push( oDD );
21397 // look for drag enter and drag over interactions
21400 // initial drag over: dragEnter fires
21401 if (!oldOvers[oDD.id]) {
21402 enterEvts.push( oDD );
21403 // subsequent drag overs: dragOver fires
21405 overEvts.push( oDD );
21408 this.dragOvers[oDD.id] = oDD;
21416 if (outEvts.length) {
21417 dc.b4DragOut(e, outEvts);
21418 dc.onDragOut(e, outEvts);
21421 if (enterEvts.length) {
21422 dc.onDragEnter(e, enterEvts);
21425 if (overEvts.length) {
21426 dc.b4DragOver(e, overEvts);
21427 dc.onDragOver(e, overEvts);
21430 if (dropEvts.length) {
21431 dc.b4DragDrop(e, dropEvts);
21432 dc.onDragDrop(e, dropEvts);
21436 // fire dragout events
21438 for (i=0, len=outEvts.length; i<len; ++i) {
21439 dc.b4DragOut(e, outEvts[i].id);
21440 dc.onDragOut(e, outEvts[i].id);
21443 // fire enter events
21444 for (i=0,len=enterEvts.length; i<len; ++i) {
21445 // dc.b4DragEnter(e, oDD.id);
21446 dc.onDragEnter(e, enterEvts[i].id);
21449 // fire over events
21450 for (i=0,len=overEvts.length; i<len; ++i) {
21451 dc.b4DragOver(e, overEvts[i].id);
21452 dc.onDragOver(e, overEvts[i].id);
21455 // fire drop events
21456 for (i=0, len=dropEvts.length; i<len; ++i) {
21457 dc.b4DragDrop(e, dropEvts[i].id);
21458 dc.onDragDrop(e, dropEvts[i].id);
21463 // notify about a drop that did not find a target
21464 if (isDrop && !dropEvts.length) {
21465 dc.onInvalidDrop(e);
21471 * Helper function for getting the best match from the list of drag
21472 * and drop objects returned by the drag and drop events when we are
21473 * in INTERSECT mode. It returns either the first object that the
21474 * cursor is over, or the object that has the greatest overlap with
21475 * the dragged element.
21476 * @method getBestMatch
21477 * @param {DragDrop[]} dds The array of drag and drop objects
21479 * @return {DragDrop} The best single match
21482 getBestMatch: function(dds) {
21484 // Return null if the input is not what we expect
21485 //if (!dds || !dds.length || dds.length == 0) {
21487 // If there is only one item, it wins
21488 //} else if (dds.length == 1) {
21490 var len = dds.length;
21495 // Loop through the targeted items
21496 for (var i=0; i<len; ++i) {
21498 // If the cursor is over the object, it wins. If the
21499 // cursor is over multiple matches, the first one we come
21501 if (dd.cursorIsOver) {
21504 // Otherwise the object with the most overlap wins
21507 winner.overlap.getArea() < dd.overlap.getArea()) {
21518 * Refreshes the cache of the top-left and bottom-right points of the
21519 * drag and drop objects in the specified group(s). This is in the
21520 * format that is stored in the drag and drop instance, so typical
21523 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
21527 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
21529 * @TODO this really should be an indexed array. Alternatively this
21530 * method could accept both.
21531 * @method refreshCache
21532 * @param {Object} groups an associative array of groups to refresh
21535 refreshCache: function(groups) {
21536 for (var sGroup in groups) {
21537 if ("string" != typeof sGroup) {
21540 for (var i in this.ids[sGroup]) {
21541 var oDD = this.ids[sGroup][i];
21543 if (this.isTypeOfDD(oDD)) {
21544 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
21545 var loc = this.getLocation(oDD);
21547 this.locationCache[oDD.id] = loc;
21549 delete this.locationCache[oDD.id];
21550 // this will unregister the drag and drop object if
21551 // the element is not in a usable state
21560 * This checks to make sure an element exists and is in the DOM. The
21561 * main purpose is to handle cases where innerHTML is used to remove
21562 * drag and drop objects from the DOM. IE provides an 'unspecified
21563 * error' when trying to access the offsetParent of such an element
21565 * @param {HTMLElement} el the element to check
21566 * @return {boolean} true if the element looks usable
21569 verifyEl: function(el) {
21574 parent = el.offsetParent;
21577 parent = el.offsetParent;
21588 * Returns a Region object containing the drag and drop element's position
21589 * and size, including the padding configured for it
21590 * @method getLocation
21591 * @param {DragDrop} oDD the drag and drop object to get the
21593 * @return {Roo.lib.Region} a Region object representing the total area
21594 * the element occupies, including any padding
21595 * the instance is configured for.
21598 getLocation: function(oDD) {
21599 if (! this.isTypeOfDD(oDD)) {
21603 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
21606 pos= Roo.lib.Dom.getXY(el);
21614 x2 = x1 + el.offsetWidth;
21616 y2 = y1 + el.offsetHeight;
21618 t = y1 - oDD.padding[0];
21619 r = x2 + oDD.padding[1];
21620 b = y2 + oDD.padding[2];
21621 l = x1 - oDD.padding[3];
21623 return new Roo.lib.Region( t, r, b, l );
21627 * Checks the cursor location to see if it over the target
21628 * @method isOverTarget
21629 * @param {Roo.lib.Point} pt The point to evaluate
21630 * @param {DragDrop} oTarget the DragDrop object we are inspecting
21631 * @return {boolean} true if the mouse is over the target
21635 isOverTarget: function(pt, oTarget, intersect) {
21636 // use cache if available
21637 var loc = this.locationCache[oTarget.id];
21638 if (!loc || !this.useCache) {
21639 loc = this.getLocation(oTarget);
21640 this.locationCache[oTarget.id] = loc;
21648 oTarget.cursorIsOver = loc.contains( pt );
21650 // DragDrop is using this as a sanity check for the initial mousedown
21651 // in this case we are done. In POINT mode, if the drag obj has no
21652 // contraints, we are also done. Otherwise we need to evaluate the
21653 // location of the target as related to the actual location of the
21654 // dragged element.
21655 var dc = this.dragCurrent;
21656 if (!dc || !dc.getTargetCoord ||
21657 (!intersect && !dc.constrainX && !dc.constrainY)) {
21658 return oTarget.cursorIsOver;
21661 oTarget.overlap = null;
21663 // Get the current location of the drag element, this is the
21664 // location of the mouse event less the delta that represents
21665 // where the original mousedown happened on the element. We
21666 // need to consider constraints and ticks as well.
21667 var pos = dc.getTargetCoord(pt.x, pt.y);
21669 var el = dc.getDragEl();
21670 var curRegion = new Roo.lib.Region( pos.y,
21671 pos.x + el.offsetWidth,
21672 pos.y + el.offsetHeight,
21675 var overlap = curRegion.intersect(loc);
21678 oTarget.overlap = overlap;
21679 return (intersect) ? true : oTarget.cursorIsOver;
21686 * unload event handler
21687 * @method _onUnload
21691 _onUnload: function(e, me) {
21692 Roo.dd.DragDropMgr.unregAll();
21696 * Cleans up the drag and drop events and objects.
21701 unregAll: function() {
21703 if (this.dragCurrent) {
21705 this.dragCurrent = null;
21708 this._execOnAll("unreg", []);
21710 for (i in this.elementCache) {
21711 delete this.elementCache[i];
21714 this.elementCache = {};
21719 * A cache of DOM elements
21720 * @property elementCache
21727 * Get the wrapper for the DOM element specified
21728 * @method getElWrapper
21729 * @param {String} id the id of the element to get
21730 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
21732 * @deprecated This wrapper isn't that useful
21735 getElWrapper: function(id) {
21736 var oWrapper = this.elementCache[id];
21737 if (!oWrapper || !oWrapper.el) {
21738 oWrapper = this.elementCache[id] =
21739 new this.ElementWrapper(Roo.getDom(id));
21745 * Returns the actual DOM element
21746 * @method getElement
21747 * @param {String} id the id of the elment to get
21748 * @return {Object} The element
21749 * @deprecated use Roo.getDom instead
21752 getElement: function(id) {
21753 return Roo.getDom(id);
21757 * Returns the style property for the DOM element (i.e.,
21758 * document.getElById(id).style)
21760 * @param {String} id the id of the elment to get
21761 * @return {Object} The style property of the element
21762 * @deprecated use Roo.getDom instead
21765 getCss: function(id) {
21766 var el = Roo.getDom(id);
21767 return (el) ? el.style : null;
21771 * Inner class for cached elements
21772 * @class DragDropMgr.ElementWrapper
21777 ElementWrapper: function(el) {
21782 this.el = el || null;
21787 this.id = this.el && el.id;
21789 * A reference to the style property
21792 this.css = this.el && el.style;
21796 * Returns the X position of an html element
21798 * @param el the element for which to get the position
21799 * @return {int} the X coordinate
21801 * @deprecated use Roo.lib.Dom.getX instead
21804 getPosX: function(el) {
21805 return Roo.lib.Dom.getX(el);
21809 * Returns the Y position of an html element
21811 * @param el the element for which to get the position
21812 * @return {int} the Y coordinate
21813 * @deprecated use Roo.lib.Dom.getY instead
21816 getPosY: function(el) {
21817 return Roo.lib.Dom.getY(el);
21821 * Swap two nodes. In IE, we use the native method, for others we
21822 * emulate the IE behavior
21824 * @param n1 the first node to swap
21825 * @param n2 the other node to swap
21828 swapNode: function(n1, n2) {
21832 var p = n2.parentNode;
21833 var s = n2.nextSibling;
21836 p.insertBefore(n1, n2);
21837 } else if (n2 == n1.nextSibling) {
21838 p.insertBefore(n2, n1);
21840 n1.parentNode.replaceChild(n2, n1);
21841 p.insertBefore(n1, s);
21847 * Returns the current scroll position
21848 * @method getScroll
21852 getScroll: function () {
21853 var t, l, dde=document.documentElement, db=document.body;
21854 if (dde && (dde.scrollTop || dde.scrollLeft)) {
21856 l = dde.scrollLeft;
21863 return { top: t, left: l };
21867 * Returns the specified element style property
21869 * @param {HTMLElement} el the element
21870 * @param {string} styleProp the style property
21871 * @return {string} The value of the style property
21872 * @deprecated use Roo.lib.Dom.getStyle
21875 getStyle: function(el, styleProp) {
21876 return Roo.fly(el).getStyle(styleProp);
21880 * Gets the scrollTop
21881 * @method getScrollTop
21882 * @return {int} the document's scrollTop
21885 getScrollTop: function () { return this.getScroll().top; },
21888 * Gets the scrollLeft
21889 * @method getScrollLeft
21890 * @return {int} the document's scrollTop
21893 getScrollLeft: function () { return this.getScroll().left; },
21896 * Sets the x/y position of an element to the location of the
21899 * @param {HTMLElement} moveEl The element to move
21900 * @param {HTMLElement} targetEl The position reference element
21903 moveToEl: function (moveEl, targetEl) {
21904 var aCoord = Roo.lib.Dom.getXY(targetEl);
21905 Roo.lib.Dom.setXY(moveEl, aCoord);
21909 * Numeric array sort function
21910 * @method numericSort
21913 numericSort: function(a, b) { return (a - b); },
21917 * @property _timeoutCount
21924 * Trying to make the load order less important. Without this we get
21925 * an error if this file is loaded before the Event Utility.
21926 * @method _addListeners
21930 _addListeners: function() {
21931 var DDM = Roo.dd.DDM;
21932 if ( Roo.lib.Event && document ) {
21935 if (DDM._timeoutCount > 2000) {
21937 setTimeout(DDM._addListeners, 10);
21938 if (document && document.body) {
21939 DDM._timeoutCount += 1;
21946 * Recursively searches the immediate parent and all child nodes for
21947 * the handle element in order to determine wheter or not it was
21949 * @method handleWasClicked
21950 * @param node the html element to inspect
21953 handleWasClicked: function(node, id) {
21954 if (this.isHandle(id, node.id)) {
21957 // check to see if this is a text node child of the one we want
21958 var p = node.parentNode;
21961 if (this.isHandle(id, p.id)) {
21976 // shorter alias, save a few bytes
21977 Roo.dd.DDM = Roo.dd.DragDropMgr;
21978 Roo.dd.DDM._addListeners();
21982 * Ext JS Library 1.1.1
21983 * Copyright(c) 2006-2007, Ext JS, LLC.
21985 * Originally Released Under LGPL - original licence link has changed is not relivant.
21988 * <script type="text/javascript">
21993 * A DragDrop implementation where the linked element follows the
21994 * mouse cursor during a drag.
21995 * @extends Roo.dd.DragDrop
21997 * @param {String} id the id of the linked element
21998 * @param {String} sGroup the group of related DragDrop items
21999 * @param {object} config an object containing configurable attributes
22000 * Valid properties for DD:
22003 Roo.dd.DD = function(id, sGroup, config) {
22005 this.init(id, sGroup, config);
22009 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
22012 * When set to true, the utility automatically tries to scroll the browser
22013 * window wehn a drag and drop element is dragged near the viewport boundary.
22014 * Defaults to true.
22021 * Sets the pointer offset to the distance between the linked element's top
22022 * left corner and the location the element was clicked
22023 * @method autoOffset
22024 * @param {int} iPageX the X coordinate of the click
22025 * @param {int} iPageY the Y coordinate of the click
22027 autoOffset: function(iPageX, iPageY) {
22028 var x = iPageX - this.startPageX;
22029 var y = iPageY - this.startPageY;
22030 this.setDelta(x, y);
22034 * Sets the pointer offset. You can call this directly to force the
22035 * offset to be in a particular location (e.g., pass in 0,0 to set it
22036 * to the center of the object)
22038 * @param {int} iDeltaX the distance from the left
22039 * @param {int} iDeltaY the distance from the top
22041 setDelta: function(iDeltaX, iDeltaY) {
22042 this.deltaX = iDeltaX;
22043 this.deltaY = iDeltaY;
22047 * Sets the drag element to the location of the mousedown or click event,
22048 * maintaining the cursor location relative to the location on the element
22049 * that was clicked. Override this if you want to place the element in a
22050 * location other than where the cursor is.
22051 * @method setDragElPos
22052 * @param {int} iPageX the X coordinate of the mousedown or drag event
22053 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22055 setDragElPos: function(iPageX, iPageY) {
22056 // the first time we do this, we are going to check to make sure
22057 // the element has css positioning
22059 var el = this.getDragEl();
22060 this.alignElWithMouse(el, iPageX, iPageY);
22064 * Sets the element to the location of the mousedown or click event,
22065 * maintaining the cursor location relative to the location on the element
22066 * that was clicked. Override this if you want to place the element in a
22067 * location other than where the cursor is.
22068 * @method alignElWithMouse
22069 * @param {HTMLElement} el the element to move
22070 * @param {int} iPageX the X coordinate of the mousedown or drag event
22071 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22073 alignElWithMouse: function(el, iPageX, iPageY) {
22074 var oCoord = this.getTargetCoord(iPageX, iPageY);
22075 var fly = el.dom ? el : Roo.fly(el);
22076 if (!this.deltaSetXY) {
22077 var aCoord = [oCoord.x, oCoord.y];
22079 var newLeft = fly.getLeft(true);
22080 var newTop = fly.getTop(true);
22081 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
22083 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
22086 this.cachePosition(oCoord.x, oCoord.y);
22087 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
22092 * Saves the most recent position so that we can reset the constraints and
22093 * tick marks on-demand. We need to know this so that we can calculate the
22094 * number of pixels the element is offset from its original position.
22095 * @method cachePosition
22096 * @param iPageX the current x position (optional, this just makes it so we
22097 * don't have to look it up again)
22098 * @param iPageY the current y position (optional, this just makes it so we
22099 * don't have to look it up again)
22101 cachePosition: function(iPageX, iPageY) {
22103 this.lastPageX = iPageX;
22104 this.lastPageY = iPageY;
22106 var aCoord = Roo.lib.Dom.getXY(this.getEl());
22107 this.lastPageX = aCoord[0];
22108 this.lastPageY = aCoord[1];
22113 * Auto-scroll the window if the dragged object has been moved beyond the
22114 * visible window boundary.
22115 * @method autoScroll
22116 * @param {int} x the drag element's x position
22117 * @param {int} y the drag element's y position
22118 * @param {int} h the height of the drag element
22119 * @param {int} w the width of the drag element
22122 autoScroll: function(x, y, h, w) {
22125 // The client height
22126 var clientH = Roo.lib.Dom.getViewWidth();
22128 // The client width
22129 var clientW = Roo.lib.Dom.getViewHeight();
22131 // The amt scrolled down
22132 var st = this.DDM.getScrollTop();
22134 // The amt scrolled right
22135 var sl = this.DDM.getScrollLeft();
22137 // Location of the bottom of the element
22140 // Location of the right of the element
22143 // The distance from the cursor to the bottom of the visible area,
22144 // adjusted so that we don't scroll if the cursor is beyond the
22145 // element drag constraints
22146 var toBot = (clientH + st - y - this.deltaY);
22148 // The distance from the cursor to the right of the visible area
22149 var toRight = (clientW + sl - x - this.deltaX);
22152 // How close to the edge the cursor must be before we scroll
22153 // var thresh = (document.all) ? 100 : 40;
22156 // How many pixels to scroll per autoscroll op. This helps to reduce
22157 // clunky scrolling. IE is more sensitive about this ... it needs this
22158 // value to be higher.
22159 var scrAmt = (document.all) ? 80 : 30;
22161 // Scroll down if we are near the bottom of the visible page and the
22162 // obj extends below the crease
22163 if ( bot > clientH && toBot < thresh ) {
22164 window.scrollTo(sl, st + scrAmt);
22167 // Scroll up if the window is scrolled down and the top of the object
22168 // goes above the top border
22169 if ( y < st && st > 0 && y - st < thresh ) {
22170 window.scrollTo(sl, st - scrAmt);
22173 // Scroll right if the obj is beyond the right border and the cursor is
22174 // near the border.
22175 if ( right > clientW && toRight < thresh ) {
22176 window.scrollTo(sl + scrAmt, st);
22179 // Scroll left if the window has been scrolled to the right and the obj
22180 // extends past the left border
22181 if ( x < sl && sl > 0 && x - sl < thresh ) {
22182 window.scrollTo(sl - scrAmt, st);
22188 * Finds the location the element should be placed if we want to move
22189 * it to where the mouse location less the click offset would place us.
22190 * @method getTargetCoord
22191 * @param {int} iPageX the X coordinate of the click
22192 * @param {int} iPageY the Y coordinate of the click
22193 * @return an object that contains the coordinates (Object.x and Object.y)
22196 getTargetCoord: function(iPageX, iPageY) {
22199 var x = iPageX - this.deltaX;
22200 var y = iPageY - this.deltaY;
22202 if (this.constrainX) {
22203 if (x < this.minX) { x = this.minX; }
22204 if (x > this.maxX) { x = this.maxX; }
22207 if (this.constrainY) {
22208 if (y < this.minY) { y = this.minY; }
22209 if (y > this.maxY) { y = this.maxY; }
22212 x = this.getTick(x, this.xTicks);
22213 y = this.getTick(y, this.yTicks);
22220 * Sets up config options specific to this class. Overrides
22221 * Roo.dd.DragDrop, but all versions of this method through the
22222 * inheritance chain are called
22224 applyConfig: function() {
22225 Roo.dd.DD.superclass.applyConfig.call(this);
22226 this.scroll = (this.config.scroll !== false);
22230 * Event that fires prior to the onMouseDown event. Overrides
22233 b4MouseDown: function(e) {
22234 // this.resetConstraints();
22235 this.autoOffset(e.getPageX(),
22240 * Event that fires prior to the onDrag event. Overrides
22243 b4Drag: function(e) {
22244 this.setDragElPos(e.getPageX(),
22248 toString: function() {
22249 return ("DD " + this.id);
22252 //////////////////////////////////////////////////////////////////////////
22253 // Debugging ygDragDrop events that can be overridden
22254 //////////////////////////////////////////////////////////////////////////
22256 startDrag: function(x, y) {
22259 onDrag: function(e) {
22262 onDragEnter: function(e, id) {
22265 onDragOver: function(e, id) {
22268 onDragOut: function(e, id) {
22271 onDragDrop: function(e, id) {
22274 endDrag: function(e) {
22281 * Ext JS Library 1.1.1
22282 * Copyright(c) 2006-2007, Ext JS, LLC.
22284 * Originally Released Under LGPL - original licence link has changed is not relivant.
22287 * <script type="text/javascript">
22291 * @class Roo.dd.DDProxy
22292 * A DragDrop implementation that inserts an empty, bordered div into
22293 * the document that follows the cursor during drag operations. At the time of
22294 * the click, the frame div is resized to the dimensions of the linked html
22295 * element, and moved to the exact location of the linked element.
22297 * References to the "frame" element refer to the single proxy element that
22298 * was created to be dragged in place of all DDProxy elements on the
22301 * @extends Roo.dd.DD
22303 * @param {String} id the id of the linked html element
22304 * @param {String} sGroup the group of related DragDrop objects
22305 * @param {object} config an object containing configurable attributes
22306 * Valid properties for DDProxy in addition to those in DragDrop:
22307 * resizeFrame, centerFrame, dragElId
22309 Roo.dd.DDProxy = function(id, sGroup, config) {
22311 this.init(id, sGroup, config);
22317 * The default drag frame div id
22318 * @property Roo.dd.DDProxy.dragElId
22322 Roo.dd.DDProxy.dragElId = "ygddfdiv";
22324 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
22327 * By default we resize the drag frame to be the same size as the element
22328 * we want to drag (this is to get the frame effect). We can turn it off
22329 * if we want a different behavior.
22330 * @property resizeFrame
22336 * By default the frame is positioned exactly where the drag element is, so
22337 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
22338 * you do not have constraints on the obj is to have the drag frame centered
22339 * around the cursor. Set centerFrame to true for this effect.
22340 * @property centerFrame
22343 centerFrame: false,
22346 * Creates the proxy element if it does not yet exist
22347 * @method createFrame
22349 createFrame: function() {
22351 var body = document.body;
22353 if (!body || !body.firstChild) {
22354 setTimeout( function() { self.createFrame(); }, 50 );
22358 var div = this.getDragEl();
22361 div = document.createElement("div");
22362 div.id = this.dragElId;
22365 s.position = "absolute";
22366 s.visibility = "hidden";
22368 s.border = "2px solid #aaa";
22371 // appendChild can blow up IE if invoked prior to the window load event
22372 // while rendering a table. It is possible there are other scenarios
22373 // that would cause this to happen as well.
22374 body.insertBefore(div, body.firstChild);
22379 * Initialization for the drag frame element. Must be called in the
22380 * constructor of all subclasses
22381 * @method initFrame
22383 initFrame: function() {
22384 this.createFrame();
22387 applyConfig: function() {
22388 Roo.dd.DDProxy.superclass.applyConfig.call(this);
22390 this.resizeFrame = (this.config.resizeFrame !== false);
22391 this.centerFrame = (this.config.centerFrame);
22392 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
22396 * Resizes the drag frame to the dimensions of the clicked object, positions
22397 * it over the object, and finally displays it
22398 * @method showFrame
22399 * @param {int} iPageX X click position
22400 * @param {int} iPageY Y click position
22403 showFrame: function(iPageX, iPageY) {
22404 var el = this.getEl();
22405 var dragEl = this.getDragEl();
22406 var s = dragEl.style;
22408 this._resizeProxy();
22410 if (this.centerFrame) {
22411 this.setDelta( Math.round(parseInt(s.width, 10)/2),
22412 Math.round(parseInt(s.height, 10)/2) );
22415 this.setDragElPos(iPageX, iPageY);
22417 Roo.fly(dragEl).show();
22421 * The proxy is automatically resized to the dimensions of the linked
22422 * element when a drag is initiated, unless resizeFrame is set to false
22423 * @method _resizeProxy
22426 _resizeProxy: function() {
22427 if (this.resizeFrame) {
22428 var el = this.getEl();
22429 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
22433 // overrides Roo.dd.DragDrop
22434 b4MouseDown: function(e) {
22435 var x = e.getPageX();
22436 var y = e.getPageY();
22437 this.autoOffset(x, y);
22438 this.setDragElPos(x, y);
22441 // overrides Roo.dd.DragDrop
22442 b4StartDrag: function(x, y) {
22443 // show the drag frame
22444 this.showFrame(x, y);
22447 // overrides Roo.dd.DragDrop
22448 b4EndDrag: function(e) {
22449 Roo.fly(this.getDragEl()).hide();
22452 // overrides Roo.dd.DragDrop
22453 // By default we try to move the element to the last location of the frame.
22454 // This is so that the default behavior mirrors that of Roo.dd.DD.
22455 endDrag: function(e) {
22457 var lel = this.getEl();
22458 var del = this.getDragEl();
22460 // Show the drag frame briefly so we can get its position
22461 del.style.visibility = "";
22464 // Hide the linked element before the move to get around a Safari
22466 lel.style.visibility = "hidden";
22467 Roo.dd.DDM.moveToEl(lel, del);
22468 del.style.visibility = "hidden";
22469 lel.style.visibility = "";
22474 beforeMove : function(){
22478 afterDrag : function(){
22482 toString: function() {
22483 return ("DDProxy " + this.id);
22489 * Ext JS Library 1.1.1
22490 * Copyright(c) 2006-2007, Ext JS, LLC.
22492 * Originally Released Under LGPL - original licence link has changed is not relivant.
22495 * <script type="text/javascript">
22499 * @class Roo.dd.DDTarget
22500 * A DragDrop implementation that does not move, but can be a drop
22501 * target. You would get the same result by simply omitting implementation
22502 * for the event callbacks, but this way we reduce the processing cost of the
22503 * event listener and the callbacks.
22504 * @extends Roo.dd.DragDrop
22506 * @param {String} id the id of the element that is a drop target
22507 * @param {String} sGroup the group of related DragDrop objects
22508 * @param {object} config an object containing configurable attributes
22509 * Valid properties for DDTarget in addition to those in
22513 Roo.dd.DDTarget = function(id, sGroup, config) {
22515 this.initTarget(id, sGroup, config);
22517 if (config && (config.listeners || config.events)) {
22518 Roo.dd.DragDrop.superclass.constructor.call(this, {
22519 listeners : config.listeners || {},
22520 events : config.events || {}
22525 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
22526 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
22527 toString: function() {
22528 return ("DDTarget " + this.id);
22533 * Ext JS Library 1.1.1
22534 * Copyright(c) 2006-2007, Ext JS, LLC.
22536 * Originally Released Under LGPL - original licence link has changed is not relivant.
22539 * <script type="text/javascript">
22544 * @class Roo.dd.ScrollManager
22545 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
22546 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
22549 Roo.dd.ScrollManager = function(){
22550 var ddm = Roo.dd.DragDropMgr;
22557 var onStop = function(e){
22562 var triggerRefresh = function(){
22563 if(ddm.dragCurrent){
22564 ddm.refreshCache(ddm.dragCurrent.groups);
22568 var doScroll = function(){
22569 if(ddm.dragCurrent){
22570 var dds = Roo.dd.ScrollManager;
22572 if(proc.el.scroll(proc.dir, dds.increment)){
22576 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
22581 var clearProc = function(){
22583 clearInterval(proc.id);
22590 var startProc = function(el, dir){
22591 Roo.log('scroll startproc');
22595 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
22598 var onFire = function(e, isDrop){
22600 if(isDrop || !ddm.dragCurrent){ return; }
22601 var dds = Roo.dd.ScrollManager;
22602 if(!dragEl || dragEl != ddm.dragCurrent){
22603 dragEl = ddm.dragCurrent;
22604 // refresh regions on drag start
22605 dds.refreshCache();
22608 var xy = Roo.lib.Event.getXY(e);
22609 var pt = new Roo.lib.Point(xy[0], xy[1]);
22610 for(var id in els){
22611 var el = els[id], r = el._region;
22612 if(r && r.contains(pt) && el.isScrollable()){
22613 if(r.bottom - pt.y <= dds.thresh){
22615 startProc(el, "down");
22618 }else if(r.right - pt.x <= dds.thresh){
22620 startProc(el, "left");
22623 }else if(pt.y - r.top <= dds.thresh){
22625 startProc(el, "up");
22628 }else if(pt.x - r.left <= dds.thresh){
22630 startProc(el, "right");
22639 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
22640 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
22644 * Registers new overflow element(s) to auto scroll
22645 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
22647 register : function(el){
22648 if(el instanceof Array){
22649 for(var i = 0, len = el.length; i < len; i++) {
22650 this.register(el[i]);
22656 Roo.dd.ScrollManager.els = els;
22660 * Unregisters overflow element(s) so they are no longer scrolled
22661 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
22663 unregister : function(el){
22664 if(el instanceof Array){
22665 for(var i = 0, len = el.length; i < len; i++) {
22666 this.unregister(el[i]);
22675 * The number of pixels from the edge of a container the pointer needs to be to
22676 * trigger scrolling (defaults to 25)
22682 * The number of pixels to scroll in each scroll increment (defaults to 50)
22688 * The frequency of scrolls in milliseconds (defaults to 500)
22694 * True to animate the scroll (defaults to true)
22700 * The animation duration in seconds -
22701 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
22707 * Manually trigger a cache refresh.
22709 refreshCache : function(){
22710 for(var id in els){
22711 if(typeof els[id] == 'object'){ // for people extending the object prototype
22712 els[id]._region = els[id].getRegion();
22719 * Ext JS Library 1.1.1
22720 * Copyright(c) 2006-2007, Ext JS, LLC.
22722 * Originally Released Under LGPL - original licence link has changed is not relivant.
22725 * <script type="text/javascript">
22730 * @class Roo.dd.Registry
22731 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
22732 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
22735 Roo.dd.Registry = function(){
22738 var autoIdSeed = 0;
22740 var getId = function(el, autogen){
22741 if(typeof el == "string"){
22745 if(!id && autogen !== false){
22746 id = "roodd-" + (++autoIdSeed);
22754 * Register a drag drop element
22755 * @param {String|HTMLElement} element The id or DOM node to register
22756 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
22757 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
22758 * knows how to interpret, plus there are some specific properties known to the Registry that should be
22759 * populated in the data object (if applicable):
22761 Value Description<br />
22762 --------- ------------------------------------------<br />
22763 handles Array of DOM nodes that trigger dragging<br />
22764 for the element being registered<br />
22765 isHandle True if the element passed in triggers<br />
22766 dragging itself, else false
22769 register : function(el, data){
22771 if(typeof el == "string"){
22772 el = document.getElementById(el);
22775 elements[getId(el)] = data;
22776 if(data.isHandle !== false){
22777 handles[data.ddel.id] = data;
22780 var hs = data.handles;
22781 for(var i = 0, len = hs.length; i < len; i++){
22782 handles[getId(hs[i])] = data;
22788 * Unregister a drag drop element
22789 * @param {String|HTMLElement} element The id or DOM node to unregister
22791 unregister : function(el){
22792 var id = getId(el, false);
22793 var data = elements[id];
22795 delete elements[id];
22797 var hs = data.handles;
22798 for(var i = 0, len = hs.length; i < len; i++){
22799 delete handles[getId(hs[i], false)];
22806 * Returns the handle registered for a DOM Node by id
22807 * @param {String|HTMLElement} id The DOM node or id to look up
22808 * @return {Object} handle The custom handle data
22810 getHandle : function(id){
22811 if(typeof id != "string"){ // must be element?
22814 return handles[id];
22818 * Returns the handle that is registered for the DOM node that is the target of the event
22819 * @param {Event} e The event
22820 * @return {Object} handle The custom handle data
22822 getHandleFromEvent : function(e){
22823 var t = Roo.lib.Event.getTarget(e);
22824 return t ? handles[t.id] : null;
22828 * Returns a custom data object that is registered for a DOM node by id
22829 * @param {String|HTMLElement} id The DOM node or id to look up
22830 * @return {Object} data The custom data
22832 getTarget : function(id){
22833 if(typeof id != "string"){ // must be element?
22836 return elements[id];
22840 * Returns a custom data object that is registered for the DOM node that is the target of the event
22841 * @param {Event} e The event
22842 * @return {Object} data The custom data
22844 getTargetFromEvent : function(e){
22845 var t = Roo.lib.Event.getTarget(e);
22846 return t ? elements[t.id] || handles[t.id] : null;
22851 * Ext JS Library 1.1.1
22852 * Copyright(c) 2006-2007, Ext JS, LLC.
22854 * Originally Released Under LGPL - original licence link has changed is not relivant.
22857 * <script type="text/javascript">
22862 * @class Roo.dd.StatusProxy
22863 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
22864 * default drag proxy used by all Roo.dd components.
22866 * @param {Object} config
22868 Roo.dd.StatusProxy = function(config){
22869 Roo.apply(this, config);
22870 this.id = this.id || Roo.id();
22871 this.el = new Roo.Layer({
22873 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
22874 {tag: "div", cls: "x-dd-drop-icon"},
22875 {tag: "div", cls: "x-dd-drag-ghost"}
22878 shadow: !config || config.shadow !== false
22880 this.ghost = Roo.get(this.el.dom.childNodes[1]);
22881 this.dropStatus = this.dropNotAllowed;
22884 Roo.dd.StatusProxy.prototype = {
22886 * @cfg {String} dropAllowed
22887 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
22889 dropAllowed : "x-dd-drop-ok",
22891 * @cfg {String} dropNotAllowed
22892 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
22894 dropNotAllowed : "x-dd-drop-nodrop",
22897 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
22898 * over the current target element.
22899 * @param {String} cssClass The css class for the new drop status indicator image
22901 setStatus : function(cssClass){
22902 cssClass = cssClass || this.dropNotAllowed;
22903 if(this.dropStatus != cssClass){
22904 this.el.replaceClass(this.dropStatus, cssClass);
22905 this.dropStatus = cssClass;
22910 * Resets the status indicator to the default dropNotAllowed value
22911 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
22913 reset : function(clearGhost){
22914 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
22915 this.dropStatus = this.dropNotAllowed;
22917 this.ghost.update("");
22922 * Updates the contents of the ghost element
22923 * @param {String} html The html that will replace the current innerHTML of the ghost element
22925 update : function(html){
22926 if(typeof html == "string"){
22927 this.ghost.update(html);
22929 this.ghost.update("");
22930 html.style.margin = "0";
22931 this.ghost.dom.appendChild(html);
22933 // ensure float = none set?? cant remember why though.
22934 var el = this.ghost.dom.firstChild;
22936 Roo.fly(el).setStyle('float', 'none');
22941 * Returns the underlying proxy {@link Roo.Layer}
22942 * @return {Roo.Layer} el
22944 getEl : function(){
22949 * Returns the ghost element
22950 * @return {Roo.Element} el
22952 getGhost : function(){
22958 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
22960 hide : function(clear){
22968 * Stops the repair animation if it's currently running
22971 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
22977 * Displays this proxy
22984 * Force the Layer to sync its shadow and shim positions to the element
22991 * Causes the proxy to return to its position of origin via an animation. Should be called after an
22992 * invalid drop operation by the item being dragged.
22993 * @param {Array} xy The XY position of the element ([x, y])
22994 * @param {Function} callback The function to call after the repair is complete
22995 * @param {Object} scope The scope in which to execute the callback
22997 repair : function(xy, callback, scope){
22998 this.callback = callback;
22999 this.scope = scope;
23000 if(xy && this.animRepair !== false){
23001 this.el.addClass("x-dd-drag-repair");
23002 this.el.hideUnders(true);
23003 this.anim = this.el.shift({
23004 duration: this.repairDuration || .5,
23008 callback: this.afterRepair,
23012 this.afterRepair();
23017 afterRepair : function(){
23019 if(typeof this.callback == "function"){
23020 this.callback.call(this.scope || this);
23022 this.callback = null;
23027 * Ext JS Library 1.1.1
23028 * Copyright(c) 2006-2007, Ext JS, LLC.
23030 * Originally Released Under LGPL - original licence link has changed is not relivant.
23033 * <script type="text/javascript">
23037 * @class Roo.dd.DragSource
23038 * @extends Roo.dd.DDProxy
23039 * A simple class that provides the basic implementation needed to make any element draggable.
23041 * @param {String/HTMLElement/Element} el The container element
23042 * @param {Object} config
23044 Roo.dd.DragSource = function(el, config){
23045 this.el = Roo.get(el);
23046 this.dragData = {};
23048 Roo.apply(this, config);
23051 this.proxy = new Roo.dd.StatusProxy();
23054 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
23055 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
23057 this.dragging = false;
23060 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
23062 * @cfg {String} dropAllowed
23063 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23065 dropAllowed : "x-dd-drop-ok",
23067 * @cfg {String} dropNotAllowed
23068 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23070 dropNotAllowed : "x-dd-drop-nodrop",
23073 * Returns the data object associated with this drag source
23074 * @return {Object} data An object containing arbitrary data
23076 getDragData : function(e){
23077 return this.dragData;
23081 onDragEnter : function(e, id){
23082 var target = Roo.dd.DragDropMgr.getDDById(id);
23083 this.cachedTarget = target;
23084 if(this.beforeDragEnter(target, e, id) !== false){
23085 if(target.isNotifyTarget){
23086 var status = target.notifyEnter(this, e, this.dragData);
23087 this.proxy.setStatus(status);
23089 this.proxy.setStatus(this.dropAllowed);
23092 if(this.afterDragEnter){
23094 * An empty function by default, but provided so that you can perform a custom action
23095 * when the dragged item enters the drop target by providing an implementation.
23096 * @param {Roo.dd.DragDrop} target The drop target
23097 * @param {Event} e The event object
23098 * @param {String} id The id of the dragged element
23099 * @method afterDragEnter
23101 this.afterDragEnter(target, e, id);
23107 * An empty function by default, but provided so that you can perform a custom action
23108 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
23109 * @param {Roo.dd.DragDrop} target The drop target
23110 * @param {Event} e The event object
23111 * @param {String} id The id of the dragged element
23112 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23114 beforeDragEnter : function(target, e, id){
23119 alignElWithMouse: function() {
23120 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
23125 onDragOver : function(e, id){
23126 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23127 if(this.beforeDragOver(target, e, id) !== false){
23128 if(target.isNotifyTarget){
23129 var status = target.notifyOver(this, e, this.dragData);
23130 this.proxy.setStatus(status);
23133 if(this.afterDragOver){
23135 * An empty function by default, but provided so that you can perform a custom action
23136 * while the dragged item is over the drop target by providing an implementation.
23137 * @param {Roo.dd.DragDrop} target The drop target
23138 * @param {Event} e The event object
23139 * @param {String} id The id of the dragged element
23140 * @method afterDragOver
23142 this.afterDragOver(target, e, id);
23148 * An empty function by default, but provided so that you can perform a custom action
23149 * while the dragged item is over the drop target and optionally cancel the onDragOver.
23150 * @param {Roo.dd.DragDrop} target The drop target
23151 * @param {Event} e The event object
23152 * @param {String} id The id of the dragged element
23153 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23155 beforeDragOver : function(target, e, id){
23160 onDragOut : function(e, id){
23161 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23162 if(this.beforeDragOut(target, e, id) !== false){
23163 if(target.isNotifyTarget){
23164 target.notifyOut(this, e, this.dragData);
23166 this.proxy.reset();
23167 if(this.afterDragOut){
23169 * An empty function by default, but provided so that you can perform a custom action
23170 * after the dragged item is dragged out of the target without dropping.
23171 * @param {Roo.dd.DragDrop} target The drop target
23172 * @param {Event} e The event object
23173 * @param {String} id The id of the dragged element
23174 * @method afterDragOut
23176 this.afterDragOut(target, e, id);
23179 this.cachedTarget = null;
23183 * An empty function by default, but provided so that you can perform a custom action before the dragged
23184 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
23185 * @param {Roo.dd.DragDrop} target The drop target
23186 * @param {Event} e The event object
23187 * @param {String} id The id of the dragged element
23188 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23190 beforeDragOut : function(target, e, id){
23195 onDragDrop : function(e, id){
23196 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23197 if(this.beforeDragDrop(target, e, id) !== false){
23198 if(target.isNotifyTarget){
23199 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
23200 this.onValidDrop(target, e, id);
23202 this.onInvalidDrop(target, e, id);
23205 this.onValidDrop(target, e, id);
23208 if(this.afterDragDrop){
23210 * An empty function by default, but provided so that you can perform a custom action
23211 * after a valid drag drop has occurred by providing an implementation.
23212 * @param {Roo.dd.DragDrop} target The drop target
23213 * @param {Event} e The event object
23214 * @param {String} id The id of the dropped element
23215 * @method afterDragDrop
23217 this.afterDragDrop(target, e, id);
23220 delete this.cachedTarget;
23224 * An empty function by default, but provided so that you can perform a custom action before the dragged
23225 * item is dropped onto the target and optionally cancel the onDragDrop.
23226 * @param {Roo.dd.DragDrop} target The drop target
23227 * @param {Event} e The event object
23228 * @param {String} id The id of the dragged element
23229 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
23231 beforeDragDrop : function(target, e, id){
23236 onValidDrop : function(target, e, id){
23238 if(this.afterValidDrop){
23240 * An empty function by default, but provided so that you can perform a custom action
23241 * after a valid drop has occurred by providing an implementation.
23242 * @param {Object} target The target DD
23243 * @param {Event} e The event object
23244 * @param {String} id The id of the dropped element
23245 * @method afterInvalidDrop
23247 this.afterValidDrop(target, e, id);
23252 getRepairXY : function(e, data){
23253 return this.el.getXY();
23257 onInvalidDrop : function(target, e, id){
23258 this.beforeInvalidDrop(target, e, id);
23259 if(this.cachedTarget){
23260 if(this.cachedTarget.isNotifyTarget){
23261 this.cachedTarget.notifyOut(this, e, this.dragData);
23263 this.cacheTarget = null;
23265 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
23267 if(this.afterInvalidDrop){
23269 * An empty function by default, but provided so that you can perform a custom action
23270 * after an invalid drop has occurred by providing an implementation.
23271 * @param {Event} e The event object
23272 * @param {String} id The id of the dropped element
23273 * @method afterInvalidDrop
23275 this.afterInvalidDrop(e, id);
23280 afterRepair : function(){
23282 this.el.highlight(this.hlColor || "c3daf9");
23284 this.dragging = false;
23288 * An empty function by default, but provided so that you can perform a custom action after an invalid
23289 * drop has occurred.
23290 * @param {Roo.dd.DragDrop} target The drop target
23291 * @param {Event} e The event object
23292 * @param {String} id The id of the dragged element
23293 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
23295 beforeInvalidDrop : function(target, e, id){
23300 handleMouseDown : function(e){
23301 if(this.dragging) {
23304 var data = this.getDragData(e);
23305 if(data && this.onBeforeDrag(data, e) !== false){
23306 this.dragData = data;
23308 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
23313 * An empty function by default, but provided so that you can perform a custom action before the initial
23314 * drag event begins and optionally cancel it.
23315 * @param {Object} data An object containing arbitrary data to be shared with drop targets
23316 * @param {Event} e The event object
23317 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23319 onBeforeDrag : function(data, e){
23324 * An empty function by default, but provided so that you can perform a custom action once the initial
23325 * drag event has begun. The drag cannot be canceled from this function.
23326 * @param {Number} x The x position of the click on the dragged object
23327 * @param {Number} y The y position of the click on the dragged object
23329 onStartDrag : Roo.emptyFn,
23331 // private - YUI override
23332 startDrag : function(x, y){
23333 this.proxy.reset();
23334 this.dragging = true;
23335 this.proxy.update("");
23336 this.onInitDrag(x, y);
23341 onInitDrag : function(x, y){
23342 var clone = this.el.dom.cloneNode(true);
23343 clone.id = Roo.id(); // prevent duplicate ids
23344 this.proxy.update(clone);
23345 this.onStartDrag(x, y);
23350 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
23351 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
23353 getProxy : function(){
23358 * Hides the drag source's {@link Roo.dd.StatusProxy}
23360 hideProxy : function(){
23362 this.proxy.reset(true);
23363 this.dragging = false;
23367 triggerCacheRefresh : function(){
23368 Roo.dd.DDM.refreshCache(this.groups);
23371 // private - override to prevent hiding
23372 b4EndDrag: function(e) {
23375 // private - override to prevent moving
23376 endDrag : function(e){
23377 this.onEndDrag(this.dragData, e);
23381 onEndDrag : function(data, e){
23384 // private - pin to cursor
23385 autoOffset : function(x, y) {
23386 this.setDelta(-12, -20);
23390 * Ext JS Library 1.1.1
23391 * Copyright(c) 2006-2007, Ext JS, LLC.
23393 * Originally Released Under LGPL - original licence link has changed is not relivant.
23396 * <script type="text/javascript">
23401 * @class Roo.dd.DropTarget
23402 * @extends Roo.dd.DDTarget
23403 * A simple class that provides the basic implementation needed to make any element a drop target that can have
23404 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
23406 * @param {String/HTMLElement/Element} el The container element
23407 * @param {Object} config
23409 Roo.dd.DropTarget = function(el, config){
23410 this.el = Roo.get(el);
23412 var listeners = false; ;
23413 if (config && config.listeners) {
23414 listeners= config.listeners;
23415 delete config.listeners;
23417 Roo.apply(this, config);
23419 if(this.containerScroll){
23420 Roo.dd.ScrollManager.register(this.el);
23424 * @scope Roo.dd.DropTarget
23429 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
23430 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
23431 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
23433 * IMPORTANT : it should set this.valid to true|false
23435 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23436 * @param {Event} e The event
23437 * @param {Object} data An object containing arbitrary data supplied by the drag source
23443 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
23444 * This method will be called on every mouse movement while the drag source is over the drop target.
23445 * This default implementation simply returns the dropAllowed config value.
23447 * IMPORTANT : it should set this.valid to true|false
23449 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23450 * @param {Event} e The event
23451 * @param {Object} data An object containing arbitrary data supplied by the drag source
23457 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
23458 * out of the target without dropping. This default implementation simply removes the CSS class specified by
23459 * overClass (if any) from the drop element.
23462 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23463 * @param {Event} e The event
23464 * @param {Object} data An object containing arbitrary data supplied by the drag source
23470 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
23471 * been dropped on it. This method has no default implementation and returns false, so you must provide an
23472 * implementation that does something to process the drop event and returns true so that the drag source's
23473 * repair action does not run.
23475 * IMPORTANT : it should set this.success
23477 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23478 * @param {Event} e The event
23479 * @param {Object} data An object containing arbitrary data supplied by the drag source
23485 Roo.dd.DropTarget.superclass.constructor.call( this,
23487 this.ddGroup || this.group,
23490 listeners : listeners || {}
23498 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
23500 * @cfg {String} overClass
23501 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
23504 * @cfg {String} ddGroup
23505 * The drag drop group to handle drop events for
23509 * @cfg {String} dropAllowed
23510 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23512 dropAllowed : "x-dd-drop-ok",
23514 * @cfg {String} dropNotAllowed
23515 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23517 dropNotAllowed : "x-dd-drop-nodrop",
23519 * @cfg {boolean} success
23520 * set this after drop listener..
23524 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
23525 * if the drop point is valid for over/enter..
23532 isNotifyTarget : true,
23537 notifyEnter : function(dd, e, data)
23540 this.fireEvent('enter', dd, e, data);
23541 if(this.overClass){
23542 this.el.addClass(this.overClass);
23544 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23545 this.valid ? this.dropAllowed : this.dropNotAllowed
23552 notifyOver : function(dd, e, data)
23555 this.fireEvent('over', dd, e, data);
23556 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23557 this.valid ? this.dropAllowed : this.dropNotAllowed
23564 notifyOut : function(dd, e, data)
23566 this.fireEvent('out', dd, e, data);
23567 if(this.overClass){
23568 this.el.removeClass(this.overClass);
23575 notifyDrop : function(dd, e, data)
23577 this.success = false;
23578 this.fireEvent('drop', dd, e, data);
23579 return this.success;
23583 * Ext JS Library 1.1.1
23584 * Copyright(c) 2006-2007, Ext JS, LLC.
23586 * Originally Released Under LGPL - original licence link has changed is not relivant.
23589 * <script type="text/javascript">
23594 * @class Roo.dd.DragZone
23595 * @extends Roo.dd.DragSource
23596 * This class provides a container DD instance that proxies for multiple child node sources.<br />
23597 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
23599 * @param {String/HTMLElement/Element} el The container element
23600 * @param {Object} config
23602 Roo.dd.DragZone = function(el, config){
23603 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
23604 if(this.containerScroll){
23605 Roo.dd.ScrollManager.register(this.el);
23609 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
23611 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
23612 * for auto scrolling during drag operations.
23615 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
23616 * method after a failed drop (defaults to "c3daf9" - light blue)
23620 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
23621 * for a valid target to drag based on the mouse down. Override this method
23622 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
23623 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
23624 * @param {EventObject} e The mouse down event
23625 * @return {Object} The dragData
23627 getDragData : function(e){
23628 return Roo.dd.Registry.getHandleFromEvent(e);
23632 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
23633 * this.dragData.ddel
23634 * @param {Number} x The x position of the click on the dragged object
23635 * @param {Number} y The y position of the click on the dragged object
23636 * @return {Boolean} true to continue the drag, false to cancel
23638 onInitDrag : function(x, y){
23639 this.proxy.update(this.dragData.ddel.cloneNode(true));
23640 this.onStartDrag(x, y);
23645 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
23647 afterRepair : function(){
23649 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
23651 this.dragging = false;
23655 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
23656 * the XY of this.dragData.ddel
23657 * @param {EventObject} e The mouse up event
23658 * @return {Array} The xy location (e.g. [100, 200])
23660 getRepairXY : function(e){
23661 return Roo.Element.fly(this.dragData.ddel).getXY();
23665 * Ext JS Library 1.1.1
23666 * Copyright(c) 2006-2007, Ext JS, LLC.
23668 * Originally Released Under LGPL - original licence link has changed is not relivant.
23671 * <script type="text/javascript">
23674 * @class Roo.dd.DropZone
23675 * @extends Roo.dd.DropTarget
23676 * This class provides a container DD instance that proxies for multiple child node targets.<br />
23677 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
23679 * @param {String/HTMLElement/Element} el The container element
23680 * @param {Object} config
23682 Roo.dd.DropZone = function(el, config){
23683 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
23686 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
23688 * Returns a custom data object associated with the DOM node that is the target of the event. By default
23689 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
23690 * provide your own custom lookup.
23691 * @param {Event} e The event
23692 * @return {Object} data The custom data
23694 getTargetFromEvent : function(e){
23695 return Roo.dd.Registry.getTargetFromEvent(e);
23699 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
23700 * that it has registered. This method has no default implementation and should be overridden to provide
23701 * node-specific processing if necessary.
23702 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23703 * {@link #getTargetFromEvent} for this node)
23704 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23705 * @param {Event} e The event
23706 * @param {Object} data An object containing arbitrary data supplied by the drag source
23708 onNodeEnter : function(n, dd, e, data){
23713 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
23714 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
23715 * overridden to provide the proper feedback.
23716 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23717 * {@link #getTargetFromEvent} for this node)
23718 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23719 * @param {Event} e The event
23720 * @param {Object} data An object containing arbitrary data supplied by the drag source
23721 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23722 * underlying {@link Roo.dd.StatusProxy} can be updated
23724 onNodeOver : function(n, dd, e, data){
23725 return this.dropAllowed;
23729 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
23730 * the drop node without dropping. This method has no default implementation and should be overridden to provide
23731 * node-specific processing if necessary.
23732 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23733 * {@link #getTargetFromEvent} for this node)
23734 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23735 * @param {Event} e The event
23736 * @param {Object} data An object containing arbitrary data supplied by the drag source
23738 onNodeOut : function(n, dd, e, data){
23743 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
23744 * the drop node. The default implementation returns false, so it should be overridden to provide the
23745 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
23746 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23747 * {@link #getTargetFromEvent} for this node)
23748 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23749 * @param {Event} e The event
23750 * @param {Object} data An object containing arbitrary data supplied by the drag source
23751 * @return {Boolean} True if the drop was valid, else false
23753 onNodeDrop : function(n, dd, e, data){
23758 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
23759 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
23760 * it should be overridden to provide the proper feedback if necessary.
23761 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23762 * @param {Event} e The event
23763 * @param {Object} data An object containing arbitrary data supplied by the drag source
23764 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23765 * underlying {@link Roo.dd.StatusProxy} can be updated
23767 onContainerOver : function(dd, e, data){
23768 return this.dropNotAllowed;
23772 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
23773 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
23774 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
23775 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
23776 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23777 * @param {Event} e The event
23778 * @param {Object} data An object containing arbitrary data supplied by the drag source
23779 * @return {Boolean} True if the drop was valid, else false
23781 onContainerDrop : function(dd, e, data){
23786 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
23787 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
23788 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
23789 * you should override this method and provide a custom implementation.
23790 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23791 * @param {Event} e The event
23792 * @param {Object} data An object containing arbitrary data supplied by the drag source
23793 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23794 * underlying {@link Roo.dd.StatusProxy} can be updated
23796 notifyEnter : function(dd, e, data){
23797 return this.dropNotAllowed;
23801 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
23802 * This method will be called on every mouse movement while the drag source is over the drop zone.
23803 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
23804 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
23805 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
23806 * registered node, it will call {@link #onContainerOver}.
23807 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23808 * @param {Event} e The event
23809 * @param {Object} data An object containing arbitrary data supplied by the drag source
23810 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23811 * underlying {@link Roo.dd.StatusProxy} can be updated
23813 notifyOver : function(dd, e, data){
23814 var n = this.getTargetFromEvent(e);
23815 if(!n){ // not over valid drop target
23816 if(this.lastOverNode){
23817 this.onNodeOut(this.lastOverNode, dd, e, data);
23818 this.lastOverNode = null;
23820 return this.onContainerOver(dd, e, data);
23822 if(this.lastOverNode != n){
23823 if(this.lastOverNode){
23824 this.onNodeOut(this.lastOverNode, dd, e, data);
23826 this.onNodeEnter(n, dd, e, data);
23827 this.lastOverNode = n;
23829 return this.onNodeOver(n, dd, e, data);
23833 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
23834 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
23835 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
23836 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23837 * @param {Event} e The event
23838 * @param {Object} data An object containing arbitrary data supplied by the drag zone
23840 notifyOut : function(dd, e, data){
23841 if(this.lastOverNode){
23842 this.onNodeOut(this.lastOverNode, dd, e, data);
23843 this.lastOverNode = null;
23848 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
23849 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
23850 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
23851 * otherwise it will call {@link #onContainerDrop}.
23852 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23853 * @param {Event} e The event
23854 * @param {Object} data An object containing arbitrary data supplied by the drag source
23855 * @return {Boolean} True if the drop was valid, else false
23857 notifyDrop : function(dd, e, data){
23858 if(this.lastOverNode){
23859 this.onNodeOut(this.lastOverNode, dd, e, data);
23860 this.lastOverNode = null;
23862 var n = this.getTargetFromEvent(e);
23864 this.onNodeDrop(n, dd, e, data) :
23865 this.onContainerDrop(dd, e, data);
23869 triggerCacheRefresh : function(){
23870 Roo.dd.DDM.refreshCache(this.groups);
23874 * Ext JS Library 1.1.1
23875 * Copyright(c) 2006-2007, Ext JS, LLC.
23877 * Originally Released Under LGPL - original licence link has changed is not relivant.
23880 * <script type="text/javascript">
23885 * @class Roo.data.SortTypes
23887 * Defines the default sorting (casting?) comparison functions used when sorting data.
23889 Roo.data.SortTypes = {
23891 * Default sort that does nothing
23892 * @param {Mixed} s The value being converted
23893 * @return {Mixed} The comparison value
23895 none : function(s){
23900 * The regular expression used to strip tags
23904 stripTagsRE : /<\/?[^>]+>/gi,
23907 * Strips all HTML tags to sort on text only
23908 * @param {Mixed} s The value being converted
23909 * @return {String} The comparison value
23911 asText : function(s){
23912 return String(s).replace(this.stripTagsRE, "");
23916 * Strips all HTML tags to sort on text only - Case insensitive
23917 * @param {Mixed} s The value being converted
23918 * @return {String} The comparison value
23920 asUCText : function(s){
23921 return String(s).toUpperCase().replace(this.stripTagsRE, "");
23925 * Case insensitive string
23926 * @param {Mixed} s The value being converted
23927 * @return {String} The comparison value
23929 asUCString : function(s) {
23930 return String(s).toUpperCase();
23935 * @param {Mixed} s The value being converted
23936 * @return {Number} The comparison value
23938 asDate : function(s) {
23942 if(s instanceof Date){
23943 return s.getTime();
23945 return Date.parse(String(s));
23950 * @param {Mixed} s The value being converted
23951 * @return {Float} The comparison value
23953 asFloat : function(s) {
23954 var val = parseFloat(String(s).replace(/,/g, ""));
23963 * @param {Mixed} s The value being converted
23964 * @return {Number} The comparison value
23966 asInt : function(s) {
23967 var val = parseInt(String(s).replace(/,/g, ""));
23975 * Ext JS Library 1.1.1
23976 * Copyright(c) 2006-2007, Ext JS, LLC.
23978 * Originally Released Under LGPL - original licence link has changed is not relivant.
23981 * <script type="text/javascript">
23985 * @class Roo.data.Record
23986 * Instances of this class encapsulate both record <em>definition</em> information, and record
23987 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
23988 * to access Records cached in an {@link Roo.data.Store} object.<br>
23990 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
23991 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
23994 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
23996 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
23997 * {@link #create}. The parameters are the same.
23998 * @param {Array} data An associative Array of data values keyed by the field name.
23999 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
24000 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
24001 * not specified an integer id is generated.
24003 Roo.data.Record = function(data, id){
24004 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
24009 * Generate a constructor for a specific record layout.
24010 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
24011 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
24012 * Each field definition object may contain the following properties: <ul>
24013 * <li><b>name</b> : String<p style="margin-left:1em">The name by which the field is referenced within the Record. This is referenced by,
24014 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
24015 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
24016 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
24017 * is being used, then this is a string containing the javascript expression to reference the data relative to
24018 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
24019 * to the data item relative to the record element. If the mapping expression is the same as the field name,
24020 * this may be omitted.</p></li>
24021 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
24022 * <ul><li>auto (Default, implies no conversion)</li>
24027 * <li>date</li></ul></p></li>
24028 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
24029 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
24030 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
24031 * by the Reader into an object that will be stored in the Record. It is passed the
24032 * following parameters:<ul>
24033 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
24035 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
24037 * <br>usage:<br><pre><code>
24038 var TopicRecord = Roo.data.Record.create(
24039 {name: 'title', mapping: 'topic_title'},
24040 {name: 'author', mapping: 'username'},
24041 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
24042 {name: 'lastPost', mapping: 'post_time', type: 'date'},
24043 {name: 'lastPoster', mapping: 'user2'},
24044 {name: 'excerpt', mapping: 'post_text'}
24047 var myNewRecord = new TopicRecord({
24048 title: 'Do my job please',
24051 lastPost: new Date(),
24052 lastPoster: 'Animal',
24053 excerpt: 'No way dude!'
24055 myStore.add(myNewRecord);
24060 Roo.data.Record.create = function(o){
24061 var f = function(){
24062 f.superclass.constructor.apply(this, arguments);
24064 Roo.extend(f, Roo.data.Record);
24065 var p = f.prototype;
24066 p.fields = new Roo.util.MixedCollection(false, function(field){
24069 for(var i = 0, len = o.length; i < len; i++){
24070 p.fields.add(new Roo.data.Field(o[i]));
24072 f.getField = function(name){
24073 return p.fields.get(name);
24078 Roo.data.Record.AUTO_ID = 1000;
24079 Roo.data.Record.EDIT = 'edit';
24080 Roo.data.Record.REJECT = 'reject';
24081 Roo.data.Record.COMMIT = 'commit';
24083 Roo.data.Record.prototype = {
24085 * Readonly flag - true if this record has been modified.
24094 join : function(store){
24095 this.store = store;
24099 * Set the named field to the specified value.
24100 * @param {String} name The name of the field to set.
24101 * @param {Object} value The value to set the field to.
24103 set : function(name, value){
24104 if(this.data[name] == value){
24108 if(!this.modified){
24109 this.modified = {};
24111 if(typeof this.modified[name] == 'undefined'){
24112 this.modified[name] = this.data[name];
24114 this.data[name] = value;
24115 if(!this.editing && this.store){
24116 this.store.afterEdit(this);
24121 * Get the value of the named field.
24122 * @param {String} name The name of the field to get the value of.
24123 * @return {Object} The value of the field.
24125 get : function(name){
24126 return this.data[name];
24130 beginEdit : function(){
24131 this.editing = true;
24132 this.modified = {};
24136 cancelEdit : function(){
24137 this.editing = false;
24138 delete this.modified;
24142 endEdit : function(){
24143 this.editing = false;
24144 if(this.dirty && this.store){
24145 this.store.afterEdit(this);
24150 * Usually called by the {@link Roo.data.Store} which owns the Record.
24151 * Rejects all changes made to the Record since either creation, or the last commit operation.
24152 * Modified fields are reverted to their original values.
24154 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24155 * of reject operations.
24157 reject : function(){
24158 var m = this.modified;
24160 if(typeof m[n] != "function"){
24161 this.data[n] = m[n];
24164 this.dirty = false;
24165 delete this.modified;
24166 this.editing = false;
24168 this.store.afterReject(this);
24173 * Usually called by the {@link Roo.data.Store} which owns the Record.
24174 * Commits all changes made to the Record since either creation, or the last commit operation.
24176 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24177 * of commit operations.
24179 commit : function(){
24180 this.dirty = false;
24181 delete this.modified;
24182 this.editing = false;
24184 this.store.afterCommit(this);
24189 hasError : function(){
24190 return this.error != null;
24194 clearError : function(){
24199 * Creates a copy of this record.
24200 * @param {String} id (optional) A new record id if you don't want to use this record's id
24203 copy : function(newId) {
24204 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
24208 * Ext JS Library 1.1.1
24209 * Copyright(c) 2006-2007, Ext JS, LLC.
24211 * Originally Released Under LGPL - original licence link has changed is not relivant.
24214 * <script type="text/javascript">
24220 * @class Roo.data.Store
24221 * @extends Roo.util.Observable
24222 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
24223 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
24225 * A Store object uses an implementation of {@link Roo.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
24226 * has no knowledge of the format of the data returned by the Proxy.<br>
24228 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
24229 * instances from the data object. These records are cached and made available through accessor functions.
24231 * Creates a new Store.
24232 * @param {Object} config A config object containing the objects needed for the Store to access data,
24233 * and read the data into Records.
24235 Roo.data.Store = function(config){
24236 this.data = new Roo.util.MixedCollection(false);
24237 this.data.getKey = function(o){
24240 this.baseParams = {};
24242 this.paramNames = {
24247 "multisort" : "_multisort"
24250 if(config && config.data){
24251 this.inlineData = config.data;
24252 delete config.data;
24255 Roo.apply(this, config);
24257 if(this.reader){ // reader passed
24258 this.reader = Roo.factory(this.reader, Roo.data);
24259 this.reader.xmodule = this.xmodule || false;
24260 if(!this.recordType){
24261 this.recordType = this.reader.recordType;
24263 if(this.reader.onMetaChange){
24264 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
24268 if(this.recordType){
24269 this.fields = this.recordType.prototype.fields;
24271 this.modified = [];
24275 * @event datachanged
24276 * Fires when the data cache has changed, and a widget which is using this Store
24277 * as a Record cache should refresh its view.
24278 * @param {Store} this
24280 datachanged : true,
24282 * @event metachange
24283 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
24284 * @param {Store} this
24285 * @param {Object} meta The JSON metadata
24290 * Fires when Records have been added to the Store
24291 * @param {Store} this
24292 * @param {Roo.data.Record[]} records The array of Records added
24293 * @param {Number} index The index at which the record(s) were added
24298 * Fires when a Record has been removed from the Store
24299 * @param {Store} this
24300 * @param {Roo.data.Record} record The Record that was removed
24301 * @param {Number} index The index at which the record was removed
24306 * Fires when a Record has been updated
24307 * @param {Store} this
24308 * @param {Roo.data.Record} record The Record that was updated
24309 * @param {String} operation The update operation being performed. Value may be one of:
24311 Roo.data.Record.EDIT
24312 Roo.data.Record.REJECT
24313 Roo.data.Record.COMMIT
24319 * Fires when the data cache has been cleared.
24320 * @param {Store} this
24324 * @event beforeload
24325 * Fires before a request is made for a new data object. If the beforeload handler returns false
24326 * the load action will be canceled.
24327 * @param {Store} this
24328 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24332 * @event beforeloadadd
24333 * Fires after a new set of Records has been loaded.
24334 * @param {Store} this
24335 * @param {Roo.data.Record[]} records The Records that were loaded
24336 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24338 beforeloadadd : true,
24341 * Fires after a new set of Records has been loaded, before they are added to the store.
24342 * @param {Store} this
24343 * @param {Roo.data.Record[]} records The Records that were loaded
24344 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24345 * @params {Object} return from reader
24349 * @event loadexception
24350 * Fires if an exception occurs in the Proxy during loading.
24351 * Called with the signature of the Proxy's "loadexception" event.
24352 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
24355 * @param {Object} return from JsonData.reader() - success, totalRecords, records
24356 * @param {Object} load options
24357 * @param {Object} jsonData from your request (normally this contains the Exception)
24359 loadexception : true
24363 this.proxy = Roo.factory(this.proxy, Roo.data);
24364 this.proxy.xmodule = this.xmodule || false;
24365 this.relayEvents(this.proxy, ["loadexception"]);
24367 this.sortToggle = {};
24368 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
24370 Roo.data.Store.superclass.constructor.call(this);
24372 if(this.inlineData){
24373 this.loadData(this.inlineData);
24374 delete this.inlineData;
24378 Roo.extend(Roo.data.Store, Roo.util.Observable, {
24380 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
24381 * without a remote query - used by combo/forms at present.
24385 * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
24388 * @cfg {Array} data Inline data to be loaded when the store is initialized.
24391 * @cfg {Roo.data.DataReader} reader [required] The Reader object which processes the data object and returns
24392 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
24395 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
24396 * on any HTTP request
24399 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
24402 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
24406 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
24407 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
24409 remoteSort : false,
24412 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
24413 * loaded or when a record is removed. (defaults to false).
24415 pruneModifiedRecords : false,
24418 lastOptions : null,
24421 * Add Records to the Store and fires the add event.
24422 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
24424 add : function(records){
24425 records = [].concat(records);
24426 for(var i = 0, len = records.length; i < len; i++){
24427 records[i].join(this);
24429 var index = this.data.length;
24430 this.data.addAll(records);
24431 this.fireEvent("add", this, records, index);
24435 * Remove a Record from the Store and fires the remove event.
24436 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
24438 remove : function(record){
24439 var index = this.data.indexOf(record);
24440 this.data.removeAt(index);
24442 if(this.pruneModifiedRecords){
24443 this.modified.remove(record);
24445 this.fireEvent("remove", this, record, index);
24449 * Remove all Records from the Store and fires the clear event.
24451 removeAll : function(){
24453 if(this.pruneModifiedRecords){
24454 this.modified = [];
24456 this.fireEvent("clear", this);
24460 * Inserts Records to the Store at the given index and fires the add event.
24461 * @param {Number} index The start index at which to insert the passed Records.
24462 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
24464 insert : function(index, records){
24465 records = [].concat(records);
24466 for(var i = 0, len = records.length; i < len; i++){
24467 this.data.insert(index, records[i]);
24468 records[i].join(this);
24470 this.fireEvent("add", this, records, index);
24474 * Get the index within the cache of the passed Record.
24475 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
24476 * @return {Number} The index of the passed Record. Returns -1 if not found.
24478 indexOf : function(record){
24479 return this.data.indexOf(record);
24483 * Get the index within the cache of the Record with the passed id.
24484 * @param {String} id The id of the Record to find.
24485 * @return {Number} The index of the Record. Returns -1 if not found.
24487 indexOfId : function(id){
24488 return this.data.indexOfKey(id);
24492 * Get the Record with the specified id.
24493 * @param {String} id The id of the Record to find.
24494 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
24496 getById : function(id){
24497 return this.data.key(id);
24501 * Get the Record at the specified index.
24502 * @param {Number} index The index of the Record to find.
24503 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
24505 getAt : function(index){
24506 return this.data.itemAt(index);
24510 * Returns a range of Records between specified indices.
24511 * @param {Number} startIndex (optional) The starting index (defaults to 0)
24512 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
24513 * @return {Roo.data.Record[]} An array of Records
24515 getRange : function(start, end){
24516 return this.data.getRange(start, end);
24520 storeOptions : function(o){
24521 o = Roo.apply({}, o);
24524 this.lastOptions = o;
24528 * Loads the Record cache from the configured Proxy using the configured Reader.
24530 * If using remote paging, then the first load call must specify the <em>start</em>
24531 * and <em>limit</em> properties in the options.params property to establish the initial
24532 * position within the dataset, and the number of Records to cache on each read from the Proxy.
24534 * <strong>It is important to note that for remote data sources, loading is asynchronous,
24535 * and this call will return before the new data has been loaded. Perform any post-processing
24536 * in a callback function, or in a "load" event handler.</strong>
24538 * @param {Object} options An object containing properties which control loading options:<ul>
24539 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
24540 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
24541 * passed the following arguments:<ul>
24542 * <li>r : Roo.data.Record[]</li>
24543 * <li>options: Options object from the load call</li>
24544 * <li>success: Boolean success indicator</li></ul></li>
24545 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
24546 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
24549 load : function(options){
24550 options = options || {};
24551 if(this.fireEvent("beforeload", this, options) !== false){
24552 this.storeOptions(options);
24553 var p = Roo.apply(options.params || {}, this.baseParams);
24554 // if meta was not loaded from remote source.. try requesting it.
24555 if (!this.reader.metaFromRemote) {
24556 p._requestMeta = 1;
24558 if(this.sortInfo && this.remoteSort){
24559 var pn = this.paramNames;
24560 p[pn["sort"]] = this.sortInfo.field;
24561 p[pn["dir"]] = this.sortInfo.direction;
24563 if (this.multiSort) {
24564 var pn = this.paramNames;
24565 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
24568 this.proxy.load(p, this.reader, this.loadRecords, this, options);
24573 * Reloads the Record cache from the configured Proxy using the configured Reader and
24574 * the options from the last load operation performed.
24575 * @param {Object} options (optional) An object containing properties which may override the options
24576 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
24577 * the most recently used options are reused).
24579 reload : function(options){
24580 this.load(Roo.applyIf(options||{}, this.lastOptions));
24584 // Called as a callback by the Reader during a load operation.
24585 loadRecords : function(o, options, success){
24588 if(success !== false){
24589 this.fireEvent("load", this, [], options, o);
24591 if(options.callback){
24592 options.callback.call(options.scope || this, [], options, false);
24596 // if data returned failure - throw an exception.
24597 if (o.success === false) {
24598 // show a message if no listener is registered.
24599 if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
24600 Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
24602 // loadmask wil be hooked into this..
24603 this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
24606 var r = o.records, t = o.totalRecords || r.length;
24608 this.fireEvent("beforeloadadd", this, r, options, o);
24610 if(!options || options.add !== true){
24611 if(this.pruneModifiedRecords){
24612 this.modified = [];
24614 for(var i = 0, len = r.length; i < len; i++){
24618 this.data = this.snapshot;
24619 delete this.snapshot;
24622 this.data.addAll(r);
24623 this.totalLength = t;
24625 this.fireEvent("datachanged", this);
24627 this.totalLength = Math.max(t, this.data.length+r.length);
24631 if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
24633 var e = new Roo.data.Record({});
24635 e.set(this.parent.displayField, this.parent.emptyTitle);
24636 e.set(this.parent.valueField, '');
24641 this.fireEvent("load", this, r, options, o);
24642 if(options.callback){
24643 options.callback.call(options.scope || this, r, options, true);
24649 * Loads data from a passed data block. A Reader which understands the format of the data
24650 * must have been configured in the constructor.
24651 * @param {Object} data The data block from which to read the Records. The format of the data expected
24652 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
24653 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
24655 loadData : function(o, append){
24656 var r = this.reader.readRecords(o);
24657 this.loadRecords(r, {add: append}, true);
24661 * using 'cn' the nested child reader read the child array into it's child stores.
24662 * @param {Object} rec The record with a 'children array
24664 loadDataFromChildren : function(rec)
24666 this.loadData(this.reader.toLoadData(rec));
24671 * Gets the number of cached records.
24673 * <em>If using paging, this may not be the total size of the dataset. If the data object
24674 * used by the Reader contains the dataset size, then the getTotalCount() function returns
24675 * the data set size</em>
24677 getCount : function(){
24678 return this.data.length || 0;
24682 * Gets the total number of records in the dataset as returned by the server.
24684 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
24685 * the dataset size</em>
24687 getTotalCount : function(){
24688 return this.totalLength || 0;
24692 * Returns the sort state of the Store as an object with two properties:
24694 field {String} The name of the field by which the Records are sorted
24695 direction {String} The sort order, "ASC" or "DESC"
24698 getSortState : function(){
24699 return this.sortInfo;
24703 applySort : function(){
24704 if(this.sortInfo && !this.remoteSort){
24705 var s = this.sortInfo, f = s.field;
24706 var st = this.fields.get(f).sortType;
24707 var fn = function(r1, r2){
24708 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
24709 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
24711 this.data.sort(s.direction, fn);
24712 if(this.snapshot && this.snapshot != this.data){
24713 this.snapshot.sort(s.direction, fn);
24719 * Sets the default sort column and order to be used by the next load operation.
24720 * @param {String} fieldName The name of the field to sort by.
24721 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
24723 setDefaultSort : function(field, dir){
24724 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
24728 * Sort the Records.
24729 * If remote sorting is used, the sort is performed on the server, and the cache is
24730 * reloaded. If local sorting is used, the cache is sorted internally.
24731 * @param {String} fieldName The name of the field to sort by.
24732 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
24734 sort : function(fieldName, dir){
24735 var f = this.fields.get(fieldName);
24737 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
24739 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
24740 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
24745 this.sortToggle[f.name] = dir;
24746 this.sortInfo = {field: f.name, direction: dir};
24747 if(!this.remoteSort){
24749 this.fireEvent("datachanged", this);
24751 this.load(this.lastOptions);
24756 * Calls the specified function for each of the Records in the cache.
24757 * @param {Function} fn The function to call. The Record is passed as the first parameter.
24758 * Returning <em>false</em> aborts and exits the iteration.
24759 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
24761 each : function(fn, scope){
24762 this.data.each(fn, scope);
24766 * Gets all records modified since the last commit. Modified records are persisted across load operations
24767 * (e.g., during paging).
24768 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
24770 getModifiedRecords : function(){
24771 return this.modified;
24775 createFilterFn : function(property, value, anyMatch){
24776 if(!value.exec){ // not a regex
24777 value = String(value);
24778 if(value.length == 0){
24781 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
24783 return function(r){
24784 return value.test(r.data[property]);
24789 * Sums the value of <i>property</i> for each record between start and end and returns the result.
24790 * @param {String} property A field on your records
24791 * @param {Number} start The record index to start at (defaults to 0)
24792 * @param {Number} end The last record index to include (defaults to length - 1)
24793 * @return {Number} The sum
24795 sum : function(property, start, end){
24796 var rs = this.data.items, v = 0;
24797 start = start || 0;
24798 end = (end || end === 0) ? end : rs.length-1;
24800 for(var i = start; i <= end; i++){
24801 v += (rs[i].data[property] || 0);
24807 * Filter the records by a specified property.
24808 * @param {String} field A field on your records
24809 * @param {String/RegExp} value Either a string that the field
24810 * should start with or a RegExp to test against the field
24811 * @param {Boolean} anyMatch True to match any part not just the beginning
24813 filter : function(property, value, anyMatch){
24814 var fn = this.createFilterFn(property, value, anyMatch);
24815 return fn ? this.filterBy(fn) : this.clearFilter();
24819 * Filter by a function. The specified function will be called with each
24820 * record in this data source. If the function returns true the record is included,
24821 * otherwise it is filtered.
24822 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
24823 * @param {Object} scope (optional) The scope of the function (defaults to this)
24825 filterBy : function(fn, scope){
24826 this.snapshot = this.snapshot || this.data;
24827 this.data = this.queryBy(fn, scope||this);
24828 this.fireEvent("datachanged", this);
24832 * Query the records by a specified property.
24833 * @param {String} field A field on your records
24834 * @param {String/RegExp} value Either a string that the field
24835 * should start with or a RegExp to test against the field
24836 * @param {Boolean} anyMatch True to match any part not just the beginning
24837 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
24839 query : function(property, value, anyMatch){
24840 var fn = this.createFilterFn(property, value, anyMatch);
24841 return fn ? this.queryBy(fn) : this.data.clone();
24845 * Query by a function. The specified function will be called with each
24846 * record in this data source. If the function returns true the record is included
24848 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
24849 * @param {Object} scope (optional) The scope of the function (defaults to this)
24850 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
24852 queryBy : function(fn, scope){
24853 var data = this.snapshot || this.data;
24854 return data.filterBy(fn, scope||this);
24858 * Collects unique values for a particular dataIndex from this store.
24859 * @param {String} dataIndex The property to collect
24860 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
24861 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
24862 * @return {Array} An array of the unique values
24864 collect : function(dataIndex, allowNull, bypassFilter){
24865 var d = (bypassFilter === true && this.snapshot) ?
24866 this.snapshot.items : this.data.items;
24867 var v, sv, r = [], l = {};
24868 for(var i = 0, len = d.length; i < len; i++){
24869 v = d[i].data[dataIndex];
24871 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
24880 * Revert to a view of the Record cache with no filtering applied.
24881 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
24883 clearFilter : function(suppressEvent){
24884 if(this.snapshot && this.snapshot != this.data){
24885 this.data = this.snapshot;
24886 delete this.snapshot;
24887 if(suppressEvent !== true){
24888 this.fireEvent("datachanged", this);
24894 afterEdit : function(record){
24895 if(this.modified.indexOf(record) == -1){
24896 this.modified.push(record);
24898 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
24902 afterReject : function(record){
24903 this.modified.remove(record);
24904 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
24908 afterCommit : function(record){
24909 this.modified.remove(record);
24910 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
24914 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
24915 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
24917 commitChanges : function(){
24918 var m = this.modified.slice(0);
24919 this.modified = [];
24920 for(var i = 0, len = m.length; i < len; i++){
24926 * Cancel outstanding changes on all changed records.
24928 rejectChanges : function(){
24929 var m = this.modified.slice(0);
24930 this.modified = [];
24931 for(var i = 0, len = m.length; i < len; i++){
24936 onMetaChange : function(meta, rtype, o){
24937 this.recordType = rtype;
24938 this.fields = rtype.prototype.fields;
24939 delete this.snapshot;
24940 this.sortInfo = meta.sortInfo || this.sortInfo;
24941 this.modified = [];
24942 this.fireEvent('metachange', this, this.reader.meta);
24945 moveIndex : function(data, type)
24947 var index = this.indexOf(data);
24949 var newIndex = index + type;
24953 this.insert(newIndex, data);
24958 * Ext JS Library 1.1.1
24959 * Copyright(c) 2006-2007, Ext JS, LLC.
24961 * Originally Released Under LGPL - original licence link has changed is not relivant.
24964 * <script type="text/javascript">
24968 * @class Roo.data.SimpleStore
24969 * @extends Roo.data.Store
24970 * Small helper class to make creating Stores from Array data easier.
24971 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
24972 * @cfg {Array} fields An array of field definition objects, or field name strings.
24973 * @cfg {Object} an existing reader (eg. copied from another store)
24974 * @cfg {Array} data The multi-dimensional array of data
24975 * @cfg {Roo.data.DataProxy} proxy [not-required]
24976 * @cfg {Roo.data.Reader} reader [not-required]
24978 * @param {Object} config
24980 Roo.data.SimpleStore = function(config)
24982 Roo.data.SimpleStore.superclass.constructor.call(this, {
24984 reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
24987 Roo.data.Record.create(config.fields)
24989 proxy : new Roo.data.MemoryProxy(config.data)
24993 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
24995 * Ext JS Library 1.1.1
24996 * Copyright(c) 2006-2007, Ext JS, LLC.
24998 * Originally Released Under LGPL - original licence link has changed is not relivant.
25001 * <script type="text/javascript">
25006 * @extends Roo.data.Store
25007 * @class Roo.data.JsonStore
25008 * Small helper class to make creating Stores for JSON data easier. <br/>
25010 var store = new Roo.data.JsonStore({
25011 url: 'get-images.php',
25013 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
25016 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
25017 * JsonReader and HttpProxy (unless inline data is provided).</b>
25018 * @cfg {Array} fields An array of field definition objects, or field name strings.
25020 * @param {Object} config
25022 Roo.data.JsonStore = function(c){
25023 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
25024 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
25025 reader: new Roo.data.JsonReader(c, c.fields)
25028 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
25030 * Ext JS Library 1.1.1
25031 * Copyright(c) 2006-2007, Ext JS, LLC.
25033 * Originally Released Under LGPL - original licence link has changed is not relivant.
25036 * <script type="text/javascript">
25040 Roo.data.Field = function(config){
25041 if(typeof config == "string"){
25042 config = {name: config};
25044 Roo.apply(this, config);
25047 this.type = "auto";
25050 var st = Roo.data.SortTypes;
25051 // named sortTypes are supported, here we look them up
25052 if(typeof this.sortType == "string"){
25053 this.sortType = st[this.sortType];
25056 // set default sortType for strings and dates
25057 if(!this.sortType){
25060 this.sortType = st.asUCString;
25063 this.sortType = st.asDate;
25066 this.sortType = st.none;
25071 var stripRe = /[\$,%]/g;
25073 // prebuilt conversion function for this field, instead of
25074 // switching every time we're reading a value
25076 var cv, dateFormat = this.dateFormat;
25081 cv = function(v){ return v; };
25084 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
25088 return v !== undefined && v !== null && v !== '' ?
25089 parseInt(String(v).replace(stripRe, ""), 10) : '';
25094 return v !== undefined && v !== null && v !== '' ?
25095 parseFloat(String(v).replace(stripRe, ""), 10) : '';
25100 cv = function(v){ return v === true || v === "true" || v == 1; };
25107 if(v instanceof Date){
25111 if(dateFormat == "timestamp"){
25112 return new Date(v*1000);
25114 return Date.parseDate(v, dateFormat);
25116 var parsed = Date.parse(v);
25117 return parsed ? new Date(parsed) : null;
25126 Roo.data.Field.prototype = {
25134 * Ext JS Library 1.1.1
25135 * Copyright(c) 2006-2007, Ext JS, LLC.
25137 * Originally Released Under LGPL - original licence link has changed is not relivant.
25140 * <script type="text/javascript">
25143 // Base class for reading structured data from a data source. This class is intended to be
25144 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
25147 * @class Roo.data.DataReader
25149 * Base class for reading structured data from a data source. This class is intended to be
25150 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
25153 Roo.data.DataReader = function(meta, recordType){
25157 this.recordType = recordType instanceof Array ?
25158 Roo.data.Record.create(recordType) : recordType;
25161 Roo.data.DataReader.prototype = {
25164 readerType : 'Data',
25166 * Create an empty record
25167 * @param {Object} data (optional) - overlay some values
25168 * @return {Roo.data.Record} record created.
25170 newRow : function(d) {
25172 this.recordType.prototype.fields.each(function(c) {
25174 case 'int' : da[c.name] = 0; break;
25175 case 'date' : da[c.name] = new Date(); break;
25176 case 'float' : da[c.name] = 0.0; break;
25177 case 'boolean' : da[c.name] = false; break;
25178 default : da[c.name] = ""; break;
25182 return new this.recordType(Roo.apply(da, d));
25188 * Ext JS Library 1.1.1
25189 * Copyright(c) 2006-2007, Ext JS, LLC.
25191 * Originally Released Under LGPL - original licence link has changed is not relivant.
25194 * <script type="text/javascript">
25198 * @class Roo.data.DataProxy
25199 * @extends Roo.util.Observable
25201 * This class is an abstract base class for implementations which provide retrieval of
25202 * unformatted data objects.<br>
25204 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
25205 * (of the appropriate type which knows how to parse the data object) to provide a block of
25206 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
25208 * Custom implementations must implement the load method as described in
25209 * {@link Roo.data.HttpProxy#load}.
25211 Roo.data.DataProxy = function(){
25214 * @event beforeload
25215 * Fires before a network request is made to retrieve a data object.
25216 * @param {Object} This DataProxy object.
25217 * @param {Object} params The params parameter to the load function.
25222 * Fires before the load method's callback is called.
25223 * @param {Object} This DataProxy object.
25224 * @param {Object} o The data object.
25225 * @param {Object} arg The callback argument object passed to the load function.
25229 * @event loadexception
25230 * Fires if an Exception occurs during data retrieval.
25231 * @param {Object} This DataProxy object.
25232 * @param {Object} o The data object.
25233 * @param {Object} arg The callback argument object passed to the load function.
25234 * @param {Object} e The Exception.
25236 loadexception : true
25238 Roo.data.DataProxy.superclass.constructor.call(this);
25241 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
25244 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
25248 * Ext JS Library 1.1.1
25249 * Copyright(c) 2006-2007, Ext JS, LLC.
25251 * Originally Released Under LGPL - original licence link has changed is not relivant.
25254 * <script type="text/javascript">
25257 * @class Roo.data.MemoryProxy
25258 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
25259 * to the Reader when its load method is called.
25261 * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
25263 Roo.data.MemoryProxy = function(data){
25267 Roo.data.MemoryProxy.superclass.constructor.call(this);
25271 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
25274 * Load data from the requested source (in this case an in-memory
25275 * data object passed to the constructor), read the data object into
25276 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
25277 * process that block using the passed callback.
25278 * @param {Object} params This parameter is not used by the MemoryProxy class.
25279 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25280 * object into a block of Roo.data.Records.
25281 * @param {Function} callback The function into which to pass the block of Roo.data.records.
25282 * The function must be passed <ul>
25283 * <li>The Record block object</li>
25284 * <li>The "arg" argument from the load function</li>
25285 * <li>A boolean success indicator</li>
25287 * @param {Object} scope The scope in which to call the callback
25288 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25290 load : function(params, reader, callback, scope, arg){
25291 params = params || {};
25294 result = reader.readRecords(params.data ? params.data :this.data);
25296 this.fireEvent("loadexception", this, arg, null, e);
25297 callback.call(scope, null, arg, false);
25300 callback.call(scope, result, arg, true);
25304 update : function(params, records){
25309 * Ext JS Library 1.1.1
25310 * Copyright(c) 2006-2007, Ext JS, LLC.
25312 * Originally Released Under LGPL - original licence link has changed is not relivant.
25315 * <script type="text/javascript">
25318 * @class Roo.data.HttpProxy
25319 * @extends Roo.data.DataProxy
25320 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
25321 * configured to reference a certain URL.<br><br>
25323 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
25324 * from which the running page was served.<br><br>
25326 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
25328 * Be aware that to enable the browser to parse an XML document, the server must set
25329 * the Content-Type header in the HTTP response to "text/xml".
25331 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
25332 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
25333 * will be used to make the request.
25335 Roo.data.HttpProxy = function(conn){
25336 Roo.data.HttpProxy.superclass.constructor.call(this);
25337 // is conn a conn config or a real conn?
25339 this.useAjax = !conn || !conn.events;
25343 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
25344 // thse are take from connection...
25347 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
25350 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
25351 * extra parameters to each request made by this object. (defaults to undefined)
25354 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
25355 * to each request made by this object. (defaults to undefined)
25358 * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
25361 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
25364 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
25370 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
25374 * Return the {@link Roo.data.Connection} object being used by this Proxy.
25375 * @return {Connection} The Connection object. This object may be used to subscribe to events on
25376 * a finer-grained basis than the DataProxy events.
25378 getConnection : function(){
25379 return this.useAjax ? Roo.Ajax : this.conn;
25383 * Load data from the configured {@link Roo.data.Connection}, read the data object into
25384 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
25385 * process that block using the passed callback.
25386 * @param {Object} params An object containing properties which are to be used as HTTP parameters
25387 * for the request to the remote server.
25388 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25389 * object into a block of Roo.data.Records.
25390 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
25391 * The function must be passed <ul>
25392 * <li>The Record block object</li>
25393 * <li>The "arg" argument from the load function</li>
25394 * <li>A boolean success indicator</li>
25396 * @param {Object} scope The scope in which to call the callback
25397 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25399 load : function(params, reader, callback, scope, arg){
25400 if(this.fireEvent("beforeload", this, params) !== false){
25402 params : params || {},
25404 callback : callback,
25409 callback : this.loadResponse,
25413 Roo.applyIf(o, this.conn);
25414 if(this.activeRequest){
25415 Roo.Ajax.abort(this.activeRequest);
25417 this.activeRequest = Roo.Ajax.request(o);
25419 this.conn.request(o);
25422 callback.call(scope||this, null, arg, false);
25427 loadResponse : function(o, success, response){
25428 delete this.activeRequest;
25430 this.fireEvent("loadexception", this, o, response);
25431 o.request.callback.call(o.request.scope, null, o.request.arg, false);
25436 result = o.reader.read(response);
25439 o.raw = { errorMsg : response.responseText };
25440 this.fireEvent("loadexception", this, o, response, e);
25441 o.request.callback.call(o.request.scope, o, o.request.arg, false);
25445 this.fireEvent("load", this, o, o.request.arg);
25446 o.request.callback.call(o.request.scope, result, o.request.arg, true);
25450 update : function(dataSet){
25455 updateResponse : function(dataSet){
25460 * Ext JS Library 1.1.1
25461 * Copyright(c) 2006-2007, Ext JS, LLC.
25463 * Originally Released Under LGPL - original licence link has changed is not relivant.
25466 * <script type="text/javascript">
25470 * @class Roo.data.ScriptTagProxy
25471 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
25472 * other than the originating domain of the running page.<br><br>
25474 * <em>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
25475 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
25477 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
25478 * source code that is used as the source inside a <script> tag.<br><br>
25480 * In order for the browser to process the returned data, the server must wrap the data object
25481 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
25482 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
25483 * depending on whether the callback name was passed:
25486 boolean scriptTag = false;
25487 String cb = request.getParameter("callback");
25490 response.setContentType("text/javascript");
25492 response.setContentType("application/x-json");
25494 Writer out = response.getWriter();
25496 out.write(cb + "(");
25498 out.print(dataBlock.toJsonString());
25505 * @param {Object} config A configuration object.
25507 Roo.data.ScriptTagProxy = function(config){
25508 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
25509 Roo.apply(this, config);
25510 this.head = document.getElementsByTagName("head")[0];
25513 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
25515 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
25517 * @cfg {String} url The URL from which to request the data object.
25520 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
25524 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
25525 * the server the name of the callback function set up by the load call to process the returned data object.
25526 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
25527 * javascript output which calls this named function passing the data object as its only parameter.
25529 callbackParam : "callback",
25531 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
25532 * name to the request.
25537 * Load data from the configured URL, read the data object into
25538 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
25539 * process that block using the passed callback.
25540 * @param {Object} params An object containing properties which are to be used as HTTP parameters
25541 * for the request to the remote server.
25542 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25543 * object into a block of Roo.data.Records.
25544 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
25545 * The function must be passed <ul>
25546 * <li>The Record block object</li>
25547 * <li>The "arg" argument from the load function</li>
25548 * <li>A boolean success indicator</li>
25550 * @param {Object} scope The scope in which to call the callback
25551 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25553 load : function(params, reader, callback, scope, arg){
25554 if(this.fireEvent("beforeload", this, params) !== false){
25556 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
25558 var url = this.url;
25559 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
25561 url += "&_dc=" + (new Date().getTime());
25563 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
25566 cb : "stcCallback"+transId,
25567 scriptId : "stcScript"+transId,
25571 callback : callback,
25577 window[trans.cb] = function(o){
25578 conn.handleResponse(o, trans);
25581 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
25583 if(this.autoAbort !== false){
25587 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
25589 var script = document.createElement("script");
25590 script.setAttribute("src", url);
25591 script.setAttribute("type", "text/javascript");
25592 script.setAttribute("id", trans.scriptId);
25593 this.head.appendChild(script);
25595 this.trans = trans;
25597 callback.call(scope||this, null, arg, false);
25602 isLoading : function(){
25603 return this.trans ? true : false;
25607 * Abort the current server request.
25609 abort : function(){
25610 if(this.isLoading()){
25611 this.destroyTrans(this.trans);
25616 destroyTrans : function(trans, isLoaded){
25617 this.head.removeChild(document.getElementById(trans.scriptId));
25618 clearTimeout(trans.timeoutId);
25620 window[trans.cb] = undefined;
25622 delete window[trans.cb];
25625 // if hasn't been loaded, wait for load to remove it to prevent script error
25626 window[trans.cb] = function(){
25627 window[trans.cb] = undefined;
25629 delete window[trans.cb];
25636 handleResponse : function(o, trans){
25637 this.trans = false;
25638 this.destroyTrans(trans, true);
25641 result = trans.reader.readRecords(o);
25643 this.fireEvent("loadexception", this, o, trans.arg, e);
25644 trans.callback.call(trans.scope||window, null, trans.arg, false);
25647 this.fireEvent("load", this, o, trans.arg);
25648 trans.callback.call(trans.scope||window, result, trans.arg, true);
25652 handleFailure : function(trans){
25653 this.trans = false;
25654 this.destroyTrans(trans, false);
25655 this.fireEvent("loadexception", this, null, trans.arg);
25656 trans.callback.call(trans.scope||window, null, trans.arg, false);
25660 * Ext JS Library 1.1.1
25661 * Copyright(c) 2006-2007, Ext JS, LLC.
25663 * Originally Released Under LGPL - original licence link has changed is not relivant.
25666 * <script type="text/javascript">
25670 * @class Roo.data.JsonReader
25671 * @extends Roo.data.DataReader
25672 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
25673 * based on mappings in a provided Roo.data.Record constructor.
25675 * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
25676 * in the reply previously.
25681 var RecordDef = Roo.data.Record.create([
25682 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
25683 {name: 'occupation'} // This field will use "occupation" as the mapping.
25685 var myReader = new Roo.data.JsonReader({
25686 totalProperty: "results", // The property which contains the total dataset size (optional)
25687 root: "rows", // The property which contains an Array of row objects
25688 id: "id" // The property within each row object that provides an ID for the record (optional)
25692 * This would consume a JSON file like this:
25694 { 'results': 2, 'rows': [
25695 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
25696 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
25699 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
25700 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
25701 * paged from the remote server.
25702 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
25703 * @cfg {String} root name of the property which contains the Array of row objects.
25704 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
25705 * @cfg {Array} fields Array of field definition objects
25707 * Create a new JsonReader
25708 * @param {Object} meta Metadata configuration options
25709 * @param {Object} recordType Either an Array of field definition objects,
25710 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
25712 Roo.data.JsonReader = function(meta, recordType){
25715 // set some defaults:
25716 Roo.applyIf(meta, {
25717 totalProperty: 'total',
25718 successProperty : 'success',
25723 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
25725 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
25727 readerType : 'Json',
25730 * @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
25731 * Used by Store query builder to append _requestMeta to params.
25734 metaFromRemote : false,
25736 * This method is only used by a DataProxy which has retrieved data from a remote server.
25737 * @param {Object} response The XHR object which contains the JSON data in its responseText.
25738 * @return {Object} data A data block which is used by an Roo.data.Store object as
25739 * a cache of Roo.data.Records.
25741 read : function(response){
25742 var json = response.responseText;
25744 var o = /* eval:var:o */ eval("("+json+")");
25746 throw {message: "JsonReader.read: Json object not found"};
25752 this.metaFromRemote = true;
25753 this.meta = o.metaData;
25754 this.recordType = Roo.data.Record.create(o.metaData.fields);
25755 this.onMetaChange(this.meta, this.recordType, o);
25757 return this.readRecords(o);
25760 // private function a store will implement
25761 onMetaChange : function(meta, recordType, o){
25768 simpleAccess: function(obj, subsc) {
25775 getJsonAccessor: function(){
25777 return function(expr) {
25779 return(re.test(expr))
25780 ? new Function("obj", "return obj." + expr)
25785 return Roo.emptyFn;
25790 * Create a data block containing Roo.data.Records from an XML document.
25791 * @param {Object} o An object which contains an Array of row objects in the property specified
25792 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
25793 * which contains the total size of the dataset.
25794 * @return {Object} data A data block which is used by an Roo.data.Store object as
25795 * a cache of Roo.data.Records.
25797 readRecords : function(o){
25799 * After any data loads, the raw JSON data is available for further custom processing.
25803 var s = this.meta, Record = this.recordType,
25804 f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
25806 // Generate extraction functions for the totalProperty, the root, the id, and for each field
25808 if(s.totalProperty) {
25809 this.getTotal = this.getJsonAccessor(s.totalProperty);
25811 if(s.successProperty) {
25812 this.getSuccess = this.getJsonAccessor(s.successProperty);
25814 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
25816 var g = this.getJsonAccessor(s.id);
25817 this.getId = function(rec) {
25819 return (r === undefined || r === "") ? null : r;
25822 this.getId = function(){return null;};
25825 for(var jj = 0; jj < fl; jj++){
25827 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
25828 this.ef[jj] = this.getJsonAccessor(map);
25832 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
25833 if(s.totalProperty){
25834 var vt = parseInt(this.getTotal(o), 10);
25839 if(s.successProperty){
25840 var vs = this.getSuccess(o);
25841 if(vs === false || vs === 'false'){
25846 for(var i = 0; i < c; i++){
25849 var id = this.getId(n);
25850 for(var j = 0; j < fl; j++){
25852 var v = this.ef[j](n);
25854 Roo.log('missing convert for ' + f.name);
25858 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
25860 var record = new Record(values, id);
25862 records[i] = record;
25868 totalRecords : totalRecords
25871 // used when loading children.. @see loadDataFromChildren
25872 toLoadData: function(rec)
25874 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
25875 var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
25876 return { data : data, total : data.length };
25881 * Ext JS Library 1.1.1
25882 * Copyright(c) 2006-2007, Ext JS, LLC.
25884 * Originally Released Under LGPL - original licence link has changed is not relivant.
25887 * <script type="text/javascript">
25891 * @class Roo.data.XmlReader
25892 * @extends Roo.data.DataReader
25893 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
25894 * based on mappings in a provided Roo.data.Record constructor.<br><br>
25896 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
25897 * header in the HTTP response must be set to "text/xml".</em>
25901 var RecordDef = Roo.data.Record.create([
25902 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
25903 {name: 'occupation'} // This field will use "occupation" as the mapping.
25905 var myReader = new Roo.data.XmlReader({
25906 totalRecords: "results", // The element which contains the total dataset size (optional)
25907 record: "row", // The repeated element which contains row information
25908 id: "id" // The element within the row that provides an ID for the record (optional)
25912 * This would consume an XML file like this:
25916 <results>2</results>
25919 <name>Bill</name>
25920 <occupation>Gardener</occupation>
25924 <name>Ben</name>
25925 <occupation>Horticulturalist</occupation>
25929 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
25930 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
25931 * paged from the remote server.
25932 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
25933 * @cfg {String} success The DomQuery path to the success attribute used by forms.
25934 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
25935 * a record identifier value.
25937 * Create a new XmlReader
25938 * @param {Object} meta Metadata configuration options
25939 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
25940 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
25941 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
25943 Roo.data.XmlReader = function(meta, recordType){
25945 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
25947 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
25949 readerType : 'Xml',
25952 * This method is only used by a DataProxy which has retrieved data from a remote server.
25953 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
25954 * to contain a method called 'responseXML' that returns an XML document object.
25955 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
25956 * a cache of Roo.data.Records.
25958 read : function(response){
25959 var doc = response.responseXML;
25961 throw {message: "XmlReader.read: XML Document not available"};
25963 return this.readRecords(doc);
25967 * Create a data block containing Roo.data.Records from an XML document.
25968 * @param {Object} doc A parsed XML document.
25969 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
25970 * a cache of Roo.data.Records.
25972 readRecords : function(doc){
25974 * After any data loads/reads, the raw XML Document is available for further custom processing.
25975 * @type XMLDocument
25977 this.xmlData = doc;
25978 var root = doc.documentElement || doc;
25979 var q = Roo.DomQuery;
25980 var recordType = this.recordType, fields = recordType.prototype.fields;
25981 var sid = this.meta.id;
25982 var totalRecords = 0, success = true;
25983 if(this.meta.totalRecords){
25984 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
25987 if(this.meta.success){
25988 var sv = q.selectValue(this.meta.success, root, true);
25989 success = sv !== false && sv !== 'false';
25992 var ns = q.select(this.meta.record, root);
25993 for(var i = 0, len = ns.length; i < len; i++) {
25996 var id = sid ? q.selectValue(sid, n) : undefined;
25997 for(var j = 0, jlen = fields.length; j < jlen; j++){
25998 var f = fields.items[j];
25999 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
26001 values[f.name] = v;
26003 var record = new recordType(values, id);
26005 records[records.length] = record;
26011 totalRecords : totalRecords || records.length
26016 * Ext JS Library 1.1.1
26017 * Copyright(c) 2006-2007, Ext JS, LLC.
26019 * Originally Released Under LGPL - original licence link has changed is not relivant.
26022 * <script type="text/javascript">
26026 * @class Roo.data.ArrayReader
26027 * @extends Roo.data.DataReader
26028 * Data reader class to create an Array of Roo.data.Record objects from an Array.
26029 * Each element of that Array represents a row of data fields. The
26030 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
26031 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
26035 var RecordDef = Roo.data.Record.create([
26036 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
26037 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
26039 var myReader = new Roo.data.ArrayReader({
26040 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
26044 * This would consume an Array like this:
26046 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
26050 * Create a new JsonReader
26051 * @param {Object} meta Metadata configuration options.
26052 * @param {Object|Array} recordType Either an Array of field definition objects
26054 * @cfg {Array} fields Array of field definition objects
26055 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
26056 * as specified to {@link Roo.data.Record#create},
26057 * or an {@link Roo.data.Record} object
26060 * created using {@link Roo.data.Record#create}.
26062 Roo.data.ArrayReader = function(meta, recordType)
26064 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26067 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
26070 * Create a data block containing Roo.data.Records from an XML document.
26071 * @param {Object} o An Array of row objects which represents the dataset.
26072 * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
26073 * a cache of Roo.data.Records.
26075 readRecords : function(o)
26077 var sid = this.meta ? this.meta.id : null;
26078 var recordType = this.recordType, fields = recordType.prototype.fields;
26081 for(var i = 0; i < root.length; i++){
26084 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
26085 for(var j = 0, jlen = fields.length; j < jlen; j++){
26086 var f = fields.items[j];
26087 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
26088 var v = n[k] !== undefined ? n[k] : f.defaultValue;
26090 values[f.name] = v;
26092 var record = new recordType(values, id);
26094 records[records.length] = record;
26098 totalRecords : records.length
26101 // used when loading children.. @see loadDataFromChildren
26102 toLoadData: function(rec)
26104 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
26105 return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
26112 * Ext JS Library 1.1.1
26113 * Copyright(c) 2006-2007, Ext JS, LLC.
26115 * Originally Released Under LGPL - original licence link has changed is not relivant.
26118 * <script type="text/javascript">
26123 * @class Roo.data.Tree
26124 * @extends Roo.util.Observable
26125 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
26126 * in the tree have most standard DOM functionality.
26128 * @param {Node} root (optional) The root node
26130 Roo.data.Tree = function(root){
26131 this.nodeHash = {};
26133 * The root node for this tree
26138 this.setRootNode(root);
26143 * Fires when a new child node is appended to a node in this tree.
26144 * @param {Tree} tree The owner tree
26145 * @param {Node} parent The parent node
26146 * @param {Node} node The newly appended node
26147 * @param {Number} index The index of the newly appended node
26152 * Fires when a child node is removed from a node in this tree.
26153 * @param {Tree} tree The owner tree
26154 * @param {Node} parent The parent node
26155 * @param {Node} node The child node removed
26160 * Fires when a node is moved to a new location in the tree
26161 * @param {Tree} tree The owner tree
26162 * @param {Node} node The node moved
26163 * @param {Node} oldParent The old parent of this node
26164 * @param {Node} newParent The new parent of this node
26165 * @param {Number} index The index it was moved to
26170 * Fires when a new child node is inserted in a node in this tree.
26171 * @param {Tree} tree The owner tree
26172 * @param {Node} parent The parent node
26173 * @param {Node} node The child node inserted
26174 * @param {Node} refNode The child node the node was inserted before
26178 * @event beforeappend
26179 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
26180 * @param {Tree} tree The owner tree
26181 * @param {Node} parent The parent node
26182 * @param {Node} node The child node to be appended
26184 "beforeappend" : true,
26186 * @event beforeremove
26187 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
26188 * @param {Tree} tree The owner tree
26189 * @param {Node} parent The parent node
26190 * @param {Node} node The child node to be removed
26192 "beforeremove" : true,
26194 * @event beforemove
26195 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
26196 * @param {Tree} tree The owner tree
26197 * @param {Node} node The node being moved
26198 * @param {Node} oldParent The parent of the node
26199 * @param {Node} newParent The new parent the node is moving to
26200 * @param {Number} index The index it is being moved to
26202 "beforemove" : true,
26204 * @event beforeinsert
26205 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
26206 * @param {Tree} tree The owner tree
26207 * @param {Node} parent The parent node
26208 * @param {Node} node The child node to be inserted
26209 * @param {Node} refNode The child node the node is being inserted before
26211 "beforeinsert" : true
26214 Roo.data.Tree.superclass.constructor.call(this);
26217 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
26218 pathSeparator: "/",
26220 proxyNodeEvent : function(){
26221 return this.fireEvent.apply(this, arguments);
26225 * Returns the root node for this tree.
26228 getRootNode : function(){
26233 * Sets the root node for this tree.
26234 * @param {Node} node
26237 setRootNode : function(node){
26239 node.ownerTree = this;
26240 node.isRoot = true;
26241 this.registerNode(node);
26246 * Gets a node in this tree by its id.
26247 * @param {String} id
26250 getNodeById : function(id){
26251 return this.nodeHash[id];
26254 registerNode : function(node){
26255 this.nodeHash[node.id] = node;
26258 unregisterNode : function(node){
26259 delete this.nodeHash[node.id];
26262 toString : function(){
26263 return "[Tree"+(this.id?" "+this.id:"")+"]";
26268 * @class Roo.data.Node
26269 * @extends Roo.util.Observable
26270 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
26271 * @cfg {String} id The id for this node. If one is not specified, one is generated.
26273 * @param {Object} attributes The attributes/config for the node
26275 Roo.data.Node = function(attributes){
26277 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
26280 this.attributes = attributes || {};
26281 this.leaf = this.attributes.leaf;
26283 * The node id. @type String
26285 this.id = this.attributes.id;
26287 this.id = Roo.id(null, "ynode-");
26288 this.attributes.id = this.id;
26293 * All child nodes of this node. @type Array
26295 this.childNodes = [];
26296 if(!this.childNodes.indexOf){ // indexOf is a must
26297 this.childNodes.indexOf = function(o){
26298 for(var i = 0, len = this.length; i < len; i++){
26307 * The parent node for this node. @type Node
26309 this.parentNode = null;
26311 * The first direct child node of this node, or null if this node has no child nodes. @type Node
26313 this.firstChild = null;
26315 * The last direct child node of this node, or null if this node has no child nodes. @type Node
26317 this.lastChild = null;
26319 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
26321 this.previousSibling = null;
26323 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
26325 this.nextSibling = null;
26330 * Fires when a new child node is appended
26331 * @param {Tree} tree The owner tree
26332 * @param {Node} this This node
26333 * @param {Node} node The newly appended node
26334 * @param {Number} index The index of the newly appended node
26339 * Fires when a child node is removed
26340 * @param {Tree} tree The owner tree
26341 * @param {Node} this This node
26342 * @param {Node} node The removed node
26347 * Fires when this node is moved to a new location in the tree
26348 * @param {Tree} tree The owner tree
26349 * @param {Node} this This node
26350 * @param {Node} oldParent The old parent of this node
26351 * @param {Node} newParent The new parent of this node
26352 * @param {Number} index The index it was moved to
26357 * Fires when a new child node is inserted.
26358 * @param {Tree} tree The owner tree
26359 * @param {Node} this This node
26360 * @param {Node} node The child node inserted
26361 * @param {Node} refNode The child node the node was inserted before
26365 * @event beforeappend
26366 * Fires before a new child is appended, return false to cancel the append.
26367 * @param {Tree} tree The owner tree
26368 * @param {Node} this This node
26369 * @param {Node} node The child node to be appended
26371 "beforeappend" : true,
26373 * @event beforeremove
26374 * Fires before a child is removed, return false to cancel the remove.
26375 * @param {Tree} tree The owner tree
26376 * @param {Node} this This node
26377 * @param {Node} node The child node to be removed
26379 "beforeremove" : true,
26381 * @event beforemove
26382 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
26383 * @param {Tree} tree The owner tree
26384 * @param {Node} this This node
26385 * @param {Node} oldParent The parent of this node
26386 * @param {Node} newParent The new parent this node is moving to
26387 * @param {Number} index The index it is being moved to
26389 "beforemove" : true,
26391 * @event beforeinsert
26392 * Fires before a new child is inserted, return false to cancel the insert.
26393 * @param {Tree} tree The owner tree
26394 * @param {Node} this This node
26395 * @param {Node} node The child node to be inserted
26396 * @param {Node} refNode The child node the node is being inserted before
26398 "beforeinsert" : true
26400 this.listeners = this.attributes.listeners;
26401 Roo.data.Node.superclass.constructor.call(this);
26404 Roo.extend(Roo.data.Node, Roo.util.Observable, {
26405 fireEvent : function(evtName){
26406 // first do standard event for this node
26407 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
26410 // then bubble it up to the tree if the event wasn't cancelled
26411 var ot = this.getOwnerTree();
26413 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
26421 * Returns true if this node is a leaf
26422 * @return {Boolean}
26424 isLeaf : function(){
26425 return this.leaf === true;
26429 setFirstChild : function(node){
26430 this.firstChild = node;
26434 setLastChild : function(node){
26435 this.lastChild = node;
26440 * Returns true if this node is the last child of its parent
26441 * @return {Boolean}
26443 isLast : function(){
26444 return (!this.parentNode ? true : this.parentNode.lastChild == this);
26448 * Returns true if this node is the first child of its parent
26449 * @return {Boolean}
26451 isFirst : function(){
26452 return (!this.parentNode ? true : this.parentNode.firstChild == this);
26455 hasChildNodes : function(){
26456 return !this.isLeaf() && this.childNodes.length > 0;
26460 * Insert node(s) as the last child node of this node.
26461 * @param {Node/Array} node The node or Array of nodes to append
26462 * @return {Node} The appended node if single append, or null if an array was passed
26464 appendChild : function(node){
26466 if(node instanceof Array){
26468 }else if(arguments.length > 1){
26472 // if passed an array or multiple args do them one by one
26474 for(var i = 0, len = multi.length; i < len; i++) {
26475 this.appendChild(multi[i]);
26478 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
26481 var index = this.childNodes.length;
26482 var oldParent = node.parentNode;
26483 // it's a move, make sure we move it cleanly
26485 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
26488 oldParent.removeChild(node);
26491 index = this.childNodes.length;
26493 this.setFirstChild(node);
26495 this.childNodes.push(node);
26496 node.parentNode = this;
26497 var ps = this.childNodes[index-1];
26499 node.previousSibling = ps;
26500 ps.nextSibling = node;
26502 node.previousSibling = null;
26504 node.nextSibling = null;
26505 this.setLastChild(node);
26506 node.setOwnerTree(this.getOwnerTree());
26507 this.fireEvent("append", this.ownerTree, this, node, index);
26508 if(this.ownerTree) {
26509 this.ownerTree.fireEvent("appendnode", this, node, index);
26512 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
26519 * Removes a child node from this node.
26520 * @param {Node} node The node to remove
26521 * @return {Node} The removed node
26523 removeChild : function(node){
26524 var index = this.childNodes.indexOf(node);
26528 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
26532 // remove it from childNodes collection
26533 this.childNodes.splice(index, 1);
26536 if(node.previousSibling){
26537 node.previousSibling.nextSibling = node.nextSibling;
26539 if(node.nextSibling){
26540 node.nextSibling.previousSibling = node.previousSibling;
26543 // update child refs
26544 if(this.firstChild == node){
26545 this.setFirstChild(node.nextSibling);
26547 if(this.lastChild == node){
26548 this.setLastChild(node.previousSibling);
26551 node.setOwnerTree(null);
26552 // clear any references from the node
26553 node.parentNode = null;
26554 node.previousSibling = null;
26555 node.nextSibling = null;
26556 this.fireEvent("remove", this.ownerTree, this, node);
26561 * Inserts the first node before the second node in this nodes childNodes collection.
26562 * @param {Node} node The node to insert
26563 * @param {Node} refNode The node to insert before (if null the node is appended)
26564 * @return {Node} The inserted node
26566 insertBefore : function(node, refNode){
26567 if(!refNode){ // like standard Dom, refNode can be null for append
26568 return this.appendChild(node);
26571 if(node == refNode){
26575 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
26578 var index = this.childNodes.indexOf(refNode);
26579 var oldParent = node.parentNode;
26580 var refIndex = index;
26582 // when moving internally, indexes will change after remove
26583 if(oldParent == this && this.childNodes.indexOf(node) < index){
26587 // it's a move, make sure we move it cleanly
26589 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
26592 oldParent.removeChild(node);
26595 this.setFirstChild(node);
26597 this.childNodes.splice(refIndex, 0, node);
26598 node.parentNode = this;
26599 var ps = this.childNodes[refIndex-1];
26601 node.previousSibling = ps;
26602 ps.nextSibling = node;
26604 node.previousSibling = null;
26606 node.nextSibling = refNode;
26607 refNode.previousSibling = node;
26608 node.setOwnerTree(this.getOwnerTree());
26609 this.fireEvent("insert", this.ownerTree, this, node, refNode);
26611 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
26617 * Returns the child node at the specified index.
26618 * @param {Number} index
26621 item : function(index){
26622 return this.childNodes[index];
26626 * Replaces one child node in this node with another.
26627 * @param {Node} newChild The replacement node
26628 * @param {Node} oldChild The node to replace
26629 * @return {Node} The replaced node
26631 replaceChild : function(newChild, oldChild){
26632 this.insertBefore(newChild, oldChild);
26633 this.removeChild(oldChild);
26638 * Returns the index of a child node
26639 * @param {Node} node
26640 * @return {Number} The index of the node or -1 if it was not found
26642 indexOf : function(child){
26643 return this.childNodes.indexOf(child);
26647 * Returns the tree this node is in.
26650 getOwnerTree : function(){
26651 // if it doesn't have one, look for one
26652 if(!this.ownerTree){
26656 this.ownerTree = p.ownerTree;
26662 return this.ownerTree;
26666 * Returns depth of this node (the root node has a depth of 0)
26669 getDepth : function(){
26672 while(p.parentNode){
26680 setOwnerTree : function(tree){
26681 // if it's move, we need to update everyone
26682 if(tree != this.ownerTree){
26683 if(this.ownerTree){
26684 this.ownerTree.unregisterNode(this);
26686 this.ownerTree = tree;
26687 var cs = this.childNodes;
26688 for(var i = 0, len = cs.length; i < len; i++) {
26689 cs[i].setOwnerTree(tree);
26692 tree.registerNode(this);
26698 * Returns the path for this node. The path can be used to expand or select this node programmatically.
26699 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
26700 * @return {String} The path
26702 getPath : function(attr){
26703 attr = attr || "id";
26704 var p = this.parentNode;
26705 var b = [this.attributes[attr]];
26707 b.unshift(p.attributes[attr]);
26710 var sep = this.getOwnerTree().pathSeparator;
26711 return sep + b.join(sep);
26715 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
26716 * function call will be the scope provided or the current node. The arguments to the function
26717 * will be the args provided or the current node. If the function returns false at any point,
26718 * the bubble is stopped.
26719 * @param {Function} fn The function to call
26720 * @param {Object} scope (optional) The scope of the function (defaults to current node)
26721 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
26723 bubble : function(fn, scope, args){
26726 if(fn.call(scope || p, args || p) === false){
26734 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
26735 * function call will be the scope provided or the current node. The arguments to the function
26736 * will be the args provided or the current node. If the function returns false at any point,
26737 * the cascade is stopped on that branch.
26738 * @param {Function} fn The function to call
26739 * @param {Object} scope (optional) The scope of the function (defaults to current node)
26740 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
26742 cascade : function(fn, scope, args){
26743 if(fn.call(scope || this, args || this) !== false){
26744 var cs = this.childNodes;
26745 for(var i = 0, len = cs.length; i < len; i++) {
26746 cs[i].cascade(fn, scope, args);
26752 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
26753 * function call will be the scope provided or the current node. The arguments to the function
26754 * will be the args provided or the current node. If the function returns false at any point,
26755 * the iteration stops.
26756 * @param {Function} fn The function to call
26757 * @param {Object} scope (optional) The scope of the function (defaults to current node)
26758 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
26760 eachChild : function(fn, scope, args){
26761 var cs = this.childNodes;
26762 for(var i = 0, len = cs.length; i < len; i++) {
26763 if(fn.call(scope || this, args || cs[i]) === false){
26770 * Finds the first child that has the attribute with the specified value.
26771 * @param {String} attribute The attribute name
26772 * @param {Mixed} value The value to search for
26773 * @return {Node} The found child or null if none was found
26775 findChild : function(attribute, value){
26776 var cs = this.childNodes;
26777 for(var i = 0, len = cs.length; i < len; i++) {
26778 if(cs[i].attributes[attribute] == value){
26786 * Finds the first child by a custom function. The child matches if the function passed
26788 * @param {Function} fn
26789 * @param {Object} scope (optional)
26790 * @return {Node} The found child or null if none was found
26792 findChildBy : function(fn, scope){
26793 var cs = this.childNodes;
26794 for(var i = 0, len = cs.length; i < len; i++) {
26795 if(fn.call(scope||cs[i], cs[i]) === true){
26803 * Sorts this nodes children using the supplied sort function
26804 * @param {Function} fn
26805 * @param {Object} scope (optional)
26807 sort : function(fn, scope){
26808 var cs = this.childNodes;
26809 var len = cs.length;
26811 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
26813 for(var i = 0; i < len; i++){
26815 n.previousSibling = cs[i-1];
26816 n.nextSibling = cs[i+1];
26818 this.setFirstChild(n);
26821 this.setLastChild(n);
26828 * Returns true if this node is an ancestor (at any point) of the passed node.
26829 * @param {Node} node
26830 * @return {Boolean}
26832 contains : function(node){
26833 return node.isAncestor(this);
26837 * Returns true if the passed node is an ancestor (at any point) of this node.
26838 * @param {Node} node
26839 * @return {Boolean}
26841 isAncestor : function(node){
26842 var p = this.parentNode;
26852 toString : function(){
26853 return "[Node"+(this.id?" "+this.id:"")+"]";
26857 * Ext JS Library 1.1.1
26858 * Copyright(c) 2006-2007, Ext JS, LLC.
26860 * Originally Released Under LGPL - original licence link has changed is not relivant.
26863 * <script type="text/javascript">
26868 * @class Roo.Shadow
26869 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
26870 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
26871 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
26873 * Create a new Shadow
26874 * @param {Object} config The config object
26876 Roo.Shadow = function(config){
26877 Roo.apply(this, config);
26878 if(typeof this.mode != "string"){
26879 this.mode = this.defaultMode;
26881 var o = this.offset, a = {h: 0};
26882 var rad = Math.floor(this.offset/2);
26883 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
26889 a.l -= this.offset + rad;
26890 a.t -= this.offset + rad;
26901 a.l -= (this.offset - rad);
26902 a.t -= this.offset + rad;
26904 a.w -= (this.offset - rad)*2;
26915 a.l -= (this.offset - rad);
26916 a.t -= (this.offset - rad);
26918 a.w -= (this.offset + rad + 1);
26919 a.h -= (this.offset + rad);
26928 Roo.Shadow.prototype = {
26930 * @cfg {String} mode
26931 * The shadow display mode. Supports the following options:<br />
26932 * sides: Shadow displays on both sides and bottom only<br />
26933 * frame: Shadow displays equally on all four sides<br />
26934 * drop: Traditional bottom-right drop shadow (default)
26938 * @cfg {String} offset
26939 * The number of pixels to offset the shadow from the element (defaults to 4)
26944 defaultMode: "drop",
26947 * Displays the shadow under the target element
26948 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
26950 show : function(target){
26951 target = Roo.get(target);
26953 this.el = Roo.Shadow.Pool.pull();
26954 if(this.el.dom.nextSibling != target.dom){
26955 this.el.insertBefore(target);
26958 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
26960 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
26963 target.getLeft(true),
26964 target.getTop(true),
26968 this.el.dom.style.display = "block";
26972 * Returns true if the shadow is visible, else false
26974 isVisible : function(){
26975 return this.el ? true : false;
26979 * Direct alignment when values are already available. Show must be called at least once before
26980 * calling this method to ensure it is initialized.
26981 * @param {Number} left The target element left position
26982 * @param {Number} top The target element top position
26983 * @param {Number} width The target element width
26984 * @param {Number} height The target element height
26986 realign : function(l, t, w, h){
26990 var a = this.adjusts, d = this.el.dom, s = d.style;
26992 s.left = (l+a.l)+"px";
26993 s.top = (t+a.t)+"px";
26994 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
26996 if(s.width != sws || s.height != shs){
27000 var cn = d.childNodes;
27001 var sww = Math.max(0, (sw-12))+"px";
27002 cn[0].childNodes[1].style.width = sww;
27003 cn[1].childNodes[1].style.width = sww;
27004 cn[2].childNodes[1].style.width = sww;
27005 cn[1].style.height = Math.max(0, (sh-12))+"px";
27011 * Hides this shadow
27015 this.el.dom.style.display = "none";
27016 Roo.Shadow.Pool.push(this.el);
27022 * Adjust the z-index of this shadow
27023 * @param {Number} zindex The new z-index
27025 setZIndex : function(z){
27028 this.el.setStyle("z-index", z);
27033 // Private utility class that manages the internal Shadow cache
27034 Roo.Shadow.Pool = function(){
27036 var markup = Roo.isIE ?
27037 '<div class="x-ie-shadow"></div>' :
27038 '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';
27041 var sh = p.shift();
27043 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
27044 sh.autoBoxAdjust = false;
27049 push : function(sh){
27055 * Ext JS Library 1.1.1
27056 * Copyright(c) 2006-2007, Ext JS, LLC.
27058 * Originally Released Under LGPL - original licence link has changed is not relivant.
27061 * <script type="text/javascript">
27066 * @class Roo.SplitBar
27067 * @extends Roo.util.Observable
27068 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
27072 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
27073 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
27074 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
27075 split.minSize = 100;
27076 split.maxSize = 600;
27077 split.animate = true;
27078 split.on('moved', splitterMoved);
27081 * Create a new SplitBar
27082 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
27083 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
27084 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27085 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
27086 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
27087 position of the SplitBar).
27089 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
27092 this.el = Roo.get(dragElement, true);
27093 this.el.dom.unselectable = "on";
27095 this.resizingEl = Roo.get(resizingElement, true);
27099 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27100 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
27103 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
27106 * The minimum size of the resizing element. (Defaults to 0)
27112 * The maximum size of the resizing element. (Defaults to 2000)
27115 this.maxSize = 2000;
27118 * Whether to animate the transition to the new size
27121 this.animate = false;
27124 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
27127 this.useShim = false;
27132 if(!existingProxy){
27134 this.proxy = Roo.SplitBar.createProxy(this.orientation);
27136 this.proxy = Roo.get(existingProxy).dom;
27139 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
27142 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
27145 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
27148 this.dragSpecs = {};
27151 * @private The adapter to use to positon and resize elements
27153 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
27154 this.adapter.init(this);
27156 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27158 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
27159 this.el.addClass("x-splitbar-h");
27162 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
27163 this.el.addClass("x-splitbar-v");
27169 * Fires when the splitter is moved (alias for {@link #event-moved})
27170 * @param {Roo.SplitBar} this
27171 * @param {Number} newSize the new width or height
27176 * Fires when the splitter is moved
27177 * @param {Roo.SplitBar} this
27178 * @param {Number} newSize the new width or height
27182 * @event beforeresize
27183 * Fires before the splitter is dragged
27184 * @param {Roo.SplitBar} this
27186 "beforeresize" : true,
27188 "beforeapply" : true
27191 Roo.util.Observable.call(this);
27194 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
27195 onStartProxyDrag : function(x, y){
27196 this.fireEvent("beforeresize", this);
27198 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
27200 o.enableDisplayMode("block");
27201 // all splitbars share the same overlay
27202 Roo.SplitBar.prototype.overlay = o;
27204 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
27205 this.overlay.show();
27206 Roo.get(this.proxy).setDisplayed("block");
27207 var size = this.adapter.getElementSize(this);
27208 this.activeMinSize = this.getMinimumSize();;
27209 this.activeMaxSize = this.getMaximumSize();;
27210 var c1 = size - this.activeMinSize;
27211 var c2 = Math.max(this.activeMaxSize - size, 0);
27212 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27213 this.dd.resetConstraints();
27214 this.dd.setXConstraint(
27215 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
27216 this.placement == Roo.SplitBar.LEFT ? c2 : c1
27218 this.dd.setYConstraint(0, 0);
27220 this.dd.resetConstraints();
27221 this.dd.setXConstraint(0, 0);
27222 this.dd.setYConstraint(
27223 this.placement == Roo.SplitBar.TOP ? c1 : c2,
27224 this.placement == Roo.SplitBar.TOP ? c2 : c1
27227 this.dragSpecs.startSize = size;
27228 this.dragSpecs.startPoint = [x, y];
27229 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
27233 * @private Called after the drag operation by the DDProxy
27235 onEndProxyDrag : function(e){
27236 Roo.get(this.proxy).setDisplayed(false);
27237 var endPoint = Roo.lib.Event.getXY(e);
27239 this.overlay.hide();
27242 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27243 newSize = this.dragSpecs.startSize +
27244 (this.placement == Roo.SplitBar.LEFT ?
27245 endPoint[0] - this.dragSpecs.startPoint[0] :
27246 this.dragSpecs.startPoint[0] - endPoint[0]
27249 newSize = this.dragSpecs.startSize +
27250 (this.placement == Roo.SplitBar.TOP ?
27251 endPoint[1] - this.dragSpecs.startPoint[1] :
27252 this.dragSpecs.startPoint[1] - endPoint[1]
27255 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
27256 if(newSize != this.dragSpecs.startSize){
27257 if(this.fireEvent('beforeapply', this, newSize) !== false){
27258 this.adapter.setElementSize(this, newSize);
27259 this.fireEvent("moved", this, newSize);
27260 this.fireEvent("resize", this, newSize);
27266 * Get the adapter this SplitBar uses
27267 * @return The adapter object
27269 getAdapter : function(){
27270 return this.adapter;
27274 * Set the adapter this SplitBar uses
27275 * @param {Object} adapter A SplitBar adapter object
27277 setAdapter : function(adapter){
27278 this.adapter = adapter;
27279 this.adapter.init(this);
27283 * Gets the minimum size for the resizing element
27284 * @return {Number} The minimum size
27286 getMinimumSize : function(){
27287 return this.minSize;
27291 * Sets the minimum size for the resizing element
27292 * @param {Number} minSize The minimum size
27294 setMinimumSize : function(minSize){
27295 this.minSize = minSize;
27299 * Gets the maximum size for the resizing element
27300 * @return {Number} The maximum size
27302 getMaximumSize : function(){
27303 return this.maxSize;
27307 * Sets the maximum size for the resizing element
27308 * @param {Number} maxSize The maximum size
27310 setMaximumSize : function(maxSize){
27311 this.maxSize = maxSize;
27315 * Sets the initialize size for the resizing element
27316 * @param {Number} size The initial size
27318 setCurrentSize : function(size){
27319 var oldAnimate = this.animate;
27320 this.animate = false;
27321 this.adapter.setElementSize(this, size);
27322 this.animate = oldAnimate;
27326 * Destroy this splitbar.
27327 * @param {Boolean} removeEl True to remove the element
27329 destroy : function(removeEl){
27331 this.shim.remove();
27334 this.proxy.parentNode.removeChild(this.proxy);
27342 * @private static Create our own proxy element element. So it will be the same same size on all browsers, we won't use borders. Instead we use a background color.
27344 Roo.SplitBar.createProxy = function(dir){
27345 var proxy = new Roo.Element(document.createElement("div"));
27346 proxy.unselectable();
27347 var cls = 'x-splitbar-proxy';
27348 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
27349 document.body.appendChild(proxy.dom);
27354 * @class Roo.SplitBar.BasicLayoutAdapter
27355 * Default Adapter. It assumes the splitter and resizing element are not positioned
27356 * elements and only gets/sets the width of the element. Generally used for table based layouts.
27358 Roo.SplitBar.BasicLayoutAdapter = function(){
27361 Roo.SplitBar.BasicLayoutAdapter.prototype = {
27362 // do nothing for now
27363 init : function(s){
27367 * Called before drag operations to get the current size of the resizing element.
27368 * @param {Roo.SplitBar} s The SplitBar using this adapter
27370 getElementSize : function(s){
27371 if(s.orientation == Roo.SplitBar.HORIZONTAL){
27372 return s.resizingEl.getWidth();
27374 return s.resizingEl.getHeight();
27379 * Called after drag operations to set the size of the resizing element.
27380 * @param {Roo.SplitBar} s The SplitBar using this adapter
27381 * @param {Number} newSize The new size to set
27382 * @param {Function} onComplete A function to be invoked when resizing is complete
27384 setElementSize : function(s, newSize, onComplete){
27385 if(s.orientation == Roo.SplitBar.HORIZONTAL){
27387 s.resizingEl.setWidth(newSize);
27389 onComplete(s, newSize);
27392 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
27397 s.resizingEl.setHeight(newSize);
27399 onComplete(s, newSize);
27402 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
27409 *@class Roo.SplitBar.AbsoluteLayoutAdapter
27410 * @extends Roo.SplitBar.BasicLayoutAdapter
27411 * Adapter that moves the splitter element to align with the resized sizing element.
27412 * Used with an absolute positioned SplitBar.
27413 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
27414 * document.body, make sure you assign an id to the body element.
27416 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
27417 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
27418 this.container = Roo.get(container);
27421 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
27422 init : function(s){
27423 this.basic.init(s);
27426 getElementSize : function(s){
27427 return this.basic.getElementSize(s);
27430 setElementSize : function(s, newSize, onComplete){
27431 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
27434 moveSplitter : function(s){
27435 var yes = Roo.SplitBar;
27436 switch(s.placement){
27438 s.el.setX(s.resizingEl.getRight());
27441 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
27444 s.el.setY(s.resizingEl.getBottom());
27447 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
27454 * Orientation constant - Create a vertical SplitBar
27458 Roo.SplitBar.VERTICAL = 1;
27461 * Orientation constant - Create a horizontal SplitBar
27465 Roo.SplitBar.HORIZONTAL = 2;
27468 * Placement constant - The resizing element is to the left of the splitter element
27472 Roo.SplitBar.LEFT = 1;
27475 * Placement constant - The resizing element is to the right of the splitter element
27479 Roo.SplitBar.RIGHT = 2;
27482 * Placement constant - The resizing element is positioned above the splitter element
27486 Roo.SplitBar.TOP = 3;
27489 * Placement constant - The resizing element is positioned under splitter element
27493 Roo.SplitBar.BOTTOM = 4;
27496 * Ext JS Library 1.1.1
27497 * Copyright(c) 2006-2007, Ext JS, LLC.
27499 * Originally Released Under LGPL - original licence link has changed is not relivant.
27502 * <script type="text/javascript">
27507 * @extends Roo.util.Observable
27508 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
27509 * This class also supports single and multi selection modes. <br>
27510 * Create a data model bound view:
27512 var store = new Roo.data.Store(...);
27514 var view = new Roo.View({
27516 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
27518 singleSelect: true,
27519 selectedClass: "ydataview-selected",
27523 // listen for node click?
27524 view.on("click", function(vw, index, node, e){
27525 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
27529 dataModel.load("foobar.xml");
27531 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
27533 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
27534 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
27536 * Note: old style constructor is still suported (container, template, config)
27539 * Create a new View
27540 * @param {Object} config The config object
27543 Roo.View = function(config, depreciated_tpl, depreciated_config){
27545 this.parent = false;
27547 if (typeof(depreciated_tpl) == 'undefined') {
27548 // new way.. - universal constructor.
27549 Roo.apply(this, config);
27550 this.el = Roo.get(this.el);
27553 this.el = Roo.get(config);
27554 this.tpl = depreciated_tpl;
27555 Roo.apply(this, depreciated_config);
27557 this.wrapEl = this.el.wrap().wrap();
27558 ///this.el = this.wrapEla.appendChild(document.createElement("div"));
27561 if(typeof(this.tpl) == "string"){
27562 this.tpl = new Roo.Template(this.tpl);
27564 // support xtype ctors..
27565 this.tpl = new Roo.factory(this.tpl, Roo);
27569 this.tpl.compile();
27574 * @event beforeclick
27575 * Fires before a click is processed. Returns false to cancel the default action.
27576 * @param {Roo.View} this
27577 * @param {Number} index The index of the target node
27578 * @param {HTMLElement} node The target node
27579 * @param {Roo.EventObject} e The raw event object
27581 "beforeclick" : true,
27584 * Fires when a template node is clicked.
27585 * @param {Roo.View} this
27586 * @param {Number} index The index of the target node
27587 * @param {HTMLElement} node The target node
27588 * @param {Roo.EventObject} e The raw event object
27593 * Fires when a template node is double clicked.
27594 * @param {Roo.View} this
27595 * @param {Number} index The index of the target node
27596 * @param {HTMLElement} node The target node
27597 * @param {Roo.EventObject} e The raw event object
27601 * @event contextmenu
27602 * Fires when a template node is right clicked.
27603 * @param {Roo.View} this
27604 * @param {Number} index The index of the target node
27605 * @param {HTMLElement} node The target node
27606 * @param {Roo.EventObject} e The raw event object
27608 "contextmenu" : true,
27610 * @event selectionchange
27611 * Fires when the selected nodes change.
27612 * @param {Roo.View} this
27613 * @param {Array} selections Array of the selected nodes
27615 "selectionchange" : true,
27618 * @event beforeselect
27619 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
27620 * @param {Roo.View} this
27621 * @param {HTMLElement} node The node to be selected
27622 * @param {Array} selections Array of currently selected nodes
27624 "beforeselect" : true,
27626 * @event preparedata
27627 * Fires on every row to render, to allow you to change the data.
27628 * @param {Roo.View} this
27629 * @param {Object} data to be rendered (change this)
27631 "preparedata" : true
27639 "click": this.onClick,
27640 "dblclick": this.onDblClick,
27641 "contextmenu": this.onContextMenu,
27645 this.selections = [];
27647 this.cmp = new Roo.CompositeElementLite([]);
27649 this.store = Roo.factory(this.store, Roo.data);
27650 this.setStore(this.store, true);
27653 if ( this.footer && this.footer.xtype) {
27655 var fctr = this.wrapEl.appendChild(document.createElement("div"));
27657 this.footer.dataSource = this.store;
27658 this.footer.container = fctr;
27659 this.footer = Roo.factory(this.footer, Roo);
27660 fctr.insertFirst(this.el);
27662 // this is a bit insane - as the paging toolbar seems to detach the el..
27663 // dom.parentNode.parentNode.parentNode
27664 // they get detached?
27668 Roo.View.superclass.constructor.call(this);
27673 Roo.extend(Roo.View, Roo.util.Observable, {
27676 * @cfg {Roo.data.Store} store Data store to load data from.
27681 * @cfg {String|Roo.Element} el The container element.
27686 * @cfg {String|Roo.Template} tpl The template used by this View
27690 * @cfg {String} dataName the named area of the template to use as the data area
27691 * Works with domtemplates roo-name="name"
27695 * @cfg {String} selectedClass The css class to add to selected nodes
27697 selectedClass : "x-view-selected",
27699 * @cfg {String} emptyText The empty text to show when nothing is loaded.
27704 * @cfg {String} text to display on mask (default Loading)
27708 * @cfg {Boolean} multiSelect Allow multiple selection
27710 multiSelect : false,
27712 * @cfg {Boolean} singleSelect Allow single selection
27714 singleSelect: false,
27717 * @cfg {Boolean} toggleSelect - selecting
27719 toggleSelect : false,
27722 * @cfg {Boolean} tickable - selecting
27727 * Returns the element this view is bound to.
27728 * @return {Roo.Element}
27730 getEl : function(){
27731 return this.wrapEl;
27737 * Refreshes the view. - called by datachanged on the store. - do not call directly.
27739 refresh : function(){
27740 //Roo.log('refresh');
27743 // if we are using something like 'domtemplate', then
27744 // the what gets used is:
27745 // t.applySubtemplate(NAME, data, wrapping data..)
27746 // the outer template then get' applied with
27747 // the store 'extra data'
27748 // and the body get's added to the
27749 // roo-name="data" node?
27750 // <span class='roo-tpl-{name}'></span> ?????
27754 this.clearSelections();
27755 this.el.update("");
27757 var records = this.store.getRange();
27758 if(records.length < 1) {
27760 // is this valid?? = should it render a template??
27762 this.el.update(this.emptyText);
27766 if (this.dataName) {
27767 this.el.update(t.apply(this.store.meta)); //????
27768 el = this.el.child('.roo-tpl-' + this.dataName);
27771 for(var i = 0, len = records.length; i < len; i++){
27772 var data = this.prepareData(records[i].data, i, records[i]);
27773 this.fireEvent("preparedata", this, data, i, records[i]);
27775 var d = Roo.apply({}, data);
27778 Roo.apply(d, {'roo-id' : Roo.id()});
27782 Roo.each(this.parent.item, function(item){
27783 if(item[_this.parent.valueField] != data[_this.parent.valueField]){
27786 Roo.apply(d, {'roo-data-checked' : 'checked'});
27790 html[html.length] = Roo.util.Format.trim(
27792 t.applySubtemplate(this.dataName, d, this.store.meta) :
27799 el.update(html.join(""));
27800 this.nodes = el.dom.childNodes;
27801 this.updateIndexes(0);
27806 * Function to override to reformat the data that is sent to
27807 * the template for each node.
27808 * DEPRICATED - use the preparedata event handler.
27809 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
27810 * a JSON object for an UpdateManager bound view).
27812 prepareData : function(data, index, record)
27814 this.fireEvent("preparedata", this, data, index, record);
27818 onUpdate : function(ds, record){
27819 // Roo.log('on update');
27820 this.clearSelections();
27821 var index = this.store.indexOf(record);
27822 var n = this.nodes[index];
27823 this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
27824 n.parentNode.removeChild(n);
27825 this.updateIndexes(index, index);
27831 onAdd : function(ds, records, index)
27833 //Roo.log(['on Add', ds, records, index] );
27834 this.clearSelections();
27835 if(this.nodes.length == 0){
27839 var n = this.nodes[index];
27840 for(var i = 0, len = records.length; i < len; i++){
27841 var d = this.prepareData(records[i].data, i, records[i]);
27843 this.tpl.insertBefore(n, d);
27846 this.tpl.append(this.el, d);
27849 this.updateIndexes(index);
27852 onRemove : function(ds, record, index){
27853 // Roo.log('onRemove');
27854 this.clearSelections();
27855 var el = this.dataName ?
27856 this.el.child('.roo-tpl-' + this.dataName) :
27859 el.dom.removeChild(this.nodes[index]);
27860 this.updateIndexes(index);
27864 * Refresh an individual node.
27865 * @param {Number} index
27867 refreshNode : function(index){
27868 this.onUpdate(this.store, this.store.getAt(index));
27871 updateIndexes : function(startIndex, endIndex){
27872 var ns = this.nodes;
27873 startIndex = startIndex || 0;
27874 endIndex = endIndex || ns.length - 1;
27875 for(var i = startIndex; i <= endIndex; i++){
27876 ns[i].nodeIndex = i;
27881 * Changes the data store this view uses and refresh the view.
27882 * @param {Store} store
27884 setStore : function(store, initial){
27885 if(!initial && this.store){
27886 this.store.un("datachanged", this.refresh);
27887 this.store.un("add", this.onAdd);
27888 this.store.un("remove", this.onRemove);
27889 this.store.un("update", this.onUpdate);
27890 this.store.un("clear", this.refresh);
27891 this.store.un("beforeload", this.onBeforeLoad);
27892 this.store.un("load", this.onLoad);
27893 this.store.un("loadexception", this.onLoad);
27897 store.on("datachanged", this.refresh, this);
27898 store.on("add", this.onAdd, this);
27899 store.on("remove", this.onRemove, this);
27900 store.on("update", this.onUpdate, this);
27901 store.on("clear", this.refresh, this);
27902 store.on("beforeload", this.onBeforeLoad, this);
27903 store.on("load", this.onLoad, this);
27904 store.on("loadexception", this.onLoad, this);
27912 * onbeforeLoad - masks the loading area.
27915 onBeforeLoad : function(store,opts)
27917 //Roo.log('onBeforeLoad');
27919 this.el.update("");
27921 this.el.mask(this.mask ? this.mask : "Loading" );
27923 onLoad : function ()
27930 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
27931 * @param {HTMLElement} node
27932 * @return {HTMLElement} The template node
27934 findItemFromChild : function(node){
27935 var el = this.dataName ?
27936 this.el.child('.roo-tpl-' + this.dataName,true) :
27939 if(!node || node.parentNode == el){
27942 var p = node.parentNode;
27943 while(p && p != el){
27944 if(p.parentNode == el){
27953 onClick : function(e){
27954 var item = this.findItemFromChild(e.getTarget());
27956 var index = this.indexOf(item);
27957 if(this.onItemClick(item, index, e) !== false){
27958 this.fireEvent("click", this, index, item, e);
27961 this.clearSelections();
27966 onContextMenu : function(e){
27967 var item = this.findItemFromChild(e.getTarget());
27969 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
27974 onDblClick : function(e){
27975 var item = this.findItemFromChild(e.getTarget());
27977 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
27981 onItemClick : function(item, index, e)
27983 if(this.fireEvent("beforeclick", this, index, item, e) === false){
27986 if (this.toggleSelect) {
27987 var m = this.isSelected(item) ? 'unselect' : 'select';
27990 _t[m](item, true, false);
27993 if(this.multiSelect || this.singleSelect){
27994 if(this.multiSelect && e.shiftKey && this.lastSelection){
27995 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
27997 this.select(item, this.multiSelect && e.ctrlKey);
27998 this.lastSelection = item;
28001 if(!this.tickable){
28002 e.preventDefault();
28010 * Get the number of selected nodes.
28013 getSelectionCount : function(){
28014 return this.selections.length;
28018 * Get the currently selected nodes.
28019 * @return {Array} An array of HTMLElements
28021 getSelectedNodes : function(){
28022 return this.selections;
28026 * Get the indexes of the selected nodes.
28029 getSelectedIndexes : function(){
28030 var indexes = [], s = this.selections;
28031 for(var i = 0, len = s.length; i < len; i++){
28032 indexes.push(s[i].nodeIndex);
28038 * Clear all selections
28039 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
28041 clearSelections : function(suppressEvent){
28042 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
28043 this.cmp.elements = this.selections;
28044 this.cmp.removeClass(this.selectedClass);
28045 this.selections = [];
28046 if(!suppressEvent){
28047 this.fireEvent("selectionchange", this, this.selections);
28053 * Returns true if the passed node is selected
28054 * @param {HTMLElement/Number} node The node or node index
28055 * @return {Boolean}
28057 isSelected : function(node){
28058 var s = this.selections;
28062 node = this.getNode(node);
28063 return s.indexOf(node) !== -1;
28068 * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
28069 * @param {Boolean} keepExisting (optional) true to keep existing selections
28070 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28072 select : function(nodeInfo, keepExisting, suppressEvent){
28073 if(nodeInfo instanceof Array){
28075 this.clearSelections(true);
28077 for(var i = 0, len = nodeInfo.length; i < len; i++){
28078 this.select(nodeInfo[i], true, true);
28082 var node = this.getNode(nodeInfo);
28083 if(!node || this.isSelected(node)){
28084 return; // already selected.
28087 this.clearSelections(true);
28090 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
28091 Roo.fly(node).addClass(this.selectedClass);
28092 this.selections.push(node);
28093 if(!suppressEvent){
28094 this.fireEvent("selectionchange", this, this.selections);
28102 * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
28103 * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
28104 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28106 unselect : function(nodeInfo, keepExisting, suppressEvent)
28108 if(nodeInfo instanceof Array){
28109 Roo.each(this.selections, function(s) {
28110 this.unselect(s, nodeInfo);
28114 var node = this.getNode(nodeInfo);
28115 if(!node || !this.isSelected(node)){
28116 //Roo.log("not selected");
28117 return; // not selected.
28121 Roo.each(this.selections, function(s) {
28123 Roo.fly(node).removeClass(this.selectedClass);
28130 this.selections= ns;
28131 this.fireEvent("selectionchange", this, this.selections);
28135 * Gets a template node.
28136 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28137 * @return {HTMLElement} The node or null if it wasn't found
28139 getNode : function(nodeInfo){
28140 if(typeof nodeInfo == "string"){
28141 return document.getElementById(nodeInfo);
28142 }else if(typeof nodeInfo == "number"){
28143 return this.nodes[nodeInfo];
28149 * Gets a range template nodes.
28150 * @param {Number} startIndex
28151 * @param {Number} endIndex
28152 * @return {Array} An array of nodes
28154 getNodes : function(start, end){
28155 var ns = this.nodes;
28156 start = start || 0;
28157 end = typeof end == "undefined" ? ns.length - 1 : end;
28160 for(var i = start; i <= end; i++){
28164 for(var i = start; i >= end; i--){
28172 * Finds the index of the passed node
28173 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28174 * @return {Number} The index of the node or -1
28176 indexOf : function(node){
28177 node = this.getNode(node);
28178 if(typeof node.nodeIndex == "number"){
28179 return node.nodeIndex;
28181 var ns = this.nodes;
28182 for(var i = 0, len = ns.length; i < len; i++){
28192 * Ext JS Library 1.1.1
28193 * Copyright(c) 2006-2007, Ext JS, LLC.
28195 * Originally Released Under LGPL - original licence link has changed is not relivant.
28198 * <script type="text/javascript">
28202 * @class Roo.JsonView
28203 * @extends Roo.View
28204 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
28206 var view = new Roo.JsonView({
28207 container: "my-element",
28208 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
28213 // listen for node click?
28214 view.on("click", function(vw, index, node, e){
28215 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
28218 // direct load of JSON data
28219 view.load("foobar.php");
28221 // Example from my blog list
28222 var tpl = new Roo.Template(
28223 '<div class="entry">' +
28224 '<a class="entry-title" href="{link}">{title}</a>' +
28225 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
28226 "</div><hr />"
28229 var moreView = new Roo.JsonView({
28230 container : "entry-list",
28234 moreView.on("beforerender", this.sortEntries, this);
28236 url: "/blog/get-posts.php",
28237 params: "allposts=true",
28238 text: "Loading Blog Entries..."
28242 * Note: old code is supported with arguments : (container, template, config)
28246 * Create a new JsonView
28248 * @param {Object} config The config object
28251 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
28254 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
28256 var um = this.el.getUpdateManager();
28257 um.setRenderer(this);
28258 um.on("update", this.onLoad, this);
28259 um.on("failure", this.onLoadException, this);
28262 * @event beforerender
28263 * Fires before rendering of the downloaded JSON data.
28264 * @param {Roo.JsonView} this
28265 * @param {Object} data The JSON data loaded
28269 * Fires when data is loaded.
28270 * @param {Roo.JsonView} this
28271 * @param {Object} data The JSON data loaded
28272 * @param {Object} response The raw Connect response object
28275 * @event loadexception
28276 * Fires when loading fails.
28277 * @param {Roo.JsonView} this
28278 * @param {Object} response The raw Connect response object
28281 'beforerender' : true,
28283 'loadexception' : true
28286 Roo.extend(Roo.JsonView, Roo.View, {
28288 * @type {String} The root property in the loaded JSON object that contains the data
28293 * Refreshes the view.
28295 refresh : function(){
28296 this.clearSelections();
28297 this.el.update("");
28299 var o = this.jsonData;
28300 if(o && o.length > 0){
28301 for(var i = 0, len = o.length; i < len; i++){
28302 var data = this.prepareData(o[i], i, o);
28303 html[html.length] = this.tpl.apply(data);
28306 html.push(this.emptyText);
28308 this.el.update(html.join(""));
28309 this.nodes = this.el.dom.childNodes;
28310 this.updateIndexes(0);
28314 * Performs an async HTTP request, and loads the JSON from the response. If <i>params</i> are specified it uses POST, otherwise it uses GET.
28315 * @param {Object/String/Function} url The URL for this request, or a function to call to get the URL, or a config object containing any of the following options:
28318 url: "your-url.php",
28319 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
28320 callback: yourFunction,
28321 scope: yourObject, //(optional scope)
28324 text: "Loading...",
28329 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
28330 * are respectively shorthand for <i>disableCaching</i>, <i>indicatorText</i>, and <i>loadScripts</i> and are used to set their associated property on this UpdateManager instance.
28331 * @param {String/Object} params (optional) The parameters to pass, as either a URL encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
28332 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
28333 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used URL. If true, it will not store the URL.
28336 var um = this.el.getUpdateManager();
28337 um.update.apply(um, arguments);
28340 // note - render is a standard framework call...
28341 // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
28342 render : function(el, response){
28344 this.clearSelections();
28345 this.el.update("");
28348 if (response != '') {
28349 o = Roo.util.JSON.decode(response.responseText);
28352 o = o[this.jsonRoot];
28358 * The current JSON data or null
28361 this.beforeRender();
28366 * Get the number of records in the current JSON dataset
28369 getCount : function(){
28370 return this.jsonData ? this.jsonData.length : 0;
28374 * Returns the JSON object for the specified node(s)
28375 * @param {HTMLElement/Array} node The node or an array of nodes
28376 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
28377 * you get the JSON object for the node
28379 getNodeData : function(node){
28380 if(node instanceof Array){
28382 for(var i = 0, len = node.length; i < len; i++){
28383 data.push(this.getNodeData(node[i]));
28387 return this.jsonData[this.indexOf(node)] || null;
28390 beforeRender : function(){
28391 this.snapshot = this.jsonData;
28393 this.sort.apply(this, this.sortInfo);
28395 this.fireEvent("beforerender", this, this.jsonData);
28398 onLoad : function(el, o){
28399 this.fireEvent("load", this, this.jsonData, o);
28402 onLoadException : function(el, o){
28403 this.fireEvent("loadexception", this, o);
28407 * Filter the data by a specific property.
28408 * @param {String} property A property on your JSON objects
28409 * @param {String/RegExp} value Either string that the property values
28410 * should start with, or a RegExp to test against the property
28412 filter : function(property, value){
28415 var ss = this.snapshot;
28416 if(typeof value == "string"){
28417 var vlen = value.length;
28419 this.clearFilter();
28422 value = value.toLowerCase();
28423 for(var i = 0, len = ss.length; i < len; i++){
28425 if(o[property].substr(0, vlen).toLowerCase() == value){
28429 } else if(value.exec){ // regex?
28430 for(var i = 0, len = ss.length; i < len; i++){
28432 if(value.test(o[property])){
28439 this.jsonData = data;
28445 * Filter by a function. The passed function will be called with each
28446 * object in the current dataset. If the function returns true the value is kept,
28447 * otherwise it is filtered.
28448 * @param {Function} fn
28449 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
28451 filterBy : function(fn, scope){
28454 var ss = this.snapshot;
28455 for(var i = 0, len = ss.length; i < len; i++){
28457 if(fn.call(scope || this, o)){
28461 this.jsonData = data;
28467 * Clears the current filter.
28469 clearFilter : function(){
28470 if(this.snapshot && this.jsonData != this.snapshot){
28471 this.jsonData = this.snapshot;
28478 * Sorts the data for this view and refreshes it.
28479 * @param {String} property A property on your JSON objects to sort on
28480 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
28481 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
28483 sort : function(property, dir, sortType){
28484 this.sortInfo = Array.prototype.slice.call(arguments, 0);
28487 var dsc = dir && dir.toLowerCase() == "desc";
28488 var f = function(o1, o2){
28489 var v1 = sortType ? sortType(o1[p]) : o1[p];
28490 var v2 = sortType ? sortType(o2[p]) : o2[p];
28493 return dsc ? +1 : -1;
28494 } else if(v1 > v2){
28495 return dsc ? -1 : +1;
28500 this.jsonData.sort(f);
28502 if(this.jsonData != this.snapshot){
28503 this.snapshot.sort(f);
28509 * Ext JS Library 1.1.1
28510 * Copyright(c) 2006-2007, Ext JS, LLC.
28512 * Originally Released Under LGPL - original licence link has changed is not relivant.
28515 * <script type="text/javascript">
28520 * @class Roo.ColorPalette
28521 * @extends Roo.Component
28522 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
28523 * Here's an example of typical usage:
28525 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
28526 cp.render('my-div');
28528 cp.on('select', function(palette, selColor){
28529 // do something with selColor
28533 * Create a new ColorPalette
28534 * @param {Object} config The config object
28536 Roo.ColorPalette = function(config){
28537 Roo.ColorPalette.superclass.constructor.call(this, config);
28541 * Fires when a color is selected
28542 * @param {ColorPalette} this
28543 * @param {String} color The 6-digit color hex code (without the # symbol)
28549 this.on("select", this.handler, this.scope, true);
28552 Roo.extend(Roo.ColorPalette, Roo.Component, {
28554 * @cfg {String} itemCls
28555 * The CSS class to apply to the containing element (defaults to "x-color-palette")
28557 itemCls : "x-color-palette",
28559 * @cfg {String} value
28560 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
28561 * the hex codes are case-sensitive.
28564 clickEvent:'click',
28566 ctype: "Roo.ColorPalette",
28569 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
28571 allowReselect : false,
28574 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
28575 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
28576 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
28577 * of colors with the width setting until the box is symmetrical.</p>
28578 * <p>You can override individual colors if needed:</p>
28580 var cp = new Roo.ColorPalette();
28581 cp.colors[0] = "FF0000"; // change the first box to red
28584 Or you can provide a custom array of your own for complete control:
28586 var cp = new Roo.ColorPalette();
28587 cp.colors = ["000000", "993300", "333300"];
28592 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
28593 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
28594 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
28595 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
28596 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
28600 onRender : function(container, position){
28601 var t = new Roo.MasterTemplate(
28602 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
28604 var c = this.colors;
28605 for(var i = 0, len = c.length; i < len; i++){
28608 var el = document.createElement("div");
28609 el.className = this.itemCls;
28611 container.dom.insertBefore(el, position);
28612 this.el = Roo.get(el);
28613 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
28614 if(this.clickEvent != 'click'){
28615 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
28620 afterRender : function(){
28621 Roo.ColorPalette.superclass.afterRender.call(this);
28623 var s = this.value;
28630 handleClick : function(e, t){
28631 e.preventDefault();
28632 if(!this.disabled){
28633 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
28634 this.select(c.toUpperCase());
28639 * Selects the specified color in the palette (fires the select event)
28640 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
28642 select : function(color){
28643 color = color.replace("#", "");
28644 if(color != this.value || this.allowReselect){
28647 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
28649 el.child("a.color-"+color).addClass("x-color-palette-sel");
28650 this.value = color;
28651 this.fireEvent("select", this, color);
28656 * Ext JS Library 1.1.1
28657 * Copyright(c) 2006-2007, Ext JS, LLC.
28659 * Originally Released Under LGPL - original licence link has changed is not relivant.
28662 * <script type="text/javascript">
28666 * @class Roo.DatePicker
28667 * @extends Roo.Component
28668 * Simple date picker class.
28670 * Create a new DatePicker
28671 * @param {Object} config The config object
28673 Roo.DatePicker = function(config){
28674 Roo.DatePicker.superclass.constructor.call(this, config);
28676 this.value = config && config.value ?
28677 config.value.clearTime() : new Date().clearTime();
28682 * Fires when a date is selected
28683 * @param {DatePicker} this
28684 * @param {Date} date The selected date
28688 * @event monthchange
28689 * Fires when the displayed month changes
28690 * @param {DatePicker} this
28691 * @param {Date} date The selected month
28693 'monthchange': true
28697 this.on("select", this.handler, this.scope || this);
28699 // build the disabledDatesRE
28700 if(!this.disabledDatesRE && this.disabledDates){
28701 var dd = this.disabledDates;
28703 for(var i = 0; i < dd.length; i++){
28705 if(i != dd.length-1) {
28709 this.disabledDatesRE = new RegExp(re + ")");
28713 Roo.extend(Roo.DatePicker, Roo.Component, {
28715 * @cfg {String} todayText
28716 * The text to display on the button that selects the current date (defaults to "Today")
28718 todayText : "Today",
28720 * @cfg {String} okText
28721 * The text to display on the ok button
28723 okText : " OK ", //   to give the user extra clicking room
28725 * @cfg {String} cancelText
28726 * The text to display on the cancel button
28728 cancelText : "Cancel",
28730 * @cfg {String} todayTip
28731 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
28733 todayTip : "{0} (Spacebar)",
28735 * @cfg {Date} minDate
28736 * Minimum allowable date (JavaScript date object, defaults to null)
28740 * @cfg {Date} maxDate
28741 * Maximum allowable date (JavaScript date object, defaults to null)
28745 * @cfg {String} minText
28746 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
28748 minText : "This date is before the minimum date",
28750 * @cfg {String} maxText
28751 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
28753 maxText : "This date is after the maximum date",
28755 * @cfg {String} format
28756 * The default date format string which can be overriden for localization support. The format must be
28757 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
28761 * @cfg {Array} disabledDays
28762 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
28764 disabledDays : null,
28766 * @cfg {String} disabledDaysText
28767 * The tooltip to display when the date falls on a disabled day (defaults to "")
28769 disabledDaysText : "",
28771 * @cfg {RegExp} disabledDatesRE
28772 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
28774 disabledDatesRE : null,
28776 * @cfg {String} disabledDatesText
28777 * The tooltip text to display when the date falls on a disabled date (defaults to "")
28779 disabledDatesText : "",
28781 * @cfg {Boolean} constrainToViewport
28782 * True to constrain the date picker to the viewport (defaults to true)
28784 constrainToViewport : true,
28786 * @cfg {Array} monthNames
28787 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
28789 monthNames : Date.monthNames,
28791 * @cfg {Array} dayNames
28792 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
28794 dayNames : Date.dayNames,
28796 * @cfg {String} nextText
28797 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
28799 nextText: 'Next Month (Control+Right)',
28801 * @cfg {String} prevText
28802 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
28804 prevText: 'Previous Month (Control+Left)',
28806 * @cfg {String} monthYearText
28807 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
28809 monthYearText: 'Choose a month (Control+Up/Down to move years)',
28811 * @cfg {Number} startDay
28812 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
28816 * @cfg {Bool} showClear
28817 * Show a clear button (usefull for date form elements that can be blank.)
28823 * Sets the value of the date field
28824 * @param {Date} value The date to set
28826 setValue : function(value){
28827 var old = this.value;
28829 if (typeof(value) == 'string') {
28831 value = Date.parseDate(value, this.format);
28834 value = new Date();
28837 this.value = value.clearTime(true);
28839 this.update(this.value);
28844 * Gets the current selected value of the date field
28845 * @return {Date} The selected date
28847 getValue : function(){
28852 focus : function(){
28854 this.update(this.activeDate);
28859 onRender : function(container, position){
28862 '<table cellspacing="0">',
28863 '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'"> </a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'"> </a></td></tr>',
28864 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
28865 var dn = this.dayNames;
28866 for(var i = 0; i < 7; i++){
28867 var d = this.startDay+i;
28871 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
28873 m[m.length] = "</tr></thead><tbody><tr>";
28874 for(var i = 0; i < 42; i++) {
28875 if(i % 7 == 0 && i != 0){
28876 m[m.length] = "</tr><tr>";
28878 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
28880 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
28881 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
28883 var el = document.createElement("div");
28884 el.className = "x-date-picker";
28885 el.innerHTML = m.join("");
28887 container.dom.insertBefore(el, position);
28889 this.el = Roo.get(el);
28890 this.eventEl = Roo.get(el.firstChild);
28892 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
28893 handler: this.showPrevMonth,
28895 preventDefault:true,
28899 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
28900 handler: this.showNextMonth,
28902 preventDefault:true,
28906 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
28908 this.monthPicker = this.el.down('div.x-date-mp');
28909 this.monthPicker.enableDisplayMode('block');
28911 var kn = new Roo.KeyNav(this.eventEl, {
28912 "left" : function(e){
28914 this.showPrevMonth() :
28915 this.update(this.activeDate.add("d", -1));
28918 "right" : function(e){
28920 this.showNextMonth() :
28921 this.update(this.activeDate.add("d", 1));
28924 "up" : function(e){
28926 this.showNextYear() :
28927 this.update(this.activeDate.add("d", -7));
28930 "down" : function(e){
28932 this.showPrevYear() :
28933 this.update(this.activeDate.add("d", 7));
28936 "pageUp" : function(e){
28937 this.showNextMonth();
28940 "pageDown" : function(e){
28941 this.showPrevMonth();
28944 "enter" : function(e){
28945 e.stopPropagation();
28952 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
28954 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
28956 this.el.unselectable();
28958 this.cells = this.el.select("table.x-date-inner tbody td");
28959 this.textNodes = this.el.query("table.x-date-inner tbody span");
28961 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
28963 tooltip: this.monthYearText
28966 this.mbtn.on('click', this.showMonthPicker, this);
28967 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
28970 var today = (new Date()).dateFormat(this.format);
28972 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
28973 if (this.showClear) {
28974 baseTb.add( new Roo.Toolbar.Fill());
28977 text: String.format(this.todayText, today),
28978 tooltip: String.format(this.todayTip, today),
28979 handler: this.selectToday,
28983 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
28986 if (this.showClear) {
28988 baseTb.add( new Roo.Toolbar.Fill());
28991 cls: 'x-btn-icon x-btn-clear',
28992 handler: function() {
28994 this.fireEvent("select", this, '');
29004 this.update(this.value);
29007 createMonthPicker : function(){
29008 if(!this.monthPicker.dom.firstChild){
29009 var buf = ['<table border="0" cellspacing="0">'];
29010 for(var i = 0; i < 6; i++){
29012 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
29013 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
29015 '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
29016 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
29020 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
29022 '</button><button type="button" class="x-date-mp-cancel">',
29024 '</button></td></tr>',
29027 this.monthPicker.update(buf.join(''));
29028 this.monthPicker.on('click', this.onMonthClick, this);
29029 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
29031 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
29032 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
29034 this.mpMonths.each(function(m, a, i){
29037 m.dom.xmonth = 5 + Math.round(i * .5);
29039 m.dom.xmonth = Math.round((i-1) * .5);
29045 showMonthPicker : function(){
29046 this.createMonthPicker();
29047 var size = this.el.getSize();
29048 this.monthPicker.setSize(size);
29049 this.monthPicker.child('table').setSize(size);
29051 this.mpSelMonth = (this.activeDate || this.value).getMonth();
29052 this.updateMPMonth(this.mpSelMonth);
29053 this.mpSelYear = (this.activeDate || this.value).getFullYear();
29054 this.updateMPYear(this.mpSelYear);
29056 this.monthPicker.slideIn('t', {duration:.2});
29059 updateMPYear : function(y){
29061 var ys = this.mpYears.elements;
29062 for(var i = 1; i <= 10; i++){
29063 var td = ys[i-1], y2;
29065 y2 = y + Math.round(i * .5);
29066 td.firstChild.innerHTML = y2;
29069 y2 = y - (5-Math.round(i * .5));
29070 td.firstChild.innerHTML = y2;
29073 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
29077 updateMPMonth : function(sm){
29078 this.mpMonths.each(function(m, a, i){
29079 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
29083 selectMPMonth: function(m){
29087 onMonthClick : function(e, t){
29089 var el = new Roo.Element(t), pn;
29090 if(el.is('button.x-date-mp-cancel')){
29091 this.hideMonthPicker();
29093 else if(el.is('button.x-date-mp-ok')){
29094 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29095 this.hideMonthPicker();
29097 else if(pn = el.up('td.x-date-mp-month', 2)){
29098 this.mpMonths.removeClass('x-date-mp-sel');
29099 pn.addClass('x-date-mp-sel');
29100 this.mpSelMonth = pn.dom.xmonth;
29102 else if(pn = el.up('td.x-date-mp-year', 2)){
29103 this.mpYears.removeClass('x-date-mp-sel');
29104 pn.addClass('x-date-mp-sel');
29105 this.mpSelYear = pn.dom.xyear;
29107 else if(el.is('a.x-date-mp-prev')){
29108 this.updateMPYear(this.mpyear-10);
29110 else if(el.is('a.x-date-mp-next')){
29111 this.updateMPYear(this.mpyear+10);
29115 onMonthDblClick : function(e, t){
29117 var el = new Roo.Element(t), pn;
29118 if(pn = el.up('td.x-date-mp-month', 2)){
29119 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
29120 this.hideMonthPicker();
29122 else if(pn = el.up('td.x-date-mp-year', 2)){
29123 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29124 this.hideMonthPicker();
29128 hideMonthPicker : function(disableAnim){
29129 if(this.monthPicker){
29130 if(disableAnim === true){
29131 this.monthPicker.hide();
29133 this.monthPicker.slideOut('t', {duration:.2});
29139 showPrevMonth : function(e){
29140 this.update(this.activeDate.add("mo", -1));
29144 showNextMonth : function(e){
29145 this.update(this.activeDate.add("mo", 1));
29149 showPrevYear : function(){
29150 this.update(this.activeDate.add("y", -1));
29154 showNextYear : function(){
29155 this.update(this.activeDate.add("y", 1));
29159 handleMouseWheel : function(e){
29160 var delta = e.getWheelDelta();
29162 this.showPrevMonth();
29164 } else if(delta < 0){
29165 this.showNextMonth();
29171 handleDateClick : function(e, t){
29173 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
29174 this.setValue(new Date(t.dateValue));
29175 this.fireEvent("select", this, this.value);
29180 selectToday : function(){
29181 this.setValue(new Date().clearTime());
29182 this.fireEvent("select", this, this.value);
29186 update : function(date)
29188 var vd = this.activeDate;
29189 this.activeDate = date;
29191 var t = date.getTime();
29192 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
29193 this.cells.removeClass("x-date-selected");
29194 this.cells.each(function(c){
29195 if(c.dom.firstChild.dateValue == t){
29196 c.addClass("x-date-selected");
29197 setTimeout(function(){
29198 try{c.dom.firstChild.focus();}catch(e){}
29207 var days = date.getDaysInMonth();
29208 var firstOfMonth = date.getFirstDateOfMonth();
29209 var startingPos = firstOfMonth.getDay()-this.startDay;
29211 if(startingPos <= this.startDay){
29215 var pm = date.add("mo", -1);
29216 var prevStart = pm.getDaysInMonth()-startingPos;
29218 var cells = this.cells.elements;
29219 var textEls = this.textNodes;
29220 days += startingPos;
29222 // convert everything to numbers so it's fast
29223 var day = 86400000;
29224 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
29225 var today = new Date().clearTime().getTime();
29226 var sel = date.clearTime().getTime();
29227 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
29228 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
29229 var ddMatch = this.disabledDatesRE;
29230 var ddText = this.disabledDatesText;
29231 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
29232 var ddaysText = this.disabledDaysText;
29233 var format = this.format;
29235 var setCellClass = function(cal, cell){
29237 var t = d.getTime();
29238 cell.firstChild.dateValue = t;
29240 cell.className += " x-date-today";
29241 cell.title = cal.todayText;
29244 cell.className += " x-date-selected";
29245 setTimeout(function(){
29246 try{cell.firstChild.focus();}catch(e){}
29251 cell.className = " x-date-disabled";
29252 cell.title = cal.minText;
29256 cell.className = " x-date-disabled";
29257 cell.title = cal.maxText;
29261 if(ddays.indexOf(d.getDay()) != -1){
29262 cell.title = ddaysText;
29263 cell.className = " x-date-disabled";
29266 if(ddMatch && format){
29267 var fvalue = d.dateFormat(format);
29268 if(ddMatch.test(fvalue)){
29269 cell.title = ddText.replace("%0", fvalue);
29270 cell.className = " x-date-disabled";
29276 for(; i < startingPos; i++) {
29277 textEls[i].innerHTML = (++prevStart);
29278 d.setDate(d.getDate()+1);
29279 cells[i].className = "x-date-prevday";
29280 setCellClass(this, cells[i]);
29282 for(; i < days; i++){
29283 intDay = i - startingPos + 1;
29284 textEls[i].innerHTML = (intDay);
29285 d.setDate(d.getDate()+1);
29286 cells[i].className = "x-date-active";
29287 setCellClass(this, cells[i]);
29290 for(; i < 42; i++) {
29291 textEls[i].innerHTML = (++extraDays);
29292 d.setDate(d.getDate()+1);
29293 cells[i].className = "x-date-nextday";
29294 setCellClass(this, cells[i]);
29297 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
29298 this.fireEvent('monthchange', this, date);
29300 if(!this.internalRender){
29301 var main = this.el.dom.firstChild;
29302 var w = main.offsetWidth;
29303 this.el.setWidth(w + this.el.getBorderWidth("lr"));
29304 Roo.fly(main).setWidth(w);
29305 this.internalRender = true;
29306 // opera does not respect the auto grow header center column
29307 // then, after it gets a width opera refuses to recalculate
29308 // without a second pass
29309 if(Roo.isOpera && !this.secondPass){
29310 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
29311 this.secondPass = true;
29312 this.update.defer(10, this, [date]);
29320 * Ext JS Library 1.1.1
29321 * Copyright(c) 2006-2007, Ext JS, LLC.
29323 * Originally Released Under LGPL - original licence link has changed is not relivant.
29326 * <script type="text/javascript">
29329 * @class Roo.TabPanel
29330 * @extends Roo.util.Observable
29331 * A lightweight tab container.
29335 // basic tabs 1, built from existing content
29336 var tabs = new Roo.TabPanel("tabs1");
29337 tabs.addTab("script", "View Script");
29338 tabs.addTab("markup", "View Markup");
29339 tabs.activate("script");
29341 // more advanced tabs, built from javascript
29342 var jtabs = new Roo.TabPanel("jtabs");
29343 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
29345 // set up the UpdateManager
29346 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
29347 var updater = tab2.getUpdateManager();
29348 updater.setDefaultUrl("ajax1.htm");
29349 tab2.on('activate', updater.refresh, updater, true);
29351 // Use setUrl for Ajax loading
29352 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
29353 tab3.setUrl("ajax2.htm", null, true);
29356 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
29359 jtabs.activate("jtabs-1");
29362 * Create a new TabPanel.
29363 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
29364 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
29366 Roo.TabPanel = function(container, config){
29368 * The container element for this TabPanel.
29369 * @type Roo.Element
29371 this.el = Roo.get(container, true);
29373 if(typeof config == "boolean"){
29374 this.tabPosition = config ? "bottom" : "top";
29376 Roo.apply(this, config);
29379 if(this.tabPosition == "bottom"){
29380 this.bodyEl = Roo.get(this.createBody(this.el.dom));
29381 this.el.addClass("x-tabs-bottom");
29383 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
29384 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
29385 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
29387 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
29389 if(this.tabPosition != "bottom"){
29390 /** The body element that contains {@link Roo.TabPanelItem} bodies. +
29391 * @type Roo.Element
29393 this.bodyEl = Roo.get(this.createBody(this.el.dom));
29394 this.el.addClass("x-tabs-top");
29398 this.bodyEl.setStyle("position", "relative");
29400 this.active = null;
29401 this.activateDelegate = this.activate.createDelegate(this);
29406 * Fires when the active tab changes
29407 * @param {Roo.TabPanel} this
29408 * @param {Roo.TabPanelItem} activePanel The new active tab
29412 * @event beforetabchange
29413 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
29414 * @param {Roo.TabPanel} this
29415 * @param {Object} e Set cancel to true on this object to cancel the tab change
29416 * @param {Roo.TabPanelItem} tab The tab being changed to
29418 "beforetabchange" : true
29421 Roo.EventManager.onWindowResize(this.onResize, this);
29422 this.cpad = this.el.getPadding("lr");
29423 this.hiddenCount = 0;
29426 // toolbar on the tabbar support...
29427 if (this.toolbar) {
29428 var tcfg = this.toolbar;
29429 tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
29430 this.toolbar = new Roo.Toolbar(tcfg);
29431 if (Roo.isSafari) {
29432 var tbl = tcfg.container.child('table', true);
29433 tbl.setAttribute('width', '100%');
29440 Roo.TabPanel.superclass.constructor.call(this);
29443 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
29445 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
29447 tabPosition : "top",
29449 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
29451 currentTabWidth : 0,
29453 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
29457 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
29461 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
29463 preferredTabWidth : 175,
29465 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
29467 resizeTabs : false,
29469 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
29471 monitorResize : true,
29473 *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
29478 * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
29479 * @param {String} id The id of the div to use <b>or create</b>
29480 * @param {String} text The text for the tab
29481 * @param {String} content (optional) Content to put in the TabPanelItem body
29482 * @param {Boolean} closable (optional) True to create a close icon on the tab
29483 * @return {Roo.TabPanelItem} The created TabPanelItem
29485 addTab : function(id, text, content, closable){
29486 var item = new Roo.TabPanelItem(this, id, text, closable);
29487 this.addTabItem(item);
29489 item.setContent(content);
29495 * Returns the {@link Roo.TabPanelItem} with the specified id/index
29496 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
29497 * @return {Roo.TabPanelItem}
29499 getTab : function(id){
29500 return this.items[id];
29504 * Hides the {@link Roo.TabPanelItem} with the specified id/index
29505 * @param {String/Number} id The id or index of the TabPanelItem to hide.
29507 hideTab : function(id){
29508 var t = this.items[id];
29511 this.hiddenCount++;
29512 this.autoSizeTabs();
29517 * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
29518 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
29520 unhideTab : function(id){
29521 var t = this.items[id];
29523 t.setHidden(false);
29524 this.hiddenCount--;
29525 this.autoSizeTabs();
29530 * Adds an existing {@link Roo.TabPanelItem}.
29531 * @param {Roo.TabPanelItem} item The TabPanelItem to add
29533 addTabItem : function(item){
29534 this.items[item.id] = item;
29535 this.items.push(item);
29536 if(this.resizeTabs){
29537 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
29538 this.autoSizeTabs();
29545 * Removes a {@link Roo.TabPanelItem}.
29546 * @param {String/Number} id The id or index of the TabPanelItem to remove.
29548 removeTab : function(id){
29549 var items = this.items;
29550 var tab = items[id];
29551 if(!tab) { return; }
29552 var index = items.indexOf(tab);
29553 if(this.active == tab && items.length > 1){
29554 var newTab = this.getNextAvailable(index);
29559 this.stripEl.dom.removeChild(tab.pnode.dom);
29560 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
29561 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
29563 items.splice(index, 1);
29564 delete this.items[tab.id];
29565 tab.fireEvent("close", tab);
29566 tab.purgeListeners();
29567 this.autoSizeTabs();
29570 getNextAvailable : function(start){
29571 var items = this.items;
29573 // look for a next tab that will slide over to
29574 // replace the one being removed
29575 while(index < items.length){
29576 var item = items[++index];
29577 if(item && !item.isHidden()){
29581 // if one isn't found select the previous tab (on the left)
29584 var item = items[--index];
29585 if(item && !item.isHidden()){
29593 * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
29594 * @param {String/Number} id The id or index of the TabPanelItem to disable.
29596 disableTab : function(id){
29597 var tab = this.items[id];
29598 if(tab && this.active != tab){
29604 * Enables a {@link Roo.TabPanelItem} that is disabled.
29605 * @param {String/Number} id The id or index of the TabPanelItem to enable.
29607 enableTab : function(id){
29608 var tab = this.items[id];
29613 * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
29614 * @param {String/Number} id The id or index of the TabPanelItem to activate.
29615 * @return {Roo.TabPanelItem} The TabPanelItem.
29617 activate : function(id){
29618 var tab = this.items[id];
29622 if(tab == this.active || tab.disabled){
29626 this.fireEvent("beforetabchange", this, e, tab);
29627 if(e.cancel !== true && !tab.disabled){
29629 this.active.hide();
29631 this.active = this.items[id];
29632 this.active.show();
29633 this.fireEvent("tabchange", this, this.active);
29639 * Gets the active {@link Roo.TabPanelItem}.
29640 * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
29642 getActiveTab : function(){
29643 return this.active;
29647 * Updates the tab body element to fit the height of the container element
29648 * for overflow scrolling
29649 * @param {Number} targetHeight (optional) Override the starting height from the elements height
29651 syncHeight : function(targetHeight){
29652 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
29653 var bm = this.bodyEl.getMargins();
29654 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
29655 this.bodyEl.setHeight(newHeight);
29659 onResize : function(){
29660 if(this.monitorResize){
29661 this.autoSizeTabs();
29666 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
29668 beginUpdate : function(){
29669 this.updating = true;
29673 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
29675 endUpdate : function(){
29676 this.updating = false;
29677 this.autoSizeTabs();
29681 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
29683 autoSizeTabs : function(){
29684 var count = this.items.length;
29685 var vcount = count - this.hiddenCount;
29686 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
29689 var w = Math.max(this.el.getWidth() - this.cpad, 10);
29690 var availWidth = Math.floor(w / vcount);
29691 var b = this.stripBody;
29692 if(b.getWidth() > w){
29693 var tabs = this.items;
29694 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
29695 if(availWidth < this.minTabWidth){
29696 /*if(!this.sleft){ // incomplete scrolling code
29697 this.createScrollButtons();
29700 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
29703 if(this.currentTabWidth < this.preferredTabWidth){
29704 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
29710 * Returns the number of tabs in this TabPanel.
29713 getCount : function(){
29714 return this.items.length;
29718 * Resizes all the tabs to the passed width
29719 * @param {Number} The new width
29721 setTabWidth : function(width){
29722 this.currentTabWidth = width;
29723 for(var i = 0, len = this.items.length; i < len; i++) {
29724 if(!this.items[i].isHidden()) {
29725 this.items[i].setWidth(width);
29731 * Destroys this TabPanel
29732 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
29734 destroy : function(removeEl){
29735 Roo.EventManager.removeResizeListener(this.onResize, this);
29736 for(var i = 0, len = this.items.length; i < len; i++){
29737 this.items[i].purgeListeners();
29739 if(removeEl === true){
29740 this.el.update("");
29747 * @class Roo.TabPanelItem
29748 * @extends Roo.util.Observable
29749 * Represents an individual item (tab plus body) in a TabPanel.
29750 * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
29751 * @param {String} id The id of this TabPanelItem
29752 * @param {String} text The text for the tab of this TabPanelItem
29753 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
29755 Roo.TabPanelItem = function(tabPanel, id, text, closable){
29757 * The {@link Roo.TabPanel} this TabPanelItem belongs to
29758 * @type Roo.TabPanel
29760 this.tabPanel = tabPanel;
29762 * The id for this TabPanelItem
29767 this.disabled = false;
29771 this.loaded = false;
29772 this.closable = closable;
29775 * The body element for this TabPanelItem.
29776 * @type Roo.Element
29778 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
29779 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
29780 this.bodyEl.setStyle("display", "block");
29781 this.bodyEl.setStyle("zoom", "1");
29784 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
29786 this.el = Roo.get(els.el, true);
29787 this.inner = Roo.get(els.inner, true);
29788 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
29789 this.pnode = Roo.get(els.el.parentNode, true);
29790 this.el.on("mousedown", this.onTabMouseDown, this);
29791 this.el.on("click", this.onTabClick, this);
29794 var c = Roo.get(els.close, true);
29795 c.dom.title = this.closeText;
29796 c.addClassOnOver("close-over");
29797 c.on("click", this.closeClick, this);
29803 * Fires when this tab becomes the active tab.
29804 * @param {Roo.TabPanel} tabPanel The parent TabPanel
29805 * @param {Roo.TabPanelItem} this
29809 * @event beforeclose
29810 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
29811 * @param {Roo.TabPanelItem} this
29812 * @param {Object} e Set cancel to true on this object to cancel the close.
29814 "beforeclose": true,
29817 * Fires when this tab is closed.
29818 * @param {Roo.TabPanelItem} this
29822 * @event deactivate
29823 * Fires when this tab is no longer the active tab.
29824 * @param {Roo.TabPanel} tabPanel The parent TabPanel
29825 * @param {Roo.TabPanelItem} this
29827 "deactivate" : true
29829 this.hidden = false;
29831 Roo.TabPanelItem.superclass.constructor.call(this);
29834 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
29835 purgeListeners : function(){
29836 Roo.util.Observable.prototype.purgeListeners.call(this);
29837 this.el.removeAllListeners();
29840 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
29843 this.pnode.addClass("on");
29846 this.tabPanel.stripWrap.repaint();
29848 this.fireEvent("activate", this.tabPanel, this);
29852 * Returns true if this tab is the active tab.
29853 * @return {Boolean}
29855 isActive : function(){
29856 return this.tabPanel.getActiveTab() == this;
29860 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
29863 this.pnode.removeClass("on");
29865 this.fireEvent("deactivate", this.tabPanel, this);
29868 hideAction : function(){
29869 this.bodyEl.hide();
29870 this.bodyEl.setStyle("position", "absolute");
29871 this.bodyEl.setLeft("-20000px");
29872 this.bodyEl.setTop("-20000px");
29875 showAction : function(){
29876 this.bodyEl.setStyle("position", "relative");
29877 this.bodyEl.setTop("");
29878 this.bodyEl.setLeft("");
29879 this.bodyEl.show();
29883 * Set the tooltip for the tab.
29884 * @param {String} tooltip The tab's tooltip
29886 setTooltip : function(text){
29887 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
29888 this.textEl.dom.qtip = text;
29889 this.textEl.dom.removeAttribute('title');
29891 this.textEl.dom.title = text;
29895 onTabClick : function(e){
29896 e.preventDefault();
29897 this.tabPanel.activate(this.id);
29900 onTabMouseDown : function(e){
29901 e.preventDefault();
29902 this.tabPanel.activate(this.id);
29905 getWidth : function(){
29906 return this.inner.getWidth();
29909 setWidth : function(width){
29910 var iwidth = width - this.pnode.getPadding("lr");
29911 this.inner.setWidth(iwidth);
29912 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
29913 this.pnode.setWidth(width);
29917 * Show or hide the tab
29918 * @param {Boolean} hidden True to hide or false to show.
29920 setHidden : function(hidden){
29921 this.hidden = hidden;
29922 this.pnode.setStyle("display", hidden ? "none" : "");
29926 * Returns true if this tab is "hidden"
29927 * @return {Boolean}
29929 isHidden : function(){
29930 return this.hidden;
29934 * Returns the text for this tab
29937 getText : function(){
29941 autoSize : function(){
29942 //this.el.beginMeasure();
29943 this.textEl.setWidth(1);
29945 * #2804 [new] Tabs in Roojs
29946 * increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
29948 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
29949 //this.el.endMeasure();
29953 * Sets the text for the tab (Note: this also sets the tooltip text)
29954 * @param {String} text The tab's text and tooltip
29956 setText : function(text){
29958 this.textEl.update(text);
29959 this.setTooltip(text);
29960 if(!this.tabPanel.resizeTabs){
29965 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
29967 activate : function(){
29968 this.tabPanel.activate(this.id);
29972 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
29974 disable : function(){
29975 if(this.tabPanel.active != this){
29976 this.disabled = true;
29977 this.pnode.addClass("disabled");
29982 * Enables this TabPanelItem if it was previously disabled.
29984 enable : function(){
29985 this.disabled = false;
29986 this.pnode.removeClass("disabled");
29990 * Sets the content for this TabPanelItem.
29991 * @param {String} content The content
29992 * @param {Boolean} loadScripts true to look for and load scripts
29994 setContent : function(content, loadScripts){
29995 this.bodyEl.update(content, loadScripts);
29999 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
30000 * @return {Roo.UpdateManager} The UpdateManager
30002 getUpdateManager : function(){
30003 return this.bodyEl.getUpdateManager();
30007 * Set a URL to be used to load the content for this TabPanelItem.
30008 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
30009 * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
30010 * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this TabPanelItem is activated. (Defaults to false)
30011 * @return {Roo.UpdateManager} The UpdateManager
30013 setUrl : function(url, params, loadOnce){
30014 if(this.refreshDelegate){
30015 this.un('activate', this.refreshDelegate);
30017 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
30018 this.on("activate", this.refreshDelegate);
30019 return this.bodyEl.getUpdateManager();
30023 _handleRefresh : function(url, params, loadOnce){
30024 if(!loadOnce || !this.loaded){
30025 var updater = this.bodyEl.getUpdateManager();
30026 updater.update(url, params, this._setLoaded.createDelegate(this));
30031 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
30032 * Will fail silently if the setUrl method has not been called.
30033 * This does not activate the panel, just updates its content.
30035 refresh : function(){
30036 if(this.refreshDelegate){
30037 this.loaded = false;
30038 this.refreshDelegate();
30043 _setLoaded : function(){
30044 this.loaded = true;
30048 closeClick : function(e){
30051 this.fireEvent("beforeclose", this, o);
30052 if(o.cancel !== true){
30053 this.tabPanel.removeTab(this.id);
30057 * The text displayed in the tooltip for the close icon.
30060 closeText : "Close this tab"
30064 Roo.TabPanel.prototype.createStrip = function(container){
30065 var strip = document.createElement("div");
30066 strip.className = "x-tabs-wrap";
30067 container.appendChild(strip);
30071 Roo.TabPanel.prototype.createStripList = function(strip){
30072 // div wrapper for retard IE
30073 // returns the "tr" element.
30074 strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
30075 '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
30076 '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
30077 return strip.firstChild.firstChild.firstChild.firstChild;
30080 Roo.TabPanel.prototype.createBody = function(container){
30081 var body = document.createElement("div");
30082 Roo.id(body, "tab-body");
30083 Roo.fly(body).addClass("x-tabs-body");
30084 container.appendChild(body);
30088 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
30089 var body = Roo.getDom(id);
30091 body = document.createElement("div");
30094 Roo.fly(body).addClass("x-tabs-item-body");
30095 bodyEl.insertBefore(body, bodyEl.firstChild);
30099 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
30100 var td = document.createElement("td");
30101 stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
30102 //stripEl.appendChild(td);
30104 td.className = "x-tabs-closable";
30105 if(!this.closeTpl){
30106 this.closeTpl = new Roo.Template(
30107 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30108 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
30109 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
30112 var el = this.closeTpl.overwrite(td, {"text": text});
30113 var close = el.getElementsByTagName("div")[0];
30114 var inner = el.getElementsByTagName("em")[0];
30115 return {"el": el, "close": close, "inner": inner};
30118 this.tabTpl = new Roo.Template(
30119 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30120 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
30123 var el = this.tabTpl.overwrite(td, {"text": text});
30124 var inner = el.getElementsByTagName("em")[0];
30125 return {"el": el, "inner": inner};
30129 * Ext JS Library 1.1.1
30130 * Copyright(c) 2006-2007, Ext JS, LLC.
30132 * Originally Released Under LGPL - original licence link has changed is not relivant.
30135 * <script type="text/javascript">
30139 * @class Roo.Button
30140 * @extends Roo.util.Observable
30141 * Simple Button class
30142 * @cfg {String} text The button text
30143 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
30144 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
30145 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
30146 * @cfg {Object} scope The scope of the handler
30147 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
30148 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
30149 * @cfg {Boolean} hidden True to start hidden (defaults to false)
30150 * @cfg {Boolean} disabled True to start disabled (defaults to false)
30151 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
30152 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
30153 applies if enableToggle = true)
30154 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
30155 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
30156 an {@link Roo.util.ClickRepeater} config object (defaults to false).
30158 * Create a new button
30159 * @param {Object} config The config object
30161 Roo.Button = function(renderTo, config)
30165 renderTo = config.renderTo || false;
30168 Roo.apply(this, config);
30172 * Fires when this button is clicked
30173 * @param {Button} this
30174 * @param {EventObject} e The click event
30179 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
30180 * @param {Button} this
30181 * @param {Boolean} pressed
30186 * Fires when the mouse hovers over the button
30187 * @param {Button} this
30188 * @param {Event} e The event object
30190 'mouseover' : true,
30193 * Fires when the mouse exits the button
30194 * @param {Button} this
30195 * @param {Event} e The event object
30200 * Fires when the button is rendered
30201 * @param {Button} this
30206 this.menu = Roo.menu.MenuMgr.get(this.menu);
30208 // register listeners first!! - so render can be captured..
30209 Roo.util.Observable.call(this);
30211 this.render(renderTo);
30217 Roo.extend(Roo.Button, Roo.util.Observable, {
30223 * Read-only. True if this button is hidden
30228 * Read-only. True if this button is disabled
30233 * Read-only. True if this button is pressed (only if enableToggle = true)
30239 * @cfg {Number} tabIndex
30240 * The DOM tabIndex for this button (defaults to undefined)
30242 tabIndex : undefined,
30245 * @cfg {Boolean} enableToggle
30246 * True to enable pressed/not pressed toggling (defaults to false)
30248 enableToggle: false,
30250 * @cfg {Roo.menu.Menu} menu
30251 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
30255 * @cfg {String} menuAlign
30256 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
30258 menuAlign : "tl-bl?",
30261 * @cfg {String} iconCls
30262 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
30264 iconCls : undefined,
30266 * @cfg {String} type
30267 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
30272 menuClassTarget: 'tr',
30275 * @cfg {String} clickEvent
30276 * The type of event to map to the button's event handler (defaults to 'click')
30278 clickEvent : 'click',
30281 * @cfg {Boolean} handleMouseEvents
30282 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
30284 handleMouseEvents : true,
30287 * @cfg {String} tooltipType
30288 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
30290 tooltipType : 'qtip',
30293 * @cfg {String} cls
30294 * A CSS class to apply to the button's main element.
30298 * @cfg {Roo.Template} template (Optional)
30299 * An {@link Roo.Template} with which to create the Button's main element. This Template must
30300 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
30301 * require code modifications if required elements (e.g. a button) aren't present.
30305 render : function(renderTo){
30307 if(this.hideParent){
30308 this.parentEl = Roo.get(renderTo);
30310 if(!this.dhconfig){
30311 if(!this.template){
30312 if(!Roo.Button.buttonTemplate){
30313 // hideous table template
30314 Roo.Button.buttonTemplate = new Roo.Template(
30315 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
30316 '<td class="x-btn-left"><i> </i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i> </i></td>',
30317 "</tr></tbody></table>");
30319 this.template = Roo.Button.buttonTemplate;
30321 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
30322 var btnEl = btn.child("button:first");
30323 btnEl.on('focus', this.onFocus, this);
30324 btnEl.on('blur', this.onBlur, this);
30326 btn.addClass(this.cls);
30329 btnEl.setStyle('background-image', 'url(' +this.icon +')');
30332 btnEl.addClass(this.iconCls);
30334 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
30337 if(this.tabIndex !== undefined){
30338 btnEl.dom.tabIndex = this.tabIndex;
30341 if(typeof this.tooltip == 'object'){
30342 Roo.QuickTips.tips(Roo.apply({
30346 btnEl.dom[this.tooltipType] = this.tooltip;
30350 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
30354 this.el.dom.id = this.el.id = this.id;
30357 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
30358 this.menu.on("show", this.onMenuShow, this);
30359 this.menu.on("hide", this.onMenuHide, this);
30361 btn.addClass("x-btn");
30362 if(Roo.isIE && !Roo.isIE7){
30363 this.autoWidth.defer(1, this);
30367 if(this.handleMouseEvents){
30368 btn.on("mouseover", this.onMouseOver, this);
30369 btn.on("mouseout", this.onMouseOut, this);
30370 btn.on("mousedown", this.onMouseDown, this);
30372 btn.on(this.clickEvent, this.onClick, this);
30373 //btn.on("mouseup", this.onMouseUp, this);
30380 Roo.ButtonToggleMgr.register(this);
30382 this.el.addClass("x-btn-pressed");
30385 var repeater = new Roo.util.ClickRepeater(btn,
30386 typeof this.repeat == "object" ? this.repeat : {}
30388 repeater.on("click", this.onClick, this);
30391 this.fireEvent('render', this);
30395 * Returns the button's underlying element
30396 * @return {Roo.Element} The element
30398 getEl : function(){
30403 * Destroys this Button and removes any listeners.
30405 destroy : function(){
30406 Roo.ButtonToggleMgr.unregister(this);
30407 this.el.removeAllListeners();
30408 this.purgeListeners();
30413 autoWidth : function(){
30415 this.el.setWidth("auto");
30416 if(Roo.isIE7 && Roo.isStrict){
30417 var ib = this.el.child('button');
30418 if(ib && ib.getWidth() > 20){
30420 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
30425 this.el.beginMeasure();
30427 if(this.el.getWidth() < this.minWidth){
30428 this.el.setWidth(this.minWidth);
30431 this.el.endMeasure();
30438 * Assigns this button's click handler
30439 * @param {Function} handler The function to call when the button is clicked
30440 * @param {Object} scope (optional) Scope for the function passed in
30442 setHandler : function(handler, scope){
30443 this.handler = handler;
30444 this.scope = scope;
30448 * Sets this button's text
30449 * @param {String} text The button text
30451 setText : function(text){
30454 this.el.child("td.x-btn-center button.x-btn-text").update(text);
30460 * Gets the text for this button
30461 * @return {String} The button text
30463 getText : function(){
30471 this.hidden = false;
30473 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
30481 this.hidden = true;
30483 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
30488 * Convenience function for boolean show/hide
30489 * @param {Boolean} visible True to show, false to hide
30491 setVisible: function(visible){
30500 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
30501 * @param {Boolean} state (optional) Force a particular state
30503 toggle : function(state){
30504 state = state === undefined ? !this.pressed : state;
30505 if(state != this.pressed){
30507 this.el.addClass("x-btn-pressed");
30508 this.pressed = true;
30509 this.fireEvent("toggle", this, true);
30511 this.el.removeClass("x-btn-pressed");
30512 this.pressed = false;
30513 this.fireEvent("toggle", this, false);
30515 if(this.toggleHandler){
30516 this.toggleHandler.call(this.scope || this, this, state);
30524 focus : function(){
30525 this.el.child('button:first').focus();
30529 * Disable this button
30531 disable : function(){
30533 this.el.addClass("x-btn-disabled");
30535 this.disabled = true;
30539 * Enable this button
30541 enable : function(){
30543 this.el.removeClass("x-btn-disabled");
30545 this.disabled = false;
30549 * Convenience function for boolean enable/disable
30550 * @param {Boolean} enabled True to enable, false to disable
30552 setDisabled : function(v){
30553 this[v !== true ? "enable" : "disable"]();
30557 onClick : function(e)
30560 e.preventDefault();
30565 if(!this.disabled){
30566 if(this.enableToggle){
30569 if(this.menu && !this.menu.isVisible()){
30570 this.menu.show(this.el, this.menuAlign);
30572 this.fireEvent("click", this, e);
30574 this.el.removeClass("x-btn-over");
30575 this.handler.call(this.scope || this, this, e);
30580 onMouseOver : function(e){
30581 if(!this.disabled){
30582 this.el.addClass("x-btn-over");
30583 this.fireEvent('mouseover', this, e);
30587 onMouseOut : function(e){
30588 if(!e.within(this.el, true)){
30589 this.el.removeClass("x-btn-over");
30590 this.fireEvent('mouseout', this, e);
30594 onFocus : function(e){
30595 if(!this.disabled){
30596 this.el.addClass("x-btn-focus");
30600 onBlur : function(e){
30601 this.el.removeClass("x-btn-focus");
30604 onMouseDown : function(e){
30605 if(!this.disabled && e.button == 0){
30606 this.el.addClass("x-btn-click");
30607 Roo.get(document).on('mouseup', this.onMouseUp, this);
30611 onMouseUp : function(e){
30613 this.el.removeClass("x-btn-click");
30614 Roo.get(document).un('mouseup', this.onMouseUp, this);
30618 onMenuShow : function(e){
30619 this.el.addClass("x-btn-menu-active");
30622 onMenuHide : function(e){
30623 this.el.removeClass("x-btn-menu-active");
30627 // Private utility class used by Button
30628 Roo.ButtonToggleMgr = function(){
30631 function toggleGroup(btn, state){
30633 var g = groups[btn.toggleGroup];
30634 for(var i = 0, l = g.length; i < l; i++){
30636 g[i].toggle(false);
30643 register : function(btn){
30644 if(!btn.toggleGroup){
30647 var g = groups[btn.toggleGroup];
30649 g = groups[btn.toggleGroup] = [];
30652 btn.on("toggle", toggleGroup);
30655 unregister : function(btn){
30656 if(!btn.toggleGroup){
30659 var g = groups[btn.toggleGroup];
30662 btn.un("toggle", toggleGroup);
30668 * Ext JS Library 1.1.1
30669 * Copyright(c) 2006-2007, Ext JS, LLC.
30671 * Originally Released Under LGPL - original licence link has changed is not relivant.
30674 * <script type="text/javascript">
30678 * @class Roo.SplitButton
30679 * @extends Roo.Button
30680 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
30681 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
30682 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
30683 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
30684 * @cfg {String} arrowTooltip The title attribute of the arrow
30686 * Create a new menu button
30687 * @param {String/HTMLElement/Element} renderTo The element to append the button to
30688 * @param {Object} config The config object
30690 Roo.SplitButton = function(renderTo, config){
30691 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
30693 * @event arrowclick
30694 * Fires when this button's arrow is clicked
30695 * @param {SplitButton} this
30696 * @param {EventObject} e The click event
30698 this.addEvents({"arrowclick":true});
30701 Roo.extend(Roo.SplitButton, Roo.Button, {
30702 render : function(renderTo){
30703 // this is one sweet looking template!
30704 var tpl = new Roo.Template(
30705 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
30706 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
30707 '<tr><td class="x-btn-left"><i> </i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>',
30708 "</tbody></table></td><td>",
30709 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
30710 '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button"> </button></td><td class="x-btn-right"><i> </i></td></tr>',
30711 "</tbody></table></td></tr></table>"
30713 var btn = tpl.append(renderTo, [this.text, this.type], true);
30714 var btnEl = btn.child("button");
30716 btn.addClass(this.cls);
30719 btnEl.setStyle('background-image', 'url(' +this.icon +')');
30722 btnEl.addClass(this.iconCls);
30724 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
30728 if(this.handleMouseEvents){
30729 btn.on("mouseover", this.onMouseOver, this);
30730 btn.on("mouseout", this.onMouseOut, this);
30731 btn.on("mousedown", this.onMouseDown, this);
30732 btn.on("mouseup", this.onMouseUp, this);
30734 btn.on(this.clickEvent, this.onClick, this);
30736 if(typeof this.tooltip == 'object'){
30737 Roo.QuickTips.tips(Roo.apply({
30741 btnEl.dom[this.tooltipType] = this.tooltip;
30744 if(this.arrowTooltip){
30745 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
30754 this.el.addClass("x-btn-pressed");
30756 if(Roo.isIE && !Roo.isIE7){
30757 this.autoWidth.defer(1, this);
30762 this.menu.on("show", this.onMenuShow, this);
30763 this.menu.on("hide", this.onMenuHide, this);
30765 this.fireEvent('render', this);
30769 autoWidth : function(){
30771 var tbl = this.el.child("table:first");
30772 var tbl2 = this.el.child("table:last");
30773 this.el.setWidth("auto");
30774 tbl.setWidth("auto");
30775 if(Roo.isIE7 && Roo.isStrict){
30776 var ib = this.el.child('button:first');
30777 if(ib && ib.getWidth() > 20){
30779 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
30784 this.el.beginMeasure();
30786 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
30787 tbl.setWidth(this.minWidth-tbl2.getWidth());
30790 this.el.endMeasure();
30793 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
30797 * Sets this button's click handler
30798 * @param {Function} handler The function to call when the button is clicked
30799 * @param {Object} scope (optional) Scope for the function passed above
30801 setHandler : function(handler, scope){
30802 this.handler = handler;
30803 this.scope = scope;
30807 * Sets this button's arrow click handler
30808 * @param {Function} handler The function to call when the arrow is clicked
30809 * @param {Object} scope (optional) Scope for the function passed above
30811 setArrowHandler : function(handler, scope){
30812 this.arrowHandler = handler;
30813 this.scope = scope;
30819 focus : function(){
30821 this.el.child("button:first").focus();
30826 onClick : function(e){
30827 e.preventDefault();
30828 if(!this.disabled){
30829 if(e.getTarget(".x-btn-menu-arrow-wrap")){
30830 if(this.menu && !this.menu.isVisible()){
30831 this.menu.show(this.el, this.menuAlign);
30833 this.fireEvent("arrowclick", this, e);
30834 if(this.arrowHandler){
30835 this.arrowHandler.call(this.scope || this, this, e);
30838 this.fireEvent("click", this, e);
30840 this.handler.call(this.scope || this, this, e);
30846 onMouseDown : function(e){
30847 if(!this.disabled){
30848 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
30852 onMouseUp : function(e){
30853 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
30858 // backwards compat
30859 Roo.MenuButton = Roo.SplitButton;/*
30861 * Ext JS Library 1.1.1
30862 * Copyright(c) 2006-2007, Ext JS, LLC.
30864 * Originally Released Under LGPL - original licence link has changed is not relivant.
30867 * <script type="text/javascript">
30871 * @class Roo.Toolbar
30872 * @children Roo.Toolbar.Item Roo.form.Field
30873 * Basic Toolbar class.
30875 * Creates a new Toolbar
30876 * @param {Object} container The config object
30878 Roo.Toolbar = function(container, buttons, config)
30880 /// old consturctor format still supported..
30881 if(container instanceof Array){ // omit the container for later rendering
30882 buttons = container;
30886 if (typeof(container) == 'object' && container.xtype) {
30887 config = container;
30888 container = config.container;
30889 buttons = config.buttons || []; // not really - use items!!
30892 if (config && config.items) {
30893 xitems = config.items;
30894 delete config.items;
30896 Roo.apply(this, config);
30897 this.buttons = buttons;
30900 this.render(container);
30902 this.xitems = xitems;
30903 Roo.each(xitems, function(b) {
30909 Roo.Toolbar.prototype = {
30911 * @cfg {Array} items
30912 * array of button configs or elements to add (will be converted to a MixedCollection)
30916 * @cfg {String/HTMLElement/Element} container
30917 * The id or element that will contain the toolbar
30920 render : function(ct){
30921 this.el = Roo.get(ct);
30923 this.el.addClass(this.cls);
30925 // using a table allows for vertical alignment
30926 // 100% width is needed by Safari...
30927 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
30928 this.tr = this.el.child("tr", true);
30930 this.items = new Roo.util.MixedCollection(false, function(o){
30931 return o.id || ("item" + (++autoId));
30934 this.add.apply(this, this.buttons);
30935 delete this.buttons;
30940 * Adds element(s) to the toolbar -- this function takes a variable number of
30941 * arguments of mixed type and adds them to the toolbar.
30942 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
30944 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
30945 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
30946 * <li>Field: Any form field (equivalent to {@link #addField})</li>
30947 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
30948 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
30949 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
30950 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
30951 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
30952 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
30954 * @param {Mixed} arg2
30955 * @param {Mixed} etc.
30958 var a = arguments, l = a.length;
30959 for(var i = 0; i < l; i++){
30964 _add : function(el) {
30967 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
30970 if (el.applyTo){ // some kind of form field
30971 return this.addField(el);
30973 if (el.render){ // some kind of Toolbar.Item
30974 return this.addItem(el);
30976 if (typeof el == "string"){ // string
30977 if(el == "separator" || el == "-"){
30978 return this.addSeparator();
30981 return this.addSpacer();
30984 return this.addFill();
30986 return this.addText(el);
30989 if(el.tagName){ // element
30990 return this.addElement(el);
30992 if(typeof el == "object"){ // must be button config?
30993 return this.addButton(el);
30995 // and now what?!?!
31001 * Add an Xtype element
31002 * @param {Object} xtype Xtype Object
31003 * @return {Object} created Object
31005 addxtype : function(e){
31006 return this.add(e);
31010 * Returns the Element for this toolbar.
31011 * @return {Roo.Element}
31013 getEl : function(){
31019 * @return {Roo.Toolbar.Item} The separator item
31021 addSeparator : function(){
31022 return this.addItem(new Roo.Toolbar.Separator());
31026 * Adds a spacer element
31027 * @return {Roo.Toolbar.Spacer} The spacer item
31029 addSpacer : function(){
31030 return this.addItem(new Roo.Toolbar.Spacer());
31034 * Adds a fill element that forces subsequent additions to the right side of the toolbar
31035 * @return {Roo.Toolbar.Fill} The fill item
31037 addFill : function(){
31038 return this.addItem(new Roo.Toolbar.Fill());
31042 * Adds any standard HTML element to the toolbar
31043 * @param {String/HTMLElement/Element} el The element or id of the element to add
31044 * @return {Roo.Toolbar.Item} The element's item
31046 addElement : function(el){
31047 return this.addItem(new Roo.Toolbar.Item(el));
31050 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
31051 * @type Roo.util.MixedCollection
31056 * Adds any Toolbar.Item or subclass
31057 * @param {Roo.Toolbar.Item} item
31058 * @return {Roo.Toolbar.Item} The item
31060 addItem : function(item){
31061 var td = this.nextBlock();
31063 this.items.add(item);
31068 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
31069 * @param {Object/Array} config A button config or array of configs
31070 * @return {Roo.Toolbar.Button/Array}
31072 addButton : function(config){
31073 if(config instanceof Array){
31075 for(var i = 0, len = config.length; i < len; i++) {
31076 buttons.push(this.addButton(config[i]));
31081 if(!(config instanceof Roo.Toolbar.Button)){
31083 new Roo.Toolbar.SplitButton(config) :
31084 new Roo.Toolbar.Button(config);
31086 var td = this.nextBlock();
31093 * Adds text to the toolbar
31094 * @param {String} text The text to add
31095 * @return {Roo.Toolbar.Item} The element's item
31097 addText : function(text){
31098 return this.addItem(new Roo.Toolbar.TextItem(text));
31102 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
31103 * @param {Number} index The index where the item is to be inserted
31104 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
31105 * @return {Roo.Toolbar.Button/Item}
31107 insertButton : function(index, item){
31108 if(item instanceof Array){
31110 for(var i = 0, len = item.length; i < len; i++) {
31111 buttons.push(this.insertButton(index + i, item[i]));
31115 if (!(item instanceof Roo.Toolbar.Button)){
31116 item = new Roo.Toolbar.Button(item);
31118 var td = document.createElement("td");
31119 this.tr.insertBefore(td, this.tr.childNodes[index]);
31121 this.items.insert(index, item);
31126 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
31127 * @param {Object} config
31128 * @return {Roo.Toolbar.Item} The element's item
31130 addDom : function(config, returnEl){
31131 var td = this.nextBlock();
31132 Roo.DomHelper.overwrite(td, config);
31133 var ti = new Roo.Toolbar.Item(td.firstChild);
31135 this.items.add(ti);
31140 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
31141 * @type Roo.util.MixedCollection
31146 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
31147 * Note: the field should not have been rendered yet. For a field that has already been
31148 * rendered, use {@link #addElement}.
31149 * @param {Roo.form.Field} field
31150 * @return {Roo.ToolbarItem}
31154 addField : function(field) {
31155 if (!this.fields) {
31157 this.fields = new Roo.util.MixedCollection(false, function(o){
31158 return o.id || ("item" + (++autoId));
31163 var td = this.nextBlock();
31165 var ti = new Roo.Toolbar.Item(td.firstChild);
31167 this.items.add(ti);
31168 this.fields.add(field);
31179 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
31180 this.el.child('div').hide();
31188 this.el.child('div').show();
31192 nextBlock : function(){
31193 var td = document.createElement("td");
31194 this.tr.appendChild(td);
31199 destroy : function(){
31200 if(this.items){ // rendered?
31201 Roo.destroy.apply(Roo, this.items.items);
31203 if(this.fields){ // rendered?
31204 Roo.destroy.apply(Roo, this.fields.items);
31206 Roo.Element.uncache(this.el, this.tr);
31211 * @class Roo.Toolbar.Item
31212 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
31214 * Creates a new Item
31215 * @param {HTMLElement} el
31217 Roo.Toolbar.Item = function(el){
31219 if (typeof (el.xtype) != 'undefined') {
31224 this.el = Roo.getDom(el);
31225 this.id = Roo.id(this.el);
31226 this.hidden = false;
31231 * Fires when the button is rendered
31232 * @param {Button} this
31236 Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
31238 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
31239 //Roo.Toolbar.Item.prototype = {
31242 * Get this item's HTML Element
31243 * @return {HTMLElement}
31245 getEl : function(){
31250 render : function(td){
31253 td.appendChild(this.el);
31255 this.fireEvent('render', this);
31259 * Removes and destroys this item.
31261 destroy : function(){
31262 this.td.parentNode.removeChild(this.td);
31269 this.hidden = false;
31270 this.td.style.display = "";
31277 this.hidden = true;
31278 this.td.style.display = "none";
31282 * Convenience function for boolean show/hide.
31283 * @param {Boolean} visible true to show/false to hide
31285 setVisible: function(visible){
31294 * Try to focus this item.
31296 focus : function(){
31297 Roo.fly(this.el).focus();
31301 * Disables this item.
31303 disable : function(){
31304 Roo.fly(this.td).addClass("x-item-disabled");
31305 this.disabled = true;
31306 this.el.disabled = true;
31310 * Enables this item.
31312 enable : function(){
31313 Roo.fly(this.td).removeClass("x-item-disabled");
31314 this.disabled = false;
31315 this.el.disabled = false;
31321 * @class Roo.Toolbar.Separator
31322 * @extends Roo.Toolbar.Item
31323 * A simple toolbar separator class
31325 * Creates a new Separator
31327 Roo.Toolbar.Separator = function(cfg){
31329 var s = document.createElement("span");
31330 s.className = "ytb-sep";
31335 Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
31337 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
31338 enable:Roo.emptyFn,
31339 disable:Roo.emptyFn,
31344 * @class Roo.Toolbar.Spacer
31345 * @extends Roo.Toolbar.Item
31346 * A simple element that adds extra horizontal space to a toolbar.
31348 * Creates a new Spacer
31350 Roo.Toolbar.Spacer = function(cfg){
31351 var s = document.createElement("div");
31352 s.className = "ytb-spacer";
31356 Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
31358 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
31359 enable:Roo.emptyFn,
31360 disable:Roo.emptyFn,
31365 * @class Roo.Toolbar.Fill
31366 * @extends Roo.Toolbar.Spacer
31367 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
31369 * Creates a new Spacer
31371 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
31373 render : function(td){
31374 td.style.width = '100%';
31375 Roo.Toolbar.Fill.superclass.render.call(this, td);
31380 * @class Roo.Toolbar.TextItem
31381 * @extends Roo.Toolbar.Item
31382 * A simple class that renders text directly into a toolbar.
31384 * Creates a new TextItem
31385 * @cfg {string} text
31387 Roo.Toolbar.TextItem = function(cfg){
31388 var text = cfg || "";
31389 if (typeof(cfg) == 'object') {
31390 text = cfg.text || "";
31394 var s = document.createElement("span");
31395 s.className = "ytb-text";
31396 s.innerHTML = text;
31401 Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg || s);
31403 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
31406 enable:Roo.emptyFn,
31407 disable:Roo.emptyFn,
31412 * @class Roo.Toolbar.Button
31413 * @extends Roo.Button
31414 * A button that renders into a toolbar.
31416 * Creates a new Button
31417 * @param {Object} config A standard {@link Roo.Button} config object
31419 Roo.Toolbar.Button = function(config){
31420 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
31422 Roo.extend(Roo.Toolbar.Button, Roo.Button,
31426 render : function(td){
31428 Roo.Toolbar.Button.superclass.render.call(this, td);
31432 * Removes and destroys this button
31434 destroy : function(){
31435 Roo.Toolbar.Button.superclass.destroy.call(this);
31436 this.td.parentNode.removeChild(this.td);
31440 * Shows this button
31443 this.hidden = false;
31444 this.td.style.display = "";
31448 * Hides this button
31451 this.hidden = true;
31452 this.td.style.display = "none";
31456 * Disables this item
31458 disable : function(){
31459 Roo.fly(this.td).addClass("x-item-disabled");
31460 this.disabled = true;
31464 * Enables this item
31466 enable : function(){
31467 Roo.fly(this.td).removeClass("x-item-disabled");
31468 this.disabled = false;
31471 // backwards compat
31472 Roo.ToolbarButton = Roo.Toolbar.Button;
31475 * @class Roo.Toolbar.SplitButton
31476 * @extends Roo.SplitButton
31477 * A menu button that renders into a toolbar.
31479 * Creates a new SplitButton
31480 * @param {Object} config A standard {@link Roo.SplitButton} config object
31482 Roo.Toolbar.SplitButton = function(config){
31483 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
31485 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
31486 render : function(td){
31488 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
31492 * Removes and destroys this button
31494 destroy : function(){
31495 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
31496 this.td.parentNode.removeChild(this.td);
31500 * Shows this button
31503 this.hidden = false;
31504 this.td.style.display = "";
31508 * Hides this button
31511 this.hidden = true;
31512 this.td.style.display = "none";
31516 // backwards compat
31517 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
31519 * Ext JS Library 1.1.1
31520 * Copyright(c) 2006-2007, Ext JS, LLC.
31522 * Originally Released Under LGPL - original licence link has changed is not relivant.
31525 * <script type="text/javascript">
31529 * @class Roo.PagingToolbar
31530 * @extends Roo.Toolbar
31531 * @children Roo.Toolbar.Item Roo.form.Field
31532 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
31534 * Create a new PagingToolbar
31535 * @param {Object} config The config object
31537 Roo.PagingToolbar = function(el, ds, config)
31539 // old args format still supported... - xtype is prefered..
31540 if (typeof(el) == 'object' && el.xtype) {
31541 // created from xtype...
31543 ds = el.dataSource;
31544 el = config.container;
31547 if (config.items) {
31548 items = config.items;
31552 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
31555 this.renderButtons(this.el);
31558 // supprot items array.
31560 Roo.each(items, function(e) {
31561 this.add(Roo.factory(e));
31566 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
31569 * @cfg {String/HTMLElement/Element} container
31570 * container The id or element that will contain the toolbar
31573 * @cfg {Boolean} displayInfo
31574 * True to display the displayMsg (defaults to false)
31579 * @cfg {Number} pageSize
31580 * The number of records to display per page (defaults to 20)
31584 * @cfg {String} displayMsg
31585 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
31587 displayMsg : 'Displaying {0} - {1} of {2}',
31589 * @cfg {String} emptyMsg
31590 * The message to display when no records are found (defaults to "No data to display")
31592 emptyMsg : 'No data to display',
31594 * Customizable piece of the default paging text (defaults to "Page")
31597 beforePageText : "Page",
31599 * Customizable piece of the default paging text (defaults to "of %0")
31602 afterPageText : "of {0}",
31604 * Customizable piece of the default paging text (defaults to "First Page")
31607 firstText : "First Page",
31609 * Customizable piece of the default paging text (defaults to "Previous Page")
31612 prevText : "Previous Page",
31614 * Customizable piece of the default paging text (defaults to "Next Page")
31617 nextText : "Next Page",
31619 * Customizable piece of the default paging text (defaults to "Last Page")
31622 lastText : "Last Page",
31624 * Customizable piece of the default paging text (defaults to "Refresh")
31627 refreshText : "Refresh",
31630 renderButtons : function(el){
31631 Roo.PagingToolbar.superclass.render.call(this, el);
31632 this.first = this.addButton({
31633 tooltip: this.firstText,
31634 cls: "x-btn-icon x-grid-page-first",
31636 handler: this.onClick.createDelegate(this, ["first"])
31638 this.prev = this.addButton({
31639 tooltip: this.prevText,
31640 cls: "x-btn-icon x-grid-page-prev",
31642 handler: this.onClick.createDelegate(this, ["prev"])
31644 //this.addSeparator();
31645 this.add(this.beforePageText);
31646 this.field = Roo.get(this.addDom({
31651 cls: "x-grid-page-number"
31653 this.field.on("keydown", this.onPagingKeydown, this);
31654 this.field.on("focus", function(){this.dom.select();});
31655 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
31656 this.field.setHeight(18);
31657 //this.addSeparator();
31658 this.next = this.addButton({
31659 tooltip: this.nextText,
31660 cls: "x-btn-icon x-grid-page-next",
31662 handler: this.onClick.createDelegate(this, ["next"])
31664 this.last = this.addButton({
31665 tooltip: this.lastText,
31666 cls: "x-btn-icon x-grid-page-last",
31668 handler: this.onClick.createDelegate(this, ["last"])
31670 //this.addSeparator();
31671 this.loading = this.addButton({
31672 tooltip: this.refreshText,
31673 cls: "x-btn-icon x-grid-loading",
31674 handler: this.onClick.createDelegate(this, ["refresh"])
31677 if(this.displayInfo){
31678 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
31683 updateInfo : function(){
31684 if(this.displayEl){
31685 var count = this.ds.getCount();
31686 var msg = count == 0 ?
31690 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
31692 this.displayEl.update(msg);
31697 onLoad : function(ds, r, o){
31698 this.cursor = o.params ? o.params.start : 0;
31699 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
31701 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
31702 this.field.dom.value = ap;
31703 this.first.setDisabled(ap == 1);
31704 this.prev.setDisabled(ap == 1);
31705 this.next.setDisabled(ap == ps);
31706 this.last.setDisabled(ap == ps);
31707 this.loading.enable();
31712 getPageData : function(){
31713 var total = this.ds.getTotalCount();
31716 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
31717 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
31722 onLoadError : function(){
31723 this.loading.enable();
31727 onPagingKeydown : function(e){
31728 var k = e.getKey();
31729 var d = this.getPageData();
31731 var v = this.field.dom.value, pageNum;
31732 if(!v || isNaN(pageNum = parseInt(v, 10))){
31733 this.field.dom.value = d.activePage;
31736 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
31737 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
31740 else if(k == e.HOME || (k == e.UP && e.ctrlKey) || (k == e.PAGEUP && e.ctrlKey) || (k == e.RIGHT && e.ctrlKey) || k == e.END || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey))
31742 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
31743 this.field.dom.value = pageNum;
31744 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
31747 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
31749 var v = this.field.dom.value, pageNum;
31750 var increment = (e.shiftKey) ? 10 : 1;
31751 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
31754 if(!v || isNaN(pageNum = parseInt(v, 10))) {
31755 this.field.dom.value = d.activePage;
31758 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
31760 this.field.dom.value = parseInt(v, 10) + increment;
31761 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
31762 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
31769 beforeLoad : function(){
31771 this.loading.disable();
31776 onClick : function(which){
31780 ds.load({params:{start: 0, limit: this.pageSize}});
31783 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
31786 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
31789 var total = ds.getTotalCount();
31790 var extra = total % this.pageSize;
31791 var lastStart = extra ? (total - extra) : total-this.pageSize;
31792 ds.load({params:{start: lastStart, limit: this.pageSize}});
31795 ds.load({params:{start: this.cursor, limit: this.pageSize}});
31801 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
31802 * @param {Roo.data.Store} store The data store to unbind
31804 unbind : function(ds){
31805 ds.un("beforeload", this.beforeLoad, this);
31806 ds.un("load", this.onLoad, this);
31807 ds.un("loadexception", this.onLoadError, this);
31808 ds.un("remove", this.updateInfo, this);
31809 ds.un("add", this.updateInfo, this);
31810 this.ds = undefined;
31814 * Binds the paging toolbar to the specified {@link Roo.data.Store}
31815 * @param {Roo.data.Store} store The data store to bind
31817 bind : function(ds){
31818 ds.on("beforeload", this.beforeLoad, this);
31819 ds.on("load", this.onLoad, this);
31820 ds.on("loadexception", this.onLoadError, this);
31821 ds.on("remove", this.updateInfo, this);
31822 ds.on("add", this.updateInfo, this);
31827 * Ext JS Library 1.1.1
31828 * Copyright(c) 2006-2007, Ext JS, LLC.
31830 * Originally Released Under LGPL - original licence link has changed is not relivant.
31833 * <script type="text/javascript">
31837 * @class Roo.Resizable
31838 * @extends Roo.util.Observable
31839 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
31840 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
31841 * the textarea in a div and set "resizeChild" to true (or to the id of the element), <b>or</b> set wrap:true in your config and
31842 * the element will be wrapped for you automatically.</p>
31843 * <p>Here is the list of valid resize handles:</p>
31846 ------ -------------------
31855 'hd' horizontal drag
31858 * <p>Here's an example showing the creation of a typical Resizable:</p>
31860 var resizer = new Roo.Resizable("element-id", {
31868 resizer.on("resize", myHandler);
31870 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
31871 * resizer.east.setDisplayed(false);</p>
31872 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
31873 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
31874 * resize operation's new size (defaults to [0, 0])
31875 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
31876 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
31877 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
31878 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
31879 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
31880 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
31881 * @cfg {Number} width The width of the element in pixels (defaults to null)
31882 * @cfg {Number} height The height of the element in pixels (defaults to null)
31883 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
31884 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
31885 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
31886 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
31887 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
31888 * in favor of the handles config option (defaults to false)
31889 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
31890 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
31891 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
31892 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
31893 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
31894 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
31895 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
31896 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
31897 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
31898 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
31899 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
31901 * Create a new resizable component
31902 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
31903 * @param {Object} config configuration options
31905 Roo.Resizable = function(el, config)
31907 this.el = Roo.get(el);
31909 if(config && config.wrap){
31910 config.resizeChild = this.el;
31911 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
31912 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
31913 this.el.setStyle("overflow", "hidden");
31914 this.el.setPositioning(config.resizeChild.getPositioning());
31915 config.resizeChild.clearPositioning();
31916 if(!config.width || !config.height){
31917 var csize = config.resizeChild.getSize();
31918 this.el.setSize(csize.width, csize.height);
31920 if(config.pinned && !config.adjustments){
31921 config.adjustments = "auto";
31925 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
31926 this.proxy.unselectable();
31927 this.proxy.enableDisplayMode('block');
31929 Roo.apply(this, config);
31932 this.disableTrackOver = true;
31933 this.el.addClass("x-resizable-pinned");
31935 // if the element isn't positioned, make it relative
31936 var position = this.el.getStyle("position");
31937 if(position != "absolute" && position != "fixed"){
31938 this.el.setStyle("position", "relative");
31940 if(!this.handles){ // no handles passed, must be legacy style
31941 this.handles = 's,e,se';
31942 if(this.multiDirectional){
31943 this.handles += ',n,w';
31946 if(this.handles == "all"){
31947 this.handles = "n s e w ne nw se sw";
31949 var hs = this.handles.split(/\s*?[,;]\s*?| /);
31950 var ps = Roo.Resizable.positions;
31951 for(var i = 0, len = hs.length; i < len; i++){
31952 if(hs[i] && ps[hs[i]]){
31953 var pos = ps[hs[i]];
31954 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
31958 this.corner = this.southeast;
31960 // updateBox = the box can move..
31961 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
31962 this.updateBox = true;
31965 this.activeHandle = null;
31967 if(this.resizeChild){
31968 if(typeof this.resizeChild == "boolean"){
31969 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
31971 this.resizeChild = Roo.get(this.resizeChild, true);
31975 if(this.adjustments == "auto"){
31976 var rc = this.resizeChild;
31977 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
31978 if(rc && (hw || hn)){
31979 rc.position("relative");
31980 rc.setLeft(hw ? hw.el.getWidth() : 0);
31981 rc.setTop(hn ? hn.el.getHeight() : 0);
31983 this.adjustments = [
31984 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
31985 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
31989 if(this.draggable){
31990 this.dd = this.dynamic ?
31991 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
31992 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
31998 * @event beforeresize
31999 * Fired before resize is allowed. Set enabled to false to cancel resize.
32000 * @param {Roo.Resizable} this
32001 * @param {Roo.EventObject} e The mousedown event
32003 "beforeresize" : true,
32006 * Fired a resizing.
32007 * @param {Roo.Resizable} this
32008 * @param {Number} x The new x position
32009 * @param {Number} y The new y position
32010 * @param {Number} w The new w width
32011 * @param {Number} h The new h hight
32012 * @param {Roo.EventObject} e The mouseup event
32017 * Fired after a resize.
32018 * @param {Roo.Resizable} this
32019 * @param {Number} width The new width
32020 * @param {Number} height The new height
32021 * @param {Roo.EventObject} e The mouseup event
32026 if(this.width !== null && this.height !== null){
32027 this.resizeTo(this.width, this.height);
32029 this.updateChildSize();
32032 this.el.dom.style.zoom = 1;
32034 Roo.Resizable.superclass.constructor.call(this);
32037 Roo.extend(Roo.Resizable, Roo.util.Observable, {
32038 resizeChild : false,
32039 adjustments : [0, 0],
32049 multiDirectional : false,
32050 disableTrackOver : false,
32051 easing : 'easeOutStrong',
32052 widthIncrement : 0,
32053 heightIncrement : 0,
32057 preserveRatio : false,
32058 transparent: false,
32064 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
32066 constrainTo: undefined,
32068 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
32070 resizeRegion: undefined,
32074 * Perform a manual resize
32075 * @param {Number} width
32076 * @param {Number} height
32078 resizeTo : function(width, height){
32079 this.el.setSize(width, height);
32080 this.updateChildSize();
32081 this.fireEvent("resize", this, width, height, null);
32085 startSizing : function(e, handle){
32086 this.fireEvent("beforeresize", this, e);
32087 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
32090 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
32091 this.overlay.unselectable();
32092 this.overlay.enableDisplayMode("block");
32093 this.overlay.on("mousemove", this.onMouseMove, this);
32094 this.overlay.on("mouseup", this.onMouseUp, this);
32096 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
32098 this.resizing = true;
32099 this.startBox = this.el.getBox();
32100 this.startPoint = e.getXY();
32101 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
32102 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
32104 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
32105 this.overlay.show();
32107 if(this.constrainTo) {
32108 var ct = Roo.get(this.constrainTo);
32109 this.resizeRegion = ct.getRegion().adjust(
32110 ct.getFrameWidth('t'),
32111 ct.getFrameWidth('l'),
32112 -ct.getFrameWidth('b'),
32113 -ct.getFrameWidth('r')
32117 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
32119 this.proxy.setBox(this.startBox);
32121 this.proxy.setStyle('visibility', 'visible');
32127 onMouseDown : function(handle, e){
32130 this.activeHandle = handle;
32131 this.startSizing(e, handle);
32136 onMouseUp : function(e){
32137 var size = this.resizeElement();
32138 this.resizing = false;
32140 this.overlay.hide();
32142 this.fireEvent("resize", this, size.width, size.height, e);
32146 updateChildSize : function(){
32148 if(this.resizeChild){
32150 var child = this.resizeChild;
32151 var adj = this.adjustments;
32152 if(el.dom.offsetWidth){
32153 var b = el.getSize(true);
32154 child.setSize(b.width+adj[0], b.height+adj[1]);
32156 // Second call here for IE
32157 // The first call enables instant resizing and
32158 // the second call corrects scroll bars if they
32161 setTimeout(function(){
32162 if(el.dom.offsetWidth){
32163 var b = el.getSize(true);
32164 child.setSize(b.width+adj[0], b.height+adj[1]);
32172 snap : function(value, inc, min){
32173 if(!inc || !value) {
32176 var newValue = value;
32177 var m = value % inc;
32180 newValue = value + (inc-m);
32182 newValue = value - m;
32185 return Math.max(min, newValue);
32189 resizeElement : function(){
32190 var box = this.proxy.getBox();
32191 if(this.updateBox){
32192 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
32194 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
32196 this.updateChildSize();
32204 constrain : function(v, diff, m, mx){
32207 }else if(v - diff > mx){
32214 onMouseMove : function(e){
32217 try{// try catch so if something goes wrong the user doesn't get hung
32219 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
32223 //var curXY = this.startPoint;
32224 var curSize = this.curSize || this.startBox;
32225 var x = this.startBox.x, y = this.startBox.y;
32226 var ox = x, oy = y;
32227 var w = curSize.width, h = curSize.height;
32228 var ow = w, oh = h;
32229 var mw = this.minWidth, mh = this.minHeight;
32230 var mxw = this.maxWidth, mxh = this.maxHeight;
32231 var wi = this.widthIncrement;
32232 var hi = this.heightIncrement;
32234 var eventXY = e.getXY();
32235 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
32236 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
32238 var pos = this.activeHandle.position;
32243 w = Math.min(Math.max(mw, w), mxw);
32248 h = Math.min(Math.max(mh, h), mxh);
32253 w = Math.min(Math.max(mw, w), mxw);
32254 h = Math.min(Math.max(mh, h), mxh);
32257 diffY = this.constrain(h, diffY, mh, mxh);
32264 var adiffX = Math.abs(diffX);
32265 var sub = (adiffX % wi); // how much
32266 if (sub > (wi/2)) { // far enough to snap
32267 diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
32269 // remove difference..
32270 diffX = (diffX > 0) ? diffX-sub : diffX+sub;
32274 x = Math.max(this.minX, x);
32277 diffX = this.constrain(w, diffX, mw, mxw);
32283 w = Math.min(Math.max(mw, w), mxw);
32284 diffY = this.constrain(h, diffY, mh, mxh);
32289 diffX = this.constrain(w, diffX, mw, mxw);
32290 diffY = this.constrain(h, diffY, mh, mxh);
32297 diffX = this.constrain(w, diffX, mw, mxw);
32299 h = Math.min(Math.max(mh, h), mxh);
32305 var sw = this.snap(w, wi, mw);
32306 var sh = this.snap(h, hi, mh);
32307 if(sw != w || sh != h){
32330 if(this.preserveRatio){
32335 h = Math.min(Math.max(mh, h), mxh);
32340 w = Math.min(Math.max(mw, w), mxw);
32345 w = Math.min(Math.max(mw, w), mxw);
32351 w = Math.min(Math.max(mw, w), mxw);
32357 h = Math.min(Math.max(mh, h), mxh);
32365 h = Math.min(Math.max(mh, h), mxh);
32375 h = Math.min(Math.max(mh, h), mxh);
32383 if (pos == 'hdrag') {
32386 this.proxy.setBounds(x, y, w, h);
32388 this.resizeElement();
32392 this.fireEvent("resizing", this, x, y, w, h, e);
32396 handleOver : function(){
32398 this.el.addClass("x-resizable-over");
32403 handleOut : function(){
32404 if(!this.resizing){
32405 this.el.removeClass("x-resizable-over");
32410 * Returns the element this component is bound to.
32411 * @return {Roo.Element}
32413 getEl : function(){
32418 * Returns the resizeChild element (or null).
32419 * @return {Roo.Element}
32421 getResizeChild : function(){
32422 return this.resizeChild;
32424 groupHandler : function()
32429 * Destroys this resizable. If the element was wrapped and
32430 * removeEl is not true then the element remains.
32431 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
32433 destroy : function(removeEl){
32434 this.proxy.remove();
32436 this.overlay.removeAllListeners();
32437 this.overlay.remove();
32439 var ps = Roo.Resizable.positions;
32441 if(typeof ps[k] != "function" && this[ps[k]]){
32442 var h = this[ps[k]];
32443 h.el.removeAllListeners();
32448 this.el.update("");
32455 // hash to map config positions to true positions
32456 Roo.Resizable.positions = {
32457 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
32462 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
32464 // only initialize the template if resizable is used
32465 var tpl = Roo.DomHelper.createTemplate(
32466 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
32469 Roo.Resizable.Handle.prototype.tpl = tpl;
32471 this.position = pos;
32473 // show north drag fro topdra
32474 var handlepos = pos == 'hdrag' ? 'north' : pos;
32476 this.el = this.tpl.append(rz.el.dom, [handlepos], true);
32477 if (pos == 'hdrag') {
32478 this.el.setStyle('cursor', 'pointer');
32480 this.el.unselectable();
32482 this.el.setOpacity(0);
32484 this.el.on("mousedown", this.onMouseDown, this);
32485 if(!disableTrackOver){
32486 this.el.on("mouseover", this.onMouseOver, this);
32487 this.el.on("mouseout", this.onMouseOut, this);
32492 Roo.Resizable.Handle.prototype = {
32493 afterResize : function(rz){
32498 onMouseDown : function(e){
32499 this.rz.onMouseDown(this, e);
32502 onMouseOver : function(e){
32503 this.rz.handleOver(this, e);
32506 onMouseOut : function(e){
32507 this.rz.handleOut(this, e);
32511 * Ext JS Library 1.1.1
32512 * Copyright(c) 2006-2007, Ext JS, LLC.
32514 * Originally Released Under LGPL - original licence link has changed is not relivant.
32517 * <script type="text/javascript">
32521 * @class Roo.Editor
32522 * @extends Roo.Component
32523 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
32525 * Create a new Editor
32526 * @param {Roo.form.Field} field The Field object (or descendant)
32527 * @param {Object} config The config object
32529 Roo.Editor = function(field, config){
32530 Roo.Editor.superclass.constructor.call(this, config);
32531 this.field = field;
32534 * @event beforestartedit
32535 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
32536 * false from the handler of this event.
32537 * @param {Editor} this
32538 * @param {Roo.Element} boundEl The underlying element bound to this editor
32539 * @param {Mixed} value The field value being set
32541 "beforestartedit" : true,
32544 * Fires when this editor is displayed
32545 * @param {Roo.Element} boundEl The underlying element bound to this editor
32546 * @param {Mixed} value The starting field value
32548 "startedit" : true,
32550 * @event beforecomplete
32551 * Fires after a change has been made to the field, but before the change is reflected in the underlying
32552 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
32553 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
32554 * event will not fire since no edit actually occurred.
32555 * @param {Editor} this
32556 * @param {Mixed} value The current field value
32557 * @param {Mixed} startValue The original field value
32559 "beforecomplete" : true,
32562 * Fires after editing is complete and any changed value has been written to the underlying field.
32563 * @param {Editor} this
32564 * @param {Mixed} value The current field value
32565 * @param {Mixed} startValue The original field value
32569 * @event specialkey
32570 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
32571 * {@link Roo.EventObject#getKey} to determine which key was pressed.
32572 * @param {Roo.form.Field} this
32573 * @param {Roo.EventObject} e The event object
32575 "specialkey" : true
32579 Roo.extend(Roo.Editor, Roo.Component, {
32581 * @cfg {Boolean/String} autosize
32582 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
32583 * or "height" to adopt the height only (defaults to false)
32586 * @cfg {Boolean} revertInvalid
32587 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
32588 * validation fails (defaults to true)
32591 * @cfg {Boolean} ignoreNoChange
32592 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
32593 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
32594 * will never be ignored.
32597 * @cfg {Boolean} hideEl
32598 * False to keep the bound element visible while the editor is displayed (defaults to true)
32601 * @cfg {Mixed} value
32602 * The data value of the underlying field (defaults to "")
32606 * @cfg {String} alignment
32607 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
32611 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
32612 * for bottom-right shadow (defaults to "frame")
32616 * @cfg {Boolean} constrain True to constrain the editor to the viewport
32620 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
32622 completeOnEnter : false,
32624 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
32626 cancelOnEsc : false,
32628 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
32633 onRender : function(ct, position){
32634 this.el = new Roo.Layer({
32635 shadow: this.shadow,
32641 constrain: this.constrain
32643 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
32644 if(this.field.msgTarget != 'title'){
32645 this.field.msgTarget = 'qtip';
32647 this.field.render(this.el);
32649 this.field.el.dom.setAttribute('autocomplete', 'off');
32651 this.field.on("specialkey", this.onSpecialKey, this);
32652 if(this.swallowKeys){
32653 this.field.el.swallowEvent(['keydown','keypress']);
32656 this.field.on("blur", this.onBlur, this);
32657 if(this.field.grow){
32658 this.field.on("autosize", this.el.sync, this.el, {delay:1});
32662 onSpecialKey : function(field, e)
32664 //Roo.log('editor onSpecialKey');
32665 if(this.completeOnEnter && e.getKey() == e.ENTER){
32667 this.completeEdit();
32670 // do not fire special key otherwise it might hide close the editor...
32671 if(e.getKey() == e.ENTER){
32674 if(this.cancelOnEsc && e.getKey() == e.ESC){
32678 this.fireEvent('specialkey', field, e);
32683 * Starts the editing process and shows the editor.
32684 * @param {String/HTMLElement/Element} el The element to edit
32685 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
32686 * to the innerHTML of el.
32688 startEdit : function(el, value){
32690 this.completeEdit();
32692 this.boundEl = Roo.get(el);
32693 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
32694 if(!this.rendered){
32695 this.render(this.parentEl || document.body);
32697 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
32700 this.startValue = v;
32701 this.field.setValue(v);
32703 var sz = this.boundEl.getSize();
32704 switch(this.autoSize){
32706 this.setSize(sz.width, "");
32709 this.setSize("", sz.height);
32712 this.setSize(sz.width, sz.height);
32715 this.el.alignTo(this.boundEl, this.alignment);
32716 this.editing = true;
32718 Roo.QuickTips.disable();
32724 * Sets the height and width of this editor.
32725 * @param {Number} width The new width
32726 * @param {Number} height The new height
32728 setSize : function(w, h){
32729 this.field.setSize(w, h);
32736 * Realigns the editor to the bound field based on the current alignment config value.
32738 realign : function(){
32739 this.el.alignTo(this.boundEl, this.alignment);
32743 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
32744 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
32746 completeEdit : function(remainVisible){
32750 var v = this.getValue();
32751 if(this.revertInvalid !== false && !this.field.isValid()){
32752 v = this.startValue;
32753 this.cancelEdit(true);
32755 if(String(v) === String(this.startValue) && this.ignoreNoChange){
32756 this.editing = false;
32760 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
32761 this.editing = false;
32762 if(this.updateEl && this.boundEl){
32763 this.boundEl.update(v);
32765 if(remainVisible !== true){
32768 this.fireEvent("complete", this, v, this.startValue);
32773 onShow : function(){
32775 if(this.hideEl !== false){
32776 this.boundEl.hide();
32779 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
32780 this.fixIEFocus = true;
32781 this.deferredFocus.defer(50, this);
32783 this.field.focus();
32785 this.fireEvent("startedit", this.boundEl, this.startValue);
32788 deferredFocus : function(){
32790 this.field.focus();
32795 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
32796 * reverted to the original starting value.
32797 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
32798 * cancel (defaults to false)
32800 cancelEdit : function(remainVisible){
32802 this.setValue(this.startValue);
32803 if(remainVisible !== true){
32810 onBlur : function(){
32811 if(this.allowBlur !== true && this.editing){
32812 this.completeEdit();
32817 onHide : function(){
32819 this.completeEdit();
32823 if(this.field.collapse){
32824 this.field.collapse();
32827 if(this.hideEl !== false){
32828 this.boundEl.show();
32831 Roo.QuickTips.enable();
32836 * Sets the data value of the editor
32837 * @param {Mixed} value Any valid value supported by the underlying field
32839 setValue : function(v){
32840 this.field.setValue(v);
32844 * Gets the data value of the editor
32845 * @return {Mixed} The data value
32847 getValue : function(){
32848 return this.field.getValue();
32852 * Ext JS Library 1.1.1
32853 * Copyright(c) 2006-2007, Ext JS, LLC.
32855 * Originally Released Under LGPL - original licence link has changed is not relivant.
32858 * <script type="text/javascript">
32862 * @class Roo.BasicDialog
32863 * @extends Roo.util.Observable
32864 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
32866 var dlg = new Roo.BasicDialog("my-dlg", {
32875 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
32876 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
32877 dlg.addButton('Cancel', dlg.hide, dlg);
32880 <b>A Dialog should always be a direct child of the body element.</b>
32881 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
32882 * @cfg {String} title Default text to display in the title bar (defaults to null)
32883 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
32884 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
32885 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
32886 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
32887 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
32888 * (defaults to null with no animation)
32889 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
32890 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
32891 * property for valid values (defaults to 'all')
32892 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
32893 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
32894 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
32895 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
32896 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
32897 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
32898 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
32899 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
32900 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
32901 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
32902 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
32903 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
32904 * draggable = true (defaults to false)
32905 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
32906 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
32907 * shadow (defaults to false)
32908 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
32909 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
32910 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
32911 * @cfg {Array} buttons Array of buttons
32912 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
32914 * Create a new BasicDialog.
32915 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
32916 * @param {Object} config Configuration options
32918 Roo.BasicDialog = function(el, config){
32919 this.el = Roo.get(el);
32920 var dh = Roo.DomHelper;
32921 if(!this.el && config && config.autoCreate){
32922 if(typeof config.autoCreate == "object"){
32923 if(!config.autoCreate.id){
32924 config.autoCreate.id = el;
32926 this.el = dh.append(document.body,
32927 config.autoCreate, true);
32929 this.el = dh.append(document.body,
32930 {tag: "div", id: el, style:'visibility:hidden;'}, true);
32934 el.setDisplayed(true);
32935 el.hide = this.hideAction;
32937 el.addClass("x-dlg");
32939 Roo.apply(this, config);
32941 this.proxy = el.createProxy("x-dlg-proxy");
32942 this.proxy.hide = this.hideAction;
32943 this.proxy.setOpacity(.5);
32947 el.setWidth(config.width);
32950 el.setHeight(config.height);
32952 this.size = el.getSize();
32953 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
32954 this.xy = [config.x,config.y];
32956 this.xy = el.getCenterXY(true);
32958 /** The header element @type Roo.Element */
32959 this.header = el.child("> .x-dlg-hd");
32960 /** The body element @type Roo.Element */
32961 this.body = el.child("> .x-dlg-bd");
32962 /** The footer element @type Roo.Element */
32963 this.footer = el.child("> .x-dlg-ft");
32966 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
32969 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
32972 this.header.unselectable();
32974 this.header.update(this.title);
32976 // this element allows the dialog to be focused for keyboard event
32977 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
32978 this.focusEl.swallowEvent("click", true);
32980 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
32982 // wrap the body and footer for special rendering
32983 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
32985 this.bwrap.dom.appendChild(this.footer.dom);
32988 this.bg = this.el.createChild({
32989 tag: "div", cls:"x-dlg-bg",
32990 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
32992 this.centerBg = this.bg.child("div.x-dlg-bg-center");
32995 if(this.autoScroll !== false && !this.autoTabs){
32996 this.body.setStyle("overflow", "auto");
32999 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
33001 if(this.closable !== false){
33002 this.el.addClass("x-dlg-closable");
33003 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
33004 this.close.on("click", this.closeClick, this);
33005 this.close.addClassOnOver("x-dlg-close-over");
33007 if(this.collapsible !== false){
33008 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
33009 this.collapseBtn.on("click", this.collapseClick, this);
33010 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
33011 this.header.on("dblclick", this.collapseClick, this);
33013 if(this.resizable !== false){
33014 this.el.addClass("x-dlg-resizable");
33015 this.resizer = new Roo.Resizable(el, {
33016 minWidth: this.minWidth || 80,
33017 minHeight:this.minHeight || 80,
33018 handles: this.resizeHandles || "all",
33021 this.resizer.on("beforeresize", this.beforeResize, this);
33022 this.resizer.on("resize", this.onResize, this);
33024 if(this.draggable !== false){
33025 el.addClass("x-dlg-draggable");
33026 if (!this.proxyDrag) {
33027 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
33030 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
33032 dd.setHandleElId(this.header.id);
33033 dd.endDrag = this.endMove.createDelegate(this);
33034 dd.startDrag = this.startMove.createDelegate(this);
33035 dd.onDrag = this.onDrag.createDelegate(this);
33040 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
33041 this.mask.enableDisplayMode("block");
33043 this.el.addClass("x-dlg-modal");
33046 this.shadow = new Roo.Shadow({
33047 mode : typeof this.shadow == "string" ? this.shadow : "sides",
33048 offset : this.shadowOffset
33051 this.shadowOffset = 0;
33053 if(Roo.useShims && this.shim !== false){
33054 this.shim = this.el.createShim();
33055 this.shim.hide = this.hideAction;
33063 if (this.buttons) {
33064 var bts= this.buttons;
33066 Roo.each(bts, function(b) {
33075 * Fires when a key is pressed
33076 * @param {Roo.BasicDialog} this
33077 * @param {Roo.EventObject} e
33082 * Fires when this dialog is moved by the user.
33083 * @param {Roo.BasicDialog} this
33084 * @param {Number} x The new page X
33085 * @param {Number} y The new page Y
33090 * Fires when this dialog is resized by the user.
33091 * @param {Roo.BasicDialog} this
33092 * @param {Number} width The new width
33093 * @param {Number} height The new height
33097 * @event beforehide
33098 * Fires before this dialog is hidden.
33099 * @param {Roo.BasicDialog} this
33101 "beforehide" : true,
33104 * Fires when this dialog is hidden.
33105 * @param {Roo.BasicDialog} this
33109 * @event beforeshow
33110 * Fires before this dialog is shown.
33111 * @param {Roo.BasicDialog} this
33113 "beforeshow" : true,
33116 * Fires when this dialog is shown.
33117 * @param {Roo.BasicDialog} this
33121 el.on("keydown", this.onKeyDown, this);
33122 el.on("mousedown", this.toFront, this);
33123 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
33125 Roo.DialogManager.register(this);
33126 Roo.BasicDialog.superclass.constructor.call(this);
33129 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
33130 shadowOffset: Roo.isIE ? 6 : 5,
33133 minButtonWidth: 75,
33134 defaultButton: null,
33135 buttonAlign: "right",
33140 * Sets the dialog title text
33141 * @param {String} text The title text to display
33142 * @return {Roo.BasicDialog} this
33144 setTitle : function(text){
33145 this.header.update(text);
33150 closeClick : function(){
33155 collapseClick : function(){
33156 this[this.collapsed ? "expand" : "collapse"]();
33160 * Collapses the dialog to its minimized state (only the title bar is visible).
33161 * Equivalent to the user clicking the collapse dialog button.
33163 collapse : function(){
33164 if(!this.collapsed){
33165 this.collapsed = true;
33166 this.el.addClass("x-dlg-collapsed");
33167 this.restoreHeight = this.el.getHeight();
33168 this.resizeTo(this.el.getWidth(), this.header.getHeight());
33173 * Expands a collapsed dialog back to its normal state. Equivalent to the user
33174 * clicking the expand dialog button.
33176 expand : function(){
33177 if(this.collapsed){
33178 this.collapsed = false;
33179 this.el.removeClass("x-dlg-collapsed");
33180 this.resizeTo(this.el.getWidth(), this.restoreHeight);
33185 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
33186 * @return {Roo.TabPanel} The tabs component
33188 initTabs : function(){
33189 var tabs = this.getTabs();
33190 while(tabs.getTab(0)){
33193 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
33195 tabs.addTab(Roo.id(dom), dom.title);
33203 beforeResize : function(){
33204 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
33208 onResize : function(){
33209 this.refreshSize();
33210 this.syncBodyHeight();
33211 this.adjustAssets();
33213 this.fireEvent("resize", this, this.size.width, this.size.height);
33217 onKeyDown : function(e){
33218 if(this.isVisible()){
33219 this.fireEvent("keydown", this, e);
33224 * Resizes the dialog.
33225 * @param {Number} width
33226 * @param {Number} height
33227 * @return {Roo.BasicDialog} this
33229 resizeTo : function(width, height){
33230 this.el.setSize(width, height);
33231 this.size = {width: width, height: height};
33232 this.syncBodyHeight();
33233 if(this.fixedcenter){
33236 if(this.isVisible()){
33237 this.constrainXY();
33238 this.adjustAssets();
33240 this.fireEvent("resize", this, width, height);
33246 * Resizes the dialog to fit the specified content size.
33247 * @param {Number} width
33248 * @param {Number} height
33249 * @return {Roo.BasicDialog} this
33251 setContentSize : function(w, h){
33252 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
33253 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
33254 //if(!this.el.isBorderBox()){
33255 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
33256 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
33259 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
33260 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
33262 this.resizeTo(w, h);
33267 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
33268 * executed in response to a particular key being pressed while the dialog is active.
33269 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
33270 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
33271 * @param {Function} fn The function to call
33272 * @param {Object} scope (optional) The scope of the function
33273 * @return {Roo.BasicDialog} this
33275 addKeyListener : function(key, fn, scope){
33276 var keyCode, shift, ctrl, alt;
33277 if(typeof key == "object" && !(key instanceof Array)){
33278 keyCode = key["key"];
33279 shift = key["shift"];
33280 ctrl = key["ctrl"];
33285 var handler = function(dlg, e){
33286 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
33287 var k = e.getKey();
33288 if(keyCode instanceof Array){
33289 for(var i = 0, len = keyCode.length; i < len; i++){
33290 if(keyCode[i] == k){
33291 fn.call(scope || window, dlg, k, e);
33297 fn.call(scope || window, dlg, k, e);
33302 this.on("keydown", handler);
33307 * Returns the TabPanel component (creates it if it doesn't exist).
33308 * Note: If you wish to simply check for the existence of tabs without creating them,
33309 * check for a null 'tabs' property.
33310 * @return {Roo.TabPanel} The tabs component
33312 getTabs : function(){
33314 this.el.addClass("x-dlg-auto-tabs");
33315 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
33316 this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
33322 * Adds a button to the footer section of the dialog.
33323 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
33324 * object or a valid Roo.DomHelper element config
33325 * @param {Function} handler The function called when the button is clicked
33326 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
33327 * @return {Roo.Button} The new button
33329 addButton : function(config, handler, scope){
33330 var dh = Roo.DomHelper;
33332 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
33334 if(!this.btnContainer){
33335 var tb = this.footer.createChild({
33337 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
33338 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
33340 this.btnContainer = tb.firstChild.firstChild.firstChild;
33345 minWidth: this.minButtonWidth,
33348 if(typeof config == "string"){
33349 bconfig.text = config;
33352 bconfig.dhconfig = config;
33354 Roo.apply(bconfig, config);
33358 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
33359 bconfig.position = Math.max(0, bconfig.position);
33360 fc = this.btnContainer.childNodes[bconfig.position];
33363 var btn = new Roo.Button(
33365 this.btnContainer.insertBefore(document.createElement("td"),fc)
33366 : this.btnContainer.appendChild(document.createElement("td")),
33367 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
33370 this.syncBodyHeight();
33373 * Array of all the buttons that have been added to this dialog via addButton
33378 this.buttons.push(btn);
33383 * Sets the default button to be focused when the dialog is displayed.
33384 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
33385 * @return {Roo.BasicDialog} this
33387 setDefaultButton : function(btn){
33388 this.defaultButton = btn;
33393 getHeaderFooterHeight : function(safe){
33396 height += this.header.getHeight();
33399 var fm = this.footer.getMargins();
33400 height += (this.footer.getHeight()+fm.top+fm.bottom);
33402 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
33403 height += this.centerBg.getPadding("tb");
33408 syncBodyHeight : function()
33410 var bd = this.body, // the text
33411 cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
33413 var height = this.size.height - this.getHeaderFooterHeight(false);
33414 bd.setHeight(height-bd.getMargins("tb"));
33415 var hh = this.header.getHeight();
33416 var h = this.size.height-hh;
33419 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
33420 bw.setHeight(h-cb.getPadding("tb"));
33422 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
33423 bd.setWidth(bw.getWidth(true));
33425 this.tabs.syncHeight();
33427 this.tabs.el.repaint();
33433 * Restores the previous state of the dialog if Roo.state is configured.
33434 * @return {Roo.BasicDialog} this
33436 restoreState : function(){
33437 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
33438 if(box && box.width){
33439 this.xy = [box.x, box.y];
33440 this.resizeTo(box.width, box.height);
33446 beforeShow : function(){
33448 if(this.fixedcenter){
33449 this.xy = this.el.getCenterXY(true);
33452 Roo.get(document.body).addClass("x-body-masked");
33453 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
33456 this.constrainXY();
33460 animShow : function(){
33461 var b = Roo.get(this.animateTarget).getBox();
33462 this.proxy.setSize(b.width, b.height);
33463 this.proxy.setLocation(b.x, b.y);
33465 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
33466 true, .35, this.showEl.createDelegate(this));
33470 * Shows the dialog.
33471 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
33472 * @return {Roo.BasicDialog} this
33474 show : function(animateTarget){
33475 if (this.fireEvent("beforeshow", this) === false){
33478 if(this.syncHeightBeforeShow){
33479 this.syncBodyHeight();
33480 }else if(this.firstShow){
33481 this.firstShow = false;
33482 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
33484 this.animateTarget = animateTarget || this.animateTarget;
33485 if(!this.el.isVisible()){
33487 if(this.animateTarget && Roo.get(this.animateTarget)){
33497 showEl : function(){
33499 this.el.setXY(this.xy);
33501 this.adjustAssets(true);
33504 // IE peekaboo bug - fix found by Dave Fenwick
33508 this.fireEvent("show", this);
33512 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
33513 * dialog itself will receive focus.
33515 focus : function(){
33516 if(this.defaultButton){
33517 this.defaultButton.focus();
33519 this.focusEl.focus();
33524 constrainXY : function(){
33525 if(this.constraintoviewport !== false){
33526 if(!this.viewSize){
33527 if(this.container){
33528 var s = this.container.getSize();
33529 this.viewSize = [s.width, s.height];
33531 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
33534 var s = Roo.get(this.container||document).getScroll();
33536 var x = this.xy[0], y = this.xy[1];
33537 var w = this.size.width, h = this.size.height;
33538 var vw = this.viewSize[0], vh = this.viewSize[1];
33539 // only move it if it needs it
33541 // first validate right/bottom
33542 if(x + w > vw+s.left){
33546 if(y + h > vh+s.top){
33550 // then make sure top/left isn't negative
33562 if(this.isVisible()){
33563 this.el.setLocation(x, y);
33564 this.adjustAssets();
33571 onDrag : function(){
33572 if(!this.proxyDrag){
33573 this.xy = this.el.getXY();
33574 this.adjustAssets();
33579 adjustAssets : function(doShow){
33580 var x = this.xy[0], y = this.xy[1];
33581 var w = this.size.width, h = this.size.height;
33582 if(doShow === true){
33584 this.shadow.show(this.el);
33590 if(this.shadow && this.shadow.isVisible()){
33591 this.shadow.show(this.el);
33593 if(this.shim && this.shim.isVisible()){
33594 this.shim.setBounds(x, y, w, h);
33599 adjustViewport : function(w, h){
33601 w = Roo.lib.Dom.getViewWidth();
33602 h = Roo.lib.Dom.getViewHeight();
33605 this.viewSize = [w, h];
33606 if(this.modal && this.mask.isVisible()){
33607 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
33608 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
33610 if(this.isVisible()){
33611 this.constrainXY();
33616 * Destroys this dialog and all its supporting elements (including any tabs, shim,
33617 * shadow, proxy, mask, etc.) Also removes all event listeners.
33618 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
33620 destroy : function(removeEl){
33621 if(this.isVisible()){
33622 this.animateTarget = null;
33625 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
33627 this.tabs.destroy(removeEl);
33640 for(var i = 0, len = this.buttons.length; i < len; i++){
33641 this.buttons[i].destroy();
33644 this.el.removeAllListeners();
33645 if(removeEl === true){
33646 this.el.update("");
33649 Roo.DialogManager.unregister(this);
33653 startMove : function(){
33654 if(this.proxyDrag){
33657 if(this.constraintoviewport !== false){
33658 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
33663 endMove : function(){
33664 if(!this.proxyDrag){
33665 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
33667 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
33670 this.refreshSize();
33671 this.adjustAssets();
33673 this.fireEvent("move", this, this.xy[0], this.xy[1]);
33677 * Brings this dialog to the front of any other visible dialogs
33678 * @return {Roo.BasicDialog} this
33680 toFront : function(){
33681 Roo.DialogManager.bringToFront(this);
33686 * Sends this dialog to the back (under) of any other visible dialogs
33687 * @return {Roo.BasicDialog} this
33689 toBack : function(){
33690 Roo.DialogManager.sendToBack(this);
33695 * Centers this dialog in the viewport
33696 * @return {Roo.BasicDialog} this
33698 center : function(){
33699 var xy = this.el.getCenterXY(true);
33700 this.moveTo(xy[0], xy[1]);
33705 * Moves the dialog's top-left corner to the specified point
33706 * @param {Number} x
33707 * @param {Number} y
33708 * @return {Roo.BasicDialog} this
33710 moveTo : function(x, y){
33712 if(this.isVisible()){
33713 this.el.setXY(this.xy);
33714 this.adjustAssets();
33720 * Aligns the dialog to the specified element
33721 * @param {String/HTMLElement/Roo.Element} element The element to align to.
33722 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
33723 * @param {Array} offsets (optional) Offset the positioning by [x, y]
33724 * @return {Roo.BasicDialog} this
33726 alignTo : function(element, position, offsets){
33727 this.xy = this.el.getAlignToXY(element, position, offsets);
33728 if(this.isVisible()){
33729 this.el.setXY(this.xy);
33730 this.adjustAssets();
33736 * Anchors an element to another element and realigns it when the window is resized.
33737 * @param {String/HTMLElement/Roo.Element} element The element to align to.
33738 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
33739 * @param {Array} offsets (optional) Offset the positioning by [x, y]
33740 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
33741 * is a number, it is used as the buffer delay (defaults to 50ms).
33742 * @return {Roo.BasicDialog} this
33744 anchorTo : function(el, alignment, offsets, monitorScroll){
33745 var action = function(){
33746 this.alignTo(el, alignment, offsets);
33748 Roo.EventManager.onWindowResize(action, this);
33749 var tm = typeof monitorScroll;
33750 if(tm != 'undefined'){
33751 Roo.EventManager.on(window, 'scroll', action, this,
33752 {buffer: tm == 'number' ? monitorScroll : 50});
33759 * Returns true if the dialog is visible
33760 * @return {Boolean}
33762 isVisible : function(){
33763 return this.el.isVisible();
33767 animHide : function(callback){
33768 var b = Roo.get(this.animateTarget).getBox();
33770 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
33772 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
33773 this.hideEl.createDelegate(this, [callback]));
33777 * Hides the dialog.
33778 * @param {Function} callback (optional) Function to call when the dialog is hidden
33779 * @return {Roo.BasicDialog} this
33781 hide : function(callback){
33782 if (this.fireEvent("beforehide", this) === false){
33786 this.shadow.hide();
33791 // sometimes animateTarget seems to get set.. causing problems...
33792 // this just double checks..
33793 if(this.animateTarget && Roo.get(this.animateTarget)) {
33794 this.animHide(callback);
33797 this.hideEl(callback);
33803 hideEl : function(callback){
33807 Roo.get(document.body).removeClass("x-body-masked");
33809 this.fireEvent("hide", this);
33810 if(typeof callback == "function"){
33816 hideAction : function(){
33817 this.setLeft("-10000px");
33818 this.setTop("-10000px");
33819 this.setStyle("visibility", "hidden");
33823 refreshSize : function(){
33824 this.size = this.el.getSize();
33825 this.xy = this.el.getXY();
33826 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
33830 // z-index is managed by the DialogManager and may be overwritten at any time
33831 setZIndex : function(index){
33833 this.mask.setStyle("z-index", index);
33836 this.shim.setStyle("z-index", ++index);
33839 this.shadow.setZIndex(++index);
33841 this.el.setStyle("z-index", ++index);
33843 this.proxy.setStyle("z-index", ++index);
33846 this.resizer.proxy.setStyle("z-index", ++index);
33849 this.lastZIndex = index;
33853 * Returns the element for this dialog
33854 * @return {Roo.Element} The underlying dialog Element
33856 getEl : function(){
33862 * @class Roo.DialogManager
33863 * Provides global access to BasicDialogs that have been created and
33864 * support for z-indexing (layering) multiple open dialogs.
33866 Roo.DialogManager = function(){
33868 var accessList = [];
33872 var sortDialogs = function(d1, d2){
33873 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
33877 var orderDialogs = function(){
33878 accessList.sort(sortDialogs);
33879 var seed = Roo.DialogManager.zseed;
33880 for(var i = 0, len = accessList.length; i < len; i++){
33881 var dlg = accessList[i];
33883 dlg.setZIndex(seed + (i*10));
33890 * The starting z-index for BasicDialogs (defaults to 9000)
33891 * @type Number The z-index value
33896 register : function(dlg){
33897 list[dlg.id] = dlg;
33898 accessList.push(dlg);
33902 unregister : function(dlg){
33903 delete list[dlg.id];
33906 if(!accessList.indexOf){
33907 for( i = 0, len = accessList.length; i < len; i++){
33908 if(accessList[i] == dlg){
33909 accessList.splice(i, 1);
33914 i = accessList.indexOf(dlg);
33916 accessList.splice(i, 1);
33922 * Gets a registered dialog by id
33923 * @param {String/Object} id The id of the dialog or a dialog
33924 * @return {Roo.BasicDialog} this
33926 get : function(id){
33927 return typeof id == "object" ? id : list[id];
33931 * Brings the specified dialog to the front
33932 * @param {String/Object} dlg The id of the dialog or a dialog
33933 * @return {Roo.BasicDialog} this
33935 bringToFront : function(dlg){
33936 dlg = this.get(dlg);
33939 dlg._lastAccess = new Date().getTime();
33946 * Sends the specified dialog to the back
33947 * @param {String/Object} dlg The id of the dialog or a dialog
33948 * @return {Roo.BasicDialog} this
33950 sendToBack : function(dlg){
33951 dlg = this.get(dlg);
33952 dlg._lastAccess = -(new Date().getTime());
33958 * Hides all dialogs
33960 hideAll : function(){
33961 for(var id in list){
33962 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
33971 * @class Roo.LayoutDialog
33972 * @extends Roo.BasicDialog
33973 * @children Roo.ContentPanel
33974 * @parent builder none
33975 * Dialog which provides adjustments for working with a layout in a Dialog.
33976 * Add your necessary layout config options to the dialog's config.<br>
33977 * Example usage (including a nested layout):
33980 dialog = new Roo.LayoutDialog("download-dlg", {
33989 // layout config merges with the dialog config
33991 tabPosition: "top",
33992 alwaysShowTabs: true
33995 dialog.addKeyListener(27, dialog.hide, dialog);
33996 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
33997 dialog.addButton("Build It!", this.getDownload, this);
33999 // we can even add nested layouts
34000 var innerLayout = new Roo.BorderLayout("dl-inner", {
34010 innerLayout.beginUpdate();
34011 innerLayout.add("east", new Roo.ContentPanel("dl-details"));
34012 innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
34013 innerLayout.endUpdate(true);
34015 var layout = dialog.getLayout();
34016 layout.beginUpdate();
34017 layout.add("center", new Roo.ContentPanel("standard-panel",
34018 {title: "Download the Source", fitToFrame:true}));
34019 layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
34020 {title: "Build your own roo.js"}));
34021 layout.getRegion("center").showPanel(sp);
34022 layout.endUpdate();
34026 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
34027 * @param {Object} config configuration options
34029 Roo.LayoutDialog = function(el, cfg){
34032 if (typeof(cfg) == 'undefined') {
34033 config = Roo.apply({}, el);
34034 // not sure why we use documentElement here.. - it should always be body.
34035 // IE7 borks horribly if we use documentElement.
34036 // webkit also does not like documentElement - it creates a body element...
34037 el = Roo.get( document.body || document.documentElement ).createChild();
34038 //config.autoCreate = true;
34042 config.autoTabs = false;
34043 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
34044 this.body.setStyle({overflow:"hidden", position:"relative"});
34045 this.layout = new Roo.BorderLayout(this.body.dom, config);
34046 this.layout.monitorWindowResize = false;
34047 this.el.addClass("x-dlg-auto-layout");
34048 // fix case when center region overwrites center function
34049 this.center = Roo.BasicDialog.prototype.center;
34050 this.on("show", this.layout.layout, this.layout, true);
34051 if (config.items) {
34052 var xitems = config.items;
34053 delete config.items;
34054 Roo.each(xitems, this.addxtype, this);
34059 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
34063 * @cfg {Roo.LayoutRegion} east
34066 * @cfg {Roo.LayoutRegion} west
34069 * @cfg {Roo.LayoutRegion} south
34072 * @cfg {Roo.LayoutRegion} north
34075 * @cfg {Roo.LayoutRegion} center
34078 * @cfg {Roo.Button} buttons[] Bottom buttons..
34083 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
34086 endUpdate : function(){
34087 this.layout.endUpdate();
34091 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
34094 beginUpdate : function(){
34095 this.layout.beginUpdate();
34099 * Get the BorderLayout for this dialog
34100 * @return {Roo.BorderLayout}
34102 getLayout : function(){
34103 return this.layout;
34106 showEl : function(){
34107 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
34109 this.layout.layout();
34114 // Use the syncHeightBeforeShow config option to control this automatically
34115 syncBodyHeight : function(){
34116 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
34117 if(this.layout){this.layout.layout();}
34121 * Add an xtype element (actually adds to the layout.)
34122 * @return {Object} xdata xtype object data.
34125 addxtype : function(c) {
34126 return this.layout.addxtype(c);
34130 * Ext JS Library 1.1.1
34131 * Copyright(c) 2006-2007, Ext JS, LLC.
34133 * Originally Released Under LGPL - original licence link has changed is not relivant.
34136 * <script type="text/javascript">
34140 * @class Roo.MessageBox
34141 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
34145 Roo.Msg.alert('Status', 'Changes saved successfully.');
34147 // Prompt for user data:
34148 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
34150 // process text value...
34154 // Show a dialog using config options:
34156 title:'Save Changes?',
34157 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
34158 buttons: Roo.Msg.YESNOCANCEL,
34165 Roo.MessageBox = function(){
34166 var dlg, opt, mask, waitTimer;
34167 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
34168 var buttons, activeTextEl, bwidth;
34171 var handleButton = function(button){
34173 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
34177 var handleHide = function(){
34178 if(opt && opt.cls){
34179 dlg.el.removeClass(opt.cls);
34182 Roo.TaskMgr.stop(waitTimer);
34188 var updateButtons = function(b){
34191 buttons["ok"].hide();
34192 buttons["cancel"].hide();
34193 buttons["yes"].hide();
34194 buttons["no"].hide();
34195 dlg.footer.dom.style.display = 'none';
34198 dlg.footer.dom.style.display = '';
34199 for(var k in buttons){
34200 if(typeof buttons[k] != "function"){
34203 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
34204 width += buttons[k].el.getWidth()+15;
34214 var handleEsc = function(d, k, e){
34215 if(opt && opt.closable !== false){
34225 * Returns a reference to the underlying {@link Roo.BasicDialog} element
34226 * @return {Roo.BasicDialog} The BasicDialog element
34228 getDialog : function(){
34230 dlg = new Roo.BasicDialog("x-msg-box", {
34235 constraintoviewport:false,
34237 collapsible : false,
34240 width:400, height:100,
34241 buttonAlign:"center",
34242 closeClick : function(){
34243 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
34244 handleButton("no");
34246 handleButton("cancel");
34250 dlg.on("hide", handleHide);
34252 dlg.addKeyListener(27, handleEsc);
34254 var bt = this.buttonText;
34255 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
34256 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
34257 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
34258 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
34259 bodyEl = dlg.body.createChild({
34261 html:'<span class="roo-mb-text"></span><br /><input type="text" class="roo-mb-input" /><textarea class="roo-mb-textarea"></textarea><div class="roo-mb-progress-wrap"><div class="roo-mb-progress"><div class="roo-mb-progress-bar"> </div></div></div>'
34263 msgEl = bodyEl.dom.firstChild;
34264 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
34265 textboxEl.enableDisplayMode();
34266 textboxEl.addKeyListener([10,13], function(){
34267 if(dlg.isVisible() && opt && opt.buttons){
34268 if(opt.buttons.ok){
34269 handleButton("ok");
34270 }else if(opt.buttons.yes){
34271 handleButton("yes");
34275 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
34276 textareaEl.enableDisplayMode();
34277 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
34278 progressEl.enableDisplayMode();
34279 var pf = progressEl.dom.firstChild;
34281 pp = Roo.get(pf.firstChild);
34282 pp.setHeight(pf.offsetHeight);
34290 * Updates the message box body text
34291 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
34292 * the XHTML-compliant non-breaking space character '&#160;')
34293 * @return {Roo.MessageBox} This message box
34295 updateText : function(text){
34296 if(!dlg.isVisible() && !opt.width){
34297 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
34299 msgEl.innerHTML = text || ' ';
34301 var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
34302 //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
34304 Math.min(opt.width || cw , this.maxWidth),
34305 Math.max(opt.minWidth || this.minWidth, bwidth)
34308 activeTextEl.setWidth(w);
34310 if(dlg.isVisible()){
34311 dlg.fixedcenter = false;
34313 // to big, make it scroll. = But as usual stupid IE does not support
34316 if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
34317 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
34318 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
34320 bodyEl.dom.style.height = '';
34321 bodyEl.dom.style.overflowY = '';
34324 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
34326 bodyEl.dom.style.overflowX = '';
34329 dlg.setContentSize(w, bodyEl.getHeight());
34330 if(dlg.isVisible()){
34331 dlg.fixedcenter = true;
34337 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
34338 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
34339 * @param {Number} value Any number between 0 and 1 (e.g., .5)
34340 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
34341 * @return {Roo.MessageBox} This message box
34343 updateProgress : function(value, text){
34345 this.updateText(text);
34347 if (pp) { // weird bug on my firefox - for some reason this is not defined
34348 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
34354 * Returns true if the message box is currently displayed
34355 * @return {Boolean} True if the message box is visible, else false
34357 isVisible : function(){
34358 return dlg && dlg.isVisible();
34362 * Hides the message box if it is displayed
34365 if(this.isVisible()){
34371 * Displays a new message box, or reinitializes an existing message box, based on the config options
34372 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
34373 * The following config object properties are supported:
34375 Property Type Description
34376 ---------- --------------- ------------------------------------------------------------------------------------
34377 animEl String/Element An id or Element from which the message box should animate as it opens and
34378 closes (defaults to undefined)
34379 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
34380 cancel:'Bar'}), or false to not show any buttons (defaults to false)
34381 closable Boolean False to hide the top-right close button (defaults to true). Note that
34382 progress and wait dialogs will ignore this property and always hide the
34383 close button as they can only be closed programmatically.
34384 cls String A custom CSS class to apply to the message box element
34385 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
34386 displayed (defaults to 75)
34387 fn Function A callback function to execute after closing the dialog. The arguments to the
34388 function will be btn (the name of the button that was clicked, if applicable,
34389 e.g. "ok"), and text (the value of the active text field, if applicable).
34390 Progress and wait dialogs will ignore this option since they do not respond to
34391 user actions and can only be closed programmatically, so any required function
34392 should be called by the same code after it closes the dialog.
34393 icon String A CSS class that provides a background image to be used as an icon for
34394 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
34395 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
34396 minWidth Number The minimum width in pixels of the message box (defaults to 100)
34397 modal Boolean False to allow user interaction with the page while the message box is
34398 displayed (defaults to true)
34399 msg String A string that will replace the existing message box body text (defaults
34400 to the XHTML-compliant non-breaking space character ' ')
34401 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
34402 progress Boolean True to display a progress bar (defaults to false)
34403 progressText String The text to display inside the progress bar if progress = true (defaults to '')
34404 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
34405 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
34406 title String The title text
34407 value String The string value to set into the active textbox element if displayed
34408 wait Boolean True to display a progress bar (defaults to false)
34409 width Number The width of the dialog in pixels
34416 msg: 'Please enter your address:',
34418 buttons: Roo.MessageBox.OKCANCEL,
34421 animEl: 'addAddressBtn'
34424 * @param {Object} config Configuration options
34425 * @return {Roo.MessageBox} This message box
34427 show : function(options)
34430 // this causes nightmares if you show one dialog after another
34431 // especially on callbacks..
34433 if(this.isVisible()){
34436 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
34437 Roo.log("Old Dialog Message:" + msgEl.innerHTML );
34438 Roo.log("New Dialog Message:" + options.msg )
34439 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
34440 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
34443 var d = this.getDialog();
34445 d.setTitle(opt.title || " ");
34446 d.close.setDisplayed(opt.closable !== false);
34447 activeTextEl = textboxEl;
34448 opt.prompt = opt.prompt || (opt.multiline ? true : false);
34453 textareaEl.setHeight(typeof opt.multiline == "number" ?
34454 opt.multiline : this.defaultTextHeight);
34455 activeTextEl = textareaEl;
34464 progressEl.setDisplayed(opt.progress === true);
34465 this.updateProgress(0);
34466 activeTextEl.dom.value = opt.value || "";
34468 dlg.setDefaultButton(activeTextEl);
34470 var bs = opt.buttons;
34473 db = buttons["ok"];
34474 }else if(bs && bs.yes){
34475 db = buttons["yes"];
34477 dlg.setDefaultButton(db);
34479 bwidth = updateButtons(opt.buttons);
34480 this.updateText(opt.msg);
34482 d.el.addClass(opt.cls);
34484 d.proxyDrag = opt.proxyDrag === true;
34485 d.modal = opt.modal !== false;
34486 d.mask = opt.modal !== false ? mask : false;
34487 if(!d.isVisible()){
34488 // force it to the end of the z-index stack so it gets a cursor in FF
34489 document.body.appendChild(dlg.el.dom);
34490 d.animateTarget = null;
34491 d.show(options.animEl);
34497 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
34498 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
34499 * and closing the message box when the process is complete.
34500 * @param {String} title The title bar text
34501 * @param {String} msg The message box body text
34502 * @return {Roo.MessageBox} This message box
34504 progress : function(title, msg){
34511 minWidth: this.minProgressWidth,
34518 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
34519 * If a callback function is passed it will be called after the user clicks the button, and the
34520 * id of the button that was clicked will be passed as the only parameter to the callback
34521 * (could also be the top-right close button).
34522 * @param {String} title The title bar text
34523 * @param {String} msg The message box body text
34524 * @param {Function} fn (optional) The callback function invoked after the message box is closed
34525 * @param {Object} scope (optional) The scope of the callback function
34526 * @return {Roo.MessageBox} This message box
34528 alert : function(title, msg, fn, scope){
34541 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
34542 * interaction while waiting for a long-running process to complete that does not have defined intervals.
34543 * You are responsible for closing the message box when the process is complete.
34544 * @param {String} msg The message box body text
34545 * @param {String} title (optional) The title bar text
34546 * @return {Roo.MessageBox} This message box
34548 wait : function(msg, title){
34559 waitTimer = Roo.TaskMgr.start({
34561 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
34569 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
34570 * If a callback function is passed it will be called after the user clicks either button, and the id of the
34571 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
34572 * @param {String} title The title bar text
34573 * @param {String} msg The message box body text
34574 * @param {Function} fn (optional) The callback function invoked after the message box is closed
34575 * @param {Object} scope (optional) The scope of the callback function
34576 * @return {Roo.MessageBox} This message box
34578 confirm : function(title, msg, fn, scope){
34582 buttons: this.YESNO,
34591 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
34592 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
34593 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
34594 * (could also be the top-right close button) and the text that was entered will be passed as the two
34595 * parameters to the callback.
34596 * @param {String} title The title bar text
34597 * @param {String} msg The message box body text
34598 * @param {Function} fn (optional) The callback function invoked after the message box is closed
34599 * @param {Object} scope (optional) The scope of the callback function
34600 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
34601 * property, or the height in pixels to create the textbox (defaults to false / single-line)
34602 * @return {Roo.MessageBox} This message box
34604 prompt : function(title, msg, fn, scope, multiline){
34608 buttons: this.OKCANCEL,
34613 multiline: multiline,
34620 * Button config that displays a single OK button
34625 * Button config that displays Yes and No buttons
34628 YESNO : {yes:true, no:true},
34630 * Button config that displays OK and Cancel buttons
34633 OKCANCEL : {ok:true, cancel:true},
34635 * Button config that displays Yes, No and Cancel buttons
34638 YESNOCANCEL : {yes:true, no:true, cancel:true},
34641 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
34644 defaultTextHeight : 75,
34646 * The maximum width in pixels of the message box (defaults to 600)
34651 * The minimum width in pixels of the message box (defaults to 100)
34656 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
34657 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
34660 minProgressWidth : 250,
34662 * An object containing the default button text strings that can be overriden for localized language support.
34663 * Supported properties are: ok, cancel, yes and no.
34664 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
34677 * Shorthand for {@link Roo.MessageBox}
34679 Roo.Msg = Roo.MessageBox;/*
34681 * Ext JS Library 1.1.1
34682 * Copyright(c) 2006-2007, Ext JS, LLC.
34684 * Originally Released Under LGPL - original licence link has changed is not relivant.
34687 * <script type="text/javascript">
34690 * @class Roo.QuickTips
34691 * Provides attractive and customizable tooltips for any element.
34694 Roo.QuickTips = function(){
34695 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
34696 var ce, bd, xy, dd;
34697 var visible = false, disabled = true, inited = false;
34698 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
34700 var onOver = function(e){
34704 var t = e.getTarget();
34705 if(!t || t.nodeType !== 1 || t == document || t == document.body){
34708 if(ce && t == ce.el){
34709 clearTimeout(hideProc);
34712 if(t && tagEls[t.id]){
34713 tagEls[t.id].el = t;
34714 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
34717 var ttp, et = Roo.fly(t);
34718 var ns = cfg.namespace;
34719 if(tm.interceptTitles && t.title){
34722 t.removeAttribute("title");
34723 e.preventDefault();
34725 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
34728 showProc = show.defer(tm.showDelay, tm, [{
34730 text: ttp.replace(/\\n/g,'<br/>'),
34731 width: et.getAttributeNS(ns, cfg.width),
34732 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
34733 title: et.getAttributeNS(ns, cfg.title),
34734 cls: et.getAttributeNS(ns, cfg.cls)
34739 var onOut = function(e){
34740 clearTimeout(showProc);
34741 var t = e.getTarget();
34742 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
34743 hideProc = setTimeout(hide, tm.hideDelay);
34747 var onMove = function(e){
34753 if(tm.trackMouse && ce){
34758 var onDown = function(e){
34759 clearTimeout(showProc);
34760 clearTimeout(hideProc);
34762 if(tm.hideOnClick){
34765 tm.enable.defer(100, tm);
34770 var getPad = function(){
34771 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
34774 var show = function(o){
34778 clearTimeout(dismissProc);
34780 if(removeCls){ // in case manually hidden
34781 el.removeClass(removeCls);
34785 el.addClass(ce.cls);
34786 removeCls = ce.cls;
34789 tipTitle.update(ce.title);
34792 tipTitle.update('');
34795 el.dom.style.width = tm.maxWidth+'px';
34796 //tipBody.dom.style.width = '';
34797 tipBodyText.update(o.text);
34798 var p = getPad(), w = ce.width;
34800 var td = tipBodyText.dom;
34801 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
34802 if(aw > tm.maxWidth){
34804 }else if(aw < tm.minWidth){
34810 //tipBody.setWidth(w);
34811 el.setWidth(parseInt(w, 10) + p);
34812 if(ce.autoHide === false){
34813 close.setDisplayed(true);
34818 close.setDisplayed(false);
34824 el.avoidY = xy[1]-18;
34829 el.setStyle("visibility", "visible");
34830 el.fadeIn({callback: afterShow});
34836 var afterShow = function(){
34840 if(tm.autoDismiss && ce.autoHide !== false){
34841 dismissProc = setTimeout(hide, tm.autoDismissDelay);
34846 var hide = function(noanim){
34847 clearTimeout(dismissProc);
34848 clearTimeout(hideProc);
34850 if(el.isVisible()){
34852 if(noanim !== true && tm.animate){
34853 el.fadeOut({callback: afterHide});
34860 var afterHide = function(){
34863 el.removeClass(removeCls);
34870 * @cfg {Number} minWidth
34871 * The minimum width of the quick tip (defaults to 40)
34875 * @cfg {Number} maxWidth
34876 * The maximum width of the quick tip (defaults to 300)
34880 * @cfg {Boolean} interceptTitles
34881 * True to automatically use the element's DOM title value if available (defaults to false)
34883 interceptTitles : false,
34885 * @cfg {Boolean} trackMouse
34886 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
34888 trackMouse : false,
34890 * @cfg {Boolean} hideOnClick
34891 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
34893 hideOnClick : true,
34895 * @cfg {Number} showDelay
34896 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
34900 * @cfg {Number} hideDelay
34901 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
34905 * @cfg {Boolean} autoHide
34906 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
34907 * Used in conjunction with hideDelay.
34912 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
34913 * (defaults to true). Used in conjunction with autoDismissDelay.
34915 autoDismiss : true,
34918 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
34920 autoDismissDelay : 5000,
34922 * @cfg {Boolean} animate
34923 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
34928 * @cfg {String} title
34929 * Title text to display (defaults to ''). This can be any valid HTML markup.
34933 * @cfg {String} text
34934 * Body text to display (defaults to ''). This can be any valid HTML markup.
34938 * @cfg {String} cls
34939 * A CSS class to apply to the base quick tip element (defaults to '').
34943 * @cfg {Number} width
34944 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
34945 * minWidth or maxWidth.
34950 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
34951 * or display QuickTips in a page.
34954 tm = Roo.QuickTips;
34955 cfg = tm.tagConfig;
34957 if(!Roo.isReady){ // allow calling of init() before onReady
34958 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
34961 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
34962 el.fxDefaults = {stopFx: true};
34963 // maximum custom styling
34964 //el.update('<div class="x-tip-top-left"><div class="x-tip-top-right"><div class="x-tip-top"></div></div></div><div class="x-tip-bd-left"><div class="x-tip-bd-right"><div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div></div></div><div class="x-tip-ft-left"><div class="x-tip-ft-right"><div class="x-tip-ft"></div></div></div>');
34965 el.update('<div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div>');
34966 tipTitle = el.child('h3');
34967 tipTitle.enableDisplayMode("block");
34968 tipBody = el.child('div.x-tip-bd');
34969 tipBodyText = el.child('div.x-tip-bd-inner');
34970 //bdLeft = el.child('div.x-tip-bd-left');
34971 //bdRight = el.child('div.x-tip-bd-right');
34972 close = el.child('div.x-tip-close');
34973 close.enableDisplayMode("block");
34974 close.on("click", hide);
34975 var d = Roo.get(document);
34976 d.on("mousedown", onDown);
34977 d.on("mouseover", onOver);
34978 d.on("mouseout", onOut);
34979 d.on("mousemove", onMove);
34980 esc = d.addKeyListener(27, hide);
34983 dd = el.initDD("default", null, {
34984 onDrag : function(){
34988 dd.setHandleElId(tipTitle.id);
34997 * Configures a new quick tip instance and assigns it to a target element. The following config options
35000 Property Type Description
35001 ---------- --------------------- ------------------------------------------------------------------------
35002 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
35004 * @param {Object} config The config object
35006 register : function(config){
35007 var cs = config instanceof Array ? config : arguments;
35008 for(var i = 0, len = cs.length; i < len; i++) {
35010 var target = c.target;
35012 if(target instanceof Array){
35013 for(var j = 0, jlen = target.length; j < jlen; j++){
35014 tagEls[target[j]] = c;
35017 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
35024 * Removes this quick tip from its element and destroys it.
35025 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
35027 unregister : function(el){
35028 delete tagEls[Roo.id(el)];
35032 * Enable this quick tip.
35034 enable : function(){
35035 if(inited && disabled){
35037 if(locks.length < 1){
35044 * Disable this quick tip.
35046 disable : function(){
35048 clearTimeout(showProc);
35049 clearTimeout(hideProc);
35050 clearTimeout(dismissProc);
35058 * Returns true if the quick tip is enabled, else false.
35060 isEnabled : function(){
35066 namespace : "roo", // was ext?? this may break..
35067 alt_namespace : "ext",
35068 attribute : "qtip",
35078 // backwards compat
35079 Roo.QuickTips.tips = Roo.QuickTips.register;/*
35081 * Ext JS Library 1.1.1
35082 * Copyright(c) 2006-2007, Ext JS, LLC.
35084 * Originally Released Under LGPL - original licence link has changed is not relivant.
35087 * <script type="text/javascript">
35092 * @class Roo.tree.TreePanel
35093 * @extends Roo.data.Tree
35094 * @cfg {Roo.tree.TreeNode} root The root node
35095 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
35096 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
35097 * @cfg {Boolean} enableDD true to enable drag and drop
35098 * @cfg {Boolean} enableDrag true to enable just drag
35099 * @cfg {Boolean} enableDrop true to enable just drop
35100 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
35101 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
35102 * @cfg {String} ddGroup The DD group this TreePanel belongs to
35103 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
35104 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
35105 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
35106 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
35107 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
35108 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
35109 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
35110 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
35111 * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
35112 * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
35113 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
35114 * @cfg {Function} renderer DEPRECATED - use TreeLoader:create event / Sets the rendering (formatting) function for the nodes. to return HTML markup for the tree view. The render function is called with the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
35115 * @cfg {Function} rendererTip DEPRECATED - use TreeLoader:create event / Sets the rendering (formatting) function for the nodes hovertip to return HTML markup for the tree view. The render function is called with the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
35118 * @param {String/HTMLElement/Element} el The container element
35119 * @param {Object} config
35121 Roo.tree.TreePanel = function(el, config){
35123 var loader = false;
35125 root = config.root;
35126 delete config.root;
35128 if (config.loader) {
35129 loader = config.loader;
35130 delete config.loader;
35133 Roo.apply(this, config);
35134 Roo.tree.TreePanel.superclass.constructor.call(this);
35135 this.el = Roo.get(el);
35136 this.el.addClass('x-tree');
35137 //console.log(root);
35139 this.setRootNode( Roo.factory(root, Roo.tree));
35142 this.loader = Roo.factory(loader, Roo.tree);
35145 * Read-only. The id of the container element becomes this TreePanel's id.
35147 this.id = this.el.id;
35150 * @event beforeload
35151 * Fires before a node is loaded, return false to cancel
35152 * @param {Node} node The node being loaded
35154 "beforeload" : true,
35157 * Fires when a node is loaded
35158 * @param {Node} node The node that was loaded
35162 * @event textchange
35163 * Fires when the text for a node is changed
35164 * @param {Node} node The node
35165 * @param {String} text The new text
35166 * @param {String} oldText The old text
35168 "textchange" : true,
35170 * @event beforeexpand
35171 * Fires before a node is expanded, return false to cancel.
35172 * @param {Node} node The node
35173 * @param {Boolean} deep
35174 * @param {Boolean} anim
35176 "beforeexpand" : true,
35178 * @event beforecollapse
35179 * Fires before a node is collapsed, return false to cancel.
35180 * @param {Node} node The node
35181 * @param {Boolean} deep
35182 * @param {Boolean} anim
35184 "beforecollapse" : true,
35187 * Fires when a node is expanded
35188 * @param {Node} node The node
35192 * @event disabledchange
35193 * Fires when the disabled status of a node changes
35194 * @param {Node} node The node
35195 * @param {Boolean} disabled
35197 "disabledchange" : true,
35200 * Fires when a node is collapsed
35201 * @param {Node} node The node
35205 * @event beforeclick
35206 * Fires before click processing on a node. Return false to cancel the default action.
35207 * @param {Node} node The node
35208 * @param {Roo.EventObject} e The event object
35210 "beforeclick":true,
35212 * @event checkchange
35213 * Fires when a node with a checkbox's checked property changes
35214 * @param {Node} this This node
35215 * @param {Boolean} checked
35217 "checkchange":true,
35220 * Fires when a node is clicked
35221 * @param {Node} node The node
35222 * @param {Roo.EventObject} e The event object
35227 * Fires when a node is double clicked
35228 * @param {Node} node The node
35229 * @param {Roo.EventObject} e The event object
35233 * @event contextmenu
35234 * Fires when a node is right clicked
35235 * @param {Node} node The node
35236 * @param {Roo.EventObject} e The event object
35238 "contextmenu":true,
35240 * @event beforechildrenrendered
35241 * Fires right before the child nodes for a node are rendered
35242 * @param {Node} node The node
35244 "beforechildrenrendered":true,
35247 * Fires when a node starts being dragged
35248 * @param {Roo.tree.TreePanel} this
35249 * @param {Roo.tree.TreeNode} node
35250 * @param {event} e The raw browser event
35252 "startdrag" : true,
35255 * Fires when a drag operation is complete
35256 * @param {Roo.tree.TreePanel} this
35257 * @param {Roo.tree.TreeNode} node
35258 * @param {event} e The raw browser event
35263 * Fires when a dragged node is dropped on a valid DD target
35264 * @param {Roo.tree.TreePanel} this
35265 * @param {Roo.tree.TreeNode} node
35266 * @param {DD} dd The dd it was dropped on
35267 * @param {event} e The raw browser event
35271 * @event beforenodedrop
35272 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
35273 * passed to handlers has the following properties:<br />
35274 * <ul style="padding:5px;padding-left:16px;">
35275 * <li>tree - The TreePanel</li>
35276 * <li>target - The node being targeted for the drop</li>
35277 * <li>data - The drag data from the drag source</li>
35278 * <li>point - The point of the drop - append, above or below</li>
35279 * <li>source - The drag source</li>
35280 * <li>rawEvent - Raw mouse event</li>
35281 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
35282 * to be inserted by setting them on this object.</li>
35283 * <li>cancel - Set this to true to cancel the drop.</li>
35285 * @param {Object} dropEvent
35287 "beforenodedrop" : true,
35290 * Fires after a DD object is dropped on a node in this tree. The dropEvent
35291 * passed to handlers has the following properties:<br />
35292 * <ul style="padding:5px;padding-left:16px;">
35293 * <li>tree - The TreePanel</li>
35294 * <li>target - The node being targeted for the drop</li>
35295 * <li>data - The drag data from the drag source</li>
35296 * <li>point - The point of the drop - append, above or below</li>
35297 * <li>source - The drag source</li>
35298 * <li>rawEvent - Raw mouse event</li>
35299 * <li>dropNode - Dropped node(s).</li>
35301 * @param {Object} dropEvent
35305 * @event nodedragover
35306 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
35307 * passed to handlers has the following properties:<br />
35308 * <ul style="padding:5px;padding-left:16px;">
35309 * <li>tree - The TreePanel</li>
35310 * <li>target - The node being targeted for the drop</li>
35311 * <li>data - The drag data from the drag source</li>
35312 * <li>point - The point of the drop - append, above or below</li>
35313 * <li>source - The drag source</li>
35314 * <li>rawEvent - Raw mouse event</li>
35315 * <li>dropNode - Drop node(s) provided by the source.</li>
35316 * <li>cancel - Set this to true to signal drop not allowed.</li>
35318 * @param {Object} dragOverEvent
35320 "nodedragover" : true,
35322 * @event appendnode
35323 * Fires when append node to the tree
35324 * @param {Roo.tree.TreePanel} this
35325 * @param {Roo.tree.TreeNode} node
35326 * @param {Number} index The index of the newly appended node
35328 "appendnode" : true
35331 if(this.singleExpand){
35332 this.on("beforeexpand", this.restrictExpand, this);
35335 this.editor.tree = this;
35336 this.editor = Roo.factory(this.editor, Roo.tree);
35339 if (this.selModel) {
35340 this.selModel = Roo.factory(this.selModel, Roo.tree);
35344 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
35345 rootVisible : true,
35346 animate: Roo.enableFx,
35349 hlDrop : Roo.enableFx,
35353 rendererTip: false,
35355 restrictExpand : function(node){
35356 var p = node.parentNode;
35358 if(p.expandedChild && p.expandedChild.parentNode == p){
35359 p.expandedChild.collapse();
35361 p.expandedChild = node;
35365 // private override
35366 setRootNode : function(node){
35367 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
35368 if(!this.rootVisible){
35369 node.ui = new Roo.tree.RootTreeNodeUI(node);
35375 * Returns the container element for this TreePanel
35377 getEl : function(){
35382 * Returns the default TreeLoader for this TreePanel
35384 getLoader : function(){
35385 return this.loader;
35391 expandAll : function(){
35392 this.root.expand(true);
35396 * Collapse all nodes
35398 collapseAll : function(){
35399 this.root.collapse(true);
35403 * Returns the selection model used by this TreePanel
35405 getSelectionModel : function(){
35406 if(!this.selModel){
35407 this.selModel = new Roo.tree.DefaultSelectionModel();
35409 return this.selModel;
35413 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
35414 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
35415 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
35418 getChecked : function(a, startNode){
35419 startNode = startNode || this.root;
35421 var f = function(){
35422 if(this.attributes.checked){
35423 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
35426 startNode.cascade(f);
35431 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
35432 * @param {String} path
35433 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
35434 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
35435 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
35437 expandPath : function(path, attr, callback){
35438 attr = attr || "id";
35439 var keys = path.split(this.pathSeparator);
35440 var curNode = this.root;
35441 if(curNode.attributes[attr] != keys[1]){ // invalid root
35443 callback(false, null);
35448 var f = function(){
35449 if(++index == keys.length){
35451 callback(true, curNode);
35455 var c = curNode.findChild(attr, keys[index]);
35458 callback(false, curNode);
35463 c.expand(false, false, f);
35465 curNode.expand(false, false, f);
35469 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
35470 * @param {String} path
35471 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
35472 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
35473 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
35475 selectPath : function(path, attr, callback){
35476 attr = attr || "id";
35477 var keys = path.split(this.pathSeparator);
35478 var v = keys.pop();
35479 if(keys.length > 0){
35480 var f = function(success, node){
35481 if(success && node){
35482 var n = node.findChild(attr, v);
35488 }else if(callback){
35489 callback(false, n);
35493 callback(false, n);
35497 this.expandPath(keys.join(this.pathSeparator), attr, f);
35499 this.root.select();
35501 callback(true, this.root);
35506 getTreeEl : function(){
35511 * Trigger rendering of this TreePanel
35513 render : function(){
35514 if (this.innerCt) {
35515 return this; // stop it rendering more than once!!
35518 this.innerCt = this.el.createChild({tag:"ul",
35519 cls:"x-tree-root-ct " +
35520 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
35522 if(this.containerScroll){
35523 Roo.dd.ScrollManager.register(this.el);
35525 if((this.enableDD || this.enableDrop) && !this.dropZone){
35527 * The dropZone used by this tree if drop is enabled
35528 * @type Roo.tree.TreeDropZone
35530 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
35531 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
35534 if((this.enableDD || this.enableDrag) && !this.dragZone){
35536 * The dragZone used by this tree if drag is enabled
35537 * @type Roo.tree.TreeDragZone
35539 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
35540 ddGroup: this.ddGroup || "TreeDD",
35541 scroll: this.ddScroll
35544 this.getSelectionModel().init(this);
35546 Roo.log("ROOT not set in tree");
35549 this.root.render();
35550 if(!this.rootVisible){
35551 this.root.renderChildren();
35557 * Ext JS Library 1.1.1
35558 * Copyright(c) 2006-2007, Ext JS, LLC.
35560 * Originally Released Under LGPL - original licence link has changed is not relivant.
35563 * <script type="text/javascript">
35568 * @class Roo.tree.DefaultSelectionModel
35569 * @extends Roo.util.Observable
35570 * The default single selection for a TreePanel.
35571 * @param {Object} cfg Configuration
35573 Roo.tree.DefaultSelectionModel = function(cfg){
35574 this.selNode = null;
35580 * @event selectionchange
35581 * Fires when the selected node changes
35582 * @param {DefaultSelectionModel} this
35583 * @param {TreeNode} node the new selection
35585 "selectionchange" : true,
35588 * @event beforeselect
35589 * Fires before the selected node changes, return false to cancel the change
35590 * @param {DefaultSelectionModel} this
35591 * @param {TreeNode} node the new selection
35592 * @param {TreeNode} node the old selection
35594 "beforeselect" : true
35597 Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
35600 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
35601 init : function(tree){
35603 tree.getTreeEl().on("keydown", this.onKeyDown, this);
35604 tree.on("click", this.onNodeClick, this);
35607 onNodeClick : function(node, e){
35608 if (e.ctrlKey && this.selNode == node) {
35609 this.unselect(node);
35617 * @param {TreeNode} node The node to select
35618 * @return {TreeNode} The selected node
35620 select : function(node){
35621 var last = this.selNode;
35622 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
35624 last.ui.onSelectedChange(false);
35626 this.selNode = node;
35627 node.ui.onSelectedChange(true);
35628 this.fireEvent("selectionchange", this, node, last);
35635 * @param {TreeNode} node The node to unselect
35637 unselect : function(node){
35638 if(this.selNode == node){
35639 this.clearSelections();
35644 * Clear all selections
35646 clearSelections : function(){
35647 var n = this.selNode;
35649 n.ui.onSelectedChange(false);
35650 this.selNode = null;
35651 this.fireEvent("selectionchange", this, null);
35657 * Get the selected node
35658 * @return {TreeNode} The selected node
35660 getSelectedNode : function(){
35661 return this.selNode;
35665 * Returns true if the node is selected
35666 * @param {TreeNode} node The node to check
35667 * @return {Boolean}
35669 isSelected : function(node){
35670 return this.selNode == node;
35674 * Selects the node above the selected node in the tree, intelligently walking the nodes
35675 * @return TreeNode The new selection
35677 selectPrevious : function(){
35678 var s = this.selNode || this.lastSelNode;
35682 var ps = s.previousSibling;
35684 if(!ps.isExpanded() || ps.childNodes.length < 1){
35685 return this.select(ps);
35687 var lc = ps.lastChild;
35688 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
35691 return this.select(lc);
35693 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
35694 return this.select(s.parentNode);
35700 * Selects the node above the selected node in the tree, intelligently walking the nodes
35701 * @return TreeNode The new selection
35703 selectNext : function(){
35704 var s = this.selNode || this.lastSelNode;
35708 if(s.firstChild && s.isExpanded()){
35709 return this.select(s.firstChild);
35710 }else if(s.nextSibling){
35711 return this.select(s.nextSibling);
35712 }else if(s.parentNode){
35714 s.parentNode.bubble(function(){
35715 if(this.nextSibling){
35716 newS = this.getOwnerTree().selModel.select(this.nextSibling);
35725 onKeyDown : function(e){
35726 var s = this.selNode || this.lastSelNode;
35727 // undesirable, but required
35732 var k = e.getKey();
35740 this.selectPrevious();
35743 e.preventDefault();
35744 if(s.hasChildNodes()){
35745 if(!s.isExpanded()){
35747 }else if(s.firstChild){
35748 this.select(s.firstChild, e);
35753 e.preventDefault();
35754 if(s.hasChildNodes() && s.isExpanded()){
35756 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
35757 this.select(s.parentNode, e);
35765 * @class Roo.tree.MultiSelectionModel
35766 * @extends Roo.util.Observable
35767 * Multi selection for a TreePanel.
35768 * @param {Object} cfg Configuration
35770 Roo.tree.MultiSelectionModel = function(){
35771 this.selNodes = [];
35775 * @event selectionchange
35776 * Fires when the selected nodes change
35777 * @param {MultiSelectionModel} this
35778 * @param {Array} nodes Array of the selected nodes
35780 "selectionchange" : true
35782 Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
35786 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
35787 init : function(tree){
35789 tree.getTreeEl().on("keydown", this.onKeyDown, this);
35790 tree.on("click", this.onNodeClick, this);
35793 onNodeClick : function(node, e){
35794 this.select(node, e, e.ctrlKey);
35799 * @param {TreeNode} node The node to select
35800 * @param {EventObject} e (optional) An event associated with the selection
35801 * @param {Boolean} keepExisting True to retain existing selections
35802 * @return {TreeNode} The selected node
35804 select : function(node, e, keepExisting){
35805 if(keepExisting !== true){
35806 this.clearSelections(true);
35808 if(this.isSelected(node)){
35809 this.lastSelNode = node;
35812 this.selNodes.push(node);
35813 this.selMap[node.id] = node;
35814 this.lastSelNode = node;
35815 node.ui.onSelectedChange(true);
35816 this.fireEvent("selectionchange", this, this.selNodes);
35822 * @param {TreeNode} node The node to unselect
35824 unselect : function(node){
35825 if(this.selMap[node.id]){
35826 node.ui.onSelectedChange(false);
35827 var sn = this.selNodes;
35830 index = sn.indexOf(node);
35832 for(var i = 0, len = sn.length; i < len; i++){
35840 this.selNodes.splice(index, 1);
35842 delete this.selMap[node.id];
35843 this.fireEvent("selectionchange", this, this.selNodes);
35848 * Clear all selections
35850 clearSelections : function(suppressEvent){
35851 var sn = this.selNodes;
35853 for(var i = 0, len = sn.length; i < len; i++){
35854 sn[i].ui.onSelectedChange(false);
35856 this.selNodes = [];
35858 if(suppressEvent !== true){
35859 this.fireEvent("selectionchange", this, this.selNodes);
35865 * Returns true if the node is selected
35866 * @param {TreeNode} node The node to check
35867 * @return {Boolean}
35869 isSelected : function(node){
35870 return this.selMap[node.id] ? true : false;
35874 * Returns an array of the selected nodes
35877 getSelectedNodes : function(){
35878 return this.selNodes;
35881 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
35883 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
35885 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
35888 * Ext JS Library 1.1.1
35889 * Copyright(c) 2006-2007, Ext JS, LLC.
35891 * Originally Released Under LGPL - original licence link has changed is not relivant.
35894 * <script type="text/javascript">
35898 * @class Roo.tree.TreeNode
35899 * @extends Roo.data.Node
35900 * @cfg {String} text The text for this node
35901 * @cfg {Boolean} expanded true to start the node expanded
35902 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
35903 * @cfg {Boolean} allowDrop false if this node cannot be drop on
35904 * @cfg {Boolean} disabled true to start the node disabled
35905 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
35906 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
35907 * @cfg {String} cls A css class to be added to the node
35908 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
35909 * @cfg {String} href URL of the link used for the node (defaults to #)
35910 * @cfg {String} hrefTarget target frame for the link
35911 * @cfg {String} qtip An Ext QuickTip for the node
35912 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
35913 * @cfg {Boolean} singleClickExpand True for single click expand on this node
35914 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
35915 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
35916 * (defaults to undefined with no checkbox rendered)
35918 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
35920 Roo.tree.TreeNode = function(attributes){
35921 attributes = attributes || {};
35922 if(typeof attributes == "string"){
35923 attributes = {text: attributes};
35925 this.childrenRendered = false;
35926 this.rendered = false;
35927 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
35928 this.expanded = attributes.expanded === true;
35929 this.isTarget = attributes.isTarget !== false;
35930 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
35931 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
35934 * Read-only. The text for this node. To change it use setText().
35937 this.text = attributes.text;
35939 * True if this node is disabled.
35942 this.disabled = attributes.disabled === true;
35946 * @event textchange
35947 * Fires when the text for this node is changed
35948 * @param {Node} this This node
35949 * @param {String} text The new text
35950 * @param {String} oldText The old text
35952 "textchange" : true,
35954 * @event beforeexpand
35955 * Fires before this node is expanded, return false to cancel.
35956 * @param {Node} this This node
35957 * @param {Boolean} deep
35958 * @param {Boolean} anim
35960 "beforeexpand" : true,
35962 * @event beforecollapse
35963 * Fires before this node is collapsed, return false to cancel.
35964 * @param {Node} this This node
35965 * @param {Boolean} deep
35966 * @param {Boolean} anim
35968 "beforecollapse" : true,
35971 * Fires when this node is expanded
35972 * @param {Node} this This node
35976 * @event disabledchange
35977 * Fires when the disabled status of this node changes
35978 * @param {Node} this This node
35979 * @param {Boolean} disabled
35981 "disabledchange" : true,
35984 * Fires when this node is collapsed
35985 * @param {Node} this This node
35989 * @event beforeclick
35990 * Fires before click processing. Return false to cancel the default action.
35991 * @param {Node} this This node
35992 * @param {Roo.EventObject} e The event object
35994 "beforeclick":true,
35996 * @event checkchange
35997 * Fires when a node with a checkbox's checked property changes
35998 * @param {Node} this This node
35999 * @param {Boolean} checked
36001 "checkchange":true,
36004 * Fires when this node is clicked
36005 * @param {Node} this This node
36006 * @param {Roo.EventObject} e The event object
36011 * Fires when this node is double clicked
36012 * @param {Node} this This node
36013 * @param {Roo.EventObject} e The event object
36017 * @event contextmenu
36018 * Fires when this node is right clicked
36019 * @param {Node} this This node
36020 * @param {Roo.EventObject} e The event object
36022 "contextmenu":true,
36024 * @event beforechildrenrendered
36025 * Fires right before the child nodes for this node are rendered
36026 * @param {Node} this This node
36028 "beforechildrenrendered":true
36031 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
36034 * Read-only. The UI for this node
36037 this.ui = new uiClass(this);
36039 // finally support items[]
36040 if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
36045 Roo.each(this.attributes.items, function(c) {
36046 this.appendChild(Roo.factory(c,Roo.Tree));
36048 delete this.attributes.items;
36053 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
36054 preventHScroll: true,
36056 * Returns true if this node is expanded
36057 * @return {Boolean}
36059 isExpanded : function(){
36060 return this.expanded;
36064 * Returns the UI object for this node
36065 * @return {TreeNodeUI}
36067 getUI : function(){
36071 // private override
36072 setFirstChild : function(node){
36073 var of = this.firstChild;
36074 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
36075 if(this.childrenRendered && of && node != of){
36076 of.renderIndent(true, true);
36079 this.renderIndent(true, true);
36083 // private override
36084 setLastChild : function(node){
36085 var ol = this.lastChild;
36086 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
36087 if(this.childrenRendered && ol && node != ol){
36088 ol.renderIndent(true, true);
36091 this.renderIndent(true, true);
36095 // these methods are overridden to provide lazy rendering support
36096 // private override
36097 appendChild : function()
36099 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
36100 if(node && this.childrenRendered){
36103 this.ui.updateExpandIcon();
36107 // private override
36108 removeChild : function(node){
36109 this.ownerTree.getSelectionModel().unselect(node);
36110 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
36111 // if it's been rendered remove dom node
36112 if(this.childrenRendered){
36115 if(this.childNodes.length < 1){
36116 this.collapse(false, false);
36118 this.ui.updateExpandIcon();
36120 if(!this.firstChild) {
36121 this.childrenRendered = false;
36126 // private override
36127 insertBefore : function(node, refNode){
36128 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
36129 if(newNode && refNode && this.childrenRendered){
36132 this.ui.updateExpandIcon();
36137 * Sets the text for this node
36138 * @param {String} text
36140 setText : function(text){
36141 var oldText = this.text;
36143 this.attributes.text = text;
36144 if(this.rendered){ // event without subscribing
36145 this.ui.onTextChange(this, text, oldText);
36147 this.fireEvent("textchange", this, text, oldText);
36151 * Triggers selection of this node
36153 select : function(){
36154 this.getOwnerTree().getSelectionModel().select(this);
36158 * Triggers deselection of this node
36160 unselect : function(){
36161 this.getOwnerTree().getSelectionModel().unselect(this);
36165 * Returns true if this node is selected
36166 * @return {Boolean}
36168 isSelected : function(){
36169 return this.getOwnerTree().getSelectionModel().isSelected(this);
36173 * Expand this node.
36174 * @param {Boolean} deep (optional) True to expand all children as well
36175 * @param {Boolean} anim (optional) false to cancel the default animation
36176 * @param {Function} callback (optional) A callback to be called when
36177 * expanding this node completes (does not wait for deep expand to complete).
36178 * Called with 1 parameter, this node.
36180 expand : function(deep, anim, callback){
36181 if(!this.expanded){
36182 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
36185 if(!this.childrenRendered){
36186 this.renderChildren();
36188 this.expanded = true;
36190 if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
36191 this.ui.animExpand(function(){
36192 this.fireEvent("expand", this);
36193 if(typeof callback == "function"){
36197 this.expandChildNodes(true);
36199 }.createDelegate(this));
36203 this.fireEvent("expand", this);
36204 if(typeof callback == "function"){
36209 if(typeof callback == "function"){
36214 this.expandChildNodes(true);
36218 isHiddenRoot : function(){
36219 return this.isRoot && !this.getOwnerTree().rootVisible;
36223 * Collapse this node.
36224 * @param {Boolean} deep (optional) True to collapse all children as well
36225 * @param {Boolean} anim (optional) false to cancel the default animation
36227 collapse : function(deep, anim){
36228 if(this.expanded && !this.isHiddenRoot()){
36229 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
36232 this.expanded = false;
36233 if((this.getOwnerTree().animate && anim !== false) || anim){
36234 this.ui.animCollapse(function(){
36235 this.fireEvent("collapse", this);
36237 this.collapseChildNodes(true);
36239 }.createDelegate(this));
36242 this.ui.collapse();
36243 this.fireEvent("collapse", this);
36247 var cs = this.childNodes;
36248 for(var i = 0, len = cs.length; i < len; i++) {
36249 cs[i].collapse(true, false);
36255 delayedExpand : function(delay){
36256 if(!this.expandProcId){
36257 this.expandProcId = this.expand.defer(delay, this);
36262 cancelExpand : function(){
36263 if(this.expandProcId){
36264 clearTimeout(this.expandProcId);
36266 this.expandProcId = false;
36270 * Toggles expanded/collapsed state of the node
36272 toggle : function(){
36281 * Ensures all parent nodes are expanded
36283 ensureVisible : function(callback){
36284 var tree = this.getOwnerTree();
36285 tree.expandPath(this.parentNode.getPath(), false, function(){
36286 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
36287 Roo.callback(callback);
36288 }.createDelegate(this));
36292 * Expand all child nodes
36293 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
36295 expandChildNodes : function(deep){
36296 var cs = this.childNodes;
36297 for(var i = 0, len = cs.length; i < len; i++) {
36298 cs[i].expand(deep);
36303 * Collapse all child nodes
36304 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
36306 collapseChildNodes : function(deep){
36307 var cs = this.childNodes;
36308 for(var i = 0, len = cs.length; i < len; i++) {
36309 cs[i].collapse(deep);
36314 * Disables this node
36316 disable : function(){
36317 this.disabled = true;
36319 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36320 this.ui.onDisableChange(this, true);
36322 this.fireEvent("disabledchange", this, true);
36326 * Enables this node
36328 enable : function(){
36329 this.disabled = false;
36330 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36331 this.ui.onDisableChange(this, false);
36333 this.fireEvent("disabledchange", this, false);
36337 renderChildren : function(suppressEvent){
36338 if(suppressEvent !== false){
36339 this.fireEvent("beforechildrenrendered", this);
36341 var cs = this.childNodes;
36342 for(var i = 0, len = cs.length; i < len; i++){
36343 cs[i].render(true);
36345 this.childrenRendered = true;
36349 sort : function(fn, scope){
36350 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
36351 if(this.childrenRendered){
36352 var cs = this.childNodes;
36353 for(var i = 0, len = cs.length; i < len; i++){
36354 cs[i].render(true);
36360 render : function(bulkRender){
36361 this.ui.render(bulkRender);
36362 if(!this.rendered){
36363 this.rendered = true;
36365 this.expanded = false;
36366 this.expand(false, false);
36372 renderIndent : function(deep, refresh){
36374 this.ui.childIndent = null;
36376 this.ui.renderIndent();
36377 if(deep === true && this.childrenRendered){
36378 var cs = this.childNodes;
36379 for(var i = 0, len = cs.length; i < len; i++){
36380 cs[i].renderIndent(true, refresh);
36386 * Ext JS Library 1.1.1
36387 * Copyright(c) 2006-2007, Ext JS, LLC.
36389 * Originally Released Under LGPL - original licence link has changed is not relivant.
36392 * <script type="text/javascript">
36396 * @class Roo.tree.AsyncTreeNode
36397 * @extends Roo.tree.TreeNode
36398 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
36400 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
36402 Roo.tree.AsyncTreeNode = function(config){
36403 this.loaded = false;
36404 this.loading = false;
36405 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
36407 * @event beforeload
36408 * Fires before this node is loaded, return false to cancel
36409 * @param {Node} this This node
36411 this.addEvents({'beforeload':true, 'load': true});
36414 * Fires when this node is loaded
36415 * @param {Node} this This node
36418 * The loader used by this node (defaults to using the tree's defined loader)
36423 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
36424 expand : function(deep, anim, callback){
36425 if(this.loading){ // if an async load is already running, waiting til it's done
36427 var f = function(){
36428 if(!this.loading){ // done loading
36429 clearInterval(timer);
36430 this.expand(deep, anim, callback);
36432 }.createDelegate(this);
36433 timer = setInterval(f, 200);
36437 if(this.fireEvent("beforeload", this) === false){
36440 this.loading = true;
36441 this.ui.beforeLoad(this);
36442 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
36444 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
36448 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
36452 * Returns true if this node is currently loading
36453 * @return {Boolean}
36455 isLoading : function(){
36456 return this.loading;
36459 loadComplete : function(deep, anim, callback){
36460 this.loading = false;
36461 this.loaded = true;
36462 this.ui.afterLoad(this);
36463 this.fireEvent("load", this);
36464 this.expand(deep, anim, callback);
36468 * Returns true if this node has been loaded
36469 * @return {Boolean}
36471 isLoaded : function(){
36472 return this.loaded;
36475 hasChildNodes : function(){
36476 if(!this.isLeaf() && !this.loaded){
36479 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
36484 * Trigger a reload for this node
36485 * @param {Function} callback
36487 reload : function(callback){
36488 this.collapse(false, false);
36489 while(this.firstChild){
36490 this.removeChild(this.firstChild);
36492 this.childrenRendered = false;
36493 this.loaded = false;
36494 if(this.isHiddenRoot()){
36495 this.expanded = false;
36497 this.expand(false, false, callback);
36501 * Ext JS Library 1.1.1
36502 * Copyright(c) 2006-2007, Ext JS, LLC.
36504 * Originally Released Under LGPL - original licence link has changed is not relivant.
36507 * <script type="text/javascript">
36511 * @class Roo.tree.TreeNodeUI
36513 * @param {Object} node The node to render
36514 * The TreeNode UI implementation is separate from the
36515 * tree implementation. Unless you are customizing the tree UI,
36516 * you should never have to use this directly.
36518 Roo.tree.TreeNodeUI = function(node){
36520 this.rendered = false;
36521 this.animating = false;
36522 this.emptyIcon = Roo.BLANK_IMAGE_URL;
36525 Roo.tree.TreeNodeUI.prototype = {
36526 removeChild : function(node){
36528 this.ctNode.removeChild(node.ui.getEl());
36532 beforeLoad : function(){
36533 this.addClass("x-tree-node-loading");
36536 afterLoad : function(){
36537 this.removeClass("x-tree-node-loading");
36540 onTextChange : function(node, text, oldText){
36542 this.textNode.innerHTML = text;
36546 onDisableChange : function(node, state){
36547 this.disabled = state;
36549 this.addClass("x-tree-node-disabled");
36551 this.removeClass("x-tree-node-disabled");
36555 onSelectedChange : function(state){
36558 this.addClass("x-tree-selected");
36561 this.removeClass("x-tree-selected");
36565 onMove : function(tree, node, oldParent, newParent, index, refNode){
36566 this.childIndent = null;
36568 var targetNode = newParent.ui.getContainer();
36569 if(!targetNode){//target not rendered
36570 this.holder = document.createElement("div");
36571 this.holder.appendChild(this.wrap);
36574 var insertBefore = refNode ? refNode.ui.getEl() : null;
36576 targetNode.insertBefore(this.wrap, insertBefore);
36578 targetNode.appendChild(this.wrap);
36580 this.node.renderIndent(true);
36584 addClass : function(cls){
36586 Roo.fly(this.elNode).addClass(cls);
36590 removeClass : function(cls){
36592 Roo.fly(this.elNode).removeClass(cls);
36596 remove : function(){
36598 this.holder = document.createElement("div");
36599 this.holder.appendChild(this.wrap);
36603 fireEvent : function(){
36604 return this.node.fireEvent.apply(this.node, arguments);
36607 initEvents : function(){
36608 this.node.on("move", this.onMove, this);
36609 var E = Roo.EventManager;
36610 var a = this.anchor;
36612 var el = Roo.fly(a, '_treeui');
36614 if(Roo.isOpera){ // opera render bug ignores the CSS
36615 el.setStyle("text-decoration", "none");
36618 el.on("click", this.onClick, this);
36619 el.on("dblclick", this.onDblClick, this);
36622 Roo.EventManager.on(this.checkbox,
36623 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
36626 el.on("contextmenu", this.onContextMenu, this);
36628 var icon = Roo.fly(this.iconNode);
36629 icon.on("click", this.onClick, this);
36630 icon.on("dblclick", this.onDblClick, this);
36631 icon.on("contextmenu", this.onContextMenu, this);
36632 E.on(this.ecNode, "click", this.ecClick, this, true);
36634 if(this.node.disabled){
36635 this.addClass("x-tree-node-disabled");
36637 if(this.node.hidden){
36638 this.addClass("x-tree-node-disabled");
36640 var ot = this.node.getOwnerTree();
36641 var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
36642 if(dd && (!this.node.isRoot || ot.rootVisible)){
36643 Roo.dd.Registry.register(this.elNode, {
36645 handles: this.getDDHandles(),
36651 getDDHandles : function(){
36652 return [this.iconNode, this.textNode];
36657 this.wrap.style.display = "none";
36663 this.wrap.style.display = "";
36667 onContextMenu : function(e){
36668 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
36669 e.preventDefault();
36671 this.fireEvent("contextmenu", this.node, e);
36675 onClick : function(e){
36680 if(this.fireEvent("beforeclick", this.node, e) !== false){
36681 if(!this.disabled && this.node.attributes.href){
36682 this.fireEvent("click", this.node, e);
36685 e.preventDefault();
36690 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
36691 this.node.toggle();
36694 this.fireEvent("click", this.node, e);
36700 onDblClick : function(e){
36701 e.preventDefault();
36706 this.toggleCheck();
36708 if(!this.animating && this.node.hasChildNodes()){
36709 this.node.toggle();
36711 this.fireEvent("dblclick", this.node, e);
36714 onCheckChange : function(){
36715 var checked = this.checkbox.checked;
36716 this.node.attributes.checked = checked;
36717 this.fireEvent('checkchange', this.node, checked);
36720 ecClick : function(e){
36721 if(!this.animating && this.node.hasChildNodes()){
36722 this.node.toggle();
36726 startDrop : function(){
36727 this.dropping = true;
36730 // delayed drop so the click event doesn't get fired on a drop
36731 endDrop : function(){
36732 setTimeout(function(){
36733 this.dropping = false;
36734 }.createDelegate(this), 50);
36737 expand : function(){
36738 this.updateExpandIcon();
36739 this.ctNode.style.display = "";
36742 focus : function(){
36743 if(!this.node.preventHScroll){
36744 try{this.anchor.focus();
36746 }else if(!Roo.isIE){
36748 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
36749 var l = noscroll.scrollLeft;
36750 this.anchor.focus();
36751 noscroll.scrollLeft = l;
36756 toggleCheck : function(value){
36757 var cb = this.checkbox;
36759 cb.checked = (value === undefined ? !cb.checked : value);
36765 this.anchor.blur();
36769 animExpand : function(callback){
36770 var ct = Roo.get(this.ctNode);
36772 if(!this.node.hasChildNodes()){
36773 this.updateExpandIcon();
36774 this.ctNode.style.display = "";
36775 Roo.callback(callback);
36778 this.animating = true;
36779 this.updateExpandIcon();
36782 callback : function(){
36783 this.animating = false;
36784 Roo.callback(callback);
36787 duration: this.node.ownerTree.duration || .25
36791 highlight : function(){
36792 var tree = this.node.getOwnerTree();
36793 Roo.fly(this.wrap).highlight(
36794 tree.hlColor || "C3DAF9",
36795 {endColor: tree.hlBaseColor}
36799 collapse : function(){
36800 this.updateExpandIcon();
36801 this.ctNode.style.display = "none";
36804 animCollapse : function(callback){
36805 var ct = Roo.get(this.ctNode);
36806 ct.enableDisplayMode('block');
36809 this.animating = true;
36810 this.updateExpandIcon();
36813 callback : function(){
36814 this.animating = false;
36815 Roo.callback(callback);
36818 duration: this.node.ownerTree.duration || .25
36822 getContainer : function(){
36823 return this.ctNode;
36826 getEl : function(){
36830 appendDDGhost : function(ghostNode){
36831 ghostNode.appendChild(this.elNode.cloneNode(true));
36834 getDDRepairXY : function(){
36835 return Roo.lib.Dom.getXY(this.iconNode);
36838 onRender : function(){
36842 render : function(bulkRender){
36843 var n = this.node, a = n.attributes;
36844 var targetNode = n.parentNode ?
36845 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
36847 if(!this.rendered){
36848 this.rendered = true;
36850 this.renderElements(n, a, targetNode, bulkRender);
36853 if(this.textNode.setAttributeNS){
36854 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
36856 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
36859 this.textNode.setAttribute("ext:qtip", a.qtip);
36861 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
36864 }else if(a.qtipCfg){
36865 a.qtipCfg.target = Roo.id(this.textNode);
36866 Roo.QuickTips.register(a.qtipCfg);
36869 if(!this.node.expanded){
36870 this.updateExpandIcon();
36873 if(bulkRender === true) {
36874 targetNode.appendChild(this.wrap);
36879 renderElements : function(n, a, targetNode, bulkRender)
36881 // add some indent caching, this helps performance when rendering a large tree
36882 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
36883 var t = n.getOwnerTree();
36884 var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
36885 if (typeof(n.attributes.html) != 'undefined') {
36886 txt = n.attributes.html;
36888 var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
36889 var cb = typeof a.checked == 'boolean';
36890 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
36891 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
36892 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
36893 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
36894 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
36895 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
36896 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
36897 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
36898 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
36899 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
36902 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
36903 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
36904 n.nextSibling.ui.getEl(), buf.join(""));
36906 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
36909 this.elNode = this.wrap.childNodes[0];
36910 this.ctNode = this.wrap.childNodes[1];
36911 var cs = this.elNode.childNodes;
36912 this.indentNode = cs[0];
36913 this.ecNode = cs[1];
36914 this.iconNode = cs[2];
36917 this.checkbox = cs[3];
36920 this.anchor = cs[index];
36921 this.textNode = cs[index].firstChild;
36924 getAnchor : function(){
36925 return this.anchor;
36928 getTextEl : function(){
36929 return this.textNode;
36932 getIconEl : function(){
36933 return this.iconNode;
36936 isChecked : function(){
36937 return this.checkbox ? this.checkbox.checked : false;
36940 updateExpandIcon : function(){
36942 var n = this.node, c1, c2;
36943 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
36944 var hasChild = n.hasChildNodes();
36948 c1 = "x-tree-node-collapsed";
36949 c2 = "x-tree-node-expanded";
36952 c1 = "x-tree-node-expanded";
36953 c2 = "x-tree-node-collapsed";
36956 this.removeClass("x-tree-node-leaf");
36957 this.wasLeaf = false;
36959 if(this.c1 != c1 || this.c2 != c2){
36960 Roo.fly(this.elNode).replaceClass(c1, c2);
36961 this.c1 = c1; this.c2 = c2;
36964 // this changes non-leafs into leafs if they have no children.
36965 // it's not very rational behaviour..
36967 if(!this.wasLeaf && this.node.leaf){
36968 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
36971 this.wasLeaf = true;
36974 var ecc = "x-tree-ec-icon "+cls;
36975 if(this.ecc != ecc){
36976 this.ecNode.className = ecc;
36982 getChildIndent : function(){
36983 if(!this.childIndent){
36987 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
36989 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
36991 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
36996 this.childIndent = buf.join("");
36998 return this.childIndent;
37001 renderIndent : function(){
37004 var p = this.node.parentNode;
37006 indent = p.ui.getChildIndent();
37008 if(this.indentMarkup != indent){ // don't rerender if not required
37009 this.indentNode.innerHTML = indent;
37010 this.indentMarkup = indent;
37012 this.updateExpandIcon();
37017 Roo.tree.RootTreeNodeUI = function(){
37018 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
37020 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
37021 render : function(){
37022 if(!this.rendered){
37023 var targetNode = this.node.ownerTree.innerCt.dom;
37024 this.node.expanded = true;
37025 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
37026 this.wrap = this.ctNode = targetNode.firstChild;
37029 collapse : function(){
37031 expand : function(){
37035 * Ext JS Library 1.1.1
37036 * Copyright(c) 2006-2007, Ext JS, LLC.
37038 * Originally Released Under LGPL - original licence link has changed is not relivant.
37041 * <script type="text/javascript">
37044 * @class Roo.tree.TreeLoader
37045 * @extends Roo.util.Observable
37046 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
37047 * nodes from a specified URL. The response must be a javascript Array definition
37048 * who's elements are node definition objects. eg:
37053 { 'id': 1, 'text': 'A folder Node', 'leaf': false },
37054 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
37061 * The old style respose with just an array is still supported, but not recommended.
37064 * A server request is sent, and child nodes are loaded only when a node is expanded.
37065 * The loading node's id is passed to the server under the parameter name "node" to
37066 * enable the server to produce the correct child nodes.
37068 * To pass extra parameters, an event handler may be attached to the "beforeload"
37069 * event, and the parameters specified in the TreeLoader's baseParams property:
37071 myTreeLoader.on("beforeload", function(treeLoader, node) {
37072 this.baseParams.category = node.attributes.category;
37077 * This would pass an HTTP parameter called "category" to the server containing
37078 * the value of the Node's "category" attribute.
37080 * Creates a new Treeloader.
37081 * @param {Object} config A config object containing config properties.
37083 Roo.tree.TreeLoader = function(config){
37084 this.baseParams = {};
37085 this.requestMethod = "POST";
37086 Roo.apply(this, config);
37091 * @event beforeload
37092 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
37093 * @param {Object} This TreeLoader object.
37094 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37095 * @param {Object} callback The callback function specified in the {@link #load} call.
37100 * Fires when the node has been successfuly loaded.
37101 * @param {Object} This TreeLoader object.
37102 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37103 * @param {Object} response The response object containing the data from the server.
37107 * @event loadexception
37108 * Fires if the network request failed.
37109 * @param {Object} This TreeLoader object.
37110 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37111 * @param {Object} response The response object containing the data from the server.
37113 loadexception : true,
37116 * Fires before a node is created, enabling you to return custom Node types
37117 * @param {Object} This TreeLoader object.
37118 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
37123 Roo.tree.TreeLoader.superclass.constructor.call(this);
37126 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
37128 * @cfg {String} dataUrl The URL from which to request a Json string which
37129 * specifies an array of node definition object representing the child nodes
37133 * @cfg {String} requestMethod either GET or POST
37134 * defaults to POST (due to BC)
37138 * @cfg {Object} baseParams (optional) An object containing properties which
37139 * specify HTTP parameters to be passed to each request for child nodes.
37142 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
37143 * created by this loader. If the attributes sent by the server have an attribute in this object,
37144 * they take priority.
37147 * @cfg {Object} uiProviders (optional) An object containing properties which
37149 * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
37150 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
37151 * <i>uiProvider</i> attribute of a returned child node is a string rather
37152 * than a reference to a TreeNodeUI implementation, this that string value
37153 * is used as a property name in the uiProviders object. You can define the provider named
37154 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
37159 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
37160 * child nodes before loading.
37162 clearOnLoad : true,
37165 * @cfg {String} root (optional) Default to false. Use this to read data from an object
37166 * property on loading, rather than expecting an array. (eg. more compatible to a standard
37167 * Grid query { data : [ .....] }
37172 * @cfg {String} queryParam (optional)
37173 * Name of the query as it will be passed on the querystring (defaults to 'node')
37174 * eg. the request will be ?node=[id]
37181 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
37182 * This is called automatically when a node is expanded, but may be used to reload
37183 * a node (or append new children if the {@link #clearOnLoad} option is false.)
37184 * @param {Roo.tree.TreeNode} node
37185 * @param {Function} callback
37187 load : function(node, callback){
37188 if(this.clearOnLoad){
37189 while(node.firstChild){
37190 node.removeChild(node.firstChild);
37193 if(node.attributes.children){ // preloaded json children
37194 var cs = node.attributes.children;
37195 for(var i = 0, len = cs.length; i < len; i++){
37196 node.appendChild(this.createNode(cs[i]));
37198 if(typeof callback == "function"){
37201 }else if(this.dataUrl){
37202 this.requestData(node, callback);
37206 getParams: function(node){
37207 var buf = [], bp = this.baseParams;
37208 for(var key in bp){
37209 if(typeof bp[key] != "function"){
37210 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
37213 var n = this.queryParam === false ? 'node' : this.queryParam;
37214 buf.push(n + "=", encodeURIComponent(node.id));
37215 return buf.join("");
37218 requestData : function(node, callback){
37219 if(this.fireEvent("beforeload", this, node, callback) !== false){
37220 this.transId = Roo.Ajax.request({
37221 method:this.requestMethod,
37222 url: this.dataUrl||this.url,
37223 success: this.handleResponse,
37224 failure: this.handleFailure,
37226 argument: {callback: callback, node: node},
37227 params: this.getParams(node)
37230 // if the load is cancelled, make sure we notify
37231 // the node that we are done
37232 if(typeof callback == "function"){
37238 isLoading : function(){
37239 return this.transId ? true : false;
37242 abort : function(){
37243 if(this.isLoading()){
37244 Roo.Ajax.abort(this.transId);
37249 createNode : function(attr)
37251 // apply baseAttrs, nice idea Corey!
37252 if(this.baseAttrs){
37253 Roo.applyIf(attr, this.baseAttrs);
37255 if(this.applyLoader !== false){
37256 attr.loader = this;
37258 // uiProvider = depreciated..
37260 if(typeof(attr.uiProvider) == 'string'){
37261 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
37262 /** eval:var:attr */ eval(attr.uiProvider);
37264 if(typeof(this.uiProviders['default']) != 'undefined') {
37265 attr.uiProvider = this.uiProviders['default'];
37268 this.fireEvent('create', this, attr);
37270 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
37272 new Roo.tree.TreeNode(attr) :
37273 new Roo.tree.AsyncTreeNode(attr));
37276 processResponse : function(response, node, callback)
37278 var json = response.responseText;
37281 var o = Roo.decode(json);
37283 if (this.root === false && typeof(o.success) != undefined) {
37284 this.root = 'data'; // the default behaviour for list like data..
37287 if (this.root !== false && !o.success) {
37288 // it's a failure condition.
37289 var a = response.argument;
37290 this.fireEvent("loadexception", this, a.node, response);
37291 Roo.log("Load failed - should have a handler really");
37297 if (this.root !== false) {
37301 for(var i = 0, len = o.length; i < len; i++){
37302 var n = this.createNode(o[i]);
37304 node.appendChild(n);
37307 if(typeof callback == "function"){
37308 callback(this, node);
37311 this.handleFailure(response);
37315 handleResponse : function(response){
37316 this.transId = false;
37317 var a = response.argument;
37318 this.processResponse(response, a.node, a.callback);
37319 this.fireEvent("load", this, a.node, response);
37322 handleFailure : function(response)
37324 // should handle failure better..
37325 this.transId = false;
37326 var a = response.argument;
37327 this.fireEvent("loadexception", this, a.node, response);
37328 if(typeof a.callback == "function"){
37329 a.callback(this, a.node);
37334 * Ext JS Library 1.1.1
37335 * Copyright(c) 2006-2007, Ext JS, LLC.
37337 * Originally Released Under LGPL - original licence link has changed is not relivant.
37340 * <script type="text/javascript">
37344 * @class Roo.tree.TreeFilter
37345 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
37346 * @param {TreePanel} tree
37347 * @param {Object} config (optional)
37349 Roo.tree.TreeFilter = function(tree, config){
37351 this.filtered = {};
37352 Roo.apply(this, config);
37355 Roo.tree.TreeFilter.prototype = {
37362 * Filter the data by a specific attribute.
37363 * @param {String/RegExp} value Either string that the attribute value
37364 * should start with or a RegExp to test against the attribute
37365 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
37366 * @param {TreeNode} startNode (optional) The node to start the filter at.
37368 filter : function(value, attr, startNode){
37369 attr = attr || "text";
37371 if(typeof value == "string"){
37372 var vlen = value.length;
37373 // auto clear empty filter
37374 if(vlen == 0 && this.clearBlank){
37378 value = value.toLowerCase();
37380 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
37382 }else if(value.exec){ // regex?
37384 return value.test(n.attributes[attr]);
37387 throw 'Illegal filter type, must be string or regex';
37389 this.filterBy(f, null, startNode);
37393 * Filter by a function. The passed function will be called with each
37394 * node in the tree (or from the startNode). If the function returns true, the node is kept
37395 * otherwise it is filtered. If a node is filtered, its children are also filtered.
37396 * @param {Function} fn The filter function
37397 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
37399 filterBy : function(fn, scope, startNode){
37400 startNode = startNode || this.tree.root;
37401 if(this.autoClear){
37404 var af = this.filtered, rv = this.reverse;
37405 var f = function(n){
37406 if(n == startNode){
37412 var m = fn.call(scope || n, n);
37420 startNode.cascade(f);
37423 if(typeof id != "function"){
37425 if(n && n.parentNode){
37426 n.parentNode.removeChild(n);
37434 * Clears the current filter. Note: with the "remove" option
37435 * set a filter cannot be cleared.
37437 clear : function(){
37439 var af = this.filtered;
37441 if(typeof id != "function"){
37448 this.filtered = {};
37453 * Ext JS Library 1.1.1
37454 * Copyright(c) 2006-2007, Ext JS, LLC.
37456 * Originally Released Under LGPL - original licence link has changed is not relivant.
37459 * <script type="text/javascript">
37464 * @class Roo.tree.TreeSorter
37465 * Provides sorting of nodes in a TreePanel
37467 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
37468 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
37469 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
37470 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
37471 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
37472 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
37474 * @param {TreePanel} tree
37475 * @param {Object} config
37477 Roo.tree.TreeSorter = function(tree, config){
37478 Roo.apply(this, config);
37479 tree.on("beforechildrenrendered", this.doSort, this);
37480 tree.on("append", this.updateSort, this);
37481 tree.on("insert", this.updateSort, this);
37483 var dsc = this.dir && this.dir.toLowerCase() == "desc";
37484 var p = this.property || "text";
37485 var sortType = this.sortType;
37486 var fs = this.folderSort;
37487 var cs = this.caseSensitive === true;
37488 var leafAttr = this.leafAttr || 'leaf';
37490 this.sortFn = function(n1, n2){
37492 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
37495 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
37499 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
37500 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
37502 return dsc ? +1 : -1;
37504 return dsc ? -1 : +1;
37511 Roo.tree.TreeSorter.prototype = {
37512 doSort : function(node){
37513 node.sort(this.sortFn);
37516 compareNodes : function(n1, n2){
37517 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
37520 updateSort : function(tree, node){
37521 if(node.childrenRendered){
37522 this.doSort.defer(1, this, [node]);
37527 * Ext JS Library 1.1.1
37528 * Copyright(c) 2006-2007, Ext JS, LLC.
37530 * Originally Released Under LGPL - original licence link has changed is not relivant.
37533 * <script type="text/javascript">
37536 if(Roo.dd.DropZone){
37538 Roo.tree.TreeDropZone = function(tree, config){
37539 this.allowParentInsert = false;
37540 this.allowContainerDrop = false;
37541 this.appendOnly = false;
37542 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
37544 this.lastInsertClass = "x-tree-no-status";
37545 this.dragOverData = {};
37548 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
37549 ddGroup : "TreeDD",
37552 expandDelay : 1000,
37554 expandNode : function(node){
37555 if(node.hasChildNodes() && !node.isExpanded()){
37556 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
37560 queueExpand : function(node){
37561 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
37564 cancelExpand : function(){
37565 if(this.expandProcId){
37566 clearTimeout(this.expandProcId);
37567 this.expandProcId = false;
37571 isValidDropPoint : function(n, pt, dd, e, data){
37572 if(!n || !data){ return false; }
37573 var targetNode = n.node;
37574 var dropNode = data.node;
37575 // default drop rules
37576 if(!(targetNode && targetNode.isTarget && pt)){
37579 if(pt == "append" && targetNode.allowChildren === false){
37582 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
37585 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
37588 // reuse the object
37589 var overEvent = this.dragOverData;
37590 overEvent.tree = this.tree;
37591 overEvent.target = targetNode;
37592 overEvent.data = data;
37593 overEvent.point = pt;
37594 overEvent.source = dd;
37595 overEvent.rawEvent = e;
37596 overEvent.dropNode = dropNode;
37597 overEvent.cancel = false;
37598 var result = this.tree.fireEvent("nodedragover", overEvent);
37599 return overEvent.cancel === false && result !== false;
37602 getDropPoint : function(e, n, dd)
37606 return tn.allowChildren !== false ? "append" : false; // always append for root
37608 var dragEl = n.ddel;
37609 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
37610 var y = Roo.lib.Event.getPageY(e);
37611 //var noAppend = tn.allowChildren === false || tn.isLeaf();
37613 // we may drop nodes anywhere, as long as allowChildren has not been set to false..
37614 var noAppend = tn.allowChildren === false;
37615 if(this.appendOnly || tn.parentNode.allowChildren === false){
37616 return noAppend ? false : "append";
37618 var noBelow = false;
37619 if(!this.allowParentInsert){
37620 noBelow = tn.hasChildNodes() && tn.isExpanded();
37622 var q = (b - t) / (noAppend ? 2 : 3);
37623 if(y >= t && y < (t + q)){
37625 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
37632 onNodeEnter : function(n, dd, e, data)
37634 this.cancelExpand();
37637 onNodeOver : function(n, dd, e, data)
37640 var pt = this.getDropPoint(e, n, dd);
37643 // auto node expand check
37644 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
37645 this.queueExpand(node);
37646 }else if(pt != "append"){
37647 this.cancelExpand();
37650 // set the insert point style on the target node
37651 var returnCls = this.dropNotAllowed;
37652 if(this.isValidDropPoint(n, pt, dd, e, data)){
37657 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
37658 cls = "x-tree-drag-insert-above";
37659 }else if(pt == "below"){
37660 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
37661 cls = "x-tree-drag-insert-below";
37663 returnCls = "x-tree-drop-ok-append";
37664 cls = "x-tree-drag-append";
37666 if(this.lastInsertClass != cls){
37667 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
37668 this.lastInsertClass = cls;
37675 onNodeOut : function(n, dd, e, data){
37677 this.cancelExpand();
37678 this.removeDropIndicators(n);
37681 onNodeDrop : function(n, dd, e, data){
37682 var point = this.getDropPoint(e, n, dd);
37683 var targetNode = n.node;
37684 targetNode.ui.startDrop();
37685 if(!this.isValidDropPoint(n, point, dd, e, data)){
37686 targetNode.ui.endDrop();
37689 // first try to find the drop node
37690 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
37693 target: targetNode,
37698 dropNode: dropNode,
37701 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
37702 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
37703 targetNode.ui.endDrop();
37706 // allow target changing
37707 targetNode = dropEvent.target;
37708 if(point == "append" && !targetNode.isExpanded()){
37709 targetNode.expand(false, null, function(){
37710 this.completeDrop(dropEvent);
37711 }.createDelegate(this));
37713 this.completeDrop(dropEvent);
37718 completeDrop : function(de){
37719 var ns = de.dropNode, p = de.point, t = de.target;
37720 if(!(ns instanceof Array)){
37724 for(var i = 0, len = ns.length; i < len; i++){
37727 t.parentNode.insertBefore(n, t);
37728 }else if(p == "below"){
37729 t.parentNode.insertBefore(n, t.nextSibling);
37735 if(this.tree.hlDrop){
37739 this.tree.fireEvent("nodedrop", de);
37742 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
37743 if(this.tree.hlDrop){
37744 dropNode.ui.focus();
37745 dropNode.ui.highlight();
37747 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
37750 getTree : function(){
37754 removeDropIndicators : function(n){
37757 Roo.fly(el).removeClass([
37758 "x-tree-drag-insert-above",
37759 "x-tree-drag-insert-below",
37760 "x-tree-drag-append"]);
37761 this.lastInsertClass = "_noclass";
37765 beforeDragDrop : function(target, e, id){
37766 this.cancelExpand();
37770 afterRepair : function(data){
37771 if(data && Roo.enableFx){
37772 data.node.ui.highlight();
37782 * Ext JS Library 1.1.1
37783 * Copyright(c) 2006-2007, Ext JS, LLC.
37785 * Originally Released Under LGPL - original licence link has changed is not relivant.
37788 * <script type="text/javascript">
37792 if(Roo.dd.DragZone){
37793 Roo.tree.TreeDragZone = function(tree, config){
37794 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
37798 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
37799 ddGroup : "TreeDD",
37801 onBeforeDrag : function(data, e){
37803 return n && n.draggable && !n.disabled;
37807 onInitDrag : function(e){
37808 var data = this.dragData;
37809 this.tree.getSelectionModel().select(data.node);
37810 this.proxy.update("");
37811 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
37812 this.tree.fireEvent("startdrag", this.tree, data.node, e);
37815 getRepairXY : function(e, data){
37816 return data.node.ui.getDDRepairXY();
37819 onEndDrag : function(data, e){
37820 this.tree.fireEvent("enddrag", this.tree, data.node, e);
37825 onValidDrop : function(dd, e, id){
37826 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
37830 beforeInvalidDrop : function(e, id){
37831 // this scrolls the original position back into view
37832 var sm = this.tree.getSelectionModel();
37833 sm.clearSelections();
37834 sm.select(this.dragData.node);
37839 * Ext JS Library 1.1.1
37840 * Copyright(c) 2006-2007, Ext JS, LLC.
37842 * Originally Released Under LGPL - original licence link has changed is not relivant.
37845 * <script type="text/javascript">
37848 * @class Roo.tree.TreeEditor
37849 * @extends Roo.Editor
37850 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
37851 * as the editor field.
37853 * @param {Object} config (used to be the tree panel.)
37854 * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
37856 * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
37857 * @cfg {Roo.form.TextField} field [required] The field configuration
37861 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
37864 if (oldconfig) { // old style..
37865 field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
37868 tree = config.tree;
37869 config.field = config.field || {};
37870 config.field.xtype = 'TextField';
37871 field = Roo.factory(config.field, Roo.form);
37873 config = config || {};
37878 * @event beforenodeedit
37879 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
37880 * false from the handler of this event.
37881 * @param {Editor} this
37882 * @param {Roo.tree.Node} node
37884 "beforenodeedit" : true
37888 Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
37892 tree.on('beforeclick', this.beforeNodeClick, this);
37893 tree.getTreeEl().on('mousedown', this.hide, this);
37894 this.on('complete', this.updateNode, this);
37895 this.on('beforestartedit', this.fitToTree, this);
37896 this.on('startedit', this.bindScroll, this, {delay:10});
37897 this.on('specialkey', this.onSpecialKey, this);
37900 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
37902 * @cfg {String} alignment
37903 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
37909 * @cfg {Boolean} hideEl
37910 * True to hide the bound element while the editor is displayed (defaults to false)
37914 * @cfg {String} cls
37915 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
37917 cls: "x-small-editor x-tree-editor",
37919 * @cfg {Boolean} shim
37920 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
37926 * @cfg {Number} maxWidth
37927 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
37928 * the containing tree element's size, it will be automatically limited for you to the container width, taking
37929 * scroll and client offsets into account prior to each edit.
37936 fitToTree : function(ed, el){
37937 var td = this.tree.getTreeEl().dom, nd = el.dom;
37938 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
37939 td.scrollLeft = nd.offsetLeft;
37943 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
37944 this.setSize(w, '');
37946 return this.fireEvent('beforenodeedit', this, this.editNode);
37951 triggerEdit : function(node){
37952 this.completeEdit();
37953 this.editNode = node;
37954 this.startEdit(node.ui.textNode, node.text);
37958 bindScroll : function(){
37959 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
37963 beforeNodeClick : function(node, e){
37964 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
37965 this.lastClick = new Date();
37966 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
37968 this.triggerEdit(node);
37975 updateNode : function(ed, value){
37976 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
37977 this.editNode.setText(value);
37981 onHide : function(){
37982 Roo.tree.TreeEditor.superclass.onHide.call(this);
37984 this.editNode.ui.focus();
37989 onSpecialKey : function(field, e){
37990 var k = e.getKey();
37994 }else if(k == e.ENTER && !e.hasModifier()){
37996 this.completeEdit();
37999 });//<Script type="text/javascript">
38002 * Ext JS Library 1.1.1
38003 * Copyright(c) 2006-2007, Ext JS, LLC.
38005 * Originally Released Under LGPL - original licence link has changed is not relivant.
38008 * <script type="text/javascript">
38012 * Not documented??? - probably should be...
38015 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
38016 //focus: Roo.emptyFn, // prevent odd scrolling behavior
38018 renderElements : function(n, a, targetNode, bulkRender){
38019 //consel.log("renderElements?");
38020 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
38022 var t = n.getOwnerTree();
38023 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
38025 var cols = t.columns;
38026 var bw = t.borderWidth;
38028 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
38029 var cb = typeof a.checked == "boolean";
38030 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38031 var colcls = 'x-t-' + tid + '-c0';
38033 '<li class="x-tree-node">',
38036 '<div class="x-tree-node-el ', a.cls,'">',
38038 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
38041 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
38042 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
38043 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
38044 (a.icon ? ' x-tree-node-inline-icon' : ''),
38045 (a.iconCls ? ' '+a.iconCls : ''),
38046 '" unselectable="on" />',
38047 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
38048 (a.checked ? 'checked="checked" />' : ' />')) : ''),
38050 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38051 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
38052 '<span unselectable="on" qtip="' + tx + '">',
38056 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38057 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
38059 for(var i = 1, len = cols.length; i < len; i++){
38061 colcls = 'x-t-' + tid + '-c' +i;
38062 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38063 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
38064 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
38070 '<div class="x-clear"></div></div>',
38071 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
38074 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
38075 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
38076 n.nextSibling.ui.getEl(), buf.join(""));
38078 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
38080 var el = this.wrap.firstChild;
38082 this.elNode = el.firstChild;
38083 this.ranchor = el.childNodes[1];
38084 this.ctNode = this.wrap.childNodes[1];
38085 var cs = el.firstChild.childNodes;
38086 this.indentNode = cs[0];
38087 this.ecNode = cs[1];
38088 this.iconNode = cs[2];
38091 this.checkbox = cs[3];
38094 this.anchor = cs[index];
38096 this.textNode = cs[index].firstChild;
38098 //el.on("click", this.onClick, this);
38099 //el.on("dblclick", this.onDblClick, this);
38102 // console.log(this);
38104 initEvents : function(){
38105 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
38108 var a = this.ranchor;
38110 var el = Roo.get(a);
38112 if(Roo.isOpera){ // opera render bug ignores the CSS
38113 el.setStyle("text-decoration", "none");
38116 el.on("click", this.onClick, this);
38117 el.on("dblclick", this.onDblClick, this);
38118 el.on("contextmenu", this.onContextMenu, this);
38122 /*onSelectedChange : function(state){
38125 this.addClass("x-tree-selected");
38128 this.removeClass("x-tree-selected");
38131 addClass : function(cls){
38133 Roo.fly(this.elRow).addClass(cls);
38139 removeClass : function(cls){
38141 Roo.fly(this.elRow).removeClass(cls);
38147 });//<Script type="text/javascript">
38151 * Ext JS Library 1.1.1
38152 * Copyright(c) 2006-2007, Ext JS, LLC.
38154 * Originally Released Under LGPL - original licence link has changed is not relivant.
38157 * <script type="text/javascript">
38162 * @class Roo.tree.ColumnTree
38163 * @extends Roo.tree.TreePanel
38164 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
38165 * @cfg {int} borderWidth compined right/left border allowance
38167 * @param {String/HTMLElement/Element} el The container element
38168 * @param {Object} config
38170 Roo.tree.ColumnTree = function(el, config)
38172 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
38176 * Fire this event on a container when it resizes
38177 * @param {int} w Width
38178 * @param {int} h Height
38182 this.on('resize', this.onResize, this);
38185 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
38189 borderWidth: Roo.isBorderBox ? 0 : 2,
38192 render : function(){
38193 // add the header.....
38195 Roo.tree.ColumnTree.superclass.render.apply(this);
38197 this.el.addClass('x-column-tree');
38199 this.headers = this.el.createChild(
38200 {cls:'x-tree-headers'},this.innerCt.dom);
38202 var cols = this.columns, c;
38203 var totalWidth = 0;
38205 var len = cols.length;
38206 for(var i = 0; i < len; i++){
38208 totalWidth += c.width;
38209 this.headEls.push(this.headers.createChild({
38210 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
38212 cls:'x-tree-hd-text',
38215 style:'width:'+(c.width-this.borderWidth)+'px;'
38218 this.headers.createChild({cls:'x-clear'});
38219 // prevent floats from wrapping when clipped
38220 this.headers.setWidth(totalWidth);
38221 //this.innerCt.setWidth(totalWidth);
38222 this.innerCt.setStyle({ overflow: 'auto' });
38223 this.onResize(this.width, this.height);
38227 onResize : function(w,h)
38232 this.innerCt.setWidth(this.width);
38233 this.innerCt.setHeight(this.height-20);
38236 var cols = this.columns, c;
38237 var totalWidth = 0;
38239 var len = cols.length;
38240 for(var i = 0; i < len; i++){
38242 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
38243 // it's the expander..
38244 expEl = this.headEls[i];
38247 totalWidth += c.width;
38251 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
38253 this.headers.setWidth(w-20);
38262 * Ext JS Library 1.1.1
38263 * Copyright(c) 2006-2007, Ext JS, LLC.
38265 * Originally Released Under LGPL - original licence link has changed is not relivant.
38268 * <script type="text/javascript">
38272 * @class Roo.menu.Menu
38273 * @extends Roo.util.Observable
38274 * @children Roo.menu.BaseItem
38275 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
38276 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
38278 * Creates a new Menu
38279 * @param {Object} config Configuration options
38281 Roo.menu.Menu = function(config){
38283 Roo.menu.Menu.superclass.constructor.call(this, config);
38285 this.id = this.id || Roo.id();
38288 * @event beforeshow
38289 * Fires before this menu is displayed
38290 * @param {Roo.menu.Menu} this
38294 * @event beforehide
38295 * Fires before this menu is hidden
38296 * @param {Roo.menu.Menu} this
38301 * Fires after this menu is displayed
38302 * @param {Roo.menu.Menu} this
38307 * Fires after this menu is hidden
38308 * @param {Roo.menu.Menu} this
38313 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
38314 * @param {Roo.menu.Menu} this
38315 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38316 * @param {Roo.EventObject} e
38321 * Fires when the mouse is hovering over this menu
38322 * @param {Roo.menu.Menu} this
38323 * @param {Roo.EventObject} e
38324 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38329 * Fires when the mouse exits this menu
38330 * @param {Roo.menu.Menu} this
38331 * @param {Roo.EventObject} e
38332 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38337 * Fires when a menu item contained in this menu is clicked
38338 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
38339 * @param {Roo.EventObject} e
38343 if (this.registerMenu) {
38344 Roo.menu.MenuMgr.register(this);
38347 var mis = this.items;
38348 this.items = new Roo.util.MixedCollection();
38350 this.add.apply(this, mis);
38354 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
38356 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
38360 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
38361 * for bottom-right shadow (defaults to "sides")
38365 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
38366 * this menu (defaults to "tl-tr?")
38368 subMenuAlign : "tl-tr?",
38370 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
38371 * relative to its element of origin (defaults to "tl-bl?")
38373 defaultAlign : "tl-bl?",
38375 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
38377 allowOtherMenus : false,
38379 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
38381 registerMenu : true,
38386 render : function(){
38390 var el = this.el = new Roo.Layer({
38392 shadow:this.shadow,
38394 parentEl: this.parentEl || document.body,
38398 this.keyNav = new Roo.menu.MenuNav(this);
38401 el.addClass("x-menu-plain");
38404 el.addClass(this.cls);
38406 // generic focus element
38407 this.focusEl = el.createChild({
38408 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
38410 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
38411 //disabling touch- as it's causing issues ..
38412 //ul.on(Roo.isTouch ? 'touchstart' : 'click' , this.onClick, this);
38413 ul.on('click' , this.onClick, this);
38416 ul.on("mouseover", this.onMouseOver, this);
38417 ul.on("mouseout", this.onMouseOut, this);
38418 this.items.each(function(item){
38423 var li = document.createElement("li");
38424 li.className = "x-menu-list-item";
38425 ul.dom.appendChild(li);
38426 item.render(li, this);
38433 autoWidth : function(){
38434 var el = this.el, ul = this.ul;
38438 var w = this.width;
38441 }else if(Roo.isIE){
38442 el.setWidth(this.minWidth);
38443 var t = el.dom.offsetWidth; // force recalc
38444 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
38449 delayAutoWidth : function(){
38452 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
38454 this.awTask.delay(20);
38459 findTargetItem : function(e){
38460 var t = e.getTarget(".x-menu-list-item", this.ul, true);
38461 if(t && t.menuItemId){
38462 return this.items.get(t.menuItemId);
38467 onClick : function(e){
38468 Roo.log("menu.onClick");
38469 var t = this.findTargetItem(e);
38474 if (Roo.isTouch && e.type == 'touchstart' && t.menu && !t.disabled) {
38475 if(t == this.activeItem && t.shouldDeactivate(e)){
38476 this.activeItem.deactivate();
38477 delete this.activeItem;
38481 this.setActiveItem(t, true);
38489 this.fireEvent("click", this, t, e);
38493 setActiveItem : function(item, autoExpand){
38494 if(item != this.activeItem){
38495 if(this.activeItem){
38496 this.activeItem.deactivate();
38498 this.activeItem = item;
38499 item.activate(autoExpand);
38500 }else if(autoExpand){
38506 tryActivate : function(start, step){
38507 var items = this.items;
38508 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
38509 var item = items.get(i);
38510 if(!item.disabled && item.canActivate){
38511 this.setActiveItem(item, false);
38519 onMouseOver : function(e){
38521 if(t = this.findTargetItem(e)){
38522 if(t.canActivate && !t.disabled){
38523 this.setActiveItem(t, true);
38526 this.fireEvent("mouseover", this, e, t);
38530 onMouseOut : function(e){
38532 if(t = this.findTargetItem(e)){
38533 if(t == this.activeItem && t.shouldDeactivate(e)){
38534 this.activeItem.deactivate();
38535 delete this.activeItem;
38538 this.fireEvent("mouseout", this, e, t);
38542 * Read-only. Returns true if the menu is currently displayed, else false.
38545 isVisible : function(){
38546 return this.el && !this.hidden;
38550 * Displays this menu relative to another element
38551 * @param {String/HTMLElement/Roo.Element} element The element to align to
38552 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
38553 * the element (defaults to this.defaultAlign)
38554 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
38556 show : function(el, pos, parentMenu){
38557 this.parentMenu = parentMenu;
38561 this.fireEvent("beforeshow", this);
38562 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
38566 * Displays this menu at a specific xy position
38567 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
38568 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
38570 showAt : function(xy, parentMenu, /* private: */_e){
38571 this.parentMenu = parentMenu;
38576 this.fireEvent("beforeshow", this);
38577 xy = this.el.adjustForConstraints(xy);
38581 this.hidden = false;
38583 this.fireEvent("show", this);
38586 focus : function(){
38588 this.doFocus.defer(50, this);
38592 doFocus : function(){
38594 this.focusEl.focus();
38599 * Hides this menu and optionally all parent menus
38600 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
38602 hide : function(deep){
38603 if(this.el && this.isVisible()){
38604 this.fireEvent("beforehide", this);
38605 if(this.activeItem){
38606 this.activeItem.deactivate();
38607 this.activeItem = null;
38610 this.hidden = true;
38611 this.fireEvent("hide", this);
38613 if(deep === true && this.parentMenu){
38614 this.parentMenu.hide(true);
38619 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
38620 * Any of the following are valid:
38622 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
38623 * <li>An HTMLElement object which will be converted to a menu item</li>
38624 * <li>A menu item config object that will be created as a new menu item</li>
38625 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
38626 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
38631 var menu = new Roo.menu.Menu();
38633 // Create a menu item to add by reference
38634 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
38636 // Add a bunch of items at once using different methods.
38637 // Only the last item added will be returned.
38638 var item = menu.add(
38639 menuItem, // add existing item by ref
38640 'Dynamic Item', // new TextItem
38641 '-', // new separator
38642 { text: 'Config Item' } // new item by config
38645 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
38646 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
38649 var a = arguments, l = a.length, item;
38650 for(var i = 0; i < l; i++){
38652 if ((typeof(el) == "object") && el.xtype && el.xns) {
38653 el = Roo.factory(el, Roo.menu);
38656 if(el.render){ // some kind of Item
38657 item = this.addItem(el);
38658 }else if(typeof el == "string"){ // string
38659 if(el == "separator" || el == "-"){
38660 item = this.addSeparator();
38662 item = this.addText(el);
38664 }else if(el.tagName || el.el){ // element
38665 item = this.addElement(el);
38666 }else if(typeof el == "object"){ // must be menu item config?
38667 item = this.addMenuItem(el);
38674 * Returns this menu's underlying {@link Roo.Element} object
38675 * @return {Roo.Element} The element
38677 getEl : function(){
38685 * Adds a separator bar to the menu
38686 * @return {Roo.menu.Item} The menu item that was added
38688 addSeparator : function(){
38689 return this.addItem(new Roo.menu.Separator());
38693 * Adds an {@link Roo.Element} object to the menu
38694 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
38695 * @return {Roo.menu.Item} The menu item that was added
38697 addElement : function(el){
38698 return this.addItem(new Roo.menu.BaseItem(el));
38702 * Adds an existing object based on {@link Roo.menu.Item} to the menu
38703 * @param {Roo.menu.Item} item The menu item to add
38704 * @return {Roo.menu.Item} The menu item that was added
38706 addItem : function(item){
38707 this.items.add(item);
38709 var li = document.createElement("li");
38710 li.className = "x-menu-list-item";
38711 this.ul.dom.appendChild(li);
38712 item.render(li, this);
38713 this.delayAutoWidth();
38719 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
38720 * @param {Object} config A MenuItem config object
38721 * @return {Roo.menu.Item} The menu item that was added
38723 addMenuItem : function(config){
38724 if(!(config instanceof Roo.menu.Item)){
38725 if(typeof config.checked == "boolean"){ // must be check menu item config?
38726 config = new Roo.menu.CheckItem(config);
38728 config = new Roo.menu.Item(config);
38731 return this.addItem(config);
38735 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
38736 * @param {String} text The text to display in the menu item
38737 * @return {Roo.menu.Item} The menu item that was added
38739 addText : function(text){
38740 return this.addItem(new Roo.menu.TextItem({ text : text }));
38744 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
38745 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
38746 * @param {Roo.menu.Item} item The menu item to add
38747 * @return {Roo.menu.Item} The menu item that was added
38749 insert : function(index, item){
38750 this.items.insert(index, item);
38752 var li = document.createElement("li");
38753 li.className = "x-menu-list-item";
38754 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
38755 item.render(li, this);
38756 this.delayAutoWidth();
38762 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
38763 * @param {Roo.menu.Item} item The menu item to remove
38765 remove : function(item){
38766 this.items.removeKey(item.id);
38771 * Removes and destroys all items in the menu
38773 removeAll : function(){
38775 while(f = this.items.first()){
38781 // MenuNav is a private utility class used internally by the Menu
38782 Roo.menu.MenuNav = function(menu){
38783 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
38784 this.scope = this.menu = menu;
38787 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
38788 doRelay : function(e, h){
38789 var k = e.getKey();
38790 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
38791 this.menu.tryActivate(0, 1);
38794 return h.call(this.scope || this, e, this.menu);
38797 up : function(e, m){
38798 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
38799 m.tryActivate(m.items.length-1, -1);
38803 down : function(e, m){
38804 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
38805 m.tryActivate(0, 1);
38809 right : function(e, m){
38811 m.activeItem.expandMenu(true);
38815 left : function(e, m){
38817 if(m.parentMenu && m.parentMenu.activeItem){
38818 m.parentMenu.activeItem.activate();
38822 enter : function(e, m){
38824 e.stopPropagation();
38825 m.activeItem.onClick(e);
38826 m.fireEvent("click", this, m.activeItem);
38832 * Ext JS Library 1.1.1
38833 * Copyright(c) 2006-2007, Ext JS, LLC.
38835 * Originally Released Under LGPL - original licence link has changed is not relivant.
38838 * <script type="text/javascript">
38842 * @class Roo.menu.MenuMgr
38843 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
38846 Roo.menu.MenuMgr = function(){
38847 var menus, active, groups = {}, attached = false, lastShow = new Date();
38849 // private - called when first menu is created
38852 active = new Roo.util.MixedCollection();
38853 Roo.get(document).addKeyListener(27, function(){
38854 if(active.length > 0){
38861 function hideAll(){
38862 if(active && active.length > 0){
38863 var c = active.clone();
38864 c.each(function(m){
38871 function onHide(m){
38873 if(active.length < 1){
38874 Roo.get(document).un("mousedown", onMouseDown);
38880 function onShow(m){
38881 var last = active.last();
38882 lastShow = new Date();
38885 Roo.get(document).on("mousedown", onMouseDown);
38889 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
38890 m.parentMenu.activeChild = m;
38891 }else if(last && last.isVisible()){
38892 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
38897 function onBeforeHide(m){
38899 m.activeChild.hide();
38901 if(m.autoHideTimer){
38902 clearTimeout(m.autoHideTimer);
38903 delete m.autoHideTimer;
38908 function onBeforeShow(m){
38909 var pm = m.parentMenu;
38910 if(!pm && !m.allowOtherMenus){
38912 }else if(pm && pm.activeChild && active != m){
38913 pm.activeChild.hide();
38918 function onMouseDown(e){
38919 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
38925 function onBeforeCheck(mi, state){
38927 var g = groups[mi.group];
38928 for(var i = 0, l = g.length; i < l; i++){
38930 g[i].setChecked(false);
38939 * Hides all menus that are currently visible
38941 hideAll : function(){
38946 register : function(menu){
38950 menus[menu.id] = menu;
38951 menu.on("beforehide", onBeforeHide);
38952 menu.on("hide", onHide);
38953 menu.on("beforeshow", onBeforeShow);
38954 menu.on("show", onShow);
38955 var g = menu.group;
38956 if(g && menu.events["checkchange"]){
38960 groups[g].push(menu);
38961 menu.on("checkchange", onCheck);
38966 * Returns a {@link Roo.menu.Menu} object
38967 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
38968 * be used to generate and return a new Menu instance.
38970 get : function(menu){
38971 if(typeof menu == "string"){ // menu id
38972 return menus[menu];
38973 }else if(menu.events){ // menu instance
38975 }else if(typeof menu.length == 'number'){ // array of menu items?
38976 return new Roo.menu.Menu({items:menu});
38977 }else{ // otherwise, must be a config
38978 return new Roo.menu.Menu(menu);
38983 unregister : function(menu){
38984 delete menus[menu.id];
38985 menu.un("beforehide", onBeforeHide);
38986 menu.un("hide", onHide);
38987 menu.un("beforeshow", onBeforeShow);
38988 menu.un("show", onShow);
38989 var g = menu.group;
38990 if(g && menu.events["checkchange"]){
38991 groups[g].remove(menu);
38992 menu.un("checkchange", onCheck);
38997 registerCheckable : function(menuItem){
38998 var g = menuItem.group;
39003 groups[g].push(menuItem);
39004 menuItem.on("beforecheckchange", onBeforeCheck);
39009 unregisterCheckable : function(menuItem){
39010 var g = menuItem.group;
39012 groups[g].remove(menuItem);
39013 menuItem.un("beforecheckchange", onBeforeCheck);
39019 * Ext JS Library 1.1.1
39020 * Copyright(c) 2006-2007, Ext JS, LLC.
39022 * Originally Released Under LGPL - original licence link has changed is not relivant.
39025 * <script type="text/javascript">
39030 * @class Roo.menu.BaseItem
39031 * @extends Roo.Component
39033 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
39034 * management and base configuration options shared by all menu components.
39036 * Creates a new BaseItem
39037 * @param {Object} config Configuration options
39039 Roo.menu.BaseItem = function(config){
39040 Roo.menu.BaseItem.superclass.constructor.call(this, config);
39045 * Fires when this item is clicked
39046 * @param {Roo.menu.BaseItem} this
39047 * @param {Roo.EventObject} e
39052 * Fires when this item is activated
39053 * @param {Roo.menu.BaseItem} this
39057 * @event deactivate
39058 * Fires when this item is deactivated
39059 * @param {Roo.menu.BaseItem} this
39065 this.on("click", this.handler, this.scope, true);
39069 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
39071 * @cfg {Function} handler
39072 * A function that will handle the click event of this menu item (defaults to undefined)
39075 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
39077 canActivate : false,
39080 * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
39085 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
39087 activeClass : "x-menu-item-active",
39089 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
39091 hideOnClick : true,
39093 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
39098 ctype: "Roo.menu.BaseItem",
39101 actionMode : "container",
39104 render : function(container, parentMenu){
39105 this.parentMenu = parentMenu;
39106 Roo.menu.BaseItem.superclass.render.call(this, container);
39107 this.container.menuItemId = this.id;
39111 onRender : function(container, position){
39112 this.el = Roo.get(this.el);
39113 container.dom.appendChild(this.el.dom);
39117 onClick : function(e){
39118 if(!this.disabled && this.fireEvent("click", this, e) !== false
39119 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
39120 this.handleClick(e);
39127 activate : function(){
39131 var li = this.container;
39132 li.addClass(this.activeClass);
39133 this.region = li.getRegion().adjust(2, 2, -2, -2);
39134 this.fireEvent("activate", this);
39139 deactivate : function(){
39140 this.container.removeClass(this.activeClass);
39141 this.fireEvent("deactivate", this);
39145 shouldDeactivate : function(e){
39146 return !this.region || !this.region.contains(e.getPoint());
39150 handleClick : function(e){
39151 if(this.hideOnClick){
39152 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
39157 expandMenu : function(autoActivate){
39162 hideMenu : function(){
39167 * Ext JS Library 1.1.1
39168 * Copyright(c) 2006-2007, Ext JS, LLC.
39170 * Originally Released Under LGPL - original licence link has changed is not relivant.
39173 * <script type="text/javascript">
39177 * @class Roo.menu.Adapter
39178 * @extends Roo.menu.BaseItem
39180 * A base utility class that adapts a non-menu component so that it can be wrapped by a menu item and added to a menu.
39181 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
39183 * Creates a new Adapter
39184 * @param {Object} config Configuration options
39186 Roo.menu.Adapter = function(component, config){
39187 Roo.menu.Adapter.superclass.constructor.call(this, config);
39188 this.component = component;
39190 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
39192 canActivate : true,
39195 onRender : function(container, position){
39196 this.component.render(container);
39197 this.el = this.component.getEl();
39201 activate : function(){
39205 this.component.focus();
39206 this.fireEvent("activate", this);
39211 deactivate : function(){
39212 this.fireEvent("deactivate", this);
39216 disable : function(){
39217 this.component.disable();
39218 Roo.menu.Adapter.superclass.disable.call(this);
39222 enable : function(){
39223 this.component.enable();
39224 Roo.menu.Adapter.superclass.enable.call(this);
39228 * Ext JS Library 1.1.1
39229 * Copyright(c) 2006-2007, Ext JS, LLC.
39231 * Originally Released Under LGPL - original licence link has changed is not relivant.
39234 * <script type="text/javascript">
39238 * @class Roo.menu.TextItem
39239 * @extends Roo.menu.BaseItem
39240 * Adds a static text string to a menu, usually used as either a heading or group separator.
39241 * Note: old style constructor with text is still supported.
39244 * Creates a new TextItem
39245 * @param {Object} cfg Configuration
39247 Roo.menu.TextItem = function(cfg){
39248 if (typeof(cfg) == 'string') {
39251 Roo.apply(this,cfg);
39254 Roo.menu.TextItem.superclass.constructor.call(this);
39257 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
39259 * @cfg {String} text Text to show on item.
39264 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39266 hideOnClick : false,
39268 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
39270 itemCls : "x-menu-text",
39273 onRender : function(){
39274 var s = document.createElement("span");
39275 s.className = this.itemCls;
39276 s.innerHTML = this.text;
39278 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
39282 * Ext JS Library 1.1.1
39283 * Copyright(c) 2006-2007, Ext JS, LLC.
39285 * Originally Released Under LGPL - original licence link has changed is not relivant.
39288 * <script type="text/javascript">
39292 * @class Roo.menu.Separator
39293 * @extends Roo.menu.BaseItem
39294 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
39295 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
39297 * @param {Object} config Configuration options
39299 Roo.menu.Separator = function(config){
39300 Roo.menu.Separator.superclass.constructor.call(this, config);
39303 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
39305 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
39307 itemCls : "x-menu-sep",
39309 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39311 hideOnClick : false,
39314 onRender : function(li){
39315 var s = document.createElement("span");
39316 s.className = this.itemCls;
39317 s.innerHTML = " ";
39319 li.addClass("x-menu-sep-li");
39320 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
39324 * Ext JS Library 1.1.1
39325 * Copyright(c) 2006-2007, Ext JS, LLC.
39327 * Originally Released Under LGPL - original licence link has changed is not relivant.
39330 * <script type="text/javascript">
39333 * @class Roo.menu.Item
39334 * @extends Roo.menu.BaseItem
39335 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
39336 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
39337 * activation and click handling.
39339 * Creates a new Item
39340 * @param {Object} config Configuration options
39342 Roo.menu.Item = function(config){
39343 Roo.menu.Item.superclass.constructor.call(this, config);
39345 this.menu = Roo.menu.MenuMgr.get(this.menu);
39348 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
39350 * @cfg {Roo.menu.Menu} menu
39354 * @cfg {String} text
39355 * The text to show on the menu item.
39359 * @cfg {String} HTML to render in menu
39360 * The text to show on the menu item (HTML version).
39364 * @cfg {String} icon
39365 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
39369 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
39371 itemCls : "x-menu-item",
39373 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
39375 canActivate : true,
39377 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
39380 // doc'd in BaseItem
39384 ctype: "Roo.menu.Item",
39387 onRender : function(container, position){
39388 var el = document.createElement("a");
39389 el.hideFocus = true;
39390 el.unselectable = "on";
39391 el.href = this.href || "#";
39392 if(this.hrefTarget){
39393 el.target = this.hrefTarget;
39395 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
39397 var html = this.html.length ? this.html : String.format('{0}',this.text);
39399 el.innerHTML = String.format(
39400 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
39401 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
39403 Roo.menu.Item.superclass.onRender.call(this, container, position);
39407 * Sets the text to display in this menu item
39408 * @param {String} text The text to display
39409 * @param {Boolean} isHTML true to indicate text is pure html.
39411 setText : function(text, isHTML){
39419 var html = this.html.length ? this.html : String.format('{0}',this.text);
39421 this.el.update(String.format(
39422 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
39423 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
39424 this.parentMenu.autoWidth();
39429 handleClick : function(e){
39430 if(!this.href){ // if no link defined, stop the event automatically
39433 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
39437 activate : function(autoExpand){
39438 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
39448 shouldDeactivate : function(e){
39449 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
39450 if(this.menu && this.menu.isVisible()){
39451 return !this.menu.getEl().getRegion().contains(e.getPoint());
39459 deactivate : function(){
39460 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
39465 expandMenu : function(autoActivate){
39466 if(!this.disabled && this.menu){
39467 clearTimeout(this.hideTimer);
39468 delete this.hideTimer;
39469 if(!this.menu.isVisible() && !this.showTimer){
39470 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
39471 }else if (this.menu.isVisible() && autoActivate){
39472 this.menu.tryActivate(0, 1);
39478 deferExpand : function(autoActivate){
39479 delete this.showTimer;
39480 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
39482 this.menu.tryActivate(0, 1);
39487 hideMenu : function(){
39488 clearTimeout(this.showTimer);
39489 delete this.showTimer;
39490 if(!this.hideTimer && this.menu && this.menu.isVisible()){
39491 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
39496 deferHide : function(){
39497 delete this.hideTimer;
39502 * Ext JS Library 1.1.1
39503 * Copyright(c) 2006-2007, Ext JS, LLC.
39505 * Originally Released Under LGPL - original licence link has changed is not relivant.
39508 * <script type="text/javascript">
39512 * @class Roo.menu.CheckItem
39513 * @extends Roo.menu.Item
39514 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
39516 * Creates a new CheckItem
39517 * @param {Object} config Configuration options
39519 Roo.menu.CheckItem = function(config){
39520 Roo.menu.CheckItem.superclass.constructor.call(this, config);
39523 * @event beforecheckchange
39524 * Fires before the checked value is set, providing an opportunity to cancel if needed
39525 * @param {Roo.menu.CheckItem} this
39526 * @param {Boolean} checked The new checked value that will be set
39528 "beforecheckchange" : true,
39530 * @event checkchange
39531 * Fires after the checked value has been set
39532 * @param {Roo.menu.CheckItem} this
39533 * @param {Boolean} checked The checked value that was set
39535 "checkchange" : true
39537 if(this.checkHandler){
39538 this.on('checkchange', this.checkHandler, this.scope);
39541 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
39543 * @cfg {String} group
39544 * All check items with the same group name will automatically be grouped into a single-select
39545 * radio button group (defaults to '')
39548 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
39550 itemCls : "x-menu-item x-menu-check-item",
39552 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
39554 groupClass : "x-menu-group-item",
39557 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
39558 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
39559 * initialized with checked = true will be rendered as checked.
39564 ctype: "Roo.menu.CheckItem",
39567 onRender : function(c){
39568 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
39570 this.el.addClass(this.groupClass);
39572 Roo.menu.MenuMgr.registerCheckable(this);
39574 this.checked = false;
39575 this.setChecked(true, true);
39580 destroy : function(){
39582 Roo.menu.MenuMgr.unregisterCheckable(this);
39584 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
39588 * Set the checked state of this item
39589 * @param {Boolean} checked The new checked value
39590 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
39592 setChecked : function(state, suppressEvent){
39593 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
39594 if(this.container){
39595 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
39597 this.checked = state;
39598 if(suppressEvent !== true){
39599 this.fireEvent("checkchange", this, state);
39605 handleClick : function(e){
39606 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
39607 this.setChecked(!this.checked);
39609 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
39613 * Ext JS Library 1.1.1
39614 * Copyright(c) 2006-2007, Ext JS, LLC.
39616 * Originally Released Under LGPL - original licence link has changed is not relivant.
39619 * <script type="text/javascript">
39623 * @class Roo.menu.DateItem
39624 * @extends Roo.menu.Adapter
39625 * A menu item that wraps the {@link Roo.DatPicker} component.
39627 * Creates a new DateItem
39628 * @param {Object} config Configuration options
39630 Roo.menu.DateItem = function(config){
39631 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
39632 /** The Roo.DatePicker object @type Roo.DatePicker */
39633 this.picker = this.component;
39634 this.addEvents({select: true});
39636 this.picker.on("render", function(picker){
39637 picker.getEl().swallowEvent("click");
39638 picker.container.addClass("x-menu-date-item");
39641 this.picker.on("select", this.onSelect, this);
39644 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
39646 onSelect : function(picker, date){
39647 this.fireEvent("select", this, date, picker);
39648 Roo.menu.DateItem.superclass.handleClick.call(this);
39652 * Ext JS Library 1.1.1
39653 * Copyright(c) 2006-2007, Ext JS, LLC.
39655 * Originally Released Under LGPL - original licence link has changed is not relivant.
39658 * <script type="text/javascript">
39662 * @class Roo.menu.ColorItem
39663 * @extends Roo.menu.Adapter
39664 * A menu item that wraps the {@link Roo.ColorPalette} component.
39666 * Creates a new ColorItem
39667 * @param {Object} config Configuration options
39669 Roo.menu.ColorItem = function(config){
39670 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
39671 /** The Roo.ColorPalette object @type Roo.ColorPalette */
39672 this.palette = this.component;
39673 this.relayEvents(this.palette, ["select"]);
39674 if(this.selectHandler){
39675 this.on('select', this.selectHandler, this.scope);
39678 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
39680 * Ext JS Library 1.1.1
39681 * Copyright(c) 2006-2007, Ext JS, LLC.
39683 * Originally Released Under LGPL - original licence link has changed is not relivant.
39686 * <script type="text/javascript">
39691 * @class Roo.menu.DateMenu
39692 * @extends Roo.menu.Menu
39693 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
39695 * Creates a new DateMenu
39696 * @param {Object} config Configuration options
39698 Roo.menu.DateMenu = function(config){
39699 Roo.menu.DateMenu.superclass.constructor.call(this, config);
39701 var di = new Roo.menu.DateItem(config);
39704 * The {@link Roo.DatePicker} instance for this DateMenu
39707 this.picker = di.picker;
39710 * @param {DatePicker} picker
39711 * @param {Date} date
39713 this.relayEvents(di, ["select"]);
39714 this.on('beforeshow', function(){
39716 this.picker.hideMonthPicker(false);
39720 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
39724 * Ext JS Library 1.1.1
39725 * Copyright(c) 2006-2007, Ext JS, LLC.
39727 * Originally Released Under LGPL - original licence link has changed is not relivant.
39730 * <script type="text/javascript">
39735 * @class Roo.menu.ColorMenu
39736 * @extends Roo.menu.Menu
39737 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
39739 * Creates a new ColorMenu
39740 * @param {Object} config Configuration options
39742 Roo.menu.ColorMenu = function(config){
39743 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
39745 var ci = new Roo.menu.ColorItem(config);
39748 * The {@link Roo.ColorPalette} instance for this ColorMenu
39749 * @type ColorPalette
39751 this.palette = ci.palette;
39754 * @param {ColorPalette} palette
39755 * @param {String} color
39757 this.relayEvents(ci, ["select"]);
39759 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
39761 * Ext JS Library 1.1.1
39762 * Copyright(c) 2006-2007, Ext JS, LLC.
39764 * Originally Released Under LGPL - original licence link has changed is not relivant.
39767 * <script type="text/javascript">
39771 * @class Roo.form.TextItem
39772 * @extends Roo.BoxComponent
39773 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
39775 * Creates a new TextItem
39776 * @param {Object} config Configuration options
39778 Roo.form.TextItem = function(config){
39779 Roo.form.TextItem.superclass.constructor.call(this, config);
39782 Roo.extend(Roo.form.TextItem, Roo.BoxComponent, {
39785 * @cfg {String} tag the tag for this item (default div)
39789 * @cfg {String} html the content for this item
39793 getAutoCreate : function()
39806 onRender : function(ct, position)
39808 Roo.form.TextItem.superclass.onRender.call(this, ct, position);
39811 var cfg = this.getAutoCreate();
39813 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
39815 if (!cfg.name.length) {
39818 this.el = ct.createChild(cfg, position);
39823 * @param {String} html update the Contents of the element.
39825 setHTML : function(html)
39827 this.fieldEl.dom.innerHTML = html;
39832 * Ext JS Library 1.1.1
39833 * Copyright(c) 2006-2007, Ext JS, LLC.
39835 * Originally Released Under LGPL - original licence link has changed is not relivant.
39838 * <script type="text/javascript">
39842 * @class Roo.form.Field
39843 * @extends Roo.BoxComponent
39844 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
39846 * Creates a new Field
39847 * @param {Object} config Configuration options
39849 Roo.form.Field = function(config){
39850 Roo.form.Field.superclass.constructor.call(this, config);
39853 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
39855 * @cfg {String} fieldLabel Label to use when rendering a form.
39858 * @cfg {String} qtip Mouse over tip
39862 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
39864 invalidClass : "x-form-invalid",
39866 * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided (defaults to "The value in this field is invalid")
39868 invalidText : "The value in this field is invalid",
39870 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
39872 focusClass : "x-form-focus",
39874 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
39875 automatic validation (defaults to "keyup").
39877 validationEvent : "keyup",
39879 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
39881 validateOnBlur : true,
39883 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
39885 validationDelay : 250,
39887 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
39888 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
39890 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
39892 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
39894 fieldClass : "x-form-field",
39896 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
39899 ----------- ----------------------------------------------------------------------
39900 qtip Display a quick tip when the user hovers over the field
39901 title Display a default browser title attribute popup
39902 under Add a block div beneath the field containing the error text
39903 side Add an error icon to the right of the field with a popup on hover
39904 [element id] Add the error text directly to the innerHTML of the specified element
39907 msgTarget : 'qtip',
39909 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
39914 * @cfg {Boolean} readOnly True to mark the field as readOnly in HTML (defaults to false) -- Note: this only sets the element's readOnly DOM attribute.
39919 * @cfg {Boolean} disabled True to disable the field (defaults to false).
39924 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
39926 inputType : undefined,
39929 * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via applyTo (defaults to undefined).
39931 tabIndex : undefined,
39934 isFormField : true,
39939 * @property {Roo.Element} fieldEl
39940 * Element Containing the rendered Field (with label etc.)
39943 * @cfg {Mixed} value A value to initialize this field with.
39948 * @cfg {String} name The field's HTML name attribute.
39951 * @cfg {String} cls A CSS class to apply to the field's underlying element.
39954 loadedValue : false,
39958 initComponent : function(){
39959 Roo.form.Field.superclass.initComponent.call(this);
39963 * Fires when this field receives input focus.
39964 * @param {Roo.form.Field} this
39969 * Fires when this field loses input focus.
39970 * @param {Roo.form.Field} this
39974 * @event specialkey
39975 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
39976 * {@link Roo.EventObject#getKey} to determine which key was pressed.
39977 * @param {Roo.form.Field} this
39978 * @param {Roo.EventObject} e The event object
39983 * Fires just before the field blurs if the field value has changed.
39984 * @param {Roo.form.Field} this
39985 * @param {Mixed} newValue The new value
39986 * @param {Mixed} oldValue The original value
39991 * Fires after the field has been marked as invalid.
39992 * @param {Roo.form.Field} this
39993 * @param {String} msg The validation message
39998 * Fires after the field has been validated with no errors.
39999 * @param {Roo.form.Field} this
40004 * Fires after the key up
40005 * @param {Roo.form.Field} this
40006 * @param {Roo.EventObject} e The event Object
40013 * Returns the name attribute of the field if available
40014 * @return {String} name The field name
40016 getName: function(){
40017 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
40021 onRender : function(ct, position){
40022 Roo.form.Field.superclass.onRender.call(this, ct, position);
40024 var cfg = this.getAutoCreate();
40026 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
40028 if (!cfg.name.length) {
40031 if(this.inputType){
40032 cfg.type = this.inputType;
40034 this.el = ct.createChild(cfg, position);
40036 var type = this.el.dom.type;
40038 if(type == 'password'){
40041 this.el.addClass('x-form-'+type);
40044 this.el.dom.readOnly = true;
40046 if(this.tabIndex !== undefined){
40047 this.el.dom.setAttribute('tabIndex', this.tabIndex);
40050 this.el.addClass([this.fieldClass, this.cls]);
40055 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
40056 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
40057 * @return {Roo.form.Field} this
40059 applyTo : function(target){
40060 this.allowDomMove = false;
40061 this.el = Roo.get(target);
40062 this.render(this.el.dom.parentNode);
40067 initValue : function(){
40068 if(this.value !== undefined){
40069 this.setValue(this.value);
40070 }else if(this.el.dom.value.length > 0){
40071 this.setValue(this.el.dom.value);
40076 * Returns true if this field has been changed since it was originally loaded and is not disabled.
40077 * DEPRICATED - it never worked well - use hasChanged/resetHasChanged.
40079 isDirty : function() {
40080 if(this.disabled) {
40083 return String(this.getValue()) !== String(this.originalValue);
40087 * stores the current value in loadedValue
40089 resetHasChanged : function()
40091 this.loadedValue = String(this.getValue());
40094 * checks the current value against the 'loaded' value.
40095 * Note - will return false if 'resetHasChanged' has not been called first.
40097 hasChanged : function()
40099 if(this.disabled || this.readOnly) {
40102 return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
40108 afterRender : function(){
40109 Roo.form.Field.superclass.afterRender.call(this);
40114 fireKey : function(e){
40115 //Roo.log('field ' + e.getKey());
40116 if(e.isNavKeyPress()){
40117 this.fireEvent("specialkey", this, e);
40122 * Resets the current field value to the originally loaded value and clears any validation messages
40124 reset : function(){
40125 this.setValue(this.resetValue);
40126 this.originalValue = this.getValue();
40127 this.clearInvalid();
40131 initEvents : function(){
40132 // safari killled keypress - so keydown is now used..
40133 this.el.on("keydown" , this.fireKey, this);
40134 this.el.on("focus", this.onFocus, this);
40135 this.el.on("blur", this.onBlur, this);
40136 this.el.relayEvent('keyup', this);
40138 // reference to original value for reset
40139 this.originalValue = this.getValue();
40140 this.resetValue = this.getValue();
40144 onFocus : function(){
40145 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40146 this.el.addClass(this.focusClass);
40148 if(!this.hasFocus){
40149 this.hasFocus = true;
40150 this.startValue = this.getValue();
40151 this.fireEvent("focus", this);
40155 beforeBlur : Roo.emptyFn,
40158 onBlur : function(){
40160 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40161 this.el.removeClass(this.focusClass);
40163 this.hasFocus = false;
40164 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
40167 var v = this.getValue();
40168 if(String(v) !== String(this.startValue)){
40169 this.fireEvent('change', this, v, this.startValue);
40171 this.fireEvent("blur", this);
40175 * Returns whether or not the field value is currently valid
40176 * @param {Boolean} preventMark True to disable marking the field invalid
40177 * @return {Boolean} True if the value is valid, else false
40179 isValid : function(preventMark){
40183 var restore = this.preventMark;
40184 this.preventMark = preventMark === true;
40185 var v = this.validateValue(this.processValue(this.getRawValue()));
40186 this.preventMark = restore;
40191 * Validates the field value
40192 * @return {Boolean} True if the value is valid, else false
40194 validate : function(){
40195 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
40196 this.clearInvalid();
40202 processValue : function(value){
40207 // Subclasses should provide the validation implementation by overriding this
40208 validateValue : function(value){
40213 * Mark this field as invalid
40214 * @param {String} msg The validation message
40216 markInvalid : function(msg){
40217 if(!this.rendered || this.preventMark){ // not rendered
40221 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40223 obj.el.addClass(this.invalidClass);
40224 msg = msg || this.invalidText;
40225 switch(this.msgTarget){
40227 obj.el.dom.qtip = msg;
40228 obj.el.dom.qclass = 'x-form-invalid-tip';
40229 if(Roo.QuickTips){ // fix for floating editors interacting with DND
40230 Roo.QuickTips.enable();
40234 this.el.dom.title = msg;
40238 var elp = this.el.findParent('.x-form-element', 5, true);
40239 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
40240 this.errorEl.setWidth(elp.getWidth(true)-20);
40242 this.errorEl.update(msg);
40243 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
40246 if(!this.errorIcon){
40247 var elp = this.el.findParent('.x-form-element', 5, true);
40248 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
40250 this.alignErrorIcon();
40251 this.errorIcon.dom.qtip = msg;
40252 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
40253 this.errorIcon.show();
40254 this.on('resize', this.alignErrorIcon, this);
40257 var t = Roo.getDom(this.msgTarget);
40259 t.style.display = this.msgDisplay;
40262 this.fireEvent('invalid', this, msg);
40266 alignErrorIcon : function(){
40267 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
40271 * Clear any invalid styles/messages for this field
40273 clearInvalid : function(){
40274 if(!this.rendered || this.preventMark){ // not rendered
40277 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40279 obj.el.removeClass(this.invalidClass);
40280 switch(this.msgTarget){
40282 obj.el.dom.qtip = '';
40285 this.el.dom.title = '';
40289 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
40293 if(this.errorIcon){
40294 this.errorIcon.dom.qtip = '';
40295 this.errorIcon.hide();
40296 this.un('resize', this.alignErrorIcon, this);
40300 var t = Roo.getDom(this.msgTarget);
40302 t.style.display = 'none';
40305 this.fireEvent('valid', this);
40309 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
40310 * @return {Mixed} value The field value
40312 getRawValue : function(){
40313 var v = this.el.getValue();
40319 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
40320 * @return {Mixed} value The field value
40322 getValue : function(){
40323 var v = this.el.getValue();
40329 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
40330 * @param {Mixed} value The value to set
40332 setRawValue : function(v){
40333 return this.el.dom.value = (v === null || v === undefined ? '' : v);
40337 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
40338 * @param {Mixed} value The value to set
40340 setValue : function(v){
40343 this.el.dom.value = (v === null || v === undefined ? '' : v);
40348 adjustSize : function(w, h){
40349 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
40350 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
40354 adjustWidth : function(tag, w){
40355 tag = tag.toLowerCase();
40356 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
40357 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
40358 if(tag == 'input'){
40361 if(tag == 'textarea'){
40364 }else if(Roo.isOpera){
40365 if(tag == 'input'){
40368 if(tag == 'textarea'){
40378 // anything other than normal should be considered experimental
40379 Roo.form.Field.msgFx = {
40381 show: function(msgEl, f){
40382 msgEl.setDisplayed('block');
40385 hide : function(msgEl, f){
40386 msgEl.setDisplayed(false).update('');
40391 show: function(msgEl, f){
40392 msgEl.slideIn('t', {stopFx:true});
40395 hide : function(msgEl, f){
40396 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
40401 show: function(msgEl, f){
40402 msgEl.fixDisplay();
40403 msgEl.alignTo(f.el, 'tl-tr');
40404 msgEl.slideIn('l', {stopFx:true});
40407 hide : function(msgEl, f){
40408 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
40413 * Ext JS Library 1.1.1
40414 * Copyright(c) 2006-2007, Ext JS, LLC.
40416 * Originally Released Under LGPL - original licence link has changed is not relivant.
40419 * <script type="text/javascript">
40424 * @class Roo.form.TextField
40425 * @extends Roo.form.Field
40426 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
40427 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
40429 * Creates a new TextField
40430 * @param {Object} config Configuration options
40432 Roo.form.TextField = function(config){
40433 Roo.form.TextField.superclass.constructor.call(this, config);
40437 * Fires when the autosize function is triggered. The field may or may not have actually changed size
40438 * according to the default logic, but this event provides a hook for the developer to apply additional
40439 * logic at runtime to resize the field if needed.
40440 * @param {Roo.form.Field} this This text field
40441 * @param {Number} width The new field width
40447 Roo.extend(Roo.form.TextField, Roo.form.Field, {
40449 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
40453 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
40457 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
40461 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
40465 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
40469 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
40471 disableKeyFilter : false,
40473 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
40477 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
40481 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
40483 maxLength : Number.MAX_VALUE,
40485 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
40487 minLengthText : "The minimum length for this field is {0}",
40489 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
40491 maxLengthText : "The maximum length for this field is {0}",
40493 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
40495 selectOnFocus : false,
40497 * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space
40499 allowLeadingSpace : false,
40501 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
40503 blankText : "This field is required",
40505 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
40506 * If available, this function will be called only after the basic validators all return true, and will be passed the
40507 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
40511 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
40512 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
40513 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
40517 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
40521 * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
40527 initEvents : function()
40529 if (this.emptyText) {
40530 this.el.attr('placeholder', this.emptyText);
40533 Roo.form.TextField.superclass.initEvents.call(this);
40534 if(this.validationEvent == 'keyup'){
40535 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
40536 this.el.on('keyup', this.filterValidation, this);
40538 else if(this.validationEvent !== false){
40539 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
40542 if(this.selectOnFocus){
40543 this.on("focus", this.preFocus, this);
40545 if (!this.allowLeadingSpace) {
40546 this.on('blur', this.cleanLeadingSpace, this);
40549 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
40550 this.el.on("keypress", this.filterKeys, this);
40553 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
40554 this.el.on("click", this.autoSize, this);
40556 if(this.el.is('input[type=password]') && Roo.isSafari){
40557 this.el.on('keydown', this.SafariOnKeyDown, this);
40561 processValue : function(value){
40562 if(this.stripCharsRe){
40563 var newValue = value.replace(this.stripCharsRe, '');
40564 if(newValue !== value){
40565 this.setRawValue(newValue);
40572 filterValidation : function(e){
40573 if(!e.isNavKeyPress()){
40574 this.validationTask.delay(this.validationDelay);
40579 onKeyUp : function(e){
40580 if(!e.isNavKeyPress()){
40584 // private - clean the leading white space
40585 cleanLeadingSpace : function(e)
40587 if ( this.inputType == 'file') {
40591 this.setValue((this.getValue() + '').replace(/^\s+/,''));
40594 * Resets the current field value to the originally-loaded value and clears any validation messages.
40597 reset : function(){
40598 Roo.form.TextField.superclass.reset.call(this);
40602 preFocus : function(){
40604 if(this.selectOnFocus){
40605 this.el.dom.select();
40611 filterKeys : function(e){
40612 var k = e.getKey();
40613 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
40616 var c = e.getCharCode(), cc = String.fromCharCode(c);
40617 if(Roo.isIE && (e.isSpecialKey() || !cc)){
40620 if(!this.maskRe.test(cc)){
40625 setValue : function(v){
40627 Roo.form.TextField.superclass.setValue.apply(this, arguments);
40633 * Validates a value according to the field's validation rules and marks the field as invalid
40634 * if the validation fails
40635 * @param {Mixed} value The value to validate
40636 * @return {Boolean} True if the value is valid, else false
40638 validateValue : function(value){
40639 if(value.length < 1) { // if it's blank
40640 if(this.allowBlank){
40641 this.clearInvalid();
40644 this.markInvalid(this.blankText);
40648 if(value.length < this.minLength){
40649 this.markInvalid(String.format(this.minLengthText, this.minLength));
40652 if(value.length > this.maxLength){
40653 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
40657 var vt = Roo.form.VTypes;
40658 if(!vt[this.vtype](value, this)){
40659 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
40663 if(typeof this.validator == "function"){
40664 var msg = this.validator(value);
40666 this.markInvalid(msg);
40670 if(this.regex && !this.regex.test(value)){
40671 this.markInvalid(this.regexText);
40678 * Selects text in this field
40679 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
40680 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
40682 selectText : function(start, end){
40683 var v = this.getRawValue();
40685 start = start === undefined ? 0 : start;
40686 end = end === undefined ? v.length : end;
40687 var d = this.el.dom;
40688 if(d.setSelectionRange){
40689 d.setSelectionRange(start, end);
40690 }else if(d.createTextRange){
40691 var range = d.createTextRange();
40692 range.moveStart("character", start);
40693 range.moveEnd("character", v.length-end);
40700 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
40701 * This only takes effect if grow = true, and fires the autosize event.
40703 autoSize : function(){
40704 if(!this.grow || !this.rendered){
40708 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
40711 var v = el.dom.value;
40712 var d = document.createElement('div');
40713 d.appendChild(document.createTextNode(v));
40717 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
40718 this.el.setWidth(w);
40719 this.fireEvent("autosize", this, w);
40723 SafariOnKeyDown : function(event)
40725 // this is a workaround for a password hang bug on chrome/ webkit.
40727 var isSelectAll = false;
40729 if(this.el.dom.selectionEnd > 0){
40730 isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
40732 if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
40733 event.preventDefault();
40738 if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
40740 event.preventDefault();
40741 // this is very hacky as keydown always get's upper case.
40743 var cc = String.fromCharCode(event.getCharCode());
40746 this.setValue( event.shiftKey ? cc : cc.toLowerCase());
40754 * Ext JS Library 1.1.1
40755 * Copyright(c) 2006-2007, Ext JS, LLC.
40757 * Originally Released Under LGPL - original licence link has changed is not relivant.
40760 * <script type="text/javascript">
40764 * @class Roo.form.Hidden
40765 * @extends Roo.form.TextField
40766 * Simple Hidden element used on forms
40768 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
40771 * Creates a new Hidden form element.
40772 * @param {Object} config Configuration options
40777 // easy hidden field...
40778 Roo.form.Hidden = function(config){
40779 Roo.form.Hidden.superclass.constructor.call(this, config);
40782 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
40784 inputType: 'hidden',
40787 labelSeparator: '',
40789 itemCls : 'x-form-item-display-none'
40797 * Ext JS Library 1.1.1
40798 * Copyright(c) 2006-2007, Ext JS, LLC.
40800 * Originally Released Under LGPL - original licence link has changed is not relivant.
40803 * <script type="text/javascript">
40807 * @class Roo.form.TriggerField
40808 * @extends Roo.form.TextField
40809 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
40810 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
40811 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
40812 * for which you can provide a custom implementation. For example:
40814 var trigger = new Roo.form.TriggerField();
40815 trigger.onTriggerClick = myTriggerFn;
40816 trigger.applyTo('my-field');
40819 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
40820 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
40821 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
40822 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
40824 * Create a new TriggerField.
40825 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
40826 * to the base TextField)
40828 Roo.form.TriggerField = function(config){
40829 this.mimicing = false;
40830 Roo.form.TriggerField.superclass.constructor.call(this, config);
40833 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
40835 * @cfg {String} triggerClass A CSS class to apply to the trigger
40838 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
40839 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
40841 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
40843 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
40847 /** @cfg {Boolean} grow @hide */
40848 /** @cfg {Number} growMin @hide */
40849 /** @cfg {Number} growMax @hide */
40855 autoSize: Roo.emptyFn,
40859 deferHeight : true,
40862 actionMode : 'wrap',
40864 onResize : function(w, h){
40865 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
40866 if(typeof w == 'number'){
40867 var x = w - this.trigger.getWidth();
40868 this.el.setWidth(this.adjustWidth('input', x));
40869 this.trigger.setStyle('left', x+'px');
40874 adjustSize : Roo.BoxComponent.prototype.adjustSize,
40877 getResizeEl : function(){
40882 getPositionEl : function(){
40887 alignErrorIcon : function(){
40888 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
40892 onRender : function(ct, position){
40893 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
40894 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
40895 this.trigger = this.wrap.createChild(this.triggerConfig ||
40896 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
40897 if(this.hideTrigger){
40898 this.trigger.setDisplayed(false);
40900 this.initTrigger();
40902 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
40907 initTrigger : function(){
40908 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
40909 this.trigger.addClassOnOver('x-form-trigger-over');
40910 this.trigger.addClassOnClick('x-form-trigger-click');
40914 onDestroy : function(){
40916 this.trigger.removeAllListeners();
40917 this.trigger.remove();
40920 this.wrap.remove();
40922 Roo.form.TriggerField.superclass.onDestroy.call(this);
40926 onFocus : function(){
40927 Roo.form.TriggerField.superclass.onFocus.call(this);
40928 if(!this.mimicing){
40929 this.wrap.addClass('x-trigger-wrap-focus');
40930 this.mimicing = true;
40931 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
40932 if(this.monitorTab){
40933 this.el.on("keydown", this.checkTab, this);
40939 checkTab : function(e){
40940 if(e.getKey() == e.TAB){
40941 this.triggerBlur();
40946 onBlur : function(){
40951 mimicBlur : function(e, t){
40952 if(!this.wrap.contains(t) && this.validateBlur()){
40953 this.triggerBlur();
40958 triggerBlur : function(){
40959 this.mimicing = false;
40960 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
40961 if(this.monitorTab){
40962 this.el.un("keydown", this.checkTab, this);
40964 this.wrap.removeClass('x-trigger-wrap-focus');
40965 Roo.form.TriggerField.superclass.onBlur.call(this);
40969 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
40970 validateBlur : function(e, t){
40975 onDisable : function(){
40976 Roo.form.TriggerField.superclass.onDisable.call(this);
40978 this.wrap.addClass('x-item-disabled');
40983 onEnable : function(){
40984 Roo.form.TriggerField.superclass.onEnable.call(this);
40986 this.wrap.removeClass('x-item-disabled');
40991 onShow : function(){
40992 var ae = this.getActionEl();
40995 ae.dom.style.display = '';
40996 ae.dom.style.visibility = 'visible';
41002 onHide : function(){
41003 var ae = this.getActionEl();
41004 ae.dom.style.display = 'none';
41008 * The function that should handle the trigger's click event. This method does nothing by default until overridden
41009 * by an implementing function.
41011 * @param {EventObject} e
41013 onTriggerClick : Roo.emptyFn
41016 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
41017 // to be extended by an implementing class. For an example of implementing this class, see the custom
41018 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
41019 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
41020 initComponent : function(){
41021 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
41023 this.triggerConfig = {
41024 tag:'span', cls:'x-form-twin-triggers', cn:[
41025 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
41026 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
41030 getTrigger : function(index){
41031 return this.triggers[index];
41034 initTrigger : function(){
41035 var ts = this.trigger.select('.x-form-trigger', true);
41036 this.wrap.setStyle('overflow', 'hidden');
41037 var triggerField = this;
41038 ts.each(function(t, all, index){
41039 t.hide = function(){
41040 var w = triggerField.wrap.getWidth();
41041 this.dom.style.display = 'none';
41042 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41044 t.show = function(){
41045 var w = triggerField.wrap.getWidth();
41046 this.dom.style.display = '';
41047 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41049 var triggerIndex = 'Trigger'+(index+1);
41051 if(this['hide'+triggerIndex]){
41052 t.dom.style.display = 'none';
41054 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
41055 t.addClassOnOver('x-form-trigger-over');
41056 t.addClassOnClick('x-form-trigger-click');
41058 this.triggers = ts.elements;
41061 onTrigger1Click : Roo.emptyFn,
41062 onTrigger2Click : Roo.emptyFn
41065 * Ext JS Library 1.1.1
41066 * Copyright(c) 2006-2007, Ext JS, LLC.
41068 * Originally Released Under LGPL - original licence link has changed is not relivant.
41071 * <script type="text/javascript">
41075 * @class Roo.form.TextArea
41076 * @extends Roo.form.TextField
41077 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
41078 * support for auto-sizing.
41080 * Creates a new TextArea
41081 * @param {Object} config Configuration options
41083 Roo.form.TextArea = function(config){
41084 Roo.form.TextArea.superclass.constructor.call(this, config);
41085 // these are provided exchanges for backwards compat
41086 // minHeight/maxHeight were replaced by growMin/growMax to be
41087 // compatible with TextField growing config values
41088 if(this.minHeight !== undefined){
41089 this.growMin = this.minHeight;
41091 if(this.maxHeight !== undefined){
41092 this.growMax = this.maxHeight;
41096 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
41098 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
41102 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
41106 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
41107 * in the field (equivalent to setting overflow: hidden, defaults to false)
41109 preventScrollbars: false,
41111 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
41112 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
41116 onRender : function(ct, position){
41118 this.defaultAutoCreate = {
41120 style:"width:300px;height:60px;",
41121 autocomplete: "new-password"
41124 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
41126 this.textSizeEl = Roo.DomHelper.append(document.body, {
41127 tag: "pre", cls: "x-form-grow-sizer"
41129 if(this.preventScrollbars){
41130 this.el.setStyle("overflow", "hidden");
41132 this.el.setHeight(this.growMin);
41136 onDestroy : function(){
41137 if(this.textSizeEl){
41138 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
41140 Roo.form.TextArea.superclass.onDestroy.call(this);
41144 onKeyUp : function(e){
41145 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
41151 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
41152 * This only takes effect if grow = true, and fires the autosize event if the height changes.
41154 autoSize : function(){
41155 if(!this.grow || !this.textSizeEl){
41159 var v = el.dom.value;
41160 var ts = this.textSizeEl;
41163 ts.appendChild(document.createTextNode(v));
41166 Roo.fly(ts).setWidth(this.el.getWidth());
41168 v = "  ";
41171 v = v.replace(/\n/g, '<p> </p>');
41173 v += " \n ";
41176 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
41177 if(h != this.lastHeight){
41178 this.lastHeight = h;
41179 this.el.setHeight(h);
41180 this.fireEvent("autosize", this, h);
41185 * Ext JS Library 1.1.1
41186 * Copyright(c) 2006-2007, Ext JS, LLC.
41188 * Originally Released Under LGPL - original licence link has changed is not relivant.
41191 * <script type="text/javascript">
41196 * @class Roo.form.NumberField
41197 * @extends Roo.form.TextField
41198 * Numeric text field that provides automatic keystroke filtering and numeric validation.
41200 * Creates a new NumberField
41201 * @param {Object} config Configuration options
41203 Roo.form.NumberField = function(config){
41204 Roo.form.NumberField.superclass.constructor.call(this, config);
41207 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
41209 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
41211 fieldClass: "x-form-field x-form-num-field",
41213 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
41215 allowDecimals : true,
41217 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
41219 decimalSeparator : ".",
41221 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
41223 decimalPrecision : 2,
41225 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
41227 allowNegative : true,
41229 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
41231 minValue : Number.NEGATIVE_INFINITY,
41233 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
41235 maxValue : Number.MAX_VALUE,
41237 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
41239 minText : "The minimum value for this field is {0}",
41241 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
41243 maxText : "The maximum value for this field is {0}",
41245 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
41246 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
41248 nanText : "{0} is not a valid number",
41251 initEvents : function(){
41252 Roo.form.NumberField.superclass.initEvents.call(this);
41253 var allowed = "0123456789";
41254 if(this.allowDecimals){
41255 allowed += this.decimalSeparator;
41257 if(this.allowNegative){
41260 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
41261 var keyPress = function(e){
41262 var k = e.getKey();
41263 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
41266 var c = e.getCharCode();
41267 if(allowed.indexOf(String.fromCharCode(c)) === -1){
41271 this.el.on("keypress", keyPress, this);
41275 validateValue : function(value){
41276 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
41279 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
41282 var num = this.parseValue(value);
41284 this.markInvalid(String.format(this.nanText, value));
41287 if(num < this.minValue){
41288 this.markInvalid(String.format(this.minText, this.minValue));
41291 if(num > this.maxValue){
41292 this.markInvalid(String.format(this.maxText, this.maxValue));
41298 getValue : function(){
41299 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
41303 parseValue : function(value){
41304 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
41305 return isNaN(value) ? '' : value;
41309 fixPrecision : function(value){
41310 var nan = isNaN(value);
41311 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
41312 return nan ? '' : value;
41314 return parseFloat(value).toFixed(this.decimalPrecision);
41317 setValue : function(v){
41318 v = this.fixPrecision(v);
41319 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
41323 decimalPrecisionFcn : function(v){
41324 return Math.floor(v);
41327 beforeBlur : function(){
41328 var v = this.parseValue(this.getRawValue());
41335 * Ext JS Library 1.1.1
41336 * Copyright(c) 2006-2007, Ext JS, LLC.
41338 * Originally Released Under LGPL - original licence link has changed is not relivant.
41341 * <script type="text/javascript">
41345 * @class Roo.form.DateField
41346 * @extends Roo.form.TriggerField
41347 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
41349 * Create a new DateField
41350 * @param {Object} config
41352 Roo.form.DateField = function(config)
41354 Roo.form.DateField.superclass.constructor.call(this, config);
41360 * Fires when a date is selected
41361 * @param {Roo.form.DateField} combo This combo box
41362 * @param {Date} date The date selected
41369 if(typeof this.minValue == "string") {
41370 this.minValue = this.parseDate(this.minValue);
41372 if(typeof this.maxValue == "string") {
41373 this.maxValue = this.parseDate(this.maxValue);
41375 this.ddMatch = null;
41376 if(this.disabledDates){
41377 var dd = this.disabledDates;
41379 for(var i = 0; i < dd.length; i++){
41381 if(i != dd.length-1) {
41385 this.ddMatch = new RegExp(re + ")");
41389 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
41391 * @cfg {String} format
41392 * The default date format string which can be overriden for localization support. The format must be
41393 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
41397 * @cfg {String} altFormats
41398 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
41399 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
41401 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
41403 * @cfg {Array} disabledDays
41404 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
41406 disabledDays : null,
41408 * @cfg {String} disabledDaysText
41409 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
41411 disabledDaysText : "Disabled",
41413 * @cfg {Array} disabledDates
41414 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
41415 * expression so they are very powerful. Some examples:
41417 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
41418 * <li>["03/08", "09/16"] would disable those days for every year</li>
41419 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
41420 * <li>["03/../2006"] would disable every day in March 2006</li>
41421 * <li>["^03"] would disable every day in every March</li>
41423 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
41424 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
41426 disabledDates : null,
41428 * @cfg {String} disabledDatesText
41429 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
41431 disabledDatesText : "Disabled",
41433 * @cfg {Date/String} minValue
41434 * The minimum allowed date. Can be either a Javascript date object or a string date in a
41435 * valid format (defaults to null).
41439 * @cfg {Date/String} maxValue
41440 * The maximum allowed date. Can be either a Javascript date object or a string date in a
41441 * valid format (defaults to null).
41445 * @cfg {String} minText
41446 * The error text to display when the date in the cell is before minValue (defaults to
41447 * 'The date in this field must be after {minValue}').
41449 minText : "The date in this field must be equal to or after {0}",
41451 * @cfg {String} maxText
41452 * The error text to display when the date in the cell is after maxValue (defaults to
41453 * 'The date in this field must be before {maxValue}').
41455 maxText : "The date in this field must be equal to or before {0}",
41457 * @cfg {String} invalidText
41458 * The error text to display when the date in the field is invalid (defaults to
41459 * '{value} is not a valid date - it must be in the format {format}').
41461 invalidText : "{0} is not a valid date - it must be in the format {1}",
41463 * @cfg {String} triggerClass
41464 * An additional CSS class used to style the trigger button. The trigger will always get the
41465 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
41466 * which displays a calendar icon).
41468 triggerClass : 'x-form-date-trigger',
41472 * @cfg {Boolean} useIso
41473 * if enabled, then the date field will use a hidden field to store the
41474 * real value as iso formated date. default (false)
41478 * @cfg {String/Object} autoCreate
41479 * A DomHelper element spec, or true for a default element spec (defaults to
41480 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
41483 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
41486 hiddenField: false,
41488 onRender : function(ct, position)
41490 Roo.form.DateField.superclass.onRender.call(this, ct, position);
41492 //this.el.dom.removeAttribute('name');
41493 Roo.log("Changing name?");
41494 this.el.dom.setAttribute('name', this.name + '____hidden___' );
41495 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
41497 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
41498 // prevent input submission
41499 this.hiddenName = this.name;
41506 validateValue : function(value)
41508 value = this.formatDate(value);
41509 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
41510 Roo.log('super failed');
41513 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
41516 var svalue = value;
41517 value = this.parseDate(value);
41519 Roo.log('parse date failed' + svalue);
41520 this.markInvalid(String.format(this.invalidText, svalue, this.format));
41523 var time = value.getTime();
41524 if(this.minValue && time < this.minValue.getTime()){
41525 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
41528 if(this.maxValue && time > this.maxValue.getTime()){
41529 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
41532 if(this.disabledDays){
41533 var day = value.getDay();
41534 for(var i = 0; i < this.disabledDays.length; i++) {
41535 if(day === this.disabledDays[i]){
41536 this.markInvalid(this.disabledDaysText);
41541 var fvalue = this.formatDate(value);
41542 if(this.ddMatch && this.ddMatch.test(fvalue)){
41543 this.markInvalid(String.format(this.disabledDatesText, fvalue));
41550 // Provides logic to override the default TriggerField.validateBlur which just returns true
41551 validateBlur : function(){
41552 return !this.menu || !this.menu.isVisible();
41555 getName: function()
41557 // returns hidden if it's set..
41558 if (!this.rendered) {return ''};
41559 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
41564 * Returns the current date value of the date field.
41565 * @return {Date} The date value
41567 getValue : function(){
41569 return this.hiddenField ?
41570 this.hiddenField.value :
41571 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
41575 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
41576 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
41577 * (the default format used is "m/d/y").
41580 //All of these calls set the same date value (May 4, 2006)
41582 //Pass a date object:
41583 var dt = new Date('5/4/06');
41584 dateField.setValue(dt);
41586 //Pass a date string (default format):
41587 dateField.setValue('5/4/06');
41589 //Pass a date string (custom format):
41590 dateField.format = 'Y-m-d';
41591 dateField.setValue('2006-5-4');
41593 * @param {String/Date} date The date or valid date string
41595 setValue : function(date){
41596 if (this.hiddenField) {
41597 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
41599 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
41600 // make sure the value field is always stored as a date..
41601 this.value = this.parseDate(date);
41607 parseDate : function(value){
41608 if(!value || value instanceof Date){
41611 var v = Date.parseDate(value, this.format);
41612 if (!v && this.useIso) {
41613 v = Date.parseDate(value, 'Y-m-d');
41615 if(!v && this.altFormats){
41616 if(!this.altFormatsArray){
41617 this.altFormatsArray = this.altFormats.split("|");
41619 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
41620 v = Date.parseDate(value, this.altFormatsArray[i]);
41627 formatDate : function(date, fmt){
41628 return (!date || !(date instanceof Date)) ?
41629 date : date.dateFormat(fmt || this.format);
41634 select: function(m, d){
41637 this.fireEvent('select', this, d);
41639 show : function(){ // retain focus styling
41643 this.focus.defer(10, this);
41644 var ml = this.menuListeners;
41645 this.menu.un("select", ml.select, this);
41646 this.menu.un("show", ml.show, this);
41647 this.menu.un("hide", ml.hide, this);
41652 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
41653 onTriggerClick : function(){
41657 if(this.menu == null){
41658 this.menu = new Roo.menu.DateMenu();
41660 Roo.apply(this.menu.picker, {
41661 showClear: this.allowBlank,
41662 minDate : this.minValue,
41663 maxDate : this.maxValue,
41664 disabledDatesRE : this.ddMatch,
41665 disabledDatesText : this.disabledDatesText,
41666 disabledDays : this.disabledDays,
41667 disabledDaysText : this.disabledDaysText,
41668 format : this.useIso ? 'Y-m-d' : this.format,
41669 minText : String.format(this.minText, this.formatDate(this.minValue)),
41670 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
41672 this.menu.on(Roo.apply({}, this.menuListeners, {
41675 this.menu.picker.setValue(this.getValue() || new Date());
41676 this.menu.show(this.el, "tl-bl?");
41679 beforeBlur : function(){
41680 var v = this.parseDate(this.getRawValue());
41690 isDirty : function() {
41691 if(this.disabled) {
41695 if(typeof(this.startValue) === 'undefined'){
41699 return String(this.getValue()) !== String(this.startValue);
41703 cleanLeadingSpace : function(e)
41710 * Ext JS Library 1.1.1
41711 * Copyright(c) 2006-2007, Ext JS, LLC.
41713 * Originally Released Under LGPL - original licence link has changed is not relivant.
41716 * <script type="text/javascript">
41720 * @class Roo.form.MonthField
41721 * @extends Roo.form.TriggerField
41722 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
41724 * Create a new MonthField
41725 * @param {Object} config
41727 Roo.form.MonthField = function(config){
41729 Roo.form.MonthField.superclass.constructor.call(this, config);
41735 * Fires when a date is selected
41736 * @param {Roo.form.MonthFieeld} combo This combo box
41737 * @param {Date} date The date selected
41744 if(typeof this.minValue == "string") {
41745 this.minValue = this.parseDate(this.minValue);
41747 if(typeof this.maxValue == "string") {
41748 this.maxValue = this.parseDate(this.maxValue);
41750 this.ddMatch = null;
41751 if(this.disabledDates){
41752 var dd = this.disabledDates;
41754 for(var i = 0; i < dd.length; i++){
41756 if(i != dd.length-1) {
41760 this.ddMatch = new RegExp(re + ")");
41764 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
41766 * @cfg {String} format
41767 * The default date format string which can be overriden for localization support. The format must be
41768 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
41772 * @cfg {String} altFormats
41773 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
41774 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
41776 altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
41778 * @cfg {Array} disabledDays
41779 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
41781 disabledDays : [0,1,2,3,4,5,6],
41783 * @cfg {String} disabledDaysText
41784 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
41786 disabledDaysText : "Disabled",
41788 * @cfg {Array} disabledDates
41789 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
41790 * expression so they are very powerful. Some examples:
41792 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
41793 * <li>["03/08", "09/16"] would disable those days for every year</li>
41794 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
41795 * <li>["03/../2006"] would disable every day in March 2006</li>
41796 * <li>["^03"] would disable every day in every March</li>
41798 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
41799 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
41801 disabledDates : null,
41803 * @cfg {String} disabledDatesText
41804 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
41806 disabledDatesText : "Disabled",
41808 * @cfg {Date/String} minValue
41809 * The minimum allowed date. Can be either a Javascript date object or a string date in a
41810 * valid format (defaults to null).
41814 * @cfg {Date/String} maxValue
41815 * The maximum allowed date. Can be either a Javascript date object or a string date in a
41816 * valid format (defaults to null).
41820 * @cfg {String} minText
41821 * The error text to display when the date in the cell is before minValue (defaults to
41822 * 'The date in this field must be after {minValue}').
41824 minText : "The date in this field must be equal to or after {0}",
41826 * @cfg {String} maxTextf
41827 * The error text to display when the date in the cell is after maxValue (defaults to
41828 * 'The date in this field must be before {maxValue}').
41830 maxText : "The date in this field must be equal to or before {0}",
41832 * @cfg {String} invalidText
41833 * The error text to display when the date in the field is invalid (defaults to
41834 * '{value} is not a valid date - it must be in the format {format}').
41836 invalidText : "{0} is not a valid date - it must be in the format {1}",
41838 * @cfg {String} triggerClass
41839 * An additional CSS class used to style the trigger button. The trigger will always get the
41840 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
41841 * which displays a calendar icon).
41843 triggerClass : 'x-form-date-trigger',
41847 * @cfg {Boolean} useIso
41848 * if enabled, then the date field will use a hidden field to store the
41849 * real value as iso formated date. default (true)
41853 * @cfg {String/Object} autoCreate
41854 * A DomHelper element spec, or true for a default element spec (defaults to
41855 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
41858 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
41861 hiddenField: false,
41863 hideMonthPicker : false,
41865 onRender : function(ct, position)
41867 Roo.form.MonthField.superclass.onRender.call(this, ct, position);
41869 this.el.dom.removeAttribute('name');
41870 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
41872 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
41873 // prevent input submission
41874 this.hiddenName = this.name;
41881 validateValue : function(value)
41883 value = this.formatDate(value);
41884 if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
41887 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
41890 var svalue = value;
41891 value = this.parseDate(value);
41893 this.markInvalid(String.format(this.invalidText, svalue, this.format));
41896 var time = value.getTime();
41897 if(this.minValue && time < this.minValue.getTime()){
41898 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
41901 if(this.maxValue && time > this.maxValue.getTime()){
41902 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
41905 /*if(this.disabledDays){
41906 var day = value.getDay();
41907 for(var i = 0; i < this.disabledDays.length; i++) {
41908 if(day === this.disabledDays[i]){
41909 this.markInvalid(this.disabledDaysText);
41915 var fvalue = this.formatDate(value);
41916 /*if(this.ddMatch && this.ddMatch.test(fvalue)){
41917 this.markInvalid(String.format(this.disabledDatesText, fvalue));
41925 // Provides logic to override the default TriggerField.validateBlur which just returns true
41926 validateBlur : function(){
41927 return !this.menu || !this.menu.isVisible();
41931 * Returns the current date value of the date field.
41932 * @return {Date} The date value
41934 getValue : function(){
41938 return this.hiddenField ?
41939 this.hiddenField.value :
41940 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
41944 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
41945 * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
41946 * (the default format used is "m/d/y").
41949 //All of these calls set the same date value (May 4, 2006)
41951 //Pass a date object:
41952 var dt = new Date('5/4/06');
41953 monthField.setValue(dt);
41955 //Pass a date string (default format):
41956 monthField.setValue('5/4/06');
41958 //Pass a date string (custom format):
41959 monthField.format = 'Y-m-d';
41960 monthField.setValue('2006-5-4');
41962 * @param {String/Date} date The date or valid date string
41964 setValue : function(date){
41965 Roo.log('month setValue' + date);
41966 // can only be first of month..
41968 var val = this.parseDate(date);
41970 if (this.hiddenField) {
41971 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
41973 Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
41974 this.value = this.parseDate(date);
41978 parseDate : function(value){
41979 if(!value || value instanceof Date){
41980 value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
41983 var v = Date.parseDate(value, this.format);
41984 if (!v && this.useIso) {
41985 v = Date.parseDate(value, 'Y-m-d');
41989 v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
41993 if(!v && this.altFormats){
41994 if(!this.altFormatsArray){
41995 this.altFormatsArray = this.altFormats.split("|");
41997 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
41998 v = Date.parseDate(value, this.altFormatsArray[i]);
42005 formatDate : function(date, fmt){
42006 return (!date || !(date instanceof Date)) ?
42007 date : date.dateFormat(fmt || this.format);
42012 select: function(m, d){
42014 this.fireEvent('select', this, d);
42016 show : function(){ // retain focus styling
42020 this.focus.defer(10, this);
42021 var ml = this.menuListeners;
42022 this.menu.un("select", ml.select, this);
42023 this.menu.un("show", ml.show, this);
42024 this.menu.un("hide", ml.hide, this);
42028 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
42029 onTriggerClick : function(){
42033 if(this.menu == null){
42034 this.menu = new Roo.menu.DateMenu();
42038 Roo.apply(this.menu.picker, {
42040 showClear: this.allowBlank,
42041 minDate : this.minValue,
42042 maxDate : this.maxValue,
42043 disabledDatesRE : this.ddMatch,
42044 disabledDatesText : this.disabledDatesText,
42046 format : this.useIso ? 'Y-m-d' : this.format,
42047 minText : String.format(this.minText, this.formatDate(this.minValue)),
42048 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
42051 this.menu.on(Roo.apply({}, this.menuListeners, {
42059 // hide month picker get's called when we called by 'before hide';
42061 var ignorehide = true;
42062 p.hideMonthPicker = function(disableAnim){
42066 if(this.monthPicker){
42067 Roo.log("hideMonthPicker called");
42068 if(disableAnim === true){
42069 this.monthPicker.hide();
42071 this.monthPicker.slideOut('t', {duration:.2});
42072 p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
42073 p.fireEvent("select", this, this.value);
42079 Roo.log('picker set value');
42080 Roo.log(this.getValue());
42081 p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
42082 m.show(this.el, 'tl-bl?');
42083 ignorehide = false;
42084 // this will trigger hideMonthPicker..
42087 // hidden the day picker
42088 Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
42094 p.showMonthPicker.defer(100, p);
42100 beforeBlur : function(){
42101 var v = this.parseDate(this.getRawValue());
42107 /** @cfg {Boolean} grow @hide */
42108 /** @cfg {Number} growMin @hide */
42109 /** @cfg {Number} growMax @hide */
42116 * Ext JS Library 1.1.1
42117 * Copyright(c) 2006-2007, Ext JS, LLC.
42119 * Originally Released Under LGPL - original licence link has changed is not relivant.
42122 * <script type="text/javascript">
42127 * @class Roo.form.ComboBox
42128 * @extends Roo.form.TriggerField
42129 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
42131 * Create a new ComboBox.
42132 * @param {Object} config Configuration options
42134 Roo.form.ComboBox = function(config){
42135 Roo.form.ComboBox.superclass.constructor.call(this, config);
42139 * Fires when the dropdown list is expanded
42140 * @param {Roo.form.ComboBox} combo This combo box
42145 * Fires when the dropdown list is collapsed
42146 * @param {Roo.form.ComboBox} combo This combo box
42150 * @event beforeselect
42151 * Fires before a list item is selected. Return false to cancel the selection.
42152 * @param {Roo.form.ComboBox} combo This combo box
42153 * @param {Roo.data.Record} record The data record returned from the underlying store
42154 * @param {Number} index The index of the selected item in the dropdown list
42156 'beforeselect' : true,
42159 * Fires when a list item is selected
42160 * @param {Roo.form.ComboBox} combo This combo box
42161 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
42162 * @param {Number} index The index of the selected item in the dropdown list
42166 * @event beforequery
42167 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
42168 * The event object passed has these properties:
42169 * @param {Roo.form.ComboBox} combo This combo box
42170 * @param {String} query The query
42171 * @param {Boolean} forceAll true to force "all" query
42172 * @param {Boolean} cancel true to cancel the query
42173 * @param {Object} e The query event object
42175 'beforequery': true,
42178 * Fires when the 'add' icon is pressed (add a listener to enable add button)
42179 * @param {Roo.form.ComboBox} combo This combo box
42184 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
42185 * @param {Roo.form.ComboBox} combo This combo box
42186 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
42192 if(this.transform){
42193 this.allowDomMove = false;
42194 var s = Roo.getDom(this.transform);
42195 if(!this.hiddenName){
42196 this.hiddenName = s.name;
42199 this.mode = 'local';
42200 var d = [], opts = s.options;
42201 for(var i = 0, len = opts.length;i < len; i++){
42203 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
42205 this.value = value;
42207 d.push([value, o.text]);
42209 this.store = new Roo.data.SimpleStore({
42211 fields: ['value', 'text'],
42214 this.valueField = 'value';
42215 this.displayField = 'text';
42217 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
42218 if(!this.lazyRender){
42219 this.target = true;
42220 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
42221 s.parentNode.removeChild(s); // remove it
42222 this.render(this.el.parentNode);
42224 s.parentNode.removeChild(s); // remove it
42229 this.store = Roo.factory(this.store, Roo.data);
42232 this.selectedIndex = -1;
42233 if(this.mode == 'local'){
42234 if(config.queryDelay === undefined){
42235 this.queryDelay = 10;
42237 if(config.minChars === undefined){
42243 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
42245 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
42248 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
42249 * rendering into an Roo.Editor, defaults to false)
42252 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
42253 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
42256 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
42259 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
42260 * the dropdown list (defaults to undefined, with no header element)
42264 * @cfg {String/Roo.Template} tpl The template to use to render the output
42268 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
42270 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
42272 listWidth: undefined,
42274 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
42275 * mode = 'remote' or 'text' if mode = 'local')
42277 displayField: undefined,
42279 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
42280 * mode = 'remote' or 'value' if mode = 'local').
42281 * Note: use of a valueField requires the user make a selection
42282 * in order for a value to be mapped.
42284 valueField: undefined,
42288 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
42289 * field's data value (defaults to the underlying DOM element's name)
42291 hiddenName: undefined,
42293 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
42297 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
42299 selectedClass: 'x-combo-selected',
42301 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
42302 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
42303 * which displays a downward arrow icon).
42305 triggerClass : 'x-form-arrow-trigger',
42307 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
42311 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
42312 * anchor positions (defaults to 'tl-bl')
42314 listAlign: 'tl-bl?',
42316 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
42320 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
42321 * query specified by the allQuery config option (defaults to 'query')
42323 triggerAction: 'query',
42325 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
42326 * (defaults to 4, does not apply if editable = false)
42330 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
42331 * delay (typeAheadDelay) if it matches a known value (defaults to false)
42335 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
42336 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
42340 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
42341 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
42345 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
42346 * when editable = true (defaults to false)
42348 selectOnFocus:false,
42350 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
42352 queryParam: 'query',
42354 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
42355 * when mode = 'remote' (defaults to 'Loading...')
42357 loadingText: 'Loading...',
42359 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
42363 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
42367 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
42368 * traditional select (defaults to true)
42372 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
42376 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
42380 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
42381 * listWidth has a higher value)
42385 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
42386 * allow the user to set arbitrary text into the field (defaults to false)
42388 forceSelection:false,
42390 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
42391 * if typeAhead = true (defaults to 250)
42393 typeAheadDelay : 250,
42395 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
42396 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
42398 valueNotFoundText : undefined,
42400 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
42402 blockFocus : false,
42405 * @cfg {Boolean} disableClear Disable showing of clear button.
42407 disableClear : false,
42409 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
42411 alwaysQuery : false,
42417 // element that contains real text value.. (when hidden is used..)
42420 onRender : function(ct, position)
42422 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
42424 if(this.hiddenName){
42425 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
42427 this.hiddenField.value =
42428 this.hiddenValue !== undefined ? this.hiddenValue :
42429 this.value !== undefined ? this.value : '';
42431 // prevent input submission
42432 this.el.dom.removeAttribute('name');
42438 this.el.dom.setAttribute('autocomplete', 'off');
42441 var cls = 'x-combo-list';
42443 this.list = new Roo.Layer({
42444 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
42447 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
42448 this.list.setWidth(lw);
42449 this.list.swallowEvent('mousewheel');
42450 this.assetHeight = 0;
42453 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
42454 this.assetHeight += this.header.getHeight();
42457 this.innerList = this.list.createChild({cls:cls+'-inner'});
42458 this.innerList.on('mouseover', this.onViewOver, this);
42459 this.innerList.on('mousemove', this.onViewMove, this);
42460 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
42462 if(this.allowBlank && !this.pageSize && !this.disableClear){
42463 this.footer = this.list.createChild({cls:cls+'-ft'});
42464 this.pageTb = new Roo.Toolbar(this.footer);
42468 this.footer = this.list.createChild({cls:cls+'-ft'});
42469 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
42470 {pageSize: this.pageSize});
42474 if (this.pageTb && this.allowBlank && !this.disableClear) {
42476 this.pageTb.add(new Roo.Toolbar.Fill(), {
42477 cls: 'x-btn-icon x-btn-clear',
42479 handler: function()
42482 _this.clearValue();
42483 _this.onSelect(false, -1);
42488 this.assetHeight += this.footer.getHeight();
42493 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
42496 this.view = new Roo.View(this.innerList, this.tpl, {
42499 selectedClass: this.selectedClass
42502 this.view.on('click', this.onViewClick, this);
42504 this.store.on('beforeload', this.onBeforeLoad, this);
42505 this.store.on('load', this.onLoad, this);
42506 this.store.on('loadexception', this.onLoadException, this);
42508 if(this.resizable){
42509 this.resizer = new Roo.Resizable(this.list, {
42510 pinned:true, handles:'se'
42512 this.resizer.on('resize', function(r, w, h){
42513 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
42514 this.listWidth = w;
42515 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
42516 this.restrictHeight();
42518 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
42520 if(!this.editable){
42521 this.editable = true;
42522 this.setEditable(false);
42526 if (typeof(this.events.add.listeners) != 'undefined') {
42528 this.addicon = this.wrap.createChild(
42529 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
42531 this.addicon.on('click', function(e) {
42532 this.fireEvent('add', this);
42535 if (typeof(this.events.edit.listeners) != 'undefined') {
42537 this.editicon = this.wrap.createChild(
42538 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
42539 if (this.addicon) {
42540 this.editicon.setStyle('margin-left', '40px');
42542 this.editicon.on('click', function(e) {
42544 // we fire even if inothing is selected..
42545 this.fireEvent('edit', this, this.lastData );
42555 initEvents : function(){
42556 Roo.form.ComboBox.superclass.initEvents.call(this);
42558 this.keyNav = new Roo.KeyNav(this.el, {
42559 "up" : function(e){
42560 this.inKeyMode = true;
42564 "down" : function(e){
42565 if(!this.isExpanded()){
42566 this.onTriggerClick();
42568 this.inKeyMode = true;
42573 "enter" : function(e){
42574 this.onViewClick();
42578 "esc" : function(e){
42582 "tab" : function(e){
42583 this.onViewClick(false);
42584 this.fireEvent("specialkey", this, e);
42590 doRelay : function(foo, bar, hname){
42591 if(hname == 'down' || this.scope.isExpanded()){
42592 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
42599 this.queryDelay = Math.max(this.queryDelay || 10,
42600 this.mode == 'local' ? 10 : 250);
42601 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
42602 if(this.typeAhead){
42603 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
42605 if(this.editable !== false){
42606 this.el.on("keyup", this.onKeyUp, this);
42608 if(this.forceSelection){
42609 this.on('blur', this.doForce, this);
42613 onDestroy : function(){
42615 this.view.setStore(null);
42616 this.view.el.removeAllListeners();
42617 this.view.el.remove();
42618 this.view.purgeListeners();
42621 this.list.destroy();
42624 this.store.un('beforeload', this.onBeforeLoad, this);
42625 this.store.un('load', this.onLoad, this);
42626 this.store.un('loadexception', this.onLoadException, this);
42628 Roo.form.ComboBox.superclass.onDestroy.call(this);
42632 fireKey : function(e){
42633 if(e.isNavKeyPress() && !this.list.isVisible()){
42634 this.fireEvent("specialkey", this, e);
42639 onResize: function(w, h){
42640 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
42642 if(typeof w != 'number'){
42643 // we do not handle it!?!?
42646 var tw = this.trigger.getWidth();
42647 tw += this.addicon ? this.addicon.getWidth() : 0;
42648 tw += this.editicon ? this.editicon.getWidth() : 0;
42650 this.el.setWidth( this.adjustWidth('input', x));
42652 this.trigger.setStyle('left', x+'px');
42654 if(this.list && this.listWidth === undefined){
42655 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
42656 this.list.setWidth(lw);
42657 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
42665 * Allow or prevent the user from directly editing the field text. If false is passed,
42666 * the user will only be able to select from the items defined in the dropdown list. This method
42667 * is the runtime equivalent of setting the 'editable' config option at config time.
42668 * @param {Boolean} value True to allow the user to directly edit the field text
42670 setEditable : function(value){
42671 if(value == this.editable){
42674 this.editable = value;
42676 this.el.dom.setAttribute('readOnly', true);
42677 this.el.on('mousedown', this.onTriggerClick, this);
42678 this.el.addClass('x-combo-noedit');
42680 this.el.dom.setAttribute('readOnly', false);
42681 this.el.un('mousedown', this.onTriggerClick, this);
42682 this.el.removeClass('x-combo-noedit');
42687 onBeforeLoad : function(){
42688 if(!this.hasFocus){
42691 this.innerList.update(this.loadingText ?
42692 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
42693 this.restrictHeight();
42694 this.selectedIndex = -1;
42698 onLoad : function(){
42699 if(!this.hasFocus){
42702 if(this.store.getCount() > 0){
42704 this.restrictHeight();
42705 if(this.lastQuery == this.allQuery){
42707 this.el.dom.select();
42709 if(!this.selectByValue(this.value, true)){
42710 this.select(0, true);
42714 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
42715 this.taTask.delay(this.typeAheadDelay);
42719 this.onEmptyResults();
42724 onLoadException : function()
42727 Roo.log(this.store.reader.jsonData);
42728 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
42729 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
42735 onTypeAhead : function(){
42736 if(this.store.getCount() > 0){
42737 var r = this.store.getAt(0);
42738 var newValue = r.data[this.displayField];
42739 var len = newValue.length;
42740 var selStart = this.getRawValue().length;
42741 if(selStart != len){
42742 this.setRawValue(newValue);
42743 this.selectText(selStart, newValue.length);
42749 onSelect : function(record, index){
42750 if(this.fireEvent('beforeselect', this, record, index) !== false){
42751 this.setFromData(index > -1 ? record.data : false);
42753 this.fireEvent('select', this, record, index);
42758 * Returns the currently selected field value or empty string if no value is set.
42759 * @return {String} value The selected value
42761 getValue : function(){
42762 if(this.valueField){
42763 return typeof this.value != 'undefined' ? this.value : '';
42765 return Roo.form.ComboBox.superclass.getValue.call(this);
42769 * Clears any text/value currently set in the field
42771 clearValue : function(){
42772 if(this.hiddenField){
42773 this.hiddenField.value = '';
42776 this.setRawValue('');
42777 this.lastSelectionText = '';
42782 * Sets the specified value into the field. If the value finds a match, the corresponding record text
42783 * will be displayed in the field. If the value does not match the data value of an existing item,
42784 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
42785 * Otherwise the field will be blank (although the value will still be set).
42786 * @param {String} value The value to match
42788 setValue : function(v){
42790 if(this.valueField){
42791 var r = this.findRecord(this.valueField, v);
42793 text = r.data[this.displayField];
42794 }else if(this.valueNotFoundText !== undefined){
42795 text = this.valueNotFoundText;
42798 this.lastSelectionText = text;
42799 if(this.hiddenField){
42800 this.hiddenField.value = v;
42802 Roo.form.ComboBox.superclass.setValue.call(this, text);
42806 * @property {Object} the last set data for the element
42811 * Sets the value of the field based on a object which is related to the record format for the store.
42812 * @param {Object} value the value to set as. or false on reset?
42814 setFromData : function(o){
42815 var dv = ''; // display value
42816 var vv = ''; // value value..
42818 if (this.displayField) {
42819 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
42821 // this is an error condition!!!
42822 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
42825 if(this.valueField){
42826 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
42828 if(this.hiddenField){
42829 this.hiddenField.value = vv;
42831 this.lastSelectionText = dv;
42832 Roo.form.ComboBox.superclass.setValue.call(this, dv);
42836 // no hidden field.. - we store the value in 'value', but still display
42837 // display field!!!!
42838 this.lastSelectionText = dv;
42839 Roo.form.ComboBox.superclass.setValue.call(this, dv);
42845 reset : function(){
42846 // overridden so that last data is reset..
42847 this.setValue(this.resetValue);
42848 this.originalValue = this.getValue();
42849 this.clearInvalid();
42850 this.lastData = false;
42852 this.view.clearSelections();
42856 findRecord : function(prop, value){
42858 if(this.store.getCount() > 0){
42859 this.store.each(function(r){
42860 if(r.data[prop] == value){
42870 getName: function()
42872 // returns hidden if it's set..
42873 if (!this.rendered) {return ''};
42874 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
42878 onViewMove : function(e, t){
42879 this.inKeyMode = false;
42883 onViewOver : function(e, t){
42884 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
42887 var item = this.view.findItemFromChild(t);
42889 var index = this.view.indexOf(item);
42890 this.select(index, false);
42895 onViewClick : function(doFocus)
42897 var index = this.view.getSelectedIndexes()[0];
42898 var r = this.store.getAt(index);
42900 this.onSelect(r, index);
42902 if(doFocus !== false && !this.blockFocus){
42908 restrictHeight : function(){
42909 this.innerList.dom.style.height = '';
42910 var inner = this.innerList.dom;
42911 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
42912 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
42913 this.list.beginUpdate();
42914 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
42915 this.list.alignTo(this.el, this.listAlign);
42916 this.list.endUpdate();
42920 onEmptyResults : function(){
42925 * Returns true if the dropdown list is expanded, else false.
42927 isExpanded : function(){
42928 return this.list.isVisible();
42932 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
42933 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
42934 * @param {String} value The data value of the item to select
42935 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
42936 * selected item if it is not currently in view (defaults to true)
42937 * @return {Boolean} True if the value matched an item in the list, else false
42939 selectByValue : function(v, scrollIntoView){
42940 if(v !== undefined && v !== null){
42941 var r = this.findRecord(this.valueField || this.displayField, v);
42943 this.select(this.store.indexOf(r), scrollIntoView);
42951 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
42952 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
42953 * @param {Number} index The zero-based index of the list item to select
42954 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
42955 * selected item if it is not currently in view (defaults to true)
42957 select : function(index, scrollIntoView){
42958 this.selectedIndex = index;
42959 this.view.select(index);
42960 if(scrollIntoView !== false){
42961 var el = this.view.getNode(index);
42963 this.innerList.scrollChildIntoView(el, false);
42969 selectNext : function(){
42970 var ct = this.store.getCount();
42972 if(this.selectedIndex == -1){
42974 }else if(this.selectedIndex < ct-1){
42975 this.select(this.selectedIndex+1);
42981 selectPrev : function(){
42982 var ct = this.store.getCount();
42984 if(this.selectedIndex == -1){
42986 }else if(this.selectedIndex != 0){
42987 this.select(this.selectedIndex-1);
42993 onKeyUp : function(e){
42994 if(this.editable !== false && !e.isSpecialKey()){
42995 this.lastKey = e.getKey();
42996 this.dqTask.delay(this.queryDelay);
43001 validateBlur : function(){
43002 return !this.list || !this.list.isVisible();
43006 initQuery : function(){
43007 this.doQuery(this.getRawValue());
43011 doForce : function(){
43012 if(this.el.dom.value.length > 0){
43013 this.el.dom.value =
43014 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
43020 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
43021 * query allowing the query action to be canceled if needed.
43022 * @param {String} query The SQL query to execute
43023 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
43024 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
43025 * saved in the current store (defaults to false)
43027 doQuery : function(q, forceAll){
43028 if(q === undefined || q === null){
43033 forceAll: forceAll,
43037 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
43041 forceAll = qe.forceAll;
43042 if(forceAll === true || (q.length >= this.minChars)){
43043 if(this.lastQuery != q || this.alwaysQuery){
43044 this.lastQuery = q;
43045 if(this.mode == 'local'){
43046 this.selectedIndex = -1;
43048 this.store.clearFilter();
43050 this.store.filter(this.displayField, q);
43054 this.store.baseParams[this.queryParam] = q;
43056 params: this.getParams(q)
43061 this.selectedIndex = -1;
43068 getParams : function(q){
43070 //p[this.queryParam] = q;
43073 p.limit = this.pageSize;
43079 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
43081 collapse : function(){
43082 if(!this.isExpanded()){
43086 Roo.get(document).un('mousedown', this.collapseIf, this);
43087 Roo.get(document).un('mousewheel', this.collapseIf, this);
43088 if (!this.editable) {
43089 Roo.get(document).un('keydown', this.listKeyPress, this);
43091 this.fireEvent('collapse', this);
43095 collapseIf : function(e){
43096 if(!e.within(this.wrap) && !e.within(this.list)){
43102 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
43104 expand : function(){
43105 if(this.isExpanded() || !this.hasFocus){
43108 this.list.alignTo(this.el, this.listAlign);
43110 Roo.get(document).on('mousedown', this.collapseIf, this);
43111 Roo.get(document).on('mousewheel', this.collapseIf, this);
43112 if (!this.editable) {
43113 Roo.get(document).on('keydown', this.listKeyPress, this);
43116 this.fireEvent('expand', this);
43120 // Implements the default empty TriggerField.onTriggerClick function
43121 onTriggerClick : function(){
43125 if(this.isExpanded()){
43127 if (!this.blockFocus) {
43132 this.hasFocus = true;
43133 if(this.triggerAction == 'all') {
43134 this.doQuery(this.allQuery, true);
43136 this.doQuery(this.getRawValue());
43138 if (!this.blockFocus) {
43143 listKeyPress : function(e)
43145 //Roo.log('listkeypress');
43146 // scroll to first matching element based on key pres..
43147 if (e.isSpecialKey()) {
43150 var k = String.fromCharCode(e.getKey()).toUpperCase();
43153 var csel = this.view.getSelectedNodes();
43154 var cselitem = false;
43156 var ix = this.view.indexOf(csel[0]);
43157 cselitem = this.store.getAt(ix);
43158 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
43164 this.store.each(function(v) {
43166 // start at existing selection.
43167 if (cselitem.id == v.id) {
43173 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
43174 match = this.store.indexOf(v);
43179 if (match === false) {
43180 return true; // no more action?
43183 this.view.select(match);
43184 var sn = Roo.get(this.view.getSelectedNodes()[0]);
43185 sn.scrollIntoView(sn.dom.parentNode, false);
43189 * @cfg {Boolean} grow
43193 * @cfg {Number} growMin
43197 * @cfg {Number} growMax
43205 * Copyright(c) 2010-2012, Roo J Solutions Limited
43212 * @class Roo.form.ComboBoxArray
43213 * @extends Roo.form.TextField
43214 * A facebook style adder... for lists of email / people / countries etc...
43215 * pick multiple items from a combo box, and shows each one.
43217 * Fred [x] Brian [x] [Pick another |v]
43220 * For this to work: it needs various extra information
43221 * - normal combo problay has
43223 * + displayField, valueField
43225 * For our purpose...
43228 * If we change from 'extends' to wrapping...
43235 * Create a new ComboBoxArray.
43236 * @param {Object} config Configuration options
43240 Roo.form.ComboBoxArray = function(config)
43244 * @event beforeremove
43245 * Fires before remove the value from the list
43246 * @param {Roo.form.ComboBoxArray} _self This combo box array
43247 * @param {Roo.form.ComboBoxArray.Item} item removed item
43249 'beforeremove' : true,
43252 * Fires when remove the value from the list
43253 * @param {Roo.form.ComboBoxArray} _self This combo box array
43254 * @param {Roo.form.ComboBoxArray.Item} item removed item
43261 Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
43263 this.items = new Roo.util.MixedCollection(false);
43265 // construct the child combo...
43275 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
43278 * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
43283 // behavies liek a hiddne field
43284 inputType: 'hidden',
43286 * @cfg {Number} width The width of the box that displays the selected element
43293 * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
43297 * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
43299 hiddenName : false,
43301 * @cfg {String} seperator The value seperator normally ','
43305 // private the array of items that are displayed..
43307 // private - the hidden field el.
43309 // private - the filed el..
43312 //validateValue : function() { return true; }, // all values are ok!
43313 //onAddClick: function() { },
43315 onRender : function(ct, position)
43318 // create the standard hidden element
43319 //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
43322 // give fake names to child combo;
43323 this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
43324 this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
43326 this.combo = Roo.factory(this.combo, Roo.form);
43327 this.combo.onRender(ct, position);
43328 if (typeof(this.combo.width) != 'undefined') {
43329 this.combo.onResize(this.combo.width,0);
43332 this.combo.initEvents();
43334 // assigned so form know we need to do this..
43335 this.store = this.combo.store;
43336 this.valueField = this.combo.valueField;
43337 this.displayField = this.combo.displayField ;
43340 this.combo.wrap.addClass('x-cbarray-grp');
43342 var cbwrap = this.combo.wrap.createChild(
43343 {tag: 'div', cls: 'x-cbarray-cb'},
43348 this.hiddenEl = this.combo.wrap.createChild({
43349 tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
43351 this.el = this.combo.wrap.createChild({
43352 tag: 'input', type:'hidden' , name: this.name, value : ''
43354 // this.el.dom.removeAttribute("name");
43357 this.outerWrap = this.combo.wrap;
43358 this.wrap = cbwrap;
43360 this.outerWrap.setWidth(this.width);
43361 this.outerWrap.dom.removeChild(this.el.dom);
43363 this.wrap.dom.appendChild(this.el.dom);
43364 this.outerWrap.dom.removeChild(this.combo.trigger.dom);
43365 this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
43367 this.combo.trigger.setStyle('position','relative');
43368 this.combo.trigger.setStyle('left', '0px');
43369 this.combo.trigger.setStyle('top', '2px');
43371 this.combo.el.setStyle('vertical-align', 'text-bottom');
43373 //this.trigger.setStyle('vertical-align', 'top');
43375 // this should use the code from combo really... on('add' ....)
43379 this.adder = this.outerWrap.createChild(
43380 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
43382 this.adder.on('click', function(e) {
43383 _t.fireEvent('adderclick', this, e);
43387 //this.adder.on('click', this.onAddClick, _t);
43390 this.combo.on('select', function(cb, rec, ix) {
43391 this.addItem(rec.data);
43394 cb.el.dom.value = '';
43395 //cb.lastData = rec.data;
43404 getName: function()
43406 // returns hidden if it's set..
43407 if (!this.rendered) {return ''};
43408 return this.hiddenName ? this.hiddenName : this.name;
43413 onResize: function(w, h){
43416 // not sure if this is needed..
43417 //this.combo.onResize(w,h);
43419 if(typeof w != 'number'){
43420 // we do not handle it!?!?
43423 var tw = this.combo.trigger.getWidth();
43424 tw += this.addicon ? this.addicon.getWidth() : 0;
43425 tw += this.editicon ? this.editicon.getWidth() : 0;
43427 this.combo.el.setWidth( this.combo.adjustWidth('input', x));
43429 this.combo.trigger.setStyle('left', '0px');
43431 if(this.list && this.listWidth === undefined){
43432 var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
43433 this.list.setWidth(lw);
43434 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
43441 addItem: function(rec)
43443 var valueField = this.combo.valueField;
43444 var displayField = this.combo.displayField;
43446 if (this.items.indexOfKey(rec[valueField]) > -1) {
43447 //console.log("GOT " + rec.data.id);
43451 var x = new Roo.form.ComboBoxArray.Item({
43452 //id : rec[this.idField],
43454 displayField : displayField ,
43455 tipField : displayField ,
43459 this.items.add(rec[valueField],x);
43460 // add it before the element..
43461 this.updateHiddenEl();
43462 x.render(this.outerWrap, this.wrap.dom);
43463 // add the image handler..
43466 updateHiddenEl : function()
43469 if (!this.hiddenEl) {
43473 var idField = this.combo.valueField;
43475 this.items.each(function(f) {
43476 ar.push(f.data[idField]);
43478 this.hiddenEl.dom.value = ar.join(this.seperator);
43484 this.items.clear();
43486 Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
43490 this.el.dom.value = '';
43491 if (this.hiddenEl) {
43492 this.hiddenEl.dom.value = '';
43496 getValue: function()
43498 return this.hiddenEl ? this.hiddenEl.dom.value : '';
43500 setValue: function(v) // not a valid action - must use addItems..
43505 if (this.store.isLocal && (typeof(v) == 'string')) {
43506 // then we can use the store to find the values..
43507 // comma seperated at present.. this needs to allow JSON based encoding..
43508 this.hiddenEl.value = v;
43510 Roo.each(v.split(this.seperator), function(k) {
43511 Roo.log("CHECK " + this.valueField + ',' + k);
43512 var li = this.store.query(this.valueField, k);
43517 add[this.valueField] = k;
43518 add[this.displayField] = li.item(0).data[this.displayField];
43524 if (typeof(v) == 'object' ) {
43525 // then let's assume it's an array of objects..
43526 Roo.each(v, function(l) {
43528 if (typeof(l) == 'string') {
43530 add[this.valueField] = l;
43531 add[this.displayField] = l
43540 setFromData: function(v)
43542 // this recieves an object, if setValues is called.
43544 this.el.dom.value = v[this.displayField];
43545 this.hiddenEl.dom.value = v[this.valueField];
43546 if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
43549 var kv = v[this.valueField];
43550 var dv = v[this.displayField];
43551 kv = typeof(kv) != 'string' ? '' : kv;
43552 dv = typeof(dv) != 'string' ? '' : dv;
43555 var keys = kv.split(this.seperator);
43556 var display = dv.split(this.seperator);
43557 for (var i = 0 ; i < keys.length; i++) {
43559 add[this.valueField] = keys[i];
43560 add[this.displayField] = display[i];
43568 * Validates the combox array value
43569 * @return {Boolean} True if the value is valid, else false
43571 validate : function(){
43572 if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
43573 this.clearInvalid();
43579 validateValue : function(value){
43580 return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
43588 isDirty : function() {
43589 if(this.disabled) {
43594 var d = Roo.decode(String(this.originalValue));
43596 return String(this.getValue()) !== String(this.originalValue);
43599 var originalValue = [];
43601 for (var i = 0; i < d.length; i++){
43602 originalValue.push(d[i][this.valueField]);
43605 return String(this.getValue()) !== String(originalValue.join(this.seperator));
43614 * @class Roo.form.ComboBoxArray.Item
43615 * @extends Roo.BoxComponent
43616 * A selected item in the list
43617 * Fred [x] Brian [x] [Pick another |v]
43620 * Create a new item.
43621 * @param {Object} config Configuration options
43624 Roo.form.ComboBoxArray.Item = function(config) {
43625 config.id = Roo.id();
43626 Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
43629 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
43632 displayField : false,
43636 defaultAutoCreate : {
43638 cls: 'x-cbarray-item',
43645 src : Roo.BLANK_IMAGE_URL ,
43653 onRender : function(ct, position)
43655 Roo.form.Field.superclass.onRender.call(this, ct, position);
43658 var cfg = this.getAutoCreate();
43659 this.el = ct.createChild(cfg, position);
43662 this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
43664 this.el.child('div').dom.innerHTML = this.cb.renderer ?
43665 this.cb.renderer(this.data) :
43666 String.format('{0}',this.data[this.displayField]);
43669 this.el.child('div').dom.setAttribute('qtip',
43670 String.format('{0}',this.data[this.tipField])
43673 this.el.child('img').on('click', this.remove, this);
43677 remove : function()
43679 if(this.cb.disabled){
43683 if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
43684 this.cb.items.remove(this);
43685 this.el.child('img').un('click', this.remove, this);
43687 this.cb.updateHiddenEl();
43689 this.cb.fireEvent('remove', this.cb, this);
43694 * RooJS Library 1.1.1
43695 * Copyright(c) 2008-2011 Alan Knowles
43702 * @class Roo.form.ComboNested
43703 * @extends Roo.form.ComboBox
43704 * A combobox for that allows selection of nested items in a list,
43719 * Create a new ComboNested
43720 * @param {Object} config Configuration options
43722 Roo.form.ComboNested = function(config){
43723 Roo.form.ComboCheck.superclass.constructor.call(this, config);
43724 // should verify some data...
43726 // hiddenName = required..
43727 // displayField = required
43728 // valudField == required
43729 var req= [ 'hiddenName', 'displayField', 'valueField' ];
43731 Roo.each(req, function(e) {
43732 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
43733 throw "Roo.form.ComboNested : missing value for: " + e;
43740 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
43743 * @config {Number} max Number of columns to show
43748 list : null, // the outermost div..
43749 innerLists : null, // the
43753 loadingChildren : false,
43755 onRender : function(ct, position)
43757 Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
43759 if(this.hiddenName){
43760 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
43762 this.hiddenField.value =
43763 this.hiddenValue !== undefined ? this.hiddenValue :
43764 this.value !== undefined ? this.value : '';
43766 // prevent input submission
43767 this.el.dom.removeAttribute('name');
43773 this.el.dom.setAttribute('autocomplete', 'off');
43776 var cls = 'x-combo-list';
43778 this.list = new Roo.Layer({
43779 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
43782 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
43783 this.list.setWidth(lw);
43784 this.list.swallowEvent('mousewheel');
43785 this.assetHeight = 0;
43788 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
43789 this.assetHeight += this.header.getHeight();
43791 this.innerLists = [];
43794 for (var i =0 ; i < this.maxColumns; i++) {
43795 this.onRenderList( cls, i);
43798 // always needs footer, as we are going to have an 'OK' button.
43799 this.footer = this.list.createChild({cls:cls+'-ft'});
43800 this.pageTb = new Roo.Toolbar(this.footer);
43805 handler: function()
43811 if ( this.allowBlank && !this.disableClear) {
43813 this.pageTb.add(new Roo.Toolbar.Fill(), {
43814 cls: 'x-btn-icon x-btn-clear',
43816 handler: function()
43819 _this.clearValue();
43820 _this.onSelect(false, -1);
43825 this.assetHeight += this.footer.getHeight();
43829 onRenderList : function ( cls, i)
43832 var lw = Math.floor(
43833 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
43836 this.list.setWidth(lw); // default to '1'
43838 var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
43839 //il.on('mouseover', this.onViewOver, this, { list: i });
43840 //il.on('mousemove', this.onViewMove, this, { list: i });
43842 il.setStyle({ 'overflow-x' : 'hidden'});
43845 this.tpl = new Roo.Template({
43846 html : '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
43847 isEmpty: function (value, allValues) {
43849 var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
43850 return dl ? 'has-children' : 'no-children'
43855 var store = this.store;
43857 store = new Roo.data.SimpleStore({
43858 //fields : this.store.reader.meta.fields,
43859 reader : this.store.reader,
43863 this.stores[i] = store;
43865 var view = this.views[i] = new Roo.View(
43871 selectedClass: this.selectedClass
43874 view.getEl().setWidth(lw);
43875 view.getEl().setStyle({
43876 position: i < 1 ? 'relative' : 'absolute',
43878 left: (i * lw ) + 'px',
43879 display : i > 0 ? 'none' : 'block'
43881 view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
43882 view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
43883 //view.on('click', this.onViewClick, this, { list : i });
43885 store.on('beforeload', this.onBeforeLoad, this);
43886 store.on('load', this.onLoad, this, { list : i});
43887 store.on('loadexception', this.onLoadException, this);
43889 // hide the other vies..
43895 restrictHeight : function()
43898 Roo.each(this.innerLists, function(il,i) {
43899 var el = this.views[i].getEl();
43900 el.dom.style.height = '';
43901 var inner = el.dom;
43902 var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
43903 // only adjust heights on other ones..
43904 mh = Math.max(h, mh);
43907 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
43908 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
43915 this.list.beginUpdate();
43916 this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
43917 this.list.alignTo(this.el, this.listAlign);
43918 this.list.endUpdate();
43923 // -- store handlers..
43925 onBeforeLoad : function()
43927 if(!this.hasFocus){
43930 this.innerLists[0].update(this.loadingText ?
43931 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
43932 this.restrictHeight();
43933 this.selectedIndex = -1;
43936 onLoad : function(a,b,c,d)
43938 if (!this.loadingChildren) {
43939 // then we are loading the top level. - hide the children
43940 for (var i = 1;i < this.views.length; i++) {
43941 this.views[i].getEl().setStyle({ display : 'none' });
43943 var lw = Math.floor(
43944 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
43947 this.list.setWidth(lw); // default to '1'
43951 if(!this.hasFocus){
43955 if(this.store.getCount() > 0) {
43957 this.restrictHeight();
43959 this.onEmptyResults();
43962 if (!this.loadingChildren) {
43963 this.selectActive();
43966 this.stores[1].loadData([]);
43967 this.stores[2].loadData([]);
43976 onLoadException : function()
43979 Roo.log(this.store.reader.jsonData);
43980 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
43981 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
43986 // no cleaning of leading spaces on blur here.
43987 cleanLeadingSpace : function(e) { },
43990 onSelectChange : function (view, sels, opts )
43992 var ix = view.getSelectedIndexes();
43994 if (opts.list > this.maxColumns - 2) {
43995 if (view.store.getCount()< 1) {
43996 this.views[opts.list ].getEl().setStyle({ display : 'none' });
44000 // used to clear ?? but if we are loading unselected
44001 this.setFromData(view.store.getAt(ix[0]).data);
44010 // this get's fired when trigger opens..
44011 // this.setFromData({});
44012 var str = this.stores[opts.list+1];
44013 str.data.clear(); // removeall wihtout the fire events..
44017 var rec = view.store.getAt(ix[0]);
44019 this.setFromData(rec.data);
44020 this.fireEvent('select', this, rec, ix[0]);
44022 var lw = Math.floor(
44024 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
44025 ) / this.maxColumns
44027 this.loadingChildren = true;
44028 this.stores[opts.list+1].loadDataFromChildren( rec );
44029 this.loadingChildren = false;
44030 var dl = this.stores[opts.list+1]. getTotalCount();
44032 this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
44034 this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
44035 for (var i = opts.list+2; i < this.views.length;i++) {
44036 this.views[i].getEl().setStyle({ display : 'none' });
44039 this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
44040 this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
44042 if (this.isLoading) {
44043 // this.selectActive(opts.list);
44051 onDoubleClick : function()
44053 this.collapse(); //??
44061 recordToStack : function(store, prop, value, stack)
44063 var cstore = new Roo.data.SimpleStore({
44064 //fields : this.store.reader.meta.fields, // we need array reader.. for
44065 reader : this.store.reader,
44069 var record = false;
44071 if(store.getCount() < 1){
44074 store.each(function(r){
44075 if(r.data[prop] == value){
44080 if (r.data.cn && r.data.cn.length) {
44081 cstore.loadDataFromChildren( r);
44082 var cret = _this.recordToStack(cstore, prop, value, stack);
44083 if (cret !== false) {
44092 if (record == false) {
44095 stack.unshift(srec);
44100 * find the stack of stores that match our value.
44105 selectActive : function ()
44107 // if store is not loaded, then we will need to wait for that to happen first.
44109 this.recordToStack(this.store, this.valueField, this.getValue(), stack);
44110 for (var i = 0; i < stack.length; i++ ) {
44111 this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
44123 * Ext JS Library 1.1.1
44124 * Copyright(c) 2006-2007, Ext JS, LLC.
44126 * Originally Released Under LGPL - original licence link has changed is not relivant.
44129 * <script type="text/javascript">
44132 * @class Roo.form.Checkbox
44133 * @extends Roo.form.Field
44134 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
44136 * Creates a new Checkbox
44137 * @param {Object} config Configuration options
44139 Roo.form.Checkbox = function(config){
44140 Roo.form.Checkbox.superclass.constructor.call(this, config);
44144 * Fires when the checkbox is checked or unchecked.
44145 * @param {Roo.form.Checkbox} this This checkbox
44146 * @param {Boolean} checked The new checked value
44152 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
44154 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
44156 focusClass : undefined,
44158 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
44160 fieldClass: "x-form-field",
44162 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
44166 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
44167 * {tag: "input", type: "checkbox", autocomplete: "off"})
44169 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
44171 * @cfg {String} boxLabel The text that appears beside the checkbox
44175 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
44179 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
44181 valueOff: '0', // value when not checked..
44183 actionMode : 'viewEl',
44186 itemCls : 'x-menu-check-item x-form-item',
44187 groupClass : 'x-menu-group-item',
44188 inputType : 'hidden',
44191 inSetChecked: false, // check that we are not calling self...
44193 inputElement: false, // real input element?
44194 basedOn: false, // ????
44196 isFormField: true, // not sure where this is needed!!!!
44198 onResize : function(){
44199 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
44200 if(!this.boxLabel){
44201 this.el.alignTo(this.wrap, 'c-c');
44205 initEvents : function(){
44206 Roo.form.Checkbox.superclass.initEvents.call(this);
44207 this.el.on("click", this.onClick, this);
44208 this.el.on("change", this.onClick, this);
44212 getResizeEl : function(){
44216 getPositionEl : function(){
44221 onRender : function(ct, position){
44222 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
44224 if(this.inputValue !== undefined){
44225 this.el.dom.value = this.inputValue;
44228 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
44229 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
44230 var viewEl = this.wrap.createChild({
44231 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
44232 this.viewEl = viewEl;
44233 this.wrap.on('click', this.onClick, this);
44235 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
44236 this.el.on('propertychange', this.setFromHidden, this); //ie
44241 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
44242 // viewEl.on('click', this.onClick, this);
44244 //if(this.checked){
44245 this.setChecked(this.checked);
44247 //this.checked = this.el.dom;
44253 initValue : Roo.emptyFn,
44256 * Returns the checked state of the checkbox.
44257 * @return {Boolean} True if checked, else false
44259 getValue : function(){
44261 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
44263 return this.valueOff;
44268 onClick : function(){
44269 if (this.disabled) {
44272 this.setChecked(!this.checked);
44274 //if(this.el.dom.checked != this.checked){
44275 // this.setValue(this.el.dom.checked);
44280 * Sets the checked state of the checkbox.
44281 * On is always based on a string comparison between inputValue and the param.
44282 * @param {Boolean/String} value - the value to set
44283 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
44285 setValue : function(v,suppressEvent){
44288 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
44289 //if(this.el && this.el.dom){
44290 // this.el.dom.checked = this.checked;
44291 // this.el.dom.defaultChecked = this.checked;
44293 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
44294 //this.fireEvent("check", this, this.checked);
44297 setChecked : function(state,suppressEvent)
44299 if (this.inSetChecked) {
44300 this.checked = state;
44306 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
44308 this.checked = state;
44309 if(suppressEvent !== true){
44310 this.fireEvent('check', this, state);
44312 this.inSetChecked = true;
44313 this.el.dom.value = state ? this.inputValue : this.valueOff;
44314 this.inSetChecked = false;
44317 // handle setting of hidden value by some other method!!?!?
44318 setFromHidden: function()
44323 //console.log("SET FROM HIDDEN");
44324 //alert('setFrom hidden');
44325 this.setValue(this.el.dom.value);
44328 onDestroy : function()
44331 Roo.get(this.viewEl).remove();
44334 Roo.form.Checkbox.superclass.onDestroy.call(this);
44337 setBoxLabel : function(str)
44339 this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
44344 * Ext JS Library 1.1.1
44345 * Copyright(c) 2006-2007, Ext JS, LLC.
44347 * Originally Released Under LGPL - original licence link has changed is not relivant.
44350 * <script type="text/javascript">
44354 * @class Roo.form.Radio
44355 * @extends Roo.form.Checkbox
44356 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
44357 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
44359 * Creates a new Radio
44360 * @param {Object} config Configuration options
44362 Roo.form.Radio = function(){
44363 Roo.form.Radio.superclass.constructor.apply(this, arguments);
44365 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
44366 inputType: 'radio',
44369 * If this radio is part of a group, it will return the selected value
44372 getGroupValue : function(){
44373 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
44377 onRender : function(ct, position){
44378 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
44380 if(this.inputValue !== undefined){
44381 this.el.dom.value = this.inputValue;
44384 this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
44385 //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
44386 //var viewEl = this.wrap.createChild({
44387 // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
44388 //this.viewEl = viewEl;
44389 //this.wrap.on('click', this.onClick, this);
44391 //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
44392 //this.el.on('propertychange', this.setFromHidden, this); //ie
44397 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
44398 // viewEl.on('click', this.onClick, this);
44401 this.el.dom.checked = 'checked' ;
44407 });//<script type="text/javascript">
44410 * Based Ext JS Library 1.1.1
44411 * Copyright(c) 2006-2007, Ext JS, LLC.
44417 * @class Roo.HtmlEditorCore
44418 * @extends Roo.Component
44419 * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
44421 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
44424 Roo.HtmlEditorCore = function(config){
44427 Roo.HtmlEditorCore.superclass.constructor.call(this, config);
44432 * @event initialize
44433 * Fires when the editor is fully initialized (including the iframe)
44434 * @param {Roo.HtmlEditorCore} this
44439 * Fires when the editor is first receives the focus. Any insertion must wait
44440 * until after this event.
44441 * @param {Roo.HtmlEditorCore} this
44445 * @event beforesync
44446 * Fires before the textarea is updated with content from the editor iframe. Return false
44447 * to cancel the sync.
44448 * @param {Roo.HtmlEditorCore} this
44449 * @param {String} html
44453 * @event beforepush
44454 * Fires before the iframe editor is updated with content from the textarea. Return false
44455 * to cancel the push.
44456 * @param {Roo.HtmlEditorCore} this
44457 * @param {String} html
44462 * Fires when the textarea is updated with content from the editor iframe.
44463 * @param {Roo.HtmlEditorCore} this
44464 * @param {String} html
44469 * Fires when the iframe editor is updated with content from the textarea.
44470 * @param {Roo.HtmlEditorCore} this
44471 * @param {String} html
44476 * @event editorevent
44477 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
44478 * @param {Roo.HtmlEditorCore} this
44484 // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
44486 // defaults : white / black...
44487 this.applyBlacklists();
44494 Roo.extend(Roo.HtmlEditorCore, Roo.Component, {
44498 * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field
44504 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
44509 * @cfg {Number} height (in pixels)
44513 * @cfg {Number} width (in pixels)
44518 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
44521 stylesheets: false,
44524 * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
44526 allowComments: false,
44530 // private properties
44531 validationEvent : false,
44533 initialized : false,
44535 sourceEditMode : false,
44536 onFocus : Roo.emptyFn,
44538 hideMode:'offsets',
44542 // blacklist + whitelisted elements..
44549 * Protected method that will not generally be called directly. It
44550 * is called when the editor initializes the iframe with HTML contents. Override this method if you
44551 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
44553 getDocMarkup : function(){
44557 // inherit styels from page...??
44558 if (this.stylesheets === false) {
44560 Roo.get(document.head).select('style').each(function(node) {
44561 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
44564 Roo.get(document.head).select('link').each(function(node) {
44565 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
44568 } else if (!this.stylesheets.length) {
44570 st = '<style type="text/css">' +
44571 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
44574 for (var i in this.stylesheets) {
44575 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
44580 st += '<style type="text/css">' +
44581 'IMG { cursor: pointer } ' +
44584 var cls = 'roo-htmleditor-body';
44586 if(this.bodyCls.length){
44587 cls += ' ' + this.bodyCls;
44590 return '<html><head>' + st +
44591 //<style type="text/css">' +
44592 //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
44594 ' </head><body contenteditable="true" data-enable-grammerly="true" class="' + cls + '"></body></html>';
44598 onRender : function(ct, position)
44601 //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
44602 this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
44605 this.el.dom.style.border = '0 none';
44606 this.el.dom.setAttribute('tabIndex', -1);
44607 this.el.addClass('x-hidden hide');
44611 if(Roo.isIE){ // fix IE 1px bogus margin
44612 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
44616 this.frameId = Roo.id();
44620 var iframe = this.owner.wrap.createChild({
44622 cls: 'form-control', // bootstrap..
44624 name: this.frameId,
44625 frameBorder : 'no',
44626 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
44631 this.iframe = iframe.dom;
44633 this.assignDocWin();
44635 this.doc.designMode = 'on';
44638 this.doc.write(this.getDocMarkup());
44642 var task = { // must defer to wait for browser to be ready
44644 //console.log("run task?" + this.doc.readyState);
44645 this.assignDocWin();
44646 if(this.doc.body || this.doc.readyState == 'complete'){
44648 this.doc.designMode="on";
44652 Roo.TaskMgr.stop(task);
44653 this.initEditor.defer(10, this);
44660 Roo.TaskMgr.start(task);
44665 onResize : function(w, h)
44667 Roo.log('resize: ' +w + ',' + h );
44668 //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
44672 if(typeof w == 'number'){
44674 this.iframe.style.width = w + 'px';
44676 if(typeof h == 'number'){
44678 this.iframe.style.height = h + 'px';
44680 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
44687 * Toggles the editor between standard and source edit mode.
44688 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
44690 toggleSourceEdit : function(sourceEditMode){
44692 this.sourceEditMode = sourceEditMode === true;
44694 if(this.sourceEditMode){
44696 Roo.get(this.iframe).addClass(['x-hidden','hide']); //FIXME - what's the BS styles for these
44699 Roo.get(this.iframe).removeClass(['x-hidden','hide']);
44700 //this.iframe.className = '';
44703 //this.setSize(this.owner.wrap.getSize());
44704 //this.fireEvent('editmodechange', this, this.sourceEditMode);
44711 * Protected method that will not generally be called directly. If you need/want
44712 * custom HTML cleanup, this is the method you should override.
44713 * @param {String} html The HTML to be cleaned
44714 * return {String} The cleaned HTML
44716 cleanHtml : function(html){
44717 html = String(html);
44718 if(html.length > 5){
44719 if(Roo.isSafari){ // strip safari nonsense
44720 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
44723 if(html == ' '){
44730 * HTML Editor -> Textarea
44731 * Protected method that will not generally be called directly. Syncs the contents
44732 * of the editor iframe with the textarea.
44734 syncValue : function(){
44735 if(this.initialized){
44736 var bd = (this.doc.body || this.doc.documentElement);
44737 //this.cleanUpPaste(); -- this is done else where and causes havoc..
44738 var html = bd.innerHTML;
44740 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
44741 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
44743 html = '<div style="'+m[0]+'">' + html + '</div>';
44746 html = this.cleanHtml(html);
44747 // fix up the special chars.. normaly like back quotes in word...
44748 // however we do not want to do this with chinese..
44749 html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
44751 var cc = match.charCodeAt();
44753 // Get the character value, handling surrogate pairs
44754 if (match.length == 2) {
44755 // It's a surrogate pair, calculate the Unicode code point
44756 var high = match.charCodeAt(0) - 0xD800;
44757 var low = match.charCodeAt(1) - 0xDC00;
44758 cc = (high * 0x400) + low + 0x10000;
44760 (cc >= 0x4E00 && cc < 0xA000 ) ||
44761 (cc >= 0x3400 && cc < 0x4E00 ) ||
44762 (cc >= 0xf900 && cc < 0xfb00 )
44767 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
44768 return "&#" + cc + ";";
44775 if(this.owner.fireEvent('beforesync', this, html) !== false){
44776 this.el.dom.value = html;
44777 this.owner.fireEvent('sync', this, html);
44783 * Protected method that will not generally be called directly. Pushes the value of the textarea
44784 * into the iframe editor.
44786 pushValue : function(){
44787 if(this.initialized){
44788 var v = this.el.dom.value.trim();
44790 // if(v.length < 1){
44794 if(this.owner.fireEvent('beforepush', this, v) !== false){
44795 var d = (this.doc.body || this.doc.documentElement);
44797 this.cleanUpPaste();
44798 this.el.dom.value = d.innerHTML;
44799 this.owner.fireEvent('push', this, v);
44805 deferFocus : function(){
44806 this.focus.defer(10, this);
44810 focus : function(){
44811 if(this.win && !this.sourceEditMode){
44818 assignDocWin: function()
44820 var iframe = this.iframe;
44823 this.doc = iframe.contentWindow.document;
44824 this.win = iframe.contentWindow;
44826 // if (!Roo.get(this.frameId)) {
44829 // this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
44830 // this.win = Roo.get(this.frameId).dom.contentWindow;
44832 if (!Roo.get(this.frameId) && !iframe.contentDocument) {
44836 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
44837 this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
44842 initEditor : function(){
44843 //console.log("INIT EDITOR");
44844 this.assignDocWin();
44848 this.doc.designMode="on";
44850 this.doc.write(this.getDocMarkup());
44853 var dbody = (this.doc.body || this.doc.documentElement);
44854 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
44855 // this copies styles from the containing element into thsi one..
44856 // not sure why we need all of this..
44857 //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
44859 //var ss = this.el.getStyles( 'background-image', 'background-repeat');
44860 //ss['background-attachment'] = 'fixed'; // w3c
44861 dbody.bgProperties = 'fixed'; // ie
44862 //Roo.DomHelper.applyStyles(dbody, ss);
44863 Roo.EventManager.on(this.doc, {
44864 //'mousedown': this.onEditorEvent,
44865 'mouseup': this.onEditorEvent,
44866 'dblclick': this.onEditorEvent,
44867 'click': this.onEditorEvent,
44868 'keyup': this.onEditorEvent,
44873 Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
44875 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
44876 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
44878 this.initialized = true;
44880 this.owner.fireEvent('initialize', this);
44885 onDestroy : function(){
44891 //for (var i =0; i < this.toolbars.length;i++) {
44892 // // fixme - ask toolbars for heights?
44893 // this.toolbars[i].onDestroy();
44896 //this.wrap.dom.innerHTML = '';
44897 //this.wrap.remove();
44902 onFirstFocus : function(){
44904 this.assignDocWin();
44907 this.activated = true;
44910 if(Roo.isGecko){ // prevent silly gecko errors
44912 var s = this.win.getSelection();
44913 if(!s.focusNode || s.focusNode.nodeType != 3){
44914 var r = s.getRangeAt(0);
44915 r.selectNodeContents((this.doc.body || this.doc.documentElement));
44920 this.execCmd('useCSS', true);
44921 this.execCmd('styleWithCSS', false);
44924 this.owner.fireEvent('activate', this);
44928 adjustFont: function(btn){
44929 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
44930 //if(Roo.isSafari){ // safari
44933 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
44934 if(Roo.isSafari){ // safari
44935 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
44936 v = (v < 10) ? 10 : v;
44937 v = (v > 48) ? 48 : v;
44938 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
44943 v = Math.max(1, v+adjust);
44945 this.execCmd('FontSize', v );
44948 onEditorEvent : function(e)
44950 this.owner.fireEvent('editorevent', this, e);
44951 // this.updateToolbar();
44952 this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
44955 insertTag : function(tg)
44957 // could be a bit smarter... -> wrap the current selected tRoo..
44958 if (tg.toLowerCase() == 'span' ||
44959 tg.toLowerCase() == 'code' ||
44960 tg.toLowerCase() == 'sup' ||
44961 tg.toLowerCase() == 'sub'
44964 range = this.createRange(this.getSelection());
44965 var wrappingNode = this.doc.createElement(tg.toLowerCase());
44966 wrappingNode.appendChild(range.extractContents());
44967 range.insertNode(wrappingNode);
44974 this.execCmd("formatblock", tg);
44978 insertText : function(txt)
44982 var range = this.createRange();
44983 range.deleteContents();
44984 //alert(Sender.getAttribute('label'));
44986 range.insertNode(this.doc.createTextNode(txt));
44992 * Executes a Midas editor command on the editor document and performs necessary focus and
44993 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
44994 * @param {String} cmd The Midas command
44995 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
44997 relayCmd : function(cmd, value){
44999 this.execCmd(cmd, value);
45000 this.owner.fireEvent('editorevent', this);
45001 //this.updateToolbar();
45002 this.owner.deferFocus();
45006 * Executes a Midas editor command directly on the editor document.
45007 * For visual commands, you should use {@link #relayCmd} instead.
45008 * <b>This should only be called after the editor is initialized.</b>
45009 * @param {String} cmd The Midas command
45010 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
45012 execCmd : function(cmd, value){
45013 this.doc.execCommand(cmd, false, value === undefined ? null : value);
45020 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
45022 * @param {String} text | dom node..
45024 insertAtCursor : function(text)
45027 if(!this.activated){
45033 var r = this.doc.selection.createRange();
45044 if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
45048 // from jquery ui (MIT licenced)
45050 var win = this.win;
45052 if (win.getSelection && win.getSelection().getRangeAt) {
45053 range = win.getSelection().getRangeAt(0);
45054 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
45055 range.insertNode(node);
45056 } else if (win.document.selection && win.document.selection.createRange) {
45057 // no firefox support
45058 var txt = typeof(text) == 'string' ? text : text.outerHTML;
45059 win.document.selection.createRange().pasteHTML(txt);
45061 // no firefox support
45062 var txt = typeof(text) == 'string' ? text : text.outerHTML;
45063 this.execCmd('InsertHTML', txt);
45072 mozKeyPress : function(e){
45074 var c = e.getCharCode(), cmd;
45077 c = String.fromCharCode(c).toLowerCase();
45091 this.cleanUpPaste.defer(100, this);
45099 e.preventDefault();
45107 fixKeys : function(){ // load time branching for fastest keydown performance
45109 return function(e){
45110 var k = e.getKey(), r;
45113 r = this.doc.selection.createRange();
45116 r.pasteHTML('    ');
45123 r = this.doc.selection.createRange();
45125 var target = r.parentElement();
45126 if(!target || target.tagName.toLowerCase() != 'li'){
45128 r.pasteHTML('<br />');
45134 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
45135 this.cleanUpPaste.defer(100, this);
45141 }else if(Roo.isOpera){
45142 return function(e){
45143 var k = e.getKey();
45147 this.execCmd('InsertHTML','    ');
45150 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
45151 this.cleanUpPaste.defer(100, this);
45156 }else if(Roo.isSafari){
45157 return function(e){
45158 var k = e.getKey();
45162 this.execCmd('InsertText','\t');
45166 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
45167 this.cleanUpPaste.defer(100, this);
45175 getAllAncestors: function()
45177 var p = this.getSelectedNode();
45180 a.push(p); // push blank onto stack..
45181 p = this.getParentElement();
45185 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
45189 a.push(this.doc.body);
45193 lastSelNode : false,
45196 getSelection : function()
45198 this.assignDocWin();
45199 return Roo.isIE ? this.doc.selection : this.win.getSelection();
45202 getSelectedNode: function()
45204 // this may only work on Gecko!!!
45206 // should we cache this!!!!
45211 var range = this.createRange(this.getSelection()).cloneRange();
45214 var parent = range.parentElement();
45216 var testRange = range.duplicate();
45217 testRange.moveToElementText(parent);
45218 if (testRange.inRange(range)) {
45221 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
45224 parent = parent.parentElement;
45229 // is ancestor a text element.
45230 var ac = range.commonAncestorContainer;
45231 if (ac.nodeType == 3) {
45232 ac = ac.parentNode;
45235 var ar = ac.childNodes;
45238 var other_nodes = [];
45239 var has_other_nodes = false;
45240 for (var i=0;i<ar.length;i++) {
45241 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
45244 // fullly contained node.
45246 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
45251 // probably selected..
45252 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
45253 other_nodes.push(ar[i]);
45257 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
45262 has_other_nodes = true;
45264 if (!nodes.length && other_nodes.length) {
45265 nodes= other_nodes;
45267 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
45273 createRange: function(sel)
45275 // this has strange effects when using with
45276 // top toolbar - not sure if it's a great idea.
45277 //this.editor.contentWindow.focus();
45278 if (typeof sel != "undefined") {
45280 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
45282 return this.doc.createRange();
45285 return this.doc.createRange();
45288 getParentElement: function()
45291 this.assignDocWin();
45292 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
45294 var range = this.createRange(sel);
45297 var p = range.commonAncestorContainer;
45298 while (p.nodeType == 3) { // text node
45309 * Range intersection.. the hard stuff...
45313 * [ -- selected range --- ]
45317 * if end is before start or hits it. fail.
45318 * if start is after end or hits it fail.
45320 * if either hits (but other is outside. - then it's not
45326 // @see http://www.thismuchiknow.co.uk/?p=64.
45327 rangeIntersectsNode : function(range, node)
45329 var nodeRange = node.ownerDocument.createRange();
45331 nodeRange.selectNode(node);
45333 nodeRange.selectNodeContents(node);
45336 var rangeStartRange = range.cloneRange();
45337 rangeStartRange.collapse(true);
45339 var rangeEndRange = range.cloneRange();
45340 rangeEndRange.collapse(false);
45342 var nodeStartRange = nodeRange.cloneRange();
45343 nodeStartRange.collapse(true);
45345 var nodeEndRange = nodeRange.cloneRange();
45346 nodeEndRange.collapse(false);
45348 return rangeStartRange.compareBoundaryPoints(
45349 Range.START_TO_START, nodeEndRange) == -1 &&
45350 rangeEndRange.compareBoundaryPoints(
45351 Range.START_TO_START, nodeStartRange) == 1;
45355 rangeCompareNode : function(range, node)
45357 var nodeRange = node.ownerDocument.createRange();
45359 nodeRange.selectNode(node);
45361 nodeRange.selectNodeContents(node);
45365 range.collapse(true);
45367 nodeRange.collapse(true);
45369 var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
45370 var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
45372 //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
45374 var nodeIsBefore = ss == 1;
45375 var nodeIsAfter = ee == -1;
45377 if (nodeIsBefore && nodeIsAfter) {
45380 if (!nodeIsBefore && nodeIsAfter) {
45381 return 1; //right trailed.
45384 if (nodeIsBefore && !nodeIsAfter) {
45385 return 2; // left trailed.
45391 // private? - in a new class?
45392 cleanUpPaste : function()
45394 // cleans up the whole document..
45395 Roo.log('cleanuppaste');
45397 this.cleanUpChildren(this.doc.body);
45398 var clean = this.cleanWordChars(this.doc.body.innerHTML);
45399 if (clean != this.doc.body.innerHTML) {
45400 this.doc.body.innerHTML = clean;
45405 cleanWordChars : function(input) {// change the chars to hex code
45406 var he = Roo.HtmlEditorCore;
45408 var output = input;
45409 Roo.each(he.swapCodes, function(sw) {
45410 var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
45412 output = output.replace(swapper, sw[1]);
45419 cleanUpChildren : function (n)
45421 if (!n.childNodes.length) {
45424 for (var i = n.childNodes.length-1; i > -1 ; i--) {
45425 this.cleanUpChild(n.childNodes[i]);
45432 cleanUpChild : function (node)
45435 //console.log(node);
45436 if (node.nodeName == "#text") {
45437 // clean up silly Windows -- stuff?
45440 if (node.nodeName == "#comment") {
45441 if (!this.allowComments) {
45442 node.parentNode.removeChild(node);
45444 // clean up silly Windows -- stuff?
45447 var lcname = node.tagName.toLowerCase();
45448 // we ignore whitelists... ?? = not really the way to go, but we probably have not got a full
45449 // whitelist of tags..
45451 if (this.black.indexOf(lcname) > -1 && this.clearUp ) {
45453 node.parentNode.removeChild(node);
45458 var remove_keep_children= Roo.HtmlEditorCore.remove.indexOf(node.tagName.toLowerCase()) > -1;
45460 // spans with no attributes - just remove them..
45461 if ((!node.attributes || !node.attributes.length) && lcname == 'span') {
45462 remove_keep_children = true;
45465 // remove <a name=....> as rendering on yahoo mailer is borked with this.
45466 // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
45468 //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
45469 // remove_keep_children = true;
45472 if (remove_keep_children) {
45473 this.cleanUpChildren(node);
45474 // inserts everything just before this node...
45475 while (node.childNodes.length) {
45476 var cn = node.childNodes[0];
45477 node.removeChild(cn);
45478 node.parentNode.insertBefore(cn, node);
45480 node.parentNode.removeChild(node);
45484 if (!node.attributes || !node.attributes.length) {
45489 this.cleanUpChildren(node);
45493 function cleanAttr(n,v)
45496 if (v.match(/^\./) || v.match(/^\//)) {
45499 if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/) || v.match(/^ftp:/)) {
45502 if (v.match(/^#/)) {
45505 if (v.match(/^\{/)) { // allow template editing.
45508 // Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
45509 node.removeAttribute(n);
45513 var cwhite = this.cwhite;
45514 var cblack = this.cblack;
45516 function cleanStyle(n,v)
45518 if (v.match(/expression/)) { //XSS?? should we even bother..
45519 node.removeAttribute(n);
45523 var parts = v.split(/;/);
45526 Roo.each(parts, function(p) {
45527 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
45531 var l = p.split(':').shift().replace(/\s+/g,'');
45532 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
45534 if ( cwhite.length && cblack.indexOf(l) > -1) {
45535 // Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
45536 //node.removeAttribute(n);
45540 // only allow 'c whitelisted system attributes'
45541 if ( cwhite.length && cwhite.indexOf(l) < 0) {
45542 // Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
45543 //node.removeAttribute(n);
45553 if (clean.length) {
45554 node.setAttribute(n, clean.join(';'));
45556 node.removeAttribute(n);
45562 for (var i = node.attributes.length-1; i > -1 ; i--) {
45563 var a = node.attributes[i];
45566 if (a.name.toLowerCase().substr(0,2)=='on') {
45567 node.removeAttribute(a.name);
45570 if (Roo.HtmlEditorCore.ablack.indexOf(a.name.toLowerCase()) > -1) {
45571 node.removeAttribute(a.name);
45574 if (Roo.HtmlEditorCore.aclean.indexOf(a.name.toLowerCase()) > -1) {
45575 cleanAttr(a.name,a.value); // fixme..
45578 if (a.name == 'style') {
45579 cleanStyle(a.name,a.value);
45582 /// clean up MS crap..
45583 // tecnically this should be a list of valid class'es..
45586 if (a.name == 'class') {
45587 if (a.value.match(/^Mso/)) {
45588 node.removeAttribute('class');
45591 if (a.value.match(/^body$/)) {
45592 node.removeAttribute('class');
45603 this.cleanUpChildren(node);
45609 * Clean up MS wordisms...
45611 cleanWord : function(node)
45614 this.cleanWord(this.doc.body);
45619 node.nodeName == 'SPAN' &&
45620 !node.hasAttributes() &&
45621 node.childNodes.length == 1 &&
45622 node.firstChild.nodeName == "#text"
45624 var textNode = node.firstChild;
45625 node.removeChild(textNode);
45626 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
45627 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
45629 node.parentNode.insertBefore(textNode, node);
45630 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
45631 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
45633 node.parentNode.removeChild(node);
45636 if (node.nodeName == "#text") {
45637 // clean up silly Windows -- stuff?
45640 if (node.nodeName == "#comment") {
45641 node.parentNode.removeChild(node);
45642 // clean up silly Windows -- stuff?
45646 if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
45647 node.parentNode.removeChild(node);
45650 //Roo.log(node.tagName);
45651 // remove - but keep children..
45652 if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
45653 //Roo.log('-- removed');
45654 while (node.childNodes.length) {
45655 var cn = node.childNodes[0];
45656 node.removeChild(cn);
45657 node.parentNode.insertBefore(cn, node);
45658 // move node to parent - and clean it..
45659 this.cleanWord(cn);
45661 node.parentNode.removeChild(node);
45662 /// no need to iterate chidlren = it's got none..
45663 //this.iterateChildren(node, this.cleanWord);
45667 if (node.className.length) {
45669 var cn = node.className.split(/\W+/);
45671 Roo.each(cn, function(cls) {
45672 if (cls.match(/Mso[a-zA-Z]+/)) {
45677 node.className = cna.length ? cna.join(' ') : '';
45679 node.removeAttribute("class");
45683 if (node.hasAttribute("lang")) {
45684 node.removeAttribute("lang");
45687 if (node.hasAttribute("style")) {
45689 var styles = node.getAttribute("style").split(";");
45691 Roo.each(styles, function(s) {
45692 if (!s.match(/:/)) {
45695 var kv = s.split(":");
45696 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
45699 // what ever is left... we allow.
45702 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
45703 if (!nstyle.length) {
45704 node.removeAttribute('style');
45707 this.iterateChildren(node, this.cleanWord);
45713 * iterateChildren of a Node, calling fn each time, using this as the scole..
45714 * @param {DomNode} node node to iterate children of.
45715 * @param {Function} fn method of this class to call on each item.
45717 iterateChildren : function(node, fn)
45719 if (!node.childNodes.length) {
45722 for (var i = node.childNodes.length-1; i > -1 ; i--) {
45723 fn.call(this, node.childNodes[i])
45729 * cleanTableWidths.
45731 * Quite often pasting from word etc.. results in tables with column and widths.
45732 * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
45735 cleanTableWidths : function(node)
45740 this.cleanTableWidths(this.doc.body);
45745 if (node.nodeName == "#text" || node.nodeName == "#comment") {
45748 Roo.log(node.tagName);
45749 if (!node.tagName.toLowerCase().match(/^(table|td|tr)$/)) {
45750 this.iterateChildren(node, this.cleanTableWidths);
45753 if (node.hasAttribute('width')) {
45754 node.removeAttribute('width');
45758 if (node.hasAttribute("style")) {
45761 var styles = node.getAttribute("style").split(";");
45763 Roo.each(styles, function(s) {
45764 if (!s.match(/:/)) {
45767 var kv = s.split(":");
45768 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
45771 // what ever is left... we allow.
45774 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
45775 if (!nstyle.length) {
45776 node.removeAttribute('style');
45780 this.iterateChildren(node, this.cleanTableWidths);
45788 domToHTML : function(currentElement, depth, nopadtext) {
45790 depth = depth || 0;
45791 nopadtext = nopadtext || false;
45793 if (!currentElement) {
45794 return this.domToHTML(this.doc.body);
45797 //Roo.log(currentElement);
45799 var allText = false;
45800 var nodeName = currentElement.nodeName;
45801 var tagName = Roo.util.Format.htmlEncode(currentElement.tagName);
45803 if (nodeName == '#text') {
45805 return nopadtext ? currentElement.nodeValue : currentElement.nodeValue.trim();
45810 if (nodeName != 'BODY') {
45813 // Prints the node tagName, such as <A>, <IMG>, etc
45816 for(i = 0; i < currentElement.attributes.length;i++) {
45818 var aname = currentElement.attributes.item(i).name;
45819 if (!currentElement.attributes.item(i).value.length) {
45822 attr.push(aname + '="' + Roo.util.Format.htmlEncode(currentElement.attributes.item(i).value) + '"' );
45825 ret = "<"+currentElement.tagName+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">";
45834 if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(tagName) > -1) {
45837 if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN'].indexOf(tagName) > -1) { // or code?
45842 // Traverse the tree
45844 var currentElementChild = currentElement.childNodes.item(i);
45845 var allText = true;
45846 var innerHTML = '';
45848 while (currentElementChild) {
45849 // Formatting code (indent the tree so it looks nice on the screen)
45850 var nopad = nopadtext;
45851 if (lastnode == 'SPAN') {
45855 if (currentElementChild.nodeName == '#text') {
45856 var toadd = Roo.util.Format.htmlEncode(currentElementChild.nodeValue);
45857 toadd = nopadtext ? toadd : toadd.trim();
45858 if (!nopad && toadd.length > 80) {
45859 innerHTML += "\n" + (new Array( depth + 1 )).join( " " );
45861 innerHTML += toadd;
45864 currentElementChild = currentElement.childNodes.item(i);
45870 innerHTML += nopad ? '' : "\n" + (new Array( depth + 1 )).join( " " );
45872 // Recursively traverse the tree structure of the child node
45873 innerHTML += this.domToHTML(currentElementChild, depth+1, nopadtext);
45874 lastnode = currentElementChild.nodeName;
45876 currentElementChild=currentElement.childNodes.item(i);
45882 // The remaining code is mostly for formatting the tree
45883 ret+= nopadtext ? '' : "\n" + (new Array( depth )).join( " " );
45888 ret+= "</"+tagName+">";
45894 applyBlacklists : function()
45896 var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white : [];
45897 var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black : [];
45901 Roo.each(Roo.HtmlEditorCore.white, function(tag) {
45902 if (b.indexOf(tag) > -1) {
45905 this.white.push(tag);
45909 Roo.each(w, function(tag) {
45910 if (b.indexOf(tag) > -1) {
45913 if (this.white.indexOf(tag) > -1) {
45916 this.white.push(tag);
45921 Roo.each(Roo.HtmlEditorCore.black, function(tag) {
45922 if (w.indexOf(tag) > -1) {
45925 this.black.push(tag);
45929 Roo.each(b, function(tag) {
45930 if (w.indexOf(tag) > -1) {
45933 if (this.black.indexOf(tag) > -1) {
45936 this.black.push(tag);
45941 w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite : [];
45942 b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack : [];
45946 Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
45947 if (b.indexOf(tag) > -1) {
45950 this.cwhite.push(tag);
45954 Roo.each(w, function(tag) {
45955 if (b.indexOf(tag) > -1) {
45958 if (this.cwhite.indexOf(tag) > -1) {
45961 this.cwhite.push(tag);
45966 Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
45967 if (w.indexOf(tag) > -1) {
45970 this.cblack.push(tag);
45974 Roo.each(b, function(tag) {
45975 if (w.indexOf(tag) > -1) {
45978 if (this.cblack.indexOf(tag) > -1) {
45981 this.cblack.push(tag);
45986 setStylesheets : function(stylesheets)
45988 if(typeof(stylesheets) == 'string'){
45989 Roo.get(this.iframe.contentDocument.head).createChild({
45991 rel : 'stylesheet',
46000 Roo.each(stylesheets, function(s) {
46005 Roo.get(_this.iframe.contentDocument.head).createChild({
46007 rel : 'stylesheet',
46016 removeStylesheets : function()
46020 Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
46025 setStyle : function(style)
46027 Roo.get(this.iframe.contentDocument.head).createChild({
46036 // hide stuff that is not compatible
46050 * @event specialkey
46054 * @cfg {String} fieldClass @hide
46057 * @cfg {String} focusClass @hide
46060 * @cfg {String} autoCreate @hide
46063 * @cfg {String} inputType @hide
46066 * @cfg {String} invalidClass @hide
46069 * @cfg {String} invalidText @hide
46072 * @cfg {String} msgFx @hide
46075 * @cfg {String} validateOnBlur @hide
46079 Roo.HtmlEditorCore.white = [
46080 'area', 'br', 'img', 'input', 'hr', 'wbr',
46082 'address', 'blockquote', 'center', 'dd', 'dir', 'div',
46083 'dl', 'dt', 'h1', 'h2', 'h3', 'h4',
46084 'h5', 'h6', 'hr', 'isindex', 'listing', 'marquee',
46085 'menu', 'multicol', 'ol', 'p', 'plaintext', 'pre',
46086 'table', 'ul', 'xmp',
46088 'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
46091 'dir', 'menu', 'ol', 'ul', 'dl',
46097 Roo.HtmlEditorCore.black = [
46098 // 'embed', 'object', // enable - backend responsiblity to clean thiese
46100 'base', 'basefont', 'bgsound', 'blink', 'body',
46101 'frame', 'frameset', 'head', 'html', 'ilayer',
46102 'iframe', 'layer', 'link', 'meta', 'object',
46103 'script', 'style' ,'title', 'xml' // clean later..
46105 Roo.HtmlEditorCore.clean = [
46106 'script', 'style', 'title', 'xml'
46108 Roo.HtmlEditorCore.remove = [
46113 Roo.HtmlEditorCore.ablack = [
46117 Roo.HtmlEditorCore.aclean = [
46118 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
46122 Roo.HtmlEditorCore.pwhite= [
46123 'http', 'https', 'mailto'
46126 // white listed style attributes.
46127 Roo.HtmlEditorCore.cwhite= [
46128 // 'text-align', /// default is to allow most things..
46134 // black listed style attributes.
46135 Roo.HtmlEditorCore.cblack= [
46136 // 'font-size' -- this can be set by the project
46140 Roo.HtmlEditorCore.swapCodes =[
46141 [ 8211, "–" ],
46142 [ 8212, "—" ],
46151 //<script type="text/javascript">
46154 * Ext JS Library 1.1.1
46155 * Copyright(c) 2006-2007, Ext JS, LLC.
46161 Roo.form.HtmlEditor = function(config){
46165 Roo.form.HtmlEditor.superclass.constructor.call(this, config);
46167 if (!this.toolbars) {
46168 this.toolbars = [];
46170 this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
46176 * @class Roo.form.HtmlEditor
46177 * @extends Roo.form.Field
46178 * Provides a lightweight HTML Editor component.
46180 * This has been tested on Fireforx / Chrome.. IE may not be so great..
46182 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
46183 * supported by this editor.</b><br/><br/>
46184 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
46185 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
46187 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
46189 * @cfg {Boolean} clearUp
46193 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
46198 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
46203 * @cfg {Number} height (in pixels)
46207 * @cfg {Number} width (in pixels)
46212 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
46215 stylesheets: false,
46219 * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
46224 * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
46230 * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
46235 * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
46240 * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
46242 allowComments: false,
46247 // private properties
46248 validationEvent : false,
46250 initialized : false,
46253 onFocus : Roo.emptyFn,
46255 hideMode:'offsets',
46257 actionMode : 'container', // defaults to hiding it...
46259 defaultAutoCreate : { // modified by initCompnoent..
46261 style:"width:500px;height:300px;",
46262 autocomplete: "new-password"
46266 initComponent : function(){
46269 * @event initialize
46270 * Fires when the editor is fully initialized (including the iframe)
46271 * @param {HtmlEditor} this
46276 * Fires when the editor is first receives the focus. Any insertion must wait
46277 * until after this event.
46278 * @param {HtmlEditor} this
46282 * @event beforesync
46283 * Fires before the textarea is updated with content from the editor iframe. Return false
46284 * to cancel the sync.
46285 * @param {HtmlEditor} this
46286 * @param {String} html
46290 * @event beforepush
46291 * Fires before the iframe editor is updated with content from the textarea. Return false
46292 * to cancel the push.
46293 * @param {HtmlEditor} this
46294 * @param {String} html
46299 * Fires when the textarea is updated with content from the editor iframe.
46300 * @param {HtmlEditor} this
46301 * @param {String} html
46306 * Fires when the iframe editor is updated with content from the textarea.
46307 * @param {HtmlEditor} this
46308 * @param {String} html
46312 * @event editmodechange
46313 * Fires when the editor switches edit modes
46314 * @param {HtmlEditor} this
46315 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
46317 editmodechange: true,
46319 * @event editorevent
46320 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
46321 * @param {HtmlEditor} this
46325 * @event firstfocus
46326 * Fires when on first focus - needed by toolbars..
46327 * @param {HtmlEditor} this
46332 * Auto save the htmlEditor value as a file into Events
46333 * @param {HtmlEditor} this
46337 * @event savedpreview
46338 * preview the saved version of htmlEditor
46339 * @param {HtmlEditor} this
46341 savedpreview: true,
46344 * @event stylesheetsclick
46345 * Fires when press the Sytlesheets button
46346 * @param {Roo.HtmlEditorCore} this
46348 stylesheetsclick: true
46350 this.defaultAutoCreate = {
46352 style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
46353 autocomplete: "new-password"
46358 * Protected method that will not generally be called directly. It
46359 * is called when the editor creates its toolbar. Override this method if you need to
46360 * add custom toolbar buttons.
46361 * @param {HtmlEditor} editor
46363 createToolbar : function(editor){
46364 Roo.log("create toolbars");
46365 if (!editor.toolbars || !editor.toolbars.length) {
46366 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
46369 for (var i =0 ; i < editor.toolbars.length;i++) {
46370 editor.toolbars[i] = Roo.factory(
46371 typeof(editor.toolbars[i]) == 'string' ?
46372 { xtype: editor.toolbars[i]} : editor.toolbars[i],
46373 Roo.form.HtmlEditor);
46374 editor.toolbars[i].init(editor);
46382 onRender : function(ct, position)
46385 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
46387 this.wrap = this.el.wrap({
46388 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
46391 this.editorcore.onRender(ct, position);
46393 if (this.resizable) {
46394 this.resizeEl = new Roo.Resizable(this.wrap, {
46398 minHeight : this.height,
46399 height: this.height,
46400 handles : this.resizable,
46403 resize : function(r, w, h) {
46404 _t.onResize(w,h); // -something
46410 this.createToolbar(this);
46414 this.setSize(this.wrap.getSize());
46416 if (this.resizeEl) {
46417 this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
46418 // should trigger onReize..
46421 this.keyNav = new Roo.KeyNav(this.el, {
46423 "tab" : function(e){
46424 e.preventDefault();
46426 var value = this.getValue();
46428 var start = this.el.dom.selectionStart;
46429 var end = this.el.dom.selectionEnd;
46433 this.setValue(value.substring(0, start) + "\t" + value.substring(end));
46434 this.el.dom.setSelectionRange(end + 1, end + 1);
46438 var f = value.substring(0, start).split("\t");
46440 if(f.pop().length != 0){
46444 this.setValue(f.join("\t") + value.substring(end));
46445 this.el.dom.setSelectionRange(start - 1, start - 1);
46449 "home" : function(e){
46450 e.preventDefault();
46452 var curr = this.el.dom.selectionStart;
46453 var lines = this.getValue().split("\n");
46460 this.el.dom.setSelectionRange(0, 0);
46466 for (var i = 0; i < lines.length;i++) {
46467 pos += lines[i].length;
46477 pos -= lines[i].length;
46483 this.el.dom.setSelectionRange(pos, pos);
46487 this.el.dom.selectionStart = pos;
46488 this.el.dom.selectionEnd = curr;
46491 "end" : function(e){
46492 e.preventDefault();
46494 var curr = this.el.dom.selectionStart;
46495 var lines = this.getValue().split("\n");
46502 this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
46508 for (var i = 0; i < lines.length;i++) {
46510 pos += lines[i].length;
46524 this.el.dom.setSelectionRange(pos, pos);
46528 this.el.dom.selectionStart = curr;
46529 this.el.dom.selectionEnd = pos;
46534 doRelay : function(foo, bar, hname){
46535 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
46541 // if(this.autosave && this.w){
46542 // this.autoSaveFn = setInterval(this.autosave, 1000);
46547 onResize : function(w, h)
46549 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
46554 if(typeof w == 'number'){
46555 var aw = w - this.wrap.getFrameWidth('lr');
46556 this.el.setWidth(this.adjustWidth('textarea', aw));
46559 if(typeof h == 'number'){
46561 for (var i =0; i < this.toolbars.length;i++) {
46562 // fixme - ask toolbars for heights?
46563 tbh += this.toolbars[i].tb.el.getHeight();
46564 if (this.toolbars[i].footer) {
46565 tbh += this.toolbars[i].footer.el.getHeight();
46572 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
46573 ah -= 5; // knock a few pixes off for look..
46575 this.el.setHeight(this.adjustWidth('textarea', ah));
46579 Roo.log('onResize:' + [w,h,ew,eh].join(',') );
46580 this.editorcore.onResize(ew,eh);
46585 * Toggles the editor between standard and source edit mode.
46586 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
46588 toggleSourceEdit : function(sourceEditMode)
46590 this.editorcore.toggleSourceEdit(sourceEditMode);
46592 if(this.editorcore.sourceEditMode){
46593 Roo.log('editor - showing textarea');
46596 // Roo.log(this.syncValue());
46597 this.editorcore.syncValue();
46598 this.el.removeClass('x-hidden');
46599 this.el.dom.removeAttribute('tabIndex');
46602 for (var i = 0; i < this.toolbars.length; i++) {
46603 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
46604 this.toolbars[i].tb.hide();
46605 this.toolbars[i].footer.hide();
46610 Roo.log('editor - hiding textarea');
46612 // Roo.log(this.pushValue());
46613 this.editorcore.pushValue();
46615 this.el.addClass('x-hidden');
46616 this.el.dom.setAttribute('tabIndex', -1);
46618 for (var i = 0; i < this.toolbars.length; i++) {
46619 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
46620 this.toolbars[i].tb.show();
46621 this.toolbars[i].footer.show();
46625 //this.deferFocus();
46628 this.setSize(this.wrap.getSize());
46629 this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
46631 this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
46634 // private (for BoxComponent)
46635 adjustSize : Roo.BoxComponent.prototype.adjustSize,
46637 // private (for BoxComponent)
46638 getResizeEl : function(){
46642 // private (for BoxComponent)
46643 getPositionEl : function(){
46648 initEvents : function(){
46649 this.originalValue = this.getValue();
46653 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
46656 markInvalid : Roo.emptyFn,
46658 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
46661 clearInvalid : Roo.emptyFn,
46663 setValue : function(v){
46664 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
46665 this.editorcore.pushValue();
46670 deferFocus : function(){
46671 this.focus.defer(10, this);
46675 focus : function(){
46676 this.editorcore.focus();
46682 onDestroy : function(){
46688 for (var i =0; i < this.toolbars.length;i++) {
46689 // fixme - ask toolbars for heights?
46690 this.toolbars[i].onDestroy();
46693 this.wrap.dom.innerHTML = '';
46694 this.wrap.remove();
46699 onFirstFocus : function(){
46700 //Roo.log("onFirstFocus");
46701 this.editorcore.onFirstFocus();
46702 for (var i =0; i < this.toolbars.length;i++) {
46703 this.toolbars[i].onFirstFocus();
46709 syncValue : function()
46711 this.editorcore.syncValue();
46714 pushValue : function()
46716 this.editorcore.pushValue();
46719 setStylesheets : function(stylesheets)
46721 this.editorcore.setStylesheets(stylesheets);
46724 removeStylesheets : function()
46726 this.editorcore.removeStylesheets();
46730 // hide stuff that is not compatible
46744 * @event specialkey
46748 * @cfg {String} fieldClass @hide
46751 * @cfg {String} focusClass @hide
46754 * @cfg {String} autoCreate @hide
46757 * @cfg {String} inputType @hide
46760 * @cfg {String} invalidClass @hide
46763 * @cfg {String} invalidText @hide
46766 * @cfg {String} msgFx @hide
46769 * @cfg {String} validateOnBlur @hide
46773 // <script type="text/javascript">
46776 * Ext JS Library 1.1.1
46777 * Copyright(c) 2006-2007, Ext JS, LLC.
46783 * @class Roo.form.HtmlEditorToolbar1
46788 new Roo.form.HtmlEditor({
46791 new Roo.form.HtmlEditorToolbar1({
46792 disable : { fonts: 1 , format: 1, ..., ... , ...],
46798 * @cfg {Object} disable List of elements to disable..
46799 * @cfg {Array} btns List of additional buttons.
46803 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
46806 Roo.form.HtmlEditor.ToolbarStandard = function(config)
46809 Roo.apply(this, config);
46811 // default disabled, based on 'good practice'..
46812 this.disable = this.disable || {};
46813 Roo.applyIf(this.disable, {
46816 specialElements : true
46820 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
46821 // dont call parent... till later.
46824 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype, {
46831 editorcore : false,
46833 * @cfg {Object} disable List of toolbar elements to disable
46840 * @cfg {String} createLinkText The default text for the create link prompt
46842 createLinkText : 'Please enter the URL for the link:',
46844 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
46846 defaultLinkValue : 'http:/'+'/',
46850 * @cfg {Array} fontFamilies An array of available font families
46868 // "á" , ?? a acute?
46873 "°" // , // degrees
46875 // "é" , // e ecute
46876 // "ú" , // u ecute?
46879 specialElements : [
46881 text: "Insert Table",
46884 ihtml : '<table><tr><td>Cell</td></tr></table>'
46888 text: "Insert Image",
46891 ihtml : '<img src="about:blank"/>'
46900 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
46901 "input:submit", "input:button", "select", "textarea", "label" ],
46904 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
46906 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
46915 * @cfg {String} defaultFont default font to use.
46917 defaultFont: 'tahoma',
46919 fontSelect : false,
46922 formatCombo : false,
46924 init : function(editor)
46926 this.editor = editor;
46927 this.editorcore = editor.editorcore ? editor.editorcore : editor;
46928 var editorcore = this.editorcore;
46932 var fid = editorcore.frameId;
46934 function btn(id, toggle, handler){
46935 var xid = fid + '-'+ id ;
46939 cls : 'x-btn-icon x-edit-'+id,
46940 enableToggle:toggle !== false,
46941 scope: _t, // was editor...
46942 handler:handler||_t.relayBtnCmd,
46943 clickEvent:'mousedown',
46944 tooltip: etb.buttonTips[id] || undefined, ///tips ???
46951 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
46953 // stop form submits
46954 tb.el.on('click', function(e){
46955 e.preventDefault(); // what does this do?
46958 if(!this.disable.font) { // && !Roo.isSafari){
46959 /* why no safari for fonts
46960 editor.fontSelect = tb.el.createChild({
46963 cls:'x-font-select',
46964 html: this.createFontOptions()
46967 editor.fontSelect.on('change', function(){
46968 var font = editor.fontSelect.dom.value;
46969 editor.relayCmd('fontname', font);
46970 editor.deferFocus();
46974 editor.fontSelect.dom,
46980 if(!this.disable.formats){
46981 this.formatCombo = new Roo.form.ComboBox({
46982 store: new Roo.data.SimpleStore({
46985 data : this.formats // from states.js
46989 //autoCreate : {tag: "div", size: "20"},
46990 displayField:'tag',
46994 triggerAction: 'all',
46995 emptyText:'Add tag',
46996 selectOnFocus:true,
46999 'select': function(c, r, i) {
47000 editorcore.insertTag(r.get('tag'));
47006 tb.addField(this.formatCombo);
47010 if(!this.disable.format){
47015 btn('strikethrough')
47018 if(!this.disable.fontSize){
47023 btn('increasefontsize', false, editorcore.adjustFont),
47024 btn('decreasefontsize', false, editorcore.adjustFont)
47029 if(!this.disable.colors){
47032 id:editorcore.frameId +'-forecolor',
47033 cls:'x-btn-icon x-edit-forecolor',
47034 clickEvent:'mousedown',
47035 tooltip: this.buttonTips['forecolor'] || undefined,
47037 menu : new Roo.menu.ColorMenu({
47038 allowReselect: true,
47039 focus: Roo.emptyFn,
47042 selectHandler: function(cp, color){
47043 editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
47044 editor.deferFocus();
47047 clickEvent:'mousedown'
47050 id:editorcore.frameId +'backcolor',
47051 cls:'x-btn-icon x-edit-backcolor',
47052 clickEvent:'mousedown',
47053 tooltip: this.buttonTips['backcolor'] || undefined,
47055 menu : new Roo.menu.ColorMenu({
47056 focus: Roo.emptyFn,
47059 allowReselect: true,
47060 selectHandler: function(cp, color){
47062 editorcore.execCmd('useCSS', false);
47063 editorcore.execCmd('hilitecolor', color);
47064 editorcore.execCmd('useCSS', true);
47065 editor.deferFocus();
47067 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
47068 Roo.isSafari || Roo.isIE ? '#'+color : color);
47069 editor.deferFocus();
47073 clickEvent:'mousedown'
47078 // now add all the items...
47081 if(!this.disable.alignments){
47084 btn('justifyleft'),
47085 btn('justifycenter'),
47086 btn('justifyright')
47090 //if(!Roo.isSafari){
47091 if(!this.disable.links){
47094 btn('createlink', false, this.createLink) /// MOVE TO HERE?!!?!?!?!
47098 if(!this.disable.lists){
47101 btn('insertorderedlist'),
47102 btn('insertunorderedlist')
47105 if(!this.disable.sourceEdit){
47108 btn('sourceedit', true, function(btn){
47109 this.toggleSourceEdit(btn.pressed);
47116 // special menu.. - needs to be tidied up..
47117 if (!this.disable.special) {
47120 cls: 'x-edit-none',
47126 for (var i =0; i < this.specialChars.length; i++) {
47127 smenu.menu.items.push({
47129 html: this.specialChars[i],
47130 handler: function(a,b) {
47131 editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
47132 //editor.insertAtCursor(a.html);
47146 if (!this.disable.cleanStyles) {
47148 cls: 'x-btn-icon x-btn-clear',
47154 for (var i =0; i < this.cleanStyles.length; i++) {
47155 cmenu.menu.items.push({
47156 actiontype : this.cleanStyles[i],
47157 html: 'Remove ' + this.cleanStyles[i],
47158 handler: function(a,b) {
47161 var c = Roo.get(editorcore.doc.body);
47162 c.select('[style]').each(function(s) {
47163 s.dom.style.removeProperty(a.actiontype);
47165 editorcore.syncValue();
47170 cmenu.menu.items.push({
47171 actiontype : 'tablewidths',
47172 html: 'Remove Table Widths',
47173 handler: function(a,b) {
47174 editorcore.cleanTableWidths();
47175 editorcore.syncValue();
47179 cmenu.menu.items.push({
47180 actiontype : 'word',
47181 html: 'Remove MS Word Formating',
47182 handler: function(a,b) {
47183 editorcore.cleanWord();
47184 editorcore.syncValue();
47189 cmenu.menu.items.push({
47190 actiontype : 'all',
47191 html: 'Remove All Styles',
47192 handler: function(a,b) {
47194 var c = Roo.get(editorcore.doc.body);
47195 c.select('[style]').each(function(s) {
47196 s.dom.removeAttribute('style');
47198 editorcore.syncValue();
47203 cmenu.menu.items.push({
47204 actiontype : 'all',
47205 html: 'Remove All CSS Classes',
47206 handler: function(a,b) {
47208 var c = Roo.get(editorcore.doc.body);
47209 c.select('[class]').each(function(s) {
47210 s.dom.removeAttribute('class');
47212 editorcore.cleanWord();
47213 editorcore.syncValue();
47218 cmenu.menu.items.push({
47219 actiontype : 'tidy',
47220 html: 'Tidy HTML Source',
47221 handler: function(a,b) {
47222 editorcore.doc.body.innerHTML = editorcore.domToHTML();
47223 editorcore.syncValue();
47232 if (!this.disable.specialElements) {
47235 cls: 'x-edit-none',
47240 for (var i =0; i < this.specialElements.length; i++) {
47241 semenu.menu.items.push(
47243 handler: function(a,b) {
47244 editor.insertAtCursor(this.ihtml);
47246 }, this.specialElements[i])
47258 for(var i =0; i< this.btns.length;i++) {
47259 var b = Roo.factory(this.btns[i],Roo.form);
47260 b.cls = 'x-edit-none';
47262 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
47263 b.cls += ' x-init-enable';
47266 b.scope = editorcore;
47274 // disable everything...
47276 this.tb.items.each(function(item){
47279 item.id != editorcore.frameId+ '-sourceedit' &&
47280 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
47286 this.rendered = true;
47288 // the all the btns;
47289 editor.on('editorevent', this.updateToolbar, this);
47290 // other toolbars need to implement this..
47291 //editor.on('editmodechange', this.updateToolbar, this);
47295 relayBtnCmd : function(btn) {
47296 this.editorcore.relayCmd(btn.cmd);
47298 // private used internally
47299 createLink : function(){
47300 Roo.log("create link?");
47301 var url = prompt(this.createLinkText, this.defaultLinkValue);
47302 if(url && url != 'http:/'+'/'){
47303 this.editorcore.relayCmd('createlink', url);
47309 * Protected method that will not generally be called directly. It triggers
47310 * a toolbar update by reading the markup state of the current selection in the editor.
47312 updateToolbar: function(){
47314 if(!this.editorcore.activated){
47315 this.editor.onFirstFocus();
47319 var btns = this.tb.items.map,
47320 doc = this.editorcore.doc,
47321 frameId = this.editorcore.frameId;
47323 if(!this.disable.font && !Roo.isSafari){
47325 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
47326 if(name != this.fontSelect.dom.value){
47327 this.fontSelect.dom.value = name;
47331 if(!this.disable.format){
47332 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
47333 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
47334 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
47335 btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
47337 if(!this.disable.alignments){
47338 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
47339 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
47340 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
47342 if(!Roo.isSafari && !this.disable.lists){
47343 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
47344 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
47347 var ans = this.editorcore.getAllAncestors();
47348 if (this.formatCombo) {
47351 var store = this.formatCombo.store;
47352 this.formatCombo.setValue("");
47353 for (var i =0; i < ans.length;i++) {
47354 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
47356 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
47364 // hides menus... - so this cant be on a menu...
47365 Roo.menu.MenuMgr.hideAll();
47367 //this.editorsyncValue();
47371 createFontOptions : function(){
47372 var buf = [], fs = this.fontFamilies, ff, lc;
47376 for(var i = 0, len = fs.length; i< len; i++){
47378 lc = ff.toLowerCase();
47380 '<option value="',lc,'" style="font-family:',ff,';"',
47381 (this.defaultFont == lc ? ' selected="true">' : '>'),
47386 return buf.join('');
47389 toggleSourceEdit : function(sourceEditMode){
47391 Roo.log("toolbar toogle");
47392 if(sourceEditMode === undefined){
47393 sourceEditMode = !this.sourceEditMode;
47395 this.sourceEditMode = sourceEditMode === true;
47396 var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
47397 // just toggle the button?
47398 if(btn.pressed !== this.sourceEditMode){
47399 btn.toggle(this.sourceEditMode);
47403 if(sourceEditMode){
47404 Roo.log("disabling buttons");
47405 this.tb.items.each(function(item){
47406 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
47412 Roo.log("enabling buttons");
47413 if(this.editorcore.initialized){
47414 this.tb.items.each(function(item){
47420 Roo.log("calling toggole on editor");
47421 // tell the editor that it's been pressed..
47422 this.editor.toggleSourceEdit(sourceEditMode);
47426 * Object collection of toolbar tooltips for the buttons in the editor. The key
47427 * is the command id associated with that button and the value is a valid QuickTips object.
47432 title: 'Bold (Ctrl+B)',
47433 text: 'Make the selected text bold.',
47434 cls: 'x-html-editor-tip'
47437 title: 'Italic (Ctrl+I)',
47438 text: 'Make the selected text italic.',
47439 cls: 'x-html-editor-tip'
47447 title: 'Bold (Ctrl+B)',
47448 text: 'Make the selected text bold.',
47449 cls: 'x-html-editor-tip'
47452 title: 'Italic (Ctrl+I)',
47453 text: 'Make the selected text italic.',
47454 cls: 'x-html-editor-tip'
47457 title: 'Underline (Ctrl+U)',
47458 text: 'Underline the selected text.',
47459 cls: 'x-html-editor-tip'
47462 title: 'Strikethrough',
47463 text: 'Strikethrough the selected text.',
47464 cls: 'x-html-editor-tip'
47466 increasefontsize : {
47467 title: 'Grow Text',
47468 text: 'Increase the font size.',
47469 cls: 'x-html-editor-tip'
47471 decreasefontsize : {
47472 title: 'Shrink Text',
47473 text: 'Decrease the font size.',
47474 cls: 'x-html-editor-tip'
47477 title: 'Text Highlight Color',
47478 text: 'Change the background color of the selected text.',
47479 cls: 'x-html-editor-tip'
47482 title: 'Font Color',
47483 text: 'Change the color of the selected text.',
47484 cls: 'x-html-editor-tip'
47487 title: 'Align Text Left',
47488 text: 'Align text to the left.',
47489 cls: 'x-html-editor-tip'
47492 title: 'Center Text',
47493 text: 'Center text in the editor.',
47494 cls: 'x-html-editor-tip'
47497 title: 'Align Text Right',
47498 text: 'Align text to the right.',
47499 cls: 'x-html-editor-tip'
47501 insertunorderedlist : {
47502 title: 'Bullet List',
47503 text: 'Start a bulleted list.',
47504 cls: 'x-html-editor-tip'
47506 insertorderedlist : {
47507 title: 'Numbered List',
47508 text: 'Start a numbered list.',
47509 cls: 'x-html-editor-tip'
47512 title: 'Hyperlink',
47513 text: 'Make the selected text a hyperlink.',
47514 cls: 'x-html-editor-tip'
47517 title: 'Source Edit',
47518 text: 'Switch to source editing mode.',
47519 cls: 'x-html-editor-tip'
47523 onDestroy : function(){
47526 this.tb.items.each(function(item){
47528 item.menu.removeAll();
47530 item.menu.el.destroy();
47538 onFirstFocus: function() {
47539 this.tb.items.each(function(item){
47548 // <script type="text/javascript">
47551 * Ext JS Library 1.1.1
47552 * Copyright(c) 2006-2007, Ext JS, LLC.
47559 * @class Roo.form.HtmlEditor.ToolbarContext
47564 new Roo.form.HtmlEditor({
47567 { xtype: 'ToolbarStandard', styles : {} }
47568 { xtype: 'ToolbarContext', disable : {} }
47574 * @config : {Object} disable List of elements to disable.. (not done yet.)
47575 * @config : {Object} styles Map of styles available.
47579 Roo.form.HtmlEditor.ToolbarContext = function(config)
47582 Roo.apply(this, config);
47583 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
47584 // dont call parent... till later.
47585 this.styles = this.styles || {};
47590 Roo.form.HtmlEditor.ToolbarContext.types = {
47602 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
47668 opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
47673 opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
47683 style : 'fontFamily',
47684 displayField: 'display',
47685 optname : 'font-family',
47734 // should we really allow this??
47735 // should this just be
47746 style : 'fontFamily',
47747 displayField: 'display',
47748 optname : 'font-family',
47755 style : 'fontFamily',
47756 displayField: 'display',
47757 optname : 'font-family',
47764 style : 'fontFamily',
47765 displayField: 'display',
47766 optname : 'font-family',
47777 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
47778 Roo.form.HtmlEditor.ToolbarContext.stores = false;
47780 Roo.form.HtmlEditor.ToolbarContext.options = {
47782 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
47783 [ 'Courier New', 'Courier New'],
47784 [ 'Tahoma', 'Tahoma'],
47785 [ 'Times New Roman,serif', 'Times'],
47786 [ 'Verdana','Verdana' ]
47790 // fixme - these need to be configurable..
47793 //Roo.form.HtmlEditor.ToolbarContext.types
47796 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
47803 editorcore : false,
47805 * @cfg {Object} disable List of toolbar elements to disable
47810 * @cfg {Object} styles List of styles
47811 * eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] }
47813 * These must be defined in the page, so they get rendered correctly..
47824 init : function(editor)
47826 this.editor = editor;
47827 this.editorcore = editor.editorcore ? editor.editorcore : editor;
47828 var editorcore = this.editorcore;
47830 var fid = editorcore.frameId;
47832 function btn(id, toggle, handler){
47833 var xid = fid + '-'+ id ;
47837 cls : 'x-btn-icon x-edit-'+id,
47838 enableToggle:toggle !== false,
47839 scope: editorcore, // was editor...
47840 handler:handler||editorcore.relayBtnCmd,
47841 clickEvent:'mousedown',
47842 tooltip: etb.buttonTips[id] || undefined, ///tips ???
47846 // create a new element.
47847 var wdiv = editor.wrap.createChild({
47849 }, editor.wrap.dom.firstChild.nextSibling, true);
47851 // can we do this more than once??
47853 // stop form submits
47856 // disable everything...
47857 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
47858 this.toolbars = {};
47860 for (var i in ty) {
47862 this.toolbars[i] = this.buildToolbar(ty[i],i);
47864 this.tb = this.toolbars.BODY;
47866 this.buildFooter();
47867 this.footer.show();
47868 editor.on('hide', function( ) { this.footer.hide() }, this);
47869 editor.on('show', function( ) { this.footer.show() }, this);
47872 this.rendered = true;
47874 // the all the btns;
47875 editor.on('editorevent', this.updateToolbar, this);
47876 // other toolbars need to implement this..
47877 //editor.on('editmodechange', this.updateToolbar, this);
47883 * Protected method that will not generally be called directly. It triggers
47884 * a toolbar update by reading the markup state of the current selection in the editor.
47886 * Note you can force an update by calling on('editorevent', scope, false)
47888 updateToolbar: function(editor,ev,sel){
47891 // capture mouse up - this is handy for selecting images..
47892 // perhaps should go somewhere else...
47893 if(!this.editorcore.activated){
47894 this.editor.onFirstFocus();
47900 // http://developer.yahoo.com/yui/docs/simple-editor.js.html
47901 // selectNode - might want to handle IE?
47903 (ev.type == 'mouseup' || ev.type == 'click' ) &&
47904 ev.target && ev.target.tagName == 'IMG') {
47905 // they have click on an image...
47906 // let's see if we can change the selection...
47909 var nodeRange = sel.ownerDocument.createRange();
47911 nodeRange.selectNode(sel);
47913 nodeRange.selectNodeContents(sel);
47915 //nodeRange.collapse(true);
47916 var s = this.editorcore.win.getSelection();
47917 s.removeAllRanges();
47918 s.addRange(nodeRange);
47922 var updateFooter = sel ? false : true;
47925 var ans = this.editorcore.getAllAncestors();
47928 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
47931 sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editorcore.doc.body;
47932 sel = sel ? sel : this.editorcore.doc.body;
47933 sel = sel.tagName.length ? sel : this.editorcore.doc.body;
47936 // pick a menu that exists..
47937 var tn = sel.tagName.toUpperCase();
47938 //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
47940 tn = sel.tagName.toUpperCase();
47942 var lastSel = this.tb.selectedNode;
47944 this.tb.selectedNode = sel;
47946 // if current menu does not match..
47948 if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode) || ev === false) {
47951 ///console.log("show: " + tn);
47952 this.tb = typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
47955 this.tb.items.first().el.innerHTML = tn + ': ';
47958 // update attributes
47959 if (this.tb.fields) {
47960 this.tb.fields.each(function(e) {
47962 e.setValue(sel.style[e.stylename]);
47965 e.setValue(sel.getAttribute(e.attrname));
47969 var hasStyles = false;
47970 for(var i in this.styles) {
47977 var st = this.tb.fields.item(0);
47979 st.store.removeAll();
47982 var cn = sel.className.split(/\s+/);
47985 if (this.styles['*']) {
47987 Roo.each(this.styles['*'], function(v) {
47988 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
47991 if (this.styles[tn]) {
47992 Roo.each(this.styles[tn], function(v) {
47993 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
47997 st.store.loadData(avs);
48001 // flag our selected Node.
48002 this.tb.selectedNode = sel;
48005 Roo.menu.MenuMgr.hideAll();
48009 if (!updateFooter) {
48010 //this.footDisp.dom.innerHTML = '';
48013 // update the footer
48017 this.footerEls = ans.reverse();
48018 Roo.each(this.footerEls, function(a,i) {
48019 if (!a) { return; }
48020 html += html.length ? ' > ' : '';
48022 html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
48027 var sz = this.footDisp.up('td').getSize();
48028 this.footDisp.dom.style.width = (sz.width -10) + 'px';
48029 this.footDisp.dom.style.marginLeft = '5px';
48031 this.footDisp.dom.style.overflow = 'hidden';
48033 this.footDisp.dom.innerHTML = html;
48035 //this.editorsyncValue();
48042 onDestroy : function(){
48045 this.tb.items.each(function(item){
48047 item.menu.removeAll();
48049 item.menu.el.destroy();
48057 onFirstFocus: function() {
48058 // need to do this for all the toolbars..
48059 this.tb.items.each(function(item){
48063 buildToolbar: function(tlist, nm)
48065 var editor = this.editor;
48066 var editorcore = this.editorcore;
48067 // create a new element.
48068 var wdiv = editor.wrap.createChild({
48070 }, editor.wrap.dom.firstChild.nextSibling, true);
48073 var tb = new Roo.Toolbar(wdiv);
48076 tb.add(nm+ ": ");
48079 for(var i in this.styles) {
48084 if (styles && styles.length) {
48086 // this needs a multi-select checkbox...
48087 tb.addField( new Roo.form.ComboBox({
48088 store: new Roo.data.SimpleStore({
48090 fields: ['val', 'selected'],
48093 name : '-roo-edit-className',
48094 attrname : 'className',
48095 displayField: 'val',
48099 triggerAction: 'all',
48100 emptyText:'Select Style',
48101 selectOnFocus:true,
48104 'select': function(c, r, i) {
48105 // initial support only for on class per el..
48106 tb.selectedNode.className = r ? r.get('val') : '';
48107 editorcore.syncValue();
48114 var tbc = Roo.form.HtmlEditor.ToolbarContext;
48115 var tbops = tbc.options;
48117 for (var i in tlist) {
48119 var item = tlist[i];
48120 tb.add(item.title + ": ");
48123 //optname == used so you can configure the options available..
48124 var opts = item.opts ? item.opts : false;
48125 if (item.optname) {
48126 opts = tbops[item.optname];
48131 // opts == pulldown..
48132 tb.addField( new Roo.form.ComboBox({
48133 store: typeof(tbc.stores[i]) != 'undefined' ? Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
48135 fields: ['val', 'display'],
48138 name : '-roo-edit-' + i,
48140 stylename : item.style ? item.style : false,
48141 displayField: item.displayField ? item.displayField : 'val',
48142 valueField : 'val',
48144 mode: typeof(tbc.stores[i]) != 'undefined' ? 'remote' : 'local',
48146 triggerAction: 'all',
48147 emptyText:'Select',
48148 selectOnFocus:true,
48149 width: item.width ? item.width : 130,
48151 'select': function(c, r, i) {
48153 tb.selectedNode.style[c.stylename] = r.get('val');
48156 tb.selectedNode.setAttribute(c.attrname, r.get('val'));
48165 tb.addField( new Roo.form.TextField({
48168 //allowBlank:false,
48173 tb.addField( new Roo.form.TextField({
48174 name: '-roo-edit-' + i,
48181 'change' : function(f, nv, ov) {
48182 tb.selectedNode.setAttribute(f.attrname, nv);
48183 editorcore.syncValue();
48196 text: 'Stylesheets',
48199 click : function ()
48201 _this.editor.fireEvent('stylesheetsclick', _this.editor);
48209 text: 'Remove Tag',
48212 click : function ()
48215 // undo does not work.
48217 var sn = tb.selectedNode;
48219 var pn = sn.parentNode;
48221 var stn = sn.childNodes[0];
48222 var en = sn.childNodes[sn.childNodes.length - 1 ];
48223 while (sn.childNodes.length) {
48224 var node = sn.childNodes[0];
48225 sn.removeChild(node);
48227 pn.insertBefore(node, sn);
48230 pn.removeChild(sn);
48231 var range = editorcore.createRange();
48233 range.setStart(stn,0);
48234 range.setEnd(en,0); //????
48235 //range.selectNode(sel);
48238 var selection = editorcore.getSelection();
48239 selection.removeAllRanges();
48240 selection.addRange(range);
48244 //_this.updateToolbar(null, null, pn);
48245 _this.updateToolbar(null, null, null);
48246 _this.footDisp.dom.innerHTML = '';
48256 tb.el.on('click', function(e){
48257 e.preventDefault(); // what does this do?
48259 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
48262 // dont need to disable them... as they will get hidden
48267 buildFooter : function()
48270 var fel = this.editor.wrap.createChild();
48271 this.footer = new Roo.Toolbar(fel);
48272 // toolbar has scrolly on left / right?
48273 var footDisp= new Roo.Toolbar.Fill();
48279 handler : function() {
48280 _t.footDisp.scrollTo('left',0,true)
48284 this.footer.add( footDisp );
48289 handler : function() {
48291 _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
48295 var fel = Roo.get(footDisp.el);
48296 fel.addClass('x-editor-context');
48297 this.footDispWrap = fel;
48298 this.footDispWrap.overflow = 'hidden';
48300 this.footDisp = fel.createChild();
48301 this.footDispWrap.on('click', this.onContextClick, this)
48305 onContextClick : function (ev,dom)
48307 ev.preventDefault();
48308 var cn = dom.className;
48310 if (!cn.match(/x-ed-loc-/)) {
48313 var n = cn.split('-').pop();
48314 var ans = this.footerEls;
48318 var range = this.editorcore.createRange();
48320 range.selectNodeContents(sel);
48321 //range.selectNode(sel);
48324 var selection = this.editorcore.getSelection();
48325 selection.removeAllRanges();
48326 selection.addRange(range);
48330 this.updateToolbar(null, null, sel);
48347 * Ext JS Library 1.1.1
48348 * Copyright(c) 2006-2007, Ext JS, LLC.
48350 * Originally Released Under LGPL - original licence link has changed is not relivant.
48353 * <script type="text/javascript">
48357 * @class Roo.form.BasicForm
48358 * @extends Roo.util.Observable
48359 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
48361 * @param {String/HTMLElement/Roo.Element} el The form element or its id
48362 * @param {Object} config Configuration options
48364 Roo.form.BasicForm = function(el, config){
48365 this.allItems = [];
48366 this.childForms = [];
48367 Roo.apply(this, config);
48369 * The Roo.form.Field items in this form.
48370 * @type MixedCollection
48374 this.items = new Roo.util.MixedCollection(false, function(o){
48375 return o.id || (o.id = Roo.id());
48379 * @event beforeaction
48380 * Fires before any action is performed. Return false to cancel the action.
48381 * @param {Form} this
48382 * @param {Action} action The action to be performed
48384 beforeaction: true,
48386 * @event actionfailed
48387 * Fires when an action fails.
48388 * @param {Form} this
48389 * @param {Action} action The action that failed
48391 actionfailed : true,
48393 * @event actioncomplete
48394 * Fires when an action is completed.
48395 * @param {Form} this
48396 * @param {Action} action The action that completed
48398 actioncomplete : true
48403 Roo.form.BasicForm.superclass.constructor.call(this);
48405 Roo.form.BasicForm.popover.apply();
48408 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
48410 * @cfg {String} method
48411 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
48414 * @cfg {DataReader} reader
48415 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
48416 * This is optional as there is built-in support for processing JSON.
48419 * @cfg {DataReader} errorReader
48420 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
48421 * This is completely optional as there is built-in support for processing JSON.
48424 * @cfg {String} url
48425 * The URL to use for form actions if one isn't supplied in the action options.
48428 * @cfg {Boolean} fileUpload
48429 * Set to true if this form is a file upload.
48433 * @cfg {Object} baseParams
48434 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
48439 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
48444 activeAction : null,
48447 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
48448 * or setValues() data instead of when the form was first created.
48450 trackResetOnLoad : false,
48454 * childForms - used for multi-tab forms
48457 childForms : false,
48460 * allItems - full list of fields.
48466 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
48467 * element by passing it or its id or mask the form itself by passing in true.
48470 waitMsgTarget : false,
48475 disableMask : false,
48478 * @cfg {Boolean} errorMask (true|false) default false
48483 * @cfg {Number} maskOffset Default 100
48488 initEl : function(el){
48489 this.el = Roo.get(el);
48490 this.id = this.el.id || Roo.id();
48491 this.el.on('submit', this.onSubmit, this);
48492 this.el.addClass('x-form');
48496 onSubmit : function(e){
48501 * Returns true if client-side validation on the form is successful.
48504 isValid : function(){
48506 var target = false;
48507 this.items.each(function(f){
48514 if(!target && f.el.isVisible(true)){
48519 if(this.errorMask && !valid){
48520 Roo.form.BasicForm.popover.mask(this, target);
48526 * Returns array of invalid form fields.
48530 invalidFields : function()
48533 this.items.each(function(f){
48546 * DEPRICATED Returns true if any fields in this form have changed since their original load.
48549 isDirty : function(){
48551 this.items.each(function(f){
48561 * Returns true if any fields in this form have changed since their original load. (New version)
48565 hasChanged : function()
48568 this.items.each(function(f){
48569 if(f.hasChanged()){
48578 * Resets all hasChanged to 'false' -
48579 * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
48580 * So hasChanged storage is only to be used for this purpose
48583 resetHasChanged : function()
48585 this.items.each(function(f){
48586 f.resetHasChanged();
48593 * Performs a predefined action (submit or load) or custom actions you define on this form.
48594 * @param {String} actionName The name of the action type
48595 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
48596 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
48597 * accept other config options):
48599 Property Type Description
48600 ---------------- --------------- ----------------------------------------------------------------------------------
48601 url String The url for the action (defaults to the form's url)
48602 method String The form method to use (defaults to the form's method, or POST if not defined)
48603 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
48604 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
48605 validate the form on the client (defaults to false)
48607 * @return {BasicForm} this
48609 doAction : function(action, options){
48610 if(typeof action == 'string'){
48611 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
48613 if(this.fireEvent('beforeaction', this, action) !== false){
48614 this.beforeAction(action);
48615 action.run.defer(100, action);
48621 * Shortcut to do a submit action.
48622 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
48623 * @return {BasicForm} this
48625 submit : function(options){
48626 this.doAction('submit', options);
48631 * Shortcut to do a load action.
48632 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
48633 * @return {BasicForm} this
48635 load : function(options){
48636 this.doAction('load', options);
48641 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
48642 * @param {Record} record The record to edit
48643 * @return {BasicForm} this
48645 updateRecord : function(record){
48646 record.beginEdit();
48647 var fs = record.fields;
48648 fs.each(function(f){
48649 var field = this.findField(f.name);
48651 record.set(f.name, field.getValue());
48659 * Loads an Roo.data.Record into this form.
48660 * @param {Record} record The record to load
48661 * @return {BasicForm} this
48663 loadRecord : function(record){
48664 this.setValues(record.data);
48669 beforeAction : function(action){
48670 var o = action.options;
48672 if(!this.disableMask) {
48673 if(this.waitMsgTarget === true){
48674 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
48675 }else if(this.waitMsgTarget){
48676 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
48677 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
48679 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
48687 afterAction : function(action, success){
48688 this.activeAction = null;
48689 var o = action.options;
48691 if(!this.disableMask) {
48692 if(this.waitMsgTarget === true){
48694 }else if(this.waitMsgTarget){
48695 this.waitMsgTarget.unmask();
48697 Roo.MessageBox.updateProgress(1);
48698 Roo.MessageBox.hide();
48706 Roo.callback(o.success, o.scope, [this, action]);
48707 this.fireEvent('actioncomplete', this, action);
48711 // failure condition..
48712 // we have a scenario where updates need confirming.
48713 // eg. if a locking scenario exists..
48714 // we look for { errors : { needs_confirm : true }} in the response.
48716 (typeof(action.result) != 'undefined') &&
48717 (typeof(action.result.errors) != 'undefined') &&
48718 (typeof(action.result.errors.needs_confirm) != 'undefined')
48721 Roo.MessageBox.confirm(
48722 "Change requires confirmation",
48723 action.result.errorMsg,
48728 _t.doAction('submit', { params : { _submit_confirmed : 1 } } );
48738 Roo.callback(o.failure, o.scope, [this, action]);
48739 // show an error message if no failed handler is set..
48740 if (!this.hasListener('actionfailed')) {
48741 Roo.MessageBox.alert("Error",
48742 (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
48743 action.result.errorMsg :
48744 "Saving Failed, please check your entries or try again"
48748 this.fireEvent('actionfailed', this, action);
48754 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
48755 * @param {String} id The value to search for
48758 findField : function(id){
48759 var field = this.items.get(id);
48761 this.items.each(function(f){
48762 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
48768 return field || null;
48772 * Add a secondary form to this one,
48773 * Used to provide tabbed forms. One form is primary, with hidden values
48774 * which mirror the elements from the other forms.
48776 * @param {Roo.form.Form} form to add.
48779 addForm : function(form)
48782 if (this.childForms.indexOf(form) > -1) {
48786 this.childForms.push(form);
48788 Roo.each(form.allItems, function (fe) {
48790 n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
48791 if (this.findField(n)) { // already added..
48794 var add = new Roo.form.Hidden({
48797 add.render(this.el);
48804 * Mark fields in this form invalid in bulk.
48805 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
48806 * @return {BasicForm} this
48808 markInvalid : function(errors){
48809 if(errors instanceof Array){
48810 for(var i = 0, len = errors.length; i < len; i++){
48811 var fieldError = errors[i];
48812 var f = this.findField(fieldError.id);
48814 f.markInvalid(fieldError.msg);
48820 if(typeof errors[id] != 'function' && (field = this.findField(id))){
48821 field.markInvalid(errors[id]);
48825 Roo.each(this.childForms || [], function (f) {
48826 f.markInvalid(errors);
48833 * Set values for fields in this form in bulk.
48834 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
48835 * @return {BasicForm} this
48837 setValues : function(values){
48838 if(values instanceof Array){ // array of objects
48839 for(var i = 0, len = values.length; i < len; i++){
48841 var f = this.findField(v.id);
48843 f.setValue(v.value);
48844 if(this.trackResetOnLoad){
48845 f.originalValue = f.getValue();
48849 }else{ // object hash
48852 if(typeof values[id] != 'function' && (field = this.findField(id))){
48854 if (field.setFromData &&
48855 field.valueField &&
48856 field.displayField &&
48857 // combos' with local stores can
48858 // be queried via setValue()
48859 // to set their value..
48860 (field.store && !field.store.isLocal)
48864 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
48865 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
48866 field.setFromData(sd);
48869 field.setValue(values[id]);
48873 if(this.trackResetOnLoad){
48874 field.originalValue = field.getValue();
48879 this.resetHasChanged();
48882 Roo.each(this.childForms || [], function (f) {
48883 f.setValues(values);
48884 f.resetHasChanged();
48891 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
48892 * they are returned as an array.
48893 * @param {Boolean} asString
48896 getValues : function(asString){
48897 if (this.childForms) {
48898 // copy values from the child forms
48899 Roo.each(this.childForms, function (f) {
48900 this.setValues(f.getValues());
48905 if (typeof(FormData) != 'undefined' && asString !== true) {
48906 // this relies on a 'recent' version of chrome apparently...
48908 var fd = (new FormData(this.el.dom)).entries();
48910 var ent = fd.next();
48911 while (!ent.done) {
48912 ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
48923 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
48924 if(asString === true){
48927 return Roo.urlDecode(fs);
48931 * Returns the fields in this form as an object with key/value pairs.
48932 * This differs from getValues as it calls getValue on each child item, rather than using dom data.
48935 getFieldValues : function(with_hidden)
48937 if (this.childForms) {
48938 // copy values from the child forms
48939 // should this call getFieldValues - probably not as we do not currently copy
48940 // hidden fields when we generate..
48941 Roo.each(this.childForms, function (f) {
48942 this.setValues(f.getValues());
48947 this.items.each(function(f){
48948 if (!f.getName()) {
48951 var v = f.getValue();
48952 if (f.inputType =='radio') {
48953 if (typeof(ret[f.getName()]) == 'undefined') {
48954 ret[f.getName()] = ''; // empty..
48957 if (!f.el.dom.checked) {
48961 v = f.el.dom.value;
48965 // not sure if this supported any more..
48966 if ((typeof(v) == 'object') && f.getRawValue) {
48967 v = f.getRawValue() ; // dates..
48969 // combo boxes where name != hiddenName...
48970 if (f.name != f.getName()) {
48971 ret[f.name] = f.getRawValue();
48973 ret[f.getName()] = v;
48980 * Clears all invalid messages in this form.
48981 * @return {BasicForm} this
48983 clearInvalid : function(){
48984 this.items.each(function(f){
48988 Roo.each(this.childForms || [], function (f) {
48997 * Resets this form.
48998 * @return {BasicForm} this
49000 reset : function(){
49001 this.items.each(function(f){
49005 Roo.each(this.childForms || [], function (f) {
49008 this.resetHasChanged();
49014 * Add Roo.form components to this form.
49015 * @param {Field} field1
49016 * @param {Field} field2 (optional)
49017 * @param {Field} etc (optional)
49018 * @return {BasicForm} this
49021 this.items.addAll(Array.prototype.slice.call(arguments, 0));
49027 * Removes a field from the items collection (does NOT remove its markup).
49028 * @param {Field} field
49029 * @return {BasicForm} this
49031 remove : function(field){
49032 this.items.remove(field);
49037 * Looks at the fields in this form, checks them for an id attribute,
49038 * and calls applyTo on the existing dom element with that id.
49039 * @return {BasicForm} this
49041 render : function(){
49042 this.items.each(function(f){
49043 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
49051 * Calls {@link Ext#apply} for all fields in this form with the passed object.
49052 * @param {Object} values
49053 * @return {BasicForm} this
49055 applyToFields : function(o){
49056 this.items.each(function(f){
49063 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
49064 * @param {Object} values
49065 * @return {BasicForm} this
49067 applyIfToFields : function(o){
49068 this.items.each(function(f){
49076 Roo.BasicForm = Roo.form.BasicForm;
49078 Roo.apply(Roo.form.BasicForm, {
49092 intervalID : false,
49098 if(this.isApplied){
49103 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
49104 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
49105 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
49106 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
49109 this.maskEl.top.enableDisplayMode("block");
49110 this.maskEl.left.enableDisplayMode("block");
49111 this.maskEl.bottom.enableDisplayMode("block");
49112 this.maskEl.right.enableDisplayMode("block");
49114 Roo.get(document.body).on('click', function(){
49118 Roo.get(document.body).on('touchstart', function(){
49122 this.isApplied = true
49125 mask : function(form, target)
49129 this.target = target;
49131 if(!this.form.errorMask || !target.el){
49135 var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
49137 var ot = this.target.el.calcOffsetsTo(scrollable);
49139 var scrollTo = ot[1] - this.form.maskOffset;
49141 scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
49143 scrollable.scrollTo('top', scrollTo);
49145 var el = this.target.wrap || this.target.el;
49147 var box = el.getBox();
49149 this.maskEl.top.setStyle('position', 'absolute');
49150 this.maskEl.top.setStyle('z-index', 10000);
49151 this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
49152 this.maskEl.top.setLeft(0);
49153 this.maskEl.top.setTop(0);
49154 this.maskEl.top.show();
49156 this.maskEl.left.setStyle('position', 'absolute');
49157 this.maskEl.left.setStyle('z-index', 10000);
49158 this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
49159 this.maskEl.left.setLeft(0);
49160 this.maskEl.left.setTop(box.y - this.padding);
49161 this.maskEl.left.show();
49163 this.maskEl.bottom.setStyle('position', 'absolute');
49164 this.maskEl.bottom.setStyle('z-index', 10000);
49165 this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
49166 this.maskEl.bottom.setLeft(0);
49167 this.maskEl.bottom.setTop(box.bottom + this.padding);
49168 this.maskEl.bottom.show();
49170 this.maskEl.right.setStyle('position', 'absolute');
49171 this.maskEl.right.setStyle('z-index', 10000);
49172 this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
49173 this.maskEl.right.setLeft(box.right + this.padding);
49174 this.maskEl.right.setTop(box.y - this.padding);
49175 this.maskEl.right.show();
49177 this.intervalID = window.setInterval(function() {
49178 Roo.form.BasicForm.popover.unmask();
49181 window.onwheel = function(){ return false;};
49183 (function(){ this.isMasked = true; }).defer(500, this);
49187 unmask : function()
49189 if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
49193 this.maskEl.top.setStyle('position', 'absolute');
49194 this.maskEl.top.setSize(0, 0).setXY([0, 0]);
49195 this.maskEl.top.hide();
49197 this.maskEl.left.setStyle('position', 'absolute');
49198 this.maskEl.left.setSize(0, 0).setXY([0, 0]);
49199 this.maskEl.left.hide();
49201 this.maskEl.bottom.setStyle('position', 'absolute');
49202 this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
49203 this.maskEl.bottom.hide();
49205 this.maskEl.right.setStyle('position', 'absolute');
49206 this.maskEl.right.setSize(0, 0).setXY([0, 0]);
49207 this.maskEl.right.hide();
49209 window.onwheel = function(){ return true;};
49211 if(this.intervalID){
49212 window.clearInterval(this.intervalID);
49213 this.intervalID = false;
49216 this.isMasked = false;
49224 * Ext JS Library 1.1.1
49225 * Copyright(c) 2006-2007, Ext JS, LLC.
49227 * Originally Released Under LGPL - original licence link has changed is not relivant.
49230 * <script type="text/javascript">
49234 * @class Roo.form.Form
49235 * @extends Roo.form.BasicForm
49236 * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
49237 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
49239 * @param {Object} config Configuration options
49241 Roo.form.Form = function(config){
49243 if (config.items) {
49244 xitems = config.items;
49245 delete config.items;
49249 Roo.form.Form.superclass.constructor.call(this, null, config);
49250 this.url = this.url || this.action;
49252 this.root = new Roo.form.Layout(Roo.applyIf({
49256 this.active = this.root;
49258 * Array of all the buttons that have been added to this form via {@link addButton}
49262 this.allItems = [];
49265 * @event clientvalidation
49266 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
49267 * @param {Form} this
49268 * @param {Boolean} valid true if the form has passed client-side validation
49270 clientvalidation: true,
49273 * Fires when the form is rendered
49274 * @param {Roo.form.Form} form
49279 if (this.progressUrl) {
49280 // push a hidden field onto the list of fields..
49284 name : 'UPLOAD_IDENTIFIER'
49289 Roo.each(xitems, this.addxtype, this);
49293 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
49295 * @cfg {Roo.Button} buttons[] buttons at bottom of form
49299 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
49302 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
49305 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
49307 buttonAlign:'center',
49310 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
49315 * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
49316 * This property cascades to child containers if not set.
49321 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
49322 * fires a looping event with that state. This is required to bind buttons to the valid
49323 * state using the config value formBind:true on the button.
49325 monitorValid : false,
49328 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
49333 * @cfg {String} progressUrl - Url to return progress data
49336 progressUrl : false,
49338 * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
49339 * sending a formdata with extra parameters - eg uploaded elements.
49345 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
49346 * fields are added and the column is closed. If no fields are passed the column remains open
49347 * until end() is called.
49348 * @param {Object} config The config to pass to the column
49349 * @param {Field} field1 (optional)
49350 * @param {Field} field2 (optional)
49351 * @param {Field} etc (optional)
49352 * @return Column The column container object
49354 column : function(c){
49355 var col = new Roo.form.Column(c);
49357 if(arguments.length > 1){ // duplicate code required because of Opera
49358 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
49365 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
49366 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
49367 * until end() is called.
49368 * @param {Object} config The config to pass to the fieldset
49369 * @param {Field} field1 (optional)
49370 * @param {Field} field2 (optional)
49371 * @param {Field} etc (optional)
49372 * @return FieldSet The fieldset container object
49374 fieldset : function(c){
49375 var fs = new Roo.form.FieldSet(c);
49377 if(arguments.length > 1){ // duplicate code required because of Opera
49378 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
49385 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
49386 * fields are added and the container is closed. If no fields are passed the container remains open
49387 * until end() is called.
49388 * @param {Object} config The config to pass to the Layout
49389 * @param {Field} field1 (optional)
49390 * @param {Field} field2 (optional)
49391 * @param {Field} etc (optional)
49392 * @return Layout The container object
49394 container : function(c){
49395 var l = new Roo.form.Layout(c);
49397 if(arguments.length > 1){ // duplicate code required because of Opera
49398 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
49405 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
49406 * @param {Object} container A Roo.form.Layout or subclass of Layout
49407 * @return {Form} this
49409 start : function(c){
49410 // cascade label info
49411 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
49412 this.active.stack.push(c);
49413 c.ownerCt = this.active;
49419 * Closes the current open container
49420 * @return {Form} this
49423 if(this.active == this.root){
49426 this.active = this.active.ownerCt;
49431 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
49432 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
49433 * as the label of the field.
49434 * @param {Field} field1
49435 * @param {Field} field2 (optional)
49436 * @param {Field} etc. (optional)
49437 * @return {Form} this
49440 this.active.stack.push.apply(this.active.stack, arguments);
49441 this.allItems.push.apply(this.allItems,arguments);
49443 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
49444 if(a[i].isFormField){
49449 Roo.form.Form.superclass.add.apply(this, r);
49459 * Find any element that has been added to a form, using it's ID or name
49460 * This can include framesets, columns etc. along with regular fields..
49461 * @param {String} id - id or name to find.
49463 * @return {Element} e - or false if nothing found.
49465 findbyId : function(id)
49471 Roo.each(this.allItems, function(f){
49472 if (f.id == id || f.name == id ){
49483 * Render this form into the passed container. This should only be called once!
49484 * @param {String/HTMLElement/Element} container The element this component should be rendered into
49485 * @return {Form} this
49487 render : function(ct)
49493 var o = this.autoCreate || {
49495 method : this.method || 'POST',
49496 id : this.id || Roo.id()
49498 this.initEl(ct.createChild(o));
49500 this.root.render(this.el);
49504 this.items.each(function(f){
49505 f.render('x-form-el-'+f.id);
49508 if(this.buttons.length > 0){
49509 // tables are required to maintain order and for correct IE layout
49510 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
49511 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
49512 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
49514 var tr = tb.getElementsByTagName('tr')[0];
49515 for(var i = 0, len = this.buttons.length; i < len; i++) {
49516 var b = this.buttons[i];
49517 var td = document.createElement('td');
49518 td.className = 'x-form-btn-td';
49519 b.render(tr.appendChild(td));
49522 if(this.monitorValid){ // initialize after render
49523 this.startMonitoring();
49525 this.fireEvent('rendered', this);
49530 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
49531 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
49532 * object or a valid Roo.DomHelper element config
49533 * @param {Function} handler The function called when the button is clicked
49534 * @param {Object} scope (optional) The scope of the handler function
49535 * @return {Roo.Button}
49537 addButton : function(config, handler, scope){
49541 minWidth: this.minButtonWidth,
49544 if(typeof config == "string"){
49547 Roo.apply(bc, config);
49549 var btn = new Roo.Button(null, bc);
49550 this.buttons.push(btn);
49555 * Adds a series of form elements (using the xtype property as the factory method.
49556 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
49557 * @param {Object} config
49560 addxtype : function()
49562 var ar = Array.prototype.slice.call(arguments, 0);
49564 for(var i = 0; i < ar.length; i++) {
49566 continue; // skip -- if this happends something invalid got sent, we
49567 // should ignore it, as basically that interface element will not show up
49568 // and that should be pretty obvious!!
49571 if (Roo.form[ar[i].xtype]) {
49573 var fe = Roo.factory(ar[i], Roo.form);
49579 fe.store.form = this;
49584 this.allItems.push(fe);
49585 if (fe.items && fe.addxtype) {
49586 fe.addxtype.apply(fe, fe.items);
49596 // console.log('adding ' + ar[i].xtype);
49598 if (ar[i].xtype == 'Button') {
49599 //console.log('adding button');
49600 //console.log(ar[i]);
49601 this.addButton(ar[i]);
49602 this.allItems.push(fe);
49606 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
49607 alert('end is not supported on xtype any more, use items');
49609 // //console.log('adding end');
49617 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
49618 * option "monitorValid"
49620 startMonitoring : function(){
49623 Roo.TaskMgr.start({
49624 run : this.bindHandler,
49625 interval : this.monitorPoll || 200,
49632 * Stops monitoring of the valid state of this form
49634 stopMonitoring : function(){
49635 this.bound = false;
49639 bindHandler : function(){
49641 return false; // stops binding
49644 this.items.each(function(f){
49645 if(!f.isValid(true)){
49650 for(var i = 0, len = this.buttons.length; i < len; i++){
49651 var btn = this.buttons[i];
49652 if(btn.formBind === true && btn.disabled === valid){
49653 btn.setDisabled(!valid);
49656 this.fireEvent('clientvalidation', this, valid);
49670 Roo.Form = Roo.form.Form;
49673 * Ext JS Library 1.1.1
49674 * Copyright(c) 2006-2007, Ext JS, LLC.
49676 * Originally Released Under LGPL - original licence link has changed is not relivant.
49679 * <script type="text/javascript">
49682 // as we use this in bootstrap.
49683 Roo.namespace('Roo.form');
49685 * @class Roo.form.Action
49686 * Internal Class used to handle form actions
49688 * @param {Roo.form.BasicForm} el The form element or its id
49689 * @param {Object} config Configuration options
49694 // define the action interface
49695 Roo.form.Action = function(form, options){
49697 this.options = options || {};
49700 * Client Validation Failed
49703 Roo.form.Action.CLIENT_INVALID = 'client';
49705 * Server Validation Failed
49708 Roo.form.Action.SERVER_INVALID = 'server';
49710 * Connect to Server Failed
49713 Roo.form.Action.CONNECT_FAILURE = 'connect';
49715 * Reading Data from Server Failed
49718 Roo.form.Action.LOAD_FAILURE = 'load';
49720 Roo.form.Action.prototype = {
49722 failureType : undefined,
49723 response : undefined,
49724 result : undefined,
49726 // interface method
49727 run : function(options){
49731 // interface method
49732 success : function(response){
49736 // interface method
49737 handleResponse : function(response){
49741 // default connection failure
49742 failure : function(response){
49744 this.response = response;
49745 this.failureType = Roo.form.Action.CONNECT_FAILURE;
49746 this.form.afterAction(this, false);
49749 processResponse : function(response){
49750 this.response = response;
49751 if(!response.responseText){
49754 this.result = this.handleResponse(response);
49755 return this.result;
49758 // utility functions used internally
49759 getUrl : function(appendParams){
49760 var url = this.options.url || this.form.url || this.form.el.dom.action;
49762 var p = this.getParams();
49764 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
49770 getMethod : function(){
49771 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
49774 getParams : function(){
49775 var bp = this.form.baseParams;
49776 var p = this.options.params;
49778 if(typeof p == "object"){
49779 p = Roo.urlEncode(Roo.applyIf(p, bp));
49780 }else if(typeof p == 'string' && bp){
49781 p += '&' + Roo.urlEncode(bp);
49784 p = Roo.urlEncode(bp);
49789 createCallback : function(){
49791 success: this.success,
49792 failure: this.failure,
49794 timeout: (this.form.timeout*1000),
49795 upload: this.form.fileUpload ? this.success : undefined
49800 Roo.form.Action.Submit = function(form, options){
49801 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
49804 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
49807 haveProgress : false,
49808 uploadComplete : false,
49810 // uploadProgress indicator.
49811 uploadProgress : function()
49813 if (!this.form.progressUrl) {
49817 if (!this.haveProgress) {
49818 Roo.MessageBox.progress("Uploading", "Uploading");
49820 if (this.uploadComplete) {
49821 Roo.MessageBox.hide();
49825 this.haveProgress = true;
49827 var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
49829 var c = new Roo.data.Connection();
49831 url : this.form.progressUrl,
49836 success : function(req){
49837 //console.log(data);
49841 rdata = Roo.decode(req.responseText)
49843 Roo.log("Invalid data from server..");
49847 if (!rdata || !rdata.success) {
49849 Roo.MessageBox.alert(Roo.encode(rdata));
49852 var data = rdata.data;
49854 if (this.uploadComplete) {
49855 Roo.MessageBox.hide();
49860 Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
49861 Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
49864 this.uploadProgress.defer(2000,this);
49867 failure: function(data) {
49868 Roo.log('progress url failed ');
49879 // run get Values on the form, so it syncs any secondary forms.
49880 this.form.getValues();
49882 var o = this.options;
49883 var method = this.getMethod();
49884 var isPost = method == 'POST';
49885 if(o.clientValidation === false || this.form.isValid()){
49887 if (this.form.progressUrl) {
49888 this.form.findField('UPLOAD_IDENTIFIER').setValue(
49889 (new Date() * 1) + '' + Math.random());
49894 Roo.Ajax.request(Roo.apply(this.createCallback(), {
49895 form:this.form.el.dom,
49896 url:this.getUrl(!isPost),
49898 params:isPost ? this.getParams() : null,
49899 isUpload: this.form.fileUpload,
49900 formData : this.form.formData
49903 this.uploadProgress();
49905 }else if (o.clientValidation !== false){ // client validation failed
49906 this.failureType = Roo.form.Action.CLIENT_INVALID;
49907 this.form.afterAction(this, false);
49911 success : function(response)
49913 this.uploadComplete= true;
49914 if (this.haveProgress) {
49915 Roo.MessageBox.hide();
49919 var result = this.processResponse(response);
49920 if(result === true || result.success){
49921 this.form.afterAction(this, true);
49925 this.form.markInvalid(result.errors);
49926 this.failureType = Roo.form.Action.SERVER_INVALID;
49928 this.form.afterAction(this, false);
49930 failure : function(response)
49932 this.uploadComplete= true;
49933 if (this.haveProgress) {
49934 Roo.MessageBox.hide();
49937 this.response = response;
49938 this.failureType = Roo.form.Action.CONNECT_FAILURE;
49939 this.form.afterAction(this, false);
49942 handleResponse : function(response){
49943 if(this.form.errorReader){
49944 var rs = this.form.errorReader.read(response);
49947 for(var i = 0, len = rs.records.length; i < len; i++) {
49948 var r = rs.records[i];
49949 errors[i] = r.data;
49952 if(errors.length < 1){
49956 success : rs.success,
49962 ret = Roo.decode(response.responseText);
49966 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
49976 Roo.form.Action.Load = function(form, options){
49977 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
49978 this.reader = this.form.reader;
49981 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
49986 Roo.Ajax.request(Roo.apply(
49987 this.createCallback(), {
49988 method:this.getMethod(),
49989 url:this.getUrl(false),
49990 params:this.getParams()
49994 success : function(response){
49996 var result = this.processResponse(response);
49997 if(result === true || !result.success || !result.data){
49998 this.failureType = Roo.form.Action.LOAD_FAILURE;
49999 this.form.afterAction(this, false);
50002 this.form.clearInvalid();
50003 this.form.setValues(result.data);
50004 this.form.afterAction(this, true);
50007 handleResponse : function(response){
50008 if(this.form.reader){
50009 var rs = this.form.reader.read(response);
50010 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
50012 success : rs.success,
50016 return Roo.decode(response.responseText);
50020 Roo.form.Action.ACTION_TYPES = {
50021 'load' : Roo.form.Action.Load,
50022 'submit' : Roo.form.Action.Submit
50025 * Ext JS Library 1.1.1
50026 * Copyright(c) 2006-2007, Ext JS, LLC.
50028 * Originally Released Under LGPL - original licence link has changed is not relivant.
50031 * <script type="text/javascript">
50035 * @class Roo.form.Layout
50036 * @extends Roo.Component
50037 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
50038 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
50040 * @param {Object} config Configuration options
50042 Roo.form.Layout = function(config){
50044 if (config.items) {
50045 xitems = config.items;
50046 delete config.items;
50048 Roo.form.Layout.superclass.constructor.call(this, config);
50050 Roo.each(xitems, this.addxtype, this);
50054 Roo.extend(Roo.form.Layout, Roo.Component, {
50056 * @cfg {String/Object} autoCreate
50057 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
50060 * @cfg {String/Object/Function} style
50061 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
50062 * a function which returns such a specification.
50065 * @cfg {String} labelAlign
50066 * Valid values are "left," "top" and "right" (defaults to "left")
50069 * @cfg {Number} labelWidth
50070 * Fixed width in pixels of all field labels (defaults to undefined)
50073 * @cfg {Boolean} clear
50074 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
50078 * @cfg {String} labelSeparator
50079 * The separator to use after field labels (defaults to ':')
50081 labelSeparator : ':',
50083 * @cfg {Boolean} hideLabels
50084 * True to suppress the display of field labels in this layout (defaults to false)
50086 hideLabels : false,
50089 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
50094 onRender : function(ct, position){
50095 if(this.el){ // from markup
50096 this.el = Roo.get(this.el);
50097 }else { // generate
50098 var cfg = this.getAutoCreate();
50099 this.el = ct.createChild(cfg, position);
50102 this.el.applyStyles(this.style);
50104 if(this.labelAlign){
50105 this.el.addClass('x-form-label-'+this.labelAlign);
50107 if(this.hideLabels){
50108 this.labelStyle = "display:none";
50109 this.elementStyle = "padding-left:0;";
50111 if(typeof this.labelWidth == 'number'){
50112 this.labelStyle = "width:"+this.labelWidth+"px;";
50113 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
50115 if(this.labelAlign == 'top'){
50116 this.labelStyle = "width:auto;";
50117 this.elementStyle = "padding-left:0;";
50120 var stack = this.stack;
50121 var slen = stack.length;
50123 if(!this.fieldTpl){
50124 var t = new Roo.Template(
50125 '<div class="x-form-item {5}">',
50126 '<label for="{0}" style="{2}">{1}{4}</label>',
50127 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
50129 '</div><div class="x-form-clear-left"></div>'
50131 t.disableFormats = true;
50133 Roo.form.Layout.prototype.fieldTpl = t;
50135 for(var i = 0; i < slen; i++) {
50136 if(stack[i].isFormField){
50137 this.renderField(stack[i]);
50139 this.renderComponent(stack[i]);
50144 this.el.createChild({cls:'x-form-clear'});
50149 renderField : function(f){
50150 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
50153 f.labelStyle||this.labelStyle||'', //2
50154 this.elementStyle||'', //3
50155 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
50156 f.itemCls||this.itemCls||'' //5
50157 ], true).getPrevSibling());
50161 renderComponent : function(c){
50162 c.render(c.isLayout ? this.el : this.el.createChild());
50165 * Adds a object form elements (using the xtype property as the factory method.)
50166 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
50167 * @param {Object} config
50169 addxtype : function(o)
50171 // create the lement.
50172 o.form = this.form;
50173 var fe = Roo.factory(o, Roo.form);
50174 this.form.allItems.push(fe);
50175 this.stack.push(fe);
50177 if (fe.isFormField) {
50178 this.form.items.add(fe);
50186 * @class Roo.form.Column
50187 * @extends Roo.form.Layout
50188 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
50190 * @param {Object} config Configuration options
50192 Roo.form.Column = function(config){
50193 Roo.form.Column.superclass.constructor.call(this, config);
50196 Roo.extend(Roo.form.Column, Roo.form.Layout, {
50198 * @cfg {Number/String} width
50199 * The fixed width of the column in pixels or CSS value (defaults to "auto")
50202 * @cfg {String/Object} autoCreate
50203 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
50207 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
50210 onRender : function(ct, position){
50211 Roo.form.Column.superclass.onRender.call(this, ct, position);
50213 this.el.setWidth(this.width);
50220 * @class Roo.form.Row
50221 * @extends Roo.form.Layout
50222 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
50223 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
50225 * @param {Object} config Configuration options
50229 Roo.form.Row = function(config){
50230 Roo.form.Row.superclass.constructor.call(this, config);
50233 Roo.extend(Roo.form.Row, Roo.form.Layout, {
50235 * @cfg {Number/String} width
50236 * The fixed width of the column in pixels or CSS value (defaults to "auto")
50239 * @cfg {Number/String} height
50240 * The fixed height of the column in pixels or CSS value (defaults to "auto")
50242 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
50246 onRender : function(ct, position){
50247 //console.log('row render');
50249 var t = new Roo.Template(
50250 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
50251 '<label for="{0}" style="{2}">{1}{4}</label>',
50252 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
50256 t.disableFormats = true;
50258 Roo.form.Layout.prototype.rowTpl = t;
50260 this.fieldTpl = this.rowTpl;
50262 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
50263 var labelWidth = 100;
50265 if ((this.labelAlign != 'top')) {
50266 if (typeof this.labelWidth == 'number') {
50267 labelWidth = this.labelWidth
50269 this.padWidth = 20 + labelWidth;
50273 Roo.form.Column.superclass.onRender.call(this, ct, position);
50275 this.el.setWidth(this.width);
50278 this.el.setHeight(this.height);
50283 renderField : function(f){
50284 f.fieldEl = this.fieldTpl.append(this.el, [
50285 f.id, f.fieldLabel,
50286 f.labelStyle||this.labelStyle||'',
50287 this.elementStyle||'',
50288 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
50289 f.itemCls||this.itemCls||'',
50290 f.width ? f.width + this.padWidth : 160 + this.padWidth
50297 * @class Roo.form.FieldSet
50298 * @extends Roo.form.Layout
50299 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
50300 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
50302 * @param {Object} config Configuration options
50304 Roo.form.FieldSet = function(config){
50305 Roo.form.FieldSet.superclass.constructor.call(this, config);
50308 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
50310 * @cfg {String} legend
50311 * The text to display as the legend for the FieldSet (defaults to '')
50314 * @cfg {String/Object} autoCreate
50315 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
50319 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
50322 onRender : function(ct, position){
50323 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
50325 this.setLegend(this.legend);
50330 setLegend : function(text){
50332 this.el.child('legend').update(text);
50337 * Ext JS Library 1.1.1
50338 * Copyright(c) 2006-2007, Ext JS, LLC.
50340 * Originally Released Under LGPL - original licence link has changed is not relivant.
50343 * <script type="text/javascript">
50346 * @class Roo.form.VTypes
50347 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
50350 Roo.form.VTypes = function(){
50351 // closure these in so they are only created once.
50352 var alpha = /^[a-zA-Z_]+$/;
50353 var alphanum = /^[a-zA-Z0-9_]+$/;
50354 var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
50355 var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
50357 // All these messages and functions are configurable
50360 * The function used to validate email addresses
50361 * @param {String} value The email address
50363 'email' : function(v){
50364 return email.test(v);
50367 * The error text to display when the email validation function returns false
50370 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
50372 * The keystroke filter mask to be applied on email input
50375 'emailMask' : /[a-z0-9_\.\-@]/i,
50378 * The function used to validate URLs
50379 * @param {String} value The URL
50381 'url' : function(v){
50382 return url.test(v);
50385 * The error text to display when the url validation function returns false
50388 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
50391 * The function used to validate alpha values
50392 * @param {String} value The value
50394 'alpha' : function(v){
50395 return alpha.test(v);
50398 * The error text to display when the alpha validation function returns false
50401 'alphaText' : 'This field should only contain letters and _',
50403 * The keystroke filter mask to be applied on alpha input
50406 'alphaMask' : /[a-z_]/i,
50409 * The function used to validate alphanumeric values
50410 * @param {String} value The value
50412 'alphanum' : function(v){
50413 return alphanum.test(v);
50416 * The error text to display when the alphanumeric validation function returns false
50419 'alphanumText' : 'This field should only contain letters, numbers and _',
50421 * The keystroke filter mask to be applied on alphanumeric input
50424 'alphanumMask' : /[a-z0-9_]/i
50426 }();//<script type="text/javascript">
50429 * @class Roo.form.FCKeditor
50430 * @extends Roo.form.TextArea
50431 * Wrapper around the FCKEditor http://www.fckeditor.net
50433 * Creates a new FCKeditor
50434 * @param {Object} config Configuration options
50436 Roo.form.FCKeditor = function(config){
50437 Roo.form.FCKeditor.superclass.constructor.call(this, config);
50440 * @event editorinit
50441 * Fired when the editor is initialized - you can add extra handlers here..
50442 * @param {FCKeditor} this
50443 * @param {Object} the FCK object.
50450 Roo.form.FCKeditor.editors = { };
50451 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
50453 //defaultAutoCreate : {
50454 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
50458 * @cfg {Object} fck options - see fck manual for details.
50463 * @cfg {Object} fck toolbar set (Basic or Default)
50465 toolbarSet : 'Basic',
50467 * @cfg {Object} fck BasePath
50469 basePath : '/fckeditor/',
50477 onRender : function(ct, position)
50480 this.defaultAutoCreate = {
50482 style:"width:300px;height:60px;",
50483 autocomplete: "new-password"
50486 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
50489 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
50490 if(this.preventScrollbars){
50491 this.el.setStyle("overflow", "hidden");
50493 this.el.setHeight(this.growMin);
50496 //console.log('onrender' + this.getId() );
50497 Roo.form.FCKeditor.editors[this.getId()] = this;
50500 this.replaceTextarea() ;
50504 getEditor : function() {
50505 return this.fckEditor;
50508 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
50509 * @param {Mixed} value The value to set
50513 setValue : function(value)
50515 //console.log('setValue: ' + value);
50517 if(typeof(value) == 'undefined') { // not sure why this is happending...
50520 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
50522 //if(!this.el || !this.getEditor()) {
50523 // this.value = value;
50524 //this.setValue.defer(100,this,[value]);
50528 if(!this.getEditor()) {
50532 this.getEditor().SetData(value);
50539 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
50540 * @return {Mixed} value The field value
50542 getValue : function()
50545 if (this.frame && this.frame.dom.style.display == 'none') {
50546 return Roo.form.FCKeditor.superclass.getValue.call(this);
50549 if(!this.el || !this.getEditor()) {
50551 // this.getValue.defer(100,this);
50556 var value=this.getEditor().GetData();
50557 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
50558 return Roo.form.FCKeditor.superclass.getValue.call(this);
50564 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
50565 * @return {Mixed} value The field value
50567 getRawValue : function()
50569 if (this.frame && this.frame.dom.style.display == 'none') {
50570 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
50573 if(!this.el || !this.getEditor()) {
50574 //this.getRawValue.defer(100,this);
50581 var value=this.getEditor().GetData();
50582 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
50583 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
50587 setSize : function(w,h) {
50591 //if (this.frame && this.frame.dom.style.display == 'none') {
50592 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
50595 //if(!this.el || !this.getEditor()) {
50596 // this.setSize.defer(100,this, [w,h]);
50602 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
50604 this.frame.dom.setAttribute('width', w);
50605 this.frame.dom.setAttribute('height', h);
50606 this.frame.setSize(w,h);
50610 toggleSourceEdit : function(value) {
50614 this.el.dom.style.display = value ? '' : 'none';
50615 this.frame.dom.style.display = value ? 'none' : '';
50620 focus: function(tag)
50622 if (this.frame.dom.style.display == 'none') {
50623 return Roo.form.FCKeditor.superclass.focus.call(this);
50625 if(!this.el || !this.getEditor()) {
50626 this.focus.defer(100,this, [tag]);
50633 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
50634 this.getEditor().Focus();
50636 if (!this.getEditor().Selection.GetSelection()) {
50637 this.focus.defer(100,this, [tag]);
50642 var r = this.getEditor().EditorDocument.createRange();
50643 r.setStart(tgs[0],0);
50644 r.setEnd(tgs[0],0);
50645 this.getEditor().Selection.GetSelection().removeAllRanges();
50646 this.getEditor().Selection.GetSelection().addRange(r);
50647 this.getEditor().Focus();
50654 replaceTextarea : function()
50656 if ( document.getElementById( this.getId() + '___Frame' ) ) {
50659 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
50661 // We must check the elements firstly using the Id and then the name.
50662 var oTextarea = document.getElementById( this.getId() );
50664 var colElementsByName = document.getElementsByName( this.getId() ) ;
50666 oTextarea.style.display = 'none' ;
50668 if ( oTextarea.tabIndex ) {
50669 this.TabIndex = oTextarea.tabIndex ;
50672 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
50673 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
50674 this.frame = Roo.get(this.getId() + '___Frame')
50677 _getConfigHtml : function()
50681 for ( var o in this.fckconfig ) {
50682 sConfig += sConfig.length > 0 ? '&' : '';
50683 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
50686 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
50690 _getIFrameHtml : function()
50692 var sFile = 'fckeditor.html' ;
50693 /* no idea what this is about..
50696 if ( (/fcksource=true/i).test( window.top.location.search ) )
50697 sFile = 'fckeditor.original.html' ;
50702 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
50703 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
50706 var html = '<iframe id="' + this.getId() +
50707 '___Frame" src="' + sLink +
50708 '" width="' + this.width +
50709 '" height="' + this.height + '"' +
50710 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
50711 ' frameborder="0" scrolling="no"></iframe>' ;
50716 _insertHtmlBefore : function( html, element )
50718 if ( element.insertAdjacentHTML ) {
50720 element.insertAdjacentHTML( 'beforeBegin', html ) ;
50722 var oRange = document.createRange() ;
50723 oRange.setStartBefore( element ) ;
50724 var oFragment = oRange.createContextualFragment( html );
50725 element.parentNode.insertBefore( oFragment, element ) ;
50738 //Roo.reg('fckeditor', Roo.form.FCKeditor);
50740 function FCKeditor_OnComplete(editorInstance){
50741 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
50742 f.fckEditor = editorInstance;
50743 //console.log("loaded");
50744 f.fireEvent('editorinit', f, editorInstance);
50764 //<script type="text/javascript">
50766 * @class Roo.form.GridField
50767 * @extends Roo.form.Field
50768 * Embed a grid (or editable grid into a form)
50771 * This embeds a grid in a form, the value of the field should be the json encoded array of rows
50773 * xgrid.store = Roo.data.Store
50774 * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
50775 * xgrid.store.reader = Roo.data.JsonReader
50779 * Creates a new GridField
50780 * @param {Object} config Configuration options
50782 Roo.form.GridField = function(config){
50783 Roo.form.GridField.superclass.constructor.call(this, config);
50787 Roo.extend(Roo.form.GridField, Roo.form.Field, {
50789 * @cfg {Number} width - used to restrict width of grid..
50793 * @cfg {Number} height - used to restrict height of grid..
50797 * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
50803 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
50804 * {tag: "input", type: "checkbox", autocomplete: "off"})
50806 // defaultAutoCreate : { tag: 'div' },
50807 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
50809 * @cfg {String} addTitle Text to include for adding a title.
50813 onResize : function(){
50814 Roo.form.Field.superclass.onResize.apply(this, arguments);
50817 initEvents : function(){
50818 // Roo.form.Checkbox.superclass.initEvents.call(this);
50819 // has no events...
50824 getResizeEl : function(){
50828 getPositionEl : function(){
50833 onRender : function(ct, position){
50835 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
50836 var style = this.style;
50839 Roo.form.GridField.superclass.onRender.call(this, ct, position);
50840 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
50841 this.viewEl = this.wrap.createChild({ tag: 'div' });
50843 this.viewEl.applyStyles(style);
50846 this.viewEl.setWidth(this.width);
50849 this.viewEl.setHeight(this.height);
50851 //if(this.inputValue !== undefined){
50852 //this.setValue(this.value);
50855 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
50858 this.grid.render();
50859 this.grid.getDataSource().on('remove', this.refreshValue, this);
50860 this.grid.getDataSource().on('update', this.refreshValue, this);
50861 this.grid.on('afteredit', this.refreshValue, this);
50867 * Sets the value of the item.
50868 * @param {String} either an object or a string..
50870 setValue : function(v){
50872 v = v || []; // empty set..
50873 // this does not seem smart - it really only affects memoryproxy grids..
50874 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
50875 var ds = this.grid.getDataSource();
50876 // assumes a json reader..
50878 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
50879 ds.loadData( data);
50881 // clear selection so it does not get stale.
50882 if (this.grid.sm) {
50883 this.grid.sm.clearSelections();
50886 Roo.form.GridField.superclass.setValue.call(this, v);
50887 this.refreshValue();
50888 // should load data in the grid really....
50892 refreshValue: function() {
50894 this.grid.getDataSource().each(function(r) {
50897 this.el.dom.value = Roo.encode(val);
50905 * Ext JS Library 1.1.1
50906 * Copyright(c) 2006-2007, Ext JS, LLC.
50908 * Originally Released Under LGPL - original licence link has changed is not relivant.
50911 * <script type="text/javascript">
50914 * @class Roo.form.DisplayField
50915 * @extends Roo.form.Field
50916 * A generic Field to display non-editable data.
50917 * @cfg {Boolean} closable (true|false) default false
50919 * Creates a new Display Field item.
50920 * @param {Object} config Configuration options
50922 Roo.form.DisplayField = function(config){
50923 Roo.form.DisplayField.superclass.constructor.call(this, config);
50928 * Fires after the click the close btn
50929 * @param {Roo.form.DisplayField} this
50935 Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
50936 inputType: 'hidden',
50942 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
50944 focusClass : undefined,
50946 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
50948 fieldClass: 'x-form-field',
50951 * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
50953 valueRenderer: undefined,
50957 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
50958 * {tag: "input", type: "checkbox", autocomplete: "off"})
50961 // defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
50965 onResize : function(){
50966 Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
50970 initEvents : function(){
50971 // Roo.form.Checkbox.superclass.initEvents.call(this);
50972 // has no events...
50975 this.closeEl.on('click', this.onClose, this);
50981 getResizeEl : function(){
50985 getPositionEl : function(){
50990 onRender : function(ct, position){
50992 Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
50993 //if(this.inputValue !== undefined){
50994 this.wrap = this.el.wrap();
50996 this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
50999 this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
51002 if (this.bodyStyle) {
51003 this.viewEl.applyStyles(this.bodyStyle);
51005 //this.viewEl.setStyle('padding', '2px');
51007 this.setValue(this.value);
51012 initValue : Roo.emptyFn,
51017 onClick : function(){
51022 * Sets the checked state of the checkbox.
51023 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
51025 setValue : function(v){
51027 var html = this.valueRenderer ? this.valueRenderer(v) : String.format('{0}', v);
51028 // this might be called before we have a dom element..
51029 if (!this.viewEl) {
51032 this.viewEl.dom.innerHTML = html;
51033 Roo.form.DisplayField.superclass.setValue.call(this, v);
51037 onClose : function(e)
51039 e.preventDefault();
51041 this.fireEvent('close', this);
51050 * @class Roo.form.DayPicker
51051 * @extends Roo.form.Field
51052 * A Day picker show [M] [T] [W] ....
51054 * Creates a new Day Picker
51055 * @param {Object} config Configuration options
51057 Roo.form.DayPicker= function(config){
51058 Roo.form.DayPicker.superclass.constructor.call(this, config);
51062 Roo.extend(Roo.form.DayPicker, Roo.form.Field, {
51064 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
51066 focusClass : undefined,
51068 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
51070 fieldClass: "x-form-field",
51073 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
51074 * {tag: "input", type: "checkbox", autocomplete: "off"})
51076 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
51079 actionMode : 'viewEl',
51083 inputType : 'hidden',
51086 inputElement: false, // real input element?
51087 basedOn: false, // ????
51089 isFormField: true, // not sure where this is needed!!!!
51091 onResize : function(){
51092 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
51093 if(!this.boxLabel){
51094 this.el.alignTo(this.wrap, 'c-c');
51098 initEvents : function(){
51099 Roo.form.Checkbox.superclass.initEvents.call(this);
51100 this.el.on("click", this.onClick, this);
51101 this.el.on("change", this.onClick, this);
51105 getResizeEl : function(){
51109 getPositionEl : function(){
51115 onRender : function(ct, position){
51116 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
51118 this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
51120 var r1 = '<table><tr>';
51121 var r2 = '<tr class="x-form-daypick-icons">';
51122 for (var i=0; i < 7; i++) {
51123 r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
51124 r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL +'"></td>';
51127 var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
51128 viewEl.select('img').on('click', this.onClick, this);
51129 this.viewEl = viewEl;
51132 // this will not work on Chrome!!!
51133 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
51134 this.el.on('propertychange', this.setFromHidden, this); //ie
51142 initValue : Roo.emptyFn,
51145 * Returns the checked state of the checkbox.
51146 * @return {Boolean} True if checked, else false
51148 getValue : function(){
51149 return this.el.dom.value;
51154 onClick : function(e){
51155 //this.setChecked(!this.checked);
51156 Roo.get(e.target).toggleClass('x-menu-item-checked');
51157 this.refreshValue();
51158 //if(this.el.dom.checked != this.checked){
51159 // this.setValue(this.el.dom.checked);
51164 refreshValue : function()
51167 this.viewEl.select('img',true).each(function(e,i,n) {
51168 val += e.is(".x-menu-item-checked") ? String(n) : '';
51170 this.setValue(val, true);
51174 * Sets the checked state of the checkbox.
51175 * On is always based on a string comparison between inputValue and the param.
51176 * @param {Boolean/String} value - the value to set
51177 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
51179 setValue : function(v,suppressEvent){
51180 if (!this.el.dom) {
51183 var old = this.el.dom.value ;
51184 this.el.dom.value = v;
51185 if (suppressEvent) {
51189 // update display..
51190 this.viewEl.select('img',true).each(function(e,i,n) {
51192 var on = e.is(".x-menu-item-checked");
51193 var newv = v.indexOf(String(n)) > -1;
51195 e.toggleClass('x-menu-item-checked');
51201 this.fireEvent('change', this, v, old);
51206 // handle setting of hidden value by some other method!!?!?
51207 setFromHidden: function()
51212 //console.log("SET FROM HIDDEN");
51213 //alert('setFrom hidden');
51214 this.setValue(this.el.dom.value);
51217 onDestroy : function()
51220 Roo.get(this.viewEl).remove();
51223 Roo.form.DayPicker.superclass.onDestroy.call(this);
51227 * RooJS Library 1.1.1
51228 * Copyright(c) 2008-2011 Alan Knowles
51235 * @class Roo.form.ComboCheck
51236 * @extends Roo.form.ComboBox
51237 * A combobox for multiple select items.
51239 * FIXME - could do with a reset button..
51242 * Create a new ComboCheck
51243 * @param {Object} config Configuration options
51245 Roo.form.ComboCheck = function(config){
51246 Roo.form.ComboCheck.superclass.constructor.call(this, config);
51247 // should verify some data...
51249 // hiddenName = required..
51250 // displayField = required
51251 // valudField == required
51252 var req= [ 'hiddenName', 'displayField', 'valueField' ];
51254 Roo.each(req, function(e) {
51255 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
51256 throw "Roo.form.ComboCheck : missing value for: " + e;
51263 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
51268 selectedClass: 'x-menu-item-checked',
51271 onRender : function(ct, position){
51277 var cls = 'x-combo-list';
51280 this.tpl = new Roo.Template({
51281 html : '<div class="'+cls+'-item x-menu-check-item">' +
51282 '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' +
51283 '<span>{' + this.displayField + '}</span>' +
51290 Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
51291 this.view.singleSelect = false;
51292 this.view.multiSelect = true;
51293 this.view.toggleSelect = true;
51294 this.pageTb.add(new Roo.Toolbar.Fill(), {
51297 handler: function()
51304 onViewOver : function(e, t){
51310 onViewClick : function(doFocus,index){
51314 select: function () {
51315 //Roo.log("SELECT CALLED");
51318 selectByValue : function(xv, scrollIntoView){
51319 var ar = this.getValueArray();
51322 Roo.each(ar, function(v) {
51323 if(v === undefined || v === null){
51326 var r = this.findRecord(this.valueField, v);
51328 sels.push(this.store.indexOf(r))
51332 this.view.select(sels);
51338 onSelect : function(record, index){
51339 // Roo.log("onselect Called");
51340 // this is only called by the clear button now..
51341 this.view.clearSelections();
51342 this.setValue('[]');
51343 if (this.value != this.valueBefore) {
51344 this.fireEvent('change', this, this.value, this.valueBefore);
51345 this.valueBefore = this.value;
51348 getValueArray : function()
51353 //Roo.log(this.value);
51354 if (typeof(this.value) == 'undefined') {
51357 var ar = Roo.decode(this.value);
51358 return ar instanceof Array ? ar : []; //?? valid?
51361 Roo.log(e + "\nRoo.form.ComboCheck:getValueArray invalid data:" + this.getValue());
51366 expand : function ()
51369 Roo.form.ComboCheck.superclass.expand.call(this);
51370 this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
51371 //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
51376 collapse : function(){
51377 Roo.form.ComboCheck.superclass.collapse.call(this);
51378 var sl = this.view.getSelectedIndexes();
51379 var st = this.store;
51383 Roo.each(sl, function(i) {
51385 nv.push(r.get(this.valueField));
51387 this.setValue(Roo.encode(nv));
51388 if (this.value != this.valueBefore) {
51390 this.fireEvent('change', this, this.value, this.valueBefore);
51391 this.valueBefore = this.value;
51396 setValue : function(v){
51400 var vals = this.getValueArray();
51402 Roo.each(vals, function(k) {
51403 var r = this.findRecord(this.valueField, k);
51405 tv.push(r.data[this.displayField]);
51406 }else if(this.valueNotFoundText !== undefined){
51407 tv.push( this.valueNotFoundText );
51412 Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
51413 this.hiddenField.value = v;
51419 * Ext JS Library 1.1.1
51420 * Copyright(c) 2006-2007, Ext JS, LLC.
51422 * Originally Released Under LGPL - original licence link has changed is not relivant.
51425 * <script type="text/javascript">
51429 * @class Roo.form.Signature
51430 * @extends Roo.form.Field
51434 * @param {Object} config Configuration options
51437 Roo.form.Signature = function(config){
51438 Roo.form.Signature.superclass.constructor.call(this, config);
51440 this.addEvents({// not in used??
51443 * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
51444 * @param {Roo.form.Signature} combo This combo box
51449 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
51450 * @param {Roo.form.ComboBox} combo This combo box
51451 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
51457 Roo.extend(Roo.form.Signature, Roo.form.Field, {
51459 * @cfg {Object} labels Label to use when rendering a form.
51463 * confirm : "Confirm"
51468 confirm : "Confirm"
51471 * @cfg {Number} width The signature panel width (defaults to 300)
51475 * @cfg {Number} height The signature panel height (defaults to 100)
51479 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
51481 allowBlank : false,
51484 // {Object} signPanel The signature SVG panel element (defaults to {})
51486 // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
51487 isMouseDown : false,
51488 // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
51489 isConfirmed : false,
51490 // {String} signatureTmp SVG mapping string (defaults to empty string)
51494 defaultAutoCreate : { // modified by initCompnoent..
51500 onRender : function(ct, position){
51502 Roo.form.Signature.superclass.onRender.call(this, ct, position);
51504 this.wrap = this.el.wrap({
51505 cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
51508 this.createToolbar(this);
51509 this.signPanel = this.wrap.createChild({
51511 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
51515 this.svgID = Roo.id();
51516 this.svgEl = this.signPanel.createChild({
51517 xmlns : 'http://www.w3.org/2000/svg',
51519 id : this.svgID + "-svg",
51521 height: this.height,
51522 viewBox: '0 0 '+this.width+' '+this.height,
51526 id: this.svgID + "-svg-r",
51528 height: this.height,
51533 id: this.svgID + "-svg-l",
51535 y1: (this.height*0.8), // start set the line in 80% of height
51536 x2: this.width, // end
51537 y2: (this.height*0.8), // end set the line in 80% of height
51539 'stroke-width': "1",
51540 'stroke-dasharray': "3",
51541 'shape-rendering': "crispEdges",
51542 'pointer-events': "none"
51546 id: this.svgID + "-svg-p",
51548 'stroke-width': "3",
51550 'pointer-events': 'none'
51555 this.svgBox = this.svgEl.dom.getScreenCTM();
51557 createSVG : function(){
51558 var svg = this.signPanel;
51559 var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
51562 r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
51563 r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
51564 r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
51565 r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
51566 r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
51567 r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
51568 r.addEventListener('touchend', function(e) { return t.up(e); }, false);
51571 isTouchEvent : function(e){
51572 return e.type.match(/^touch/);
51574 getCoords : function (e) {
51575 var pt = this.svgEl.dom.createSVGPoint();
51578 if (this.isTouchEvent(e)) {
51579 pt.x = e.targetTouches[0].clientX;
51580 pt.y = e.targetTouches[0].clientY;
51582 var a = this.svgEl.dom.getScreenCTM();
51583 var b = a.inverse();
51584 var mx = pt.matrixTransform(b);
51585 return mx.x + ',' + mx.y;
51587 //mouse event headler
51588 down : function (e) {
51589 this.signatureTmp += 'M' + this.getCoords(e) + ' ';
51590 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
51592 this.isMouseDown = true;
51594 e.preventDefault();
51596 move : function (e) {
51597 if (this.isMouseDown) {
51598 this.signatureTmp += 'L' + this.getCoords(e) + ' ';
51599 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
51602 e.preventDefault();
51604 up : function (e) {
51605 this.isMouseDown = false;
51606 var sp = this.signatureTmp.split(' ');
51609 if(!sp[sp.length-2].match(/^L/)){
51613 this.signatureTmp = sp.join(" ");
51616 if(this.getValue() != this.signatureTmp){
51617 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
51618 this.isConfirmed = false;
51620 e.preventDefault();
51624 * Protected method that will not generally be called directly. It
51625 * is called when the editor creates its toolbar. Override this method if you need to
51626 * add custom toolbar buttons.
51627 * @param {HtmlEditor} editor
51629 createToolbar : function(editor){
51630 function btn(id, toggle, handler){
51631 var xid = fid + '-'+ id ;
51635 cls : 'x-btn-icon x-edit-'+id,
51636 enableToggle:toggle !== false,
51637 scope: editor, // was editor...
51638 handler:handler||editor.relayBtnCmd,
51639 clickEvent:'mousedown',
51640 tooltip: etb.buttonTips[id] || undefined, ///tips ???
51646 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
51650 cls : ' x-signature-btn x-signature-'+id,
51651 scope: editor, // was editor...
51652 handler: this.reset,
51653 clickEvent:'mousedown',
51654 text: this.labels.clear
51661 cls : ' x-signature-btn x-signature-'+id,
51662 scope: editor, // was editor...
51663 handler: this.confirmHandler,
51664 clickEvent:'mousedown',
51665 text: this.labels.confirm
51672 * when user is clicked confirm then show this image.....
51674 * @return {String} Image Data URI
51676 getImageDataURI : function(){
51677 var svg = this.svgEl.dom.parentNode.innerHTML;
51678 var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
51683 * @return {Boolean} this.isConfirmed
51685 getConfirmed : function(){
51686 return this.isConfirmed;
51690 * @return {Number} this.width
51692 getWidth : function(){
51697 * @return {Number} this.height
51699 getHeight : function(){
51700 return this.height;
51703 getSignature : function(){
51704 return this.signatureTmp;
51707 reset : function(){
51708 this.signatureTmp = '';
51709 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
51710 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
51711 this.isConfirmed = false;
51712 Roo.form.Signature.superclass.reset.call(this);
51714 setSignature : function(s){
51715 this.signatureTmp = s;
51716 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
51717 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
51719 this.isConfirmed = false;
51720 Roo.form.Signature.superclass.reset.call(this);
51723 // Roo.log(this.signPanel.dom.contentWindow.up())
51726 setConfirmed : function(){
51730 // Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
51733 confirmHandler : function(){
51734 if(!this.getSignature()){
51738 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
51739 this.setValue(this.getSignature());
51740 this.isConfirmed = true;
51742 this.fireEvent('confirm', this);
51745 // Subclasses should provide the validation implementation by overriding this
51746 validateValue : function(value){
51747 if(this.allowBlank){
51751 if(this.isConfirmed){
51758 * Ext JS Library 1.1.1
51759 * Copyright(c) 2006-2007, Ext JS, LLC.
51761 * Originally Released Under LGPL - original licence link has changed is not relivant.
51764 * <script type="text/javascript">
51769 * @class Roo.form.ComboBox
51770 * @extends Roo.form.TriggerField
51771 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
51773 * Create a new ComboBox.
51774 * @param {Object} config Configuration options
51776 Roo.form.Select = function(config){
51777 Roo.form.Select.superclass.constructor.call(this, config);
51781 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
51783 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
51786 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
51787 * rendering into an Roo.Editor, defaults to false)
51790 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
51791 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
51794 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
51797 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
51798 * the dropdown list (defaults to undefined, with no header element)
51802 * @cfg {String/Roo.Template} tpl The template to use to render the output
51806 defaultAutoCreate : {tag: "select" },
51808 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
51810 listWidth: undefined,
51812 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
51813 * mode = 'remote' or 'text' if mode = 'local')
51815 displayField: undefined,
51817 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
51818 * mode = 'remote' or 'value' if mode = 'local').
51819 * Note: use of a valueField requires the user make a selection
51820 * in order for a value to be mapped.
51822 valueField: undefined,
51826 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
51827 * field's data value (defaults to the underlying DOM element's name)
51829 hiddenName: undefined,
51831 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
51835 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
51837 selectedClass: 'x-combo-selected',
51839 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
51840 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
51841 * which displays a downward arrow icon).
51843 triggerClass : 'x-form-arrow-trigger',
51845 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
51849 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
51850 * anchor positions (defaults to 'tl-bl')
51852 listAlign: 'tl-bl?',
51854 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
51858 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
51859 * query specified by the allQuery config option (defaults to 'query')
51861 triggerAction: 'query',
51863 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
51864 * (defaults to 4, does not apply if editable = false)
51868 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
51869 * delay (typeAheadDelay) if it matches a known value (defaults to false)
51873 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
51874 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
51878 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
51879 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
51883 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
51884 * when editable = true (defaults to false)
51886 selectOnFocus:false,
51888 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
51890 queryParam: 'query',
51892 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
51893 * when mode = 'remote' (defaults to 'Loading...')
51895 loadingText: 'Loading...',
51897 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
51901 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
51905 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
51906 * traditional select (defaults to true)
51910 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
51914 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
51918 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
51919 * listWidth has a higher value)
51923 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
51924 * allow the user to set arbitrary text into the field (defaults to false)
51926 forceSelection:false,
51928 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
51929 * if typeAhead = true (defaults to 250)
51931 typeAheadDelay : 250,
51933 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
51934 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
51936 valueNotFoundText : undefined,
51939 * @cfg {String} defaultValue The value displayed after loading the store.
51944 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
51946 blockFocus : false,
51949 * @cfg {Boolean} disableClear Disable showing of clear button.
51951 disableClear : false,
51953 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
51955 alwaysQuery : false,
51961 // element that contains real text value.. (when hidden is used..)
51964 onRender : function(ct, position){
51965 Roo.form.Field.prototype.onRender.call(this, ct, position);
51968 this.store.on('beforeload', this.onBeforeLoad, this);
51969 this.store.on('load', this.onLoad, this);
51970 this.store.on('loadexception', this.onLoadException, this);
51971 this.store.load({});
51979 initEvents : function(){
51980 //Roo.form.ComboBox.superclass.initEvents.call(this);
51984 onDestroy : function(){
51987 this.store.un('beforeload', this.onBeforeLoad, this);
51988 this.store.un('load', this.onLoad, this);
51989 this.store.un('loadexception', this.onLoadException, this);
51991 //Roo.form.ComboBox.superclass.onDestroy.call(this);
51995 fireKey : function(e){
51996 if(e.isNavKeyPress() && !this.list.isVisible()){
51997 this.fireEvent("specialkey", this, e);
52002 onResize: function(w, h){
52010 * Allow or prevent the user from directly editing the field text. If false is passed,
52011 * the user will only be able to select from the items defined in the dropdown list. This method
52012 * is the runtime equivalent of setting the 'editable' config option at config time.
52013 * @param {Boolean} value True to allow the user to directly edit the field text
52015 setEditable : function(value){
52020 onBeforeLoad : function(){
52022 Roo.log("Select before load");
52025 this.innerList.update(this.loadingText ?
52026 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
52027 //this.restrictHeight();
52028 this.selectedIndex = -1;
52032 onLoad : function(){
52035 var dom = this.el.dom;
52036 dom.innerHTML = '';
52037 var od = dom.ownerDocument;
52039 if (this.emptyText) {
52040 var op = od.createElement('option');
52041 op.setAttribute('value', '');
52042 op.innerHTML = String.format('{0}', this.emptyText);
52043 dom.appendChild(op);
52045 if(this.store.getCount() > 0){
52047 var vf = this.valueField;
52048 var df = this.displayField;
52049 this.store.data.each(function(r) {
52050 // which colmsn to use... testing - cdoe / title..
52051 var op = od.createElement('option');
52052 op.setAttribute('value', r.data[vf]);
52053 op.innerHTML = String.format('{0}', r.data[df]);
52054 dom.appendChild(op);
52056 if (typeof(this.defaultValue != 'undefined')) {
52057 this.setValue(this.defaultValue);
52062 //this.onEmptyResults();
52067 onLoadException : function()
52069 dom.innerHTML = '';
52071 Roo.log("Select on load exception");
52075 Roo.log(this.store.reader.jsonData);
52076 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
52077 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
52083 onTypeAhead : function(){
52088 onSelect : function(record, index){
52089 Roo.log('on select?');
52091 if(this.fireEvent('beforeselect', this, record, index) !== false){
52092 this.setFromData(index > -1 ? record.data : false);
52094 this.fireEvent('select', this, record, index);
52099 * Returns the currently selected field value or empty string if no value is set.
52100 * @return {String} value The selected value
52102 getValue : function(){
52103 var dom = this.el.dom;
52104 this.value = dom.options[dom.selectedIndex].value;
52110 * Clears any text/value currently set in the field
52112 clearValue : function(){
52114 this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
52119 * Sets the specified value into the field. If the value finds a match, the corresponding record text
52120 * will be displayed in the field. If the value does not match the data value of an existing item,
52121 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
52122 * Otherwise the field will be blank (although the value will still be set).
52123 * @param {String} value The value to match
52125 setValue : function(v){
52126 var d = this.el.dom;
52127 for (var i =0; i < d.options.length;i++) {
52128 if (v == d.options[i].value) {
52129 d.selectedIndex = i;
52137 * @property {Object} the last set data for the element
52142 * Sets the value of the field based on a object which is related to the record format for the store.
52143 * @param {Object} value the value to set as. or false on reset?
52145 setFromData : function(o){
52146 Roo.log('setfrom data?');
52152 reset : function(){
52156 findRecord : function(prop, value){
52161 if(this.store.getCount() > 0){
52162 this.store.each(function(r){
52163 if(r.data[prop] == value){
52173 getName: function()
52175 // returns hidden if it's set..
52176 if (!this.rendered) {return ''};
52177 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
52185 onEmptyResults : function(){
52186 Roo.log('empty results');
52191 * Returns true if the dropdown list is expanded, else false.
52193 isExpanded : function(){
52198 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
52199 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
52200 * @param {String} value The data value of the item to select
52201 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
52202 * selected item if it is not currently in view (defaults to true)
52203 * @return {Boolean} True if the value matched an item in the list, else false
52205 selectByValue : function(v, scrollIntoView){
52206 Roo.log('select By Value');
52209 if(v !== undefined && v !== null){
52210 var r = this.findRecord(this.valueField || this.displayField, v);
52212 this.select(this.store.indexOf(r), scrollIntoView);
52220 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
52221 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
52222 * @param {Number} index The zero-based index of the list item to select
52223 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
52224 * selected item if it is not currently in view (defaults to true)
52226 select : function(index, scrollIntoView){
52227 Roo.log('select ');
52230 this.selectedIndex = index;
52231 this.view.select(index);
52232 if(scrollIntoView !== false){
52233 var el = this.view.getNode(index);
52235 this.innerList.scrollChildIntoView(el, false);
52243 validateBlur : function(){
52250 initQuery : function(){
52251 this.doQuery(this.getRawValue());
52255 doForce : function(){
52256 if(this.el.dom.value.length > 0){
52257 this.el.dom.value =
52258 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
52264 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
52265 * query allowing the query action to be canceled if needed.
52266 * @param {String} query The SQL query to execute
52267 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
52268 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
52269 * saved in the current store (defaults to false)
52271 doQuery : function(q, forceAll){
52273 Roo.log('doQuery?');
52274 if(q === undefined || q === null){
52279 forceAll: forceAll,
52283 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
52287 forceAll = qe.forceAll;
52288 if(forceAll === true || (q.length >= this.minChars)){
52289 if(this.lastQuery != q || this.alwaysQuery){
52290 this.lastQuery = q;
52291 if(this.mode == 'local'){
52292 this.selectedIndex = -1;
52294 this.store.clearFilter();
52296 this.store.filter(this.displayField, q);
52300 this.store.baseParams[this.queryParam] = q;
52302 params: this.getParams(q)
52307 this.selectedIndex = -1;
52314 getParams : function(q){
52316 //p[this.queryParam] = q;
52319 p.limit = this.pageSize;
52325 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
52327 collapse : function(){
52332 collapseIf : function(e){
52337 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
52339 expand : function(){
52347 * @cfg {Boolean} grow
52351 * @cfg {Number} growMin
52355 * @cfg {Number} growMax
52363 setWidth : function()
52367 getResizeEl : function(){
52370 });//<script type="text/javasscript">
52374 * @class Roo.DDView
52375 * A DnD enabled version of Roo.View.
52376 * @param {Element/String} container The Element in which to create the View.
52377 * @param {String} tpl The template string used to create the markup for each element of the View
52378 * @param {Object} config The configuration properties. These include all the config options of
52379 * {@link Roo.View} plus some specific to this class.<br>
52381 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
52382 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
52384 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
52385 .x-view-drag-insert-above {
52386 border-top:1px dotted #3366cc;
52388 .x-view-drag-insert-below {
52389 border-bottom:1px dotted #3366cc;
52395 Roo.DDView = function(container, tpl, config) {
52396 Roo.DDView.superclass.constructor.apply(this, arguments);
52397 this.getEl().setStyle("outline", "0px none");
52398 this.getEl().unselectable();
52399 if (this.dragGroup) {
52400 this.setDraggable(this.dragGroup.split(","));
52402 if (this.dropGroup) {
52403 this.setDroppable(this.dropGroup.split(","));
52405 if (this.deletable) {
52406 this.setDeletable();
52408 this.isDirtyFlag = false;
52414 Roo.extend(Roo.DDView, Roo.View, {
52415 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
52416 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
52417 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
52418 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
52422 reset: Roo.emptyFn,
52424 clearInvalid: Roo.form.Field.prototype.clearInvalid,
52426 validate: function() {
52430 destroy: function() {
52431 this.purgeListeners();
52432 this.getEl.removeAllListeners();
52433 this.getEl().remove();
52434 if (this.dragZone) {
52435 if (this.dragZone.destroy) {
52436 this.dragZone.destroy();
52439 if (this.dropZone) {
52440 if (this.dropZone.destroy) {
52441 this.dropZone.destroy();
52446 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
52447 getName: function() {
52451 /** Loads the View from a JSON string representing the Records to put into the Store. */
52452 setValue: function(v) {
52454 throw "DDView.setValue(). DDView must be constructed with a valid Store";
52457 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
52458 this.store.proxy = new Roo.data.MemoryProxy(data);
52462 /** @return {String} a parenthesised list of the ids of the Records in the View. */
52463 getValue: function() {
52465 this.store.each(function(rec) {
52466 result += rec.id + ',';
52468 return result.substr(0, result.length - 1) + ')';
52471 getIds: function() {
52472 var i = 0, result = new Array(this.store.getCount());
52473 this.store.each(function(rec) {
52474 result[i++] = rec.id;
52479 isDirty: function() {
52480 return this.isDirtyFlag;
52484 * Part of the Roo.dd.DropZone interface. If no target node is found, the
52485 * whole Element becomes the target, and this causes the drop gesture to append.
52487 getTargetFromEvent : function(e) {
52488 var target = e.getTarget();
52489 while ((target !== null) && (target.parentNode != this.el.dom)) {
52490 target = target.parentNode;
52493 target = this.el.dom.lastChild || this.el.dom;
52499 * Create the drag data which consists of an object which has the property "ddel" as
52500 * the drag proxy element.
52502 getDragData : function(e) {
52503 var target = this.findItemFromChild(e.getTarget());
52505 this.handleSelection(e);
52506 var selNodes = this.getSelectedNodes();
52509 copy: this.copy || (this.allowCopy && e.ctrlKey),
52513 var selectedIndices = this.getSelectedIndexes();
52514 for (var i = 0; i < selectedIndices.length; i++) {
52515 dragData.records.push(this.store.getAt(selectedIndices[i]));
52517 if (selNodes.length == 1) {
52518 dragData.ddel = target.cloneNode(true); // the div element
52520 var div = document.createElement('div'); // create the multi element drag "ghost"
52521 div.className = 'multi-proxy';
52522 for (var i = 0, len = selNodes.length; i < len; i++) {
52523 div.appendChild(selNodes[i].cloneNode(true));
52525 dragData.ddel = div;
52527 //console.log(dragData)
52528 //console.log(dragData.ddel.innerHTML)
52531 //console.log('nodragData')
52535 /** Specify to which ddGroup items in this DDView may be dragged. */
52536 setDraggable: function(ddGroup) {
52537 if (ddGroup instanceof Array) {
52538 Roo.each(ddGroup, this.setDraggable, this);
52541 if (this.dragZone) {
52542 this.dragZone.addToGroup(ddGroup);
52544 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
52545 containerScroll: true,
52549 // Draggability implies selection. DragZone's mousedown selects the element.
52550 if (!this.multiSelect) { this.singleSelect = true; }
52552 // Wire the DragZone's handlers up to methods in *this*
52553 this.dragZone.getDragData = this.getDragData.createDelegate(this);
52557 /** Specify from which ddGroup this DDView accepts drops. */
52558 setDroppable: function(ddGroup) {
52559 if (ddGroup instanceof Array) {
52560 Roo.each(ddGroup, this.setDroppable, this);
52563 if (this.dropZone) {
52564 this.dropZone.addToGroup(ddGroup);
52566 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
52567 containerScroll: true,
52571 // Wire the DropZone's handlers up to methods in *this*
52572 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
52573 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
52574 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
52575 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
52576 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
52580 /** Decide whether to drop above or below a View node. */
52581 getDropPoint : function(e, n, dd){
52582 if (n == this.el.dom) { return "above"; }
52583 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
52584 var c = t + (b - t) / 2;
52585 var y = Roo.lib.Event.getPageY(e);
52593 onNodeEnter : function(n, dd, e, data){
52597 onNodeOver : function(n, dd, e, data){
52598 var pt = this.getDropPoint(e, n, dd);
52599 // set the insert point style on the target node
52600 var dragElClass = this.dropNotAllowed;
52603 if (pt == "above"){
52604 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
52605 targetElClass = "x-view-drag-insert-above";
52607 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
52608 targetElClass = "x-view-drag-insert-below";
52610 if (this.lastInsertClass != targetElClass){
52611 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
52612 this.lastInsertClass = targetElClass;
52615 return dragElClass;
52618 onNodeOut : function(n, dd, e, data){
52619 this.removeDropIndicators(n);
52622 onNodeDrop : function(n, dd, e, data){
52623 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
52626 var pt = this.getDropPoint(e, n, dd);
52627 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
52628 if (pt == "below") { insertAt++; }
52629 for (var i = 0; i < data.records.length; i++) {
52630 var r = data.records[i];
52631 var dup = this.store.getById(r.id);
52632 if (dup && (dd != this.dragZone)) {
52633 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
52636 this.store.insert(insertAt++, r.copy());
52638 data.source.isDirtyFlag = true;
52640 this.store.insert(insertAt++, r);
52642 this.isDirtyFlag = true;
52645 this.dragZone.cachedTarget = null;
52649 removeDropIndicators : function(n){
52651 Roo.fly(n).removeClass([
52652 "x-view-drag-insert-above",
52653 "x-view-drag-insert-below"]);
52654 this.lastInsertClass = "_noclass";
52659 * Utility method. Add a delete option to the DDView's context menu.
52660 * @param {String} imageUrl The URL of the "delete" icon image.
52662 setDeletable: function(imageUrl) {
52663 if (!this.singleSelect && !this.multiSelect) {
52664 this.singleSelect = true;
52666 var c = this.getContextMenu();
52667 this.contextMenu.on("itemclick", function(item) {
52670 this.remove(this.getSelectedIndexes());
52674 this.contextMenu.add({
52681 /** Return the context menu for this DDView. */
52682 getContextMenu: function() {
52683 if (!this.contextMenu) {
52684 // Create the View's context menu
52685 this.contextMenu = new Roo.menu.Menu({
52686 id: this.id + "-contextmenu"
52688 this.el.on("contextmenu", this.showContextMenu, this);
52690 return this.contextMenu;
52693 disableContextMenu: function() {
52694 if (this.contextMenu) {
52695 this.el.un("contextmenu", this.showContextMenu, this);
52699 showContextMenu: function(e, item) {
52700 item = this.findItemFromChild(e.getTarget());
52703 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
52704 this.contextMenu.showAt(e.getXY());
52709 * Remove {@link Roo.data.Record}s at the specified indices.
52710 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
52712 remove: function(selectedIndices) {
52713 selectedIndices = [].concat(selectedIndices);
52714 for (var i = 0; i < selectedIndices.length; i++) {
52715 var rec = this.store.getAt(selectedIndices[i]);
52716 this.store.remove(rec);
52721 * Double click fires the event, but also, if this is draggable, and there is only one other
52722 * related DropZone, it transfers the selected node.
52724 onDblClick : function(e){
52725 var item = this.findItemFromChild(e.getTarget());
52727 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
52730 if (this.dragGroup) {
52731 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
52732 while (targets.indexOf(this.dropZone) > -1) {
52733 targets.remove(this.dropZone);
52735 if (targets.length == 1) {
52736 this.dragZone.cachedTarget = null;
52737 var el = Roo.get(targets[0].getEl());
52738 var box = el.getBox(true);
52739 targets[0].onNodeDrop(el.dom, {
52741 xy: [box.x, box.y + box.height - 1]
52742 }, null, this.getDragData(e));
52748 handleSelection: function(e) {
52749 this.dragZone.cachedTarget = null;
52750 var item = this.findItemFromChild(e.getTarget());
52752 this.clearSelections(true);
52755 if (item && (this.multiSelect || this.singleSelect)){
52756 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
52757 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
52758 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
52759 this.unselect(item);
52761 this.select(item, this.multiSelect && e.ctrlKey);
52762 this.lastSelection = item;
52767 onItemClick : function(item, index, e){
52768 if(this.fireEvent("beforeclick", this, index, item, e) === false){
52774 unselect : function(nodeInfo, suppressEvent){
52775 var node = this.getNode(nodeInfo);
52776 if(node && this.isSelected(node)){
52777 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
52778 Roo.fly(node).removeClass(this.selectedClass);
52779 this.selections.remove(node);
52780 if(!suppressEvent){
52781 this.fireEvent("selectionchange", this, this.selections);
52789 * Ext JS Library 1.1.1
52790 * Copyright(c) 2006-2007, Ext JS, LLC.
52792 * Originally Released Under LGPL - original licence link has changed is not relivant.
52795 * <script type="text/javascript">
52799 * @class Roo.LayoutManager
52800 * @extends Roo.util.Observable
52801 * Base class for layout managers.
52803 Roo.LayoutManager = function(container, config){
52804 Roo.LayoutManager.superclass.constructor.call(this);
52805 this.el = Roo.get(container);
52806 // ie scrollbar fix
52807 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
52808 document.body.scroll = "no";
52809 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
52810 this.el.position('relative');
52812 this.id = this.el.id;
52813 this.el.addClass("x-layout-container");
52814 /** false to disable window resize monitoring @type Boolean */
52815 this.monitorWindowResize = true;
52820 * Fires when a layout is performed.
52821 * @param {Roo.LayoutManager} this
52825 * @event regionresized
52826 * Fires when the user resizes a region.
52827 * @param {Roo.LayoutRegion} region The resized region
52828 * @param {Number} newSize The new size (width for east/west, height for north/south)
52830 "regionresized" : true,
52832 * @event regioncollapsed
52833 * Fires when a region is collapsed.
52834 * @param {Roo.LayoutRegion} region The collapsed region
52836 "regioncollapsed" : true,
52838 * @event regionexpanded
52839 * Fires when a region is expanded.
52840 * @param {Roo.LayoutRegion} region The expanded region
52842 "regionexpanded" : true
52844 this.updating = false;
52845 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
52848 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
52850 * Returns true if this layout is currently being updated
52851 * @return {Boolean}
52853 isUpdating : function(){
52854 return this.updating;
52858 * Suspend the LayoutManager from doing auto-layouts while
52859 * making multiple add or remove calls
52861 beginUpdate : function(){
52862 this.updating = true;
52866 * Restore auto-layouts and optionally disable the manager from performing a layout
52867 * @param {Boolean} noLayout true to disable a layout update
52869 endUpdate : function(noLayout){
52870 this.updating = false;
52876 layout: function(){
52880 onRegionResized : function(region, newSize){
52881 this.fireEvent("regionresized", region, newSize);
52885 onRegionCollapsed : function(region){
52886 this.fireEvent("regioncollapsed", region);
52889 onRegionExpanded : function(region){
52890 this.fireEvent("regionexpanded", region);
52894 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
52895 * performs box-model adjustments.
52896 * @return {Object} The size as an object {width: (the width), height: (the height)}
52898 getViewSize : function(){
52900 if(this.el.dom != document.body){
52901 size = this.el.getSize();
52903 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
52905 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
52906 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
52911 * Returns the Element this layout is bound to.
52912 * @return {Roo.Element}
52914 getEl : function(){
52919 * Returns the specified region.
52920 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
52921 * @return {Roo.LayoutRegion}
52923 getRegion : function(target){
52924 return this.regions[target.toLowerCase()];
52927 onWindowResize : function(){
52928 if(this.monitorWindowResize){
52934 * Ext JS Library 1.1.1
52935 * Copyright(c) 2006-2007, Ext JS, LLC.
52937 * Originally Released Under LGPL - original licence link has changed is not relivant.
52940 * <script type="text/javascript">
52943 * @class Roo.BorderLayout
52944 * @extends Roo.LayoutManager
52945 * @children Roo.ContentPanel
52946 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
52947 * please see: <br><br>
52948 * <a href="http://www.jackslocum.com/yui/2006/10/19/cross-browser-web-20-layouts-with-yahoo-ui/">Cross Browser Layouts - Part 1</a><br>
52949 * <a href="http://www.jackslocum.com/yui/2006/10/28/cross-browser-web-20-layouts-part-2-ajax-feed-viewer-20/">Cross Browser Layouts - Part 2</a><br><br>
52952 var layout = new Roo.BorderLayout(document.body, {
52986 preferredTabWidth: 150
52991 var CP = Roo.ContentPanel;
52993 layout.beginUpdate();
52994 layout.add("north", new CP("north", "North"));
52995 layout.add("south", new CP("south", {title: "South", closable: true}));
52996 layout.add("west", new CP("west", {title: "West"}));
52997 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
52998 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
52999 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
53000 layout.getRegion("center").showPanel("center1");
53001 layout.endUpdate();
53004 <b>The container the layout is rendered into can be either the body element or any other element.
53005 If it is not the body element, the container needs to either be an absolute positioned element,
53006 or you will need to add "position:relative" to the css of the container. You will also need to specify
53007 the container size if it is not the body element.</b>
53010 * Create a new BorderLayout
53011 * @param {String/HTMLElement/Element} container The container this layout is bound to
53012 * @param {Object} config Configuration options
53014 Roo.BorderLayout = function(container, config){
53015 config = config || {};
53016 Roo.BorderLayout.superclass.constructor.call(this, container, config);
53017 this.factory = config.factory || Roo.BorderLayout.RegionFactory;
53018 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
53019 var target = this.factory.validRegions[i];
53020 if(config[target]){
53021 this.addRegion(target, config[target]);
53026 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
53029 * @cfg {Roo.LayoutRegion} east
53032 * @cfg {Roo.LayoutRegion} west
53035 * @cfg {Roo.LayoutRegion} north
53038 * @cfg {Roo.LayoutRegion} south
53041 * @cfg {Roo.LayoutRegion} center
53044 * Creates and adds a new region if it doesn't already exist.
53045 * @param {String} target The target region key (north, south, east, west or center).
53046 * @param {Object} config The regions config object
53047 * @return {BorderLayoutRegion} The new region
53049 addRegion : function(target, config){
53050 if(!this.regions[target]){
53051 var r = this.factory.create(target, this, config);
53052 this.bindRegion(target, r);
53054 return this.regions[target];
53058 bindRegion : function(name, r){
53059 this.regions[name] = r;
53060 r.on("visibilitychange", this.layout, this);
53061 r.on("paneladded", this.layout, this);
53062 r.on("panelremoved", this.layout, this);
53063 r.on("invalidated", this.layout, this);
53064 r.on("resized", this.onRegionResized, this);
53065 r.on("collapsed", this.onRegionCollapsed, this);
53066 r.on("expanded", this.onRegionExpanded, this);
53070 * Performs a layout update.
53072 layout : function(){
53073 if(this.updating) {
53076 var size = this.getViewSize();
53077 var w = size.width;
53078 var h = size.height;
53083 //var x = 0, y = 0;
53085 var rs = this.regions;
53086 var north = rs["north"];
53087 var south = rs["south"];
53088 var west = rs["west"];
53089 var east = rs["east"];
53090 var center = rs["center"];
53091 //if(this.hideOnLayout){ // not supported anymore
53092 //c.el.setStyle("display", "none");
53094 if(north && north.isVisible()){
53095 var b = north.getBox();
53096 var m = north.getMargins();
53097 b.width = w - (m.left+m.right);
53100 centerY = b.height + b.y + m.bottom;
53101 centerH -= centerY;
53102 north.updateBox(this.safeBox(b));
53104 if(south && south.isVisible()){
53105 var b = south.getBox();
53106 var m = south.getMargins();
53107 b.width = w - (m.left+m.right);
53109 var totalHeight = (b.height + m.top + m.bottom);
53110 b.y = h - totalHeight + m.top;
53111 centerH -= totalHeight;
53112 south.updateBox(this.safeBox(b));
53114 if(west && west.isVisible()){
53115 var b = west.getBox();
53116 var m = west.getMargins();
53117 b.height = centerH - (m.top+m.bottom);
53119 b.y = centerY + m.top;
53120 var totalWidth = (b.width + m.left + m.right);
53121 centerX += totalWidth;
53122 centerW -= totalWidth;
53123 west.updateBox(this.safeBox(b));
53125 if(east && east.isVisible()){
53126 var b = east.getBox();
53127 var m = east.getMargins();
53128 b.height = centerH - (m.top+m.bottom);
53129 var totalWidth = (b.width + m.left + m.right);
53130 b.x = w - totalWidth + m.left;
53131 b.y = centerY + m.top;
53132 centerW -= totalWidth;
53133 east.updateBox(this.safeBox(b));
53136 var m = center.getMargins();
53138 x: centerX + m.left,
53139 y: centerY + m.top,
53140 width: centerW - (m.left+m.right),
53141 height: centerH - (m.top+m.bottom)
53143 //if(this.hideOnLayout){
53144 //center.el.setStyle("display", "block");
53146 center.updateBox(this.safeBox(centerBox));
53149 this.fireEvent("layout", this);
53153 safeBox : function(box){
53154 box.width = Math.max(0, box.width);
53155 box.height = Math.max(0, box.height);
53160 * Adds a ContentPanel (or subclass) to this layout.
53161 * @param {String} target The target region key (north, south, east, west or center).
53162 * @param {Roo.ContentPanel} panel The panel to add
53163 * @return {Roo.ContentPanel} The added panel
53165 add : function(target, panel){
53167 target = target.toLowerCase();
53168 return this.regions[target].add(panel);
53172 * Remove a ContentPanel (or subclass) to this layout.
53173 * @param {String} target The target region key (north, south, east, west or center).
53174 * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
53175 * @return {Roo.ContentPanel} The removed panel
53177 remove : function(target, panel){
53178 target = target.toLowerCase();
53179 return this.regions[target].remove(panel);
53183 * Searches all regions for a panel with the specified id
53184 * @param {String} panelId
53185 * @return {Roo.ContentPanel} The panel or null if it wasn't found
53187 findPanel : function(panelId){
53188 var rs = this.regions;
53189 for(var target in rs){
53190 if(typeof rs[target] != "function"){
53191 var p = rs[target].getPanel(panelId);
53201 * Searches all regions for a panel with the specified id and activates (shows) it.
53202 * @param {String/ContentPanel} panelId The panels id or the panel itself
53203 * @return {Roo.ContentPanel} The shown panel or null
53205 showPanel : function(panelId) {
53206 var rs = this.regions;
53207 for(var target in rs){
53208 var r = rs[target];
53209 if(typeof r != "function"){
53210 if(r.hasPanel(panelId)){
53211 return r.showPanel(panelId);
53219 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
53220 * @param {Roo.state.Provider} provider (optional) An alternate state provider
53222 restoreState : function(provider){
53224 provider = Roo.state.Manager;
53226 var sm = new Roo.LayoutStateManager();
53227 sm.init(this, provider);
53231 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
53232 * object should contain properties for each region to add ContentPanels to, and each property's value should be
53233 * a valid ContentPanel config object. Example:
53235 // Create the main layout
53236 var layout = new Roo.BorderLayout('main-ct', {
53247 // Create and add multiple ContentPanels at once via configs
53250 id: 'source-files',
53252 title:'Ext Source Files',
53265 * @param {Object} regions An object containing ContentPanel configs by region name
53267 batchAdd : function(regions){
53268 this.beginUpdate();
53269 for(var rname in regions){
53270 var lr = this.regions[rname];
53272 this.addTypedPanels(lr, regions[rname]);
53279 addTypedPanels : function(lr, ps){
53280 if(typeof ps == 'string'){
53281 lr.add(new Roo.ContentPanel(ps));
53283 else if(ps instanceof Array){
53284 for(var i =0, len = ps.length; i < len; i++){
53285 this.addTypedPanels(lr, ps[i]);
53288 else if(!ps.events){ // raw config?
53290 delete ps.el; // prevent conflict
53291 lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
53293 else { // panel object assumed!
53298 * Adds a xtype elements to the layout.
53302 xtype : 'ContentPanel',
53309 xtype : 'NestedLayoutPanel',
53315 items : [ ... list of content panels or nested layout panels.. ]
53319 * @param {Object} cfg Xtype definition of item to add.
53321 addxtype : function(cfg)
53323 // basically accepts a pannel...
53324 // can accept a layout region..!?!?
53325 //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
53327 if (!cfg.xtype.match(/Panel$/)) {
53332 if (typeof(cfg.region) == 'undefined') {
53333 Roo.log("Failed to add Panel, region was not set");
53337 var region = cfg.region;
53343 xitems = cfg.items;
53350 case 'ContentPanel': // ContentPanel (el, cfg)
53351 case 'ScrollPanel': // ContentPanel (el, cfg)
53353 if(cfg.autoCreate) {
53354 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
53356 var el = this.el.createChild();
53357 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
53360 this.add(region, ret);
53364 case 'TreePanel': // our new panel!
53365 cfg.el = this.el.createChild();
53366 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
53367 this.add(region, ret);
53370 case 'NestedLayoutPanel':
53371 // create a new Layout (which is a Border Layout...
53372 var el = this.el.createChild();
53373 var clayout = cfg.layout;
53375 clayout.items = clayout.items || [];
53376 // replace this exitems with the clayout ones..
53377 xitems = clayout.items;
53380 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
53381 cfg.background = false;
53383 var layout = new Roo.BorderLayout(el, clayout);
53385 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
53386 //console.log('adding nested layout panel ' + cfg.toSource());
53387 this.add(region, ret);
53388 nb = {}; /// find first...
53393 // needs grid and region
53395 //var el = this.getRegion(region).el.createChild();
53396 var el = this.el.createChild();
53397 // create the grid first...
53399 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
53401 if (region == 'center' && this.active ) {
53402 cfg.background = false;
53404 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
53406 this.add(region, ret);
53407 if (cfg.background) {
53408 ret.on('activate', function(gp) {
53409 if (!gp.grid.rendered) {
53424 if (typeof(Roo[cfg.xtype]) != 'undefined') {
53426 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
53427 this.add(region, ret);
53430 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
53434 // GridPanel (grid, cfg)
53437 this.beginUpdate();
53441 Roo.each(xitems, function(i) {
53442 region = nb && i.region ? i.region : false;
53444 var add = ret.addxtype(i);
53447 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
53448 if (!i.background) {
53449 abn[region] = nb[region] ;
53456 // make the last non-background panel active..
53457 //if (nb) { Roo.log(abn); }
53460 for(var r in abn) {
53461 region = this.getRegion(r);
53463 // tried using nb[r], but it does not work..
53465 region.showPanel(abn[r]);
53476 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
53477 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
53478 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
53479 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
53482 var CP = Roo.ContentPanel;
53484 var layout = Roo.BorderLayout.create({
53488 panels: [new CP("north", "North")]
53497 panels: [new CP("west", {title: "West"})]
53506 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
53515 panels: [new CP("south", {title: "South", closable: true})]
53522 preferredTabWidth: 150,
53524 new CP("center1", {title: "Close Me", closable: true}),
53525 new CP("center2", {title: "Center Panel", closable: false})
53530 layout.getRegion("center").showPanel("center1");
53535 Roo.BorderLayout.create = function(config, targetEl){
53536 var layout = new Roo.BorderLayout(targetEl || document.body, config);
53537 layout.beginUpdate();
53538 var regions = Roo.BorderLayout.RegionFactory.validRegions;
53539 for(var j = 0, jlen = regions.length; j < jlen; j++){
53540 var lr = regions[j];
53541 if(layout.regions[lr] && config[lr].panels){
53542 var r = layout.regions[lr];
53543 var ps = config[lr].panels;
53544 layout.addTypedPanels(r, ps);
53547 layout.endUpdate();
53552 Roo.BorderLayout.RegionFactory = {
53554 validRegions : ["north","south","east","west","center"],
53557 create : function(target, mgr, config){
53558 target = target.toLowerCase();
53559 if(config.lightweight || config.basic){
53560 return new Roo.BasicLayoutRegion(mgr, config, target);
53564 return new Roo.NorthLayoutRegion(mgr, config);
53566 return new Roo.SouthLayoutRegion(mgr, config);
53568 return new Roo.EastLayoutRegion(mgr, config);
53570 return new Roo.WestLayoutRegion(mgr, config);
53572 return new Roo.CenterLayoutRegion(mgr, config);
53574 throw 'Layout region "'+target+'" not supported.';
53578 * Ext JS Library 1.1.1
53579 * Copyright(c) 2006-2007, Ext JS, LLC.
53581 * Originally Released Under LGPL - original licence link has changed is not relivant.
53584 * <script type="text/javascript">
53588 * @class Roo.BasicLayoutRegion
53589 * @extends Roo.util.Observable
53590 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
53591 * and does not have a titlebar, tabs or any other features. All it does is size and position
53592 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
53594 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
53596 this.position = pos;
53599 * @scope Roo.BasicLayoutRegion
53603 * @event beforeremove
53604 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
53605 * @param {Roo.LayoutRegion} this
53606 * @param {Roo.ContentPanel} panel The panel
53607 * @param {Object} e The cancel event object
53609 "beforeremove" : true,
53611 * @event invalidated
53612 * Fires when the layout for this region is changed.
53613 * @param {Roo.LayoutRegion} this
53615 "invalidated" : true,
53617 * @event visibilitychange
53618 * Fires when this region is shown or hidden
53619 * @param {Roo.LayoutRegion} this
53620 * @param {Boolean} visibility true or false
53622 "visibilitychange" : true,
53624 * @event paneladded
53625 * Fires when a panel is added.
53626 * @param {Roo.LayoutRegion} this
53627 * @param {Roo.ContentPanel} panel The panel
53629 "paneladded" : true,
53631 * @event panelremoved
53632 * Fires when a panel is removed.
53633 * @param {Roo.LayoutRegion} this
53634 * @param {Roo.ContentPanel} panel The panel
53636 "panelremoved" : true,
53638 * @event beforecollapse
53639 * Fires when this region before collapse.
53640 * @param {Roo.LayoutRegion} this
53642 "beforecollapse" : true,
53645 * Fires when this region is collapsed.
53646 * @param {Roo.LayoutRegion} this
53648 "collapsed" : true,
53651 * Fires when this region is expanded.
53652 * @param {Roo.LayoutRegion} this
53657 * Fires when this region is slid into view.
53658 * @param {Roo.LayoutRegion} this
53660 "slideshow" : true,
53663 * Fires when this region slides out of view.
53664 * @param {Roo.LayoutRegion} this
53666 "slidehide" : true,
53668 * @event panelactivated
53669 * Fires when a panel is activated.
53670 * @param {Roo.LayoutRegion} this
53671 * @param {Roo.ContentPanel} panel The activated panel
53673 "panelactivated" : true,
53676 * Fires when the user resizes this region.
53677 * @param {Roo.LayoutRegion} this
53678 * @param {Number} newSize The new size (width for east/west, height for north/south)
53682 /** A collection of panels in this region. @type Roo.util.MixedCollection */
53683 this.panels = new Roo.util.MixedCollection();
53684 this.panels.getKey = this.getPanelId.createDelegate(this);
53686 this.activePanel = null;
53687 // ensure listeners are added...
53689 if (config.listeners || config.events) {
53690 Roo.BasicLayoutRegion.superclass.constructor.call(this, {
53691 listeners : config.listeners || {},
53692 events : config.events || {}
53696 if(skipConfig !== true){
53697 this.applyConfig(config);
53701 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
53702 getPanelId : function(p){
53706 applyConfig : function(config){
53707 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
53708 this.config = config;
53713 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
53714 * the width, for horizontal (north, south) the height.
53715 * @param {Number} newSize The new width or height
53717 resizeTo : function(newSize){
53718 var el = this.el ? this.el :
53719 (this.activePanel ? this.activePanel.getEl() : null);
53721 switch(this.position){
53724 el.setWidth(newSize);
53725 this.fireEvent("resized", this, newSize);
53729 el.setHeight(newSize);
53730 this.fireEvent("resized", this, newSize);
53736 getBox : function(){
53737 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
53740 getMargins : function(){
53741 return this.margins;
53744 updateBox : function(box){
53746 var el = this.activePanel.getEl();
53747 el.dom.style.left = box.x + "px";
53748 el.dom.style.top = box.y + "px";
53749 this.activePanel.setSize(box.width, box.height);
53753 * Returns the container element for this region.
53754 * @return {Roo.Element}
53756 getEl : function(){
53757 return this.activePanel;
53761 * Returns true if this region is currently visible.
53762 * @return {Boolean}
53764 isVisible : function(){
53765 return this.activePanel ? true : false;
53768 setActivePanel : function(panel){
53769 panel = this.getPanel(panel);
53770 if(this.activePanel && this.activePanel != panel){
53771 this.activePanel.setActiveState(false);
53772 this.activePanel.getEl().setLeftTop(-10000,-10000);
53774 this.activePanel = panel;
53775 panel.setActiveState(true);
53777 panel.setSize(this.box.width, this.box.height);
53779 this.fireEvent("panelactivated", this, panel);
53780 this.fireEvent("invalidated");
53784 * Show the specified panel.
53785 * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
53786 * @return {Roo.ContentPanel} The shown panel or null
53788 showPanel : function(panel){
53789 if(panel = this.getPanel(panel)){
53790 this.setActivePanel(panel);
53796 * Get the active panel for this region.
53797 * @return {Roo.ContentPanel} The active panel or null
53799 getActivePanel : function(){
53800 return this.activePanel;
53804 * Add the passed ContentPanel(s)
53805 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
53806 * @return {Roo.ContentPanel} The panel added (if only one was added)
53808 add : function(panel){
53809 if(arguments.length > 1){
53810 for(var i = 0, len = arguments.length; i < len; i++) {
53811 this.add(arguments[i]);
53815 if(this.hasPanel(panel)){
53816 this.showPanel(panel);
53819 var el = panel.getEl();
53820 if(el.dom.parentNode != this.mgr.el.dom){
53821 this.mgr.el.dom.appendChild(el.dom);
53823 if(panel.setRegion){
53824 panel.setRegion(this);
53826 this.panels.add(panel);
53827 el.setStyle("position", "absolute");
53828 if(!panel.background){
53829 this.setActivePanel(panel);
53830 if(this.config.initialSize && this.panels.getCount()==1){
53831 this.resizeTo(this.config.initialSize);
53834 this.fireEvent("paneladded", this, panel);
53839 * Returns true if the panel is in this region.
53840 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
53841 * @return {Boolean}
53843 hasPanel : function(panel){
53844 if(typeof panel == "object"){ // must be panel obj
53845 panel = panel.getId();
53847 return this.getPanel(panel) ? true : false;
53851 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
53852 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
53853 * @param {Boolean} preservePanel Overrides the config preservePanel option
53854 * @return {Roo.ContentPanel} The panel that was removed
53856 remove : function(panel, preservePanel){
53857 panel = this.getPanel(panel);
53862 this.fireEvent("beforeremove", this, panel, e);
53863 if(e.cancel === true){
53866 var panelId = panel.getId();
53867 this.panels.removeKey(panelId);
53872 * Returns the panel specified or null if it's not in this region.
53873 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
53874 * @return {Roo.ContentPanel}
53876 getPanel : function(id){
53877 if(typeof id == "object"){ // must be panel obj
53880 return this.panels.get(id);
53884 * Returns this regions position (north/south/east/west/center).
53887 getPosition: function(){
53888 return this.position;
53892 * Ext JS Library 1.1.1
53893 * Copyright(c) 2006-2007, Ext JS, LLC.
53895 * Originally Released Under LGPL - original licence link has changed is not relivant.
53898 * <script type="text/javascript">
53902 * @class Roo.LayoutRegion
53903 * @extends Roo.BasicLayoutRegion
53904 * This class represents a region in a layout manager.
53905 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
53906 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
53907 * @cfg {Boolean} floatable False to disable floating (defaults to true)
53908 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
53909 * @cfg {Object} cmargins Margins for the element when collapsed (defaults to: north/south {top: 2, left: 0, right:0, bottom: 2} or east/west {top: 0, left: 2, right:2, bottom: 0})
53910 * @cfg {String} tabPosition (top|bottom) "top" or "bottom" (defaults to "bottom")
53911 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
53912 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
53913 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
53914 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
53915 * @cfg {String} title The title for the region (overrides panel titles)
53916 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
53917 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
53918 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
53919 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
53920 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
53921 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
53922 * the space available, similar to FireFox 1.5 tabs (defaults to false)
53923 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
53924 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
53925 * @cfg {Boolean} showPin True to show a pin button
53926 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
53927 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
53928 * @cfg {Boolean} disableTabTips True to disable tab tooltips
53929 * @cfg {Number} width For East/West panels
53930 * @cfg {Number} height For North/South panels
53931 * @cfg {Boolean} split To show the splitter
53932 * @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
53934 Roo.LayoutRegion = function(mgr, config, pos){
53935 Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
53936 var dh = Roo.DomHelper;
53937 /** This region's container element
53938 * @type Roo.Element */
53939 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
53940 /** This region's title element
53941 * @type Roo.Element */
53943 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
53944 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
53945 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
53947 this.titleEl.enableDisplayMode();
53948 /** This region's title text element
53949 * @type HTMLElement */
53950 this.titleTextEl = this.titleEl.dom.firstChild;
53951 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
53952 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
53953 this.closeBtn.enableDisplayMode();
53954 this.closeBtn.on("click", this.closeClicked, this);
53955 this.closeBtn.hide();
53957 this.createBody(config);
53958 this.visible = true;
53959 this.collapsed = false;
53961 if(config.hideWhenEmpty){
53963 this.on("paneladded", this.validateVisibility, this);
53964 this.on("panelremoved", this.validateVisibility, this);
53966 this.applyConfig(config);
53969 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
53971 createBody : function(){
53972 /** This region's body element
53973 * @type Roo.Element */
53974 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
53977 applyConfig : function(c){
53978 if(c.collapsible && this.position != "center" && !this.collapsedEl){
53979 var dh = Roo.DomHelper;
53980 if(c.titlebar !== false){
53981 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
53982 this.collapseBtn.on("click", this.collapse, this);
53983 this.collapseBtn.enableDisplayMode();
53985 if(c.showPin === true || this.showPin){
53986 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
53987 this.stickBtn.enableDisplayMode();
53988 this.stickBtn.on("click", this.expand, this);
53989 this.stickBtn.hide();
53992 /** This region's collapsed element
53993 * @type Roo.Element */
53994 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
53995 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
53997 if(c.floatable !== false){
53998 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
53999 this.collapsedEl.on("click", this.collapseClick, this);
54002 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
54003 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
54004 id: "message", unselectable: "on", style:{"float":"left"}});
54005 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
54007 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
54008 this.expandBtn.on("click", this.expand, this);
54010 if(this.collapseBtn){
54011 this.collapseBtn.setVisible(c.collapsible == true);
54013 this.cmargins = c.cmargins || this.cmargins ||
54014 (this.position == "west" || this.position == "east" ?
54015 {top: 0, left: 2, right:2, bottom: 0} :
54016 {top: 2, left: 0, right:0, bottom: 2});
54017 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
54018 this.bottomTabs = c.tabPosition != "top";
54019 this.autoScroll = c.autoScroll || false;
54020 if(this.autoScroll){
54021 this.bodyEl.setStyle("overflow", "auto");
54023 this.bodyEl.setStyle("overflow", "hidden");
54025 //if(c.titlebar !== false){
54026 if((!c.titlebar && !c.title) || c.titlebar === false){
54027 this.titleEl.hide();
54029 this.titleEl.show();
54031 this.titleTextEl.innerHTML = c.title;
54035 this.duration = c.duration || .30;
54036 this.slideDuration = c.slideDuration || .45;
54039 this.collapse(true);
54046 * Returns true if this region is currently visible.
54047 * @return {Boolean}
54049 isVisible : function(){
54050 return this.visible;
54054 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
54055 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
54057 setCollapsedTitle : function(title){
54058 title = title || " ";
54059 if(this.collapsedTitleTextEl){
54060 this.collapsedTitleTextEl.innerHTML = title;
54064 getBox : function(){
54066 if(!this.collapsed){
54067 b = this.el.getBox(false, true);
54069 b = this.collapsedEl.getBox(false, true);
54074 getMargins : function(){
54075 return this.collapsed ? this.cmargins : this.margins;
54078 highlight : function(){
54079 this.el.addClass("x-layout-panel-dragover");
54082 unhighlight : function(){
54083 this.el.removeClass("x-layout-panel-dragover");
54086 updateBox : function(box){
54088 if(!this.collapsed){
54089 this.el.dom.style.left = box.x + "px";
54090 this.el.dom.style.top = box.y + "px";
54091 this.updateBody(box.width, box.height);
54093 this.collapsedEl.dom.style.left = box.x + "px";
54094 this.collapsedEl.dom.style.top = box.y + "px";
54095 this.collapsedEl.setSize(box.width, box.height);
54098 this.tabs.autoSizeTabs();
54102 updateBody : function(w, h){
54104 this.el.setWidth(w);
54105 w -= this.el.getBorderWidth("rl");
54106 if(this.config.adjustments){
54107 w += this.config.adjustments[0];
54111 this.el.setHeight(h);
54112 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
54113 h -= this.el.getBorderWidth("tb");
54114 if(this.config.adjustments){
54115 h += this.config.adjustments[1];
54117 this.bodyEl.setHeight(h);
54119 h = this.tabs.syncHeight(h);
54122 if(this.panelSize){
54123 w = w !== null ? w : this.panelSize.width;
54124 h = h !== null ? h : this.panelSize.height;
54126 if(this.activePanel){
54127 var el = this.activePanel.getEl();
54128 w = w !== null ? w : el.getWidth();
54129 h = h !== null ? h : el.getHeight();
54130 this.panelSize = {width: w, height: h};
54131 this.activePanel.setSize(w, h);
54133 if(Roo.isIE && this.tabs){
54134 this.tabs.el.repaint();
54139 * Returns the container element for this region.
54140 * @return {Roo.Element}
54142 getEl : function(){
54147 * Hides this region.
54150 if(!this.collapsed){
54151 this.el.dom.style.left = "-2000px";
54154 this.collapsedEl.dom.style.left = "-2000px";
54155 this.collapsedEl.hide();
54157 this.visible = false;
54158 this.fireEvent("visibilitychange", this, false);
54162 * Shows this region if it was previously hidden.
54165 if(!this.collapsed){
54168 this.collapsedEl.show();
54170 this.visible = true;
54171 this.fireEvent("visibilitychange", this, true);
54174 closeClicked : function(){
54175 if(this.activePanel){
54176 this.remove(this.activePanel);
54180 collapseClick : function(e){
54182 e.stopPropagation();
54185 e.stopPropagation();
54191 * Collapses this region.
54192 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
54194 collapse : function(skipAnim, skipCheck){
54195 if(this.collapsed) {
54199 if(skipCheck || this.fireEvent("beforecollapse", this) != false){
54201 this.collapsed = true;
54203 this.split.el.hide();
54205 if(this.config.animate && skipAnim !== true){
54206 this.fireEvent("invalidated", this);
54207 this.animateCollapse();
54209 this.el.setLocation(-20000,-20000);
54211 this.collapsedEl.show();
54212 this.fireEvent("collapsed", this);
54213 this.fireEvent("invalidated", this);
54219 animateCollapse : function(){
54224 * Expands this region if it was previously collapsed.
54225 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
54226 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
54228 expand : function(e, skipAnim){
54230 e.stopPropagation();
54232 if(!this.collapsed || this.el.hasActiveFx()) {
54236 this.afterSlideIn();
54239 this.collapsed = false;
54240 if(this.config.animate && skipAnim !== true){
54241 this.animateExpand();
54245 this.split.el.show();
54247 this.collapsedEl.setLocation(-2000,-2000);
54248 this.collapsedEl.hide();
54249 this.fireEvent("invalidated", this);
54250 this.fireEvent("expanded", this);
54254 animateExpand : function(){
54258 initTabs : function()
54260 this.bodyEl.setStyle("overflow", "hidden");
54261 var ts = new Roo.TabPanel(
54264 tabPosition: this.bottomTabs ? 'bottom' : 'top',
54265 disableTooltips: this.config.disableTabTips,
54266 toolbar : this.config.toolbar
54269 if(this.config.hideTabs){
54270 ts.stripWrap.setDisplayed(false);
54273 ts.resizeTabs = this.config.resizeTabs === true;
54274 ts.minTabWidth = this.config.minTabWidth || 40;
54275 ts.maxTabWidth = this.config.maxTabWidth || 250;
54276 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
54277 ts.monitorResize = false;
54278 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
54279 ts.bodyEl.addClass('x-layout-tabs-body');
54280 this.panels.each(this.initPanelAsTab, this);
54283 initPanelAsTab : function(panel){
54284 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
54285 this.config.closeOnTab && panel.isClosable());
54286 if(panel.tabTip !== undefined){
54287 ti.setTooltip(panel.tabTip);
54289 ti.on("activate", function(){
54290 this.setActivePanel(panel);
54292 if(this.config.closeOnTab){
54293 ti.on("beforeclose", function(t, e){
54295 this.remove(panel);
54301 updatePanelTitle : function(panel, title){
54302 if(this.activePanel == panel){
54303 this.updateTitle(title);
54306 var ti = this.tabs.getTab(panel.getEl().id);
54308 if(panel.tabTip !== undefined){
54309 ti.setTooltip(panel.tabTip);
54314 updateTitle : function(title){
54315 if(this.titleTextEl && !this.config.title){
54316 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
54320 setActivePanel : function(panel){
54321 panel = this.getPanel(panel);
54322 if(this.activePanel && this.activePanel != panel){
54323 this.activePanel.setActiveState(false);
54325 this.activePanel = panel;
54326 panel.setActiveState(true);
54327 if(this.panelSize){
54328 panel.setSize(this.panelSize.width, this.panelSize.height);
54331 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
54333 this.updateTitle(panel.getTitle());
54335 this.fireEvent("invalidated", this);
54337 this.fireEvent("panelactivated", this, panel);
54341 * Shows the specified panel.
54342 * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
54343 * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
54345 showPanel : function(panel)
54347 panel = this.getPanel(panel);
54350 var tab = this.tabs.getTab(panel.getEl().id);
54351 if(tab.isHidden()){
54352 this.tabs.unhideTab(tab.id);
54356 this.setActivePanel(panel);
54363 * Get the active panel for this region.
54364 * @return {Roo.ContentPanel} The active panel or null
54366 getActivePanel : function(){
54367 return this.activePanel;
54370 validateVisibility : function(){
54371 if(this.panels.getCount() < 1){
54372 this.updateTitle(" ");
54373 this.closeBtn.hide();
54376 if(!this.isVisible()){
54383 * Adds the passed ContentPanel(s) to this region.
54384 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
54385 * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
54387 add : function(panel){
54388 if(arguments.length > 1){
54389 for(var i = 0, len = arguments.length; i < len; i++) {
54390 this.add(arguments[i]);
54394 if(this.hasPanel(panel)){
54395 this.showPanel(panel);
54398 panel.setRegion(this);
54399 this.panels.add(panel);
54400 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
54401 this.bodyEl.dom.appendChild(panel.getEl().dom);
54402 if(panel.background !== true){
54403 this.setActivePanel(panel);
54405 this.fireEvent("paneladded", this, panel);
54411 this.initPanelAsTab(panel);
54413 if(panel.background !== true){
54414 this.tabs.activate(panel.getEl().id);
54416 this.fireEvent("paneladded", this, panel);
54421 * Hides the tab for the specified panel.
54422 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
54424 hidePanel : function(panel){
54425 if(this.tabs && (panel = this.getPanel(panel))){
54426 this.tabs.hideTab(panel.getEl().id);
54431 * Unhides the tab for a previously hidden panel.
54432 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
54434 unhidePanel : function(panel){
54435 if(this.tabs && (panel = this.getPanel(panel))){
54436 this.tabs.unhideTab(panel.getEl().id);
54440 clearPanels : function(){
54441 while(this.panels.getCount() > 0){
54442 this.remove(this.panels.first());
54447 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
54448 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
54449 * @param {Boolean} preservePanel Overrides the config preservePanel option
54450 * @return {Roo.ContentPanel} The panel that was removed
54452 remove : function(panel, preservePanel){
54453 panel = this.getPanel(panel);
54458 this.fireEvent("beforeremove", this, panel, e);
54459 if(e.cancel === true){
54462 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
54463 var panelId = panel.getId();
54464 this.panels.removeKey(panelId);
54466 document.body.appendChild(panel.getEl().dom);
54469 this.tabs.removeTab(panel.getEl().id);
54470 }else if (!preservePanel){
54471 this.bodyEl.dom.removeChild(panel.getEl().dom);
54473 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
54474 var p = this.panels.first();
54475 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
54476 tempEl.appendChild(p.getEl().dom);
54477 this.bodyEl.update("");
54478 this.bodyEl.dom.appendChild(p.getEl().dom);
54480 this.updateTitle(p.getTitle());
54482 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
54483 this.setActivePanel(p);
54485 panel.setRegion(null);
54486 if(this.activePanel == panel){
54487 this.activePanel = null;
54489 if(this.config.autoDestroy !== false && preservePanel !== true){
54490 try{panel.destroy();}catch(e){}
54492 this.fireEvent("panelremoved", this, panel);
54497 * Returns the TabPanel component used by this region
54498 * @return {Roo.TabPanel}
54500 getTabs : function(){
54504 createTool : function(parentEl, className){
54505 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
54506 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
54507 btn.addClassOnOver("x-layout-tools-button-over");
54512 * Ext JS Library 1.1.1
54513 * Copyright(c) 2006-2007, Ext JS, LLC.
54515 * Originally Released Under LGPL - original licence link has changed is not relivant.
54518 * <script type="text/javascript">
54524 * @class Roo.SplitLayoutRegion
54525 * @extends Roo.LayoutRegion
54526 * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
54528 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
54529 this.cursor = cursor;
54530 Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
54533 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
54534 splitTip : "Drag to resize.",
54535 collapsibleSplitTip : "Drag to resize. Double click to hide.",
54536 useSplitTips : false,
54538 applyConfig : function(config){
54539 Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
54542 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
54543 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
54544 /** The SplitBar for this region
54545 * @type Roo.SplitBar */
54546 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
54547 this.split.on("moved", this.onSplitMove, this);
54548 this.split.useShim = config.useShim === true;
54549 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
54550 if(this.useSplitTips){
54551 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
54553 if(config.collapsible){
54554 this.split.el.on("dblclick", this.collapse, this);
54557 if(typeof config.minSize != "undefined"){
54558 this.split.minSize = config.minSize;
54560 if(typeof config.maxSize != "undefined"){
54561 this.split.maxSize = config.maxSize;
54563 if(config.hideWhenEmpty || config.hidden || config.collapsed){
54564 this.hideSplitter();
54569 getHMaxSize : function(){
54570 var cmax = this.config.maxSize || 10000;
54571 var center = this.mgr.getRegion("center");
54572 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
54575 getVMaxSize : function(){
54576 var cmax = this.config.maxSize || 10000;
54577 var center = this.mgr.getRegion("center");
54578 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
54581 onSplitMove : function(split, newSize){
54582 this.fireEvent("resized", this, newSize);
54586 * Returns the {@link Roo.SplitBar} for this region.
54587 * @return {Roo.SplitBar}
54589 getSplitBar : function(){
54594 this.hideSplitter();
54595 Roo.SplitLayoutRegion.superclass.hide.call(this);
54598 hideSplitter : function(){
54600 this.split.el.setLocation(-2000,-2000);
54601 this.split.el.hide();
54607 this.split.el.show();
54609 Roo.SplitLayoutRegion.superclass.show.call(this);
54612 beforeSlide: function(){
54613 if(Roo.isGecko){// firefox overflow auto bug workaround
54614 this.bodyEl.clip();
54616 this.tabs.bodyEl.clip();
54618 if(this.activePanel){
54619 this.activePanel.getEl().clip();
54621 if(this.activePanel.beforeSlide){
54622 this.activePanel.beforeSlide();
54628 afterSlide : function(){
54629 if(Roo.isGecko){// firefox overflow auto bug workaround
54630 this.bodyEl.unclip();
54632 this.tabs.bodyEl.unclip();
54634 if(this.activePanel){
54635 this.activePanel.getEl().unclip();
54636 if(this.activePanel.afterSlide){
54637 this.activePanel.afterSlide();
54643 initAutoHide : function(){
54644 if(this.autoHide !== false){
54645 if(!this.autoHideHd){
54646 var st = new Roo.util.DelayedTask(this.slideIn, this);
54647 this.autoHideHd = {
54648 "mouseout": function(e){
54649 if(!e.within(this.el, true)){
54653 "mouseover" : function(e){
54659 this.el.on(this.autoHideHd);
54663 clearAutoHide : function(){
54664 if(this.autoHide !== false){
54665 this.el.un("mouseout", this.autoHideHd.mouseout);
54666 this.el.un("mouseover", this.autoHideHd.mouseover);
54670 clearMonitor : function(){
54671 Roo.get(document).un("click", this.slideInIf, this);
54674 // these names are backwards but not changed for compat
54675 slideOut : function(){
54676 if(this.isSlid || this.el.hasActiveFx()){
54679 this.isSlid = true;
54680 if(this.collapseBtn){
54681 this.collapseBtn.hide();
54683 this.closeBtnState = this.closeBtn.getStyle('display');
54684 this.closeBtn.hide();
54686 this.stickBtn.show();
54689 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
54690 this.beforeSlide();
54691 this.el.setStyle("z-index", 10001);
54692 this.el.slideIn(this.getSlideAnchor(), {
54693 callback: function(){
54695 this.initAutoHide();
54696 Roo.get(document).on("click", this.slideInIf, this);
54697 this.fireEvent("slideshow", this);
54704 afterSlideIn : function(){
54705 this.clearAutoHide();
54706 this.isSlid = false;
54707 this.clearMonitor();
54708 this.el.setStyle("z-index", "");
54709 if(this.collapseBtn){
54710 this.collapseBtn.show();
54712 this.closeBtn.setStyle('display', this.closeBtnState);
54714 this.stickBtn.hide();
54716 this.fireEvent("slidehide", this);
54719 slideIn : function(cb){
54720 if(!this.isSlid || this.el.hasActiveFx()){
54724 this.isSlid = false;
54725 this.beforeSlide();
54726 this.el.slideOut(this.getSlideAnchor(), {
54727 callback: function(){
54728 this.el.setLeftTop(-10000, -10000);
54730 this.afterSlideIn();
54738 slideInIf : function(e){
54739 if(!e.within(this.el)){
54744 animateCollapse : function(){
54745 this.beforeSlide();
54746 this.el.setStyle("z-index", 20000);
54747 var anchor = this.getSlideAnchor();
54748 this.el.slideOut(anchor, {
54749 callback : function(){
54750 this.el.setStyle("z-index", "");
54751 this.collapsedEl.slideIn(anchor, {duration:.3});
54753 this.el.setLocation(-10000,-10000);
54755 this.fireEvent("collapsed", this);
54762 animateExpand : function(){
54763 this.beforeSlide();
54764 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
54765 this.el.setStyle("z-index", 20000);
54766 this.collapsedEl.hide({
54769 this.el.slideIn(this.getSlideAnchor(), {
54770 callback : function(){
54771 this.el.setStyle("z-index", "");
54774 this.split.el.show();
54776 this.fireEvent("invalidated", this);
54777 this.fireEvent("expanded", this);
54805 getAnchor : function(){
54806 return this.anchors[this.position];
54809 getCollapseAnchor : function(){
54810 return this.canchors[this.position];
54813 getSlideAnchor : function(){
54814 return this.sanchors[this.position];
54817 getAlignAdj : function(){
54818 var cm = this.cmargins;
54819 switch(this.position){
54835 getExpandAdj : function(){
54836 var c = this.collapsedEl, cm = this.cmargins;
54837 switch(this.position){
54839 return [-(cm.right+c.getWidth()+cm.left), 0];
54842 return [cm.right+c.getWidth()+cm.left, 0];
54845 return [0, -(cm.top+cm.bottom+c.getHeight())];
54848 return [0, cm.top+cm.bottom+c.getHeight()];
54854 * Ext JS Library 1.1.1
54855 * Copyright(c) 2006-2007, Ext JS, LLC.
54857 * Originally Released Under LGPL - original licence link has changed is not relivant.
54860 * <script type="text/javascript">
54863 * These classes are private internal classes
54865 Roo.CenterLayoutRegion = function(mgr, config){
54866 Roo.LayoutRegion.call(this, mgr, config, "center");
54867 this.visible = true;
54868 this.minWidth = config.minWidth || 20;
54869 this.minHeight = config.minHeight || 20;
54872 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
54874 // center panel can't be hidden
54878 // center panel can't be hidden
54881 getMinWidth: function(){
54882 return this.minWidth;
54885 getMinHeight: function(){
54886 return this.minHeight;
54891 Roo.NorthLayoutRegion = function(mgr, config){
54892 Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
54894 this.split.placement = Roo.SplitBar.TOP;
54895 this.split.orientation = Roo.SplitBar.VERTICAL;
54896 this.split.el.addClass("x-layout-split-v");
54898 var size = config.initialSize || config.height;
54899 if(typeof size != "undefined"){
54900 this.el.setHeight(size);
54903 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
54904 orientation: Roo.SplitBar.VERTICAL,
54905 getBox : function(){
54906 if(this.collapsed){
54907 return this.collapsedEl.getBox();
54909 var box = this.el.getBox();
54911 box.height += this.split.el.getHeight();
54916 updateBox : function(box){
54917 if(this.split && !this.collapsed){
54918 box.height -= this.split.el.getHeight();
54919 this.split.el.setLeft(box.x);
54920 this.split.el.setTop(box.y+box.height);
54921 this.split.el.setWidth(box.width);
54923 if(this.collapsed){
54924 this.updateBody(box.width, null);
54926 Roo.LayoutRegion.prototype.updateBox.call(this, box);
54930 Roo.SouthLayoutRegion = function(mgr, config){
54931 Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
54933 this.split.placement = Roo.SplitBar.BOTTOM;
54934 this.split.orientation = Roo.SplitBar.VERTICAL;
54935 this.split.el.addClass("x-layout-split-v");
54937 var size = config.initialSize || config.height;
54938 if(typeof size != "undefined"){
54939 this.el.setHeight(size);
54942 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
54943 orientation: Roo.SplitBar.VERTICAL,
54944 getBox : function(){
54945 if(this.collapsed){
54946 return this.collapsedEl.getBox();
54948 var box = this.el.getBox();
54950 var sh = this.split.el.getHeight();
54957 updateBox : function(box){
54958 if(this.split && !this.collapsed){
54959 var sh = this.split.el.getHeight();
54962 this.split.el.setLeft(box.x);
54963 this.split.el.setTop(box.y-sh);
54964 this.split.el.setWidth(box.width);
54966 if(this.collapsed){
54967 this.updateBody(box.width, null);
54969 Roo.LayoutRegion.prototype.updateBox.call(this, box);
54973 Roo.EastLayoutRegion = function(mgr, config){
54974 Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
54976 this.split.placement = Roo.SplitBar.RIGHT;
54977 this.split.orientation = Roo.SplitBar.HORIZONTAL;
54978 this.split.el.addClass("x-layout-split-h");
54980 var size = config.initialSize || config.width;
54981 if(typeof size != "undefined"){
54982 this.el.setWidth(size);
54985 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
54986 orientation: Roo.SplitBar.HORIZONTAL,
54987 getBox : function(){
54988 if(this.collapsed){
54989 return this.collapsedEl.getBox();
54991 var box = this.el.getBox();
54993 var sw = this.split.el.getWidth();
55000 updateBox : function(box){
55001 if(this.split && !this.collapsed){
55002 var sw = this.split.el.getWidth();
55004 this.split.el.setLeft(box.x);
55005 this.split.el.setTop(box.y);
55006 this.split.el.setHeight(box.height);
55009 if(this.collapsed){
55010 this.updateBody(null, box.height);
55012 Roo.LayoutRegion.prototype.updateBox.call(this, box);
55016 Roo.WestLayoutRegion = function(mgr, config){
55017 Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
55019 this.split.placement = Roo.SplitBar.LEFT;
55020 this.split.orientation = Roo.SplitBar.HORIZONTAL;
55021 this.split.el.addClass("x-layout-split-h");
55023 var size = config.initialSize || config.width;
55024 if(typeof size != "undefined"){
55025 this.el.setWidth(size);
55028 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
55029 orientation: Roo.SplitBar.HORIZONTAL,
55030 getBox : function(){
55031 if(this.collapsed){
55032 return this.collapsedEl.getBox();
55034 var box = this.el.getBox();
55036 box.width += this.split.el.getWidth();
55041 updateBox : function(box){
55042 if(this.split && !this.collapsed){
55043 var sw = this.split.el.getWidth();
55045 this.split.el.setLeft(box.x+box.width);
55046 this.split.el.setTop(box.y);
55047 this.split.el.setHeight(box.height);
55049 if(this.collapsed){
55050 this.updateBody(null, box.height);
55052 Roo.LayoutRegion.prototype.updateBox.call(this, box);
55057 * Ext JS Library 1.1.1
55058 * Copyright(c) 2006-2007, Ext JS, LLC.
55060 * Originally Released Under LGPL - original licence link has changed is not relivant.
55063 * <script type="text/javascript">
55068 * Private internal class for reading and applying state
55070 Roo.LayoutStateManager = function(layout){
55071 // default empty state
55080 Roo.LayoutStateManager.prototype = {
55081 init : function(layout, provider){
55082 this.provider = provider;
55083 var state = provider.get(layout.id+"-layout-state");
55085 var wasUpdating = layout.isUpdating();
55087 layout.beginUpdate();
55089 for(var key in state){
55090 if(typeof state[key] != "function"){
55091 var rstate = state[key];
55092 var r = layout.getRegion(key);
55095 r.resizeTo(rstate.size);
55097 if(rstate.collapsed == true){
55100 r.expand(null, true);
55106 layout.endUpdate();
55108 this.state = state;
55110 this.layout = layout;
55111 layout.on("regionresized", this.onRegionResized, this);
55112 layout.on("regioncollapsed", this.onRegionCollapsed, this);
55113 layout.on("regionexpanded", this.onRegionExpanded, this);
55116 storeState : function(){
55117 this.provider.set(this.layout.id+"-layout-state", this.state);
55120 onRegionResized : function(region, newSize){
55121 this.state[region.getPosition()].size = newSize;
55125 onRegionCollapsed : function(region){
55126 this.state[region.getPosition()].collapsed = true;
55130 onRegionExpanded : function(region){
55131 this.state[region.getPosition()].collapsed = false;
55136 * Ext JS Library 1.1.1
55137 * Copyright(c) 2006-2007, Ext JS, LLC.
55139 * Originally Released Under LGPL - original licence link has changed is not relivant.
55142 * <script type="text/javascript">
55145 * @class Roo.ContentPanel
55146 * @extends Roo.util.Observable
55147 * @children Roo.form.Form Roo.JsonView Roo.View
55148 * @parent Roo.BorderLayout Roo.LayoutDialog builder-top
55149 * A basic ContentPanel element.
55150 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
55151 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
55152 * @cfg {Boolean|Object} autoCreate True to auto generate the DOM element for this panel, or a {@link Roo.DomHelper} config of the element to create
55153 * @cfg {Boolean} closable True if the panel can be closed/removed
55154 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
55155 * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
55156 * @cfg {Roo.Toolbar} toolbar A toolbar for this panel
55157 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
55158 * @cfg {String} title The title for this panel
55159 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
55160 * @cfg {String} url Calls {@link #setUrl} with this value
55161 * @cfg {String} region [required] (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
55162 * @cfg {String|Object} params When used with {@link #url}, calls {@link #setUrl} with this value
55163 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
55164 * @cfg {String} content Raw content to fill content panel with (uses setContent on construction.)
55165 * @cfg {String} style Extra style to add to the content panel
55166 * @cfg {Roo.menu.Menu} menu popup menu
55169 * Create a new ContentPanel.
55170 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
55171 * @param {String/Object} config A string to set only the title or a config object
55172 * @param {String} content (optional) Set the HTML content for this panel
55173 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
55175 Roo.ContentPanel = function(el, config, content){
55179 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
55183 if (config && config.parentLayout) {
55184 el = config.parentLayout.el.createChild();
55187 if(el.autoCreate){ // xtype is available if this is called from factory
55191 this.el = Roo.get(el);
55192 if(!this.el && config && config.autoCreate){
55193 if(typeof config.autoCreate == "object"){
55194 if(!config.autoCreate.id){
55195 config.autoCreate.id = config.id||el;
55197 this.el = Roo.DomHelper.append(document.body,
55198 config.autoCreate, true);
55200 this.el = Roo.DomHelper.append(document.body,
55201 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
55206 this.closable = false;
55207 this.loaded = false;
55208 this.active = false;
55209 if(typeof config == "string"){
55210 this.title = config;
55212 Roo.apply(this, config);
55215 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
55216 this.wrapEl = this.el.wrap();
55217 this.toolbar.container = this.el.insertSibling(false, 'before');
55218 this.toolbar = new Roo.Toolbar(this.toolbar);
55221 // xtype created footer. - not sure if will work as we normally have to render first..
55222 if (this.footer && !this.footer.el && this.footer.xtype) {
55223 if (!this.wrapEl) {
55224 this.wrapEl = this.el.wrap();
55227 this.footer.container = this.wrapEl.createChild();
55229 this.footer = Roo.factory(this.footer, Roo);
55234 this.resizeEl = Roo.get(this.resizeEl, true);
55236 this.resizeEl = this.el;
55238 // handle view.xtype
55246 * Fires when this panel is activated.
55247 * @param {Roo.ContentPanel} this
55251 * @event deactivate
55252 * Fires when this panel is activated.
55253 * @param {Roo.ContentPanel} this
55255 "deactivate" : true,
55259 * Fires when this panel is resized if fitToFrame is true.
55260 * @param {Roo.ContentPanel} this
55261 * @param {Number} width The width after any component adjustments
55262 * @param {Number} height The height after any component adjustments
55268 * Fires when this tab is created
55269 * @param {Roo.ContentPanel} this
55279 if(this.autoScroll){
55280 this.resizeEl.setStyle("overflow", "auto");
55282 // fix randome scrolling
55283 this.el.on('scroll', function() {
55284 Roo.log('fix random scolling');
55285 this.scrollTo('top',0);
55288 content = content || this.content;
55290 this.setContent(content);
55292 if(config && config.url){
55293 this.setUrl(this.url, this.params, this.loadOnce);
55298 Roo.ContentPanel.superclass.constructor.call(this);
55300 if (this.view && typeof(this.view.xtype) != 'undefined') {
55301 this.view.el = this.el.appendChild(document.createElement("div"));
55302 this.view = Roo.factory(this.view);
55303 this.view.render && this.view.render(false, '');
55307 this.fireEvent('render', this);
55310 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
55312 setRegion : function(region){
55313 this.region = region;
55315 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
55317 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
55322 * Returns the toolbar for this Panel if one was configured.
55323 * @return {Roo.Toolbar}
55325 getToolbar : function(){
55326 return this.toolbar;
55329 setActiveState : function(active){
55330 this.active = active;
55332 this.fireEvent("deactivate", this);
55334 this.fireEvent("activate", this);
55338 * Updates this panel's element
55339 * @param {String} content The new content
55340 * @param {Boolean} loadScripts (optional) true to look for and process scripts
55342 setContent : function(content, loadScripts){
55343 this.el.update(content, loadScripts);
55346 ignoreResize : function(w, h){
55347 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
55350 this.lastSize = {width: w, height: h};
55355 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
55356 * @return {Roo.UpdateManager} The UpdateManager
55358 getUpdateManager : function(){
55359 return this.el.getUpdateManager();
55362 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
55363 * @param {Object/String/Function} url The url for this request or a function to call to get the url or a config object containing any of the following options:
55366 url: "your-url.php",
55367 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
55368 callback: yourFunction,
55369 scope: yourObject, //(optional scope)
55372 text: "Loading...",
55377 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
55378 * are shorthand for <i>disableCaching</i>, <i>indicatorText</i> and <i>loadScripts</i> and are used to set their associated property on this panel UpdateManager instance.
55379 * @param {String/Object} params (optional) The parameters to pass as either a URL encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
55380 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
55381 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used URL. If true, it will not store the URL.
55382 * @return {Roo.ContentPanel} this
55385 var um = this.el.getUpdateManager();
55386 um.update.apply(um, arguments);
55392 * Set a URL to be used to load the content for this panel. When this panel is activated, the content will be loaded from that URL.
55393 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
55394 * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
55395 * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this panel is activated. (Defaults to false)
55396 * @return {Roo.UpdateManager} The UpdateManager
55398 setUrl : function(url, params, loadOnce){
55399 if(this.refreshDelegate){
55400 this.removeListener("activate", this.refreshDelegate);
55402 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
55403 this.on("activate", this.refreshDelegate);
55404 return this.el.getUpdateManager();
55407 _handleRefresh : function(url, params, loadOnce){
55408 if(!loadOnce || !this.loaded){
55409 var updater = this.el.getUpdateManager();
55410 updater.update(url, params, this._setLoaded.createDelegate(this));
55414 _setLoaded : function(){
55415 this.loaded = true;
55419 * Returns this panel's id
55422 getId : function(){
55427 * Returns this panel's element - used by regiosn to add.
55428 * @return {Roo.Element}
55430 getEl : function(){
55431 return this.wrapEl || this.el;
55434 adjustForComponents : function(width, height)
55436 //Roo.log('adjustForComponents ');
55437 if(this.resizeEl != this.el){
55438 width -= this.el.getFrameWidth('lr');
55439 height -= this.el.getFrameWidth('tb');
55442 var te = this.toolbar.getEl();
55443 height -= te.getHeight();
55444 te.setWidth(width);
55447 var te = this.footer.getEl();
55448 //Roo.log("footer:" + te.getHeight());
55450 height -= te.getHeight();
55451 te.setWidth(width);
55455 if(this.adjustments){
55456 width += this.adjustments[0];
55457 height += this.adjustments[1];
55459 return {"width": width, "height": height};
55462 setSize : function(width, height){
55463 if(this.fitToFrame && !this.ignoreResize(width, height)){
55464 if(this.fitContainer && this.resizeEl != this.el){
55465 this.el.setSize(width, height);
55467 var size = this.adjustForComponents(width, height);
55468 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
55469 this.fireEvent('resize', this, size.width, size.height);
55474 * Returns this panel's title
55477 getTitle : function(){
55482 * Set this panel's title
55483 * @param {String} title
55485 setTitle : function(title){
55486 this.title = title;
55488 this.region.updatePanelTitle(this, title);
55493 * Returns true is this panel was configured to be closable
55494 * @return {Boolean}
55496 isClosable : function(){
55497 return this.closable;
55500 beforeSlide : function(){
55502 this.resizeEl.clip();
55505 afterSlide : function(){
55507 this.resizeEl.unclip();
55511 * Force a content refresh from the URL specified in the {@link #setUrl} method.
55512 * Will fail silently if the {@link #setUrl} method has not been called.
55513 * This does not activate the panel, just updates its content.
55515 refresh : function(){
55516 if(this.refreshDelegate){
55517 this.loaded = false;
55518 this.refreshDelegate();
55523 * Destroys this panel
55525 destroy : function(){
55526 this.el.removeAllListeners();
55527 var tempEl = document.createElement("span");
55528 tempEl.appendChild(this.el.dom);
55529 tempEl.innerHTML = "";
55535 * form - if the content panel contains a form - this is a reference to it.
55536 * @type {Roo.form.Form}
55540 * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
55541 * This contains a reference to it.
55547 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
55557 * @param {Object} cfg Xtype definition of item to add.
55560 addxtype : function(cfg) {
55562 if (cfg.xtype.match(/^Form$/)) {
55565 //if (this.footer) {
55566 // el = this.footer.container.insertSibling(false, 'before');
55568 el = this.el.createChild();
55571 this.form = new Roo.form.Form(cfg);
55574 if ( this.form.allItems.length) {
55575 this.form.render(el.dom);
55579 // should only have one of theses..
55580 if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
55581 // views.. should not be just added - used named prop 'view''
55583 cfg.el = this.el.appendChild(document.createElement("div"));
55586 var ret = new Roo.factory(cfg);
55588 ret.render && ret.render(false, ''); // render blank..
55597 * @class Roo.GridPanel
55598 * @extends Roo.ContentPanel
55600 * Create a new GridPanel.
55601 * @param {Roo.grid.Grid} grid The grid for this panel
55602 * @param {String/Object} config A string to set only the panel's title, or a config object
55604 Roo.GridPanel = function(grid, config){
55607 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
55608 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
55610 this.wrapper.dom.appendChild(grid.getGridEl().dom);
55612 Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
55615 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
55617 // xtype created footer. - not sure if will work as we normally have to render first..
55618 if (this.footer && !this.footer.el && this.footer.xtype) {
55620 this.footer.container = this.grid.getView().getFooterPanel(true);
55621 this.footer.dataSource = this.grid.dataSource;
55622 this.footer = Roo.factory(this.footer, Roo);
55626 grid.monitorWindowResize = false; // turn off autosizing
55627 grid.autoHeight = false;
55628 grid.autoWidth = false;
55630 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
55633 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
55634 getId : function(){
55635 return this.grid.id;
55639 * Returns the grid for this panel
55640 * @return {Roo.grid.Grid}
55642 getGrid : function(){
55646 setSize : function(width, height){
55647 if(!this.ignoreResize(width, height)){
55648 var grid = this.grid;
55649 var size = this.adjustForComponents(width, height);
55650 grid.getGridEl().setSize(size.width, size.height);
55655 beforeSlide : function(){
55656 this.grid.getView().scroller.clip();
55659 afterSlide : function(){
55660 this.grid.getView().scroller.unclip();
55663 destroy : function(){
55664 this.grid.destroy();
55666 Roo.GridPanel.superclass.destroy.call(this);
55672 * @class Roo.NestedLayoutPanel
55673 * @extends Roo.ContentPanel
55675 * Create a new NestedLayoutPanel.
55678 * @param {Roo.BorderLayout} layout [required] The layout for this panel
55679 * @param {String/Object} config A string to set only the title or a config object
55681 Roo.NestedLayoutPanel = function(layout, config)
55683 // construct with only one argument..
55684 /* FIXME - implement nicer consturctors
55685 if (layout.layout) {
55687 layout = config.layout;
55688 delete config.layout;
55690 if (layout.xtype && !layout.getEl) {
55691 // then layout needs constructing..
55692 layout = Roo.factory(layout, Roo);
55697 Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
55699 layout.monitorWindowResize = false; // turn off autosizing
55700 this.layout = layout;
55701 this.layout.getEl().addClass("x-layout-nested-layout");
55708 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
55710 setSize : function(width, height){
55711 if(!this.ignoreResize(width, height)){
55712 var size = this.adjustForComponents(width, height);
55713 var el = this.layout.getEl();
55714 el.setSize(size.width, size.height);
55715 var touch = el.dom.offsetWidth;
55716 this.layout.layout();
55717 // ie requires a double layout on the first pass
55718 if(Roo.isIE && !this.initialized){
55719 this.initialized = true;
55720 this.layout.layout();
55725 // activate all subpanels if not currently active..
55727 setActiveState : function(active){
55728 this.active = active;
55730 this.fireEvent("deactivate", this);
55734 this.fireEvent("activate", this);
55735 // not sure if this should happen before or after..
55736 if (!this.layout) {
55737 return; // should not happen..
55740 for (var r in this.layout.regions) {
55741 reg = this.layout.getRegion(r);
55742 if (reg.getActivePanel()) {
55743 //reg.showPanel(reg.getActivePanel()); // force it to activate..
55744 reg.setActivePanel(reg.getActivePanel());
55747 if (!reg.panels.length) {
55750 reg.showPanel(reg.getPanel(0));
55759 * Returns the nested BorderLayout for this panel
55760 * @return {Roo.BorderLayout}
55762 getLayout : function(){
55763 return this.layout;
55767 * Adds a xtype elements to the layout of the nested panel
55771 xtype : 'ContentPanel',
55778 xtype : 'NestedLayoutPanel',
55784 items : [ ... list of content panels or nested layout panels.. ]
55788 * @param {Object} cfg Xtype definition of item to add.
55790 addxtype : function(cfg) {
55791 return this.layout.addxtype(cfg);
55796 Roo.ScrollPanel = function(el, config, content){
55797 config = config || {};
55798 config.fitToFrame = true;
55799 Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
55801 this.el.dom.style.overflow = "hidden";
55802 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
55803 this.el.removeClass("x-layout-inactive-content");
55804 this.el.on("mousewheel", this.onWheel, this);
55806 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
55807 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
55808 up.unselectable(); down.unselectable();
55809 up.on("click", this.scrollUp, this);
55810 down.on("click", this.scrollDown, this);
55811 up.addClassOnOver("x-scroller-btn-over");
55812 down.addClassOnOver("x-scroller-btn-over");
55813 up.addClassOnClick("x-scroller-btn-click");
55814 down.addClassOnClick("x-scroller-btn-click");
55815 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
55817 this.resizeEl = this.el;
55818 this.el = wrap; this.up = up; this.down = down;
55821 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
55823 wheelIncrement : 5,
55824 scrollUp : function(){
55825 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
55828 scrollDown : function(){
55829 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
55832 afterScroll : function(){
55833 var el = this.resizeEl;
55834 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
55835 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
55836 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
55839 setSize : function(){
55840 Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
55841 this.afterScroll();
55844 onWheel : function(e){
55845 var d = e.getWheelDelta();
55846 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
55847 this.afterScroll();
55851 setContent : function(content, loadScripts){
55852 this.resizeEl.update(content, loadScripts);
55860 * @class Roo.TreePanel
55861 * @extends Roo.ContentPanel
55862 * Treepanel component
55865 * Create a new TreePanel. - defaults to fit/scoll contents.
55866 * @param {String/Object} config A string to set only the panel's title, or a config object
55868 Roo.TreePanel = function(config){
55869 var el = config.el;
55870 var tree = config.tree;
55871 delete config.tree;
55872 delete config.el; // hopefull!
55874 // wrapper for IE7 strict & safari scroll issue
55876 var treeEl = el.createChild();
55877 config.resizeEl = treeEl;
55881 Roo.TreePanel.superclass.constructor.call(this, el, config);
55884 this.tree = new Roo.tree.TreePanel(treeEl , tree);
55885 //console.log(tree);
55886 this.on('activate', function()
55888 if (this.tree.rendered) {
55891 //console.log('render tree');
55892 this.tree.render();
55894 // this should not be needed.. - it's actually the 'el' that resizes?
55895 // actuall it breaks the containerScroll - dragging nodes auto scroll at top
55897 //this.on('resize', function (cp, w, h) {
55898 // this.tree.innerCt.setWidth(w);
55899 // this.tree.innerCt.setHeight(h);
55900 // //this.tree.innerCt.setStyle('overflow-y', 'auto');
55907 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {
55911 * @cfg {Roo.tree.TreePanel} tree [required] The tree TreePanel, with config etc.
55929 * Ext JS Library 1.1.1
55930 * Copyright(c) 2006-2007, Ext JS, LLC.
55932 * Originally Released Under LGPL - original licence link has changed is not relivant.
55935 * <script type="text/javascript">
55940 * @class Roo.ReaderLayout
55941 * @extends Roo.BorderLayout
55942 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
55943 * center region containing two nested regions (a top one for a list view and one for item preview below),
55944 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
55945 * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
55946 * expedites the setup of the overall layout and regions for this common application style.
55949 var reader = new Roo.ReaderLayout();
55950 var CP = Roo.ContentPanel; // shortcut for adding
55952 reader.beginUpdate();
55953 reader.add("north", new CP("north", "North"));
55954 reader.add("west", new CP("west", {title: "West"}));
55955 reader.add("east", new CP("east", {title: "East"}));
55957 reader.regions.listView.add(new CP("listView", "List"));
55958 reader.regions.preview.add(new CP("preview", "Preview"));
55959 reader.endUpdate();
55962 * Create a new ReaderLayout
55963 * @param {Object} config Configuration options
55964 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
55965 * document.body if omitted)
55967 Roo.ReaderLayout = function(config, renderTo){
55968 var c = config || {size:{}};
55969 Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
55970 north: c.north !== false ? Roo.apply({
55974 }, c.north) : false,
55975 west: c.west !== false ? Roo.apply({
55983 margins:{left:5,right:0,bottom:5,top:5},
55984 cmargins:{left:5,right:5,bottom:5,top:5}
55985 }, c.west) : false,
55986 east: c.east !== false ? Roo.apply({
55994 margins:{left:0,right:5,bottom:5,top:5},
55995 cmargins:{left:5,right:5,bottom:5,top:5}
55996 }, c.east) : false,
55997 center: Roo.apply({
55998 tabPosition: 'top',
56002 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
56006 this.el.addClass('x-reader');
56008 this.beginUpdate();
56010 var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
56011 south: c.preview !== false ? Roo.apply({
56018 cmargins:{top:5,left:0, right:0, bottom:0}
56019 }, c.preview) : false,
56020 center: Roo.apply({
56026 this.add('center', new Roo.NestedLayoutPanel(inner,
56027 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
56031 this.regions.preview = inner.getRegion('south');
56032 this.regions.listView = inner.getRegion('center');
56035 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
56037 * Ext JS Library 1.1.1
56038 * Copyright(c) 2006-2007, Ext JS, LLC.
56040 * Originally Released Under LGPL - original licence link has changed is not relivant.
56043 * <script type="text/javascript">
56047 * @class Roo.grid.Grid
56048 * @extends Roo.util.Observable
56049 * This class represents the primary interface of a component based grid control.
56050 * <br><br>Usage:<pre><code>
56051 var grid = new Roo.grid.Grid("my-container-id", {
56054 selModel: mySelectionModel,
56055 autoSizeColumns: true,
56056 monitorWindowResize: false,
56057 trackMouseOver: true
56062 * <b>Common Problems:</b><br/>
56063 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
56064 * element will correct this<br/>
56065 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
56066 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
56067 * are unpredictable.<br/>
56068 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
56069 * grid to calculate dimensions/offsets.<br/>
56071 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
56072 * The container MUST have some type of size defined for the grid to fill. The container will be
56073 * automatically set to position relative if it isn't already.
56074 * @param {Object} config A config object that sets properties on this grid.
56076 Roo.grid.Grid = function(container, config){
56077 // initialize the container
56078 this.container = Roo.get(container);
56079 this.container.update("");
56080 this.container.setStyle("overflow", "hidden");
56081 this.container.addClass('x-grid-container');
56083 this.id = this.container.id;
56085 Roo.apply(this, config);
56086 // check and correct shorthanded configs
56088 this.dataSource = this.ds;
56092 this.colModel = this.cm;
56096 this.selModel = this.sm;
56100 if (this.selModel) {
56101 this.selModel = Roo.factory(this.selModel, Roo.grid);
56102 this.sm = this.selModel;
56103 this.sm.xmodule = this.xmodule || false;
56105 if (typeof(this.colModel.config) == 'undefined') {
56106 this.colModel = new Roo.grid.ColumnModel(this.colModel);
56107 this.cm = this.colModel;
56108 this.cm.xmodule = this.xmodule || false;
56110 if (this.dataSource) {
56111 this.dataSource= Roo.factory(this.dataSource, Roo.data);
56112 this.ds = this.dataSource;
56113 this.ds.xmodule = this.xmodule || false;
56120 this.container.setWidth(this.width);
56124 this.container.setHeight(this.height);
56131 * The raw click event for the entire grid.
56132 * @param {Roo.EventObject} e
56137 * The raw dblclick event for the entire grid.
56138 * @param {Roo.EventObject} e
56142 * @event contextmenu
56143 * The raw contextmenu event for the entire grid.
56144 * @param {Roo.EventObject} e
56146 "contextmenu" : true,
56149 * The raw mousedown event for the entire grid.
56150 * @param {Roo.EventObject} e
56152 "mousedown" : true,
56155 * The raw mouseup event for the entire grid.
56156 * @param {Roo.EventObject} e
56161 * The raw mouseover event for the entire grid.
56162 * @param {Roo.EventObject} e
56164 "mouseover" : true,
56167 * The raw mouseout event for the entire grid.
56168 * @param {Roo.EventObject} e
56173 * The raw keypress event for the entire grid.
56174 * @param {Roo.EventObject} e
56179 * The raw keydown event for the entire grid.
56180 * @param {Roo.EventObject} e
56188 * Fires when a cell is clicked
56189 * @param {Grid} this
56190 * @param {Number} rowIndex
56191 * @param {Number} columnIndex
56192 * @param {Roo.EventObject} e
56194 "cellclick" : true,
56196 * @event celldblclick
56197 * Fires when a cell is double clicked
56198 * @param {Grid} this
56199 * @param {Number} rowIndex
56200 * @param {Number} columnIndex
56201 * @param {Roo.EventObject} e
56203 "celldblclick" : true,
56206 * Fires when a row is clicked
56207 * @param {Grid} this
56208 * @param {Number} rowIndex
56209 * @param {Roo.EventObject} e
56213 * @event rowdblclick
56214 * Fires when a row is double clicked
56215 * @param {Grid} this
56216 * @param {Number} rowIndex
56217 * @param {Roo.EventObject} e
56219 "rowdblclick" : true,
56221 * @event headerclick
56222 * Fires when a header is clicked
56223 * @param {Grid} this
56224 * @param {Number} columnIndex
56225 * @param {Roo.EventObject} e
56227 "headerclick" : true,
56229 * @event headerdblclick
56230 * Fires when a header cell is double clicked
56231 * @param {Grid} this
56232 * @param {Number} columnIndex
56233 * @param {Roo.EventObject} e
56235 "headerdblclick" : true,
56237 * @event rowcontextmenu
56238 * Fires when a row is right clicked
56239 * @param {Grid} this
56240 * @param {Number} rowIndex
56241 * @param {Roo.EventObject} e
56243 "rowcontextmenu" : true,
56245 * @event cellcontextmenu
56246 * Fires when a cell is right clicked
56247 * @param {Grid} this
56248 * @param {Number} rowIndex
56249 * @param {Number} cellIndex
56250 * @param {Roo.EventObject} e
56252 "cellcontextmenu" : true,
56254 * @event headercontextmenu
56255 * Fires when a header is right clicked
56256 * @param {Grid} this
56257 * @param {Number} columnIndex
56258 * @param {Roo.EventObject} e
56260 "headercontextmenu" : true,
56262 * @event bodyscroll
56263 * Fires when the body element is scrolled
56264 * @param {Number} scrollLeft
56265 * @param {Number} scrollTop
56267 "bodyscroll" : true,
56269 * @event columnresize
56270 * Fires when the user resizes a column
56271 * @param {Number} columnIndex
56272 * @param {Number} newSize
56274 "columnresize" : true,
56276 * @event columnmove
56277 * Fires when the user moves a column
56278 * @param {Number} oldIndex
56279 * @param {Number} newIndex
56281 "columnmove" : true,
56284 * Fires when row(s) start being dragged
56285 * @param {Grid} this
56286 * @param {Roo.GridDD} dd The drag drop object
56287 * @param {event} e The raw browser event
56289 "startdrag" : true,
56292 * Fires when a drag operation is complete
56293 * @param {Grid} this
56294 * @param {Roo.GridDD} dd The drag drop object
56295 * @param {event} e The raw browser event
56300 * Fires when dragged row(s) are dropped on a valid DD target
56301 * @param {Grid} this
56302 * @param {Roo.GridDD} dd The drag drop object
56303 * @param {String} targetId The target drag drop object
56304 * @param {event} e The raw browser event
56309 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
56310 * @param {Grid} this
56311 * @param {Roo.GridDD} dd The drag drop object
56312 * @param {String} targetId The target drag drop object
56313 * @param {event} e The raw browser event
56318 * Fires when the dragged row(s) first cross another DD target while being dragged
56319 * @param {Grid} this
56320 * @param {Roo.GridDD} dd The drag drop object
56321 * @param {String} targetId The target drag drop object
56322 * @param {event} e The raw browser event
56324 "dragenter" : true,
56327 * Fires when the dragged row(s) leave another DD target while being dragged
56328 * @param {Grid} this
56329 * @param {Roo.GridDD} dd The drag drop object
56330 * @param {String} targetId The target drag drop object
56331 * @param {event} e The raw browser event
56336 * Fires when a row is rendered, so you can change add a style to it.
56337 * @param {GridView} gridview The grid view
56338 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
56344 * Fires when the grid is rendered
56345 * @param {Grid} grid
56350 Roo.grid.Grid.superclass.constructor.call(this);
56352 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
56355 * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
56358 * @cfg {Roo.grid.GridView} view The view that renders the grid (default = Roo.grid.GridView)
56361 * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
56364 * @cfg {Roo.grid.Store} ds The data store for the grid
56367 * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
56370 * @cfg {String} ddGroup - drag drop group.
56373 * @cfg {String} dragGroup - drag group (?? not sure if needed.)
56377 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
56379 minColumnWidth : 25,
56382 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
56383 * <b>on initial render.</b> It is more efficient to explicitly size the columns
56384 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
56386 autoSizeColumns : false,
56389 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
56391 autoSizeHeaders : true,
56394 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
56396 monitorWindowResize : true,
56399 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
56400 * rows measured to get a columns size. Default is 0 (all rows).
56402 maxRowsToMeasure : 0,
56405 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
56407 trackMouseOver : true,
56410 * @cfg {Boolean} enableDrag True to enable drag of rows. Default is false. (double check if this is needed?)
56413 * @cfg {Boolean} enableDrop True to enable drop of elements. Default is false. (double check if this is needed?)
56417 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
56419 enableDragDrop : false,
56422 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
56424 enableColumnMove : true,
56427 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
56429 enableColumnHide : true,
56432 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
56434 enableRowHeightSync : false,
56437 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
56442 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
56444 autoHeight : false,
56447 * @cfg {String} autoExpandColumn The id (or dataIndex) of a column in this grid that should expand to fill unused space. This id can not be 0. Default is false.
56449 autoExpandColumn : false,
56452 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
56455 autoExpandMin : 50,
56458 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
56460 autoExpandMax : 1000,
56463 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
56468 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
56472 * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
56482 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
56483 * of a fixed width. Default is false.
56486 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
56491 * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
56492 * %0 is replaced with the number of selected rows.
56494 ddText : "{0} selected row{1}",
56498 * Called once after all setup has been completed and the grid is ready to be rendered.
56499 * @return {Roo.grid.Grid} this
56501 render : function()
56503 var c = this.container;
56504 // try to detect autoHeight/width mode
56505 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
56506 this.autoHeight = true;
56508 var view = this.getView();
56511 c.on("click", this.onClick, this);
56512 c.on("dblclick", this.onDblClick, this);
56513 c.on("contextmenu", this.onContextMenu, this);
56514 c.on("keydown", this.onKeyDown, this);
56516 c.on("touchstart", this.onTouchStart, this);
56519 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
56521 this.getSelectionModel().init(this);
56526 this.loadMask = new Roo.LoadMask(this.container,
56527 Roo.apply({store:this.dataSource}, this.loadMask));
56531 if (this.toolbar && this.toolbar.xtype) {
56532 this.toolbar.container = this.getView().getHeaderPanel(true);
56533 this.toolbar = new Roo.Toolbar(this.toolbar);
56535 if (this.footer && this.footer.xtype) {
56536 this.footer.dataSource = this.getDataSource();
56537 this.footer.container = this.getView().getFooterPanel(true);
56538 this.footer = Roo.factory(this.footer, Roo);
56540 if (this.dropTarget && this.dropTarget.xtype) {
56541 delete this.dropTarget.xtype;
56542 this.dropTarget = new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
56546 this.rendered = true;
56547 this.fireEvent('render', this);
56552 * Reconfigures the grid to use a different Store and Column Model.
56553 * The View will be bound to the new objects and refreshed.
56554 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
56555 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
56557 reconfigure : function(dataSource, colModel){
56559 this.loadMask.destroy();
56560 this.loadMask = new Roo.LoadMask(this.container,
56561 Roo.apply({store:dataSource}, this.loadMask));
56563 this.view.bind(dataSource, colModel);
56564 this.dataSource = dataSource;
56565 this.colModel = colModel;
56566 this.view.refresh(true);
56570 * Add's a column, default at the end..
56572 * @param {int} position to add (default end)
56573 * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel}
56575 addColumns : function(pos, ar)
56578 for (var i =0;i< ar.length;i++) {
56580 cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
56581 this.cm.lookup[cfg.id] = cfg;
56585 if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
56586 pos = this.cm.config.length; //this.cm.config.push(cfg);
56588 pos = Math.max(0,pos);
56591 this.cm.config.splice.apply(this.cm.config, ar);
56595 this.view.generateRules(this.cm);
56596 this.view.refresh(true);
56604 onKeyDown : function(e){
56605 this.fireEvent("keydown", e);
56609 * Destroy this grid.
56610 * @param {Boolean} removeEl True to remove the element
56612 destroy : function(removeEl, keepListeners){
56614 this.loadMask.destroy();
56616 var c = this.container;
56617 c.removeAllListeners();
56618 this.view.destroy();
56619 this.colModel.purgeListeners();
56620 if(!keepListeners){
56621 this.purgeListeners();
56624 if(removeEl === true){
56630 processEvent : function(name, e){
56631 // does this fire select???
56632 //Roo.log('grid:processEvent ' + name);
56634 if (name != 'touchstart' ) {
56635 this.fireEvent(name, e);
56638 var t = e.getTarget();
56640 var header = v.findHeaderIndex(t);
56641 if(header !== false){
56642 var ename = name == 'touchstart' ? 'click' : name;
56644 this.fireEvent("header" + ename, this, header, e);
56646 var row = v.findRowIndex(t);
56647 var cell = v.findCellIndex(t);
56648 if (name == 'touchstart') {
56649 // first touch is always a click.
56650 // hopefull this happens after selection is updated.?
56653 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
56654 var cs = this.selModel.getSelectedCell();
56655 if (row == cs[0] && cell == cs[1]){
56659 if (typeof(this.selModel.getSelections) != 'undefined') {
56660 var cs = this.selModel.getSelections();
56661 var ds = this.dataSource;
56662 if (cs.length == 1 && ds.getAt(row) == cs[0]){
56673 this.fireEvent("row" + name, this, row, e);
56674 if(cell !== false){
56675 this.fireEvent("cell" + name, this, row, cell, e);
56682 onClick : function(e){
56683 this.processEvent("click", e);
56686 onTouchStart : function(e){
56687 this.processEvent("touchstart", e);
56691 onContextMenu : function(e, t){
56692 this.processEvent("contextmenu", e);
56696 onDblClick : function(e){
56697 this.processEvent("dblclick", e);
56701 walkCells : function(row, col, step, fn, scope){
56702 var cm = this.colModel, clen = cm.getColumnCount();
56703 var ds = this.dataSource, rlen = ds.getCount(), first = true;
56715 if(fn.call(scope || this, row, col, cm) === true){
56733 if(fn.call(scope || this, row, col, cm) === true){
56745 getSelections : function(){
56746 return this.selModel.getSelections();
56750 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
56751 * but if manual update is required this method will initiate it.
56753 autoSize : function(){
56755 this.view.layout();
56756 if(this.view.adjustForScroll){
56757 this.view.adjustForScroll();
56763 * Returns the grid's underlying element.
56764 * @return {Element} The element
56766 getGridEl : function(){
56767 return this.container;
56770 // private for compatibility, overridden by editor grid
56771 stopEditing : function(){},
56774 * Returns the grid's SelectionModel.
56775 * @return {SelectionModel}
56777 getSelectionModel : function(){
56778 if(!this.selModel){
56779 this.selModel = new Roo.grid.RowSelectionModel();
56781 return this.selModel;
56785 * Returns the grid's DataSource.
56786 * @return {DataSource}
56788 getDataSource : function(){
56789 return this.dataSource;
56793 * Returns the grid's ColumnModel.
56794 * @return {ColumnModel}
56796 getColumnModel : function(){
56797 return this.colModel;
56801 * Returns the grid's GridView object.
56802 * @return {GridView}
56804 getView : function(){
56806 this.view = new Roo.grid.GridView(this.viewConfig);
56807 this.relayEvents(this.view, [
56808 "beforerowremoved", "beforerowsinserted",
56809 "beforerefresh", "rowremoved",
56810 "rowsinserted", "rowupdated" ,"refresh"
56816 * Called to get grid's drag proxy text, by default returns this.ddText.
56817 * Override this to put something different in the dragged text.
56820 getDragDropText : function(){
56821 var count = this.selModel.getCount();
56822 return String.format(this.ddText, count, count == 1 ? '' : 's');
56827 * Ext JS Library 1.1.1
56828 * Copyright(c) 2006-2007, Ext JS, LLC.
56830 * Originally Released Under LGPL - original licence link has changed is not relivant.
56833 * <script type="text/javascript">
56836 * @class Roo.grid.AbstractGridView
56837 * @extends Roo.util.Observable
56839 * Abstract base class for grid Views
56842 Roo.grid.AbstractGridView = function(){
56846 "beforerowremoved" : true,
56847 "beforerowsinserted" : true,
56848 "beforerefresh" : true,
56849 "rowremoved" : true,
56850 "rowsinserted" : true,
56851 "rowupdated" : true,
56854 Roo.grid.AbstractGridView.superclass.constructor.call(this);
56857 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
56858 rowClass : "x-grid-row",
56859 cellClass : "x-grid-cell",
56860 tdClass : "x-grid-td",
56861 hdClass : "x-grid-hd",
56862 splitClass : "x-grid-hd-split",
56864 init: function(grid){
56866 var cid = this.grid.getGridEl().id;
56867 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
56868 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
56869 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
56870 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
56873 getColumnRenderers : function(){
56874 var renderers = [];
56875 var cm = this.grid.colModel;
56876 var colCount = cm.getColumnCount();
56877 for(var i = 0; i < colCount; i++){
56878 renderers[i] = cm.getRenderer(i);
56883 getColumnIds : function(){
56885 var cm = this.grid.colModel;
56886 var colCount = cm.getColumnCount();
56887 for(var i = 0; i < colCount; i++){
56888 ids[i] = cm.getColumnId(i);
56893 getDataIndexes : function(){
56894 if(!this.indexMap){
56895 this.indexMap = this.buildIndexMap();
56897 return this.indexMap.colToData;
56900 getColumnIndexByDataIndex : function(dataIndex){
56901 if(!this.indexMap){
56902 this.indexMap = this.buildIndexMap();
56904 return this.indexMap.dataToCol[dataIndex];
56908 * Set a css style for a column dynamically.
56909 * @param {Number} colIndex The index of the column
56910 * @param {String} name The css property name
56911 * @param {String} value The css value
56913 setCSSStyle : function(colIndex, name, value){
56914 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
56915 Roo.util.CSS.updateRule(selector, name, value);
56918 generateRules : function(cm){
56919 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
56920 Roo.util.CSS.removeStyleSheet(rulesId);
56921 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
56922 var cid = cm.getColumnId(i);
56923 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
56924 this.tdSelector, cid, " {\n}\n",
56925 this.hdSelector, cid, " {\n}\n",
56926 this.splitSelector, cid, " {\n}\n");
56928 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
56932 * Ext JS Library 1.1.1
56933 * Copyright(c) 2006-2007, Ext JS, LLC.
56935 * Originally Released Under LGPL - original licence link has changed is not relivant.
56938 * <script type="text/javascript">
56942 // This is a support class used internally by the Grid components
56943 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
56945 this.view = grid.getView();
56946 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
56947 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
56949 this.setHandleElId(Roo.id(hd));
56950 this.setOuterHandleElId(Roo.id(hd2));
56952 this.scroll = false;
56954 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
56956 getDragData : function(e){
56957 var t = Roo.lib.Event.getTarget(e);
56958 var h = this.view.findHeaderCell(t);
56960 return {ddel: h.firstChild, header:h};
56965 onInitDrag : function(e){
56966 this.view.headersDisabled = true;
56967 var clone = this.dragData.ddel.cloneNode(true);
56968 clone.id = Roo.id();
56969 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
56970 this.proxy.update(clone);
56974 afterValidDrop : function(){
56976 setTimeout(function(){
56977 v.headersDisabled = false;
56981 afterInvalidDrop : function(){
56983 setTimeout(function(){
56984 v.headersDisabled = false;
56990 * Ext JS Library 1.1.1
56991 * Copyright(c) 2006-2007, Ext JS, LLC.
56993 * Originally Released Under LGPL - original licence link has changed is not relivant.
56996 * <script type="text/javascript">
56999 // This is a support class used internally by the Grid components
57000 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
57002 this.view = grid.getView();
57003 // split the proxies so they don't interfere with mouse events
57004 this.proxyTop = Roo.DomHelper.append(document.body, {
57005 cls:"col-move-top", html:" "
57007 this.proxyBottom = Roo.DomHelper.append(document.body, {
57008 cls:"col-move-bottom", html:" "
57010 this.proxyTop.hide = this.proxyBottom.hide = function(){
57011 this.setLeftTop(-100,-100);
57012 this.setStyle("visibility", "hidden");
57014 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
57015 // temporarily disabled
57016 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
57017 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
57019 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
57020 proxyOffsets : [-4, -9],
57021 fly: Roo.Element.fly,
57023 getTargetFromEvent : function(e){
57024 var t = Roo.lib.Event.getTarget(e);
57025 var cindex = this.view.findCellIndex(t);
57026 if(cindex !== false){
57027 return this.view.getHeaderCell(cindex);
57032 nextVisible : function(h){
57033 var v = this.view, cm = this.grid.colModel;
57036 if(!cm.isHidden(v.getCellIndex(h))){
57044 prevVisible : function(h){
57045 var v = this.view, cm = this.grid.colModel;
57048 if(!cm.isHidden(v.getCellIndex(h))){
57056 positionIndicator : function(h, n, e){
57057 var x = Roo.lib.Event.getPageX(e);
57058 var r = Roo.lib.Dom.getRegion(n.firstChild);
57059 var px, pt, py = r.top + this.proxyOffsets[1];
57060 if((r.right - x) <= (r.right-r.left)/2){
57061 px = r.right+this.view.borderWidth;
57067 var oldIndex = this.view.getCellIndex(h);
57068 var newIndex = this.view.getCellIndex(n);
57070 if(this.grid.colModel.isFixed(newIndex)){
57074 var locked = this.grid.colModel.isLocked(newIndex);
57079 if(oldIndex < newIndex){
57082 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
57085 px += this.proxyOffsets[0];
57086 this.proxyTop.setLeftTop(px, py);
57087 this.proxyTop.show();
57088 if(!this.bottomOffset){
57089 this.bottomOffset = this.view.mainHd.getHeight();
57091 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
57092 this.proxyBottom.show();
57096 onNodeEnter : function(n, dd, e, data){
57097 if(data.header != n){
57098 this.positionIndicator(data.header, n, e);
57102 onNodeOver : function(n, dd, e, data){
57103 var result = false;
57104 if(data.header != n){
57105 result = this.positionIndicator(data.header, n, e);
57108 this.proxyTop.hide();
57109 this.proxyBottom.hide();
57111 return result ? this.dropAllowed : this.dropNotAllowed;
57114 onNodeOut : function(n, dd, e, data){
57115 this.proxyTop.hide();
57116 this.proxyBottom.hide();
57119 onNodeDrop : function(n, dd, e, data){
57120 var h = data.header;
57122 var cm = this.grid.colModel;
57123 var x = Roo.lib.Event.getPageX(e);
57124 var r = Roo.lib.Dom.getRegion(n.firstChild);
57125 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
57126 var oldIndex = this.view.getCellIndex(h);
57127 var newIndex = this.view.getCellIndex(n);
57128 var locked = cm.isLocked(newIndex);
57132 if(oldIndex < newIndex){
57135 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
57138 cm.setLocked(oldIndex, locked, true);
57139 cm.moveColumn(oldIndex, newIndex);
57140 this.grid.fireEvent("columnmove", oldIndex, newIndex);
57148 * Ext JS Library 1.1.1
57149 * Copyright(c) 2006-2007, Ext JS, LLC.
57151 * Originally Released Under LGPL - original licence link has changed is not relivant.
57154 * <script type="text/javascript">
57158 * @class Roo.grid.GridView
57159 * @extends Roo.util.Observable
57162 * @param {Object} config
57164 Roo.grid.GridView = function(config){
57165 Roo.grid.GridView.superclass.constructor.call(this);
57168 Roo.apply(this, config);
57171 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
57173 unselectable : 'unselectable="on"',
57174 unselectableCls : 'x-unselectable',
57177 rowClass : "x-grid-row",
57179 cellClass : "x-grid-col",
57181 tdClass : "x-grid-td",
57183 hdClass : "x-grid-hd",
57185 splitClass : "x-grid-split",
57187 sortClasses : ["sort-asc", "sort-desc"],
57189 enableMoveAnim : false,
57193 dh : Roo.DomHelper,
57195 fly : Roo.Element.fly,
57197 css : Roo.util.CSS,
57203 scrollIncrement : 22,
57205 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
57207 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
57209 bind : function(ds, cm){
57211 this.ds.un("load", this.onLoad, this);
57212 this.ds.un("datachanged", this.onDataChange, this);
57213 this.ds.un("add", this.onAdd, this);
57214 this.ds.un("remove", this.onRemove, this);
57215 this.ds.un("update", this.onUpdate, this);
57216 this.ds.un("clear", this.onClear, this);
57219 ds.on("load", this.onLoad, this);
57220 ds.on("datachanged", this.onDataChange, this);
57221 ds.on("add", this.onAdd, this);
57222 ds.on("remove", this.onRemove, this);
57223 ds.on("update", this.onUpdate, this);
57224 ds.on("clear", this.onClear, this);
57229 this.cm.un("widthchange", this.onColWidthChange, this);
57230 this.cm.un("headerchange", this.onHeaderChange, this);
57231 this.cm.un("hiddenchange", this.onHiddenChange, this);
57232 this.cm.un("columnmoved", this.onColumnMove, this);
57233 this.cm.un("columnlockchange", this.onColumnLock, this);
57236 this.generateRules(cm);
57237 cm.on("widthchange", this.onColWidthChange, this);
57238 cm.on("headerchange", this.onHeaderChange, this);
57239 cm.on("hiddenchange", this.onHiddenChange, this);
57240 cm.on("columnmoved", this.onColumnMove, this);
57241 cm.on("columnlockchange", this.onColumnLock, this);
57246 init: function(grid){
57247 Roo.grid.GridView.superclass.init.call(this, grid);
57249 this.bind(grid.dataSource, grid.colModel);
57251 grid.on("headerclick", this.handleHeaderClick, this);
57253 if(grid.trackMouseOver){
57254 grid.on("mouseover", this.onRowOver, this);
57255 grid.on("mouseout", this.onRowOut, this);
57257 grid.cancelTextSelection = function(){};
57258 this.gridId = grid.id;
57260 var tpls = this.templates || {};
57263 tpls.master = new Roo.Template(
57264 '<div class="x-grid" hidefocus="true">',
57265 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
57266 '<div class="x-grid-topbar"></div>',
57267 '<div class="x-grid-scroller"><div></div></div>',
57268 '<div class="x-grid-locked">',
57269 '<div class="x-grid-header">{lockedHeader}</div>',
57270 '<div class="x-grid-body">{lockedBody}</div>',
57272 '<div class="x-grid-viewport">',
57273 '<div class="x-grid-header">{header}</div>',
57274 '<div class="x-grid-body">{body}</div>',
57276 '<div class="x-grid-bottombar"></div>',
57278 '<div class="x-grid-resize-proxy"> </div>',
57281 tpls.master.disableformats = true;
57285 tpls.header = new Roo.Template(
57286 '<table border="0" cellspacing="0" cellpadding="0">',
57287 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
57290 tpls.header.disableformats = true;
57292 tpls.header.compile();
57295 tpls.hcell = new Roo.Template(
57296 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
57297 '<div class="x-grid-hd-text ' + this.unselectableCls + '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
57300 tpls.hcell.disableFormats = true;
57302 tpls.hcell.compile();
57305 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
57306 this.unselectableCls + '" ' + this.unselectable +'> </div>');
57307 tpls.hsplit.disableFormats = true;
57309 tpls.hsplit.compile();
57312 tpls.body = new Roo.Template(
57313 '<table border="0" cellspacing="0" cellpadding="0">',
57314 "<tbody>{rows}</tbody>",
57317 tpls.body.disableFormats = true;
57319 tpls.body.compile();
57322 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
57323 tpls.row.disableFormats = true;
57325 tpls.row.compile();
57328 tpls.cell = new Roo.Template(
57329 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
57330 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
57331 this.unselectableCls + '" ' + this.unselectable +'" {attr}>{value}</div></div>',
57334 tpls.cell.disableFormats = true;
57336 tpls.cell.compile();
57338 this.templates = tpls;
57341 // remap these for backwards compat
57342 onColWidthChange : function(){
57343 this.updateColumns.apply(this, arguments);
57345 onHeaderChange : function(){
57346 this.updateHeaders.apply(this, arguments);
57348 onHiddenChange : function(){
57349 this.handleHiddenChange.apply(this, arguments);
57351 onColumnMove : function(){
57352 this.handleColumnMove.apply(this, arguments);
57354 onColumnLock : function(){
57355 this.handleLockChange.apply(this, arguments);
57358 onDataChange : function(){
57360 this.updateHeaderSortState();
57363 onClear : function(){
57367 onUpdate : function(ds, record){
57368 this.refreshRow(record);
57371 refreshRow : function(record){
57372 var ds = this.ds, index;
57373 if(typeof record == 'number'){
57375 record = ds.getAt(index);
57377 index = ds.indexOf(record);
57379 this.insertRows(ds, index, index, true);
57380 this.onRemove(ds, record, index+1, true);
57381 this.syncRowHeights(index, index);
57383 this.fireEvent("rowupdated", this, index, record);
57386 onAdd : function(ds, records, index){
57387 this.insertRows(ds, index, index + (records.length-1));
57390 onRemove : function(ds, record, index, isUpdate){
57391 if(isUpdate !== true){
57392 this.fireEvent("beforerowremoved", this, index, record);
57394 var bt = this.getBodyTable(), lt = this.getLockedTable();
57395 if(bt.rows[index]){
57396 bt.firstChild.removeChild(bt.rows[index]);
57398 if(lt.rows[index]){
57399 lt.firstChild.removeChild(lt.rows[index]);
57401 if(isUpdate !== true){
57402 this.stripeRows(index);
57403 this.syncRowHeights(index, index);
57405 this.fireEvent("rowremoved", this, index, record);
57409 onLoad : function(){
57410 this.scrollToTop();
57414 * Scrolls the grid to the top
57416 scrollToTop : function(){
57418 this.scroller.dom.scrollTop = 0;
57424 * Gets a panel in the header of the grid that can be used for toolbars etc.
57425 * After modifying the contents of this panel a call to grid.autoSize() may be
57426 * required to register any changes in size.
57427 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
57428 * @return Roo.Element
57430 getHeaderPanel : function(doShow){
57432 this.headerPanel.show();
57434 return this.headerPanel;
57438 * Gets a panel in the footer of the grid that can be used for toolbars etc.
57439 * After modifying the contents of this panel a call to grid.autoSize() may be
57440 * required to register any changes in size.
57441 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
57442 * @return Roo.Element
57444 getFooterPanel : function(doShow){
57446 this.footerPanel.show();
57448 return this.footerPanel;
57451 initElements : function(){
57452 var E = Roo.Element;
57453 var el = this.grid.getGridEl().dom.firstChild;
57454 var cs = el.childNodes;
57456 this.el = new E(el);
57458 this.focusEl = new E(el.firstChild);
57459 this.focusEl.swallowEvent("click", true);
57461 this.headerPanel = new E(cs[1]);
57462 this.headerPanel.enableDisplayMode("block");
57464 this.scroller = new E(cs[2]);
57465 this.scrollSizer = new E(this.scroller.dom.firstChild);
57467 this.lockedWrap = new E(cs[3]);
57468 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
57469 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
57471 this.mainWrap = new E(cs[4]);
57472 this.mainHd = new E(this.mainWrap.dom.firstChild);
57473 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
57475 this.footerPanel = new E(cs[5]);
57476 this.footerPanel.enableDisplayMode("block");
57478 this.resizeProxy = new E(cs[6]);
57480 this.headerSelector = String.format(
57481 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
57482 this.lockedHd.id, this.mainHd.id
57485 this.splitterSelector = String.format(
57486 '#{0} div.x-grid-split, #{1} div.x-grid-split',
57487 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
57490 idToCssName : function(s)
57492 return s.replace(/[^a-z0-9]+/ig, '-');
57495 getHeaderCell : function(index){
57496 return Roo.DomQuery.select(this.headerSelector)[index];
57499 getHeaderCellMeasure : function(index){
57500 return this.getHeaderCell(index).firstChild;
57503 getHeaderCellText : function(index){
57504 return this.getHeaderCell(index).firstChild.firstChild;
57507 getLockedTable : function(){
57508 return this.lockedBody.dom.firstChild;
57511 getBodyTable : function(){
57512 return this.mainBody.dom.firstChild;
57515 getLockedRow : function(index){
57516 return this.getLockedTable().rows[index];
57519 getRow : function(index){
57520 return this.getBodyTable().rows[index];
57523 getRowComposite : function(index){
57525 this.rowEl = new Roo.CompositeElementLite();
57527 var els = [], lrow, mrow;
57528 if(lrow = this.getLockedRow(index)){
57531 if(mrow = this.getRow(index)){
57534 this.rowEl.elements = els;
57538 * Gets the 'td' of the cell
57540 * @param {Integer} rowIndex row to select
57541 * @param {Integer} colIndex column to select
57545 getCell : function(rowIndex, colIndex){
57546 var locked = this.cm.getLockedCount();
57548 if(colIndex < locked){
57549 source = this.lockedBody.dom.firstChild;
57551 source = this.mainBody.dom.firstChild;
57552 colIndex -= locked;
57554 return source.rows[rowIndex].childNodes[colIndex];
57557 getCellText : function(rowIndex, colIndex){
57558 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
57561 getCellBox : function(cell){
57562 var b = this.fly(cell).getBox();
57563 if(Roo.isOpera){ // opera fails to report the Y
57564 b.y = cell.offsetTop + this.mainBody.getY();
57569 getCellIndex : function(cell){
57570 var id = String(cell.className).match(this.cellRE);
57572 return parseInt(id[1], 10);
57577 findHeaderIndex : function(n){
57578 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
57579 return r ? this.getCellIndex(r) : false;
57582 findHeaderCell : function(n){
57583 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
57584 return r ? r : false;
57587 findRowIndex : function(n){
57591 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
57592 return r ? r.rowIndex : false;
57595 findCellIndex : function(node){
57596 var stop = this.el.dom;
57597 while(node && node != stop){
57598 if(this.findRE.test(node.className)){
57599 return this.getCellIndex(node);
57601 node = node.parentNode;
57606 getColumnId : function(index){
57607 return this.cm.getColumnId(index);
57610 getSplitters : function()
57612 if(this.splitterSelector){
57613 return Roo.DomQuery.select(this.splitterSelector);
57619 getSplitter : function(index){
57620 return this.getSplitters()[index];
57623 onRowOver : function(e, t){
57625 if((row = this.findRowIndex(t)) !== false){
57626 this.getRowComposite(row).addClass("x-grid-row-over");
57630 onRowOut : function(e, t){
57632 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
57633 this.getRowComposite(row).removeClass("x-grid-row-over");
57637 renderHeaders : function(){
57639 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
57640 var cb = [], lb = [], sb = [], lsb = [], p = {};
57641 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
57642 p.cellId = "x-grid-hd-0-" + i;
57643 p.splitId = "x-grid-csplit-0-" + i;
57644 p.id = cm.getColumnId(i);
57645 p.value = cm.getColumnHeader(i) || "";
57646 p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</) ? '' : p.value || "";
57647 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
57648 if(!cm.isLocked(i)){
57649 cb[cb.length] = ct.apply(p);
57650 sb[sb.length] = st.apply(p);
57652 lb[lb.length] = ct.apply(p);
57653 lsb[lsb.length] = st.apply(p);
57656 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
57657 ht.apply({cells: cb.join(""), splits:sb.join("")})];
57660 updateHeaders : function(){
57661 var html = this.renderHeaders();
57662 this.lockedHd.update(html[0]);
57663 this.mainHd.update(html[1]);
57667 * Focuses the specified row.
57668 * @param {Number} row The row index
57670 focusRow : function(row)
57672 //Roo.log('GridView.focusRow');
57673 var x = this.scroller.dom.scrollLeft;
57674 this.focusCell(row, 0, false);
57675 this.scroller.dom.scrollLeft = x;
57679 * Focuses the specified cell.
57680 * @param {Number} row The row index
57681 * @param {Number} col The column index
57682 * @param {Boolean} hscroll false to disable horizontal scrolling
57684 focusCell : function(row, col, hscroll)
57686 //Roo.log('GridView.focusCell');
57687 var el = this.ensureVisible(row, col, hscroll);
57688 this.focusEl.alignTo(el, "tl-tl");
57690 this.focusEl.focus();
57692 this.focusEl.focus.defer(1, this.focusEl);
57697 * Scrolls the specified cell into view
57698 * @param {Number} row The row index
57699 * @param {Number} col The column index
57700 * @param {Boolean} hscroll false to disable horizontal scrolling
57702 ensureVisible : function(row, col, hscroll)
57704 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
57705 //return null; //disable for testing.
57706 if(typeof row != "number"){
57707 row = row.rowIndex;
57709 if(row < 0 && row >= this.ds.getCount()){
57712 col = (col !== undefined ? col : 0);
57713 var cm = this.grid.colModel;
57714 while(cm.isHidden(col)){
57718 var el = this.getCell(row, col);
57722 var c = this.scroller.dom;
57724 var ctop = parseInt(el.offsetTop, 10);
57725 var cleft = parseInt(el.offsetLeft, 10);
57726 var cbot = ctop + el.offsetHeight;
57727 var cright = cleft + el.offsetWidth;
57729 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
57730 var stop = parseInt(c.scrollTop, 10);
57731 var sleft = parseInt(c.scrollLeft, 10);
57732 var sbot = stop + ch;
57733 var sright = sleft + c.clientWidth;
57735 Roo.log('GridView.ensureVisible:' +
57737 ' c.clientHeight:' + c.clientHeight +
57738 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
57746 c.scrollTop = ctop;
57747 //Roo.log("set scrolltop to ctop DISABLE?");
57748 }else if(cbot > sbot){
57749 //Roo.log("set scrolltop to cbot-ch");
57750 c.scrollTop = cbot-ch;
57753 if(hscroll !== false){
57755 c.scrollLeft = cleft;
57756 }else if(cright > sright){
57757 c.scrollLeft = cright-c.clientWidth;
57764 updateColumns : function(){
57765 this.grid.stopEditing();
57766 var cm = this.grid.colModel, colIds = this.getColumnIds();
57767 //var totalWidth = cm.getTotalWidth();
57769 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
57770 //if(cm.isHidden(i)) continue;
57771 var w = cm.getColumnWidth(i);
57772 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
57773 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
57775 this.updateSplitters();
57778 generateRules : function(cm){
57779 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
57780 Roo.util.CSS.removeStyleSheet(rulesId);
57781 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
57782 var cid = cm.getColumnId(i);
57784 if(cm.config[i].align){
57785 align = 'text-align:'+cm.config[i].align+';';
57788 if(cm.isHidden(i)){
57789 hidden = 'display:none;';
57791 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
57793 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
57794 this.hdSelector, cid, " {\n", align, width, "}\n",
57795 this.tdSelector, cid, " {\n",hidden,"\n}\n",
57796 this.splitSelector, cid, " {\n", hidden , "\n}\n");
57798 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
57801 updateSplitters : function(){
57802 var cm = this.cm, s = this.getSplitters();
57803 if(s){ // splitters not created yet
57804 var pos = 0, locked = true;
57805 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
57806 if(cm.isHidden(i)) {
57809 var w = cm.getColumnWidth(i); // make sure it's a number
57810 if(!cm.isLocked(i) && locked){
57815 s[i].style.left = (pos-this.splitOffset) + "px";
57820 handleHiddenChange : function(colModel, colIndex, hidden){
57822 this.hideColumn(colIndex);
57824 this.unhideColumn(colIndex);
57828 hideColumn : function(colIndex){
57829 var cid = this.getColumnId(colIndex);
57830 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
57831 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
57833 this.updateHeaders();
57835 this.updateSplitters();
57839 unhideColumn : function(colIndex){
57840 var cid = this.getColumnId(colIndex);
57841 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
57842 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
57845 this.updateHeaders();
57847 this.updateSplitters();
57851 insertRows : function(dm, firstRow, lastRow, isUpdate){
57852 if(firstRow == 0 && lastRow == dm.getCount()-1){
57856 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
57858 var s = this.getScrollState();
57859 var markup = this.renderRows(firstRow, lastRow);
57860 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
57861 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
57862 this.restoreScroll(s);
57864 this.fireEvent("rowsinserted", this, firstRow, lastRow);
57865 this.syncRowHeights(firstRow, lastRow);
57866 this.stripeRows(firstRow);
57872 bufferRows : function(markup, target, index){
57873 var before = null, trows = target.rows, tbody = target.tBodies[0];
57874 if(index < trows.length){
57875 before = trows[index];
57877 var b = document.createElement("div");
57878 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
57879 var rows = b.firstChild.rows;
57880 for(var i = 0, len = rows.length; i < len; i++){
57882 tbody.insertBefore(rows[0], before);
57884 tbody.appendChild(rows[0]);
57891 deleteRows : function(dm, firstRow, lastRow){
57892 if(dm.getRowCount()<1){
57893 this.fireEvent("beforerefresh", this);
57894 this.mainBody.update("");
57895 this.lockedBody.update("");
57896 this.fireEvent("refresh", this);
57898 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
57899 var bt = this.getBodyTable();
57900 var tbody = bt.firstChild;
57901 var rows = bt.rows;
57902 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
57903 tbody.removeChild(rows[firstRow]);
57905 this.stripeRows(firstRow);
57906 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
57910 updateRows : function(dataSource, firstRow, lastRow){
57911 var s = this.getScrollState();
57913 this.restoreScroll(s);
57916 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
57920 this.updateHeaderSortState();
57923 getScrollState : function(){
57925 var sb = this.scroller.dom;
57926 return {left: sb.scrollLeft, top: sb.scrollTop};
57929 stripeRows : function(startRow){
57930 if(!this.grid.stripeRows || this.ds.getCount() < 1){
57933 startRow = startRow || 0;
57934 var rows = this.getBodyTable().rows;
57935 var lrows = this.getLockedTable().rows;
57936 var cls = ' x-grid-row-alt ';
57937 for(var i = startRow, len = rows.length; i < len; i++){
57938 var row = rows[i], lrow = lrows[i];
57939 var isAlt = ((i+1) % 2 == 0);
57940 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
57941 if(isAlt == hasAlt){
57945 row.className += " x-grid-row-alt";
57947 row.className = row.className.replace("x-grid-row-alt", "");
57950 lrow.className = row.className;
57955 restoreScroll : function(state){
57956 //Roo.log('GridView.restoreScroll');
57957 var sb = this.scroller.dom;
57958 sb.scrollLeft = state.left;
57959 sb.scrollTop = state.top;
57963 syncScroll : function(){
57964 //Roo.log('GridView.syncScroll');
57965 var sb = this.scroller.dom;
57966 var sh = this.mainHd.dom;
57967 var bs = this.mainBody.dom;
57968 var lv = this.lockedBody.dom;
57969 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
57970 lv.scrollTop = bs.scrollTop = sb.scrollTop;
57973 handleScroll : function(e){
57975 var sb = this.scroller.dom;
57976 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
57980 handleWheel : function(e){
57981 var d = e.getWheelDelta();
57982 this.scroller.dom.scrollTop -= d*22;
57983 // set this here to prevent jumpy scrolling on large tables
57984 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
57988 renderRows : function(startRow, endRow){
57989 // pull in all the crap needed to render rows
57990 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
57991 var colCount = cm.getColumnCount();
57993 if(ds.getCount() < 1){
57997 // build a map for all the columns
57999 for(var i = 0; i < colCount; i++){
58000 var name = cm.getDataIndex(i);
58002 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
58003 renderer : cm.getRenderer(i),
58004 id : cm.getColumnId(i),
58005 locked : cm.isLocked(i),
58006 has_editor : cm.isCellEditable(i)
58010 startRow = startRow || 0;
58011 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
58013 // records to render
58014 var rs = ds.getRange(startRow, endRow);
58016 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
58019 // As much as I hate to duplicate code, this was branched because FireFox really hates
58020 // [].join("") on strings. The performance difference was substantial enough to
58021 // branch this function
58022 doRender : Roo.isGecko ?
58023 function(cs, rs, ds, startRow, colCount, stripe){
58024 var ts = this.templates, ct = ts.cell, rt = ts.row;
58026 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
58028 var hasListener = this.grid.hasListener('rowclass');
58030 for(var j = 0, len = rs.length; j < len; j++){
58031 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
58032 for(var i = 0; i < colCount; i++){
58034 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
58036 p.css = p.attr = "";
58037 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
58038 if(p.value == undefined || p.value === "") {
58039 p.value = " ";
58042 p.css += ' x-grid-editable-cell';
58044 if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
58045 p.css += ' x-grid-dirty-cell';
58047 var markup = ct.apply(p);
58055 if(stripe && ((rowIndex+1) % 2 == 0)){
58056 alt.push("x-grid-row-alt")
58059 alt.push( " x-grid-dirty-row");
58062 if(this.getRowClass){
58063 alt.push(this.getRowClass(r, rowIndex));
58069 rowIndex : rowIndex,
58072 this.grid.fireEvent('rowclass', this, rowcfg);
58073 alt.push(rowcfg.rowClass);
58075 rp.alt = alt.join(" ");
58076 lbuf+= rt.apply(rp);
58078 buf+= rt.apply(rp);
58080 return [lbuf, buf];
58082 function(cs, rs, ds, startRow, colCount, stripe){
58083 var ts = this.templates, ct = ts.cell, rt = ts.row;
58085 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
58086 var hasListener = this.grid.hasListener('rowclass');
58089 for(var j = 0, len = rs.length; j < len; j++){
58090 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
58091 for(var i = 0; i < colCount; i++){
58093 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
58095 p.css = p.attr = "";
58096 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
58097 if(p.value == undefined || p.value === "") {
58098 p.value = " ";
58102 p.css += ' x-grid-editable-cell';
58104 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
58105 p.css += ' x-grid-dirty-cell'
58108 var markup = ct.apply(p);
58110 cb[cb.length] = markup;
58112 lcb[lcb.length] = markup;
58116 if(stripe && ((rowIndex+1) % 2 == 0)){
58117 alt.push( "x-grid-row-alt");
58120 alt.push(" x-grid-dirty-row");
58123 if(this.getRowClass){
58124 alt.push( this.getRowClass(r, rowIndex));
58130 rowIndex : rowIndex,
58133 this.grid.fireEvent('rowclass', this, rowcfg);
58134 alt.push(rowcfg.rowClass);
58137 rp.alt = alt.join(" ");
58138 rp.cells = lcb.join("");
58139 lbuf[lbuf.length] = rt.apply(rp);
58140 rp.cells = cb.join("");
58141 buf[buf.length] = rt.apply(rp);
58143 return [lbuf.join(""), buf.join("")];
58146 renderBody : function(){
58147 var markup = this.renderRows();
58148 var bt = this.templates.body;
58149 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
58153 * Refreshes the grid
58154 * @param {Boolean} headersToo
58156 refresh : function(headersToo){
58157 this.fireEvent("beforerefresh", this);
58158 this.grid.stopEditing();
58159 var result = this.renderBody();
58160 this.lockedBody.update(result[0]);
58161 this.mainBody.update(result[1]);
58162 if(headersToo === true){
58163 this.updateHeaders();
58164 this.updateColumns();
58165 this.updateSplitters();
58166 this.updateHeaderSortState();
58168 this.syncRowHeights();
58170 this.fireEvent("refresh", this);
58173 handleColumnMove : function(cm, oldIndex, newIndex){
58174 this.indexMap = null;
58175 var s = this.getScrollState();
58176 this.refresh(true);
58177 this.restoreScroll(s);
58178 this.afterMove(newIndex);
58181 afterMove : function(colIndex){
58182 if(this.enableMoveAnim && Roo.enableFx){
58183 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
58185 // if multisort - fix sortOrder, and reload..
58186 if (this.grid.dataSource.multiSort) {
58187 // the we can call sort again..
58188 var dm = this.grid.dataSource;
58189 var cm = this.grid.colModel;
58191 for(var i = 0; i < cm.config.length; i++ ) {
58193 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
58194 continue; // dont' bother, it's not in sort list or being set.
58197 so.push(cm.config[i].dataIndex);
58200 dm.load(dm.lastOptions);
58207 updateCell : function(dm, rowIndex, dataIndex){
58208 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
58209 if(typeof colIndex == "undefined"){ // not present in grid
58212 var cm = this.grid.colModel;
58213 var cell = this.getCell(rowIndex, colIndex);
58214 var cellText = this.getCellText(rowIndex, colIndex);
58217 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
58218 id : cm.getColumnId(colIndex),
58219 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
58221 var renderer = cm.getRenderer(colIndex);
58222 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
58223 if(typeof val == "undefined" || val === "") {
58226 cellText.innerHTML = val;
58227 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
58228 this.syncRowHeights(rowIndex, rowIndex);
58231 calcColumnWidth : function(colIndex, maxRowsToMeasure){
58233 if(this.grid.autoSizeHeaders){
58234 var h = this.getHeaderCellMeasure(colIndex);
58235 maxWidth = Math.max(maxWidth, h.scrollWidth);
58238 if(this.cm.isLocked(colIndex)){
58239 tb = this.getLockedTable();
58242 tb = this.getBodyTable();
58243 index = colIndex - this.cm.getLockedCount();
58246 var rows = tb.rows;
58247 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
58248 for(var i = 0; i < stopIndex; i++){
58249 var cell = rows[i].childNodes[index].firstChild;
58250 maxWidth = Math.max(maxWidth, cell.scrollWidth);
58253 return maxWidth + /*margin for error in IE*/ 5;
58256 * Autofit a column to its content.
58257 * @param {Number} colIndex
58258 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
58260 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
58261 if(this.cm.isHidden(colIndex)){
58262 return; // can't calc a hidden column
58265 var cid = this.cm.getColumnId(colIndex);
58266 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
58267 if(this.grid.autoSizeHeaders){
58268 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
58271 var newWidth = this.calcColumnWidth(colIndex);
58272 this.cm.setColumnWidth(colIndex,
58273 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
58274 if(!suppressEvent){
58275 this.grid.fireEvent("columnresize", colIndex, newWidth);
58280 * Autofits all columns to their content and then expands to fit any extra space in the grid
58282 autoSizeColumns : function(){
58283 var cm = this.grid.colModel;
58284 var colCount = cm.getColumnCount();
58285 for(var i = 0; i < colCount; i++){
58286 this.autoSizeColumn(i, true, true);
58288 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
58291 this.updateColumns();
58297 * Autofits all columns to the grid's width proportionate with their current size
58298 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
58300 fitColumns : function(reserveScrollSpace){
58301 var cm = this.grid.colModel;
58302 var colCount = cm.getColumnCount();
58306 for (i = 0; i < colCount; i++){
58307 if(!cm.isHidden(i) && !cm.isFixed(i)){
58308 w = cm.getColumnWidth(i);
58314 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
58315 if(reserveScrollSpace){
58318 var frac = (avail - cm.getTotalWidth())/width;
58319 while (cols.length){
58322 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
58324 this.updateColumns();
58328 onRowSelect : function(rowIndex){
58329 var row = this.getRowComposite(rowIndex);
58330 row.addClass("x-grid-row-selected");
58333 onRowDeselect : function(rowIndex){
58334 var row = this.getRowComposite(rowIndex);
58335 row.removeClass("x-grid-row-selected");
58338 onCellSelect : function(row, col){
58339 var cell = this.getCell(row, col);
58341 Roo.fly(cell).addClass("x-grid-cell-selected");
58345 onCellDeselect : function(row, col){
58346 var cell = this.getCell(row, col);
58348 Roo.fly(cell).removeClass("x-grid-cell-selected");
58352 updateHeaderSortState : function(){
58354 // sort state can be single { field: xxx, direction : yyy}
58355 // or { xxx=>ASC , yyy : DESC ..... }
58358 if (!this.ds.multiSort) {
58359 var state = this.ds.getSortState();
58363 mstate[state.field] = state.direction;
58364 // FIXME... - this is not used here.. but might be elsewhere..
58365 this.sortState = state;
58368 mstate = this.ds.sortToggle;
58370 //remove existing sort classes..
58372 var sc = this.sortClasses;
58373 var hds = this.el.select(this.headerSelector).removeClass(sc);
58375 for(var f in mstate) {
58377 var sortColumn = this.cm.findColumnIndex(f);
58379 if(sortColumn != -1){
58380 var sortDir = mstate[f];
58381 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
58390 handleHeaderClick : function(g, index,e){
58392 Roo.log("header click");
58395 // touch events on header are handled by context
58396 this.handleHdCtx(g,index,e);
58401 if(this.headersDisabled){
58404 var dm = g.dataSource, cm = g.colModel;
58405 if(!cm.isSortable(index)){
58410 if (dm.multiSort) {
58411 // update the sortOrder
58413 for(var i = 0; i < cm.config.length; i++ ) {
58415 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
58416 continue; // dont' bother, it's not in sort list or being set.
58419 so.push(cm.config[i].dataIndex);
58425 dm.sort(cm.getDataIndex(index));
58429 destroy : function(){
58431 this.colMenu.removeAll();
58432 Roo.menu.MenuMgr.unregister(this.colMenu);
58433 this.colMenu.getEl().remove();
58434 delete this.colMenu;
58437 this.hmenu.removeAll();
58438 Roo.menu.MenuMgr.unregister(this.hmenu);
58439 this.hmenu.getEl().remove();
58442 if(this.grid.enableColumnMove){
58443 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
58445 for(var dd in dds){
58446 if(!dds[dd].config.isTarget && dds[dd].dragElId){
58447 var elid = dds[dd].dragElId;
58449 Roo.get(elid).remove();
58450 } else if(dds[dd].config.isTarget){
58451 dds[dd].proxyTop.remove();
58452 dds[dd].proxyBottom.remove();
58455 if(Roo.dd.DDM.locationCache[dd]){
58456 delete Roo.dd.DDM.locationCache[dd];
58459 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
58462 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
58463 this.bind(null, null);
58464 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
58467 handleLockChange : function(){
58468 this.refresh(true);
58471 onDenyColumnLock : function(){
58475 onDenyColumnHide : function(){
58479 handleHdMenuClick : function(item){
58480 var index = this.hdCtxIndex;
58481 var cm = this.cm, ds = this.ds;
58484 ds.sort(cm.getDataIndex(index), "ASC");
58487 ds.sort(cm.getDataIndex(index), "DESC");
58490 var lc = cm.getLockedCount();
58491 if(cm.getColumnCount(true) <= lc+1){
58492 this.onDenyColumnLock();
58496 cm.setLocked(index, true, true);
58497 cm.moveColumn(index, lc);
58498 this.grid.fireEvent("columnmove", index, lc);
58500 cm.setLocked(index, true);
58504 var lc = cm.getLockedCount();
58505 if((lc-1) != index){
58506 cm.setLocked(index, false, true);
58507 cm.moveColumn(index, lc-1);
58508 this.grid.fireEvent("columnmove", index, lc-1);
58510 cm.setLocked(index, false);
58513 case 'wider': // used to expand cols on touch..
58515 var cw = cm.getColumnWidth(index);
58516 cw += (item.id == 'wider' ? 1 : -1) * 50;
58517 cw = Math.max(0, cw);
58518 cw = Math.min(cw,4000);
58519 cm.setColumnWidth(index, cw);
58523 index = cm.getIndexById(item.id.substr(4));
58525 if(item.checked && cm.getColumnCount(true) <= 1){
58526 this.onDenyColumnHide();
58529 cm.setHidden(index, item.checked);
58535 beforeColMenuShow : function(){
58536 var cm = this.cm, colCount = cm.getColumnCount();
58537 this.colMenu.removeAll();
58538 for(var i = 0; i < colCount; i++){
58539 this.colMenu.add(new Roo.menu.CheckItem({
58540 id: "col-"+cm.getColumnId(i),
58541 text: cm.getColumnHeader(i),
58542 checked: !cm.isHidden(i),
58548 handleHdCtx : function(g, index, e){
58550 var hd = this.getHeaderCell(index);
58551 this.hdCtxIndex = index;
58552 var ms = this.hmenu.items, cm = this.cm;
58553 ms.get("asc").setDisabled(!cm.isSortable(index));
58554 ms.get("desc").setDisabled(!cm.isSortable(index));
58555 if(this.grid.enableColLock !== false){
58556 ms.get("lock").setDisabled(cm.isLocked(index));
58557 ms.get("unlock").setDisabled(!cm.isLocked(index));
58559 this.hmenu.show(hd, "tl-bl");
58562 handleHdOver : function(e){
58563 var hd = this.findHeaderCell(e.getTarget());
58564 if(hd && !this.headersDisabled){
58565 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
58566 this.fly(hd).addClass("x-grid-hd-over");
58571 handleHdOut : function(e){
58572 var hd = this.findHeaderCell(e.getTarget());
58574 this.fly(hd).removeClass("x-grid-hd-over");
58578 handleSplitDblClick : function(e, t){
58579 var i = this.getCellIndex(t);
58580 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
58581 this.autoSizeColumn(i, true);
58586 render : function(){
58589 var colCount = cm.getColumnCount();
58591 if(this.grid.monitorWindowResize === true){
58592 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
58594 var header = this.renderHeaders();
58595 var body = this.templates.body.apply({rows:""});
58596 var html = this.templates.master.apply({
58599 lockedHeader: header[0],
58603 //this.updateColumns();
58605 this.grid.getGridEl().dom.innerHTML = html;
58607 this.initElements();
58609 // a kludge to fix the random scolling effect in webkit
58610 this.el.on("scroll", function() {
58611 this.el.dom.scrollTop=0; // hopefully not recursive..
58614 this.scroller.on("scroll", this.handleScroll, this);
58615 this.lockedBody.on("mousewheel", this.handleWheel, this);
58616 this.mainBody.on("mousewheel", this.handleWheel, this);
58618 this.mainHd.on("mouseover", this.handleHdOver, this);
58619 this.mainHd.on("mouseout", this.handleHdOut, this);
58620 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
58621 {delegate: "."+this.splitClass});
58623 this.lockedHd.on("mouseover", this.handleHdOver, this);
58624 this.lockedHd.on("mouseout", this.handleHdOut, this);
58625 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
58626 {delegate: "."+this.splitClass});
58628 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
58629 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
58632 this.updateSplitters();
58634 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
58635 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
58636 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
58639 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
58640 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
58642 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
58643 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
58645 if(this.grid.enableColLock !== false){
58646 this.hmenu.add('-',
58647 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
58648 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
58652 this.hmenu.add('-',
58653 {id:"wider", text: this.columnsWiderText},
58654 {id:"narrow", text: this.columnsNarrowText }
58660 if(this.grid.enableColumnHide !== false){
58662 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
58663 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
58664 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
58666 this.hmenu.add('-',
58667 {id:"columns", text: this.columnsText, menu: this.colMenu}
58670 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
58672 this.grid.on("headercontextmenu", this.handleHdCtx, this);
58675 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
58676 this.dd = new Roo.grid.GridDragZone(this.grid, {
58677 ddGroup : this.grid.ddGroup || 'GridDD'
58683 for(var i = 0; i < colCount; i++){
58684 if(cm.isHidden(i)){
58685 this.hideColumn(i);
58687 if(cm.config[i].align){
58688 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
58689 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
58693 this.updateHeaderSortState();
58695 this.beforeInitialResize();
58698 // two part rendering gives faster view to the user
58699 this.renderPhase2.defer(1, this);
58702 renderPhase2 : function(){
58703 // render the rows now
58705 if(this.grid.autoSizeColumns){
58706 this.autoSizeColumns();
58710 beforeInitialResize : function(){
58714 onColumnSplitterMoved : function(i, w){
58715 this.userResized = true;
58716 var cm = this.grid.colModel;
58717 cm.setColumnWidth(i, w, true);
58718 var cid = cm.getColumnId(i);
58719 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
58720 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
58721 this.updateSplitters();
58723 this.grid.fireEvent("columnresize", i, w);
58726 syncRowHeights : function(startIndex, endIndex){
58727 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
58728 startIndex = startIndex || 0;
58729 var mrows = this.getBodyTable().rows;
58730 var lrows = this.getLockedTable().rows;
58731 var len = mrows.length-1;
58732 endIndex = Math.min(endIndex || len, len);
58733 for(var i = startIndex; i <= endIndex; i++){
58734 var m = mrows[i], l = lrows[i];
58735 var h = Math.max(m.offsetHeight, l.offsetHeight);
58736 m.style.height = l.style.height = h + "px";
58741 layout : function(initialRender, is2ndPass)
58744 var auto = g.autoHeight;
58745 var scrollOffset = 16;
58746 var c = g.getGridEl(), cm = this.cm,
58747 expandCol = g.autoExpandColumn,
58749 //c.beginMeasure();
58751 if(!c.dom.offsetWidth){ // display:none?
58753 this.lockedWrap.show();
58754 this.mainWrap.show();
58759 var hasLock = this.cm.isLocked(0);
58761 var tbh = this.headerPanel.getHeight();
58762 var bbh = this.footerPanel.getHeight();
58765 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
58766 var newHeight = ch + c.getBorderWidth("tb");
58768 newHeight = Math.min(g.maxHeight, newHeight);
58770 c.setHeight(newHeight);
58774 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
58777 var s = this.scroller;
58779 var csize = c.getSize(true);
58781 this.el.setSize(csize.width, csize.height);
58783 this.headerPanel.setWidth(csize.width);
58784 this.footerPanel.setWidth(csize.width);
58786 var hdHeight = this.mainHd.getHeight();
58787 var vw = csize.width;
58788 var vh = csize.height - (tbh + bbh);
58792 var bt = this.getBodyTable();
58794 if(cm.getLockedCount() == cm.config.length){
58795 bt = this.getLockedTable();
58798 var ltWidth = hasLock ?
58799 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
58801 var scrollHeight = bt.offsetHeight;
58802 var scrollWidth = ltWidth + bt.offsetWidth;
58803 var vscroll = false, hscroll = false;
58805 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
58807 var lw = this.lockedWrap, mw = this.mainWrap;
58808 var lb = this.lockedBody, mb = this.mainBody;
58810 setTimeout(function(){
58811 var t = s.dom.offsetTop;
58812 var w = s.dom.clientWidth,
58813 h = s.dom.clientHeight;
58816 lw.setSize(ltWidth, h);
58818 mw.setLeftTop(ltWidth, t);
58819 mw.setSize(w-ltWidth, h);
58821 lb.setHeight(h-hdHeight);
58822 mb.setHeight(h-hdHeight);
58824 if(is2ndPass !== true && !gv.userResized && expandCol){
58825 // high speed resize without full column calculation
58827 var ci = cm.getIndexById(expandCol);
58829 ci = cm.findColumnIndex(expandCol);
58831 ci = Math.max(0, ci); // make sure it's got at least the first col.
58832 var expandId = cm.getColumnId(ci);
58833 var tw = cm.getTotalWidth(false);
58834 var currentWidth = cm.getColumnWidth(ci);
58835 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
58836 if(currentWidth != cw){
58837 cm.setColumnWidth(ci, cw, true);
58838 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
58839 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
58840 gv.updateSplitters();
58841 gv.layout(false, true);
58853 onWindowResize : function(){
58854 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
58860 appendFooter : function(parentEl){
58864 sortAscText : "Sort Ascending",
58865 sortDescText : "Sort Descending",
58866 lockText : "Lock Column",
58867 unlockText : "Unlock Column",
58868 columnsText : "Columns",
58870 columnsWiderText : "Wider",
58871 columnsNarrowText : "Thinner"
58875 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
58876 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
58877 this.proxy.el.addClass('x-grid3-col-dd');
58880 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
58881 handleMouseDown : function(e){
58885 callHandleMouseDown : function(e){
58886 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
58891 * Ext JS Library 1.1.1
58892 * Copyright(c) 2006-2007, Ext JS, LLC.
58894 * Originally Released Under LGPL - original licence link has changed is not relivant.
58897 * <script type="text/javascript">
58900 * @extends Roo.dd.DDProxy
58901 * @class Roo.grid.SplitDragZone
58902 * Support for Column Header resizing
58904 * @param {Object} config
58907 // This is a support class used internally by the Grid components
58908 Roo.grid.SplitDragZone = function(grid, hd, hd2){
58910 this.view = grid.getView();
58911 this.proxy = this.view.resizeProxy;
58912 Roo.grid.SplitDragZone.superclass.constructor.call(
58915 "gridSplitters" + this.grid.getGridEl().id, // SGROUP
58917 dragElId : Roo.id(this.proxy.dom),
58922 this.setHandleElId(Roo.id(hd));
58923 if (hd2 !== false) {
58924 this.setOuterHandleElId(Roo.id(hd2));
58927 this.scroll = false;
58929 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
58930 fly: Roo.Element.fly,
58932 b4StartDrag : function(x, y){
58933 this.view.headersDisabled = true;
58934 var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
58935 this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
58937 this.proxy.setHeight(h);
58939 // for old system colWidth really stored the actual width?
58940 // in bootstrap we tried using xs/ms/etc.. to do % sizing?
58941 // which in reality did not work.. - it worked only for fixed sizes
58942 // for resizable we need to use actual sizes.
58943 var w = this.cm.getColumnWidth(this.cellIndex);
58944 if (!this.view.mainWrap) {
58946 w = this.view.getHeaderIndex(this.cellIndex).getWidth();
58951 // this was w-this.grid.minColumnWidth;
58952 // doesnt really make sense? - w = thie curren width or the rendered one?
58953 var minw = Math.max(w-this.grid.minColumnWidth, 0);
58954 this.resetConstraints();
58955 this.setXConstraint(minw, 1000);
58956 this.setYConstraint(0, 0);
58957 this.minX = x - minw;
58958 this.maxX = x + 1000;
58960 if (!this.view.mainWrap) { // this is Bootstrap code..
58961 this.getDragEl().style.display='block';
58964 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
58968 handleMouseDown : function(e){
58969 ev = Roo.EventObject.setEvent(e);
58970 var t = this.fly(ev.getTarget());
58971 if(t.hasClass("x-grid-split")){
58972 this.cellIndex = this.view.getCellIndex(t.dom);
58973 this.split = t.dom;
58974 this.cm = this.grid.colModel;
58975 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
58976 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
58981 endDrag : function(e){
58982 this.view.headersDisabled = false;
58983 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
58984 var diff = endX - this.startPos;
58986 var w = this.cm.getColumnWidth(this.cellIndex);
58987 if (!this.view.mainWrap) {
58990 this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
58993 autoOffset : function(){
58994 this.setDelta(0,0);
58998 * Ext JS Library 1.1.1
58999 * Copyright(c) 2006-2007, Ext JS, LLC.
59001 * Originally Released Under LGPL - original licence link has changed is not relivant.
59004 * <script type="text/javascript">
59008 // This is a support class used internally by the Grid components
59009 Roo.grid.GridDragZone = function(grid, config){
59010 this.view = grid.getView();
59011 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
59012 if(this.view.lockedBody){
59013 this.setHandleElId(Roo.id(this.view.mainBody.dom));
59014 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
59016 this.scroll = false;
59018 this.ddel = document.createElement('div');
59019 this.ddel.className = 'x-grid-dd-wrap';
59022 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
59023 ddGroup : "GridDD",
59025 getDragData : function(e){
59026 var t = Roo.lib.Event.getTarget(e);
59027 var rowIndex = this.view.findRowIndex(t);
59028 var sm = this.grid.selModel;
59030 //Roo.log(rowIndex);
59032 if (sm.getSelectedCell) {
59033 // cell selection..
59034 if (!sm.getSelectedCell()) {
59037 if (rowIndex != sm.getSelectedCell()[0]) {
59042 if (sm.getSelections && sm.getSelections().length < 1) {
59047 // before it used to all dragging of unseleted... - now we dont do that.
59048 if(rowIndex !== false){
59053 //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
59055 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
59058 if (e.hasModifier()){
59059 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
59062 Roo.log("getDragData");
59067 rowIndex: rowIndex,
59068 selections: sm.getSelections ? sm.getSelections() : (
59069 sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
59076 onInitDrag : function(e){
59077 var data = this.dragData;
59078 this.ddel.innerHTML = this.grid.getDragDropText();
59079 this.proxy.update(this.ddel);
59080 // fire start drag?
59083 afterRepair : function(){
59084 this.dragging = false;
59087 getRepairXY : function(e, data){
59091 onEndDrag : function(data, e){
59095 onValidDrop : function(dd, e, id){
59100 beforeInvalidDrop : function(e, id){
59105 * Ext JS Library 1.1.1
59106 * Copyright(c) 2006-2007, Ext JS, LLC.
59108 * Originally Released Under LGPL - original licence link has changed is not relivant.
59111 * <script type="text/javascript">
59116 * @class Roo.grid.ColumnModel
59117 * @extends Roo.util.Observable
59118 * This is the default implementation of a ColumnModel used by the Grid. It defines
59119 * the columns in the grid.
59122 var colModel = new Roo.grid.ColumnModel([
59123 {header: "Ticker", width: 60, sortable: true, locked: true},
59124 {header: "Company Name", width: 150, sortable: true},
59125 {header: "Market Cap.", width: 100, sortable: true},
59126 {header: "$ Sales", width: 100, sortable: true, renderer: money},
59127 {header: "Employees", width: 100, sortable: true, resizable: false}
59132 * The config options listed for this class are options which may appear in each
59133 * individual column definition.
59134 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
59136 * @param {Object} config An Array of column config objects. See this class's
59137 * config objects for details.
59139 Roo.grid.ColumnModel = function(config){
59141 * The config passed into the constructor
59143 this.config = []; //config;
59146 // if no id, create one
59147 // if the column does not have a dataIndex mapping,
59148 // map it to the order it is in the config
59149 for(var i = 0, len = config.length; i < len; i++){
59150 this.addColumn(config[i]);
59155 * The width of columns which have no width specified (defaults to 100)
59158 this.defaultWidth = 100;
59161 * Default sortable of columns which have no sortable specified (defaults to false)
59164 this.defaultSortable = false;
59168 * @event widthchange
59169 * Fires when the width of a column changes.
59170 * @param {ColumnModel} this
59171 * @param {Number} columnIndex The column index
59172 * @param {Number} newWidth The new width
59174 "widthchange": true,
59176 * @event headerchange
59177 * Fires when the text of a header changes.
59178 * @param {ColumnModel} this
59179 * @param {Number} columnIndex The column index
59180 * @param {Number} newText The new header text
59182 "headerchange": true,
59184 * @event hiddenchange
59185 * Fires when a column is hidden or "unhidden".
59186 * @param {ColumnModel} this
59187 * @param {Number} columnIndex The column index
59188 * @param {Boolean} hidden true if hidden, false otherwise
59190 "hiddenchange": true,
59192 * @event columnmoved
59193 * Fires when a column is moved.
59194 * @param {ColumnModel} this
59195 * @param {Number} oldIndex
59196 * @param {Number} newIndex
59198 "columnmoved" : true,
59200 * @event columlockchange
59201 * Fires when a column's locked state is changed
59202 * @param {ColumnModel} this
59203 * @param {Number} colIndex
59204 * @param {Boolean} locked true if locked
59206 "columnlockchange" : true
59208 Roo.grid.ColumnModel.superclass.constructor.call(this);
59210 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
59212 * @cfg {String} header The header text to display in the Grid view.
59215 * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
59218 * @cfg {String} smHeader Header at Bootsrap Small width
59221 * @cfg {String} mdHeader Header at Bootsrap Medium width
59224 * @cfg {String} lgHeader Header at Bootsrap Large width
59227 * @cfg {String} xlHeader Header at Bootsrap extra Large width
59230 * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
59231 * {@link Roo.data.Record} definition from which to draw the column's value. If not
59232 * specified, the column's index is used as an index into the Record's data Array.
59235 * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
59236 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
59239 * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
59240 * Defaults to the value of the {@link #defaultSortable} property.
59241 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
59244 * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
59247 * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
59250 * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
59253 * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
59256 * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
59257 * given the cell's data value. See {@link #setRenderer}. If not specified, the
59258 * default renderer returns the escaped data value. If an object is returned (bootstrap only)
59259 * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
59262 * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
59265 * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
59268 * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc). Defaults to undefined.
59271 * @cfg {String} cursor (Optional)
59274 * @cfg {String} tooltip (Optional)
59277 * @cfg {Number} xs (Optional) can be '0' for hidden at this size (number less than 12)
59280 * @cfg {Number} sm (Optional) can be '0' for hidden at this size (number less than 12)
59283 * @cfg {Number} md (Optional) can be '0' for hidden at this size (number less than 12)
59286 * @cfg {Number} lg (Optional) can be '0' for hidden at this size (number less than 12)
59289 * @cfg {Number} xl (Optional) can be '0' for hidden at this size (number less than 12)
59292 * Returns the id of the column at the specified index.
59293 * @param {Number} index The column index
59294 * @return {String} the id
59296 getColumnId : function(index){
59297 return this.config[index].id;
59301 * Returns the column for a specified id.
59302 * @param {String} id The column id
59303 * @return {Object} the column
59305 getColumnById : function(id){
59306 return this.lookup[id];
59311 * Returns the column Object for a specified dataIndex.
59312 * @param {String} dataIndex The column dataIndex
59313 * @return {Object|Boolean} the column or false if not found
59315 getColumnByDataIndex: function(dataIndex){
59316 var index = this.findColumnIndex(dataIndex);
59317 return index > -1 ? this.config[index] : false;
59321 * Returns the index for a specified column id.
59322 * @param {String} id The column id
59323 * @return {Number} the index, or -1 if not found
59325 getIndexById : function(id){
59326 for(var i = 0, len = this.config.length; i < len; i++){
59327 if(this.config[i].id == id){
59335 * Returns the index for a specified column dataIndex.
59336 * @param {String} dataIndex The column dataIndex
59337 * @return {Number} the index, or -1 if not found
59340 findColumnIndex : function(dataIndex){
59341 for(var i = 0, len = this.config.length; i < len; i++){
59342 if(this.config[i].dataIndex == dataIndex){
59350 moveColumn : function(oldIndex, newIndex){
59351 var c = this.config[oldIndex];
59352 this.config.splice(oldIndex, 1);
59353 this.config.splice(newIndex, 0, c);
59354 this.dataMap = null;
59355 this.fireEvent("columnmoved", this, oldIndex, newIndex);
59358 isLocked : function(colIndex){
59359 return this.config[colIndex].locked === true;
59362 setLocked : function(colIndex, value, suppressEvent){
59363 if(this.isLocked(colIndex) == value){
59366 this.config[colIndex].locked = value;
59367 if(!suppressEvent){
59368 this.fireEvent("columnlockchange", this, colIndex, value);
59372 getTotalLockedWidth : function(){
59373 var totalWidth = 0;
59374 for(var i = 0; i < this.config.length; i++){
59375 if(this.isLocked(i) && !this.isHidden(i)){
59376 this.totalWidth += this.getColumnWidth(i);
59382 getLockedCount : function(){
59383 for(var i = 0, len = this.config.length; i < len; i++){
59384 if(!this.isLocked(i)){
59389 return this.config.length;
59393 * Returns the number of columns.
59396 getColumnCount : function(visibleOnly){
59397 if(visibleOnly === true){
59399 for(var i = 0, len = this.config.length; i < len; i++){
59400 if(!this.isHidden(i)){
59406 return this.config.length;
59410 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
59411 * @param {Function} fn
59412 * @param {Object} scope (optional)
59413 * @return {Array} result
59415 getColumnsBy : function(fn, scope){
59417 for(var i = 0, len = this.config.length; i < len; i++){
59418 var c = this.config[i];
59419 if(fn.call(scope||this, c, i) === true){
59427 * Returns true if the specified column is sortable.
59428 * @param {Number} col The column index
59429 * @return {Boolean}
59431 isSortable : function(col){
59432 if(typeof this.config[col].sortable == "undefined"){
59433 return this.defaultSortable;
59435 return this.config[col].sortable;
59439 * Returns the rendering (formatting) function defined for the column.
59440 * @param {Number} col The column index.
59441 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
59443 getRenderer : function(col){
59444 if(!this.config[col].renderer){
59445 return Roo.grid.ColumnModel.defaultRenderer;
59447 return this.config[col].renderer;
59451 * Sets the rendering (formatting) function for a column.
59452 * @param {Number} col The column index
59453 * @param {Function} fn The function to use to process the cell's raw data
59454 * to return HTML markup for the grid view. The render function is called with
59455 * the following parameters:<ul>
59456 * <li>Data value.</li>
59457 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
59458 * <li>css A CSS style string to apply to the table cell.</li>
59459 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
59460 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
59461 * <li>Row index</li>
59462 * <li>Column index</li>
59463 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
59465 setRenderer : function(col, fn){
59466 this.config[col].renderer = fn;
59470 * Returns the width for the specified column.
59471 * @param {Number} col The column index
59472 * @param (optional) {String} gridSize bootstrap width size.
59475 getColumnWidth : function(col, gridSize)
59477 var cfg = this.config[col];
59479 if (typeof(gridSize) == 'undefined') {
59480 return cfg.width * 1 || this.defaultWidth;
59482 if (gridSize === false) { // if we set it..
59483 return cfg.width || false;
59485 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
59487 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
59488 if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
59491 return cfg[ sizes[i] ];
59498 * Sets the width for a column.
59499 * @param {Number} col The column index
59500 * @param {Number} width The new width
59502 setColumnWidth : function(col, width, suppressEvent){
59503 this.config[col].width = width;
59504 this.totalWidth = null;
59505 if(!suppressEvent){
59506 this.fireEvent("widthchange", this, col, width);
59511 * Returns the total width of all columns.
59512 * @param {Boolean} includeHidden True to include hidden column widths
59515 getTotalWidth : function(includeHidden){
59516 if(!this.totalWidth){
59517 this.totalWidth = 0;
59518 for(var i = 0, len = this.config.length; i < len; i++){
59519 if(includeHidden || !this.isHidden(i)){
59520 this.totalWidth += this.getColumnWidth(i);
59524 return this.totalWidth;
59528 * Returns the header for the specified column.
59529 * @param {Number} col The column index
59532 getColumnHeader : function(col){
59533 return this.config[col].header;
59537 * Sets the header for a column.
59538 * @param {Number} col The column index
59539 * @param {String} header The new header
59541 setColumnHeader : function(col, header){
59542 this.config[col].header = header;
59543 this.fireEvent("headerchange", this, col, header);
59547 * Returns the tooltip for the specified column.
59548 * @param {Number} col The column index
59551 getColumnTooltip : function(col){
59552 return this.config[col].tooltip;
59555 * Sets the tooltip for a column.
59556 * @param {Number} col The column index
59557 * @param {String} tooltip The new tooltip
59559 setColumnTooltip : function(col, tooltip){
59560 this.config[col].tooltip = tooltip;
59564 * Returns the dataIndex for the specified column.
59565 * @param {Number} col The column index
59568 getDataIndex : function(col){
59569 return this.config[col].dataIndex;
59573 * Sets the dataIndex for a column.
59574 * @param {Number} col The column index
59575 * @param {Number} dataIndex The new dataIndex
59577 setDataIndex : function(col, dataIndex){
59578 this.config[col].dataIndex = dataIndex;
59584 * Returns true if the cell is editable.
59585 * @param {Number} colIndex The column index
59586 * @param {Number} rowIndex The row index - this is nto actually used..?
59587 * @return {Boolean}
59589 isCellEditable : function(colIndex, rowIndex){
59590 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
59594 * Returns the editor defined for the cell/column.
59595 * return false or null to disable editing.
59596 * @param {Number} colIndex The column index
59597 * @param {Number} rowIndex The row index
59600 getCellEditor : function(colIndex, rowIndex){
59601 return this.config[colIndex].editor;
59605 * Sets if a column is editable.
59606 * @param {Number} col The column index
59607 * @param {Boolean} editable True if the column is editable
59609 setEditable : function(col, editable){
59610 this.config[col].editable = editable;
59615 * Returns true if the column is hidden.
59616 * @param {Number} colIndex The column index
59617 * @return {Boolean}
59619 isHidden : function(colIndex){
59620 return this.config[colIndex].hidden;
59625 * Returns true if the column width cannot be changed
59627 isFixed : function(colIndex){
59628 return this.config[colIndex].fixed;
59632 * Returns true if the column can be resized
59633 * @return {Boolean}
59635 isResizable : function(colIndex){
59636 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
59639 * Sets if a column is hidden.
59640 * @param {Number} colIndex The column index
59641 * @param {Boolean} hidden True if the column is hidden
59643 setHidden : function(colIndex, hidden){
59644 this.config[colIndex].hidden = hidden;
59645 this.totalWidth = null;
59646 this.fireEvent("hiddenchange", this, colIndex, hidden);
59650 * Sets the editor for a column.
59651 * @param {Number} col The column index
59652 * @param {Object} editor The editor object
59654 setEditor : function(col, editor){
59655 this.config[col].editor = editor;
59658 * Add a column (experimental...) - defaults to adding to the end..
59659 * @param {Object} config
59661 addColumn : function(c)
59664 var i = this.config.length;
59665 this.config[i] = c;
59667 if(typeof c.dataIndex == "undefined"){
59670 if(typeof c.renderer == "string"){
59671 c.renderer = Roo.util.Format[c.renderer];
59673 if(typeof c.id == "undefined"){
59676 if(c.editor && c.editor.xtype){
59677 c.editor = Roo.factory(c.editor, Roo.grid);
59679 if(c.editor && c.editor.isFormField){
59680 c.editor = new Roo.grid.GridEditor(c.editor);
59682 this.lookup[c.id] = c;
59687 Roo.grid.ColumnModel.defaultRenderer = function(value)
59689 if(typeof value == "object") {
59692 if(typeof value == "string" && value.length < 1){
59696 return String.format("{0}", value);
59699 // Alias for backwards compatibility
59700 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
59703 * Ext JS Library 1.1.1
59704 * Copyright(c) 2006-2007, Ext JS, LLC.
59706 * Originally Released Under LGPL - original licence link has changed is not relivant.
59709 * <script type="text/javascript">
59713 * @class Roo.grid.AbstractSelectionModel
59714 * @extends Roo.util.Observable
59716 * Abstract base class for grid SelectionModels. It provides the interface that should be
59717 * implemented by descendant classes. This class should not be directly instantiated.
59720 Roo.grid.AbstractSelectionModel = function(){
59721 this.locked = false;
59722 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
59725 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
59726 /** @ignore Called by the grid automatically. Do not call directly. */
59727 init : function(grid){
59733 * Locks the selections.
59736 this.locked = true;
59740 * Unlocks the selections.
59742 unlock : function(){
59743 this.locked = false;
59747 * Returns true if the selections are locked.
59748 * @return {Boolean}
59750 isLocked : function(){
59751 return this.locked;
59755 * Ext JS Library 1.1.1
59756 * Copyright(c) 2006-2007, Ext JS, LLC.
59758 * Originally Released Under LGPL - original licence link has changed is not relivant.
59761 * <script type="text/javascript">
59764 * @extends Roo.grid.AbstractSelectionModel
59765 * @class Roo.grid.RowSelectionModel
59766 * The default SelectionModel used by {@link Roo.grid.Grid}.
59767 * It supports multiple selections and keyboard selection/navigation.
59769 * @param {Object} config
59771 Roo.grid.RowSelectionModel = function(config){
59772 Roo.apply(this, config);
59773 this.selections = new Roo.util.MixedCollection(false, function(o){
59778 this.lastActive = false;
59782 * @event selectionchange
59783 * Fires when the selection changes
59784 * @param {SelectionModel} this
59786 "selectionchange" : true,
59788 * @event afterselectionchange
59789 * Fires after the selection changes (eg. by key press or clicking)
59790 * @param {SelectionModel} this
59792 "afterselectionchange" : true,
59794 * @event beforerowselect
59795 * Fires when a row is selected being selected, return false to cancel.
59796 * @param {SelectionModel} this
59797 * @param {Number} rowIndex The selected index
59798 * @param {Boolean} keepExisting False if other selections will be cleared
59800 "beforerowselect" : true,
59803 * Fires when a row is selected.
59804 * @param {SelectionModel} this
59805 * @param {Number} rowIndex The selected index
59806 * @param {Roo.data.Record} r The record
59808 "rowselect" : true,
59810 * @event rowdeselect
59811 * Fires when a row is deselected.
59812 * @param {SelectionModel} this
59813 * @param {Number} rowIndex The selected index
59815 "rowdeselect" : true
59817 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
59818 this.locked = false;
59821 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
59823 * @cfg {Boolean} singleSelect
59824 * True to allow selection of only one row at a time (defaults to false)
59826 singleSelect : false,
59829 initEvents : function(){
59831 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
59832 this.grid.on("mousedown", this.handleMouseDown, this);
59833 }else{ // allow click to work like normal
59834 this.grid.on("rowclick", this.handleDragableRowClick, this);
59836 // bootstrap does not have a view..
59837 var view = this.grid.view ? this.grid.view : this.grid;
59838 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
59839 "up" : function(e){
59841 this.selectPrevious(e.shiftKey);
59842 }else if(this.last !== false && this.lastActive !== false){
59843 var last = this.last;
59844 this.selectRange(this.last, this.lastActive-1);
59845 view.focusRow(this.lastActive);
59846 if(last !== false){
59850 this.selectFirstRow();
59852 this.fireEvent("afterselectionchange", this);
59854 "down" : function(e){
59856 this.selectNext(e.shiftKey);
59857 }else if(this.last !== false && this.lastActive !== false){
59858 var last = this.last;
59859 this.selectRange(this.last, this.lastActive+1);
59860 view.focusRow(this.lastActive);
59861 if(last !== false){
59865 this.selectFirstRow();
59867 this.fireEvent("afterselectionchange", this);
59873 view.on("refresh", this.onRefresh, this);
59874 view.on("rowupdated", this.onRowUpdated, this);
59875 view.on("rowremoved", this.onRemove, this);
59879 onRefresh : function(){
59880 var ds = this.grid.ds, i, v = this.grid.view;
59881 var s = this.selections;
59882 s.each(function(r){
59883 if((i = ds.indexOfId(r.id)) != -1){
59885 s.add(ds.getAt(i)); // updating the selection relate data
59893 onRemove : function(v, index, r){
59894 this.selections.remove(r);
59898 onRowUpdated : function(v, index, r){
59899 if(this.isSelected(r)){
59900 v.onRowSelect(index);
59906 * @param {Array} records The records to select
59907 * @param {Boolean} keepExisting (optional) True to keep existing selections
59909 selectRecords : function(records, keepExisting){
59911 this.clearSelections();
59913 var ds = this.grid.ds;
59914 for(var i = 0, len = records.length; i < len; i++){
59915 this.selectRow(ds.indexOf(records[i]), true);
59920 * Gets the number of selected rows.
59923 getCount : function(){
59924 return this.selections.length;
59928 * Selects the first row in the grid.
59930 selectFirstRow : function(){
59935 * Select the last row.
59936 * @param {Boolean} keepExisting (optional) True to keep existing selections
59938 selectLastRow : function(keepExisting){
59939 this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
59943 * Selects the row immediately following the last selected row.
59944 * @param {Boolean} keepExisting (optional) True to keep existing selections
59946 selectNext : function(keepExisting){
59947 if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
59948 this.selectRow(this.last+1, keepExisting);
59949 var view = this.grid.view ? this.grid.view : this.grid;
59950 view.focusRow(this.last);
59955 * Selects the row that precedes the last selected row.
59956 * @param {Boolean} keepExisting (optional) True to keep existing selections
59958 selectPrevious : function(keepExisting){
59960 this.selectRow(this.last-1, keepExisting);
59961 var view = this.grid.view ? this.grid.view : this.grid;
59962 view.focusRow(this.last);
59967 * Returns the selected records
59968 * @return {Array} Array of selected records
59970 getSelections : function(){
59971 return [].concat(this.selections.items);
59975 * Returns the first selected record.
59978 getSelected : function(){
59979 return this.selections.itemAt(0);
59984 * Clears all selections.
59986 clearSelections : function(fast){
59991 var ds = this.grid.ds;
59992 var s = this.selections;
59993 s.each(function(r){
59994 this.deselectRow(ds.indexOfId(r.id));
59998 this.selections.clear();
60005 * Selects all rows.
60007 selectAll : function(){
60011 this.selections.clear();
60012 for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
60013 this.selectRow(i, true);
60018 * Returns True if there is a selection.
60019 * @return {Boolean}
60021 hasSelection : function(){
60022 return this.selections.length > 0;
60026 * Returns True if the specified row is selected.
60027 * @param {Number/Record} record The record or index of the record to check
60028 * @return {Boolean}
60030 isSelected : function(index){
60031 var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
60032 return (r && this.selections.key(r.id) ? true : false);
60036 * Returns True if the specified record id is selected.
60037 * @param {String} id The id of record to check
60038 * @return {Boolean}
60040 isIdSelected : function(id){
60041 return (this.selections.key(id) ? true : false);
60045 handleMouseDown : function(e, t)
60047 var view = this.grid.view ? this.grid.view : this.grid;
60049 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
60052 if(e.shiftKey && this.last !== false){
60053 var last = this.last;
60054 this.selectRange(last, rowIndex, e.ctrlKey);
60055 this.last = last; // reset the last
60056 view.focusRow(rowIndex);
60058 var isSelected = this.isSelected(rowIndex);
60059 if(e.button !== 0 && isSelected){
60060 view.focusRow(rowIndex);
60061 }else if(e.ctrlKey && isSelected){
60062 this.deselectRow(rowIndex);
60063 }else if(!isSelected){
60064 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
60065 view.focusRow(rowIndex);
60068 this.fireEvent("afterselectionchange", this);
60071 handleDragableRowClick : function(grid, rowIndex, e)
60073 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
60074 this.selectRow(rowIndex, false);
60075 var view = this.grid.view ? this.grid.view : this.grid;
60076 view.focusRow(rowIndex);
60077 this.fireEvent("afterselectionchange", this);
60082 * Selects multiple rows.
60083 * @param {Array} rows Array of the indexes of the row to select
60084 * @param {Boolean} keepExisting (optional) True to keep existing selections
60086 selectRows : function(rows, keepExisting){
60088 this.clearSelections();
60090 for(var i = 0, len = rows.length; i < len; i++){
60091 this.selectRow(rows[i], true);
60096 * Selects a range of rows. All rows in between startRow and endRow are also selected.
60097 * @param {Number} startRow The index of the first row in the range
60098 * @param {Number} endRow The index of the last row in the range
60099 * @param {Boolean} keepExisting (optional) True to retain existing selections
60101 selectRange : function(startRow, endRow, keepExisting){
60106 this.clearSelections();
60108 if(startRow <= endRow){
60109 for(var i = startRow; i <= endRow; i++){
60110 this.selectRow(i, true);
60113 for(var i = startRow; i >= endRow; i--){
60114 this.selectRow(i, true);
60120 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
60121 * @param {Number} startRow The index of the first row in the range
60122 * @param {Number} endRow The index of the last row in the range
60124 deselectRange : function(startRow, endRow, preventViewNotify){
60128 for(var i = startRow; i <= endRow; i++){
60129 this.deselectRow(i, preventViewNotify);
60135 * @param {Number} row The index of the row to select
60136 * @param {Boolean} keepExisting (optional) True to keep existing selections
60138 selectRow : function(index, keepExisting, preventViewNotify){
60139 if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
60142 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
60143 if(!keepExisting || this.singleSelect){
60144 this.clearSelections();
60146 var r = this.grid.ds.getAt(index);
60147 this.selections.add(r);
60148 this.last = this.lastActive = index;
60149 if(!preventViewNotify){
60150 var view = this.grid.view ? this.grid.view : this.grid;
60151 view.onRowSelect(index);
60153 this.fireEvent("rowselect", this, index, r);
60154 this.fireEvent("selectionchange", this);
60160 * @param {Number} row The index of the row to deselect
60162 deselectRow : function(index, preventViewNotify){
60166 if(this.last == index){
60169 if(this.lastActive == index){
60170 this.lastActive = false;
60172 var r = this.grid.ds.getAt(index);
60173 this.selections.remove(r);
60174 if(!preventViewNotify){
60175 var view = this.grid.view ? this.grid.view : this.grid;
60176 view.onRowDeselect(index);
60178 this.fireEvent("rowdeselect", this, index);
60179 this.fireEvent("selectionchange", this);
60183 restoreLast : function(){
60185 this.last = this._last;
60190 acceptsNav : function(row, col, cm){
60191 return !cm.isHidden(col) && cm.isCellEditable(col, row);
60195 onEditorKey : function(field, e){
60196 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
60201 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
60203 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
60205 }else if(k == e.ENTER && !e.ctrlKey){
60209 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
60211 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
60213 }else if(k == e.ESC){
60217 g.startEditing(newCell[0], newCell[1]);
60222 * Ext JS Library 1.1.1
60223 * Copyright(c) 2006-2007, Ext JS, LLC.
60225 * Originally Released Under LGPL - original licence link has changed is not relivant.
60228 * <script type="text/javascript">
60231 * @class Roo.grid.CellSelectionModel
60232 * @extends Roo.grid.AbstractSelectionModel
60233 * This class provides the basic implementation for cell selection in a grid.
60235 * @param {Object} config The object containing the configuration of this model.
60236 * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
60238 Roo.grid.CellSelectionModel = function(config){
60239 Roo.apply(this, config);
60241 this.selection = null;
60245 * @event beforerowselect
60246 * Fires before a cell is selected.
60247 * @param {SelectionModel} this
60248 * @param {Number} rowIndex The selected row index
60249 * @param {Number} colIndex The selected cell index
60251 "beforecellselect" : true,
60253 * @event cellselect
60254 * Fires when a cell is selected.
60255 * @param {SelectionModel} this
60256 * @param {Number} rowIndex The selected row index
60257 * @param {Number} colIndex The selected cell index
60259 "cellselect" : true,
60261 * @event selectionchange
60262 * Fires when the active selection changes.
60263 * @param {SelectionModel} this
60264 * @param {Object} selection null for no selection or an object (o) with two properties
60266 <li>o.record: the record object for the row the selection is in</li>
60267 <li>o.cell: An array of [rowIndex, columnIndex]</li>
60270 "selectionchange" : true,
60273 * Fires when the tab (or enter) was pressed on the last editable cell
60274 * You can use this to trigger add new row.
60275 * @param {SelectionModel} this
60279 * @event beforeeditnext
60280 * Fires before the next editable sell is made active
60281 * You can use this to skip to another cell or fire the tabend
60282 * if you set cell to false
60283 * @param {Object} eventdata object : { cell : [ row, col ] }
60285 "beforeeditnext" : true
60287 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
60290 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
60292 enter_is_tab: false,
60295 initEvents : function(){
60296 this.grid.on("mousedown", this.handleMouseDown, this);
60297 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
60298 var view = this.grid.view;
60299 view.on("refresh", this.onViewChange, this);
60300 view.on("rowupdated", this.onRowUpdated, this);
60301 view.on("beforerowremoved", this.clearSelections, this);
60302 view.on("beforerowsinserted", this.clearSelections, this);
60303 if(this.grid.isEditor){
60304 this.grid.on("beforeedit", this.beforeEdit, this);
60309 beforeEdit : function(e){
60310 this.select(e.row, e.column, false, true, e.record);
60314 onRowUpdated : function(v, index, r){
60315 if(this.selection && this.selection.record == r){
60316 v.onCellSelect(index, this.selection.cell[1]);
60321 onViewChange : function(){
60322 this.clearSelections(true);
60326 * Returns the currently selected cell,.
60327 * @return {Array} The selected cell (row, column) or null if none selected.
60329 getSelectedCell : function(){
60330 return this.selection ? this.selection.cell : null;
60334 * Clears all selections.
60335 * @param {Boolean} true to prevent the gridview from being notified about the change.
60337 clearSelections : function(preventNotify){
60338 var s = this.selection;
60340 if(preventNotify !== true){
60341 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
60343 this.selection = null;
60344 this.fireEvent("selectionchange", this, null);
60349 * Returns true if there is a selection.
60350 * @return {Boolean}
60352 hasSelection : function(){
60353 return this.selection ? true : false;
60357 handleMouseDown : function(e, t){
60358 var v = this.grid.getView();
60359 if(this.isLocked()){
60362 var row = v.findRowIndex(t);
60363 var cell = v.findCellIndex(t);
60364 if(row !== false && cell !== false){
60365 this.select(row, cell);
60371 * @param {Number} rowIndex
60372 * @param {Number} collIndex
60374 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
60375 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
60376 this.clearSelections();
60377 r = r || this.grid.dataSource.getAt(rowIndex);
60380 cell : [rowIndex, colIndex]
60382 if(!preventViewNotify){
60383 var v = this.grid.getView();
60384 v.onCellSelect(rowIndex, colIndex);
60385 if(preventFocus !== true){
60386 v.focusCell(rowIndex, colIndex);
60389 this.fireEvent("cellselect", this, rowIndex, colIndex);
60390 this.fireEvent("selectionchange", this, this.selection);
60395 isSelectable : function(rowIndex, colIndex, cm){
60396 return !cm.isHidden(colIndex);
60400 handleKeyDown : function(e){
60401 //Roo.log('Cell Sel Model handleKeyDown');
60402 if(!e.isNavKeyPress()){
60405 var g = this.grid, s = this.selection;
60408 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
60410 this.select(cell[0], cell[1]);
60415 var walk = function(row, col, step){
60416 return g.walkCells(row, col, step, sm.isSelectable, sm);
60418 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
60425 // handled by onEditorKey
60426 if (g.isEditor && g.editing) {
60430 newCell = walk(r, c-1, -1);
60432 newCell = walk(r, c+1, 1);
60437 newCell = walk(r+1, c, 1);
60441 newCell = walk(r-1, c, -1);
60445 newCell = walk(r, c+1, 1);
60449 newCell = walk(r, c-1, -1);
60454 if(g.isEditor && !g.editing){
60455 g.startEditing(r, c);
60464 this.select(newCell[0], newCell[1]);
60470 acceptsNav : function(row, col, cm){
60471 return !cm.isHidden(col) && cm.isCellEditable(col, row);
60475 * @param {Number} field (not used) - as it's normally used as a listener
60476 * @param {Number} e - event - fake it by using
60478 * var e = Roo.EventObjectImpl.prototype;
60479 * e.keyCode = e.TAB
60483 onEditorKey : function(field, e){
60485 var k = e.getKey(),
60488 ed = g.activeEditor,
60490 ///Roo.log('onEditorKey' + k);
60493 if (this.enter_is_tab && k == e.ENTER) {
60499 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
60501 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
60507 } else if(k == e.ENTER && !e.ctrlKey){
60510 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
60512 } else if(k == e.ESC){
60517 var ecall = { cell : newCell, forward : forward };
60518 this.fireEvent('beforeeditnext', ecall );
60519 newCell = ecall.cell;
60520 forward = ecall.forward;
60524 //Roo.log('next cell after edit');
60525 g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
60526 } else if (forward) {
60527 // tabbed past last
60528 this.fireEvent.defer(100, this, ['tabend',this]);
60533 * Ext JS Library 1.1.1
60534 * Copyright(c) 2006-2007, Ext JS, LLC.
60536 * Originally Released Under LGPL - original licence link has changed is not relivant.
60539 * <script type="text/javascript">
60543 * @class Roo.grid.EditorGrid
60544 * @extends Roo.grid.Grid
60545 * Class for creating and editable grid.
60546 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
60547 * The container MUST have some type of size defined for the grid to fill. The container will be
60548 * automatically set to position relative if it isn't already.
60549 * @param {Object} dataSource The data model to bind to
60550 * @param {Object} colModel The column model with info about this grid's columns
60552 Roo.grid.EditorGrid = function(container, config){
60553 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
60554 this.getGridEl().addClass("xedit-grid");
60556 if(!this.selModel){
60557 this.selModel = new Roo.grid.CellSelectionModel();
60560 this.activeEditor = null;
60564 * @event beforeedit
60565 * Fires before cell editing is triggered. The edit event object has the following properties <br />
60566 * <ul style="padding:5px;padding-left:16px;">
60567 * <li>grid - This grid</li>
60568 * <li>record - The record being edited</li>
60569 * <li>field - The field name being edited</li>
60570 * <li>value - The value for the field being edited.</li>
60571 * <li>row - The grid row index</li>
60572 * <li>column - The grid column index</li>
60573 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
60575 * @param {Object} e An edit event (see above for description)
60577 "beforeedit" : true,
60580 * Fires after a cell is edited. <br />
60581 * <ul style="padding:5px;padding-left:16px;">
60582 * <li>grid - This grid</li>
60583 * <li>record - The record being edited</li>
60584 * <li>field - The field name being edited</li>
60585 * <li>value - The value being set</li>
60586 * <li>originalValue - The original value for the field, before the edit.</li>
60587 * <li>row - The grid row index</li>
60588 * <li>column - The grid column index</li>
60590 * @param {Object} e An edit event (see above for description)
60592 "afteredit" : true,
60594 * @event validateedit
60595 * Fires after a cell is edited, but before the value is set in the record.
60596 * You can use this to modify the value being set in the field, Return false
60597 * to cancel the change. The edit event object has the following properties <br />
60598 * <ul style="padding:5px;padding-left:16px;">
60599 * <li>editor - This editor</li>
60600 * <li>grid - This grid</li>
60601 * <li>record - The record being edited</li>
60602 * <li>field - The field name being edited</li>
60603 * <li>value - The value being set</li>
60604 * <li>originalValue - The original value for the field, before the edit.</li>
60605 * <li>row - The grid row index</li>
60606 * <li>column - The grid column index</li>
60607 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
60609 * @param {Object} e An edit event (see above for description)
60611 "validateedit" : true
60613 this.on("bodyscroll", this.stopEditing, this);
60614 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
60617 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
60619 * @cfg {Number} clicksToEdit
60620 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
60627 trackMouseOver: false, // causes very odd FF errors
60629 onCellDblClick : function(g, row, col){
60630 this.startEditing(row, col);
60633 onEditComplete : function(ed, value, startValue){
60634 this.editing = false;
60635 this.activeEditor = null;
60636 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
60638 var field = this.colModel.getDataIndex(ed.col);
60643 originalValue: startValue,
60650 var cell = Roo.get(this.view.getCell(ed.row,ed.col));
60653 if(String(value) !== String(startValue)){
60655 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
60656 r.set(field, e.value);
60657 // if we are dealing with a combo box..
60658 // then we also set the 'name' colum to be the displayField
60659 if (ed.field.displayField && ed.field.name) {
60660 r.set(ed.field.name, ed.field.el.dom.value);
60663 delete e.cancel; //?? why!!!
60664 this.fireEvent("afteredit", e);
60667 this.fireEvent("afteredit", e); // always fire it!
60669 this.view.focusCell(ed.row, ed.col);
60673 * Starts editing the specified for the specified row/column
60674 * @param {Number} rowIndex
60675 * @param {Number} colIndex
60677 startEditing : function(row, col){
60678 this.stopEditing();
60679 if(this.colModel.isCellEditable(col, row)){
60680 this.view.ensureVisible(row, col, true);
60682 var r = this.dataSource.getAt(row);
60683 var field = this.colModel.getDataIndex(col);
60684 var cell = Roo.get(this.view.getCell(row,col));
60689 value: r.data[field],
60694 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
60695 this.editing = true;
60696 var ed = this.colModel.getCellEditor(col, row);
60702 ed.render(ed.parentEl || document.body);
60708 (function(){ // complex but required for focus issues in safari, ie and opera
60712 ed.on("complete", this.onEditComplete, this, {single: true});
60713 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
60714 this.activeEditor = ed;
60715 var v = r.data[field];
60716 ed.startEdit(this.view.getCell(row, col), v);
60717 // combo's with 'displayField and name set
60718 if (ed.field.displayField && ed.field.name) {
60719 ed.field.el.dom.value = r.data[ed.field.name];
60723 }).defer(50, this);
60729 * Stops any active editing
60731 stopEditing : function(){
60732 if(this.activeEditor){
60733 this.activeEditor.completeEdit();
60735 this.activeEditor = null;
60739 * Called to get grid's drag proxy text, by default returns this.ddText.
60742 getDragDropText : function(){
60743 var count = this.selModel.getSelectedCell() ? 1 : 0;
60744 return String.format(this.ddText, count, count == 1 ? '' : 's');
60749 * Ext JS Library 1.1.1
60750 * Copyright(c) 2006-2007, Ext JS, LLC.
60752 * Originally Released Under LGPL - original licence link has changed is not relivant.
60755 * <script type="text/javascript">
60758 // private - not really -- you end up using it !
60759 // This is a support class used internally by the Grid components
60762 * @class Roo.grid.GridEditor
60763 * @extends Roo.Editor
60764 * Class for creating and editable grid elements.
60765 * @param {Object} config any settings (must include field)
60767 Roo.grid.GridEditor = function(field, config){
60768 if (!config && field.field) {
60770 field = Roo.factory(config.field, Roo.form);
60772 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
60773 field.monitorTab = false;
60776 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
60779 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
60782 alignment: "tl-tl",
60785 cls: "x-small-editor x-grid-editor",
60790 * Ext JS Library 1.1.1
60791 * Copyright(c) 2006-2007, Ext JS, LLC.
60793 * Originally Released Under LGPL - original licence link has changed is not relivant.
60796 * <script type="text/javascript">
60801 Roo.grid.PropertyRecord = Roo.data.Record.create([
60802 {name:'name',type:'string'}, 'value'
60806 Roo.grid.PropertyStore = function(grid, source){
60808 this.store = new Roo.data.Store({
60809 recordType : Roo.grid.PropertyRecord
60811 this.store.on('update', this.onUpdate, this);
60813 this.setSource(source);
60815 Roo.grid.PropertyStore.superclass.constructor.call(this);
60820 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
60821 setSource : function(o){
60823 this.store.removeAll();
60826 if(this.isEditableValue(o[k])){
60827 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
60830 this.store.loadRecords({records: data}, {}, true);
60833 onUpdate : function(ds, record, type){
60834 if(type == Roo.data.Record.EDIT){
60835 var v = record.data['value'];
60836 var oldValue = record.modified['value'];
60837 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
60838 this.source[record.id] = v;
60840 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
60847 getProperty : function(row){
60848 return this.store.getAt(row);
60851 isEditableValue: function(val){
60852 if(val && val instanceof Date){
60854 }else if(typeof val == 'object' || typeof val == 'function'){
60860 setValue : function(prop, value){
60861 this.source[prop] = value;
60862 this.store.getById(prop).set('value', value);
60865 getSource : function(){
60866 return this.source;
60870 Roo.grid.PropertyColumnModel = function(grid, store){
60873 g.PropertyColumnModel.superclass.constructor.call(this, [
60874 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
60875 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
60877 this.store = store;
60878 this.bselect = Roo.DomHelper.append(document.body, {
60879 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
60880 {tag: 'option', value: 'true', html: 'true'},
60881 {tag: 'option', value: 'false', html: 'false'}
60884 Roo.id(this.bselect);
60887 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
60888 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
60889 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
60890 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
60891 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
60893 this.renderCellDelegate = this.renderCell.createDelegate(this);
60894 this.renderPropDelegate = this.renderProp.createDelegate(this);
60897 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
60901 valueText : 'Value',
60903 dateFormat : 'm/j/Y',
60906 renderDate : function(dateVal){
60907 return dateVal.dateFormat(this.dateFormat);
60910 renderBool : function(bVal){
60911 return bVal ? 'true' : 'false';
60914 isCellEditable : function(colIndex, rowIndex){
60915 return colIndex == 1;
60918 getRenderer : function(col){
60920 this.renderCellDelegate : this.renderPropDelegate;
60923 renderProp : function(v){
60924 return this.getPropertyName(v);
60927 renderCell : function(val){
60929 if(val instanceof Date){
60930 rv = this.renderDate(val);
60931 }else if(typeof val == 'boolean'){
60932 rv = this.renderBool(val);
60934 return Roo.util.Format.htmlEncode(rv);
60937 getPropertyName : function(name){
60938 var pn = this.grid.propertyNames;
60939 return pn && pn[name] ? pn[name] : name;
60942 getCellEditor : function(colIndex, rowIndex){
60943 var p = this.store.getProperty(rowIndex);
60944 var n = p.data['name'], val = p.data['value'];
60946 if(typeof(this.grid.customEditors[n]) == 'string'){
60947 return this.editors[this.grid.customEditors[n]];
60949 if(typeof(this.grid.customEditors[n]) != 'undefined'){
60950 return this.grid.customEditors[n];
60952 if(val instanceof Date){
60953 return this.editors['date'];
60954 }else if(typeof val == 'number'){
60955 return this.editors['number'];
60956 }else if(typeof val == 'boolean'){
60957 return this.editors['boolean'];
60959 return this.editors['string'];
60965 * @class Roo.grid.PropertyGrid
60966 * @extends Roo.grid.EditorGrid
60967 * This class represents the interface of a component based property grid control.
60968 * <br><br>Usage:<pre><code>
60969 var grid = new Roo.grid.PropertyGrid("my-container-id", {
60977 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
60978 * The container MUST have some type of size defined for the grid to fill. The container will be
60979 * automatically set to position relative if it isn't already.
60980 * @param {Object} config A config object that sets properties on this grid.
60982 Roo.grid.PropertyGrid = function(container, config){
60983 config = config || {};
60984 var store = new Roo.grid.PropertyStore(this);
60985 this.store = store;
60986 var cm = new Roo.grid.PropertyColumnModel(this, store);
60987 store.store.sort('name', 'ASC');
60988 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
60991 enableColLock:false,
60992 enableColumnMove:false,
60994 trackMouseOver: false,
60997 this.getGridEl().addClass('x-props-grid');
60998 this.lastEditRow = null;
60999 this.on('columnresize', this.onColumnResize, this);
61002 * @event beforepropertychange
61003 * Fires before a property changes (return false to stop?)
61004 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
61005 * @param {String} id Record Id
61006 * @param {String} newval New Value
61007 * @param {String} oldval Old Value
61009 "beforepropertychange": true,
61011 * @event propertychange
61012 * Fires after a property changes
61013 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
61014 * @param {String} id Record Id
61015 * @param {String} newval New Value
61016 * @param {String} oldval Old Value
61018 "propertychange": true
61020 this.customEditors = this.customEditors || {};
61022 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
61025 * @cfg {Object} customEditors map of colnames=> custom editors.
61026 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
61027 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
61028 * false disables editing of the field.
61032 * @cfg {Object} propertyNames map of property Names to their displayed value
61035 render : function(){
61036 Roo.grid.PropertyGrid.superclass.render.call(this);
61037 this.autoSize.defer(100, this);
61040 autoSize : function(){
61041 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
61043 this.view.fitColumns();
61047 onColumnResize : function(){
61048 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
61052 * Sets the data for the Grid
61053 * accepts a Key => Value object of all the elements avaiable.
61054 * @param {Object} data to appear in grid.
61056 setSource : function(source){
61057 this.store.setSource(source);
61061 * Gets all the data from the grid.
61062 * @return {Object} data data stored in grid
61064 getSource : function(){
61065 return this.store.getSource();
61074 * @class Roo.grid.Calendar
61075 * @extends Roo.grid.Grid
61076 * This class extends the Grid to provide a calendar widget
61077 * <br><br>Usage:<pre><code>
61078 var grid = new Roo.grid.Calendar("my-container-id", {
61081 selModel: mySelectionModel,
61082 autoSizeColumns: true,
61083 monitorWindowResize: false,
61084 trackMouseOver: true
61085 eventstore : real data store..
61091 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
61092 * The container MUST have some type of size defined for the grid to fill. The container will be
61093 * automatically set to position relative if it isn't already.
61094 * @param {Object} config A config object that sets properties on this grid.
61096 Roo.grid.Calendar = function(container, config){
61097 // initialize the container
61098 this.container = Roo.get(container);
61099 this.container.update("");
61100 this.container.setStyle("overflow", "hidden");
61101 this.container.addClass('x-grid-container');
61103 this.id = this.container.id;
61105 Roo.apply(this, config);
61106 // check and correct shorthanded configs
61110 for (var r = 0;r < 6;r++) {
61113 for (var c =0;c < 7;c++) {
61117 if (this.eventStore) {
61118 this.eventStore= Roo.factory(this.eventStore, Roo.data);
61119 this.eventStore.on('load',this.onLoad, this);
61120 this.eventStore.on('beforeload',this.clearEvents, this);
61124 this.dataSource = new Roo.data.Store({
61125 proxy: new Roo.data.MemoryProxy(rows),
61126 reader: new Roo.data.ArrayReader({}, [
61127 'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
61130 this.dataSource.load();
61131 this.ds = this.dataSource;
61132 this.ds.xmodule = this.xmodule || false;
61135 var cellRender = function(v,x,r)
61137 return String.format(
61138 '<div class="fc-day fc-widget-content"><div>' +
61139 '<div class="fc-event-container"></div>' +
61140 '<div class="fc-day-number">{0}</div>'+
61142 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
61143 '</div></div>', v);
61148 this.colModel = new Roo.grid.ColumnModel( [
61150 xtype: 'ColumnModel',
61152 dataIndex : 'weekday0',
61154 renderer : cellRender
61157 xtype: 'ColumnModel',
61159 dataIndex : 'weekday1',
61161 renderer : cellRender
61164 xtype: 'ColumnModel',
61166 dataIndex : 'weekday2',
61167 header : 'Tuesday',
61168 renderer : cellRender
61171 xtype: 'ColumnModel',
61173 dataIndex : 'weekday3',
61174 header : 'Wednesday',
61175 renderer : cellRender
61178 xtype: 'ColumnModel',
61180 dataIndex : 'weekday4',
61181 header : 'Thursday',
61182 renderer : cellRender
61185 xtype: 'ColumnModel',
61187 dataIndex : 'weekday5',
61189 renderer : cellRender
61192 xtype: 'ColumnModel',
61194 dataIndex : 'weekday6',
61195 header : 'Saturday',
61196 renderer : cellRender
61199 this.cm = this.colModel;
61200 this.cm.xmodule = this.xmodule || false;
61204 //this.selModel = new Roo.grid.CellSelectionModel();
61205 //this.sm = this.selModel;
61206 //this.selModel.init(this);
61210 this.container.setWidth(this.width);
61214 this.container.setHeight(this.height);
61221 * The raw click event for the entire grid.
61222 * @param {Roo.EventObject} e
61227 * The raw dblclick event for the entire grid.
61228 * @param {Roo.EventObject} e
61232 * @event contextmenu
61233 * The raw contextmenu event for the entire grid.
61234 * @param {Roo.EventObject} e
61236 "contextmenu" : true,
61239 * The raw mousedown event for the entire grid.
61240 * @param {Roo.EventObject} e
61242 "mousedown" : true,
61245 * The raw mouseup event for the entire grid.
61246 * @param {Roo.EventObject} e
61251 * The raw mouseover event for the entire grid.
61252 * @param {Roo.EventObject} e
61254 "mouseover" : true,
61257 * The raw mouseout event for the entire grid.
61258 * @param {Roo.EventObject} e
61263 * The raw keypress event for the entire grid.
61264 * @param {Roo.EventObject} e
61269 * The raw keydown event for the entire grid.
61270 * @param {Roo.EventObject} e
61278 * Fires when a cell is clicked
61279 * @param {Grid} this
61280 * @param {Number} rowIndex
61281 * @param {Number} columnIndex
61282 * @param {Roo.EventObject} e
61284 "cellclick" : true,
61286 * @event celldblclick
61287 * Fires when a cell is double clicked
61288 * @param {Grid} this
61289 * @param {Number} rowIndex
61290 * @param {Number} columnIndex
61291 * @param {Roo.EventObject} e
61293 "celldblclick" : true,
61296 * Fires when a row is clicked
61297 * @param {Grid} this
61298 * @param {Number} rowIndex
61299 * @param {Roo.EventObject} e
61303 * @event rowdblclick
61304 * Fires when a row is double clicked
61305 * @param {Grid} this
61306 * @param {Number} rowIndex
61307 * @param {Roo.EventObject} e
61309 "rowdblclick" : true,
61311 * @event headerclick
61312 * Fires when a header is clicked
61313 * @param {Grid} this
61314 * @param {Number} columnIndex
61315 * @param {Roo.EventObject} e
61317 "headerclick" : true,
61319 * @event headerdblclick
61320 * Fires when a header cell is double clicked
61321 * @param {Grid} this
61322 * @param {Number} columnIndex
61323 * @param {Roo.EventObject} e
61325 "headerdblclick" : true,
61327 * @event rowcontextmenu
61328 * Fires when a row is right clicked
61329 * @param {Grid} this
61330 * @param {Number} rowIndex
61331 * @param {Roo.EventObject} e
61333 "rowcontextmenu" : true,
61335 * @event cellcontextmenu
61336 * Fires when a cell is right clicked
61337 * @param {Grid} this
61338 * @param {Number} rowIndex
61339 * @param {Number} cellIndex
61340 * @param {Roo.EventObject} e
61342 "cellcontextmenu" : true,
61344 * @event headercontextmenu
61345 * Fires when a header is right clicked
61346 * @param {Grid} this
61347 * @param {Number} columnIndex
61348 * @param {Roo.EventObject} e
61350 "headercontextmenu" : true,
61352 * @event bodyscroll
61353 * Fires when the body element is scrolled
61354 * @param {Number} scrollLeft
61355 * @param {Number} scrollTop
61357 "bodyscroll" : true,
61359 * @event columnresize
61360 * Fires when the user resizes a column
61361 * @param {Number} columnIndex
61362 * @param {Number} newSize
61364 "columnresize" : true,
61366 * @event columnmove
61367 * Fires when the user moves a column
61368 * @param {Number} oldIndex
61369 * @param {Number} newIndex
61371 "columnmove" : true,
61374 * Fires when row(s) start being dragged
61375 * @param {Grid} this
61376 * @param {Roo.GridDD} dd The drag drop object
61377 * @param {event} e The raw browser event
61379 "startdrag" : true,
61382 * Fires when a drag operation is complete
61383 * @param {Grid} this
61384 * @param {Roo.GridDD} dd The drag drop object
61385 * @param {event} e The raw browser event
61390 * Fires when dragged row(s) are dropped on a valid DD target
61391 * @param {Grid} this
61392 * @param {Roo.GridDD} dd The drag drop object
61393 * @param {String} targetId The target drag drop object
61394 * @param {event} e The raw browser event
61399 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
61400 * @param {Grid} this
61401 * @param {Roo.GridDD} dd The drag drop object
61402 * @param {String} targetId The target drag drop object
61403 * @param {event} e The raw browser event
61408 * Fires when the dragged row(s) first cross another DD target while being dragged
61409 * @param {Grid} this
61410 * @param {Roo.GridDD} dd The drag drop object
61411 * @param {String} targetId The target drag drop object
61412 * @param {event} e The raw browser event
61414 "dragenter" : true,
61417 * Fires when the dragged row(s) leave another DD target while being dragged
61418 * @param {Grid} this
61419 * @param {Roo.GridDD} dd The drag drop object
61420 * @param {String} targetId The target drag drop object
61421 * @param {event} e The raw browser event
61426 * Fires when a row is rendered, so you can change add a style to it.
61427 * @param {GridView} gridview The grid view
61428 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
61434 * Fires when the grid is rendered
61435 * @param {Grid} grid
61440 * Fires when a date is selected
61441 * @param {DatePicker} this
61442 * @param {Date} date The selected date
61446 * @event monthchange
61447 * Fires when the displayed month changes
61448 * @param {DatePicker} this
61449 * @param {Date} date The selected month
61451 'monthchange': true,
61453 * @event evententer
61454 * Fires when mouse over an event
61455 * @param {Calendar} this
61456 * @param {event} Event
61458 'evententer': true,
61460 * @event eventleave
61461 * Fires when the mouse leaves an
61462 * @param {Calendar} this
61465 'eventleave': true,
61467 * @event eventclick
61468 * Fires when the mouse click an
61469 * @param {Calendar} this
61472 'eventclick': true,
61474 * @event eventrender
61475 * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
61476 * @param {Calendar} this
61477 * @param {data} data to be modified
61479 'eventrender': true
61483 Roo.grid.Grid.superclass.constructor.call(this);
61484 this.on('render', function() {
61485 this.view.el.addClass('x-grid-cal');
61487 (function() { this.setDate(new Date()); }).defer(100,this); //default today..
61491 if (!Roo.grid.Calendar.style) {
61492 Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
61495 '.x-grid-cal .x-grid-col' : {
61496 height: 'auto !important',
61497 'vertical-align': 'top'
61499 '.x-grid-cal .fc-event-hori' : {
61510 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
61512 * @cfg {Store} eventStore The store that loads events.
61517 activeDate : false,
61520 monitorWindowResize : false,
61523 resizeColumns : function() {
61524 var col = (this.view.el.getWidth() / 7) - 3;
61525 // loop through cols, and setWidth
61526 for(var i =0 ; i < 7 ; i++){
61527 this.cm.setColumnWidth(i, col);
61530 setDate :function(date) {
61532 Roo.log('setDate?');
61534 this.resizeColumns();
61535 var vd = this.activeDate;
61536 this.activeDate = date;
61537 // if(vd && this.el){
61538 // var t = date.getTime();
61539 // if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
61540 // Roo.log('using add remove');
61542 // this.fireEvent('monthchange', this, date);
61544 // this.cells.removeClass("fc-state-highlight");
61545 // this.cells.each(function(c){
61546 // if(c.dateValue == t){
61547 // c.addClass("fc-state-highlight");
61548 // setTimeout(function(){
61549 // try{c.dom.firstChild.focus();}catch(e){}
61559 var days = date.getDaysInMonth();
61561 var firstOfMonth = date.getFirstDateOfMonth();
61562 var startingPos = firstOfMonth.getDay()-this.startDay;
61564 if(startingPos < this.startDay){
61568 var pm = date.add(Date.MONTH, -1);
61569 var prevStart = pm.getDaysInMonth()-startingPos;
61573 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
61575 this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
61576 //this.cells.addClassOnOver('fc-state-hover');
61578 var cells = this.cells.elements;
61579 var textEls = this.textNodes;
61581 //Roo.each(cells, function(cell){
61582 // cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
61585 days += startingPos;
61587 // convert everything to numbers so it's fast
61588 var day = 86400000;
61589 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
61592 //Roo.log(prevStart);
61594 var today = new Date().clearTime().getTime();
61595 var sel = date.clearTime().getTime();
61596 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
61597 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
61598 var ddMatch = this.disabledDatesRE;
61599 var ddText = this.disabledDatesText;
61600 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
61601 var ddaysText = this.disabledDaysText;
61602 var format = this.format;
61604 var setCellClass = function(cal, cell){
61606 //Roo.log('set Cell Class');
61608 var t = d.getTime();
61613 cell.dateValue = t;
61615 cell.className += " fc-today";
61616 cell.className += " fc-state-highlight";
61617 cell.title = cal.todayText;
61620 // disable highlight in other month..
61621 cell.className += " fc-state-highlight";
61626 //cell.className = " fc-state-disabled";
61627 cell.title = cal.minText;
61631 //cell.className = " fc-state-disabled";
61632 cell.title = cal.maxText;
61636 if(ddays.indexOf(d.getDay()) != -1){
61637 // cell.title = ddaysText;
61638 // cell.className = " fc-state-disabled";
61641 if(ddMatch && format){
61642 var fvalue = d.dateFormat(format);
61643 if(ddMatch.test(fvalue)){
61644 cell.title = ddText.replace("%0", fvalue);
61645 cell.className = " fc-state-disabled";
61649 if (!cell.initialClassName) {
61650 cell.initialClassName = cell.dom.className;
61653 cell.dom.className = cell.initialClassName + ' ' + cell.className;
61658 for(; i < startingPos; i++) {
61659 cells[i].dayName = (++prevStart);
61660 Roo.log(textEls[i]);
61661 d.setDate(d.getDate()+1);
61663 //cells[i].className = "fc-past fc-other-month";
61664 setCellClass(this, cells[i]);
61669 for(; i < days; i++){
61670 intDay = i - startingPos + 1;
61671 cells[i].dayName = (intDay);
61672 d.setDate(d.getDate()+1);
61674 cells[i].className = ''; // "x-date-active";
61675 setCellClass(this, cells[i]);
61679 for(; i < 42; i++) {
61680 //textEls[i].innerHTML = (++extraDays);
61682 d.setDate(d.getDate()+1);
61683 cells[i].dayName = (++extraDays);
61684 cells[i].className = "fc-future fc-other-month";
61685 setCellClass(this, cells[i]);
61688 //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
61690 var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
61692 // this will cause all the cells to mis
61695 for (var r = 0;r < 6;r++) {
61696 for (var c =0;c < 7;c++) {
61697 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
61701 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
61702 for(i=0;i<cells.length;i++) {
61704 this.cells.elements[i].dayName = cells[i].dayName ;
61705 this.cells.elements[i].className = cells[i].className;
61706 this.cells.elements[i].initialClassName = cells[i].initialClassName ;
61707 this.cells.elements[i].title = cells[i].title ;
61708 this.cells.elements[i].dateValue = cells[i].dateValue ;
61714 //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
61715 //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
61717 ////if(totalRows != 6){
61718 //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
61719 // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
61722 this.fireEvent('monthchange', this, date);
61727 * Returns the grid's SelectionModel.
61728 * @return {SelectionModel}
61730 getSelectionModel : function(){
61731 if(!this.selModel){
61732 this.selModel = new Roo.grid.CellSelectionModel();
61734 return this.selModel;
61738 this.eventStore.load()
61744 findCell : function(dt) {
61745 dt = dt.clearTime().getTime();
61747 this.cells.each(function(c){
61748 //Roo.log("check " +c.dateValue + '?=' + dt);
61749 if(c.dateValue == dt){
61759 findCells : function(rec) {
61760 var s = rec.data.start_dt.clone().clearTime().getTime();
61762 var e= rec.data.end_dt.clone().clearTime().getTime();
61765 this.cells.each(function(c){
61766 ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
61768 if(c.dateValue > e){
61771 if(c.dateValue < s){
61780 findBestRow: function(cells)
61784 for (var i =0 ; i < cells.length;i++) {
61785 ret = Math.max(cells[i].rows || 0,ret);
61792 addItem : function(rec)
61794 // look for vertical location slot in
61795 var cells = this.findCells(rec);
61797 rec.row = this.findBestRow(cells);
61799 // work out the location.
61803 for(var i =0; i < cells.length; i++) {
61811 if (crow.start.getY() == cells[i].getY()) {
61813 crow.end = cells[i];
61829 for (var i = 0; i < cells.length;i++) {
61830 cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
61837 clearEvents: function() {
61839 if (!this.eventStore.getCount()) {
61842 // reset number of rows in cells.
61843 Roo.each(this.cells.elements, function(c){
61847 this.eventStore.each(function(e) {
61848 this.clearEvent(e);
61853 clearEvent : function(ev)
61856 Roo.each(ev.els, function(el) {
61857 el.un('mouseenter' ,this.onEventEnter, this);
61858 el.un('mouseleave' ,this.onEventLeave, this);
61866 renderEvent : function(ev,ctr) {
61868 ctr = this.view.el.select('.fc-event-container',true).first();
61872 this.clearEvent(ev);
61878 var cells = ev.cells;
61879 var rows = ev.rows;
61880 this.fireEvent('eventrender', this, ev);
61882 for(var i =0; i < rows.length; i++) {
61886 cls += ' fc-event-start';
61888 if ((i+1) == rows.length) {
61889 cls += ' fc-event-end';
61892 //Roo.log(ev.data);
61893 // how many rows should it span..
61894 var cg = this.eventTmpl.append(ctr,Roo.apply({
61897 }, ev.data) , true);
61900 cg.on('mouseenter' ,this.onEventEnter, this, ev);
61901 cg.on('mouseleave' ,this.onEventLeave, this, ev);
61902 cg.on('click', this.onEventClick, this, ev);
61906 var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
61907 var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
61910 cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);
61911 cg.setWidth(ebox.right - sbox.x -2);
61915 renderEvents: function()
61917 // first make sure there is enough space..
61919 if (!this.eventTmpl) {
61920 this.eventTmpl = new Roo.Template(
61921 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}" style="position: absolute" unselectable="on">' +
61922 '<div class="fc-event-inner">' +
61923 '<span class="fc-event-time">{time}</span>' +
61924 '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
61926 '<div class="ui-resizable-heandle ui-resizable-e"> </div>' +
61934 this.cells.each(function(c) {
61935 //Roo.log(c.select('.fc-day-content div',true).first());
61936 c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
61939 var ctr = this.view.el.select('.fc-event-container',true).first();
61942 this.eventStore.each(function(ev){
61944 this.renderEvent(ev);
61948 this.view.layout();
61952 onEventEnter: function (e, el,event,d) {
61953 this.fireEvent('evententer', this, el, event);
61956 onEventLeave: function (e, el,event,d) {
61957 this.fireEvent('eventleave', this, el, event);
61960 onEventClick: function (e, el,event,d) {
61961 this.fireEvent('eventclick', this, el, event);
61964 onMonthChange: function () {
61968 onLoad: function () {
61970 //Roo.log('calendar onload');
61972 if(this.eventStore.getCount() > 0){
61976 this.eventStore.each(function(d){
61981 if (typeof(add.end_dt) == 'undefined') {
61982 Roo.log("Missing End time in calendar data: ");
61986 if (typeof(add.start_dt) == 'undefined') {
61987 Roo.log("Missing Start time in calendar data: ");
61991 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
61992 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
61993 add.id = add.id || d.id;
61994 add.title = add.title || '??';
62002 this.renderEvents();
62012 render : function ()
62016 if (!this.view.el.hasClass('course-timesheet')) {
62017 this.view.el.addClass('course-timesheet');
62019 if (this.tsStyle) {
62024 Roo.log(_this.grid.view.el.getWidth());
62027 this.tsStyle = Roo.util.CSS.createStyleSheet({
62028 '.course-timesheet .x-grid-row' : {
62031 '.x-grid-row td' : {
62032 'vertical-align' : 0
62034 '.course-edit-link' : {
62036 'text-overflow' : 'ellipsis',
62037 'overflow' : 'hidden',
62038 'white-space' : 'nowrap',
62039 'cursor' : 'pointer'
62044 '.de-act-sup-link' : {
62045 'color' : 'purple',
62046 'text-decoration' : 'line-through'
62050 'text-decoration' : 'line-through'
62052 '.course-timesheet .course-highlight' : {
62053 'border-top-style': 'dashed !important',
62054 'border-bottom-bottom': 'dashed !important'
62056 '.course-timesheet .course-item' : {
62057 'font-family' : 'tahoma, arial, helvetica',
62058 'font-size' : '11px',
62059 'overflow' : 'hidden',
62060 'padding-left' : '10px',
62061 'padding-right' : '10px',
62062 'padding-top' : '10px'
62070 monitorWindowResize : false,
62071 cellrenderer : function(v,x,r)
62076 xtype: 'CellSelectionModel',
62083 beforeload : function (_self, options)
62085 options.params = options.params || {};
62086 options.params._month = _this.monthField.getValue();
62087 options.params.limit = 9999;
62088 options.params['sort'] = 'when_dt';
62089 options.params['dir'] = 'ASC';
62090 this.proxy.loadResponse = this.loadResponse;
62092 //this.addColumns();
62094 load : function (_self, records, options)
62096 _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
62097 // if you click on the translation.. you can edit it...
62098 var el = Roo.get(this);
62099 var id = el.dom.getAttribute('data-id');
62100 var d = el.dom.getAttribute('data-date');
62101 var t = el.dom.getAttribute('data-time');
62102 //var id = this.child('span').dom.textContent;
62105 Pman.Dialog.CourseCalendar.show({
62109 productitem_active : id ? 1 : 0
62111 _this.grid.ds.load({});
62116 _this.panel.fireEvent('resize', [ '', '' ]);
62119 loadResponse : function(o, success, response){
62120 // this is overridden on before load..
62122 Roo.log("our code?");
62123 //Roo.log(success);
62124 //Roo.log(response)
62125 delete this.activeRequest;
62127 this.fireEvent("loadexception", this, o, response);
62128 o.request.callback.call(o.request.scope, null, o.request.arg, false);
62133 result = o.reader.read(response);
62135 Roo.log("load exception?");
62136 this.fireEvent("loadexception", this, o, response, e);
62137 o.request.callback.call(o.request.scope, null, o.request.arg, false);
62140 Roo.log("ready...");
62141 // loop through result.records;
62142 // and set this.tdate[date] = [] << array of records..
62144 Roo.each(result.records, function(r){
62146 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
62147 _this.tdata[r.data.when_dt.format('j')] = [];
62149 _this.tdata[r.data.when_dt.format('j')].push(r.data);
62152 //Roo.log(_this.tdata);
62154 result.records = [];
62155 result.totalRecords = 6;
62157 // let's generate some duumy records for the rows.
62158 //var st = _this.dateField.getValue();
62160 // work out monday..
62161 //st = st.add(Date.DAY, -1 * st.format('w'));
62163 var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
62165 var firstOfMonth = date.getFirstDayOfMonth();
62166 var days = date.getDaysInMonth();
62168 var firstAdded = false;
62169 for (var i = 0; i < result.totalRecords ; i++) {
62170 //var d= st.add(Date.DAY, i);
62173 for(var w = 0 ; w < 7 ; w++){
62174 if(!firstAdded && firstOfMonth != w){
62181 var dd = (d > 0 && d < 10) ? "0"+d : d;
62182 row['weekday'+w] = String.format(
62183 '<span style="font-size: 16px;"><b>{0}</b></span>'+
62184 '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
62186 date.format('Y-m-')+dd
62189 if(typeof(_this.tdata[d]) != 'undefined'){
62190 Roo.each(_this.tdata[d], function(r){
62194 var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
62195 if(r.parent_id*1>0){
62196 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
62199 if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
62200 deactive = 'de-act-link';
62203 row['weekday'+w] += String.format(
62204 '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
62206 r.product_id_name, //1
62207 r.when_dt.format('h:ia'), //2
62217 // only do this if something added..
62219 result.records.push(_this.grid.dataSource.reader.newRow(row));
62223 // push it twice. (second one with an hour..
62227 this.fireEvent("load", this, o, o.request.arg);
62228 o.request.callback.call(o.request.scope, result, o.request.arg, true);
62230 sortInfo : {field: 'when_dt', direction : 'ASC' },
62232 xtype: 'HttpProxy',
62235 url : baseURL + '/Roo/Shop_course.php'
62238 xtype: 'JsonReader',
62255 'name': 'parent_id',
62259 'name': 'product_id',
62263 'name': 'productitem_id',
62281 click : function (_self, e)
62283 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
62284 sd.setMonth(sd.getMonth()-1);
62285 _this.monthField.setValue(sd.format('Y-m-d'));
62286 _this.grid.ds.load({});
62292 xtype: 'Separator',
62296 xtype: 'MonthField',
62299 render : function (_self)
62301 _this.monthField = _self;
62302 // _this.monthField.set today
62304 select : function (combo, date)
62306 _this.grid.ds.load({});
62309 value : (function() { return new Date(); })()
62312 xtype: 'Separator',
62318 text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
62328 click : function (_self, e)
62330 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
62331 sd.setMonth(sd.getMonth()+1);
62332 _this.monthField.setValue(sd.format('Y-m-d'));
62333 _this.grid.ds.load({});
62346 * Ext JS Library 1.1.1
62347 * Copyright(c) 2006-2007, Ext JS, LLC.
62349 * Originally Released Under LGPL - original licence link has changed is not relivant.
62352 * <script type="text/javascript">
62356 * @class Roo.LoadMask
62357 * A simple utility class for generically masking elements while loading data. If the element being masked has
62358 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
62359 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
62360 * element's UpdateManager load indicator and will be destroyed after the initial load.
62362 * Create a new LoadMask
62363 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
62364 * @param {Object} config The config object
62366 Roo.LoadMask = function(el, config){
62367 this.el = Roo.get(el);
62368 Roo.apply(this, config);
62370 this.store.on('beforeload', this.onBeforeLoad, this);
62371 this.store.on('load', this.onLoad, this);
62372 this.store.on('loadexception', this.onLoadException, this);
62373 this.removeMask = false;
62375 var um = this.el.getUpdateManager();
62376 um.showLoadIndicator = false; // disable the default indicator
62377 um.on('beforeupdate', this.onBeforeLoad, this);
62378 um.on('update', this.onLoad, this);
62379 um.on('failure', this.onLoad, this);
62380 this.removeMask = true;
62384 Roo.LoadMask.prototype = {
62386 * @cfg {Boolean} removeMask
62387 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
62388 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
62390 removeMask : false,
62392 * @cfg {String} msg
62393 * The text to display in a centered loading message box (defaults to 'Loading...')
62395 msg : 'Loading...',
62397 * @cfg {String} msgCls
62398 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
62400 msgCls : 'x-mask-loading',
62403 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
62409 * Disables the mask to prevent it from being displayed
62411 disable : function(){
62412 this.disabled = true;
62416 * Enables the mask so that it can be displayed
62418 enable : function(){
62419 this.disabled = false;
62422 onLoadException : function()
62424 Roo.log(arguments);
62426 if (typeof(arguments[3]) != 'undefined') {
62427 Roo.MessageBox.alert("Error loading",arguments[3]);
62431 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
62432 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
62439 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
62442 onLoad : function()
62444 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
62448 onBeforeLoad : function(){
62449 if(!this.disabled){
62450 (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
62455 destroy : function(){
62457 this.store.un('beforeload', this.onBeforeLoad, this);
62458 this.store.un('load', this.onLoad, this);
62459 this.store.un('loadexception', this.onLoadException, this);
62461 var um = this.el.getUpdateManager();
62462 um.un('beforeupdate', this.onBeforeLoad, this);
62463 um.un('update', this.onLoad, this);
62464 um.un('failure', this.onLoad, this);
62469 * Ext JS Library 1.1.1
62470 * Copyright(c) 2006-2007, Ext JS, LLC.
62472 * Originally Released Under LGPL - original licence link has changed is not relivant.
62475 * <script type="text/javascript">
62480 * @class Roo.XTemplate
62481 * @extends Roo.Template
62482 * Provides a template that can have nested templates for loops or conditionals. The syntax is:
62484 var t = new Roo.XTemplate(
62485 '<select name="{name}">',
62486 '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
62490 // then append, applying the master template values
62493 * Supported features:
62498 {a_variable} - output encoded.
62499 {a_variable.format:("Y-m-d")} - call a method on the variable
62500 {a_variable:raw} - unencoded output
62501 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
62502 {a_variable:this.method_on_template(...)} - call a method on the template object.
62507 <tpl for="a_variable or condition.."></tpl>
62508 <tpl if="a_variable or condition"></tpl>
62509 <tpl exec="some javascript"></tpl>
62510 <tpl name="named_template"></tpl> (experimental)
62512 <tpl for="."></tpl> - just iterate the property..
62513 <tpl for=".."></tpl> - iterates with the parent (probably the template)
62517 Roo.XTemplate = function()
62519 Roo.XTemplate.superclass.constructor.apply(this, arguments);
62526 Roo.extend(Roo.XTemplate, Roo.Template, {
62529 * The various sub templates
62534 * basic tag replacing syntax
62537 * // you can fake an object call by doing this
62541 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
62544 * compile the template
62546 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
62549 compile: function()
62553 s = ['<tpl>', s, '</tpl>'].join('');
62555 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
62556 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
62557 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
62558 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
62559 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
62564 while(true == !!(m = s.match(re))){
62565 var forMatch = m[0].match(nameRe),
62566 ifMatch = m[0].match(ifRe),
62567 execMatch = m[0].match(execRe),
62568 namedMatch = m[0].match(namedRe),
62573 name = forMatch && forMatch[1] ? forMatch[1] : '';
62576 // if - puts fn into test..
62577 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
62579 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
62584 // exec - calls a function... returns empty if true is returned.
62585 exp = execMatch && execMatch[1] ? execMatch[1] : null;
62587 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
62595 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
62596 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
62597 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
62600 var uid = namedMatch ? namedMatch[1] : id;
62604 id: namedMatch ? namedMatch[1] : id,
62611 s = s.replace(m[0], '');
62613 s = s.replace(m[0], '{xtpl'+ id + '}');
62618 for(var i = tpls.length-1; i >= 0; --i){
62619 this.compileTpl(tpls[i]);
62620 this.tpls[tpls[i].id] = tpls[i];
62622 this.master = tpls[tpls.length-1];
62626 * same as applyTemplate, except it's done to one of the subTemplates
62627 * when using named templates, you can do:
62629 * var str = pl.applySubTemplate('your-name', values);
62632 * @param {Number} id of the template
62633 * @param {Object} values to apply to template
62634 * @param {Object} parent (normaly the instance of this object)
62636 applySubTemplate : function(id, values, parent)
62640 var t = this.tpls[id];
62644 if(t.test && !t.test.call(this, values, parent)){
62648 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
62649 Roo.log(e.toString());
62655 if(t.exec && t.exec.call(this, values, parent)){
62659 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
62660 Roo.log(e.toString());
62665 var vs = t.target ? t.target.call(this, values, parent) : values;
62666 parent = t.target ? values : parent;
62667 if(t.target && vs instanceof Array){
62669 for(var i = 0, len = vs.length; i < len; i++){
62670 buf[buf.length] = t.compiled.call(this, vs[i], parent);
62672 return buf.join('');
62674 return t.compiled.call(this, vs, parent);
62676 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
62677 Roo.log(e.toString());
62678 Roo.log(t.compiled);
62683 compileTpl : function(tpl)
62685 var fm = Roo.util.Format;
62686 var useF = this.disableFormats !== true;
62687 var sep = Roo.isGecko ? "+" : ",";
62688 var undef = function(str) {
62689 Roo.log("Property not found :" + str);
62693 var fn = function(m, name, format, args)
62695 //Roo.log(arguments);
62696 args = args ? args.replace(/\\'/g,"'") : args;
62697 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
62698 if (typeof(format) == 'undefined') {
62699 format= 'htmlEncode';
62701 if (format == 'raw' ) {
62705 if(name.substr(0, 4) == 'xtpl'){
62706 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
62709 // build an array of options to determine if value is undefined..
62711 // basically get 'xxxx.yyyy' then do
62712 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
62713 // (function () { Roo.log("Property not found"); return ''; })() :
62718 Roo.each(name.split('.'), function(st) {
62719 lookfor += (lookfor.length ? '.': '') + st;
62720 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
62723 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
62726 if(format && useF){
62728 args = args ? ',' + args : "";
62730 if(format.substr(0, 5) != "this."){
62731 format = "fm." + format + '(';
62733 format = 'this.call("'+ format.substr(5) + '", ';
62737 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
62741 // called with xxyx.yuu:(test,test)
62743 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
62745 // raw.. - :raw modifier..
62746 return "'"+ sep + udef_st + name + ")"+sep+"'";
62750 // branched to use + in gecko and [].join() in others
62752 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
62753 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
62756 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
62757 body.push(tpl.body.replace(/(\r\n|\n)/g,
62758 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
62759 body.push("'].join('');};};");
62760 body = body.join('');
62763 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
62765 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
62771 applyTemplate : function(values){
62772 return this.master.compiled.call(this, values, {});
62773 //var s = this.subs;
62776 apply : function(){
62777 return this.applyTemplate.apply(this, arguments);
62782 Roo.XTemplate.from = function(el){
62783 el = Roo.getDom(el);
62784 return new Roo.XTemplate(el.value || el.innerHTML);