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",
707 * Ext JS Library 1.1.1
708 * Copyright(c) 2006-2007, Ext JS, LLC.
710 * Originally Released Under LGPL - original licence link has changed is not relivant.
713 * <script type="text/javascript">
717 // wrappedn so fnCleanup is not in global scope...
719 function fnCleanUp() {
720 var p = Function.prototype;
721 delete p.createSequence;
723 delete p.createDelegate;
724 delete p.createCallback;
725 delete p.createInterceptor;
727 window.detachEvent("onunload", fnCleanUp);
729 window.attachEvent("onunload", fnCleanUp);
736 * These functions are available on every Function object (any JavaScript function).
738 Roo.apply(Function.prototype, {
740 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
741 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
742 * Will create a function that is bound to those 2 args.
743 * @return {Function} The new function
745 createCallback : function(/*args...*/){
746 // make args available, in function below
747 var args = arguments;
750 return method.apply(window, args);
755 * Creates a delegate (callback) that sets the scope to obj.
756 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
757 * Will create a function that is automatically scoped to this.
758 * @param {Object} obj (optional) The object for which the scope is set
759 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
760 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
761 * if a number the args are inserted at the specified position
762 * @return {Function} The new function
764 createDelegate : function(obj, args, appendArgs){
767 var callArgs = args || arguments;
768 if(appendArgs === true){
769 callArgs = Array.prototype.slice.call(arguments, 0);
770 callArgs = callArgs.concat(args);
771 }else if(typeof appendArgs == "number"){
772 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
773 var applyArgs = [appendArgs, 0].concat(args); // create method call params
774 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
776 return method.apply(obj || window, callArgs);
781 * Calls this function after the number of millseconds specified.
782 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
783 * @param {Object} obj (optional) The object for which the scope is set
784 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
785 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
786 * if a number the args are inserted at the specified position
787 * @return {Number} The timeout id that can be used with clearTimeout
789 defer : function(millis, obj, args, appendArgs){
790 var fn = this.createDelegate(obj, args, appendArgs);
792 return setTimeout(fn, millis);
798 * Create a combined function call sequence of the original function + the passed function.
799 * The resulting function returns the results of the original function.
800 * The passed fcn is called with the parameters of the original function
801 * @param {Function} fcn The function to sequence
802 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
803 * @return {Function} The new function
805 createSequence : function(fcn, scope){
806 if(typeof fcn != "function"){
811 var retval = method.apply(this || window, arguments);
812 fcn.apply(scope || this || window, arguments);
818 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
819 * The resulting function returns the results of the original function.
820 * The passed fcn is called with the parameters of the original function.
822 * @param {Function} fcn The function to call before the original
823 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
824 * @return {Function} The new function
826 createInterceptor : function(fcn, scope){
827 if(typeof fcn != "function"){
834 if(fcn.apply(scope || this || window, arguments) === false){
837 return method.apply(this || window, arguments);
843 * Ext JS Library 1.1.1
844 * Copyright(c) 2006-2007, Ext JS, LLC.
846 * Originally Released Under LGPL - original licence link has changed is not relivant.
849 * <script type="text/javascript">
852 Roo.applyIf(String, {
857 * Escapes the passed string for ' and \
858 * @param {String} string The string to escape
859 * @return {String} The escaped string
862 escape : function(string) {
863 return string.replace(/('|\\)/g, "\\$1");
867 * Pads the left side of a string with a specified character. This is especially useful
868 * for normalizing number and date strings. Example usage:
870 var s = String.leftPad('123', 5, '0');
871 // s now contains the string: '00123'
873 * @param {String} string The original string
874 * @param {Number} size The total length of the output string
875 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
876 * @return {String} The padded string
879 leftPad : function (val, size, ch) {
880 var result = new String(val);
881 if(ch === null || ch === undefined || ch === '') {
884 while (result.length < size) {
885 result = ch + result;
891 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
892 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
894 var cls = 'my-class', text = 'Some text';
895 var s = String.format('<div class="{0}">{1}</div>', cls, text);
896 // s now contains the string: '<div class="my-class">Some text</div>'
898 * @param {String} string The tokenized string to be formatted
899 * @param {String} value1 The value to replace token {0}
900 * @param {String} value2 Etc...
901 * @return {String} The formatted string
904 format : function(format){
905 var args = Array.prototype.slice.call(arguments, 1);
906 return format.replace(/\{(\d+)\}/g, function(m, i){
907 return Roo.util.Format.htmlEncode(args[i]);
915 * Utility function that allows you to easily switch a string between two alternating values. The passed value
916 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
917 * they are already different, the first value passed in is returned. Note that this method returns the new value
918 * but does not change the current string.
920 // alternate sort directions
921 sort = sort.toggle('ASC', 'DESC');
923 // instead of conditional logic:
924 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
926 * @param {String} value The value to compare to the current string
927 * @param {String} other The new value to use if the string already equals the first value passed in
928 * @return {String} The new value
931 String.prototype.toggle = function(value, other){
932 return this == value ? other : value;
937 * Remove invalid unicode characters from a string
939 * @return {String} The clean string
941 String.prototype.unicodeClean = function () {
942 return this.replace(/[\s\S]/g,
943 function(character) {
944 if (character.charCodeAt()< 256) {
948 encodeURIComponent(character);
959 * Ext JS Library 1.1.1
960 * Copyright(c) 2006-2007, Ext JS, LLC.
962 * Originally Released Under LGPL - original licence link has changed is not relivant.
965 * <script type="text/javascript">
971 Roo.applyIf(Number.prototype, {
973 * Checks whether or not the current number is within a desired range. If the number is already within the
974 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
975 * exceeded. Note that this method returns the constrained value but does not change the current number.
976 * @param {Number} min The minimum number in the range
977 * @param {Number} max The maximum number in the range
978 * @return {Number} The constrained value if outside the range, otherwise the current value
980 constrain : function(min, max){
981 return Math.min(Math.max(this, min), max);
985 * Ext JS Library 1.1.1
986 * Copyright(c) 2006-2007, Ext JS, LLC.
988 * Originally Released Under LGPL - original licence link has changed is not relivant.
991 * <script type="text/javascript">
996 Roo.applyIf(Array.prototype, {
999 * Checks whether or not the specified object exists in the array.
1000 * @param {Object} o The object to check for
1001 * @return {Number} The index of o in the array (or -1 if it is not found)
1003 indexOf : function(o){
1004 for (var i = 0, len = this.length; i < len; i++){
1005 if(this[i] == o) { return i; }
1011 * Removes the specified object from the array. If the object is not found nothing happens.
1012 * @param {Object} o The object to remove
1014 remove : function(o){
1015 var index = this.indexOf(o);
1017 this.splice(index, 1);
1021 * Map (JS 1.6 compatibility)
1022 * @param {Function} function to call
1024 map : function(fun )
1026 var len = this.length >>> 0;
1027 if (typeof fun != "function") {
1028 throw new TypeError();
1030 var res = new Array(len);
1031 var thisp = arguments[1];
1032 for (var i = 0; i < len; i++)
1035 res[i] = fun.call(thisp, this[i], i, this);
1043 * @param {Array} o The array to compare to
1044 * @returns {Boolean} true if the same
1046 equals : function(b)
1048 // https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
1055 if (this.length !== b.length) {
1059 // sort?? a.sort().equals(b.sort());
1061 for (var i = 0; i < this.length; ++i) {
1062 if (this[i] !== b[i]) {
1074 Roo.applyIf(Array, {
1078 * @param {Array} o Or Array like object (eg. nodelist)
1085 for (var i =0; i < o.length; i++) {
1094 * Ext JS Library 1.1.1
1095 * Copyright(c) 2006-2007, Ext JS, LLC.
1097 * Originally Released Under LGPL - original licence link has changed is not relivant.
1100 * <script type="text/javascript">
1106 * The date parsing and format syntax is a subset of
1107 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
1108 * supported will provide results equivalent to their PHP versions.
1110 * Following is the list of all currently supported formats:
1113 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
1115 Format Output Description
1116 ------ ---------- --------------------------------------------------------------
1117 d 10 Day of the month, 2 digits with leading zeros
1118 D Wed A textual representation of a day, three letters
1119 j 10 Day of the month without leading zeros
1120 l Wednesday A full textual representation of the day of the week
1121 S th English ordinal day of month suffix, 2 chars (use with j)
1122 w 3 Numeric representation of the day of the week
1123 z 9 The julian date, or day of the year (0-365)
1124 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1125 F January A full textual representation of the month
1126 m 01 Numeric representation of a month, with leading zeros
1127 M Jan Month name abbreviation, three letters
1128 n 1 Numeric representation of a month, without leading zeros
1129 t 31 Number of days in the given month
1130 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1131 Y 2007 A full numeric representation of a year, 4 digits
1132 y 07 A two digit representation of a year
1133 a pm Lowercase Ante meridiem and Post meridiem
1134 A PM Uppercase Ante meridiem and Post meridiem
1135 g 3 12-hour format of an hour without leading zeros
1136 G 15 24-hour format of an hour without leading zeros
1137 h 03 12-hour format of an hour with leading zeros
1138 H 15 24-hour format of an hour with leading zeros
1139 i 05 Minutes with leading zeros
1140 s 01 Seconds, with leading zeros
1141 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1142 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1143 T CST Timezone setting of the machine running the code
1144 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1147 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1149 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1150 document.write(dt.format('Y-m-d')); //2007-01-10
1151 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1152 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
1155 * Here are some standard date/time patterns that you might find helpful. They
1156 * are not part of the source of Date.js, but to use them you can simply copy this
1157 * block of code into any script that is included after Date.js and they will also become
1158 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1161 ISO8601Long:"Y-m-d H:i:s",
1162 ISO8601Short:"Y-m-d",
1164 LongDate: "l, F d, Y",
1165 FullDateTime: "l, F d, Y g:i:s A",
1168 LongTime: "g:i:s A",
1169 SortableDateTime: "Y-m-d\\TH:i:s",
1170 UniversalSortableDateTime: "Y-m-d H:i:sO",
1177 var dt = new Date();
1178 document.write(dt.format(Date.patterns.ShortDate));
1183 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1184 * They generate precompiled functions from date formats instead of parsing and
1185 * processing the pattern every time you format a date. These functions are available
1186 * on every Date object (any javascript function).
1188 * The original article and download are here:
1189 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1196 Returns the number of milliseconds between this date and date
1197 @param {Date} date (optional) Defaults to now
1198 @return {Number} The diff in milliseconds
1199 @member Date getElapsed
1201 Date.prototype.getElapsed = function(date) {
1202 return Math.abs((date || new Date()).getTime()-this.getTime());
1204 // was in date file..
1208 Date.parseFunctions = {count:0};
1210 Date.parseRegexes = [];
1212 Date.formatFunctions = {count:0};
1215 Date.prototype.dateFormat = function(format) {
1216 if (Date.formatFunctions[format] == null) {
1217 Date.createNewFormat(format);
1219 var func = Date.formatFunctions[format];
1220 return this[func]();
1225 * Formats a date given the supplied format string
1226 * @param {String} format The format string
1227 * @return {String} The formatted date
1230 Date.prototype.format = Date.prototype.dateFormat;
1233 Date.createNewFormat = function(format) {
1234 var funcName = "format" + Date.formatFunctions.count++;
1235 Date.formatFunctions[format] = funcName;
1236 var code = "Date.prototype." + funcName + " = function(){return ";
1237 var special = false;
1239 for (var i = 0; i < format.length; ++i) {
1240 ch = format.charAt(i);
1241 if (!special && ch == "\\") {
1246 code += "'" + String.escape(ch) + "' + ";
1249 code += Date.getFormatCode(ch);
1252 /** eval:var:zzzzzzzzzzzzz */
1253 eval(code.substring(0, code.length - 3) + ";}");
1257 Date.getFormatCode = function(character) {
1258 switch (character) {
1260 return "String.leftPad(this.getDate(), 2, '0') + ";
1262 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1264 return "this.getDate() + ";
1266 return "Date.dayNames[this.getDay()] + ";
1268 return "this.getSuffix() + ";
1270 return "this.getDay() + ";
1272 return "this.getDayOfYear() + ";
1274 return "this.getWeekOfYear() + ";
1276 return "Date.monthNames[this.getMonth()] + ";
1278 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1280 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1282 return "(this.getMonth() + 1) + ";
1284 return "this.getDaysInMonth() + ";
1286 return "(this.isLeapYear() ? 1 : 0) + ";
1288 return "this.getFullYear() + ";
1290 return "('' + this.getFullYear()).substring(2, 4) + ";
1292 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1294 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1296 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1298 return "this.getHours() + ";
1300 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1302 return "String.leftPad(this.getHours(), 2, '0') + ";
1304 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1306 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1308 return "this.getGMTOffset() + ";
1310 return "this.getGMTColonOffset() + ";
1312 return "this.getTimezone() + ";
1314 return "(this.getTimezoneOffset() * -60) + ";
1316 return "'" + String.escape(character) + "' + ";
1321 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1322 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1323 * the date format that is not specified will default to the current date value for that part. Time parts can also
1324 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1325 * string or the parse operation will fail.
1328 //dt = Fri May 25 2007 (current date)
1329 var dt = new Date();
1331 //dt = Thu May 25 2006 (today's month/day in 2006)
1332 dt = Date.parseDate("2006", "Y");
1334 //dt = Sun Jan 15 2006 (all date parts specified)
1335 dt = Date.parseDate("2006-1-15", "Y-m-d");
1337 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1338 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1340 * @param {String} input The unparsed date as a string
1341 * @param {String} format The format the date is in
1342 * @return {Date} The parsed date
1345 Date.parseDate = function(input, format) {
1346 if (Date.parseFunctions[format] == null) {
1347 Date.createParser(format);
1349 var func = Date.parseFunctions[format];
1350 return Date[func](input);
1356 Date.createParser = function(format) {
1357 var funcName = "parse" + Date.parseFunctions.count++;
1358 var regexNum = Date.parseRegexes.length;
1359 var currentGroup = 1;
1360 Date.parseFunctions[format] = funcName;
1362 var code = "Date." + funcName + " = function(input){\n"
1363 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1364 + "var d = new Date();\n"
1365 + "y = d.getFullYear();\n"
1366 + "m = d.getMonth();\n"
1367 + "d = d.getDate();\n"
1368 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1369 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1370 + "if (results && results.length > 0) {";
1373 var special = false;
1375 for (var i = 0; i < format.length; ++i) {
1376 ch = format.charAt(i);
1377 if (!special && ch == "\\") {
1382 regex += String.escape(ch);
1385 var obj = Date.formatCodeToRegex(ch, currentGroup);
1386 currentGroup += obj.g;
1388 if (obj.g && obj.c) {
1394 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1395 + "{v = new Date(y, m, d, h, i, s);}\n"
1396 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1397 + "{v = new Date(y, m, d, h, i);}\n"
1398 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1399 + "{v = new Date(y, m, d, h);}\n"
1400 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1401 + "{v = new Date(y, m, d);}\n"
1402 + "else if (y >= 0 && m >= 0)\n"
1403 + "{v = new Date(y, m);}\n"
1404 + "else if (y >= 0)\n"
1405 + "{v = new Date(y);}\n"
1406 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1407 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1408 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1411 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1412 /** eval:var:zzzzzzzzzzzzz */
1417 Date.formatCodeToRegex = function(character, currentGroup) {
1418 switch (character) {
1422 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1425 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1426 s:"(\\d{1,2})"}; // day of month without leading zeroes
1429 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1430 s:"(\\d{2})"}; // day of month with leading zeroes
1434 s:"(?:" + Date.dayNames.join("|") + ")"};
1438 s:"(?:st|nd|rd|th)"};
1453 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1454 s:"(" + Date.monthNames.join("|") + ")"};
1457 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1458 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1461 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1462 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1465 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1466 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1477 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1481 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1482 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1486 c:"if (results[" + currentGroup + "] == 'am') {\n"
1487 + "if (h == 12) { h = 0; }\n"
1488 + "} else { if (h < 12) { h += 12; }}",
1492 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1493 + "if (h == 12) { h = 0; }\n"
1494 + "} else { if (h < 12) { h += 12; }}",
1499 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1500 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1504 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1505 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1508 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1512 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1517 "o = results[", currentGroup, "];\n",
1518 "var sn = o.substring(0,1);\n", // get + / - sign
1519 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1520 "var mn = o.substring(3,5) % 60;\n", // get minutes
1521 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1522 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1524 s:"([+\-]\\d{2,4})"};
1530 "o = results[", currentGroup, "];\n",
1531 "var sn = o.substring(0,1);\n",
1532 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1533 "var mn = o.substring(4,6) % 60;\n",
1534 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1535 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1541 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1544 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1545 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1546 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1550 s:String.escape(character)};
1555 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1556 * @return {String} The abbreviated timezone name (e.g. 'CST')
1558 Date.prototype.getTimezone = function() {
1559 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1563 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1564 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1566 Date.prototype.getGMTOffset = function() {
1567 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1568 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1569 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1573 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1574 * @return {String} 2-characters representing hours and 2-characters representing minutes
1575 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1577 Date.prototype.getGMTColonOffset = function() {
1578 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1579 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1581 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1585 * Get the numeric day number of the year, adjusted for leap year.
1586 * @return {Number} 0 through 364 (365 in leap years)
1588 Date.prototype.getDayOfYear = function() {
1590 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1591 for (var i = 0; i < this.getMonth(); ++i) {
1592 num += Date.daysInMonth[i];
1594 return num + this.getDate() - 1;
1598 * Get the string representation of the numeric week number of the year
1599 * (equivalent to the format specifier 'W').
1600 * @return {String} '00' through '52'
1602 Date.prototype.getWeekOfYear = function() {
1603 // Skip to Thursday of this week
1604 var now = this.getDayOfYear() + (4 - this.getDay());
1605 // Find the first Thursday of the year
1606 var jan1 = new Date(this.getFullYear(), 0, 1);
1607 var then = (7 - jan1.getDay() + 4);
1608 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1612 * Whether or not the current date is in a leap year.
1613 * @return {Boolean} True if the current date is in a leap year, else false
1615 Date.prototype.isLeapYear = function() {
1616 var year = this.getFullYear();
1617 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1621 * Get the first day of the current month, adjusted for leap year. The returned value
1622 * is the numeric day index within the week (0-6) which can be used in conjunction with
1623 * the {@link #monthNames} array to retrieve the textual day name.
1626 var dt = new Date('1/10/2007');
1627 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1629 * @return {Number} The day number (0-6)
1631 Date.prototype.getFirstDayOfMonth = function() {
1632 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1633 return (day < 0) ? (day + 7) : day;
1637 * Get the last day of the current month, adjusted for leap year. The returned value
1638 * is the numeric day index within the week (0-6) which can be used in conjunction with
1639 * the {@link #monthNames} array to retrieve the textual day name.
1642 var dt = new Date('1/10/2007');
1643 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1645 * @return {Number} The day number (0-6)
1647 Date.prototype.getLastDayOfMonth = function() {
1648 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1649 return (day < 0) ? (day + 7) : day;
1654 * Get the first date of this date's month
1657 Date.prototype.getFirstDateOfMonth = function() {
1658 return new Date(this.getFullYear(), this.getMonth(), 1);
1662 * Get the last date of this date's month
1665 Date.prototype.getLastDateOfMonth = function() {
1666 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1669 * Get the number of days in the current month, adjusted for leap year.
1670 * @return {Number} The number of days in the month
1672 Date.prototype.getDaysInMonth = function() {
1673 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1674 return Date.daysInMonth[this.getMonth()];
1678 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1679 * @return {String} 'st, 'nd', 'rd' or 'th'
1681 Date.prototype.getSuffix = function() {
1682 switch (this.getDate()) {
1699 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1702 * An array of textual month names.
1703 * Override these values for international dates, for example...
1704 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1723 * An array of textual day names.
1724 * Override these values for international dates, for example...
1725 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1741 Date.monthNumbers = {
1756 * Creates and returns a new Date instance with the exact same date value as the called instance.
1757 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1758 * variable will also be changed. When the intention is to create a new variable that will not
1759 * modify the original instance, you should create a clone.
1761 * Example of correctly cloning a date:
1764 var orig = new Date('10/1/2006');
1767 document.write(orig); //returns 'Thu Oct 05 2006'!
1770 var orig = new Date('10/1/2006');
1771 var copy = orig.clone();
1773 document.write(orig); //returns 'Thu Oct 01 2006'
1775 * @return {Date} The new Date instance
1777 Date.prototype.clone = function() {
1778 return new Date(this.getTime());
1782 * Clears any time information from this date
1783 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1784 @return {Date} this or the clone
1786 Date.prototype.clearTime = function(clone){
1788 return this.clone().clearTime();
1793 this.setMilliseconds(0);
1798 // safari setMonth is broken -- check that this is only donw once...
1799 if(Roo.isSafari && typeof(Date.brokenSetMonth) == 'undefined'){
1800 Date.brokenSetMonth = Date.prototype.setMonth;
1801 Date.prototype.setMonth = function(num){
1803 var n = Math.ceil(-num);
1804 var back_year = Math.ceil(n/12);
1805 var month = (n % 12) ? 12 - n % 12 : 0 ;
1806 this.setFullYear(this.getFullYear() - back_year);
1807 return Date.brokenSetMonth.call(this, month);
1809 return Date.brokenSetMonth.apply(this, arguments);
1814 /** Date interval constant
1818 /** Date interval constant
1822 /** Date interval constant
1826 /** Date interval constant
1830 /** Date interval constant
1834 /** Date interval constant
1838 /** Date interval constant
1844 * Provides a convenient method of performing basic date arithmetic. This method
1845 * does not modify the Date instance being called - it creates and returns
1846 * a new Date instance containing the resulting date value.
1851 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1852 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1854 //Negative values will subtract correctly:
1855 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1856 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1858 //You can even chain several calls together in one line!
1859 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1860 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1863 * @param {String} interval A valid date interval enum value
1864 * @param {Number} value The amount to add to the current date
1865 * @return {Date} The new Date instance
1867 Date.prototype.add = function(interval, value){
1868 var d = this.clone();
1869 if (!interval || value === 0) { return d; }
1870 switch(interval.toLowerCase()){
1872 d.setMilliseconds(this.getMilliseconds() + value);
1875 d.setSeconds(this.getSeconds() + value);
1878 d.setMinutes(this.getMinutes() + value);
1881 d.setHours(this.getHours() + value);
1884 d.setDate(this.getDate() + value);
1887 var day = this.getDate();
1889 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1892 d.setMonth(this.getMonth() + value);
1895 d.setFullYear(this.getFullYear() + value);
1901 * @class Roo.lib.Dom
1905 * Dom utils (from YIU afaik)
1911 * Get the view width
1912 * @param {Boolean} full True will get the full document, otherwise it's the view width
1913 * @return {Number} The width
1916 getViewWidth : function(full) {
1917 return full ? this.getDocumentWidth() : this.getViewportWidth();
1920 * Get the view height
1921 * @param {Boolean} full True will get the full document, otherwise it's the view height
1922 * @return {Number} The height
1924 getViewHeight : function(full) {
1925 return full ? this.getDocumentHeight() : this.getViewportHeight();
1928 * Get the Full Document height
1929 * @return {Number} The height
1931 getDocumentHeight: function() {
1932 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1933 return Math.max(scrollHeight, this.getViewportHeight());
1936 * Get the Full Document width
1937 * @return {Number} The width
1939 getDocumentWidth: function() {
1940 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1941 return Math.max(scrollWidth, this.getViewportWidth());
1944 * Get the Window Viewport height
1945 * @return {Number} The height
1947 getViewportHeight: function() {
1948 var height = self.innerHeight;
1949 var mode = document.compatMode;
1951 if ((mode || Roo.isIE) && !Roo.isOpera) {
1952 height = (mode == "CSS1Compat") ?
1953 document.documentElement.clientHeight :
1954 document.body.clientHeight;
1960 * Get the Window Viewport width
1961 * @return {Number} The width
1963 getViewportWidth: function() {
1964 var width = self.innerWidth;
1965 var mode = document.compatMode;
1967 if (mode || Roo.isIE) {
1968 width = (mode == "CSS1Compat") ?
1969 document.documentElement.clientWidth :
1970 document.body.clientWidth;
1975 isAncestor : function(p, c) {
1982 if (p.contains && !Roo.isSafari) {
1983 return p.contains(c);
1984 } else if (p.compareDocumentPosition) {
1985 return !!(p.compareDocumentPosition(c) & 16);
1987 var parent = c.parentNode;
1992 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1995 parent = parent.parentNode;
2001 getRegion : function(el) {
2002 return Roo.lib.Region.getRegion(el);
2005 getY : function(el) {
2006 return this.getXY(el)[1];
2009 getX : function(el) {
2010 return this.getXY(el)[0];
2013 getXY : function(el) {
2014 var p, pe, b, scroll, bd = document.body;
2015 el = Roo.getDom(el);
2016 var fly = Roo.lib.AnimBase.fly;
2017 if (el.getBoundingClientRect) {
2018 b = el.getBoundingClientRect();
2019 scroll = fly(document).getScroll();
2020 return [b.left + scroll.left, b.top + scroll.top];
2026 var hasAbsolute = fly(el).getStyle("position") == "absolute";
2033 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
2040 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
2041 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
2048 if (p != el && pe.getStyle('overflow') != 'visible') {
2056 if (Roo.isSafari && hasAbsolute) {
2061 if (Roo.isGecko && !hasAbsolute) {
2063 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
2064 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
2068 while (p && p != bd) {
2069 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
2081 setXY : function(el, xy) {
2082 el = Roo.fly(el, '_setXY');
2084 var pts = el.translatePoints(xy);
2085 if (xy[0] !== false) {
2086 el.dom.style.left = pts.left + "px";
2088 if (xy[1] !== false) {
2089 el.dom.style.top = pts.top + "px";
2093 setX : function(el, x) {
2094 this.setXY(el, [x, false]);
2097 setY : function(el, y) {
2098 this.setXY(el, [false, y]);
2102 * Portions of this file are based on pieces of Yahoo User Interface Library
2103 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2104 * YUI licensed under the BSD License:
2105 * http://developer.yahoo.net/yui/license.txt
2106 * <script type="text/javascript">
2110 Roo.lib.Event = function() {
2111 var loadComplete = false;
2113 var unloadListeners = [];
2115 var onAvailStack = [];
2117 var lastError = null;
2130 startInterval: function() {
2131 if (!this._interval) {
2133 var callback = function() {
2134 self._tryPreloadAttach();
2136 this._interval = setInterval(callback, this.POLL_INTERVAL);
2141 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2142 onAvailStack.push({ id: p_id,
2145 override: p_override,
2146 checkReady: false });
2148 retryCount = this.POLL_RETRYS;
2149 this.startInterval();
2153 addListener: function(el, eventName, fn) {
2154 el = Roo.getDom(el);
2159 if ("unload" == eventName) {
2160 unloadListeners[unloadListeners.length] =
2161 [el, eventName, fn];
2165 var wrappedFn = function(e) {
2166 return fn(Roo.lib.Event.getEvent(e));
2169 var li = [el, eventName, fn, wrappedFn];
2171 var index = listeners.length;
2172 listeners[index] = li;
2174 this.doAdd(el, eventName, wrappedFn, false);
2180 removeListener: function(el, eventName, fn) {
2183 el = Roo.getDom(el);
2186 return this.purgeElement(el, false, eventName);
2190 if ("unload" == eventName) {
2192 for (i = 0,len = unloadListeners.length; i < len; i++) {
2193 var li = unloadListeners[i];
2196 li[1] == eventName &&
2198 unloadListeners.splice(i, 1);
2206 var cacheItem = null;
2209 var index = arguments[3];
2211 if ("undefined" == typeof index) {
2212 index = this._getCacheIndex(el, eventName, fn);
2216 cacheItem = listeners[index];
2219 if (!el || !cacheItem) {
2223 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2225 delete listeners[index][this.WFN];
2226 delete listeners[index][this.FN];
2227 listeners.splice(index, 1);
2234 getTarget: function(ev, resolveTextNode) {
2235 ev = ev.browserEvent || ev;
2236 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2237 var t = ev.target || ev.srcElement;
2238 return this.resolveTextNode(t);
2242 resolveTextNode: function(node) {
2243 if (Roo.isSafari && node && 3 == node.nodeType) {
2244 return node.parentNode;
2251 getPageX: function(ev) {
2252 ev = ev.browserEvent || ev;
2253 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2255 if (!x && 0 !== x) {
2256 x = ev.clientX || 0;
2259 x += this.getScroll()[1];
2267 getPageY: function(ev) {
2268 ev = ev.browserEvent || ev;
2269 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2271 if (!y && 0 !== y) {
2272 y = ev.clientY || 0;
2275 y += this.getScroll()[0];
2284 getXY: function(ev) {
2285 ev = ev.browserEvent || ev;
2286 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2287 return [this.getPageX(ev), this.getPageY(ev)];
2291 getRelatedTarget: function(ev) {
2292 ev = ev.browserEvent || ev;
2293 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2294 var t = ev.relatedTarget;
2296 if (ev.type == "mouseout") {
2298 } else if (ev.type == "mouseover") {
2303 return this.resolveTextNode(t);
2307 getTime: function(ev) {
2308 ev = ev.browserEvent || ev;
2309 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2311 var t = new Date().getTime();
2315 this.lastError = ex;
2324 stopEvent: function(ev) {
2325 this.stopPropagation(ev);
2326 this.preventDefault(ev);
2330 stopPropagation: function(ev) {
2331 ev = ev.browserEvent || ev;
2332 if (ev.stopPropagation) {
2333 ev.stopPropagation();
2335 ev.cancelBubble = true;
2340 preventDefault: function(ev) {
2341 ev = ev.browserEvent || ev;
2342 if(ev.preventDefault) {
2343 ev.preventDefault();
2345 ev.returnValue = false;
2350 getEvent: function(e) {
2351 var ev = e || window.event;
2353 var c = this.getEvent.caller;
2355 ev = c.arguments[0];
2356 if (ev && Event == ev.constructor) {
2366 getCharCode: function(ev) {
2367 ev = ev.browserEvent || ev;
2368 return ev.charCode || ev.keyCode || 0;
2372 _getCacheIndex: function(el, eventName, fn) {
2373 for (var i = 0,len = listeners.length; i < len; ++i) {
2374 var li = listeners[i];
2376 li[this.FN] == fn &&
2377 li[this.EL] == el &&
2378 li[this.TYPE] == eventName) {
2390 getEl: function(id) {
2391 return document.getElementById(id);
2395 clearCache: function() {
2399 _load: function(e) {
2400 loadComplete = true;
2401 var EU = Roo.lib.Event;
2405 EU.doRemove(window, "load", EU._load);
2410 _tryPreloadAttach: function() {
2419 var tryAgain = !loadComplete;
2421 tryAgain = (retryCount > 0);
2426 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2427 var item = onAvailStack[i];
2429 var el = this.getEl(item.id);
2432 if (!item.checkReady ||
2435 (document && document.body)) {
2438 if (item.override) {
2439 if (item.override === true) {
2442 scope = item.override;
2445 item.fn.call(scope, item.obj);
2446 onAvailStack[i] = null;
2449 notAvail.push(item);
2454 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2458 this.startInterval();
2460 clearInterval(this._interval);
2461 this._interval = null;
2464 this.locked = false;
2471 purgeElement: function(el, recurse, eventName) {
2472 var elListeners = this.getListeners(el, eventName);
2474 for (var i = 0,len = elListeners.length; i < len; ++i) {
2475 var l = elListeners[i];
2476 this.removeListener(el, l.type, l.fn);
2480 if (recurse && el && el.childNodes) {
2481 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2482 this.purgeElement(el.childNodes[i], recurse, eventName);
2488 getListeners: function(el, eventName) {
2489 var results = [], searchLists;
2491 searchLists = [listeners, unloadListeners];
2492 } else if (eventName == "unload") {
2493 searchLists = [unloadListeners];
2495 searchLists = [listeners];
2498 for (var j = 0; j < searchLists.length; ++j) {
2499 var searchList = searchLists[j];
2500 if (searchList && searchList.length > 0) {
2501 for (var i = 0,len = searchList.length; i < len; ++i) {
2502 var l = searchList[i];
2503 if (l && l[this.EL] === el &&
2504 (!eventName || eventName === l[this.TYPE])) {
2509 adjust: l[this.ADJ_SCOPE],
2517 return (results.length) ? results : null;
2521 _unload: function(e) {
2523 var EU = Roo.lib.Event, i, j, l, len, index;
2525 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2526 l = unloadListeners[i];
2529 if (l[EU.ADJ_SCOPE]) {
2530 if (l[EU.ADJ_SCOPE] === true) {
2533 scope = l[EU.ADJ_SCOPE];
2536 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2537 unloadListeners[i] = null;
2543 unloadListeners = null;
2545 if (listeners && listeners.length > 0) {
2546 j = listeners.length;
2549 l = listeners[index];
2551 EU.removeListener(l[EU.EL], l[EU.TYPE],
2561 EU.doRemove(window, "unload", EU._unload);
2566 getScroll: function() {
2567 var dd = document.documentElement, db = document.body;
2568 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2569 return [dd.scrollTop, dd.scrollLeft];
2571 return [db.scrollTop, db.scrollLeft];
2578 doAdd: function () {
2579 if (window.addEventListener) {
2580 return function(el, eventName, fn, capture) {
2581 el.addEventListener(eventName, fn, (capture));
2583 } else if (window.attachEvent) {
2584 return function(el, eventName, fn, capture) {
2585 el.attachEvent("on" + eventName, fn);
2594 doRemove: function() {
2595 if (window.removeEventListener) {
2596 return function (el, eventName, fn, capture) {
2597 el.removeEventListener(eventName, fn, (capture));
2599 } else if (window.detachEvent) {
2600 return function (el, eventName, fn) {
2601 el.detachEvent("on" + eventName, fn);
2613 var E = Roo.lib.Event;
2614 E.on = E.addListener;
2615 E.un = E.removeListener;
2617 if (document && document.body) {
2620 E.doAdd(window, "load", E._load);
2622 E.doAdd(window, "unload", E._unload);
2623 E._tryPreloadAttach();
2630 * @class Roo.lib.Ajax
2632 * provide a simple Ajax request utility functions
2634 * Portions of this file are based on pieces of Yahoo User Interface Library
2635 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2636 * YUI licensed under the BSD License:
2637 * http://developer.yahoo.net/yui/license.txt
2638 * <script type="text/javascript">
2646 request : function(method, uri, cb, data, options) {
2648 var hs = options.headers;
2651 if(hs.hasOwnProperty(h)){
2652 this.initHeader(h, hs[h], false);
2656 if(options.xmlData){
2657 this.initHeader('Content-Type', 'text/xml', false);
2659 data = options.xmlData;
2663 return this.asyncRequest(method, uri, cb, data);
2669 * @param {DomForm} form element
2670 * @return {String} urlencode form output.
2672 serializeForm : function(form) {
2673 if(typeof form == 'string') {
2674 form = (document.getElementById(form) || document.forms[form]);
2677 var el, name, val, disabled, data = '', hasSubmit = false;
2678 for (var i = 0; i < form.elements.length; i++) {
2679 el = form.elements[i];
2680 disabled = form.elements[i].disabled;
2681 name = form.elements[i].name;
2682 val = form.elements[i].value;
2684 if (!disabled && name){
2688 case 'select-multiple':
2689 for (var j = 0; j < el.options.length; j++) {
2690 if (el.options[j].selected) {
2692 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2695 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2703 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2716 if(hasSubmit == false) {
2717 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2722 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2727 data = data.substr(0, data.length - 1);
2735 useDefaultHeader:true,
2737 defaultPostHeader:'application/x-www-form-urlencoded',
2739 useDefaultXhrHeader:true,
2741 defaultXhrHeader:'XMLHttpRequest',
2743 hasDefaultHeaders:true,
2755 setProgId:function(id)
2757 this.activeX.unshift(id);
2760 setDefaultPostHeader:function(b)
2762 this.useDefaultHeader = b;
2765 setDefaultXhrHeader:function(b)
2767 this.useDefaultXhrHeader = b;
2770 setPollingInterval:function(i)
2772 if (typeof i == 'number' && isFinite(i)) {
2773 this.pollInterval = i;
2777 createXhrObject:function(transactionId)
2783 http = new XMLHttpRequest();
2785 obj = { conn:http, tId:transactionId };
2789 for (var i = 0; i < this.activeX.length; ++i) {
2793 http = new ActiveXObject(this.activeX[i]);
2795 obj = { conn:http, tId:transactionId };
2808 getConnectionObject:function()
2811 var tId = this.transactionId;
2815 o = this.createXhrObject(tId);
2817 this.transactionId++;
2828 asyncRequest:function(method, uri, callback, postData)
2830 var o = this.getConnectionObject();
2836 o.conn.open(method, uri, true);
2838 if (this.useDefaultXhrHeader) {
2839 if (!this.defaultHeaders['X-Requested-With']) {
2840 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2844 if(postData && this.useDefaultHeader){
2845 this.initHeader('Content-Type', this.defaultPostHeader);
2848 if (this.hasDefaultHeaders || this.hasHeaders) {
2852 this.handleReadyState(o, callback);
2853 o.conn.send(postData || null);
2859 handleReadyState:function(o, callback)
2863 if (callback && callback.timeout) {
2865 this.timeout[o.tId] = window.setTimeout(function() {
2866 oConn.abort(o, callback, true);
2867 }, callback.timeout);
2870 this.poll[o.tId] = window.setInterval(
2872 if (o.conn && o.conn.readyState == 4) {
2873 window.clearInterval(oConn.poll[o.tId]);
2874 delete oConn.poll[o.tId];
2876 if(callback && callback.timeout) {
2877 window.clearTimeout(oConn.timeout[o.tId]);
2878 delete oConn.timeout[o.tId];
2881 oConn.handleTransactionResponse(o, callback);
2884 , this.pollInterval);
2887 handleTransactionResponse:function(o, callback, isAbort)
2891 this.releaseObject(o);
2895 var httpStatus, responseObject;
2899 if (o.conn.status !== undefined && o.conn.status != 0) {
2900 httpStatus = o.conn.status;
2912 if (httpStatus >= 200 && httpStatus < 300) {
2913 responseObject = this.createResponseObject(o, callback.argument);
2914 if (callback.success) {
2915 if (!callback.scope) {
2916 callback.success(responseObject);
2921 callback.success.apply(callback.scope, [responseObject]);
2926 switch (httpStatus) {
2934 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2935 if (callback.failure) {
2936 if (!callback.scope) {
2937 callback.failure(responseObject);
2940 callback.failure.apply(callback.scope, [responseObject]);
2945 responseObject = this.createResponseObject(o, callback.argument);
2946 if (callback.failure) {
2947 if (!callback.scope) {
2948 callback.failure(responseObject);
2951 callback.failure.apply(callback.scope, [responseObject]);
2957 this.releaseObject(o);
2958 responseObject = null;
2961 createResponseObject:function(o, callbackArg)
2968 var headerStr = o.conn.getAllResponseHeaders();
2969 var header = headerStr.split('\n');
2970 for (var i = 0; i < header.length; i++) {
2971 var delimitPos = header[i].indexOf(':');
2972 if (delimitPos != -1) {
2973 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2981 obj.status = o.conn.status;
2982 obj.statusText = o.conn.statusText;
2983 obj.getResponseHeader = headerObj;
2984 obj.getAllResponseHeaders = headerStr;
2985 obj.responseText = o.conn.responseText;
2986 obj.responseXML = o.conn.responseXML;
2988 if (typeof callbackArg !== undefined) {
2989 obj.argument = callbackArg;
2995 createExceptionObject:function(tId, callbackArg, isAbort)
2998 var COMM_ERROR = 'communication failure';
2999 var ABORT_CODE = -1;
3000 var ABORT_ERROR = 'transaction aborted';
3006 obj.status = ABORT_CODE;
3007 obj.statusText = ABORT_ERROR;
3010 obj.status = COMM_CODE;
3011 obj.statusText = COMM_ERROR;
3015 obj.argument = callbackArg;
3021 initHeader:function(label, value, isDefault)
3023 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
3025 if (headerObj[label] === undefined) {
3026 headerObj[label] = value;
3031 headerObj[label] = value + "," + headerObj[label];
3035 this.hasDefaultHeaders = true;
3038 this.hasHeaders = true;
3043 setHeader:function(o)
3045 if (this.hasDefaultHeaders) {
3046 for (var prop in this.defaultHeaders) {
3047 if (this.defaultHeaders.hasOwnProperty(prop)) {
3048 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
3053 if (this.hasHeaders) {
3054 for (var prop in this.headers) {
3055 if (this.headers.hasOwnProperty(prop)) {
3056 o.conn.setRequestHeader(prop, this.headers[prop]);
3060 this.hasHeaders = false;
3064 resetDefaultHeaders:function() {
3065 delete this.defaultHeaders;
3066 this.defaultHeaders = {};
3067 this.hasDefaultHeaders = false;
3070 abort:function(o, callback, isTimeout)
3072 if(this.isCallInProgress(o)) {
3074 window.clearInterval(this.poll[o.tId]);
3075 delete this.poll[o.tId];
3077 delete this.timeout[o.tId];
3080 this.handleTransactionResponse(o, callback, true);
3090 isCallInProgress:function(o)
3093 return o.conn.readyState != 4 && o.conn.readyState != 0;
3102 releaseObject:function(o)
3111 'MSXML2.XMLHTTP.3.0',
3119 * Portions of this file are based on pieces of Yahoo User Interface Library
3120 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3121 * YUI licensed under the BSD License:
3122 * http://developer.yahoo.net/yui/license.txt
3123 * <script type="text/javascript">
3127 Roo.lib.Region = function(t, r, b, l) {
3137 Roo.lib.Region.prototype = {
3138 contains : function(region) {
3139 return ( region.left >= this.left &&
3140 region.right <= this.right &&
3141 region.top >= this.top &&
3142 region.bottom <= this.bottom );
3146 getArea : function() {
3147 return ( (this.bottom - this.top) * (this.right - this.left) );
3150 intersect : function(region) {
3151 var t = Math.max(this.top, region.top);
3152 var r = Math.min(this.right, region.right);
3153 var b = Math.min(this.bottom, region.bottom);
3154 var l = Math.max(this.left, region.left);
3156 if (b >= t && r >= l) {
3157 return new Roo.lib.Region(t, r, b, l);
3162 union : function(region) {
3163 var t = Math.min(this.top, region.top);
3164 var r = Math.max(this.right, region.right);
3165 var b = Math.max(this.bottom, region.bottom);
3166 var l = Math.min(this.left, region.left);
3168 return new Roo.lib.Region(t, r, b, l);
3171 adjust : function(t, l, b, r) {
3180 Roo.lib.Region.getRegion = function(el) {
3181 var p = Roo.lib.Dom.getXY(el);
3184 var r = p[0] + el.offsetWidth;
3185 var b = p[1] + el.offsetHeight;
3188 return new Roo.lib.Region(t, r, b, l);
3191 * Portions of this file are based on pieces of Yahoo User Interface Library
3192 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3193 * YUI licensed under the BSD License:
3194 * http://developer.yahoo.net/yui/license.txt
3195 * <script type="text/javascript">
3198 //@@dep Roo.lib.Region
3201 Roo.lib.Point = function(x, y) {
3202 if (x instanceof Array) {
3206 this.x = this.right = this.left = this[0] = x;
3207 this.y = this.top = this.bottom = this[1] = y;
3210 Roo.lib.Point.prototype = new Roo.lib.Region();
3212 * Portions of this file are based on pieces of Yahoo User Interface Library
3213 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3214 * YUI licensed under the BSD License:
3215 * http://developer.yahoo.net/yui/license.txt
3216 * <script type="text/javascript">
3223 scroll : function(el, args, duration, easing, cb, scope) {
3224 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3227 motion : function(el, args, duration, easing, cb, scope) {
3228 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3231 color : function(el, args, duration, easing, cb, scope) {
3232 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3235 run : function(el, args, duration, easing, cb, scope, type) {
3236 type = type || Roo.lib.AnimBase;
3237 if (typeof easing == "string") {
3238 easing = Roo.lib.Easing[easing];
3240 var anim = new type(el, args, duration, easing);
3241 anim.animateX(function() {
3242 Roo.callback(cb, scope);
3248 * Portions of this file are based on pieces of Yahoo User Interface Library
3249 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3250 * YUI licensed under the BSD License:
3251 * http://developer.yahoo.net/yui/license.txt
3252 * <script type="text/javascript">
3260 if (!libFlyweight) {
3261 libFlyweight = new Roo.Element.Flyweight();
3263 libFlyweight.dom = el;
3264 return libFlyweight;
3267 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3271 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3273 this.init(el, attributes, duration, method);
3277 Roo.lib.AnimBase.fly = fly;
3281 Roo.lib.AnimBase.prototype = {
3283 toString: function() {
3284 var el = this.getEl();
3285 var id = el.id || el.tagName;
3286 return ("Anim " + id);
3290 noNegatives: /width|height|opacity|padding/i,
3291 offsetAttribute: /^((width|height)|(top|left))$/,
3292 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3293 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3297 doMethod: function(attr, start, end) {
3298 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3302 setAttribute: function(attr, val, unit) {
3303 if (this.patterns.noNegatives.test(attr)) {
3304 val = (val > 0) ? val : 0;
3307 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3311 getAttribute: function(attr) {
3312 var el = this.getEl();
3313 var val = fly(el).getStyle(attr);
3315 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3316 return parseFloat(val);
3319 var a = this.patterns.offsetAttribute.exec(attr) || [];
3320 var pos = !!( a[3] );
3321 var box = !!( a[2] );
3324 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3325 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3334 getDefaultUnit: function(attr) {
3335 if (this.patterns.defaultUnit.test(attr)) {
3342 animateX : function(callback, scope) {
3343 var f = function() {
3344 this.onComplete.removeListener(f);
3345 if (typeof callback == "function") {
3346 callback.call(scope || this, this);
3349 this.onComplete.addListener(f, this);
3354 setRuntimeAttribute: function(attr) {
3357 var attributes = this.attributes;
3359 this.runtimeAttributes[attr] = {};
3361 var isset = function(prop) {
3362 return (typeof prop !== 'undefined');
3365 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3369 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3372 if (isset(attributes[attr]['to'])) {
3373 end = attributes[attr]['to'];
3374 } else if (isset(attributes[attr]['by'])) {
3375 if (start.constructor == Array) {
3377 for (var i = 0, len = start.length; i < len; ++i) {
3378 end[i] = start[i] + attributes[attr]['by'][i];
3381 end = start + attributes[attr]['by'];
3385 this.runtimeAttributes[attr].start = start;
3386 this.runtimeAttributes[attr].end = end;
3389 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3393 init: function(el, attributes, duration, method) {
3395 var isAnimated = false;
3398 var startTime = null;
3401 var actualFrames = 0;
3404 el = Roo.getDom(el);
3407 this.attributes = attributes || {};
3410 this.duration = duration || 1;
3413 this.method = method || Roo.lib.Easing.easeNone;
3416 this.useSeconds = true;
3419 this.currentFrame = 0;
3422 this.totalFrames = Roo.lib.AnimMgr.fps;
3425 this.getEl = function() {
3430 this.isAnimated = function() {
3435 this.getStartTime = function() {
3439 this.runtimeAttributes = {};
3442 this.animate = function() {
3443 if (this.isAnimated()) {
3447 this.currentFrame = 0;
3449 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3451 Roo.lib.AnimMgr.registerElement(this);
3455 this.stop = function(finish) {
3457 this.currentFrame = this.totalFrames;
3458 this._onTween.fire();
3460 Roo.lib.AnimMgr.stop(this);
3463 var onStart = function() {
3464 this.onStart.fire();
3466 this.runtimeAttributes = {};
3467 for (var attr in this.attributes) {
3468 this.setRuntimeAttribute(attr);
3473 startTime = new Date();
3477 var onTween = function() {
3479 duration: new Date() - this.getStartTime(),
3480 currentFrame: this.currentFrame
3483 data.toString = function() {
3485 'duration: ' + data.duration +
3486 ', currentFrame: ' + data.currentFrame
3490 this.onTween.fire(data);
3492 var runtimeAttributes = this.runtimeAttributes;
3494 for (var attr in runtimeAttributes) {
3495 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3501 var onComplete = function() {
3502 var actual_duration = (new Date() - startTime) / 1000 ;
3505 duration: actual_duration,
3506 frames: actualFrames,
3507 fps: actualFrames / actual_duration
3510 data.toString = function() {
3512 'duration: ' + data.duration +
3513 ', frames: ' + data.frames +
3514 ', fps: ' + data.fps
3520 this.onComplete.fire(data);
3524 this._onStart = new Roo.util.Event(this);
3525 this.onStart = new Roo.util.Event(this);
3526 this.onTween = new Roo.util.Event(this);
3527 this._onTween = new Roo.util.Event(this);
3528 this.onComplete = new Roo.util.Event(this);
3529 this._onComplete = new Roo.util.Event(this);
3530 this._onStart.addListener(onStart);
3531 this._onTween.addListener(onTween);
3532 this._onComplete.addListener(onComplete);
3537 * Portions of this file are based on pieces of Yahoo User Interface Library
3538 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3539 * YUI licensed under the BSD License:
3540 * http://developer.yahoo.net/yui/license.txt
3541 * <script type="text/javascript">
3545 Roo.lib.AnimMgr = new function() {
3562 this.registerElement = function(tween) {
3563 queue[queue.length] = tween;
3565 tween._onStart.fire();
3570 this.unRegister = function(tween, index) {
3571 tween._onComplete.fire();
3572 index = index || getIndex(tween);
3574 queue.splice(index, 1);
3578 if (tweenCount <= 0) {
3584 this.start = function() {
3585 if (thread === null) {
3586 thread = setInterval(this.run, this.delay);
3591 this.stop = function(tween) {
3593 clearInterval(thread);
3595 for (var i = 0, len = queue.length; i < len; ++i) {
3596 if (queue[0].isAnimated()) {
3597 this.unRegister(queue[0], 0);
3606 this.unRegister(tween);
3611 this.run = function() {
3612 for (var i = 0, len = queue.length; i < len; ++i) {
3613 var tween = queue[i];
3614 if (!tween || !tween.isAnimated()) {
3618 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3620 tween.currentFrame += 1;
3622 if (tween.useSeconds) {
3623 correctFrame(tween);
3625 tween._onTween.fire();
3628 Roo.lib.AnimMgr.stop(tween, i);
3633 var getIndex = function(anim) {
3634 for (var i = 0, len = queue.length; i < len; ++i) {
3635 if (queue[i] == anim) {
3643 var correctFrame = function(tween) {
3644 var frames = tween.totalFrames;
3645 var frame = tween.currentFrame;
3646 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3647 var elapsed = (new Date() - tween.getStartTime());
3650 if (elapsed < tween.duration * 1000) {
3651 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3653 tweak = frames - (frame + 1);
3655 if (tweak > 0 && isFinite(tweak)) {
3656 if (tween.currentFrame + tweak >= frames) {
3657 tweak = frames - (frame + 1);
3660 tween.currentFrame += tweak;
3666 * Portions of this file are based on pieces of Yahoo User Interface Library
3667 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3668 * YUI licensed under the BSD License:
3669 * http://developer.yahoo.net/yui/license.txt
3670 * <script type="text/javascript">
3673 Roo.lib.Bezier = new function() {
3675 this.getPosition = function(points, t) {
3676 var n = points.length;
3679 for (var i = 0; i < n; ++i) {
3680 tmp[i] = [points[i][0], points[i][1]];
3683 for (var j = 1; j < n; ++j) {
3684 for (i = 0; i < n - j; ++i) {
3685 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3686 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3690 return [ tmp[0][0], tmp[0][1] ];
3696 * @class Roo.lib.Color
3698 * An abstract Color implementation. Concrete Color implementations should use
3699 * an instance of this function as their prototype, and implement the getRGB and
3700 * getHSL functions. getRGB should return an object representing the RGB
3701 * components of this Color, with the red, green, and blue components in the
3702 * range [0,255] and the alpha component in the range [0,100]. getHSL should
3703 * return an object representing the HSL components of this Color, with the hue
3704 * component in the range [0,360), the saturation and lightness components in
3705 * the range [0,100], and the alpha component in the range [0,1].
3710 * Functions for Color handling and processing.
3712 * http://www.safalra.com/web-design/javascript/Color-handling-and-processing/
3714 * The author of this program, Safalra (Stephen Morley), irrevocably releases all
3715 * rights to this program, with the intention of it becoming part of the public
3716 * domain. Because this program is released into the public domain, it comes with
3717 * no warranty either expressed or implied, to the extent permitted by law.
3719 * For more free and public domain JavaScript code by the same author, visit:
3720 * http://www.safalra.com/web-design/javascript/
3723 Roo.lib.Color = function() { }
3726 Roo.apply(Roo.lib.Color.prototype, {
3734 * @return {Object} an object representing the RGBA components of this Color. The red,
3735 * green, and blue components are converted to integers in the range [0,255].
3736 * The alpha is a value in the range [0,1].
3738 getIntegerRGB : function(){
3740 // get the RGB components of this Color
3741 var rgb = this.getRGB();
3743 // return the integer components
3745 'r' : Math.round(rgb.r),
3746 'g' : Math.round(rgb.g),
3747 'b' : Math.round(rgb.b),
3755 * @return {Object} an object representing the RGBA components of this Color. The red,
3756 * green, and blue components are converted to numbers in the range [0,100].
3757 * The alpha is a value in the range [0,1].
3759 getPercentageRGB : function(){
3761 // get the RGB components of this Color
3762 var rgb = this.getRGB();
3764 // return the percentage components
3766 'r' : 100 * rgb.r / 255,
3767 'g' : 100 * rgb.g / 255,
3768 'b' : 100 * rgb.b / 255,
3775 * getCSSHexadecimalRGB
3776 * @return {String} a string representing this Color as a CSS hexadecimal RGB Color
3777 * value - that is, a string of the form #RRGGBB where each of RR, GG, and BB
3778 * are two-digit hexadecimal numbers.
3780 getCSSHexadecimalRGB : function()
3783 // get the integer RGB components
3784 var rgb = this.getIntegerRGB();
3786 // determine the hexadecimal equivalents
3787 var r16 = rgb.r.toString(16);
3788 var g16 = rgb.g.toString(16);
3789 var b16 = rgb.b.toString(16);
3791 // return the CSS RGB Color value
3793 + (r16.length == 2 ? r16 : '0' + r16)
3794 + (g16.length == 2 ? g16 : '0' + g16)
3795 + (b16.length == 2 ? b16 : '0' + b16);
3801 * @return {String} a string representing this Color as a CSS integer RGB Color
3802 * value - that is, a string of the form rgb(r,g,b) where each of r, g, and b
3803 * are integers in the range [0,255].
3805 getCSSIntegerRGB : function(){
3807 // get the integer RGB components
3808 var rgb = this.getIntegerRGB();
3810 // return the CSS RGB Color value
3811 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
3817 * @return {String} Returns a string representing this Color as a CSS integer RGBA Color
3818 * value - that is, a string of the form rgba(r,g,b,a) where each of r, g, and
3819 * b are integers in the range [0,255] and a is in the range [0,1].
3821 getCSSIntegerRGBA : function(){
3823 // get the integer RGB components
3824 var rgb = this.getIntegerRGB();
3826 // return the CSS integer RGBA Color value
3827 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')';
3832 * getCSSPercentageRGB
3833 * @return {String} a string representing this Color as a CSS percentage RGB Color
3834 * value - that is, a string of the form rgb(r%,g%,b%) where each of r, g, and
3835 * b are in the range [0,100].
3837 getCSSPercentageRGB : function(){
3839 // get the percentage RGB components
3840 var rgb = this.getPercentageRGB();
3842 // return the CSS RGB Color value
3843 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%)';
3848 * getCSSPercentageRGBA
3849 * @return {String} a string representing this Color as a CSS percentage RGBA Color
3850 * value - that is, a string of the form rgba(r%,g%,b%,a) where each of r, g,
3851 * and b are in the range [0,100] and a is in the range [0,1].
3853 getCSSPercentageRGBA : function(){
3855 // get the percentage RGB components
3856 var rgb = this.getPercentageRGB();
3858 // return the CSS percentage RGBA Color value
3859 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%,' + rgb.a + ')';
3865 * @return {String} a string representing this Color as a CSS HSL Color value - that
3866 * is, a string of the form hsl(h,s%,l%) where h is in the range [0,100] and
3867 * s and l are in the range [0,100].
3869 getCSSHSL : function(){
3871 // get the HSL components
3872 var hsl = this.getHSL();
3874 // return the CSS HSL Color value
3875 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)';
3881 * @return {String} a string representing this Color as a CSS HSLA Color value - that
3882 * is, a string of the form hsla(h,s%,l%,a) where h is in the range [0,100],
3883 * s and l are in the range [0,100], and a is in the range [0,1].
3885 getCSSHSLA : function(){
3887 // get the HSL components
3888 var hsl = this.getHSL();
3890 // return the CSS HSL Color value
3891 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%,' + hsl.a + ')';
3896 * Sets the Color of the specified node to this Color. This functions sets
3897 * the CSS 'color' property for the node. The parameter is:
3899 * @param {DomElement} node - the node whose Color should be set
3901 setNodeColor : function(node){
3903 // set the Color of the node
3904 node.style.color = this.getCSSHexadecimalRGB();
3909 * Sets the background Color of the specified node to this Color. This
3910 * functions sets the CSS 'background-color' property for the node. The
3913 * @param {DomElement} node - the node whose background Color should be set
3915 setNodeBackgroundColor : function(node){
3917 // set the background Color of the node
3918 node.style.backgroundColor = this.getCSSHexadecimalRGB();
3921 // convert between formats..
3924 var r = this.getIntegerRGB();
3925 return new Roo.lib.RGBColor(r.r,r.g,r.b,r.a);
3930 var hsl = this.getHSL();
3931 // return the CSS HSL Color value
3932 return new Roo.lib.HSLColor(hsl.h, hsl.s, hsl.l , hsl.a );
3938 var rgb = this.toRGB();
3939 var hsv = rgb.getHSV();
3940 // return the CSS HSL Color value
3941 return new Roo.lib.HSVColor(hsv.h, hsv.s, hsv.v , hsv.a );
3945 // modify v = 0 ... 1 (eg. 0.5)
3946 saturate : function(v)
3948 var rgb = this.toRGB();
3949 var hsv = rgb.getHSV();
3950 return new Roo.lib.HSVColor(hsv.h, hsv.s * v, hsv.v , hsv.a );
3958 * @return {Object} the RGB and alpha components of this Color as an object with r,
3959 * g, b, and a properties. r, g, and b are in the range [0,255] and a is in
3964 // return the RGB components
3976 * @return {Object} the HSV and alpha components of this Color as an object with h,
3977 * s, v, and a properties. h is in the range [0,360), s and v are in the range
3978 * [0,100], and a is in the range [0,1].
3983 // calculate the HSV components if necessary
3984 if (this.hsv == null) {
3985 this.calculateHSV();
3988 // return the HSV components
4000 * @return {Object} the HSL and alpha components of this Color as an object with h,
4001 * s, l, and a properties. h is in the range [0,360), s and l are in the range
4002 * [0,100], and a is in the range [0,1].
4004 getHSL : function(){
4007 // calculate the HSV components if necessary
4008 if (this.hsl == null) { this.calculateHSL(); }
4010 // return the HSL components
4025 * @class Roo.lib.RGBColor
4026 * @extends Roo.lib.Color
4027 * Creates a Color specified in the RGB Color space, with an optional alpha
4028 * component. The parameters are:
4032 * @param {Number} r - the red component, clipped to the range [0,255]
4033 * @param {Number} g - the green component, clipped to the range [0,255]
4034 * @param {Number} b - the blue component, clipped to the range [0,255]
4035 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4036 * optional and defaults to 1
4038 Roo.lib.RGBColor = function (r, g, b, a){
4040 // store the alpha component after clipping it if necessary
4041 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4043 // store the RGB components after clipping them if necessary
4046 'r' : Math.max(0, Math.min(255, r)),
4047 'g' : Math.max(0, Math.min(255, g)),
4048 'b' : Math.max(0, Math.min(255, b))
4051 // initialise the HSV and HSL components to null
4055 * //private returns the HSV or HSL hue component of this RGBColor. The hue is in the
4056 * range [0,360). The parameters are:
4058 * maximum - the maximum of the RGB component values
4059 * range - the range of the RGB component values
4064 // this does an 'exteds'
4065 Roo.extend(Roo.lib.RGBColor, Roo.lib.Color, {
4068 getHue : function(maximum, range)
4072 // check whether the range is zero
4075 // set the hue to zero (any hue is acceptable as the Color is grey)
4080 // determine which of the components has the highest value and set the hue
4083 // red has the highest value
4085 var hue = (rgb.g - rgb.b) / range * 60;
4086 if (hue < 0) { hue += 360; }
4089 // green has the highest value
4091 var hue = (rgb.b - rgb.r) / range * 60 + 120;
4094 // blue has the highest value
4096 var hue = (rgb.r - rgb.g) / range * 60 + 240;
4108 /* //private Calculates and stores the HSV components of this RGBColor so that they can
4109 * be returned be the getHSV function.
4111 calculateHSV : 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 // store the HSV components
4120 'h' : this.getHue(maximum, range),
4121 's' : (maximum == 0 ? 0 : 100 * range / maximum),
4122 'v' : maximum / 2.55
4127 /* //private Calculates and stores the HSL components of this RGBColor so that they can
4128 * be returned be the getHSL function.
4130 calculateHSL : function(){
4132 // get the maximum and range of the RGB component values
4133 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4134 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4136 // determine the lightness in the range [0,1]
4137 var l = maximum / 255 - range / 510;
4139 // store the HSL components
4142 'h' : this.getHue(maximum, range),
4143 's' : (range == 0 ? 0 : range / 2.55 / (l < 0.5 ? l * 2 : 2 - l * 2)),
4152 * @class Roo.lib.HSVColor
4153 * @extends Roo.lib.Color
4154 * Creates a Color specified in the HSV Color space, with an optional alpha
4155 * component. The parameters are:
4158 * @param {Number} h - the hue component, wrapped to the range [0,360)
4159 * @param {Number} s - the saturation component, clipped to the range [0,100]
4160 * @param {Number} v - the value component, clipped to the range [0,100]
4161 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4162 * optional and defaults to 1
4164 Roo.lib.HSVColor = function (h, s, v, a){
4166 // store the alpha component after clipping it if necessary
4167 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4169 // store the HSV components after clipping or wrapping them if necessary
4172 'h' : (h % 360 + 360) % 360,
4173 's' : Math.max(0, Math.min(100, s)),
4174 'v' : Math.max(0, Math.min(100, v))
4177 // initialise the RGB and HSL components to null
4182 Roo.extend(Roo.lib.HSVColor, Roo.lib.Color, {
4183 /* Calculates and stores the RGB components of this HSVColor so that they can
4184 * be returned be the getRGB function.
4186 calculateRGB: function ()
4189 // check whether the saturation is zero
4192 // set the Color to the appropriate shade of grey
4199 // set some temporary values
4200 var f = hsv.h / 60 - Math.floor(hsv.h / 60);
4201 var p = hsv.v * (1 - hsv.s / 100);
4202 var q = hsv.v * (1 - hsv.s / 100 * f);
4203 var t = hsv.v * (1 - hsv.s / 100 * (1 - f));
4205 // set the RGB Color components to their temporary values
4206 switch (Math.floor(hsv.h / 60)){
4207 case 0: var r = hsv.v; var g = t; var b = p; break;
4208 case 1: var r = q; var g = hsv.v; var b = p; break;
4209 case 2: var r = p; var g = hsv.v; var b = t; break;
4210 case 3: var r = p; var g = q; var b = hsv.v; break;
4211 case 4: var r = t; var g = p; var b = hsv.v; break;
4212 case 5: var r = hsv.v; var g = p; var b = q; break;
4217 // store the RGB components
4227 /* Calculates and stores the HSL components of this HSVColor so that they can
4228 * be returned be the getHSL function.
4230 calculateHSL : function (){
4233 // determine the lightness in the range [0,100]
4234 var l = (2 - hsv.s / 100) * hsv.v / 2;
4236 // store the HSL components
4240 's' : hsv.s * hsv.v / (l < 50 ? l * 2 : 200 - l * 2),
4244 // correct a division-by-zero error
4245 if (isNaN(hsl.s)) { hsl.s = 0; }
4254 * @class Roo.lib.HSLColor
4255 * @extends Roo.lib.Color
4258 * Creates a Color specified in the HSL Color space, with an optional alpha
4259 * component. The parameters are:
4261 * @param {Number} h - the hue component, wrapped to the range [0,360)
4262 * @param {Number} s - the saturation component, clipped to the range [0,100]
4263 * @param {Number} l - the lightness component, clipped to the range [0,100]
4264 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4265 * optional and defaults to 1
4268 Roo.lib.HSLColor = function(h, s, l, a){
4270 // store the alpha component after clipping it if necessary
4271 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4273 // store the HSL components after clipping or wrapping them if necessary
4276 'h' : (h % 360 + 360) % 360,
4277 's' : Math.max(0, Math.min(100, s)),
4278 'l' : Math.max(0, Math.min(100, l))
4281 // initialise the RGB and HSV components to null
4284 Roo.extend(Roo.lib.HSLColor, Roo.lib.Color, {
4286 /* Calculates and stores the RGB components of this HSLColor so that they can
4287 * be returned be the getRGB function.
4289 calculateRGB: function (){
4291 // check whether the saturation is zero
4292 if (this.hsl.s == 0){
4294 // store the RGB components representing the appropriate shade of grey
4297 'r' : this.hsl.l * 2.55,
4298 'g' : this.hsl.l * 2.55,
4299 'b' : this.hsl.l * 2.55
4304 // set some temporary values
4305 var p = this.hsl.l < 50
4306 ? this.hsl.l * (1 + hsl.s / 100)
4307 : this.hsl.l + hsl.s - hsl.l * hsl.s / 100;
4308 var q = 2 * hsl.l - p;
4310 // initialise the RGB components
4313 'r' : (h + 120) / 60 % 6,
4315 'b' : (h + 240) / 60 % 6
4318 // loop over the RGB components
4319 for (var key in this.rgb){
4321 // ensure that the property is not inherited from the root object
4322 if (this.rgb.hasOwnProperty(key)){
4324 // set the component to its value in the range [0,100]
4325 if (this.rgb[key] < 1){
4326 this.rgb[key] = q + (p - q) * this.rgb[key];
4327 }else if (this.rgb[key] < 3){
4329 }else if (this.rgb[key] < 4){
4330 this.rgb[key] = q + (p - q) * (4 - this.rgb[key]);
4335 // set the component to its value in the range [0,255]
4336 this.rgb[key] *= 2.55;
4346 /* Calculates and stores the HSV components of this HSLColor so that they can
4347 * be returned be the getHSL function.
4349 calculateHSV : function(){
4351 // set a temporary value
4352 var t = this.hsl.s * (this.hsl.l < 50 ? this.hsl.l : 100 - this.hsl.l) / 100;
4354 // store the HSV components
4358 's' : 200 * t / (this.hsl.l + t),
4359 'v' : t + this.hsl.l
4362 // correct a division-by-zero error
4363 if (isNaN(this.hsv.s)) { this.hsv.s = 0; }
4370 * Portions of this file are based on pieces of Yahoo User Interface Library
4371 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4372 * YUI licensed under the BSD License:
4373 * http://developer.yahoo.net/yui/license.txt
4374 * <script type="text/javascript">
4379 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
4380 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
4383 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
4385 var fly = Roo.lib.AnimBase.fly;
4387 var superclass = Y.ColorAnim.superclass;
4388 var proto = Y.ColorAnim.prototype;
4390 proto.toString = function() {
4391 var el = this.getEl();
4392 var id = el.id || el.tagName;
4393 return ("ColorAnim " + id);
4396 proto.patterns.color = /color$/i;
4397 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
4398 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
4399 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
4400 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
4403 proto.parseColor = function(s) {
4404 if (s.length == 3) {
4408 var c = this.patterns.hex.exec(s);
4409 if (c && c.length == 4) {
4410 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
4413 c = this.patterns.rgb.exec(s);
4414 if (c && c.length == 4) {
4415 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
4418 c = this.patterns.hex3.exec(s);
4419 if (c && c.length == 4) {
4420 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
4425 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
4426 proto.getAttribute = function(attr) {
4427 var el = this.getEl();
4428 if (this.patterns.color.test(attr)) {
4429 var val = fly(el).getStyle(attr);
4431 if (this.patterns.transparent.test(val)) {
4432 var parent = el.parentNode;
4433 val = fly(parent).getStyle(attr);
4435 while (parent && this.patterns.transparent.test(val)) {
4436 parent = parent.parentNode;
4437 val = fly(parent).getStyle(attr);
4438 if (parent.tagName.toUpperCase() == 'HTML') {
4444 val = superclass.getAttribute.call(this, attr);
4449 proto.getAttribute = function(attr) {
4450 var el = this.getEl();
4451 if (this.patterns.color.test(attr)) {
4452 var val = fly(el).getStyle(attr);
4454 if (this.patterns.transparent.test(val)) {
4455 var parent = el.parentNode;
4456 val = fly(parent).getStyle(attr);
4458 while (parent && this.patterns.transparent.test(val)) {
4459 parent = parent.parentNode;
4460 val = fly(parent).getStyle(attr);
4461 if (parent.tagName.toUpperCase() == 'HTML') {
4467 val = superclass.getAttribute.call(this, attr);
4473 proto.doMethod = function(attr, start, end) {
4476 if (this.patterns.color.test(attr)) {
4478 for (var i = 0, len = start.length; i < len; ++i) {
4479 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
4482 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
4485 val = superclass.doMethod.call(this, attr, start, end);
4491 proto.setRuntimeAttribute = function(attr) {
4492 superclass.setRuntimeAttribute.call(this, attr);
4494 if (this.patterns.color.test(attr)) {
4495 var attributes = this.attributes;
4496 var start = this.parseColor(this.runtimeAttributes[attr].start);
4497 var end = this.parseColor(this.runtimeAttributes[attr].end);
4499 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
4500 end = this.parseColor(attributes[attr].by);
4502 for (var i = 0, len = start.length; i < len; ++i) {
4503 end[i] = start[i] + end[i];
4507 this.runtimeAttributes[attr].start = start;
4508 this.runtimeAttributes[attr].end = end;
4514 * Portions of this file are based on pieces of Yahoo User Interface Library
4515 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4516 * YUI licensed under the BSD License:
4517 * http://developer.yahoo.net/yui/license.txt
4518 * <script type="text/javascript">
4524 easeNone: function (t, b, c, d) {
4525 return c * t / d + b;
4529 easeIn: function (t, b, c, d) {
4530 return c * (t /= d) * t + b;
4534 easeOut: function (t, b, c, d) {
4535 return -c * (t /= d) * (t - 2) + b;
4539 easeBoth: function (t, b, c, d) {
4540 if ((t /= d / 2) < 1) {
4541 return c / 2 * t * t + b;
4544 return -c / 2 * ((--t) * (t - 2) - 1) + b;
4548 easeInStrong: function (t, b, c, d) {
4549 return c * (t /= d) * t * t * t + b;
4553 easeOutStrong: function (t, b, c, d) {
4554 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
4558 easeBothStrong: function (t, b, c, d) {
4559 if ((t /= d / 2) < 1) {
4560 return c / 2 * t * t * t * t + b;
4563 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
4568 elasticIn: function (t, b, c, d, a, p) {
4572 if ((t /= d) == 1) {
4579 if (!a || a < Math.abs(c)) {
4584 var s = p / (2 * Math.PI) * Math.asin(c / a);
4587 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4591 elasticOut: function (t, b, c, d, a, p) {
4595 if ((t /= d) == 1) {
4602 if (!a || a < Math.abs(c)) {
4607 var s = p / (2 * Math.PI) * Math.asin(c / a);
4610 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
4614 elasticBoth: function (t, b, c, d, a, p) {
4619 if ((t /= d / 2) == 2) {
4627 if (!a || a < Math.abs(c)) {
4632 var s = p / (2 * Math.PI) * Math.asin(c / a);
4636 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
4637 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4639 return a * Math.pow(2, -10 * (t -= 1)) *
4640 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
4645 backIn: function (t, b, c, d, s) {
4646 if (typeof s == 'undefined') {
4649 return c * (t /= d) * t * ((s + 1) * t - s) + b;
4653 backOut: function (t, b, c, d, s) {
4654 if (typeof s == 'undefined') {
4657 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
4661 backBoth: function (t, b, c, d, s) {
4662 if (typeof s == 'undefined') {
4666 if ((t /= d / 2 ) < 1) {
4667 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
4669 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
4673 bounceIn: function (t, b, c, d) {
4674 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
4678 bounceOut: function (t, b, c, d) {
4679 if ((t /= d) < (1 / 2.75)) {
4680 return c * (7.5625 * t * t) + b;
4681 } else if (t < (2 / 2.75)) {
4682 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
4683 } else if (t < (2.5 / 2.75)) {
4684 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
4686 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
4690 bounceBoth: function (t, b, c, d) {
4692 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
4694 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
4697 * Portions of this file are based on pieces of Yahoo User Interface Library
4698 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4699 * YUI licensed under the BSD License:
4700 * http://developer.yahoo.net/yui/license.txt
4701 * <script type="text/javascript">
4705 Roo.lib.Motion = function(el, attributes, duration, method) {
4707 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
4711 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
4715 var superclass = Y.Motion.superclass;
4716 var proto = Y.Motion.prototype;
4718 proto.toString = function() {
4719 var el = this.getEl();
4720 var id = el.id || el.tagName;
4721 return ("Motion " + id);
4724 proto.patterns.points = /^points$/i;
4726 proto.setAttribute = function(attr, val, unit) {
4727 if (this.patterns.points.test(attr)) {
4728 unit = unit || 'px';
4729 superclass.setAttribute.call(this, 'left', val[0], unit);
4730 superclass.setAttribute.call(this, 'top', val[1], unit);
4732 superclass.setAttribute.call(this, attr, val, unit);
4736 proto.getAttribute = function(attr) {
4737 if (this.patterns.points.test(attr)) {
4739 superclass.getAttribute.call(this, 'left'),
4740 superclass.getAttribute.call(this, 'top')
4743 val = superclass.getAttribute.call(this, attr);
4749 proto.doMethod = function(attr, start, end) {
4752 if (this.patterns.points.test(attr)) {
4753 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
4754 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
4756 val = superclass.doMethod.call(this, attr, start, end);
4761 proto.setRuntimeAttribute = function(attr) {
4762 if (this.patterns.points.test(attr)) {
4763 var el = this.getEl();
4764 var attributes = this.attributes;
4766 var control = attributes['points']['control'] || [];
4770 if (control.length > 0 && !(control[0] instanceof Array)) {
4771 control = [control];
4774 for (i = 0,len = control.length; i < len; ++i) {
4775 tmp[i] = control[i];
4780 Roo.fly(el).position();
4782 if (isset(attributes['points']['from'])) {
4783 Roo.lib.Dom.setXY(el, attributes['points']['from']);
4786 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
4789 start = this.getAttribute('points');
4792 if (isset(attributes['points']['to'])) {
4793 end = translateValues.call(this, attributes['points']['to'], start);
4795 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4796 for (i = 0,len = control.length; i < len; ++i) {
4797 control[i] = translateValues.call(this, control[i], start);
4801 } else if (isset(attributes['points']['by'])) {
4802 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
4804 for (i = 0,len = control.length; i < len; ++i) {
4805 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4809 this.runtimeAttributes[attr] = [start];
4811 if (control.length > 0) {
4812 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4815 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4818 superclass.setRuntimeAttribute.call(this, attr);
4822 var translateValues = function(val, start) {
4823 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4824 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4829 var isset = function(prop) {
4830 return (typeof prop !== 'undefined');
4834 * Portions of this file are based on pieces of Yahoo User Interface Library
4835 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4836 * YUI licensed under the BSD License:
4837 * http://developer.yahoo.net/yui/license.txt
4838 * <script type="text/javascript">
4842 Roo.lib.Scroll = function(el, attributes, duration, method) {
4844 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4848 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4852 var superclass = Y.Scroll.superclass;
4853 var proto = Y.Scroll.prototype;
4855 proto.toString = function() {
4856 var el = this.getEl();
4857 var id = el.id || el.tagName;
4858 return ("Scroll " + id);
4861 proto.doMethod = function(attr, start, end) {
4864 if (attr == 'scroll') {
4866 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4867 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4871 val = superclass.doMethod.call(this, attr, start, end);
4876 proto.getAttribute = function(attr) {
4878 var el = this.getEl();
4880 if (attr == 'scroll') {
4881 val = [ el.scrollLeft, el.scrollTop ];
4883 val = superclass.getAttribute.call(this, attr);
4889 proto.setAttribute = function(attr, val, unit) {
4890 var el = this.getEl();
4892 if (attr == 'scroll') {
4893 el.scrollLeft = val[0];
4894 el.scrollTop = val[1];
4896 superclass.setAttribute.call(this, attr, val, unit);
4902 * Ext JS Library 1.1.1
4903 * Copyright(c) 2006-2007, Ext JS, LLC.
4905 * Originally Released Under LGPL - original licence link has changed is not relivant.
4908 * <script type="text/javascript">
4912 // nasty IE9 hack - what a pile of crap that is..
4914 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4915 Range.prototype.createContextualFragment = function (html) {
4916 var doc = window.document;
4917 var container = doc.createElement("div");
4918 container.innerHTML = html;
4919 var frag = doc.createDocumentFragment(), n;
4920 while ((n = container.firstChild)) {
4921 frag.appendChild(n);
4928 * @class Roo.DomHelper
4929 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4930 * 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>.
4933 Roo.DomHelper = function(){
4934 var tempTableEl = null;
4935 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4936 var tableRe = /^table|tbody|tr|td$/i;
4938 // build as innerHTML where available
4940 var createHtml = function(o){
4941 if(typeof o == 'string'){
4950 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") { continue; }
4951 if(attr == "style"){
4953 if(typeof s == "function"){
4956 if(typeof s == "string"){
4957 b += ' style="' + s + '"';
4958 }else if(typeof s == "object"){
4961 if(typeof s[key] != "function"){
4962 b += key + ":" + s[key] + ";";
4969 b += ' class="' + o["cls"] + '"';
4970 }else if(attr == "htmlFor"){
4971 b += ' for="' + o["htmlFor"] + '"';
4973 b += " " + attr + '="' + o[attr] + '"';
4977 if(emptyTags.test(o.tag)){
4981 var cn = o.children || o.cn;
4983 //http://bugs.kde.org/show_bug.cgi?id=71506
4984 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4985 for(var i = 0, len = cn.length; i < len; i++) {
4986 b += createHtml(cn[i], b);
4989 b += createHtml(cn, b);
4995 b += "</" + o.tag + ">";
5002 var createDom = function(o, parentNode){
5004 // defininition craeted..
5006 if (o.ns && o.ns != 'html') {
5008 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
5009 xmlns[o.ns] = o.xmlns;
5012 if (typeof(xmlns[o.ns]) == 'undefined') {
5013 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
5019 if (typeof(o) == 'string') {
5020 return parentNode.appendChild(document.createTextNode(o));
5022 o.tag = o.tag || div;
5023 if (o.ns && Roo.isIE) {
5025 o.tag = o.ns + ':' + o.tag;
5028 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
5029 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
5032 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
5033 attr == "style" || typeof o[attr] == "function") { continue; }
5035 if(attr=="cls" && Roo.isIE){
5036 el.className = o["cls"];
5038 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
5044 Roo.DomHelper.applyStyles(el, o.style);
5045 var cn = o.children || o.cn;
5047 //http://bugs.kde.org/show_bug.cgi?id=71506
5048 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5049 for(var i = 0, len = cn.length; i < len; i++) {
5050 createDom(cn[i], el);
5057 el.innerHTML = o.html;
5060 parentNode.appendChild(el);
5065 var ieTable = function(depth, s, h, e){
5066 tempTableEl.innerHTML = [s, h, e].join('');
5067 var i = -1, el = tempTableEl;
5068 while(++i < depth && el.firstChild){
5074 // kill repeat to save bytes
5078 tbe = '</tbody>'+te,
5084 * Nasty code for IE's broken table implementation
5086 var insertIntoTable = function(tag, where, el, html){
5088 tempTableEl = document.createElement('div');
5093 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
5096 if(where == 'beforebegin'){
5100 before = el.nextSibling;
5103 node = ieTable(4, trs, html, tre);
5105 else if(tag == 'tr'){
5106 if(where == 'beforebegin'){
5109 node = ieTable(3, tbs, html, tbe);
5110 } else if(where == 'afterend'){
5111 before = el.nextSibling;
5113 node = ieTable(3, tbs, html, tbe);
5114 } else{ // INTO a TR
5115 if(where == 'afterbegin'){
5116 before = el.firstChild;
5118 node = ieTable(4, trs, html, tre);
5120 } else if(tag == 'tbody'){
5121 if(where == 'beforebegin'){
5124 node = ieTable(2, ts, html, te);
5125 } else if(where == 'afterend'){
5126 before = el.nextSibling;
5128 node = ieTable(2, ts, html, te);
5130 if(where == 'afterbegin'){
5131 before = el.firstChild;
5133 node = ieTable(3, tbs, html, tbe);
5136 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
5139 if(where == 'afterbegin'){
5140 before = el.firstChild;
5142 node = ieTable(2, ts, html, te);
5144 el.insertBefore(node, before);
5148 // this is a bit like the react update code...
5151 var updateNode = function(from, to)
5153 // should we handle non-standard elements?
5155 if (from.nodeType != to.nodeType) {
5156 from.parentNode.replaceChild(to, from);
5159 if (from.nodeType == 3) {
5160 // assume it's text?!
5161 if (from.data == to.data) {
5164 from.data = to.data;
5168 // assume 'to' doesnt have '1/3 nodetypes!
5169 if (from.nodeType !=1 || from.tagName != to.tagName) {
5170 from.parentNode.replaceChild(to, from);
5173 // compare attributes
5174 var ar = Array.from(from.attributes);
5175 for(var i = 0; i< ar.length;i++) {
5176 if (to.hasAttribute(ar[i].name)) {
5179 from.removeAttribute(ar[i].name);
5182 for(var i = 0; i< ar.length;i++) {
5183 if (from.getAttribute(ar[i].name) == to.getAttribute(ar[i].name)) {
5186 from.setAttribute(ar[i].name, to.getAttribute(ar[i].name));
5189 var far = Array.from(from.childNodes);
5190 var tar = Array.from(to.childNodes);
5191 // if the lengths are different.. then it's probably a editable content change, rather than
5192 // a change of the block definition..
5193 if (from.innerHTML == to.innerHTML) {
5196 if (far.length != tar.length) {
5197 from.innerHTML = to.innerHTML;
5201 for(var i = 0; i < far.length; i++) {
5202 updateNode(far[i], tar[i]);
5211 /** True to force the use of DOM instead of html fragments @type Boolean */
5215 * Returns the markup for the passed Element(s) config
5216 * @param {Object} o The Dom object spec (and children)
5219 markup : function(o){
5220 return createHtml(o);
5224 * Applies a style specification to an element
5225 * @param {String/HTMLElement} el The element to apply styles to
5226 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
5227 * a function which returns such a specification.
5229 applyStyles : function(el, styles){
5232 if(typeof styles == "string"){
5233 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
5235 while ((matches = re.exec(styles)) != null){
5236 el.setStyle(matches[1], matches[2]);
5238 }else if (typeof styles == "object"){
5239 for (var style in styles){
5240 el.setStyle(style, styles[style]);
5242 }else if (typeof styles == "function"){
5243 Roo.DomHelper.applyStyles(el, styles.call());
5249 * Inserts an HTML fragment into the Dom
5250 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
5251 * @param {HTMLElement} el The context element
5252 * @param {String} html The HTML fragmenet
5253 * @return {HTMLElement} The new node
5255 insertHtml : function(where, el, html){
5256 where = where.toLowerCase();
5257 if(el.insertAdjacentHTML){
5258 if(tableRe.test(el.tagName)){
5260 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
5266 el.insertAdjacentHTML('BeforeBegin', html);
5267 return el.previousSibling;
5269 el.insertAdjacentHTML('AfterBegin', html);
5270 return el.firstChild;
5272 el.insertAdjacentHTML('BeforeEnd', html);
5273 return el.lastChild;
5275 el.insertAdjacentHTML('AfterEnd', html);
5276 return el.nextSibling;
5278 throw 'Illegal insertion point -> "' + where + '"';
5280 var range = el.ownerDocument.createRange();
5284 range.setStartBefore(el);
5285 frag = range.createContextualFragment(html);
5286 el.parentNode.insertBefore(frag, el);
5287 return el.previousSibling;
5290 range.setStartBefore(el.firstChild);
5291 frag = range.createContextualFragment(html);
5292 el.insertBefore(frag, el.firstChild);
5293 return el.firstChild;
5295 el.innerHTML = html;
5296 return el.firstChild;
5300 range.setStartAfter(el.lastChild);
5301 frag = range.createContextualFragment(html);
5302 el.appendChild(frag);
5303 return el.lastChild;
5305 el.innerHTML = html;
5306 return el.lastChild;
5309 range.setStartAfter(el);
5310 frag = range.createContextualFragment(html);
5311 el.parentNode.insertBefore(frag, el.nextSibling);
5312 return el.nextSibling;
5314 throw 'Illegal insertion point -> "' + where + '"';
5318 * Creates new Dom element(s) and inserts them before el
5319 * @param {String/HTMLElement/Element} el The context element
5320 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5321 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5322 * @return {HTMLElement/Roo.Element} The new node
5324 insertBefore : function(el, o, returnElement){
5325 return this.doInsert(el, o, returnElement, "beforeBegin");
5329 * Creates new Dom element(s) and inserts them after el
5330 * @param {String/HTMLElement/Element} el The context element
5331 * @param {Object} o The Dom object spec (and children)
5332 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5333 * @return {HTMLElement/Roo.Element} The new node
5335 insertAfter : function(el, o, returnElement){
5336 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
5340 * Creates new Dom element(s) and inserts them as the first child of el
5341 * @param {String/HTMLElement/Element} el The context element
5342 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5343 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5344 * @return {HTMLElement/Roo.Element} The new node
5346 insertFirst : function(el, o, returnElement){
5347 return this.doInsert(el, o, returnElement, "afterBegin");
5351 doInsert : function(el, o, returnElement, pos, sibling){
5352 el = Roo.getDom(el);
5354 if(this.useDom || o.ns){
5355 newNode = createDom(o, null);
5356 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
5358 var html = createHtml(o);
5359 newNode = this.insertHtml(pos, el, html);
5361 return returnElement ? Roo.get(newNode, true) : newNode;
5365 * Creates new Dom element(s) and appends them to el
5366 * @param {String/HTMLElement/Element} el The context element
5367 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5368 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5369 * @return {HTMLElement/Roo.Element} The new node
5371 append : function(el, o, returnElement){
5372 el = Roo.getDom(el);
5374 if(this.useDom || o.ns){
5375 newNode = createDom(o, null);
5376 el.appendChild(newNode);
5378 var html = createHtml(o);
5379 newNode = this.insertHtml("beforeEnd", el, html);
5381 return returnElement ? Roo.get(newNode, true) : newNode;
5385 * Creates new Dom element(s) and overwrites the contents of el with them
5386 * @param {String/HTMLElement/Element} el The context element
5387 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5388 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5389 * @return {HTMLElement/Roo.Element} The new node
5391 overwrite : function(el, o, returnElement)
5393 el = Roo.getDom(el);
5396 while (el.childNodes.length) {
5397 el.removeChild(el.firstChild);
5401 el.innerHTML = createHtml(o);
5404 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5408 * Creates a new Roo.DomHelper.Template from the Dom object spec
5409 * @param {Object} o The Dom object spec (and children)
5410 * @return {Roo.DomHelper.Template} The new template
5412 createTemplate : function(o){
5413 var html = createHtml(o);
5414 return new Roo.Template(html);
5417 * Updates the first element with the spec from the o (replacing if necessary)
5418 * This iterates through the children, and updates attributes / children etc..
5419 * @param {String/HTMLElement/Element} el The context element
5420 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5423 update : function(el, o)
5425 updateNode(Roo.getDom(el), createDom(o));
5434 * Ext JS Library 1.1.1
5435 * Copyright(c) 2006-2007, Ext JS, LLC.
5437 * Originally Released Under LGPL - original licence link has changed is not relivant.
5440 * <script type="text/javascript">
5444 * @class Roo.Template
5445 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
5446 * For a list of available format functions, see {@link Roo.util.Format}.<br />
5449 var t = new Roo.Template({
5450 html : '<div name="{id}">' +
5451 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
5453 myformat: function (value, allValues) {
5454 return 'XX' + value;
5457 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
5459 * For more information see this blog post with examples:
5460 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
5461 - Create Elements using DOM, HTML fragments and Templates</a>.
5463 * @param {Object} cfg - Configuration object.
5465 Roo.Template = function(cfg){
5467 if(cfg instanceof Array){
5469 }else if(arguments.length > 1){
5470 cfg = Array.prototype.join.call(arguments, "");
5474 if (typeof(cfg) == 'object') {
5485 Roo.Template.prototype = {
5488 * @cfg {Function} onLoad Called after the template has been loaded and complied (usually from a remove source)
5494 * @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..
5495 * it should be fixed so that template is observable...
5499 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
5507 * Returns an HTML fragment of this template with the specified values applied.
5508 * @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'})
5509 * @return {String} The HTML fragment
5514 applyTemplate : function(values){
5515 //Roo.log(["applyTemplate", values]);
5519 return this.compiled(values);
5521 var useF = this.disableFormats !== true;
5522 var fm = Roo.util.Format, tpl = this;
5523 var fn = function(m, name, format, args){
5525 if(format.substr(0, 5) == "this."){
5526 return tpl.call(format.substr(5), values[name], values);
5529 // quoted values are required for strings in compiled templates,
5530 // but for non compiled we need to strip them
5531 // quoted reversed for jsmin
5532 var re = /^\s*['"](.*)["']\s*$/;
5533 args = args.split(',');
5534 for(var i = 0, len = args.length; i < len; i++){
5535 args[i] = args[i].replace(re, "$1");
5537 args = [values[name]].concat(args);
5539 args = [values[name]];
5541 return fm[format].apply(fm, args);
5544 return values[name] !== undefined ? values[name] : "";
5547 return this.html.replace(this.re, fn);
5565 this.loading = true;
5566 this.compiled = false;
5568 var cx = new Roo.data.Connection();
5572 success : function (response) {
5576 _t.set(response.responseText,true);
5582 failure : function(response) {
5583 Roo.log("Template failed to load from " + _t.url);
5590 * Sets the HTML used as the template and optionally compiles it.
5591 * @param {String} html
5592 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
5593 * @return {Roo.Template} this
5595 set : function(html, compile){
5597 this.compiled = false;
5605 * True to disable format functions (defaults to false)
5608 disableFormats : false,
5611 * The regular expression used to match template variables
5615 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
5618 * Compiles the template into an internal function, eliminating the RegEx overhead.
5619 * @return {Roo.Template} this
5621 compile : function(){
5622 var fm = Roo.util.Format;
5623 var useF = this.disableFormats !== true;
5624 var sep = Roo.isGecko ? "+" : ",";
5625 var fn = function(m, name, format, args){
5627 args = args ? ',' + args : "";
5628 if(format.substr(0, 5) != "this."){
5629 format = "fm." + format + '(';
5631 format = 'this.call("'+ format.substr(5) + '", ';
5635 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
5637 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
5640 // branched to use + in gecko and [].join() in others
5642 body = "this.compiled = function(values){ return '" +
5643 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
5646 body = ["this.compiled = function(values){ return ['"];
5647 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
5648 body.push("'].join('');};");
5649 body = body.join('');
5659 // private function used to call members
5660 call : function(fnName, value, allValues){
5661 return this[fnName](value, allValues);
5665 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
5666 * @param {String/HTMLElement/Roo.Element} el The context element
5667 * @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'})
5668 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5669 * @return {HTMLElement/Roo.Element} The new node or Element
5671 insertFirst: function(el, values, returnElement){
5672 return this.doInsert('afterBegin', el, values, returnElement);
5676 * Applies the supplied values to the template and inserts the new node(s) before el.
5677 * @param {String/HTMLElement/Roo.Element} el The context element
5678 * @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'})
5679 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5680 * @return {HTMLElement/Roo.Element} The new node or Element
5682 insertBefore: function(el, values, returnElement){
5683 return this.doInsert('beforeBegin', el, values, returnElement);
5687 * Applies the supplied values to the template and inserts the new node(s) after el.
5688 * @param {String/HTMLElement/Roo.Element} el The context element
5689 * @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'})
5690 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5691 * @return {HTMLElement/Roo.Element} The new node or Element
5693 insertAfter : function(el, values, returnElement){
5694 return this.doInsert('afterEnd', el, values, returnElement);
5698 * Applies the supplied values to the template and appends the new node(s) to el.
5699 * @param {String/HTMLElement/Roo.Element} el The context element
5700 * @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'})
5701 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5702 * @return {HTMLElement/Roo.Element} The new node or Element
5704 append : function(el, values, returnElement){
5705 return this.doInsert('beforeEnd', el, values, returnElement);
5708 doInsert : function(where, el, values, returnEl){
5709 el = Roo.getDom(el);
5710 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
5711 return returnEl ? Roo.get(newNode, true) : newNode;
5715 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
5716 * @param {String/HTMLElement/Roo.Element} el The context element
5717 * @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'})
5718 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5719 * @return {HTMLElement/Roo.Element} The new node or Element
5721 overwrite : function(el, values, returnElement){
5722 el = Roo.getDom(el);
5723 el.innerHTML = this.applyTemplate(values);
5724 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5728 * Alias for {@link #applyTemplate}
5731 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
5734 Roo.DomHelper.Template = Roo.Template;
5737 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
5738 * @param {String/HTMLElement} el A DOM element or its id
5739 * @returns {Roo.Template} The created template
5742 Roo.Template.from = function(el){
5743 el = Roo.getDom(el);
5744 return new Roo.Template(el.value || el.innerHTML);
5747 * Ext JS Library 1.1.1
5748 * Copyright(c) 2006-2007, Ext JS, LLC.
5750 * Originally Released Under LGPL - original licence link has changed is not relivant.
5753 * <script type="text/javascript">
5758 * This is code is also distributed under MIT license for use
5759 * with jQuery and prototype JavaScript libraries.
5762 * @class Roo.DomQuery
5763 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).
5765 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>
5768 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.
5770 <h4>Element Selectors:</h4>
5772 <li> <b>*</b> any element</li>
5773 <li> <b>E</b> an element with the tag E</li>
5774 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
5775 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
5776 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
5777 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
5779 <h4>Attribute Selectors:</h4>
5780 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
5782 <li> <b>E[foo]</b> has an attribute "foo"</li>
5783 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
5784 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
5785 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
5786 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
5787 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
5788 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
5790 <h4>Pseudo Classes:</h4>
5792 <li> <b>E:first-child</b> E is the first child of its parent</li>
5793 <li> <b>E:last-child</b> E is the last child of its parent</li>
5794 <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>
5795 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
5796 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
5797 <li> <b>E:only-child</b> E is the only child of its parent</li>
5798 <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>
5799 <li> <b>E:first</b> the first E in the resultset</li>
5800 <li> <b>E:last</b> the last E in the resultset</li>
5801 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
5802 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
5803 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
5804 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
5805 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
5806 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
5807 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
5808 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
5809 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
5811 <h4>CSS Value Selectors:</h4>
5813 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
5814 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
5815 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
5816 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
5817 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
5818 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
5822 Roo.DomQuery = function(){
5823 var cache = {}, simpleCache = {}, valueCache = {};
5824 var nonSpace = /\S/;
5825 var trimRe = /^\s+|\s+$/g;
5826 var tplRe = /\{(\d+)\}/g;
5827 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
5828 var tagTokenRe = /^(#)?([\w-\*]+)/;
5829 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
5831 function child(p, index){
5833 var n = p.firstChild;
5835 if(n.nodeType == 1){
5846 while((n = n.nextSibling) && n.nodeType != 1);
5851 while((n = n.previousSibling) && n.nodeType != 1);
5855 function children(d){
5856 var n = d.firstChild, ni = -1;
5858 var nx = n.nextSibling;
5859 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
5869 function byClassName(c, a, v){
5873 var r = [], ri = -1, cn;
5874 for(var i = 0, ci; ci = c[i]; i++){
5878 ( (ci instanceof SVGElement) ? ci.className.baseVal : ci.className)
5879 +' ').indexOf(v) != -1){
5886 function attrValue(n, attr){
5887 if(!n.tagName && typeof n.length != "undefined"){
5896 if(attr == "class" || attr == "className"){
5897 return (n instanceof SVGElement) ? n.className.baseVal : n.className;
5899 return n.getAttribute(attr) || n[attr];
5903 function getNodes(ns, mode, tagName){
5904 var result = [], ri = -1, cs;
5908 tagName = tagName || "*";
5909 if(typeof ns.getElementsByTagName != "undefined"){
5913 for(var i = 0, ni; ni = ns[i]; i++){
5914 cs = ni.getElementsByTagName(tagName);
5915 for(var j = 0, ci; ci = cs[j]; j++){
5919 }else if(mode == "/" || mode == ">"){
5920 var utag = tagName.toUpperCase();
5921 for(var i = 0, ni, cn; ni = ns[i]; i++){
5922 cn = ni.children || ni.childNodes;
5923 for(var j = 0, cj; cj = cn[j]; j++){
5924 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5929 }else if(mode == "+"){
5930 var utag = tagName.toUpperCase();
5931 for(var i = 0, n; n = ns[i]; i++){
5932 while((n = n.nextSibling) && n.nodeType != 1);
5933 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5937 }else if(mode == "~"){
5938 for(var i = 0, n; n = ns[i]; i++){
5939 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5948 function concat(a, b){
5952 for(var i = 0, l = b.length; i < l; i++){
5958 function byTag(cs, tagName){
5959 if(cs.tagName || cs == document){
5965 var r = [], ri = -1;
5966 tagName = tagName.toLowerCase();
5967 for(var i = 0, ci; ci = cs[i]; i++){
5968 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
5975 function byId(cs, attr, id){
5976 if(cs.tagName || cs == document){
5982 var r = [], ri = -1;
5983 for(var i = 0,ci; ci = cs[i]; i++){
5984 if(ci && ci.id == id){
5992 function byAttribute(cs, attr, value, op, custom){
5993 var r = [], ri = -1, st = custom=="{";
5994 var f = Roo.DomQuery.operators[op];
5995 for(var i = 0, ci; ci = cs[i]; i++){
5998 a = Roo.DomQuery.getStyle(ci, attr);
6000 else if(attr == "class" || attr == "className"){
6001 a = (ci instanceof SVGElement) ? ci.className.baseVal : ci.className;
6002 }else if(attr == "for"){
6004 }else if(attr == "href"){
6005 a = ci.getAttribute("href", 2);
6007 a = ci.getAttribute(attr);
6009 if((f && f(a, value)) || (!f && a)){
6016 function byPseudo(cs, name, value){
6017 return Roo.DomQuery.pseudos[name](cs, value);
6020 // This is for IE MSXML which does not support expandos.
6021 // IE runs the same speed using setAttribute, however FF slows way down
6022 // and Safari completely fails so they need to continue to use expandos.
6023 var isIE = window.ActiveXObject ? true : false;
6025 // this eval is stop the compressor from
6026 // renaming the variable to something shorter
6028 /** eval:var:batch */
6033 function nodupIEXml(cs){
6035 cs[0].setAttribute("_nodup", d);
6037 for(var i = 1, len = cs.length; i < len; i++){
6039 if(!c.getAttribute("_nodup") != d){
6040 c.setAttribute("_nodup", d);
6044 for(var i = 0, len = cs.length; i < len; i++){
6045 cs[i].removeAttribute("_nodup");
6054 var len = cs.length, c, i, r = cs, cj, ri = -1;
6055 if(!len || typeof cs.nodeType != "undefined" || len == 1){
6058 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
6059 return nodupIEXml(cs);
6063 for(i = 1; c = cs[i]; i++){
6068 for(var j = 0; j < i; j++){
6071 for(j = i+1; cj = cs[j]; j++){
6083 function quickDiffIEXml(c1, c2){
6085 for(var i = 0, len = c1.length; i < len; i++){
6086 c1[i].setAttribute("_qdiff", d);
6089 for(var i = 0, len = c2.length; i < len; i++){
6090 if(c2[i].getAttribute("_qdiff") != d){
6091 r[r.length] = c2[i];
6094 for(var i = 0, len = c1.length; i < len; i++){
6095 c1[i].removeAttribute("_qdiff");
6100 function quickDiff(c1, c2){
6101 var len1 = c1.length;
6105 if(isIE && c1[0].selectSingleNode){
6106 return quickDiffIEXml(c1, c2);
6109 for(var i = 0; i < len1; i++){
6113 for(var i = 0, len = c2.length; i < len; i++){
6114 if(c2[i]._qdiff != d){
6115 r[r.length] = c2[i];
6121 function quickId(ns, mode, root, id){
6123 var d = root.ownerDocument || root;
6124 return d.getElementById(id);
6126 ns = getNodes(ns, mode, "*");
6127 return byId(ns, null, id);
6131 getStyle : function(el, name){
6132 return Roo.fly(el).getStyle(name);
6135 * Compiles a selector/xpath query into a reusable function. The returned function
6136 * takes one parameter "root" (optional), which is the context node from where the query should start.
6137 * @param {String} selector The selector/xpath query
6138 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
6139 * @return {Function}
6141 compile : function(path, type){
6142 type = type || "select";
6144 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
6145 var q = path, mode, lq;
6146 var tk = Roo.DomQuery.matchers;
6147 var tklen = tk.length;
6150 // accept leading mode switch
6151 var lmode = q.match(modeRe);
6152 if(lmode && lmode[1]){
6153 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
6154 q = q.replace(lmode[1], "");
6156 // strip leading slashes
6157 while(path.substr(0, 1)=="/"){
6158 path = path.substr(1);
6161 while(q && lq != q){
6163 var tm = q.match(tagTokenRe);
6164 if(type == "select"){
6167 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
6169 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
6171 q = q.replace(tm[0], "");
6172 }else if(q.substr(0, 1) != '@'){
6173 fn[fn.length] = 'n = getNodes(n, mode, "*");';
6178 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
6180 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
6182 q = q.replace(tm[0], "");
6185 while(!(mm = q.match(modeRe))){
6186 var matched = false;
6187 for(var j = 0; j < tklen; j++){
6189 var m = q.match(t.re);
6191 fn[fn.length] = t.select.replace(tplRe, function(x, i){
6194 q = q.replace(m[0], "");
6199 // prevent infinite loop on bad selector
6201 throw 'Error parsing selector, parsing failed at "' + q + '"';
6205 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
6206 q = q.replace(mm[1], "");
6209 fn[fn.length] = "return nodup(n);\n}";
6212 * list of variables that need from compression as they are used by eval.
6222 * eval:var:byClassName
6224 * eval:var:byAttribute
6225 * eval:var:attrValue
6233 * Selects a group of elements.
6234 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
6235 * @param {Node} root (optional) The start of the query (defaults to document).
6238 select : function(path, root, type){
6239 if(!root || root == document){
6242 if(typeof root == "string"){
6243 root = document.getElementById(root);
6245 var paths = path.split(",");
6247 for(var i = 0, len = paths.length; i < len; i++){
6248 var p = paths[i].replace(trimRe, "");
6250 cache[p] = Roo.DomQuery.compile(p);
6252 throw p + " is not a valid selector";
6255 var result = cache[p](root);
6256 if(result && result != document){
6257 results = results.concat(result);
6260 if(paths.length > 1){
6261 return nodup(results);
6267 * Selects a single element.
6268 * @param {String} selector The selector/xpath query
6269 * @param {Node} root (optional) The start of the query (defaults to document).
6272 selectNode : function(path, root){
6273 return Roo.DomQuery.select(path, root)[0];
6277 * Selects the value of a node, optionally replacing null with the defaultValue.
6278 * @param {String} selector The selector/xpath query
6279 * @param {Node} root (optional) The start of the query (defaults to document).
6280 * @param {String} defaultValue
6282 selectValue : function(path, root, defaultValue){
6283 path = path.replace(trimRe, "");
6284 if(!valueCache[path]){
6285 valueCache[path] = Roo.DomQuery.compile(path, "select");
6287 var n = valueCache[path](root);
6288 n = n[0] ? n[0] : n;
6289 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
6290 return ((v === null||v === undefined||v==='') ? defaultValue : v);
6294 * Selects the value of a node, parsing integers and floats.
6295 * @param {String} selector The selector/xpath query
6296 * @param {Node} root (optional) The start of the query (defaults to document).
6297 * @param {Number} defaultValue
6300 selectNumber : function(path, root, defaultValue){
6301 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
6302 return parseFloat(v);
6306 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
6307 * @param {String/HTMLElement/Array} el An element id, element or array of elements
6308 * @param {String} selector The simple selector to test
6311 is : function(el, ss){
6312 if(typeof el == "string"){
6313 el = document.getElementById(el);
6315 var isArray = (el instanceof Array);
6316 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
6317 return isArray ? (result.length == el.length) : (result.length > 0);
6321 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
6322 * @param {Array} el An array of elements to filter
6323 * @param {String} selector The simple selector to test
6324 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
6325 * the selector instead of the ones that match
6328 filter : function(els, ss, nonMatches){
6329 ss = ss.replace(trimRe, "");
6330 if(!simpleCache[ss]){
6331 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
6333 var result = simpleCache[ss](els);
6334 return nonMatches ? quickDiff(result, els) : result;
6338 * Collection of matching regular expressions and code snippets.
6342 select: 'n = byClassName(n, null, " {1} ");'
6344 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
6345 select: 'n = byPseudo(n, "{1}", "{2}");'
6347 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
6348 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
6351 select: 'n = byId(n, null, "{1}");'
6354 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
6359 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
6360 * 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, > <.
6363 "=" : function(a, v){
6366 "!=" : function(a, v){
6369 "^=" : function(a, v){
6370 return a && a.substr(0, v.length) == v;
6372 "$=" : function(a, v){
6373 return a && a.substr(a.length-v.length) == v;
6375 "*=" : function(a, v){
6376 return a && a.indexOf(v) !== -1;
6378 "%=" : function(a, v){
6379 return (a % v) == 0;
6381 "|=" : function(a, v){
6382 return a && (a == v || a.substr(0, v.length+1) == v+'-');
6384 "~=" : function(a, v){
6385 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
6390 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
6391 * and the argument (if any) supplied in the selector.
6394 "first-child" : function(c){
6395 var r = [], ri = -1, n;
6396 for(var i = 0, ci; ci = n = c[i]; i++){
6397 while((n = n.previousSibling) && n.nodeType != 1);
6405 "last-child" : function(c){
6406 var r = [], ri = -1, n;
6407 for(var i = 0, ci; ci = n = c[i]; i++){
6408 while((n = n.nextSibling) && n.nodeType != 1);
6416 "nth-child" : function(c, a) {
6417 var r = [], ri = -1;
6418 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
6419 var f = (m[1] || 1) - 0, l = m[2] - 0;
6420 for(var i = 0, n; n = c[i]; i++){
6421 var pn = n.parentNode;
6422 if (batch != pn._batch) {
6424 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
6425 if(cn.nodeType == 1){
6432 if (l == 0 || n.nodeIndex == l){
6435 } else if ((n.nodeIndex + l) % f == 0){
6443 "only-child" : function(c){
6444 var r = [], ri = -1;;
6445 for(var i = 0, ci; ci = c[i]; i++){
6446 if(!prev(ci) && !next(ci)){
6453 "empty" : function(c){
6454 var r = [], ri = -1;
6455 for(var i = 0, ci; ci = c[i]; i++){
6456 var cns = ci.childNodes, j = 0, cn, empty = true;
6459 if(cn.nodeType == 1 || cn.nodeType == 3){
6471 "contains" : function(c, v){
6472 var r = [], ri = -1;
6473 for(var i = 0, ci; ci = c[i]; i++){
6474 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
6481 "nodeValue" : function(c, v){
6482 var r = [], ri = -1;
6483 for(var i = 0, ci; ci = c[i]; i++){
6484 if(ci.firstChild && ci.firstChild.nodeValue == v){
6491 "checked" : function(c){
6492 var r = [], ri = -1;
6493 for(var i = 0, ci; ci = c[i]; i++){
6494 if(ci.checked == true){
6501 "not" : function(c, ss){
6502 return Roo.DomQuery.filter(c, ss, true);
6505 "odd" : function(c){
6506 return this["nth-child"](c, "odd");
6509 "even" : function(c){
6510 return this["nth-child"](c, "even");
6513 "nth" : function(c, a){
6514 return c[a-1] || [];
6517 "first" : function(c){
6521 "last" : function(c){
6522 return c[c.length-1] || [];
6525 "has" : function(c, ss){
6526 var s = Roo.DomQuery.select;
6527 var r = [], ri = -1;
6528 for(var i = 0, ci; ci = c[i]; i++){
6529 if(s(ss, ci).length > 0){
6536 "next" : function(c, ss){
6537 var is = Roo.DomQuery.is;
6538 var r = [], ri = -1;
6539 for(var i = 0, ci; ci = c[i]; i++){
6548 "prev" : function(c, ss){
6549 var is = Roo.DomQuery.is;
6550 var r = [], ri = -1;
6551 for(var i = 0, ci; ci = c[i]; i++){
6564 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
6565 * @param {String} path The selector/xpath query
6566 * @param {Node} root (optional) The start of the query (defaults to document).
6571 Roo.query = Roo.DomQuery.select;
6574 * Ext JS Library 1.1.1
6575 * Copyright(c) 2006-2007, Ext JS, LLC.
6577 * Originally Released Under LGPL - original licence link has changed is not relivant.
6580 * <script type="text/javascript">
6584 * @class Roo.util.Observable
6585 * Base class that provides a common interface for publishing events. Subclasses are expected to
6586 * to have a property "events" with all the events defined.<br>
6589 Employee = function(name){
6596 Roo.extend(Employee, Roo.util.Observable);
6598 * @param {Object} config properties to use (incuding events / listeners)
6601 Roo.util.Observable = function(cfg){
6604 this.addEvents(cfg.events || {});
6606 delete cfg.events; // make sure
6609 Roo.apply(this, cfg);
6612 this.on(this.listeners);
6613 delete this.listeners;
6616 Roo.util.Observable.prototype = {
6618 * @cfg {Object} listeners list of events and functions to call for this object,
6622 'click' : function(e) {
6632 * Fires the specified event with the passed parameters (minus the event name).
6633 * @param {String} eventName
6634 * @param {Object...} args Variable number of parameters are passed to handlers
6635 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
6637 fireEvent : function(){
6638 var ce = this.events[arguments[0].toLowerCase()];
6639 if(typeof ce == "object"){
6640 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
6647 filterOptRe : /^(?:scope|delay|buffer|single)$/,
6650 * Appends an event handler to this component
6651 * @param {String} eventName The type of event to listen for
6652 * @param {Function} handler The method the event invokes
6653 * @param {Object} scope (optional) The scope in which to execute the handler
6654 * function. The handler function's "this" context.
6655 * @param {Object} options (optional) An object containing handler configuration
6656 * properties. This may contain any of the following properties:<ul>
6657 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6658 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6659 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6660 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6661 * by the specified number of milliseconds. If the event fires again within that time, the original
6662 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6665 * <b>Combining Options</b><br>
6666 * Using the options argument, it is possible to combine different types of listeners:<br>
6668 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
6670 el.on('click', this.onClick, this, {
6677 * <b>Attaching multiple handlers in 1 call</b><br>
6678 * The method also allows for a single argument to be passed which is a config object containing properties
6679 * which specify multiple handlers.
6688 fn: this.onMouseOver,
6692 fn: this.onMouseOut,
6698 * Or a shorthand syntax which passes the same scope object to all handlers:
6701 'click': this.onClick,
6702 'mouseover': this.onMouseOver,
6703 'mouseout': this.onMouseOut,
6708 addListener : function(eventName, fn, scope, o){
6709 if(typeof eventName == "object"){
6712 if(this.filterOptRe.test(e)){
6715 if(typeof o[e] == "function"){
6717 this.addListener(e, o[e], o.scope, o);
6719 // individual options
6720 this.addListener(e, o[e].fn, o[e].scope, o[e]);
6725 o = (!o || typeof o == "boolean") ? {} : o;
6726 eventName = eventName.toLowerCase();
6727 var ce = this.events[eventName] || true;
6728 if(typeof ce == "boolean"){
6729 ce = new Roo.util.Event(this, eventName);
6730 this.events[eventName] = ce;
6732 ce.addListener(fn, scope, o);
6736 * Removes a listener
6737 * @param {String} eventName The type of event to listen for
6738 * @param {Function} handler The handler to remove
6739 * @param {Object} scope (optional) The scope (this object) for the handler
6741 removeListener : function(eventName, fn, scope){
6742 var ce = this.events[eventName.toLowerCase()];
6743 if(typeof ce == "object"){
6744 ce.removeListener(fn, scope);
6749 * Removes all listeners for this object
6751 purgeListeners : function(){
6752 for(var evt in this.events){
6753 if(typeof this.events[evt] == "object"){
6754 this.events[evt].clearListeners();
6759 relayEvents : function(o, events){
6760 var createHandler = function(ename){
6763 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
6766 for(var i = 0, len = events.length; i < len; i++){
6767 var ename = events[i];
6768 if(!this.events[ename]){
6769 this.events[ename] = true;
6771 o.on(ename, createHandler(ename), this);
6776 * Used to define events on this Observable
6777 * @param {Object} object The object with the events defined
6779 addEvents : function(o){
6783 Roo.applyIf(this.events, o);
6787 * Checks to see if this object has any listeners for a specified event
6788 * @param {String} eventName The name of the event to check for
6789 * @return {Boolean} True if the event is being listened for, else false
6791 hasListener : function(eventName){
6792 var e = this.events[eventName];
6793 return typeof e == "object" && e.listeners.length > 0;
6797 * Appends an event handler to this element (shorthand for addListener)
6798 * @param {String} eventName The type of event to listen for
6799 * @param {Function} handler The method the event invokes
6800 * @param {Object} scope (optional) The scope in which to execute the handler
6801 * function. The handler function's "this" context.
6802 * @param {Object} options (optional)
6805 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
6807 * Removes a listener (shorthand for removeListener)
6808 * @param {String} eventName The type of event to listen for
6809 * @param {Function} handler The handler to remove
6810 * @param {Object} scope (optional) The scope (this object) for the handler
6813 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
6816 * Starts capture on the specified Observable. All events will be passed
6817 * to the supplied function with the event name + standard signature of the event
6818 * <b>before</b> the event is fired. If the supplied function returns false,
6819 * the event will not fire.
6820 * @param {Observable} o The Observable to capture
6821 * @param {Function} fn The function to call
6822 * @param {Object} scope (optional) The scope (this object) for the fn
6825 Roo.util.Observable.capture = function(o, fn, scope){
6826 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
6830 * Removes <b>all</b> added captures from the Observable.
6831 * @param {Observable} o The Observable to release
6834 Roo.util.Observable.releaseCapture = function(o){
6835 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
6840 var createBuffered = function(h, o, scope){
6841 var task = new Roo.util.DelayedTask();
6843 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
6847 var createSingle = function(h, e, fn, scope){
6849 e.removeListener(fn, scope);
6850 return h.apply(scope, arguments);
6854 var createDelayed = function(h, o, scope){
6856 var args = Array.prototype.slice.call(arguments, 0);
6857 setTimeout(function(){
6858 h.apply(scope, args);
6863 Roo.util.Event = function(obj, name){
6866 this.listeners = [];
6869 Roo.util.Event.prototype = {
6870 addListener : function(fn, scope, options){
6871 var o = options || {};
6872 scope = scope || this.obj;
6873 if(!this.isListening(fn, scope)){
6874 var l = {fn: fn, scope: scope, options: o};
6877 h = createDelayed(h, o, scope);
6880 h = createSingle(h, this, fn, scope);
6883 h = createBuffered(h, o, scope);
6886 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
6887 this.listeners.push(l);
6889 this.listeners = this.listeners.slice(0);
6890 this.listeners.push(l);
6895 findListener : function(fn, scope){
6896 scope = scope || this.obj;
6897 var ls = this.listeners;
6898 for(var i = 0, len = ls.length; i < len; i++){
6900 if(l.fn == fn && l.scope == scope){
6907 isListening : function(fn, scope){
6908 return this.findListener(fn, scope) != -1;
6911 removeListener : function(fn, scope){
6913 if((index = this.findListener(fn, scope)) != -1){
6915 this.listeners.splice(index, 1);
6917 this.listeners = this.listeners.slice(0);
6918 this.listeners.splice(index, 1);
6925 clearListeners : function(){
6926 this.listeners = [];
6930 var ls = this.listeners, scope, len = ls.length;
6933 var args = Array.prototype.slice.call(arguments, 0);
6934 for(var i = 0; i < len; i++){
6936 if(l.fireFn.apply(l.scope||this.obj||window, args) === false){
6937 this.firing = false;
6941 this.firing = false;
6948 * Copyright(c) 2007-2017, Roo J Solutions Ltd
6955 * @class Roo.Document
6956 * @extends Roo.util.Observable
6957 * This is a convience class to wrap up the main document loading code.. , rather than adding Roo.onReady(......)
6959 * @param {Object} config the methods and properties of the 'base' class for the application.
6961 * Generic Page handler - implement this to start your app..
6964 * MyProject = new Roo.Document({
6966 'load' : true // your events..
6969 'ready' : function() {
6970 // fired on Roo.onReady()
6975 Roo.Document = function(cfg) {
6980 Roo.util.Observable.call(this,cfg);
6984 Roo.onReady(function() {
6985 _this.fireEvent('ready');
6991 Roo.extend(Roo.Document, Roo.util.Observable, {});/*
6993 * Ext JS Library 1.1.1
6994 * Copyright(c) 2006-2007, Ext JS, LLC.
6996 * Originally Released Under LGPL - original licence link has changed is not relivant.
6999 * <script type="text/javascript">
7003 * @class Roo.EventManager
7004 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
7005 * several useful events directly.
7006 * See {@link Roo.EventObject} for more details on normalized event objects.
7009 Roo.EventManager = function(){
7010 var docReadyEvent, docReadyProcId, docReadyState = false;
7011 var resizeEvent, resizeTask, textEvent, textSize;
7012 var E = Roo.lib.Event;
7013 var D = Roo.lib.Dom;
7018 var fireDocReady = function(){
7020 docReadyState = true;
7023 clearInterval(docReadyProcId);
7025 if(Roo.isGecko || Roo.isOpera) {
7026 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
7029 var defer = document.getElementById("ie-deferred-loader");
7031 defer.onreadystatechange = null;
7032 defer.parentNode.removeChild(defer);
7036 docReadyEvent.fire();
7037 docReadyEvent.clearListeners();
7042 var initDocReady = function(){
7043 docReadyEvent = new Roo.util.Event();
7044 if(Roo.isGecko || Roo.isOpera) {
7045 document.addEventListener("DOMContentLoaded", fireDocReady, false);
7047 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
7048 var defer = document.getElementById("ie-deferred-loader");
7049 defer.onreadystatechange = function(){
7050 if(this.readyState == "complete"){
7054 }else if(Roo.isSafari){
7055 docReadyProcId = setInterval(function(){
7056 var rs = document.readyState;
7057 if(rs == "complete") {
7062 // no matter what, make sure it fires on load
7063 E.on(window, "load", fireDocReady);
7066 var createBuffered = function(h, o){
7067 var task = new Roo.util.DelayedTask(h);
7069 // create new event object impl so new events don't wipe out properties
7070 e = new Roo.EventObjectImpl(e);
7071 task.delay(o.buffer, h, null, [e]);
7075 var createSingle = function(h, el, ename, fn){
7077 Roo.EventManager.removeListener(el, ename, fn);
7082 var createDelayed = function(h, o){
7084 // create new event object impl so new events don't wipe out properties
7085 e = new Roo.EventObjectImpl(e);
7086 setTimeout(function(){
7091 var transitionEndVal = false;
7093 var transitionEnd = function()
7095 if (transitionEndVal) {
7096 return transitionEndVal;
7098 var el = document.createElement('div');
7100 var transEndEventNames = {
7101 WebkitTransition : 'webkitTransitionEnd',
7102 MozTransition : 'transitionend',
7103 OTransition : 'oTransitionEnd otransitionend',
7104 transition : 'transitionend'
7107 for (var name in transEndEventNames) {
7108 if (el.style[name] !== undefined) {
7109 transitionEndVal = transEndEventNames[name];
7110 return transitionEndVal ;
7117 var listen = function(element, ename, opt, fn, scope)
7119 var o = (!opt || typeof opt == "boolean") ? {} : opt;
7120 fn = fn || o.fn; scope = scope || o.scope;
7121 var el = Roo.getDom(element);
7125 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
7128 if (ename == 'transitionend') {
7129 ename = transitionEnd();
7131 var h = function(e){
7132 e = Roo.EventObject.setEvent(e);
7135 t = e.getTarget(o.delegate, el);
7142 if(o.stopEvent === true){
7145 if(o.preventDefault === true){
7148 if(o.stopPropagation === true){
7149 e.stopPropagation();
7152 if(o.normalized === false){
7156 fn.call(scope || el, e, t, o);
7159 h = createDelayed(h, o);
7162 h = createSingle(h, el, ename, fn);
7165 h = createBuffered(h, o);
7168 fn._handlers = fn._handlers || [];
7171 fn._handlers.push([Roo.id(el), ename, h]);
7175 E.on(el, ename, h); // this adds the actuall listener to the object..
7178 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
7179 el.addEventListener("DOMMouseScroll", h, false);
7180 E.on(window, 'unload', function(){
7181 el.removeEventListener("DOMMouseScroll", h, false);
7184 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7185 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
7190 var stopListening = function(el, ename, fn){
7191 var id = Roo.id(el), hds = fn._handlers, hd = fn;
7193 for(var i = 0, len = hds.length; i < len; i++){
7195 if(h[0] == id && h[1] == ename){
7202 E.un(el, ename, hd);
7203 el = Roo.getDom(el);
7204 if(ename == "mousewheel" && el.addEventListener){
7205 el.removeEventListener("DOMMouseScroll", hd, false);
7207 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7208 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
7212 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
7219 * @scope Roo.EventManager
7224 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
7225 * object with a Roo.EventObject
7226 * @param {Function} fn The method the event invokes
7227 * @param {Object} scope An object that becomes the scope of the handler
7228 * @param {boolean} override If true, the obj passed in becomes
7229 * the execution scope of the listener
7230 * @return {Function} The wrapped function
7233 wrap : function(fn, scope, override){
7235 Roo.EventObject.setEvent(e);
7236 fn.call(override ? scope || window : window, Roo.EventObject, scope);
7241 * Appends an event handler to an element (shorthand for addListener)
7242 * @param {String/HTMLElement} element The html element or id to assign the
7243 * @param {String} eventName The type of event to listen for
7244 * @param {Function} handler The method the event invokes
7245 * @param {Object} scope (optional) The scope in which to execute the handler
7246 * function. The handler function's "this" context.
7247 * @param {Object} options (optional) An object containing handler configuration
7248 * properties. This may contain any of the following properties:<ul>
7249 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7250 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7251 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7252 * <li>preventDefault {Boolean} True to prevent the default action</li>
7253 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7254 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7255 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7256 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7257 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7258 * by the specified number of milliseconds. If the event fires again within that time, the original
7259 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7262 * <b>Combining Options</b><br>
7263 * Using the options argument, it is possible to combine different types of listeners:<br>
7265 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7267 el.on('click', this.onClick, this, {
7274 * <b>Attaching multiple handlers in 1 call</b><br>
7275 * The method also allows for a single argument to be passed which is a config object containing properties
7276 * which specify multiple handlers.
7286 fn: this.onMouseOver
7295 * Or a shorthand syntax:<br>
7298 'click' : this.onClick,
7299 'mouseover' : this.onMouseOver,
7300 'mouseout' : this.onMouseOut
7304 addListener : function(element, eventName, fn, scope, options){
7305 if(typeof eventName == "object"){
7311 if(typeof o[e] == "function"){
7313 listen(element, e, o, o[e], o.scope);
7315 // individual options
7316 listen(element, e, o[e]);
7321 return listen(element, eventName, options, fn, scope);
7325 * Removes an event handler
7327 * @param {String/HTMLElement} element The id or html element to remove the
7329 * @param {String} eventName The type of event
7330 * @param {Function} fn
7331 * @return {Boolean} True if a listener was actually removed
7333 removeListener : function(element, eventName, fn){
7334 return stopListening(element, eventName, fn);
7338 * Fires when the document is ready (before onload and before images are loaded). Can be
7339 * accessed shorthanded Roo.onReady().
7340 * @param {Function} fn The method the event invokes
7341 * @param {Object} scope An object that becomes the scope of the handler
7342 * @param {boolean} options
7344 onDocumentReady : function(fn, scope, options){
7345 if(docReadyState){ // if it already fired
7346 docReadyEvent.addListener(fn, scope, options);
7347 docReadyEvent.fire();
7348 docReadyEvent.clearListeners();
7354 docReadyEvent.addListener(fn, scope, options);
7358 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
7359 * @param {Function} fn The method the event invokes
7360 * @param {Object} scope An object that becomes the scope of the handler
7361 * @param {boolean} options
7363 onWindowResize : function(fn, scope, options)
7366 resizeEvent = new Roo.util.Event();
7367 resizeTask = new Roo.util.DelayedTask(function(){
7368 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7370 E.on(window, "resize", function()
7373 resizeTask.delay(50);
7375 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7379 resizeEvent.addListener(fn, scope, options);
7383 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
7384 * @param {Function} fn The method the event invokes
7385 * @param {Object} scope An object that becomes the scope of the handler
7386 * @param {boolean} options
7388 onTextResize : function(fn, scope, options){
7390 textEvent = new Roo.util.Event();
7391 var textEl = new Roo.Element(document.createElement('div'));
7392 textEl.dom.className = 'x-text-resize';
7393 textEl.dom.innerHTML = 'X';
7394 textEl.appendTo(document.body);
7395 textSize = textEl.dom.offsetHeight;
7396 setInterval(function(){
7397 if(textEl.dom.offsetHeight != textSize){
7398 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
7400 }, this.textResizeInterval);
7402 textEvent.addListener(fn, scope, options);
7406 * Removes the passed window resize listener.
7407 * @param {Function} fn The method the event invokes
7408 * @param {Object} scope The scope of handler
7410 removeResizeListener : function(fn, scope){
7412 resizeEvent.removeListener(fn, scope);
7417 fireResize : function(){
7419 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7423 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
7427 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
7429 textResizeInterval : 50
7434 * @scopeAlias pub=Roo.EventManager
7438 * Appends an event handler to an element (shorthand for addListener)
7439 * @param {String/HTMLElement} element The html element or id to assign the
7440 * @param {String} eventName The type of event to listen for
7441 * @param {Function} handler The method the event invokes
7442 * @param {Object} scope (optional) The scope in which to execute the handler
7443 * function. The handler function's "this" context.
7444 * @param {Object} options (optional) An object containing handler configuration
7445 * properties. This may contain any of the following properties:<ul>
7446 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7447 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7448 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7449 * <li>preventDefault {Boolean} True to prevent the default action</li>
7450 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7451 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7452 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7453 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7454 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7455 * by the specified number of milliseconds. If the event fires again within that time, the original
7456 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7459 * <b>Combining Options</b><br>
7460 * Using the options argument, it is possible to combine different types of listeners:<br>
7462 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7464 el.on('click', this.onClick, this, {
7471 * <b>Attaching multiple handlers in 1 call</b><br>
7472 * The method also allows for a single argument to be passed which is a config object containing properties
7473 * which specify multiple handlers.
7483 fn: this.onMouseOver
7492 * Or a shorthand syntax:<br>
7495 'click' : this.onClick,
7496 'mouseover' : this.onMouseOver,
7497 'mouseout' : this.onMouseOut
7501 pub.on = pub.addListener;
7502 pub.un = pub.removeListener;
7504 pub.stoppedMouseDownEvent = new Roo.util.Event();
7508 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
7509 * @param {Function} fn The method the event invokes
7510 * @param {Object} scope An object that becomes the scope of the handler
7511 * @param {boolean} override If true, the obj passed in becomes
7512 * the execution scope of the listener
7516 Roo.onReady = Roo.EventManager.onDocumentReady;
7518 Roo.onReady(function(){
7519 var bd = Roo.get(document.body);
7524 : Roo.isIE11 ? "roo-ie11"
7525 : Roo.isEdge ? "roo-edge"
7526 : Roo.isGecko ? "roo-gecko"
7527 : Roo.isOpera ? "roo-opera"
7528 : Roo.isSafari ? "roo-safari" : ""];
7531 cls.push("roo-mac");
7534 cls.push("roo-linux");
7537 cls.push("roo-ios");
7540 cls.push("roo-touch");
7542 if(Roo.isBorderBox){
7543 cls.push('roo-border-box');
7545 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
7546 var p = bd.dom.parentNode;
7548 p.className += ' roo-strict';
7551 bd.addClass(cls.join(' '));
7555 * @class Roo.EventObject
7556 * EventObject exposes the Yahoo! UI Event functionality directly on the object
7557 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
7560 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
7562 var target = e.getTarget();
7565 var myDiv = Roo.get("myDiv");
7566 myDiv.on("click", handleClick);
7568 Roo.EventManager.on("myDiv", 'click', handleClick);
7569 Roo.EventManager.addListener("myDiv", 'click', handleClick);
7573 Roo.EventObject = function(){
7575 var E = Roo.lib.Event;
7577 // safari keypress events for special keys return bad keycodes
7580 63235 : 39, // right
7583 63276 : 33, // page up
7584 63277 : 34, // page down
7585 63272 : 46, // delete
7590 // normalize button clicks
7591 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
7592 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
7594 Roo.EventObjectImpl = function(e){
7596 this.setEvent(e.browserEvent || e);
7599 Roo.EventObjectImpl.prototype = {
7601 * Used to fix doc tools.
7602 * @scope Roo.EventObject.prototype
7608 /** The normal browser event */
7609 browserEvent : null,
7610 /** The button pressed in a mouse event */
7612 /** True if the shift key was down during the event */
7614 /** True if the control key was down during the event */
7616 /** True if the alt key was down during the event */
7675 setEvent : function(e){
7676 if(e == this || (e && e.browserEvent)){ // already wrapped
7679 this.browserEvent = e;
7681 // normalize buttons
7682 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
7683 if(e.type == 'click' && this.button == -1){
7687 this.shiftKey = e.shiftKey;
7688 // mac metaKey behaves like ctrlKey
7689 this.ctrlKey = e.ctrlKey || e.metaKey;
7690 this.altKey = e.altKey;
7691 // in getKey these will be normalized for the mac
7692 this.keyCode = e.keyCode;
7693 // keyup warnings on firefox.
7694 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
7695 // cache the target for the delayed and or buffered events
7696 this.target = E.getTarget(e);
7698 this.xy = E.getXY(e);
7701 this.shiftKey = false;
7702 this.ctrlKey = false;
7703 this.altKey = false;
7713 * Stop the event (preventDefault and stopPropagation)
7715 stopEvent : function(){
7716 if(this.browserEvent){
7717 if(this.browserEvent.type == 'mousedown'){
7718 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7720 E.stopEvent(this.browserEvent);
7725 * Prevents the browsers default handling of the event.
7727 preventDefault : function(){
7728 if(this.browserEvent){
7729 E.preventDefault(this.browserEvent);
7734 isNavKeyPress : function(){
7735 var k = this.keyCode;
7736 k = Roo.isSafari ? (safariKeys[k] || k) : k;
7737 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
7740 isSpecialKey : function(){
7741 var k = this.keyCode;
7742 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
7743 (k == 16) || (k == 17) ||
7744 (k >= 18 && k <= 20) ||
7745 (k >= 33 && k <= 35) ||
7746 (k >= 36 && k <= 39) ||
7747 (k >= 44 && k <= 45);
7750 * Cancels bubbling of the event.
7752 stopPropagation : function(){
7753 if(this.browserEvent){
7754 if(this.type == 'mousedown'){
7755 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7757 E.stopPropagation(this.browserEvent);
7762 * Gets the key code for the event.
7765 getCharCode : function(){
7766 return this.charCode || this.keyCode;
7770 * Returns a normalized keyCode for the event.
7771 * @return {Number} The key code
7773 getKey : function(){
7774 var k = this.keyCode || this.charCode;
7775 return Roo.isSafari ? (safariKeys[k] || k) : k;
7779 * Gets the x coordinate of the event.
7782 getPageX : function(){
7787 * Gets the y coordinate of the event.
7790 getPageY : function(){
7795 * Gets the time of the event.
7798 getTime : function(){
7799 if(this.browserEvent){
7800 return E.getTime(this.browserEvent);
7806 * Gets the page coordinates of the event.
7807 * @return {Array} The xy values like [x, y]
7814 * Gets the target for the event.
7815 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
7816 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7817 search as a number or element (defaults to 10 || document.body)
7818 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7819 * @return {HTMLelement}
7821 getTarget : function(selector, maxDepth, returnEl){
7822 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
7825 * Gets the related target.
7826 * @return {HTMLElement}
7828 getRelatedTarget : function(){
7829 if(this.browserEvent){
7830 return E.getRelatedTarget(this.browserEvent);
7836 * Normalizes mouse wheel delta across browsers
7837 * @return {Number} The delta
7839 getWheelDelta : function(){
7840 var e = this.browserEvent;
7842 if(e.wheelDelta){ /* IE/Opera. */
7843 delta = e.wheelDelta/120;
7844 }else if(e.detail){ /* Mozilla case. */
7845 delta = -e.detail/3;
7851 * Returns true if the control, meta, shift or alt key was pressed during this event.
7854 hasModifier : function(){
7855 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
7859 * Returns true if the target of this event equals el or is a child of el
7860 * @param {String/HTMLElement/Element} el
7861 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
7864 within : function(el, related){
7865 var t = this[related ? "getRelatedTarget" : "getTarget"]();
7866 return t && Roo.fly(el).contains(t);
7869 getPoint : function(){
7870 return new Roo.lib.Point(this.xy[0], this.xy[1]);
7874 return new Roo.EventObjectImpl();
7879 * Ext JS Library 1.1.1
7880 * Copyright(c) 2006-2007, Ext JS, LLC.
7882 * Originally Released Under LGPL - original licence link has changed is not relivant.
7885 * <script type="text/javascript">
7889 // was in Composite Element!??!?!
7892 var D = Roo.lib.Dom;
7893 var E = Roo.lib.Event;
7894 var A = Roo.lib.Anim;
7896 // local style camelizing for speed
7898 var camelRe = /(-[a-z])/gi;
7899 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
7900 var view = document.defaultView;
7903 * @class Roo.Element
7904 * Represents an Element in the DOM.<br><br>
7907 var el = Roo.get("my-div");
7910 var el = getEl("my-div");
7912 // or with a DOM element
7913 var el = Roo.get(myDivElement);
7915 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
7916 * each call instead of constructing a new one.<br><br>
7917 * <b>Animations</b><br />
7918 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
7919 * should either be a boolean (true) or an object literal with animation options. The animation options are:
7921 Option Default Description
7922 --------- -------- ---------------------------------------------
7923 duration .35 The duration of the animation in seconds
7924 easing easeOut The YUI easing method
7925 callback none A function to execute when the anim completes
7926 scope this The scope (this) of the callback function
7928 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
7929 * manipulate the animation. Here's an example:
7931 var el = Roo.get("my-div");
7936 // default animation
7937 el.setWidth(100, true);
7939 // animation with some options set
7946 // using the "anim" property to get the Anim object
7952 el.setWidth(100, opt);
7954 if(opt.anim.isAnimated()){
7958 * <b> Composite (Collections of) Elements</b><br />
7959 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
7960 * @constructor Create a new Element directly.
7961 * @param {String/HTMLElement} element
7962 * @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).
7964 Roo.Element = function(element, forceNew)
7966 var dom = typeof element == "string" ?
7967 document.getElementById(element) : element;
7969 this.listeners = {};
7971 if(!dom){ // invalid id/element
7975 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
7976 return Roo.Element.cache[id];
7986 * The DOM element ID
7989 this.id = id || Roo.id(dom);
7991 return this; // assumed for cctor?
7994 var El = Roo.Element;
7998 * The element's default display mode (defaults to "")
8001 originalDisplay : "",
8004 // note this is overridden in BS version..
8007 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
8013 * Sets the element's visibility mode. When setVisible() is called it
8014 * will use this to determine whether to set the visibility or the display property.
8015 * @param visMode Element.VISIBILITY or Element.DISPLAY
8016 * @return {Roo.Element} this
8018 setVisibilityMode : function(visMode){
8019 this.visibilityMode = visMode;
8023 * Convenience method for setVisibilityMode(Element.DISPLAY)
8024 * @param {String} display (optional) What to set display to when visible
8025 * @return {Roo.Element} this
8027 enableDisplayMode : function(display){
8028 this.setVisibilityMode(El.DISPLAY);
8029 if(typeof display != "undefined") { this.originalDisplay = display; }
8034 * 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)
8035 * @param {String} selector The simple selector to test
8036 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8037 search as a number or element (defaults to 10 || document.body)
8038 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8039 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8041 findParent : function(simpleSelector, maxDepth, returnEl){
8042 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
8043 maxDepth = maxDepth || 50;
8044 if(typeof maxDepth != "number"){
8045 stopEl = Roo.getDom(maxDepth);
8048 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
8049 if(dq.is(p, simpleSelector)){
8050 return returnEl ? Roo.get(p) : p;
8060 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
8061 * @param {String} selector The simple selector to test
8062 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8063 search as a number or element (defaults to 10 || document.body)
8064 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8065 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8067 findParentNode : function(simpleSelector, maxDepth, returnEl){
8068 var p = Roo.fly(this.dom.parentNode, '_internal');
8069 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
8073 * Looks at the scrollable parent element
8075 findScrollableParent : function()
8077 var overflowRegex = /(auto|scroll)/;
8079 if(this.getStyle('position') === 'fixed'){
8080 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8083 var excludeStaticParent = this.getStyle('position') === "absolute";
8085 for (var parent = this; (parent = Roo.get(parent.dom.parentNode));){
8087 if (excludeStaticParent && parent.getStyle('position') === "static") {
8091 if (overflowRegex.test(parent.getStyle('overflow') + parent.getStyle('overflow-x') + parent.getStyle('overflow-y'))){
8095 if(parent.dom.nodeName.toLowerCase() == 'body'){
8096 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8100 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8104 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
8105 * This is a shortcut for findParentNode() that always returns an Roo.Element.
8106 * @param {String} selector The simple selector to test
8107 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8108 search as a number or element (defaults to 10 || document.body)
8109 * @return {Roo.Element} The matching DOM node (or null if no match was found)
8111 up : function(simpleSelector, maxDepth){
8112 return this.findParentNode(simpleSelector, maxDepth, true);
8118 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
8119 * @param {String} selector The simple selector to test
8120 * @return {Boolean} True if this element matches the selector, else false
8122 is : function(simpleSelector){
8123 return Roo.DomQuery.is(this.dom, simpleSelector);
8127 * Perform animation on this element.
8128 * @param {Object} args The YUI animation control args
8129 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
8130 * @param {Function} onComplete (optional) Function to call when animation completes
8131 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
8132 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
8133 * @return {Roo.Element} this
8135 animate : function(args, duration, onComplete, easing, animType){
8136 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
8141 * @private Internal animation call
8143 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
8144 animType = animType || 'run';
8146 var anim = Roo.lib.Anim[animType](
8148 (opt.duration || defaultDur) || .35,
8149 (opt.easing || defaultEase) || 'easeOut',
8151 Roo.callback(cb, this);
8152 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
8160 // private legacy anim prep
8161 preanim : function(a, i){
8162 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
8166 * Removes worthless text nodes
8167 * @param {Boolean} forceReclean (optional) By default the element
8168 * keeps track if it has been cleaned already so
8169 * you can call this over and over. However, if you update the element and
8170 * need to force a reclean, you can pass true.
8172 clean : function(forceReclean){
8173 if(this.isCleaned && forceReclean !== true){
8177 var d = this.dom, n = d.firstChild, ni = -1;
8179 var nx = n.nextSibling;
8180 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
8187 this.isCleaned = true;
8192 calcOffsetsTo : function(el){
8195 var restorePos = false;
8196 if(el.getStyle('position') == 'static'){
8197 el.position('relative');
8202 while(op && op != d && op.tagName != 'HTML'){
8205 op = op.offsetParent;
8208 el.position('static');
8214 * Scrolls this element into view within the passed container.
8215 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
8216 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
8217 * @return {Roo.Element} this
8219 scrollIntoView : function(container, hscroll){
8220 var c = Roo.getDom(container) || document.body;
8223 var o = this.calcOffsetsTo(c),
8226 b = t+el.offsetHeight,
8227 r = l+el.offsetWidth;
8229 var ch = c.clientHeight;
8230 var ct = parseInt(c.scrollTop, 10);
8231 var cl = parseInt(c.scrollLeft, 10);
8233 var cr = cl + c.clientWidth;
8241 if(hscroll !== false){
8245 c.scrollLeft = r-c.clientWidth;
8252 scrollChildIntoView : function(child, hscroll){
8253 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
8257 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
8258 * the new height may not be available immediately.
8259 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
8260 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
8261 * @param {Function} onComplete (optional) Function to call when animation completes
8262 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
8263 * @return {Roo.Element} this
8265 autoHeight : function(animate, duration, onComplete, easing){
8266 var oldHeight = this.getHeight();
8268 this.setHeight(1); // force clipping
8269 setTimeout(function(){
8270 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
8272 this.setHeight(height);
8274 if(typeof onComplete == "function"){
8278 this.setHeight(oldHeight); // restore original height
8279 this.setHeight(height, animate, duration, function(){
8281 if(typeof onComplete == "function") { onComplete(); }
8282 }.createDelegate(this), easing);
8284 }.createDelegate(this), 0);
8289 * Returns true if this element is an ancestor of the passed element
8290 * @param {HTMLElement/String} el The element to check
8291 * @return {Boolean} True if this element is an ancestor of el, else false
8293 contains : function(el){
8294 if(!el){return false;}
8295 return D.isAncestor(this.dom, el.dom ? el.dom : el);
8299 * Checks whether the element is currently visible using both visibility and display properties.
8300 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
8301 * @return {Boolean} True if the element is currently visible, else false
8303 isVisible : function(deep) {
8304 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
8305 if(deep !== true || !vis){
8308 var p = this.dom.parentNode;
8309 while(p && p.tagName.toLowerCase() != "body"){
8310 if(!Roo.fly(p, '_isVisible').isVisible()){
8319 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
8320 * @param {String} selector The CSS selector
8321 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
8322 * @return {CompositeElement/CompositeElementLite} The composite element
8324 select : function(selector, unique){
8325 return El.select(selector, unique, this.dom);
8329 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
8330 * @param {String} selector The CSS selector
8331 * @return {Array} An array of the matched nodes
8333 query : function(selector, unique){
8334 return Roo.DomQuery.select(selector, this.dom);
8338 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
8339 * @param {String} selector The CSS selector
8340 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8341 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8343 child : function(selector, returnDom){
8344 var n = Roo.DomQuery.selectNode(selector, this.dom);
8345 return returnDom ? n : Roo.get(n);
8349 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
8350 * @param {String} selector The CSS selector
8351 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8352 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8354 down : function(selector, returnDom){
8355 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
8356 return returnDom ? n : Roo.get(n);
8360 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
8361 * @param {String} group The group the DD object is member of
8362 * @param {Object} config The DD config object
8363 * @param {Object} overrides An object containing methods to override/implement on the DD object
8364 * @return {Roo.dd.DD} The DD object
8366 initDD : function(group, config, overrides){
8367 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
8368 return Roo.apply(dd, overrides);
8372 * Initializes a {@link Roo.dd.DDProxy} object for this element.
8373 * @param {String} group The group the DDProxy object is member of
8374 * @param {Object} config The DDProxy config object
8375 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
8376 * @return {Roo.dd.DDProxy} The DDProxy object
8378 initDDProxy : function(group, config, overrides){
8379 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
8380 return Roo.apply(dd, overrides);
8384 * Initializes a {@link Roo.dd.DDTarget} object for this element.
8385 * @param {String} group The group the DDTarget object is member of
8386 * @param {Object} config The DDTarget config object
8387 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
8388 * @return {Roo.dd.DDTarget} The DDTarget object
8390 initDDTarget : function(group, config, overrides){
8391 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
8392 return Roo.apply(dd, overrides);
8396 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
8397 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
8398 * @param {Boolean} visible Whether the element is visible
8399 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8400 * @return {Roo.Element} this
8402 setVisible : function(visible, animate){
8404 if(this.visibilityMode == El.DISPLAY){
8405 this.setDisplayed(visible);
8408 this.dom.style.visibility = visible ? "visible" : "hidden";
8411 // closure for composites
8413 var visMode = this.visibilityMode;
8415 this.setOpacity(.01);
8416 this.setVisible(true);
8418 this.anim({opacity: { to: (visible?1:0) }},
8419 this.preanim(arguments, 1),
8420 null, .35, 'easeIn', function(){
8422 if(visMode == El.DISPLAY){
8423 dom.style.display = "none";
8425 dom.style.visibility = "hidden";
8427 Roo.get(dom).setOpacity(1);
8435 * Returns true if display is not "none"
8438 isDisplayed : function() {
8439 return this.getStyle("display") != "none";
8443 * Toggles the element's visibility or display, depending on visibility mode.
8444 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8445 * @return {Roo.Element} this
8447 toggle : function(animate){
8448 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
8453 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
8454 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
8455 * @return {Roo.Element} this
8457 setDisplayed : function(value) {
8458 if(typeof value == "boolean"){
8459 value = value ? this.originalDisplay : "none";
8461 this.setStyle("display", value);
8466 * Tries to focus the element. Any exceptions are caught and ignored.
8467 * @return {Roo.Element} this
8469 focus : function() {
8477 * Tries to blur the element. Any exceptions are caught and ignored.
8478 * @return {Roo.Element} this
8488 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
8489 * @param {String/Array} className The CSS class to add, or an array of classes
8490 * @return {Roo.Element} this
8492 addClass : function(className){
8493 if(className instanceof Array){
8494 for(var i = 0, len = className.length; i < len; i++) {
8495 this.addClass(className[i]);
8498 if(className && !this.hasClass(className)){
8499 if (this.dom instanceof SVGElement) {
8500 this.dom.className.baseVal =this.dom.className.baseVal + " " + className;
8502 this.dom.className = this.dom.className + " " + className;
8510 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
8511 * @param {String/Array} className The CSS class to add, or an array of classes
8512 * @return {Roo.Element} this
8514 radioClass : function(className){
8515 var siblings = this.dom.parentNode.childNodes;
8516 for(var i = 0; i < siblings.length; i++) {
8517 var s = siblings[i];
8518 if(s.nodeType == 1){
8519 Roo.get(s).removeClass(className);
8522 this.addClass(className);
8527 * Removes one or more CSS classes from the element.
8528 * @param {String/Array} className The CSS class to remove, or an array of classes
8529 * @return {Roo.Element} this
8531 removeClass : function(className){
8533 var cn = this.dom instanceof SVGElement ? this.dom.className.baseVal : this.dom.className;
8534 if(!className || !cn){
8537 if(className instanceof Array){
8538 for(var i = 0, len = className.length; i < len; i++) {
8539 this.removeClass(className[i]);
8542 if(this.hasClass(className)){
8543 var re = this.classReCache[className];
8545 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
8546 this.classReCache[className] = re;
8548 if (this.dom instanceof SVGElement) {
8549 this.dom.className.baseVal = cn.replace(re, " ");
8551 this.dom.className = cn.replace(re, " ");
8562 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
8563 * @param {String} className The CSS class to toggle
8564 * @return {Roo.Element} this
8566 toggleClass : function(className){
8567 if(this.hasClass(className)){
8568 this.removeClass(className);
8570 this.addClass(className);
8576 * Checks if the specified CSS class exists on this element's DOM node.
8577 * @param {String} className The CSS class to check for
8578 * @return {Boolean} True if the class exists, else false
8580 hasClass : function(className){
8581 if (this.dom instanceof SVGElement) {
8582 return className && (' '+this.dom.className.baseVal +' ').indexOf(' '+className+' ') != -1;
8584 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
8588 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
8589 * @param {String} oldClassName The CSS class to replace
8590 * @param {String} newClassName The replacement CSS class
8591 * @return {Roo.Element} this
8593 replaceClass : function(oldClassName, newClassName){
8594 this.removeClass(oldClassName);
8595 this.addClass(newClassName);
8600 * Returns an object with properties matching the styles requested.
8601 * For example, el.getStyles('color', 'font-size', 'width') might return
8602 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
8603 * @param {String} style1 A style name
8604 * @param {String} style2 A style name
8605 * @param {String} etc.
8606 * @return {Object} The style object
8608 getStyles : function(){
8609 var a = arguments, len = a.length, r = {};
8610 for(var i = 0; i < len; i++){
8611 r[a[i]] = this.getStyle(a[i]);
8617 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
8618 * @param {String} property The style property whose value is returned.
8619 * @return {String} The current value of the style property for this element.
8621 getStyle : function(){
8622 return view && view.getComputedStyle ?
8624 var el = this.dom, v, cs, camel;
8625 if(prop == 'float'){
8628 if(el.style && (v = el.style[prop])){
8631 if(cs = view.getComputedStyle(el, "")){
8632 if(!(camel = propCache[prop])){
8633 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8640 var el = this.dom, v, cs, camel;
8641 if(prop == 'opacity'){
8642 if(typeof el.style.filter == 'string'){
8643 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
8645 var fv = parseFloat(m[1]);
8647 return fv ? fv / 100 : 0;
8652 }else if(prop == 'float'){
8653 prop = "styleFloat";
8655 if(!(camel = propCache[prop])){
8656 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8658 if(v = el.style[camel]){
8661 if(cs = el.currentStyle){
8669 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
8670 * @param {String/Object} property The style property to be set, or an object of multiple styles.
8671 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
8672 * @return {Roo.Element} this
8674 setStyle : function(prop, value){
8675 if(typeof prop == "string"){
8677 if (prop == 'float') {
8678 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
8683 if(!(camel = propCache[prop])){
8684 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8687 if(camel == 'opacity') {
8688 this.setOpacity(value);
8690 this.dom.style[camel] = value;
8693 for(var style in prop){
8694 if(typeof prop[style] != "function"){
8695 this.setStyle(style, prop[style]);
8703 * More flexible version of {@link #setStyle} for setting style properties.
8704 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
8705 * a function which returns such a specification.
8706 * @return {Roo.Element} this
8708 applyStyles : function(style){
8709 Roo.DomHelper.applyStyles(this.dom, style);
8714 * 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).
8715 * @return {Number} The X position of the element
8718 return D.getX(this.dom);
8722 * 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).
8723 * @return {Number} The Y position of the element
8726 return D.getY(this.dom);
8730 * 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).
8731 * @return {Array} The XY position of the element
8734 return D.getXY(this.dom);
8738 * 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).
8739 * @param {Number} The X position of the element
8740 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8741 * @return {Roo.Element} this
8743 setX : function(x, animate){
8745 D.setX(this.dom, x);
8747 this.setXY([x, this.getY()], this.preanim(arguments, 1));
8753 * 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).
8754 * @param {Number} The Y position of the element
8755 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8756 * @return {Roo.Element} this
8758 setY : function(y, animate){
8760 D.setY(this.dom, y);
8762 this.setXY([this.getX(), y], this.preanim(arguments, 1));
8768 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
8769 * @param {String} left The left CSS property value
8770 * @return {Roo.Element} this
8772 setLeft : function(left){
8773 this.setStyle("left", this.addUnits(left));
8778 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
8779 * @param {String} top The top CSS property value
8780 * @return {Roo.Element} this
8782 setTop : function(top){
8783 this.setStyle("top", this.addUnits(top));
8788 * Sets the element's CSS right style.
8789 * @param {String} right The right CSS property value
8790 * @return {Roo.Element} this
8792 setRight : function(right){
8793 this.setStyle("right", this.addUnits(right));
8798 * Sets the element's CSS bottom style.
8799 * @param {String} bottom The bottom CSS property value
8800 * @return {Roo.Element} this
8802 setBottom : function(bottom){
8803 this.setStyle("bottom", this.addUnits(bottom));
8808 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8809 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8810 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
8811 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8812 * @return {Roo.Element} this
8814 setXY : function(pos, animate){
8816 D.setXY(this.dom, pos);
8818 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
8824 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8825 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8826 * @param {Number} x X value for new position (coordinates are page-based)
8827 * @param {Number} y Y value for new position (coordinates are page-based)
8828 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8829 * @return {Roo.Element} this
8831 setLocation : function(x, y, animate){
8832 this.setXY([x, y], this.preanim(arguments, 2));
8837 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8838 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8839 * @param {Number} x X value for new position (coordinates are page-based)
8840 * @param {Number} y Y value for new position (coordinates are page-based)
8841 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8842 * @return {Roo.Element} this
8844 moveTo : function(x, y, animate){
8845 this.setXY([x, y], this.preanim(arguments, 2));
8850 * Returns the region of the given element.
8851 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
8852 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
8854 getRegion : function(){
8855 return D.getRegion(this.dom);
8859 * Returns the offset height of the element
8860 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
8861 * @return {Number} The element's height
8863 getHeight : function(contentHeight){
8864 var h = this.dom.offsetHeight || 0;
8865 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
8869 * Returns the offset width of the element
8870 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
8871 * @return {Number} The element's width
8873 getWidth : function(contentWidth){
8874 var w = this.dom.offsetWidth || 0;
8875 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
8879 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
8880 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
8881 * if a height has not been set using CSS.
8884 getComputedHeight : function(){
8885 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
8887 h = parseInt(this.getStyle('height'), 10) || 0;
8888 if(!this.isBorderBox()){
8889 h += this.getFrameWidth('tb');
8896 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
8897 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
8898 * if a width has not been set using CSS.
8901 getComputedWidth : function(){
8902 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
8904 w = parseInt(this.getStyle('width'), 10) || 0;
8905 if(!this.isBorderBox()){
8906 w += this.getFrameWidth('lr');
8913 * Returns the size of the element.
8914 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
8915 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
8917 getSize : function(contentSize){
8918 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
8922 * Returns the width and height of the viewport.
8923 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
8925 getViewSize : function(){
8926 var d = this.dom, doc = document, aw = 0, ah = 0;
8927 if(d == doc || d == doc.body){
8928 return {width : D.getViewWidth(), height: D.getViewHeight()};
8931 width : d.clientWidth,
8932 height: d.clientHeight
8938 * Returns the value of the "value" attribute
8939 * @param {Boolean} asNumber true to parse the value as a number
8940 * @return {String/Number}
8942 getValue : function(asNumber){
8943 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
8947 adjustWidth : function(width){
8948 if(typeof width == "number"){
8949 if(this.autoBoxAdjust && !this.isBorderBox()){
8950 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8960 adjustHeight : function(height){
8961 if(typeof height == "number"){
8962 if(this.autoBoxAdjust && !this.isBorderBox()){
8963 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8973 * Set the width of the element
8974 * @param {Number} width The new width
8975 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8976 * @return {Roo.Element} this
8978 setWidth : function(width, animate){
8979 width = this.adjustWidth(width);
8981 this.dom.style.width = this.addUnits(width);
8983 this.anim({width: {to: width}}, this.preanim(arguments, 1));
8989 * Set the height of the element
8990 * @param {Number} height The new height
8991 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8992 * @return {Roo.Element} this
8994 setHeight : function(height, animate){
8995 height = this.adjustHeight(height);
8997 this.dom.style.height = this.addUnits(height);
8999 this.anim({height: {to: height}}, this.preanim(arguments, 1));
9005 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
9006 * @param {Number} width The new width
9007 * @param {Number} height The new height
9008 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9009 * @return {Roo.Element} this
9011 setSize : function(width, height, animate){
9012 if(typeof width == "object"){ // in case of object from getSize()
9013 height = width.height; width = width.width;
9015 width = this.adjustWidth(width); height = this.adjustHeight(height);
9017 this.dom.style.width = this.addUnits(width);
9018 this.dom.style.height = this.addUnits(height);
9020 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
9026 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
9027 * @param {Number} x X value for new position (coordinates are page-based)
9028 * @param {Number} y Y value for new position (coordinates are page-based)
9029 * @param {Number} width The new width
9030 * @param {Number} height The new height
9031 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9032 * @return {Roo.Element} this
9034 setBounds : function(x, y, width, height, animate){
9036 this.setSize(width, height);
9037 this.setLocation(x, y);
9039 width = this.adjustWidth(width); height = this.adjustHeight(height);
9040 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
9041 this.preanim(arguments, 4), 'motion');
9047 * 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.
9048 * @param {Roo.lib.Region} region The region to fill
9049 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9050 * @return {Roo.Element} this
9052 setRegion : function(region, animate){
9053 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
9058 * Appends an event handler
9060 * @param {String} eventName The type of event to append
9061 * @param {Function} fn The method the event invokes
9062 * @param {Object} scope (optional) The scope (this object) of the fn
9063 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9065 addListener : function(eventName, fn, scope, options)
9067 if (eventName == 'dblclick') { // doublclick (touchstart) - faked on touch.
9068 this.addListener('touchstart', this.onTapHandler, this);
9071 // we need to handle a special case where dom element is a svg element.
9072 // in this case we do not actua
9077 if (this.dom instanceof SVGElement && !(this.dom instanceof SVGSVGElement)) {
9078 if (typeof(this.listeners[eventName]) == 'undefined') {
9079 this.listeners[eventName] = new Roo.util.Event(this, eventName);
9081 this.listeners[eventName].addListener(fn, scope, options);
9086 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
9091 onTapHandler : function(event)
9093 if(!this.tapedTwice) {
9094 this.tapedTwice = true;
9096 setTimeout( function() {
9097 s.tapedTwice = false;
9101 event.preventDefault();
9102 var revent = new MouseEvent('dblclick', {
9108 this.dom.dispatchEvent(revent);
9109 //action on double tap goes below
9114 * Removes an event handler from this element
9115 * @param {String} eventName the type of event to remove
9116 * @param {Function} fn the method the event invokes
9117 * @param {Function} scope (needed for svg fake listeners)
9118 * @return {Roo.Element} this
9120 removeListener : function(eventName, fn, scope){
9121 Roo.EventManager.removeListener(this.dom, eventName, fn);
9122 if (typeof(this.listeners) == 'undefined' || typeof(this.listeners[eventName]) == 'undefined') {
9125 this.listeners[eventName].removeListener(fn, scope);
9130 * Removes all previous added listeners from this element
9131 * @return {Roo.Element} this
9133 removeAllListeners : function(){
9134 E.purgeElement(this.dom);
9135 this.listeners = {};
9139 relayEvent : function(eventName, observable){
9140 this.on(eventName, function(e){
9141 observable.fireEvent(eventName, e);
9147 * Set the opacity of the element
9148 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
9149 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9150 * @return {Roo.Element} this
9152 setOpacity : function(opacity, animate){
9154 var s = this.dom.style;
9157 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
9158 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
9160 s.opacity = opacity;
9163 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
9169 * Gets the left X coordinate
9170 * @param {Boolean} local True to get the local css position instead of page coordinate
9173 getLeft : function(local){
9177 return parseInt(this.getStyle("left"), 10) || 0;
9182 * Gets the right X coordinate of the element (element X position + element width)
9183 * @param {Boolean} local True to get the local css position instead of page coordinate
9186 getRight : function(local){
9188 return this.getX() + this.getWidth();
9190 return (this.getLeft(true) + this.getWidth()) || 0;
9195 * Gets the top Y coordinate
9196 * @param {Boolean} local True to get the local css position instead of page coordinate
9199 getTop : function(local) {
9203 return parseInt(this.getStyle("top"), 10) || 0;
9208 * Gets the bottom Y coordinate of the element (element Y position + element height)
9209 * @param {Boolean} local True to get the local css position instead of page coordinate
9212 getBottom : function(local){
9214 return this.getY() + this.getHeight();
9216 return (this.getTop(true) + this.getHeight()) || 0;
9221 * Initializes positioning on this element. If a desired position is not passed, it will make the
9222 * the element positioned relative IF it is not already positioned.
9223 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
9224 * @param {Number} zIndex (optional) The zIndex to apply
9225 * @param {Number} x (optional) Set the page X position
9226 * @param {Number} y (optional) Set the page Y position
9228 position : function(pos, zIndex, x, y){
9230 if(this.getStyle('position') == 'static'){
9231 this.setStyle('position', 'relative');
9234 this.setStyle("position", pos);
9237 this.setStyle("z-index", zIndex);
9239 if(x !== undefined && y !== undefined){
9241 }else if(x !== undefined){
9243 }else if(y !== undefined){
9249 * Clear positioning back to the default when the document was loaded
9250 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
9251 * @return {Roo.Element} this
9253 clearPositioning : function(value){
9261 "position" : "static"
9267 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
9268 * snapshot before performing an update and then restoring the element.
9271 getPositioning : function(){
9272 var l = this.getStyle("left");
9273 var t = this.getStyle("top");
9275 "position" : this.getStyle("position"),
9277 "right" : l ? "" : this.getStyle("right"),
9279 "bottom" : t ? "" : this.getStyle("bottom"),
9280 "z-index" : this.getStyle("z-index")
9285 * Gets the width of the border(s) for the specified side(s)
9286 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9287 * passing lr would get the border (l)eft width + the border (r)ight width.
9288 * @return {Number} The width of the sides passed added together
9290 getBorderWidth : function(side){
9291 return this.addStyles(side, El.borders);
9295 * Gets the width of the padding(s) for the specified side(s)
9296 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9297 * passing lr would get the padding (l)eft + the padding (r)ight.
9298 * @return {Number} The padding of the sides passed added together
9300 getPadding : function(side){
9301 return this.addStyles(side, El.paddings);
9305 * Set positioning with an object returned by getPositioning().
9306 * @param {Object} posCfg
9307 * @return {Roo.Element} this
9309 setPositioning : function(pc){
9310 this.applyStyles(pc);
9311 if(pc.right == "auto"){
9312 this.dom.style.right = "";
9314 if(pc.bottom == "auto"){
9315 this.dom.style.bottom = "";
9321 fixDisplay : function(){
9322 if(this.getStyle("display") == "none"){
9323 this.setStyle("visibility", "hidden");
9324 this.setStyle("display", this.originalDisplay); // first try reverting to default
9325 if(this.getStyle("display") == "none"){ // if that fails, default to block
9326 this.setStyle("display", "block");
9332 * Quick set left and top adding default units
9333 * @param {String} left The left CSS property value
9334 * @param {String} top The top CSS property value
9335 * @return {Roo.Element} this
9337 setLeftTop : function(left, top){
9338 this.dom.style.left = this.addUnits(left);
9339 this.dom.style.top = this.addUnits(top);
9344 * Move this element relative to its current position.
9345 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9346 * @param {Number} distance How far to move the element in pixels
9347 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9348 * @return {Roo.Element} this
9350 move : function(direction, distance, animate){
9351 var xy = this.getXY();
9352 direction = direction.toLowerCase();
9356 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
9360 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
9365 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
9370 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
9377 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
9378 * @return {Roo.Element} this
9381 if(!this.isClipped){
9382 this.isClipped = true;
9383 this.originalClip = {
9384 "o": this.getStyle("overflow"),
9385 "x": this.getStyle("overflow-x"),
9386 "y": this.getStyle("overflow-y")
9388 this.setStyle("overflow", "hidden");
9389 this.setStyle("overflow-x", "hidden");
9390 this.setStyle("overflow-y", "hidden");
9396 * Return clipping (overflow) to original clipping before clip() was called
9397 * @return {Roo.Element} this
9399 unclip : function(){
9401 this.isClipped = false;
9402 var o = this.originalClip;
9403 if(o.o){this.setStyle("overflow", o.o);}
9404 if(o.x){this.setStyle("overflow-x", o.x);}
9405 if(o.y){this.setStyle("overflow-y", o.y);}
9412 * Gets the x,y coordinates specified by the anchor position on the element.
9413 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
9414 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
9415 * {width: (target width), height: (target height)} (defaults to the element's current size)
9416 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
9417 * @return {Array} [x, y] An array containing the element's x and y coordinates
9419 getAnchorXY : function(anchor, local, s){
9420 //Passing a different size is useful for pre-calculating anchors,
9421 //especially for anchored animations that change the el size.
9423 var w, h, vp = false;
9426 if(d == document.body || d == document){
9428 w = D.getViewWidth(); h = D.getViewHeight();
9430 w = this.getWidth(); h = this.getHeight();
9433 w = s.width; h = s.height;
9435 var x = 0, y = 0, r = Math.round;
9436 switch((anchor || "tl").toLowerCase()){
9478 var sc = this.getScroll();
9479 return [x + sc.left, y + sc.top];
9481 //Add the element's offset xy
9482 var o = this.getXY();
9483 return [x+o[0], y+o[1]];
9487 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
9488 * supported position values.
9489 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9490 * @param {String} position The position to align to.
9491 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9492 * @return {Array} [x, y]
9494 getAlignToXY : function(el, p, o)
9499 throw "Element.alignTo with an element that doesn't exist";
9501 var c = false; //constrain to viewport
9502 var p1 = "", p2 = "";
9509 }else if(p.indexOf("-") == -1){
9512 p = p.toLowerCase();
9513 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
9515 throw "Element.alignTo with an invalid alignment " + p;
9517 p1 = m[1]; p2 = m[2]; c = !!m[3];
9519 //Subtract the aligned el's internal xy from the target's offset xy
9520 //plus custom offset to get the aligned el's new offset xy
9521 var a1 = this.getAnchorXY(p1, true);
9522 var a2 = el.getAnchorXY(p2, false);
9523 var x = a2[0] - a1[0] + o[0];
9524 var y = a2[1] - a1[1] + o[1];
9526 //constrain the aligned el to viewport if necessary
9527 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
9528 // 5px of margin for ie
9529 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
9531 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
9532 //perpendicular to the vp border, allow the aligned el to slide on that border,
9533 //otherwise swap the aligned el to the opposite border of the target.
9534 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
9535 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
9536 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t") );
9537 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
9540 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
9541 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
9543 if((x+w) > dw + scrollX){
9544 x = swapX ? r.left-w : dw+scrollX-w;
9547 x = swapX ? r.right : scrollX;
9549 if((y+h) > dh + scrollY){
9550 y = swapY ? r.top-h : dh+scrollY-h;
9553 y = swapY ? r.bottom : scrollY;
9560 getConstrainToXY : function(){
9561 var os = {top:0, left:0, bottom:0, right: 0};
9563 return function(el, local, offsets, proposedXY){
9565 offsets = offsets ? Roo.applyIf(offsets, os) : os;
9567 var vw, vh, vx = 0, vy = 0;
9568 if(el.dom == document.body || el.dom == document){
9569 vw = Roo.lib.Dom.getViewWidth();
9570 vh = Roo.lib.Dom.getViewHeight();
9572 vw = el.dom.clientWidth;
9573 vh = el.dom.clientHeight;
9575 var vxy = el.getXY();
9581 var s = el.getScroll();
9583 vx += offsets.left + s.left;
9584 vy += offsets.top + s.top;
9586 vw -= offsets.right;
9587 vh -= offsets.bottom;
9592 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
9593 var x = xy[0], y = xy[1];
9594 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
9596 // only move it if it needs it
9599 // first validate right/bottom
9608 // then make sure top/left isn't negative
9617 return moved ? [x, y] : false;
9622 adjustForConstraints : function(xy, parent, offsets){
9623 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
9627 * Aligns this element with another element relative to the specified anchor points. If the other element is the
9628 * document it aligns it to the viewport.
9629 * The position parameter is optional, and can be specified in any one of the following formats:
9631 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
9632 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
9633 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
9634 * deprecated in favor of the newer two anchor syntax below</i>.</li>
9635 * <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
9636 * element's anchor point, and the second value is used as the target's anchor point.</li>
9638 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
9639 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
9640 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
9641 * that specified in order to enforce the viewport constraints.
9642 * Following are all of the supported anchor positions:
9645 ----- -----------------------------
9646 tl The top left corner (default)
9647 t The center of the top edge
9648 tr The top right corner
9649 l The center of the left edge
9650 c In the center of the element
9651 r The center of the right edge
9652 bl The bottom left corner
9653 b The center of the bottom edge
9654 br The bottom right corner
9658 // align el to other-el using the default positioning ("tl-bl", non-constrained)
9659 el.alignTo("other-el");
9661 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
9662 el.alignTo("other-el", "tr?");
9664 // align the bottom right corner of el with the center left edge of other-el
9665 el.alignTo("other-el", "br-l?");
9667 // align the center of el with the bottom left corner of other-el and
9668 // adjust the x position by -6 pixels (and the y position by 0)
9669 el.alignTo("other-el", "c-bl", [-6, 0]);
9671 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9672 * @param {String} position The position to align to.
9673 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9674 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9675 * @return {Roo.Element} this
9677 alignTo : function(element, position, offsets, animate){
9678 var xy = this.getAlignToXY(element, position, offsets);
9679 this.setXY(xy, this.preanim(arguments, 3));
9684 * Anchors an element to another element and realigns it when the window is resized.
9685 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9686 * @param {String} position The position to align to.
9687 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9688 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
9689 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
9690 * is a number, it is used as the buffer delay (defaults to 50ms).
9691 * @param {Function} callback The function to call after the animation finishes
9692 * @return {Roo.Element} this
9694 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
9695 var action = function(){
9696 this.alignTo(el, alignment, offsets, animate);
9697 Roo.callback(callback, this);
9699 Roo.EventManager.onWindowResize(action, this);
9700 var tm = typeof monitorScroll;
9701 if(tm != 'undefined'){
9702 Roo.EventManager.on(window, 'scroll', action, this,
9703 {buffer: tm == 'number' ? monitorScroll : 50});
9705 action.call(this); // align immediately
9709 * Clears any opacity settings from this element. Required in some cases for IE.
9710 * @return {Roo.Element} this
9712 clearOpacity : function(){
9713 if (window.ActiveXObject) {
9714 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
9715 this.dom.style.filter = "";
9718 this.dom.style.opacity = "";
9719 this.dom.style["-moz-opacity"] = "";
9720 this.dom.style["-khtml-opacity"] = "";
9726 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9727 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9728 * @return {Roo.Element} this
9730 hide : function(animate){
9731 this.setVisible(false, this.preanim(arguments, 0));
9736 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9737 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9738 * @return {Roo.Element} this
9740 show : function(animate){
9741 this.setVisible(true, this.preanim(arguments, 0));
9746 * @private Test if size has a unit, otherwise appends the default
9748 addUnits : function(size){
9749 return Roo.Element.addUnits(size, this.defaultUnit);
9753 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
9754 * @return {Roo.Element} this
9756 beginMeasure : function(){
9758 if(el.offsetWidth || el.offsetHeight){
9759 return this; // offsets work already
9762 var p = this.dom, b = document.body; // start with this element
9763 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
9764 var pe = Roo.get(p);
9765 if(pe.getStyle('display') == 'none'){
9766 changed.push({el: p, visibility: pe.getStyle("visibility")});
9767 p.style.visibility = "hidden";
9768 p.style.display = "block";
9772 this._measureChanged = changed;
9778 * Restores displays to before beginMeasure was called
9779 * @return {Roo.Element} this
9781 endMeasure : function(){
9782 var changed = this._measureChanged;
9784 for(var i = 0, len = changed.length; i < len; i++) {
9786 r.el.style.visibility = r.visibility;
9787 r.el.style.display = "none";
9789 this._measureChanged = null;
9795 * Update the innerHTML of this element, optionally searching for and processing scripts
9796 * @param {String} html The new HTML
9797 * @param {Boolean} loadScripts (optional) true to look for and process scripts
9798 * @param {Function} callback For async script loading you can be noticed when the update completes
9799 * @return {Roo.Element} this
9801 update : function(html, loadScripts, callback){
9802 if(typeof html == "undefined"){
9805 if(loadScripts !== true){
9806 this.dom.innerHTML = html;
9807 if(typeof callback == "function"){
9815 html += '<span id="' + id + '"></span>';
9817 E.onAvailable(id, function(){
9818 var hd = document.getElementsByTagName("head")[0];
9819 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
9820 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
9821 var typeRe = /\stype=([\'\"])(.*?)\1/i;
9824 while(match = re.exec(html)){
9825 var attrs = match[1];
9826 var srcMatch = attrs ? attrs.match(srcRe) : false;
9827 if(srcMatch && srcMatch[2]){
9828 var s = document.createElement("script");
9829 s.src = srcMatch[2];
9830 var typeMatch = attrs.match(typeRe);
9831 if(typeMatch && typeMatch[2]){
9832 s.type = typeMatch[2];
9835 }else if(match[2] && match[2].length > 0){
9836 if(window.execScript) {
9837 window.execScript(match[2]);
9845 window.eval(match[2]);
9849 var el = document.getElementById(id);
9850 if(el){el.parentNode.removeChild(el);}
9851 if(typeof callback == "function"){
9855 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
9860 * Direct access to the UpdateManager update() method (takes the same parameters).
9861 * @param {String/Function} url The url for this request or a function to call to get the url
9862 * @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}
9863 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
9864 * @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.
9865 * @return {Roo.Element} this
9868 var um = this.getUpdateManager();
9869 um.update.apply(um, arguments);
9874 * Gets this element's UpdateManager
9875 * @return {Roo.UpdateManager} The UpdateManager
9877 getUpdateManager : function(){
9878 if(!this.updateManager){
9879 this.updateManager = new Roo.UpdateManager(this);
9881 return this.updateManager;
9885 * Disables text selection for this element (normalized across browsers)
9886 * @return {Roo.Element} this
9888 unselectable : function(){
9889 this.dom.unselectable = "on";
9890 this.swallowEvent("selectstart", true);
9891 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
9892 this.addClass("x-unselectable");
9897 * Calculates the x, y to center this element on the screen
9898 * @return {Array} The x, y values [x, y]
9900 getCenterXY : function(){
9901 return this.getAlignToXY(document, 'c-c');
9905 * Centers the Element in either the viewport, or another Element.
9906 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
9908 center : function(centerIn){
9909 this.alignTo(centerIn || document, 'c-c');
9914 * Tests various css rules/browsers to determine if this element uses a border box
9917 isBorderBox : function(){
9918 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
9922 * Return a box {x, y, width, height} that can be used to set another elements
9923 * size/location to match this element.
9924 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
9925 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
9926 * @return {Object} box An object in the format {x, y, width, height}
9928 getBox : function(contentBox, local){
9933 var left = parseInt(this.getStyle("left"), 10) || 0;
9934 var top = parseInt(this.getStyle("top"), 10) || 0;
9937 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
9939 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
9941 var l = this.getBorderWidth("l")+this.getPadding("l");
9942 var r = this.getBorderWidth("r")+this.getPadding("r");
9943 var t = this.getBorderWidth("t")+this.getPadding("t");
9944 var b = this.getBorderWidth("b")+this.getPadding("b");
9945 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)};
9947 bx.right = bx.x + bx.width;
9948 bx.bottom = bx.y + bx.height;
9953 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
9954 for more information about the sides.
9955 * @param {String} sides
9958 getFrameWidth : function(sides, onlyContentBox){
9959 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
9963 * 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.
9964 * @param {Object} box The box to fill {x, y, width, height}
9965 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
9966 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9967 * @return {Roo.Element} this
9969 setBox : function(box, adjust, animate){
9970 var w = box.width, h = box.height;
9971 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
9972 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
9973 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
9975 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
9980 * Forces the browser to repaint this element
9981 * @return {Roo.Element} this
9983 repaint : function(){
9985 this.addClass("x-repaint");
9986 setTimeout(function(){
9987 Roo.get(dom).removeClass("x-repaint");
9993 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
9994 * then it returns the calculated width of the sides (see getPadding)
9995 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
9996 * @return {Object/Number}
9998 getMargins : function(side){
10001 top: parseInt(this.getStyle("margin-top"), 10) || 0,
10002 left: parseInt(this.getStyle("margin-left"), 10) || 0,
10003 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
10004 right: parseInt(this.getStyle("margin-right"), 10) || 0
10007 return this.addStyles(side, El.margins);
10012 addStyles : function(sides, styles){
10014 for(var i = 0, len = sides.length; i < len; i++){
10015 v = this.getStyle(styles[sides.charAt(i)]);
10017 w = parseInt(v, 10);
10025 * Creates a proxy element of this element
10026 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
10027 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
10028 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
10029 * @return {Roo.Element} The new proxy element
10031 createProxy : function(config, renderTo, matchBox){
10033 renderTo = Roo.getDom(renderTo);
10035 renderTo = document.body;
10037 config = typeof config == "object" ?
10038 config : {tag : "div", cls: config};
10039 var proxy = Roo.DomHelper.append(renderTo, config, true);
10041 proxy.setBox(this.getBox());
10047 * Puts a mask over this element to disable user interaction. Requires core.css.
10048 * This method can only be applied to elements which accept child nodes.
10049 * @param {String} msg (optional) A message to display in the mask
10050 * @param {String} msgCls (optional) A css class to apply to the msg element - use no-spinner to hide the spinner on bootstrap
10051 * @return {Element} The mask element
10053 mask : function(msg, msgCls)
10055 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
10056 this.setStyle("position", "relative");
10059 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
10062 this.addClass("x-masked");
10063 this._mask.setDisplayed(true);
10067 var dom = this.dom;
10068 while (dom && dom.style) {
10069 if (!isNaN(parseInt(dom.style.zIndex))) {
10070 z = Math.max(z, parseInt(dom.style.zIndex));
10072 dom = dom.parentNode;
10074 // if we are masking the body - then it hides everything..
10075 if (this.dom == document.body) {
10077 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
10078 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
10081 if(typeof msg == 'string'){
10082 if(!this._maskMsg){
10083 this._maskMsg = Roo.DomHelper.append(this.dom, {
10084 cls: "roo-el-mask-msg",
10088 cls: 'fa fa-spinner fa-spin'
10096 var mm = this._maskMsg;
10097 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
10098 if (mm.dom.lastChild) { // weird IE issue?
10099 mm.dom.lastChild.innerHTML = msg;
10101 mm.setDisplayed(true);
10103 mm.setStyle('z-index', z + 102);
10105 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
10106 this._mask.setHeight(this.getHeight());
10108 this._mask.setStyle('z-index', z + 100);
10114 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
10115 * it is cached for reuse.
10117 unmask : function(removeEl){
10119 if(removeEl === true){
10120 this._mask.remove();
10123 this._maskMsg.remove();
10124 delete this._maskMsg;
10127 this._mask.setDisplayed(false);
10129 this._maskMsg.setDisplayed(false);
10133 this.removeClass("x-masked");
10137 * Returns true if this element is masked
10138 * @return {Boolean}
10140 isMasked : function(){
10141 return this._mask && this._mask.isVisible();
10145 * Creates an iframe shim for this element to keep selects and other windowed objects from
10147 * @return {Roo.Element} The new shim element
10149 createShim : function(){
10150 var el = document.createElement('iframe');
10151 el.frameBorder = 'no';
10152 el.className = 'roo-shim';
10153 if(Roo.isIE && Roo.isSecure){
10154 el.src = Roo.SSL_SECURE_URL;
10156 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
10157 shim.autoBoxAdjust = false;
10162 * Removes this element from the DOM and deletes it from the cache
10164 remove : function(){
10165 if(this.dom.parentNode){
10166 this.dom.parentNode.removeChild(this.dom);
10168 delete El.cache[this.dom.id];
10172 * Sets up event handlers to add and remove a css class when the mouse is over this element
10173 * @param {String} className
10174 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
10175 * mouseout events for children elements
10176 * @return {Roo.Element} this
10178 addClassOnOver : function(className, preventFlicker){
10179 this.on("mouseover", function(){
10180 Roo.fly(this, '_internal').addClass(className);
10182 var removeFn = function(e){
10183 if(preventFlicker !== true || !e.within(this, true)){
10184 Roo.fly(this, '_internal').removeClass(className);
10187 this.on("mouseout", removeFn, this.dom);
10192 * Sets up event handlers to add and remove a css class when this element has the focus
10193 * @param {String} className
10194 * @return {Roo.Element} this
10196 addClassOnFocus : function(className){
10197 this.on("focus", function(){
10198 Roo.fly(this, '_internal').addClass(className);
10200 this.on("blur", function(){
10201 Roo.fly(this, '_internal').removeClass(className);
10206 * 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)
10207 * @param {String} className
10208 * @return {Roo.Element} this
10210 addClassOnClick : function(className){
10211 var dom = this.dom;
10212 this.on("mousedown", function(){
10213 Roo.fly(dom, '_internal').addClass(className);
10214 var d = Roo.get(document);
10215 var fn = function(){
10216 Roo.fly(dom, '_internal').removeClass(className);
10217 d.removeListener("mouseup", fn);
10219 d.on("mouseup", fn);
10225 * Stops the specified event from bubbling and optionally prevents the default action
10226 * @param {String} eventName
10227 * @param {Boolean} preventDefault (optional) true to prevent the default action too
10228 * @return {Roo.Element} this
10230 swallowEvent : function(eventName, preventDefault){
10231 var fn = function(e){
10232 e.stopPropagation();
10233 if(preventDefault){
10234 e.preventDefault();
10237 if(eventName instanceof Array){
10238 for(var i = 0, len = eventName.length; i < len; i++){
10239 this.on(eventName[i], fn);
10243 this.on(eventName, fn);
10250 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
10253 * Sizes this element to its parent element's dimensions performing
10254 * neccessary box adjustments.
10255 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
10256 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
10257 * @return {Roo.Element} this
10259 fitToParent : function(monitorResize, targetParent) {
10260 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
10261 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
10262 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
10265 var p = Roo.get(targetParent || this.dom.parentNode);
10266 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
10267 if (monitorResize === true) {
10268 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
10269 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
10275 * Gets the next sibling, skipping text nodes
10276 * @return {HTMLElement} The next sibling or null
10278 getNextSibling : function(){
10279 var n = this.dom.nextSibling;
10280 while(n && n.nodeType != 1){
10287 * Gets the previous sibling, skipping text nodes
10288 * @return {HTMLElement} The previous sibling or null
10290 getPrevSibling : function(){
10291 var n = this.dom.previousSibling;
10292 while(n && n.nodeType != 1){
10293 n = n.previousSibling;
10300 * Appends the passed element(s) to this element
10301 * @param {String/HTMLElement/Array/Element/CompositeElement} el
10302 * @return {Roo.Element} this
10304 appendChild: function(el){
10311 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
10312 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
10313 * automatically generated with the specified attributes.
10314 * @param {HTMLElement} insertBefore (optional) a child element of this element
10315 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
10316 * @return {Roo.Element} The new child element
10318 createChild: function(config, insertBefore, returnDom){
10319 config = config || {tag:'div'};
10321 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
10323 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
10327 * Appends this element to the passed element
10328 * @param {String/HTMLElement/Element} el The new parent element
10329 * @return {Roo.Element} this
10331 appendTo: function(el){
10332 el = Roo.getDom(el);
10333 el.appendChild(this.dom);
10338 * Inserts this element before the passed element in the DOM
10339 * @param {String/HTMLElement/Element} el The element to insert before
10340 * @return {Roo.Element} this
10342 insertBefore: function(el){
10343 el = Roo.getDom(el);
10344 el.parentNode.insertBefore(this.dom, el);
10349 * Inserts this element after the passed element in the DOM
10350 * @param {String/HTMLElement/Element} el The element to insert after
10351 * @return {Roo.Element} this
10353 insertAfter: function(el){
10354 el = Roo.getDom(el);
10355 el.parentNode.insertBefore(this.dom, el.nextSibling);
10360 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
10361 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10362 * @return {Roo.Element} The new child
10364 insertFirst: function(el, returnDom){
10366 if(typeof el == 'object' && !el.nodeType){ // dh config
10367 return this.createChild(el, this.dom.firstChild, returnDom);
10369 el = Roo.getDom(el);
10370 this.dom.insertBefore(el, this.dom.firstChild);
10371 return !returnDom ? Roo.get(el) : el;
10376 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
10377 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10378 * @param {String} where (optional) 'before' or 'after' defaults to before
10379 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10380 * @return {Roo.Element} the inserted Element
10382 insertSibling: function(el, where, returnDom){
10383 where = where ? where.toLowerCase() : 'before';
10385 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
10387 if(typeof el == 'object' && !el.nodeType){ // dh config
10388 if(where == 'after' && !this.dom.nextSibling){
10389 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
10391 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
10395 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
10396 where == 'before' ? this.dom : this.dom.nextSibling);
10405 * Creates and wraps this element with another element
10406 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
10407 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10408 * @return {HTMLElement/Element} The newly created wrapper element
10410 wrap: function(config, returnDom){
10412 config = {tag: "div"};
10414 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
10415 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
10420 * Replaces the passed element with this element
10421 * @param {String/HTMLElement/Element} el The element to replace
10422 * @return {Roo.Element} this
10424 replace: function(el){
10426 this.insertBefore(el);
10432 * Inserts an html fragment into this element
10433 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
10434 * @param {String} html The HTML fragment
10435 * @param {Boolean} returnEl True to return an Roo.Element
10436 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
10438 insertHtml : function(where, html, returnEl){
10439 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
10440 return returnEl ? Roo.get(el) : el;
10444 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
10445 * @param {Object} o The object with the attributes
10446 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
10447 * @return {Roo.Element} this
10449 set : function(o, useSet){
10451 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
10452 for(var attr in o){
10453 if(attr == "style" || typeof o[attr] == "function") { continue; }
10455 el.className = o["cls"];
10458 el.setAttribute(attr, o[attr]);
10460 el[attr] = o[attr];
10465 Roo.DomHelper.applyStyles(el, o.style);
10471 * Convenience method for constructing a KeyMap
10472 * @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:
10473 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
10474 * @param {Function} fn The function to call
10475 * @param {Object} scope (optional) The scope of the function
10476 * @return {Roo.KeyMap} The KeyMap created
10478 addKeyListener : function(key, fn, scope){
10480 if(typeof key != "object" || key instanceof Array){
10496 return new Roo.KeyMap(this, config);
10500 * Creates a KeyMap for this element
10501 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
10502 * @return {Roo.KeyMap} The KeyMap created
10504 addKeyMap : function(config){
10505 return new Roo.KeyMap(this, config);
10509 * Returns true if this element is scrollable.
10510 * @return {Boolean}
10512 isScrollable : function(){
10513 var dom = this.dom;
10514 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
10518 * 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().
10519 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
10520 * @param {Number} value The new scroll value
10521 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10522 * @return {Element} this
10525 scrollTo : function(side, value, animate){
10526 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
10527 if(!animate || !A){
10528 this.dom[prop] = value;
10530 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
10531 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
10537 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
10538 * within this element's scrollable range.
10539 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
10540 * @param {Number} distance How far to scroll the element in pixels
10541 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10542 * @return {Boolean} Returns true if a scroll was triggered or false if the element
10543 * was scrolled as far as it could go.
10545 scroll : function(direction, distance, animate){
10546 if(!this.isScrollable()){
10550 var l = el.scrollLeft, t = el.scrollTop;
10551 var w = el.scrollWidth, h = el.scrollHeight;
10552 var cw = el.clientWidth, ch = el.clientHeight;
10553 direction = direction.toLowerCase();
10554 var scrolled = false;
10555 var a = this.preanim(arguments, 2);
10560 var v = Math.min(l + distance, w-cw);
10561 this.scrollTo("left", v, a);
10568 var v = Math.max(l - distance, 0);
10569 this.scrollTo("left", v, a);
10577 var v = Math.max(t - distance, 0);
10578 this.scrollTo("top", v, a);
10586 var v = Math.min(t + distance, h-ch);
10587 this.scrollTo("top", v, a);
10596 * Translates the passed page coordinates into left/top css values for this element
10597 * @param {Number/Array} x The page x or an array containing [x, y]
10598 * @param {Number} y The page y
10599 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
10601 translatePoints : function(x, y){
10602 if(typeof x == 'object' || x instanceof Array){
10603 y = x[1]; x = x[0];
10605 var p = this.getStyle('position');
10606 var o = this.getXY();
10608 var l = parseInt(this.getStyle('left'), 10);
10609 var t = parseInt(this.getStyle('top'), 10);
10612 l = (p == "relative") ? 0 : this.dom.offsetLeft;
10615 t = (p == "relative") ? 0 : this.dom.offsetTop;
10618 return {left: (x - o[0] + l), top: (y - o[1] + t)};
10622 * Returns the current scroll position of the element.
10623 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
10625 getScroll : function(){
10626 var d = this.dom, doc = document;
10627 if(d == doc || d == doc.body){
10628 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
10629 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
10630 return {left: l, top: t};
10632 return {left: d.scrollLeft, top: d.scrollTop};
10637 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
10638 * are convert to standard 6 digit hex color.
10639 * @param {String} attr The css attribute
10640 * @param {String} defaultValue The default value to use when a valid color isn't found
10641 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
10644 getColor : function(attr, defaultValue, prefix){
10645 var v = this.getStyle(attr);
10646 if(!v || v == "transparent" || v == "inherit") {
10647 return defaultValue;
10649 var color = typeof prefix == "undefined" ? "#" : prefix;
10650 if(v.substr(0, 4) == "rgb("){
10651 var rvs = v.slice(4, v.length -1).split(",");
10652 for(var i = 0; i < 3; i++){
10653 var h = parseInt(rvs[i]).toString(16);
10660 if(v.substr(0, 1) == "#"){
10661 if(v.length == 4) {
10662 for(var i = 1; i < 4; i++){
10663 var c = v.charAt(i);
10666 }else if(v.length == 7){
10667 color += v.substr(1);
10671 return(color.length > 5 ? color.toLowerCase() : defaultValue);
10675 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
10676 * gradient background, rounded corners and a 4-way shadow.
10677 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
10678 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
10679 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
10680 * @return {Roo.Element} this
10682 boxWrap : function(cls){
10683 cls = cls || 'x-box';
10684 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
10685 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
10690 * Returns the value of a namespaced attribute from the element's underlying DOM node.
10691 * @param {String} namespace The namespace in which to look for the attribute
10692 * @param {String} name The attribute name
10693 * @return {String} The attribute value
10695 getAttributeNS : Roo.isIE ? function(ns, name){
10697 var type = typeof d[ns+":"+name];
10698 if(type != 'undefined' && type != 'unknown'){
10699 return d[ns+":"+name];
10702 } : function(ns, name){
10704 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
10709 * Sets or Returns the value the dom attribute value
10710 * @param {String|Object} name The attribute name (or object to set multiple attributes)
10711 * @param {String} value (optional) The value to set the attribute to
10712 * @return {String} The attribute value
10714 attr : function(name){
10715 if (arguments.length > 1) {
10716 this.dom.setAttribute(name, arguments[1]);
10717 return arguments[1];
10719 if (typeof(name) == 'object') {
10720 for(var i in name) {
10721 this.attr(i, name[i]);
10727 if (!this.dom.hasAttribute(name)) {
10730 return this.dom.getAttribute(name);
10737 var ep = El.prototype;
10740 * Appends an event handler (Shorthand for addListener)
10741 * @param {String} eventName The type of event to append
10742 * @param {Function} fn The method the event invokes
10743 * @param {Object} scope (optional) The scope (this object) of the fn
10744 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
10747 ep.on = ep.addListener;
10748 // backwards compat
10749 ep.mon = ep.addListener;
10752 * Removes an event handler from this element (shorthand for removeListener)
10753 * @param {String} eventName the type of event to remove
10754 * @param {Function} fn the method the event invokes
10755 * @return {Roo.Element} this
10758 ep.un = ep.removeListener;
10761 * true to automatically adjust width and height settings for box-model issues (default to true)
10763 ep.autoBoxAdjust = true;
10766 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
10769 El.addUnits = function(v, defaultUnit){
10770 if(v === "" || v == "auto"){
10773 if(v === undefined){
10776 if(typeof v == "number" || !El.unitPattern.test(v)){
10777 return v + (defaultUnit || 'px');
10782 // special markup used throughout Roo when box wrapping elements
10783 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>';
10785 * Visibility mode constant - Use visibility to hide element
10791 * Visibility mode constant - Use display to hide element
10797 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
10798 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
10799 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
10811 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10812 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10813 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10814 * @return {Element} The Element object
10817 El.get = function(el){
10819 if(!el){ return null; }
10820 if(typeof el == "string"){ // element id
10821 if(!(elm = document.getElementById(el))){
10824 if(ex = El.cache[el]){
10827 ex = El.cache[el] = new El(elm);
10830 }else if(el.tagName){ // dom element
10834 if(ex = El.cache[id]){
10837 ex = El.cache[id] = new El(el);
10840 }else if(el instanceof El){
10842 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
10843 // catch case where it hasn't been appended
10844 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
10847 }else if(el.isComposite){
10849 }else if(el instanceof Array){
10850 return El.select(el);
10851 }else if(el == document){
10852 // create a bogus element object representing the document object
10854 var f = function(){};
10855 f.prototype = El.prototype;
10857 docEl.dom = document;
10865 El.uncache = function(el){
10866 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
10868 delete El.cache[a[i].id || a[i]];
10874 // Garbage collection - uncache elements/purge listeners on orphaned elements
10875 // so we don't hold a reference and cause the browser to retain them
10876 El.garbageCollect = function(){
10877 if(!Roo.enableGarbageCollector){
10878 clearInterval(El.collectorThread);
10881 for(var eid in El.cache){
10882 var el = El.cache[eid], d = el.dom;
10883 // -------------------------------------------------------
10884 // Determining what is garbage:
10885 // -------------------------------------------------------
10887 // dom node is null, definitely garbage
10888 // -------------------------------------------------------
10890 // no parentNode == direct orphan, definitely garbage
10891 // -------------------------------------------------------
10892 // !d.offsetParent && !document.getElementById(eid)
10893 // display none elements have no offsetParent so we will
10894 // also try to look it up by it's id. However, check
10895 // offsetParent first so we don't do unneeded lookups.
10896 // This enables collection of elements that are not orphans
10897 // directly, but somewhere up the line they have an orphan
10899 // -------------------------------------------------------
10900 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
10901 delete El.cache[eid];
10902 if(d && Roo.enableListenerCollection){
10908 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
10912 El.Flyweight = function(dom){
10915 El.Flyweight.prototype = El.prototype;
10917 El._flyweights = {};
10919 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10920 * the dom node can be overwritten by other code.
10921 * @param {String/HTMLElement} el The dom node or id
10922 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10923 * prevent conflicts (e.g. internally Roo uses "_internal")
10925 * @return {Element} The shared Element object
10927 El.fly = function(el, named){
10928 named = named || '_global';
10929 el = Roo.getDom(el);
10933 if(!El._flyweights[named]){
10934 El._flyweights[named] = new El.Flyweight();
10936 El._flyweights[named].dom = el;
10937 return El._flyweights[named];
10941 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10942 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10943 * Shorthand of {@link Roo.Element#get}
10944 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10945 * @return {Element} The Element object
10951 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10952 * the dom node can be overwritten by other code.
10953 * Shorthand of {@link Roo.Element#fly}
10954 * @param {String/HTMLElement} el The dom node or id
10955 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10956 * prevent conflicts (e.g. internally Roo uses "_internal")
10958 * @return {Element} The shared Element object
10964 // speedy lookup for elements never to box adjust
10965 var noBoxAdjust = Roo.isStrict ? {
10968 input:1, select:1, textarea:1
10970 if(Roo.isIE || Roo.isGecko){
10971 noBoxAdjust['button'] = 1;
10975 Roo.EventManager.on(window, 'unload', function(){
10977 delete El._flyweights;
10985 Roo.Element.selectorFunction = Roo.DomQuery.select;
10988 Roo.Element.select = function(selector, unique, root){
10990 if(typeof selector == "string"){
10991 els = Roo.Element.selectorFunction(selector, root);
10992 }else if(selector.length !== undefined){
10995 throw "Invalid selector";
10997 if(unique === true){
10998 return new Roo.CompositeElement(els);
11000 return new Roo.CompositeElementLite(els);
11004 * Selects elements based on the passed CSS selector to enable working on them as 1.
11005 * @param {String/Array} selector The CSS selector or an array of elements
11006 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
11007 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
11008 * @return {CompositeElementLite/CompositeElement}
11012 Roo.select = Roo.Element.select;
11029 * Ext JS Library 1.1.1
11030 * Copyright(c) 2006-2007, Ext JS, LLC.
11032 * Originally Released Under LGPL - original licence link has changed is not relivant.
11035 * <script type="text/javascript">
11040 //Notifies Element that fx methods are available
11041 Roo.enableFx = true;
11045 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
11046 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
11047 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
11048 * Element effects to work.</p><br/>
11050 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
11051 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
11052 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
11053 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
11054 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
11055 * expected results and should be done with care.</p><br/>
11057 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
11058 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
11061 ----- -----------------------------
11062 tl The top left corner
11063 t The center of the top edge
11064 tr The top right corner
11065 l The center of the left edge
11066 r The center of the right edge
11067 bl The bottom left corner
11068 b The center of the bottom edge
11069 br The bottom right corner
11071 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
11072 * below are common options that can be passed to any Fx method.</b>
11073 * @cfg {Function} callback A function called when the effect is finished
11074 * @cfg {Object} scope The scope of the effect function
11075 * @cfg {String} easing A valid Easing value for the effect
11076 * @cfg {String} afterCls A css class to apply after the effect
11077 * @cfg {Number} duration The length of time (in seconds) that the effect should last
11078 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
11079 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
11080 * effects that end with the element being visually hidden, ignored otherwise)
11081 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
11082 * a function which returns such a specification that will be applied to the Element after the effect finishes
11083 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
11084 * @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
11085 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
11089 * Slides the element into view. An anchor point can be optionally passed to set the point of
11090 * origin for the slide effect. This function automatically handles wrapping the element with
11091 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11094 // default: slide the element in from the top
11097 // custom: slide the element in from the right with a 2-second duration
11098 el.slideIn('r', { duration: 2 });
11100 // common config options shown with default values
11106 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11107 * @param {Object} options (optional) Object literal with any of the Fx config options
11108 * @return {Roo.Element} The Element
11110 slideIn : function(anchor, o){
11111 var el = this.getFxEl();
11114 el.queueFx(o, function(){
11116 anchor = anchor || "t";
11118 // fix display to visibility
11121 // restore values after effect
11122 var r = this.getFxRestore();
11123 var b = this.getBox();
11124 // fixed size for slide
11128 var wrap = this.fxWrap(r.pos, o, "hidden");
11130 var st = this.dom.style;
11131 st.visibility = "visible";
11132 st.position = "absolute";
11134 // clear out temp styles after slide and unwrap
11135 var after = function(){
11136 el.fxUnwrap(wrap, r.pos, o);
11137 st.width = r.width;
11138 st.height = r.height;
11141 // time to calc the positions
11142 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
11144 switch(anchor.toLowerCase()){
11146 wrap.setSize(b.width, 0);
11147 st.left = st.bottom = "0";
11151 wrap.setSize(0, b.height);
11152 st.right = st.top = "0";
11156 wrap.setSize(0, b.height);
11157 wrap.setX(b.right);
11158 st.left = st.top = "0";
11159 a = {width: bw, points: pt};
11162 wrap.setSize(b.width, 0);
11163 wrap.setY(b.bottom);
11164 st.left = st.top = "0";
11165 a = {height: bh, points: pt};
11168 wrap.setSize(0, 0);
11169 st.right = st.bottom = "0";
11170 a = {width: bw, height: bh};
11173 wrap.setSize(0, 0);
11174 wrap.setY(b.y+b.height);
11175 st.right = st.top = "0";
11176 a = {width: bw, height: bh, points: pt};
11179 wrap.setSize(0, 0);
11180 wrap.setXY([b.right, b.bottom]);
11181 st.left = st.top = "0";
11182 a = {width: bw, height: bh, points: pt};
11185 wrap.setSize(0, 0);
11186 wrap.setX(b.x+b.width);
11187 st.left = st.bottom = "0";
11188 a = {width: bw, height: bh, points: pt};
11191 this.dom.style.visibility = "visible";
11194 arguments.callee.anim = wrap.fxanim(a,
11204 * Slides the element out of view. An anchor point can be optionally passed to set the end point
11205 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
11206 * 'hidden') but block elements will still take up space in the document. The element must be removed
11207 * from the DOM using the 'remove' config option if desired. This function automatically handles
11208 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11211 // default: slide the element out to the top
11214 // custom: slide the element out to the right with a 2-second duration
11215 el.slideOut('r', { duration: 2 });
11217 // common config options shown with default values
11225 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11226 * @param {Object} options (optional) Object literal with any of the Fx config options
11227 * @return {Roo.Element} The Element
11229 slideOut : function(anchor, o){
11230 var el = this.getFxEl();
11233 el.queueFx(o, function(){
11235 anchor = anchor || "t";
11237 // restore values after effect
11238 var r = this.getFxRestore();
11240 var b = this.getBox();
11241 // fixed size for slide
11245 var wrap = this.fxWrap(r.pos, o, "visible");
11247 var st = this.dom.style;
11248 st.visibility = "visible";
11249 st.position = "absolute";
11253 var after = function(){
11255 el.setDisplayed(false);
11260 el.fxUnwrap(wrap, r.pos, o);
11262 st.width = r.width;
11263 st.height = r.height;
11268 var a, zero = {to: 0};
11269 switch(anchor.toLowerCase()){
11271 st.left = st.bottom = "0";
11272 a = {height: zero};
11275 st.right = st.top = "0";
11279 st.left = st.top = "0";
11280 a = {width: zero, points: {to:[b.right, b.y]}};
11283 st.left = st.top = "0";
11284 a = {height: zero, points: {to:[b.x, b.bottom]}};
11287 st.right = st.bottom = "0";
11288 a = {width: zero, height: zero};
11291 st.right = st.top = "0";
11292 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
11295 st.left = st.top = "0";
11296 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
11299 st.left = st.bottom = "0";
11300 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
11304 arguments.callee.anim = wrap.fxanim(a,
11314 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
11315 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
11316 * The element must be removed from the DOM using the 'remove' config option if desired.
11322 // common config options shown with default values
11330 * @param {Object} options (optional) Object literal with any of the Fx config options
11331 * @return {Roo.Element} The Element
11333 puff : function(o){
11334 var el = this.getFxEl();
11337 el.queueFx(o, function(){
11338 this.clearOpacity();
11341 // restore values after effect
11342 var r = this.getFxRestore();
11343 var st = this.dom.style;
11345 var after = function(){
11347 el.setDisplayed(false);
11354 el.setPositioning(r.pos);
11355 st.width = r.width;
11356 st.height = r.height;
11361 var width = this.getWidth();
11362 var height = this.getHeight();
11364 arguments.callee.anim = this.fxanim({
11365 width : {to: this.adjustWidth(width * 2)},
11366 height : {to: this.adjustHeight(height * 2)},
11367 points : {by: [-(width * .5), -(height * .5)]},
11369 fontSize: {to:200, unit: "%"}
11380 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
11381 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
11382 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
11388 // all config options shown with default values
11396 * @param {Object} options (optional) Object literal with any of the Fx config options
11397 * @return {Roo.Element} The Element
11399 switchOff : function(o){
11400 var el = this.getFxEl();
11403 el.queueFx(o, function(){
11404 this.clearOpacity();
11407 // restore values after effect
11408 var r = this.getFxRestore();
11409 var st = this.dom.style;
11411 var after = function(){
11413 el.setDisplayed(false);
11419 el.setPositioning(r.pos);
11420 st.width = r.width;
11421 st.height = r.height;
11426 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
11427 this.clearOpacity();
11431 points:{by:[0, this.getHeight() * .5]}
11432 }, o, 'motion', 0.3, 'easeIn', after);
11433 }).defer(100, this);
11440 * Highlights the Element by setting a color (applies to the background-color by default, but can be
11441 * changed using the "attr" config option) and then fading back to the original color. If no original
11442 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
11445 // default: highlight background to yellow
11448 // custom: highlight foreground text to blue for 2 seconds
11449 el.highlight("0000ff", { attr: 'color', duration: 2 });
11451 // common config options shown with default values
11452 el.highlight("ffff9c", {
11453 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
11454 endColor: (current color) or "ffffff",
11459 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
11460 * @param {Object} options (optional) Object literal with any of the Fx config options
11461 * @return {Roo.Element} The Element
11463 highlight : function(color, o){
11464 var el = this.getFxEl();
11467 el.queueFx(o, function(){
11468 color = color || "ffff9c";
11469 attr = o.attr || "backgroundColor";
11471 this.clearOpacity();
11474 var origColor = this.getColor(attr);
11475 var restoreColor = this.dom.style[attr];
11476 endColor = (o.endColor || origColor) || "ffffff";
11478 var after = function(){
11479 el.dom.style[attr] = restoreColor;
11484 a[attr] = {from: color, to: endColor};
11485 arguments.callee.anim = this.fxanim(a,
11495 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
11498 // default: a single light blue ripple
11501 // custom: 3 red ripples lasting 3 seconds total
11502 el.frame("ff0000", 3, { duration: 3 });
11504 // common config options shown with default values
11505 el.frame("C3DAF9", 1, {
11506 duration: 1 //duration of entire animation (not each individual ripple)
11507 // Note: Easing is not configurable and will be ignored if included
11510 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
11511 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
11512 * @param {Object} options (optional) Object literal with any of the Fx config options
11513 * @return {Roo.Element} The Element
11515 frame : function(color, count, o){
11516 var el = this.getFxEl();
11519 el.queueFx(o, function(){
11520 color = color || "#C3DAF9";
11521 if(color.length == 6){
11522 color = "#" + color;
11524 count = count || 1;
11525 duration = o.duration || 1;
11528 var b = this.getBox();
11529 var animFn = function(){
11530 var proxy = this.createProxy({
11533 visbility:"hidden",
11534 position:"absolute",
11535 "z-index":"35000", // yee haw
11536 border:"0px solid " + color
11539 var scale = Roo.isBorderBox ? 2 : 1;
11541 top:{from:b.y, to:b.y - 20},
11542 left:{from:b.x, to:b.x - 20},
11543 borderWidth:{from:0, to:10},
11544 opacity:{from:1, to:0},
11545 height:{from:b.height, to:(b.height + (20*scale))},
11546 width:{from:b.width, to:(b.width + (20*scale))}
11547 }, duration, function(){
11551 animFn.defer((duration/2)*1000, this);
11562 * Creates a pause before any subsequent queued effects begin. If there are
11563 * no effects queued after the pause it will have no effect.
11568 * @param {Number} seconds The length of time to pause (in seconds)
11569 * @return {Roo.Element} The Element
11571 pause : function(seconds){
11572 var el = this.getFxEl();
11575 el.queueFx(o, function(){
11576 setTimeout(function(){
11578 }, seconds * 1000);
11584 * Fade an element in (from transparent to opaque). The ending opacity can be specified
11585 * using the "endOpacity" config option.
11588 // default: fade in from opacity 0 to 100%
11591 // custom: fade in from opacity 0 to 75% over 2 seconds
11592 el.fadeIn({ endOpacity: .75, duration: 2});
11594 // common config options shown with default values
11596 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
11601 * @param {Object} options (optional) Object literal with any of the Fx config options
11602 * @return {Roo.Element} The Element
11604 fadeIn : function(o){
11605 var el = this.getFxEl();
11607 el.queueFx(o, function(){
11608 this.setOpacity(0);
11610 this.dom.style.visibility = 'visible';
11611 var to = o.endOpacity || 1;
11612 arguments.callee.anim = this.fxanim({opacity:{to:to}},
11613 o, null, .5, "easeOut", function(){
11615 this.clearOpacity();
11624 * Fade an element out (from opaque to transparent). The ending opacity can be specified
11625 * using the "endOpacity" config option.
11628 // default: fade out from the element's current opacity to 0
11631 // custom: fade out from the element's current opacity to 25% over 2 seconds
11632 el.fadeOut({ endOpacity: .25, duration: 2});
11634 // common config options shown with default values
11636 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
11643 * @param {Object} options (optional) Object literal with any of the Fx config options
11644 * @return {Roo.Element} The Element
11646 fadeOut : function(o){
11647 var el = this.getFxEl();
11649 el.queueFx(o, function(){
11650 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
11651 o, null, .5, "easeOut", function(){
11652 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
11653 this.dom.style.display = "none";
11655 this.dom.style.visibility = "hidden";
11657 this.clearOpacity();
11665 * Animates the transition of an element's dimensions from a starting height/width
11666 * to an ending height/width.
11669 // change height and width to 100x100 pixels
11670 el.scale(100, 100);
11672 // common config options shown with default values. The height and width will default to
11673 // the element's existing values if passed as null.
11676 [element's height], {
11681 * @param {Number} width The new width (pass undefined to keep the original width)
11682 * @param {Number} height The new height (pass undefined to keep the original height)
11683 * @param {Object} options (optional) Object literal with any of the Fx config options
11684 * @return {Roo.Element} The Element
11686 scale : function(w, h, o){
11687 this.shift(Roo.apply({}, o, {
11695 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
11696 * Any of these properties not specified in the config object will not be changed. This effect
11697 * requires that at least one new dimension, position or opacity setting must be passed in on
11698 * the config object in order for the function to have any effect.
11701 // slide the element horizontally to x position 200 while changing the height and opacity
11702 el.shift({ x: 200, height: 50, opacity: .8 });
11704 // common config options shown with default values.
11706 width: [element's width],
11707 height: [element's height],
11708 x: [element's x position],
11709 y: [element's y position],
11710 opacity: [element's opacity],
11715 * @param {Object} options Object literal with any of the Fx config options
11716 * @return {Roo.Element} The Element
11718 shift : function(o){
11719 var el = this.getFxEl();
11721 el.queueFx(o, function(){
11722 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
11723 if(w !== undefined){
11724 a.width = {to: this.adjustWidth(w)};
11726 if(h !== undefined){
11727 a.height = {to: this.adjustHeight(h)};
11729 if(x !== undefined || y !== undefined){
11731 x !== undefined ? x : this.getX(),
11732 y !== undefined ? y : this.getY()
11735 if(op !== undefined){
11736 a.opacity = {to: op};
11738 if(o.xy !== undefined){
11739 a.points = {to: o.xy};
11741 arguments.callee.anim = this.fxanim(a,
11742 o, 'motion', .35, "easeOut", function(){
11750 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
11751 * ending point of the effect.
11754 // default: slide the element downward while fading out
11757 // custom: slide the element out to the right with a 2-second duration
11758 el.ghost('r', { duration: 2 });
11760 // common config options shown with default values
11768 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
11769 * @param {Object} options (optional) Object literal with any of the Fx config options
11770 * @return {Roo.Element} The Element
11772 ghost : function(anchor, o){
11773 var el = this.getFxEl();
11776 el.queueFx(o, function(){
11777 anchor = anchor || "b";
11779 // restore values after effect
11780 var r = this.getFxRestore();
11781 var w = this.getWidth(),
11782 h = this.getHeight();
11784 var st = this.dom.style;
11786 var after = function(){
11788 el.setDisplayed(false);
11794 el.setPositioning(r.pos);
11795 st.width = r.width;
11796 st.height = r.height;
11801 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
11802 switch(anchor.toLowerCase()){
11829 arguments.callee.anim = this.fxanim(a,
11839 * Ensures that all effects queued after syncFx is called on the element are
11840 * run concurrently. This is the opposite of {@link #sequenceFx}.
11841 * @return {Roo.Element} The Element
11843 syncFx : function(){
11844 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11853 * Ensures that all effects queued after sequenceFx is called on the element are
11854 * run in sequence. This is the opposite of {@link #syncFx}.
11855 * @return {Roo.Element} The Element
11857 sequenceFx : function(){
11858 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11860 concurrent : false,
11867 nextFx : function(){
11868 var ef = this.fxQueue[0];
11875 * Returns true if the element has any effects actively running or queued, else returns false.
11876 * @return {Boolean} True if element has active effects, else false
11878 hasActiveFx : function(){
11879 return this.fxQueue && this.fxQueue[0];
11883 * Stops any running effects and clears the element's internal effects queue if it contains
11884 * any additional effects that haven't started yet.
11885 * @return {Roo.Element} The Element
11887 stopFx : function(){
11888 if(this.hasActiveFx()){
11889 var cur = this.fxQueue[0];
11890 if(cur && cur.anim && cur.anim.isAnimated()){
11891 this.fxQueue = [cur]; // clear out others
11892 cur.anim.stop(true);
11899 beforeFx : function(o){
11900 if(this.hasActiveFx() && !o.concurrent){
11911 * Returns true if the element is currently blocking so that no other effect can be queued
11912 * until this effect is finished, else returns false if blocking is not set. This is commonly
11913 * used to ensure that an effect initiated by a user action runs to completion prior to the
11914 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
11915 * @return {Boolean} True if blocking, else false
11917 hasFxBlock : function(){
11918 var q = this.fxQueue;
11919 return q && q[0] && q[0].block;
11923 queueFx : function(o, fn){
11927 if(!this.hasFxBlock()){
11928 Roo.applyIf(o, this.fxDefaults);
11930 var run = this.beforeFx(o);
11931 fn.block = o.block;
11932 this.fxQueue.push(fn);
11944 fxWrap : function(pos, o, vis){
11946 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
11949 wrapXY = this.getXY();
11951 var div = document.createElement("div");
11952 div.style.visibility = vis;
11953 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
11954 wrap.setPositioning(pos);
11955 if(wrap.getStyle("position") == "static"){
11956 wrap.position("relative");
11958 this.clearPositioning('auto');
11960 wrap.dom.appendChild(this.dom);
11962 wrap.setXY(wrapXY);
11969 fxUnwrap : function(wrap, pos, o){
11970 this.clearPositioning();
11971 this.setPositioning(pos);
11973 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
11979 getFxRestore : function(){
11980 var st = this.dom.style;
11981 return {pos: this.getPositioning(), width: st.width, height : st.height};
11985 afterFx : function(o){
11987 this.applyStyles(o.afterStyle);
11990 this.addClass(o.afterCls);
11992 if(o.remove === true){
11995 Roo.callback(o.callback, o.scope, [this]);
11997 this.fxQueue.shift();
12003 getFxEl : function(){ // support for composite element fx
12004 return Roo.get(this.dom);
12008 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
12009 animType = animType || 'run';
12011 var anim = Roo.lib.Anim[animType](
12013 (opt.duration || defaultDur) || .35,
12014 (opt.easing || defaultEase) || 'easeOut',
12016 Roo.callback(cb, this);
12025 // backwords compat
12026 Roo.Fx.resize = Roo.Fx.scale;
12028 //When included, Roo.Fx is automatically applied to Element so that all basic
12029 //effects are available directly via the Element API
12030 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
12032 * Ext JS Library 1.1.1
12033 * Copyright(c) 2006-2007, Ext JS, LLC.
12035 * Originally Released Under LGPL - original licence link has changed is not relivant.
12038 * <script type="text/javascript">
12043 * @class Roo.CompositeElement
12044 * Standard composite class. Creates a Roo.Element for every element in the collection.
12046 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12047 * actions will be performed on all the elements in this collection.</b>
12049 * All methods return <i>this</i> and can be chained.
12051 var els = Roo.select("#some-el div.some-class", true);
12052 // or select directly from an existing element
12053 var el = Roo.get('some-el');
12054 el.select('div.some-class', true);
12056 els.setWidth(100); // all elements become 100 width
12057 els.hide(true); // all elements fade out and hide
12059 els.setWidth(100).hide(true);
12062 Roo.CompositeElement = function(els){
12063 this.elements = [];
12064 this.addElements(els);
12066 Roo.CompositeElement.prototype = {
12068 addElements : function(els){
12072 if(typeof els == "string"){
12073 els = Roo.Element.selectorFunction(els);
12075 var yels = this.elements;
12076 var index = yels.length-1;
12077 for(var i = 0, len = els.length; i < len; i++) {
12078 yels[++index] = Roo.get(els[i]);
12084 * Clears this composite and adds the elements returned by the passed selector.
12085 * @param {String/Array} els A string CSS selector, an array of elements or an element
12086 * @return {CompositeElement} this
12088 fill : function(els){
12089 this.elements = [];
12095 * Filters this composite to only elements that match the passed selector.
12096 * @param {String} selector A string CSS selector
12097 * @param {Boolean} inverse return inverse filter (not matches)
12098 * @return {CompositeElement} this
12100 filter : function(selector, inverse){
12102 inverse = inverse || false;
12103 this.each(function(el){
12104 var match = inverse ? !el.is(selector) : el.is(selector);
12106 els[els.length] = el.dom;
12113 invoke : function(fn, args){
12114 var els = this.elements;
12115 for(var i = 0, len = els.length; i < len; i++) {
12116 Roo.Element.prototype[fn].apply(els[i], args);
12121 * Adds elements to this composite.
12122 * @param {String/Array} els A string CSS selector, an array of elements or an element
12123 * @return {CompositeElement} this
12125 add : function(els){
12126 if(typeof els == "string"){
12127 this.addElements(Roo.Element.selectorFunction(els));
12128 }else if(els.length !== undefined){
12129 this.addElements(els);
12131 this.addElements([els]);
12136 * Calls the passed function passing (el, this, index) for each element in this composite.
12137 * @param {Function} fn The function to call
12138 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12139 * @return {CompositeElement} this
12141 each : function(fn, scope){
12142 var els = this.elements;
12143 for(var i = 0, len = els.length; i < len; i++){
12144 if(fn.call(scope || els[i], els[i], this, i) === false) {
12152 * Returns the Element object at the specified index
12153 * @param {Number} index
12154 * @return {Roo.Element}
12156 item : function(index){
12157 return this.elements[index] || null;
12161 * Returns the first Element
12162 * @return {Roo.Element}
12164 first : function(){
12165 return this.item(0);
12169 * Returns the last Element
12170 * @return {Roo.Element}
12173 return this.item(this.elements.length-1);
12177 * Returns the number of elements in this composite
12180 getCount : function(){
12181 return this.elements.length;
12185 * Returns true if this composite contains the passed element
12188 contains : function(el){
12189 return this.indexOf(el) !== -1;
12193 * Returns true if this composite contains the passed element
12196 indexOf : function(el){
12197 return this.elements.indexOf(Roo.get(el));
12202 * Removes the specified element(s).
12203 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
12204 * or an array of any of those.
12205 * @param {Boolean} removeDom (optional) True to also remove the element from the document
12206 * @return {CompositeElement} this
12208 removeElement : function(el, removeDom){
12209 if(el instanceof Array){
12210 for(var i = 0, len = el.length; i < len; i++){
12211 this.removeElement(el[i]);
12215 var index = typeof el == 'number' ? el : this.indexOf(el);
12218 var d = this.elements[index];
12222 d.parentNode.removeChild(d);
12225 this.elements.splice(index, 1);
12231 * Replaces the specified element with the passed element.
12232 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
12234 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
12235 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
12236 * @return {CompositeElement} this
12238 replaceElement : function(el, replacement, domReplace){
12239 var index = typeof el == 'number' ? el : this.indexOf(el);
12242 this.elements[index].replaceWith(replacement);
12244 this.elements.splice(index, 1, Roo.get(replacement))
12251 * Removes all elements.
12253 clear : function(){
12254 this.elements = [];
12258 Roo.CompositeElement.createCall = function(proto, fnName){
12259 if(!proto[fnName]){
12260 proto[fnName] = function(){
12261 return this.invoke(fnName, arguments);
12265 for(var fnName in Roo.Element.prototype){
12266 if(typeof Roo.Element.prototype[fnName] == "function"){
12267 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
12273 * Ext JS Library 1.1.1
12274 * Copyright(c) 2006-2007, Ext JS, LLC.
12276 * Originally Released Under LGPL - original licence link has changed is not relivant.
12279 * <script type="text/javascript">
12283 * @class Roo.CompositeElementLite
12284 * @extends Roo.CompositeElement
12285 * Flyweight composite class. Reuses the same Roo.Element for element operations.
12287 var els = Roo.select("#some-el div.some-class");
12288 // or select directly from an existing element
12289 var el = Roo.get('some-el');
12290 el.select('div.some-class');
12292 els.setWidth(100); // all elements become 100 width
12293 els.hide(true); // all elements fade out and hide
12295 els.setWidth(100).hide(true);
12296 </code></pre><br><br>
12297 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12298 * actions will be performed on all the elements in this collection.</b>
12300 Roo.CompositeElementLite = function(els){
12301 Roo.CompositeElementLite.superclass.constructor.call(this, els);
12302 this.el = new Roo.Element.Flyweight();
12304 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
12305 addElements : function(els){
12307 if(els instanceof Array){
12308 this.elements = this.elements.concat(els);
12310 var yels = this.elements;
12311 var index = yels.length-1;
12312 for(var i = 0, len = els.length; i < len; i++) {
12313 yels[++index] = els[i];
12319 invoke : function(fn, args){
12320 var els = this.elements;
12322 for(var i = 0, len = els.length; i < len; i++) {
12324 Roo.Element.prototype[fn].apply(el, args);
12329 * Returns a flyweight Element of the dom element object at the specified index
12330 * @param {Number} index
12331 * @return {Roo.Element}
12333 item : function(index){
12334 if(!this.elements[index]){
12337 this.el.dom = this.elements[index];
12341 // fixes scope with flyweight
12342 addListener : function(eventName, handler, scope, opt){
12343 var els = this.elements;
12344 for(var i = 0, len = els.length; i < len; i++) {
12345 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
12351 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
12352 * passed is the flyweight (shared) Roo.Element instance, so if you require a
12353 * a reference to the dom node, use el.dom.</b>
12354 * @param {Function} fn The function to call
12355 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12356 * @return {CompositeElement} this
12358 each : function(fn, scope){
12359 var els = this.elements;
12361 for(var i = 0, len = els.length; i < len; i++){
12363 if(fn.call(scope || el, el, this, i) === false){
12370 indexOf : function(el){
12371 return this.elements.indexOf(Roo.getDom(el));
12374 replaceElement : function(el, replacement, domReplace){
12375 var index = typeof el == 'number' ? el : this.indexOf(el);
12377 replacement = Roo.getDom(replacement);
12379 var d = this.elements[index];
12380 d.parentNode.insertBefore(replacement, d);
12381 d.parentNode.removeChild(d);
12383 this.elements.splice(index, 1, replacement);
12388 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
12392 * Ext JS Library 1.1.1
12393 * Copyright(c) 2006-2007, Ext JS, LLC.
12395 * Originally Released Under LGPL - original licence link has changed is not relivant.
12398 * <script type="text/javascript">
12404 * @class Roo.data.Connection
12405 * @extends Roo.util.Observable
12406 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
12407 * either to a configured URL, or to a URL specified at request time.
12409 * Requests made by this class are asynchronous, and will return immediately. No data from
12410 * the server will be available to the statement immediately following the {@link #request} call.
12411 * To process returned data, use a callback in the request options object, or an event listener.
12413 * Note: If you are doing a file upload, you will not get a normal response object sent back to
12414 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
12415 * The response object is created using the innerHTML of the IFRAME's document as the responseText
12416 * property and, if present, the IFRAME's XML document as the responseXML property.
12418 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
12419 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
12420 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
12421 * standard DOM methods.
12423 * @param {Object} config a configuration object.
12425 Roo.data.Connection = function(config){
12426 Roo.apply(this, config);
12429 * @event beforerequest
12430 * Fires before a network request is made to retrieve a data object.
12431 * @param {Connection} conn This Connection object.
12432 * @param {Object} options The options config object passed to the {@link #request} method.
12434 "beforerequest" : true,
12436 * @event requestcomplete
12437 * Fires if the request was successfully completed.
12438 * @param {Connection} conn This Connection object.
12439 * @param {Object} response The XHR object containing the response data.
12440 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12441 * @param {Object} options The options config object passed to the {@link #request} method.
12443 "requestcomplete" : true,
12445 * @event requestexception
12446 * Fires if an error HTTP status was returned from the server.
12447 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
12448 * @param {Connection} conn This Connection object.
12449 * @param {Object} response The XHR object containing the response data.
12450 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12451 * @param {Object} options The options config object passed to the {@link #request} method.
12453 "requestexception" : true
12455 Roo.data.Connection.superclass.constructor.call(this);
12458 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
12460 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12463 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12464 * extra parameters to each request made by this object. (defaults to undefined)
12467 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12468 * to each request made by this object. (defaults to undefined)
12471 * @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)
12474 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12478 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12484 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12487 disableCaching: true,
12490 * Sends an HTTP request to a remote server.
12491 * @param {Object} options An object which may contain the following properties:<ul>
12492 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
12493 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
12494 * request, a url encoded string or a function to call to get either.</li>
12495 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
12496 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
12497 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
12498 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
12499 * <li>options {Object} The parameter to the request call.</li>
12500 * <li>success {Boolean} True if the request succeeded.</li>
12501 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12503 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
12504 * The callback is passed the following parameters:<ul>
12505 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12506 * <li>options {Object} The parameter to the request call.</li>
12508 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
12509 * The callback is passed the following parameters:<ul>
12510 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12511 * <li>options {Object} The parameter to the request call.</li>
12513 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
12514 * for the callback function. Defaults to the browser window.</li>
12515 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
12516 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
12517 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
12518 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
12519 * params for the post data. Any params will be appended to the URL.</li>
12520 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
12522 * @return {Number} transactionId
12524 request : function(o){
12525 if(this.fireEvent("beforerequest", this, o) !== false){
12528 if(typeof p == "function"){
12529 p = p.call(o.scope||window, o);
12531 if(typeof p == "object"){
12532 p = Roo.urlEncode(o.params);
12534 if(this.extraParams){
12535 var extras = Roo.urlEncode(this.extraParams);
12536 p = p ? (p + '&' + extras) : extras;
12539 var url = o.url || this.url;
12540 if(typeof url == 'function'){
12541 url = url.call(o.scope||window, o);
12545 var form = Roo.getDom(o.form);
12546 url = url || form.action;
12548 var enctype = form.getAttribute("enctype");
12551 return this.doFormDataUpload(o, url);
12554 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
12555 return this.doFormUpload(o, p, url);
12557 var f = Roo.lib.Ajax.serializeForm(form);
12558 p = p ? (p + '&' + f) : f;
12561 if (!o.form && o.formData) {
12562 o.formData = o.formData === true ? new FormData() : o.formData;
12563 for (var k in o.params) {
12564 o.formData.append(k,o.params[k]);
12567 return this.doFormDataUpload(o, url);
12571 var hs = o.headers;
12572 if(this.defaultHeaders){
12573 hs = Roo.apply(hs || {}, this.defaultHeaders);
12580 success: this.handleResponse,
12581 failure: this.handleFailure,
12583 argument: {options: o},
12584 timeout : o.timeout || this.timeout
12587 var method = o.method||this.method||(p ? "POST" : "GET");
12589 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
12590 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
12593 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12597 }else if(this.autoAbort !== false){
12601 if((method == 'GET' && p) || o.xmlData){
12602 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
12605 Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
12606 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
12607 Roo.lib.Ajax.useDefaultHeader == true;
12608 return this.transId;
12610 Roo.callback(o.callback, o.scope, [o, null, null]);
12616 * Determine whether this object has a request outstanding.
12617 * @param {Number} transactionId (Optional) defaults to the last transaction
12618 * @return {Boolean} True if there is an outstanding request.
12620 isLoading : function(transId){
12622 return Roo.lib.Ajax.isCallInProgress(transId);
12624 return this.transId ? true : false;
12629 * Aborts any outstanding request.
12630 * @param {Number} transactionId (Optional) defaults to the last transaction
12632 abort : function(transId){
12633 if(transId || this.isLoading()){
12634 Roo.lib.Ajax.abort(transId || this.transId);
12639 handleResponse : function(response){
12640 this.transId = false;
12641 var options = response.argument.options;
12642 response.argument = options ? options.argument : null;
12643 this.fireEvent("requestcomplete", this, response, options);
12644 Roo.callback(options.success, options.scope, [response, options]);
12645 Roo.callback(options.callback, options.scope, [options, true, response]);
12649 handleFailure : function(response, e){
12650 this.transId = false;
12651 var options = response.argument.options;
12652 response.argument = options ? options.argument : null;
12653 this.fireEvent("requestexception", this, response, options, e);
12654 Roo.callback(options.failure, options.scope, [response, options]);
12655 Roo.callback(options.callback, options.scope, [options, false, response]);
12659 doFormUpload : function(o, ps, url){
12661 var frame = document.createElement('iframe');
12664 frame.className = 'x-hidden';
12666 frame.src = Roo.SSL_SECURE_URL;
12668 document.body.appendChild(frame);
12671 document.frames[id].name = id;
12674 var form = Roo.getDom(o.form);
12676 form.method = 'POST';
12677 form.enctype = form.encoding = 'multipart/form-data';
12683 if(ps){ // add dynamic params
12685 ps = Roo.urlDecode(ps, false);
12687 if(ps.hasOwnProperty(k)){
12688 hd = document.createElement('input');
12689 hd.type = 'hidden';
12692 form.appendChild(hd);
12699 var r = { // bogus response object
12704 r.argument = o ? o.argument : null;
12709 doc = frame.contentWindow.document;
12711 doc = (frame.contentDocument || window.frames[id].document);
12713 if(doc && doc.body){
12714 r.responseText = doc.body.innerHTML;
12716 if(doc && doc.XMLDocument){
12717 r.responseXML = doc.XMLDocument;
12719 r.responseXML = doc;
12726 Roo.EventManager.removeListener(frame, 'load', cb, this);
12728 this.fireEvent("requestcomplete", this, r, o);
12729 Roo.callback(o.success, o.scope, [r, o]);
12730 Roo.callback(o.callback, o.scope, [o, true, r]);
12732 setTimeout(function(){document.body.removeChild(frame);}, 100);
12735 Roo.EventManager.on(frame, 'load', cb, this);
12738 if(hiddens){ // remove dynamic params
12739 for(var i = 0, len = hiddens.length; i < len; i++){
12740 form.removeChild(hiddens[i]);
12744 // this is a 'formdata version???'
12747 doFormDataUpload : function(o, url)
12751 var form = Roo.getDom(o.form);
12752 form.enctype = form.encoding = 'multipart/form-data';
12753 formData = o.formData === true ? new FormData(form) : o.formData;
12755 formData = o.formData === true ? new FormData() : o.formData;
12760 success: this.handleResponse,
12761 failure: this.handleFailure,
12763 argument: {options: o},
12764 timeout : o.timeout || this.timeout
12767 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12771 }else if(this.autoAbort !== false){
12775 //Roo.lib.Ajax.defaultPostHeader = null;
12776 Roo.lib.Ajax.useDefaultHeader = false;
12777 this.transId = Roo.lib.Ajax.request( "POST", url, cb, formData, o);
12778 Roo.lib.Ajax.useDefaultHeader = true;
12786 * Ext JS Library 1.1.1
12787 * Copyright(c) 2006-2007, Ext JS, LLC.
12789 * Originally Released Under LGPL - original licence link has changed is not relivant.
12792 * <script type="text/javascript">
12796 * Global Ajax request class.
12799 * @extends Roo.data.Connection
12802 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
12803 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
12804 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
12805 * @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)
12806 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12807 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
12808 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12810 Roo.Ajax = new Roo.data.Connection({
12819 * Serialize the passed form into a url encoded string
12821 * @param {String/HTMLElement} form
12824 serializeForm : function(form){
12825 return Roo.lib.Ajax.serializeForm(form);
12829 * Ext JS Library 1.1.1
12830 * Copyright(c) 2006-2007, Ext JS, LLC.
12832 * Originally Released Under LGPL - original licence link has changed is not relivant.
12835 * <script type="text/javascript">
12840 * @class Roo.UpdateManager
12841 * @extends Roo.util.Observable
12842 * Provides AJAX-style update for Element object.<br><br>
12845 * // Get it from a Roo.Element object
12846 * var el = Roo.get("foo");
12847 * var mgr = el.getUpdateManager();
12848 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
12850 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
12852 * // or directly (returns the same UpdateManager instance)
12853 * var mgr = new Roo.UpdateManager("myElementId");
12854 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
12855 * mgr.on("update", myFcnNeedsToKnow);
12857 // short handed call directly from the element object
12858 Roo.get("foo").load({
12862 text: "Loading Foo..."
12866 * Create new UpdateManager directly.
12867 * @param {String/HTMLElement/Roo.Element} el The element to update
12868 * @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).
12870 Roo.UpdateManager = function(el, forceNew){
12872 if(!forceNew && el.updateManager){
12873 return el.updateManager;
12876 * The Element object
12877 * @type Roo.Element
12881 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
12884 this.defaultUrl = null;
12888 * @event beforeupdate
12889 * Fired before an update is made, return false from your handler and the update is cancelled.
12890 * @param {Roo.Element} el
12891 * @param {String/Object/Function} url
12892 * @param {String/Object} params
12894 "beforeupdate": true,
12897 * Fired after successful update is made.
12898 * @param {Roo.Element} el
12899 * @param {Object} oResponseObject The response Object
12904 * Fired on update failure.
12905 * @param {Roo.Element} el
12906 * @param {Object} oResponseObject The response Object
12910 var d = Roo.UpdateManager.defaults;
12912 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
12915 this.sslBlankUrl = d.sslBlankUrl;
12917 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
12920 this.disableCaching = d.disableCaching;
12922 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
12925 this.indicatorText = d.indicatorText;
12927 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
12930 this.showLoadIndicator = d.showLoadIndicator;
12932 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
12935 this.timeout = d.timeout;
12938 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
12941 this.loadScripts = d.loadScripts;
12944 * Transaction object of current executing transaction
12946 this.transaction = null;
12951 this.autoRefreshProcId = null;
12953 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
12956 this.refreshDelegate = this.refresh.createDelegate(this);
12958 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
12961 this.updateDelegate = this.update.createDelegate(this);
12963 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
12966 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
12970 this.successDelegate = this.processSuccess.createDelegate(this);
12974 this.failureDelegate = this.processFailure.createDelegate(this);
12976 if(!this.renderer){
12978 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
12980 this.renderer = new Roo.UpdateManager.BasicRenderer();
12983 Roo.UpdateManager.superclass.constructor.call(this);
12986 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
12988 * Get the Element this UpdateManager is bound to
12989 * @return {Roo.Element} The element
12991 getEl : function(){
12995 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
12996 * @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:
12999 url: "your-url.php",<br/>
13000 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
13001 callback: yourFunction,<br/>
13002 scope: yourObject, //(optional scope) <br/>
13003 discardUrl: false, <br/>
13004 nocache: false,<br/>
13005 text: "Loading...",<br/>
13007 scripts: false<br/>
13010 * The only required property is url. The optional properties nocache, text and scripts
13011 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
13012 * @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}
13013 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13014 * @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.
13016 update : function(url, params, callback, discardUrl){
13017 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
13018 var method = this.method,
13020 if(typeof url == "object"){ // must be config object
13023 params = params || cfg.params;
13024 callback = callback || cfg.callback;
13025 discardUrl = discardUrl || cfg.discardUrl;
13026 if(callback && cfg.scope){
13027 callback = callback.createDelegate(cfg.scope);
13029 if(typeof cfg.method != "undefined"){method = cfg.method;};
13030 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
13031 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
13032 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
13033 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
13035 this.showLoading();
13037 this.defaultUrl = url;
13039 if(typeof url == "function"){
13040 url = url.call(this);
13043 method = method || (params ? "POST" : "GET");
13044 if(method == "GET"){
13045 url = this.prepareUrl(url);
13048 var o = Roo.apply(cfg ||{}, {
13051 success: this.successDelegate,
13052 failure: this.failureDelegate,
13053 callback: undefined,
13054 timeout: (this.timeout*1000),
13055 argument: {"url": url, "form": null, "callback": callback, "params": params}
13057 Roo.log("updated manager called with timeout of " + o.timeout);
13058 this.transaction = Roo.Ajax.request(o);
13063 * 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.
13064 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
13065 * @param {String/HTMLElement} form The form Id or form element
13066 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
13067 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
13068 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13070 formUpdate : function(form, url, reset, callback){
13071 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
13072 if(typeof url == "function"){
13073 url = url.call(this);
13075 form = Roo.getDom(form);
13076 this.transaction = Roo.Ajax.request({
13079 success: this.successDelegate,
13080 failure: this.failureDelegate,
13081 timeout: (this.timeout*1000),
13082 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
13084 this.showLoading.defer(1, this);
13089 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
13090 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13092 refresh : function(callback){
13093 if(this.defaultUrl == null){
13096 this.update(this.defaultUrl, null, callback, true);
13100 * Set this element to auto refresh.
13101 * @param {Number} interval How often to update (in seconds).
13102 * @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)
13103 * @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}
13104 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13105 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
13107 startAutoRefresh : function(interval, url, params, callback, refreshNow){
13109 this.update(url || this.defaultUrl, params, callback, true);
13111 if(this.autoRefreshProcId){
13112 clearInterval(this.autoRefreshProcId);
13114 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
13118 * Stop auto refresh on this element.
13120 stopAutoRefresh : function(){
13121 if(this.autoRefreshProcId){
13122 clearInterval(this.autoRefreshProcId);
13123 delete this.autoRefreshProcId;
13127 isAutoRefreshing : function(){
13128 return this.autoRefreshProcId ? true : false;
13131 * Called to update the element to "Loading" state. Override to perform custom action.
13133 showLoading : function(){
13134 if(this.showLoadIndicator){
13135 this.el.update(this.indicatorText);
13140 * Adds unique parameter to query string if disableCaching = true
13143 prepareUrl : function(url){
13144 if(this.disableCaching){
13145 var append = "_dc=" + (new Date().getTime());
13146 if(url.indexOf("?") !== -1){
13147 url += "&" + append;
13149 url += "?" + append;
13158 processSuccess : function(response){
13159 this.transaction = null;
13160 if(response.argument.form && response.argument.reset){
13161 try{ // put in try/catch since some older FF releases had problems with this
13162 response.argument.form.reset();
13165 if(this.loadScripts){
13166 this.renderer.render(this.el, response, this,
13167 this.updateComplete.createDelegate(this, [response]));
13169 this.renderer.render(this.el, response, this);
13170 this.updateComplete(response);
13174 updateComplete : function(response){
13175 this.fireEvent("update", this.el, response);
13176 if(typeof response.argument.callback == "function"){
13177 response.argument.callback(this.el, true, response);
13184 processFailure : function(response){
13185 this.transaction = null;
13186 this.fireEvent("failure", this.el, response);
13187 if(typeof response.argument.callback == "function"){
13188 response.argument.callback(this.el, false, response);
13193 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
13194 * @param {Object} renderer The object implementing the render() method
13196 setRenderer : function(renderer){
13197 this.renderer = renderer;
13200 getRenderer : function(){
13201 return this.renderer;
13205 * Set the defaultUrl used for updates
13206 * @param {String/Function} defaultUrl The url or a function to call to get the url
13208 setDefaultUrl : function(defaultUrl){
13209 this.defaultUrl = defaultUrl;
13213 * Aborts the executing transaction
13215 abort : function(){
13216 if(this.transaction){
13217 Roo.Ajax.abort(this.transaction);
13222 * Returns true if an update is in progress
13223 * @return {Boolean}
13225 isUpdating : function(){
13226 if(this.transaction){
13227 return Roo.Ajax.isLoading(this.transaction);
13234 * @class Roo.UpdateManager.defaults
13235 * @static (not really - but it helps the doc tool)
13236 * The defaults collection enables customizing the default properties of UpdateManager
13238 Roo.UpdateManager.defaults = {
13240 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
13246 * True to process scripts by default (Defaults to false).
13249 loadScripts : false,
13252 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
13255 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
13257 * Whether to append unique parameter on get request to disable caching (Defaults to false).
13260 disableCaching : false,
13262 * Whether to show indicatorText when loading (Defaults to true).
13265 showLoadIndicator : true,
13267 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
13270 indicatorText : '<div class="loading-indicator">Loading...</div>'
13274 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
13276 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
13277 * @param {String/HTMLElement/Roo.Element} el The element to update
13278 * @param {String} url The url
13279 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
13280 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
13283 * @member Roo.UpdateManager
13285 Roo.UpdateManager.updateElement = function(el, url, params, options){
13286 var um = Roo.get(el, true).getUpdateManager();
13287 Roo.apply(um, options);
13288 um.update(url, params, options ? options.callback : null);
13290 // alias for backwards compat
13291 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
13293 * @class Roo.UpdateManager.BasicRenderer
13294 * Default Content renderer. Updates the elements innerHTML with the responseText.
13296 Roo.UpdateManager.BasicRenderer = function(){};
13298 Roo.UpdateManager.BasicRenderer.prototype = {
13300 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
13301 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
13302 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
13303 * @param {Roo.Element} el The element being rendered
13304 * @param {Object} response The YUI Connect response object
13305 * @param {UpdateManager} updateManager The calling update manager
13306 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
13308 render : function(el, response, updateManager, callback){
13309 el.update(response.responseText, updateManager.loadScripts, callback);
13315 * (c)) Alan Knowles
13321 * @class Roo.DomTemplate
13322 * @extends Roo.Template
13323 * An effort at a dom based template engine..
13325 * Similar to XTemplate, except it uses dom parsing to create the template..
13327 * Supported features:
13332 {a_variable} - output encoded.
13333 {a_variable.format:("Y-m-d")} - call a method on the variable
13334 {a_variable:raw} - unencoded output
13335 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
13336 {a_variable:this.method_on_template(...)} - call a method on the template object.
13341 <div roo-for="a_variable or condition.."></div>
13342 <div roo-if="a_variable or condition"></div>
13343 <div roo-exec="some javascript"></div>
13344 <div roo-name="named_template"></div>
13349 Roo.DomTemplate = function()
13351 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
13358 Roo.extend(Roo.DomTemplate, Roo.Template, {
13360 * id counter for sub templates.
13364 * flag to indicate if dom parser is inside a pre,
13365 * it will strip whitespace if not.
13370 * The various sub templates
13378 * basic tag replacing syntax
13381 * // you can fake an object call by doing this
13385 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
13386 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
13388 iterChild : function (node, method) {
13390 var oldPre = this.inPre;
13391 if (node.tagName == 'PRE') {
13394 for( var i = 0; i < node.childNodes.length; i++) {
13395 method.call(this, node.childNodes[i]);
13397 this.inPre = oldPre;
13403 * compile the template
13405 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
13408 compile: function()
13412 // covert the html into DOM...
13416 doc = document.implementation.createHTMLDocument("");
13417 doc.documentElement.innerHTML = this.html ;
13418 div = doc.documentElement;
13420 // old IE... - nasty -- it causes all sorts of issues.. with
13421 // images getting pulled from server..
13422 div = document.createElement('div');
13423 div.innerHTML = this.html;
13425 //doc.documentElement.innerHTML = htmlBody
13431 this.iterChild(div, function(n) {_t.compileNode(n, true); });
13433 var tpls = this.tpls;
13435 // create a top level template from the snippet..
13437 //Roo.log(div.innerHTML);
13444 body : div.innerHTML,
13457 Roo.each(tpls, function(tp){
13458 this.compileTpl(tp);
13459 this.tpls[tp.id] = tp;
13462 this.master = tpls[0];
13468 compileNode : function(node, istop) {
13473 // skip anything not a tag..
13474 if (node.nodeType != 1) {
13475 if (node.nodeType == 3 && !this.inPre) {
13476 // reduce white space..
13477 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
13500 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
13501 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
13502 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
13503 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
13509 // just itterate children..
13510 this.iterChild(node,this.compileNode);
13513 tpl.uid = this.id++;
13514 tpl.value = node.getAttribute('roo-' + tpl.attr);
13515 node.removeAttribute('roo-'+ tpl.attr);
13516 if (tpl.attr != 'name') {
13517 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
13518 node.parentNode.replaceChild(placeholder, node);
13521 var placeholder = document.createElement('span');
13522 placeholder.className = 'roo-tpl-' + tpl.value;
13523 node.parentNode.replaceChild(placeholder, node);
13526 // parent now sees '{domtplXXXX}
13527 this.iterChild(node,this.compileNode);
13529 // we should now have node body...
13530 var div = document.createElement('div');
13531 div.appendChild(node);
13533 // this has the unfortunate side effect of converting tagged attributes
13534 // eg. href="{...}" into %7C...%7D
13535 // this has been fixed by searching for those combo's although it's a bit hacky..
13538 tpl.body = div.innerHTML;
13545 switch (tpl.value) {
13546 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
13547 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
13548 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
13553 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13557 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13561 tpl.id = tpl.value; // replace non characters???
13567 this.tpls.push(tpl);
13577 * Compile a segment of the template into a 'sub-template'
13583 compileTpl : function(tpl)
13585 var fm = Roo.util.Format;
13586 var useF = this.disableFormats !== true;
13588 var sep = Roo.isGecko ? "+\n" : ",\n";
13590 var undef = function(str) {
13591 Roo.debug && Roo.log("Property not found :" + str);
13595 //Roo.log(tpl.body);
13599 var fn = function(m, lbrace, name, format, args)
13602 //Roo.log(arguments);
13603 args = args ? args.replace(/\\'/g,"'") : args;
13604 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
13605 if (typeof(format) == 'undefined') {
13606 format = 'htmlEncode';
13608 if (format == 'raw' ) {
13612 if(name.substr(0, 6) == 'domtpl'){
13613 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
13616 // build an array of options to determine if value is undefined..
13618 // basically get 'xxxx.yyyy' then do
13619 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
13620 // (function () { Roo.log("Property not found"); return ''; })() :
13625 Roo.each(name.split('.'), function(st) {
13626 lookfor += (lookfor.length ? '.': '') + st;
13627 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
13630 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
13633 if(format && useF){
13635 args = args ? ',' + args : "";
13637 if(format.substr(0, 5) != "this."){
13638 format = "fm." + format + '(';
13640 format = 'this.call("'+ format.substr(5) + '", ';
13644 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
13647 if (args && args.length) {
13648 // called with xxyx.yuu:(test,test)
13650 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
13652 // raw.. - :raw modifier..
13653 return "'"+ sep + udef_st + name + ")"+sep+"'";
13657 // branched to use + in gecko and [].join() in others
13659 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
13660 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
13663 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
13664 body.push(tpl.body.replace(/(\r\n|\n)/g,
13665 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
13666 body.push("'].join('');};};");
13667 body = body.join('');
13670 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
13672 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
13679 * same as applyTemplate, except it's done to one of the subTemplates
13680 * when using named templates, you can do:
13682 * var str = pl.applySubTemplate('your-name', values);
13685 * @param {Number} id of the template
13686 * @param {Object} values to apply to template
13687 * @param {Object} parent (normaly the instance of this object)
13689 applySubTemplate : function(id, values, parent)
13693 var t = this.tpls[id];
13697 if(t.ifCall && !t.ifCall.call(this, values, parent)){
13698 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
13702 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
13709 if(t.execCall && t.execCall.call(this, values, parent)){
13713 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13719 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
13720 parent = t.target ? values : parent;
13721 if(t.forCall && vs instanceof Array){
13723 for(var i = 0, len = vs.length; i < len; i++){
13725 buf[buf.length] = t.compiled.call(this, vs[i], parent);
13727 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13729 //Roo.log(t.compiled);
13733 return buf.join('');
13736 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13741 return t.compiled.call(this, vs, parent);
13743 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13745 //Roo.log(t.compiled);
13753 applyTemplate : function(values){
13754 return this.master.compiled.call(this, values, {});
13755 //var s = this.subs;
13758 apply : function(){
13759 return this.applyTemplate.apply(this, arguments);
13764 Roo.DomTemplate.from = function(el){
13765 el = Roo.getDom(el);
13766 return new Roo.Domtemplate(el.value || el.innerHTML);
13769 * Ext JS Library 1.1.1
13770 * Copyright(c) 2006-2007, Ext JS, LLC.
13772 * Originally Released Under LGPL - original licence link has changed is not relivant.
13775 * <script type="text/javascript">
13779 * @class Roo.util.DelayedTask
13780 * Provides a convenient method of performing setTimeout where a new
13781 * timeout cancels the old timeout. An example would be performing validation on a keypress.
13782 * You can use this class to buffer
13783 * the keypress events for a certain number of milliseconds, and perform only if they stop
13784 * for that amount of time.
13785 * @constructor The parameters to this constructor serve as defaults and are not required.
13786 * @param {Function} fn (optional) The default function to timeout
13787 * @param {Object} scope (optional) The default scope of that timeout
13788 * @param {Array} args (optional) The default Array of arguments
13790 Roo.util.DelayedTask = function(fn, scope, args){
13791 var id = null, d, t;
13793 var call = function(){
13794 var now = new Date().getTime();
13798 fn.apply(scope, args || []);
13802 * Cancels any pending timeout and queues a new one
13803 * @param {Number} delay The milliseconds to delay
13804 * @param {Function} newFn (optional) Overrides function passed to constructor
13805 * @param {Object} newScope (optional) Overrides scope passed to constructor
13806 * @param {Array} newArgs (optional) Overrides args passed to constructor
13808 this.delay = function(delay, newFn, newScope, newArgs){
13809 if(id && delay != d){
13813 t = new Date().getTime();
13815 scope = newScope || scope;
13816 args = newArgs || args;
13818 id = setInterval(call, d);
13823 * Cancel the last queued timeout
13825 this.cancel = function(){
13833 * Ext JS Library 1.1.1
13834 * Copyright(c) 2006-2007, Ext JS, LLC.
13836 * Originally Released Under LGPL - original licence link has changed is not relivant.
13839 * <script type="text/javascript">
13842 * @class Roo.util.TaskRunner
13843 * Manage background tasks - not sure why this is better that setInterval?
13848 Roo.util.TaskRunner = function(interval){
13849 interval = interval || 10;
13850 var tasks = [], removeQueue = [];
13852 var running = false;
13854 var stopThread = function(){
13860 var startThread = function(){
13863 id = setInterval(runTasks, interval);
13867 var removeTask = function(task){
13868 removeQueue.push(task);
13874 var runTasks = function(){
13875 if(removeQueue.length > 0){
13876 for(var i = 0, len = removeQueue.length; i < len; i++){
13877 tasks.remove(removeQueue[i]);
13880 if(tasks.length < 1){
13885 var now = new Date().getTime();
13886 for(var i = 0, len = tasks.length; i < len; ++i){
13888 var itime = now - t.taskRunTime;
13889 if(t.interval <= itime){
13890 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
13891 t.taskRunTime = now;
13892 if(rt === false || t.taskRunCount === t.repeat){
13897 if(t.duration && t.duration <= (now - t.taskStartTime)){
13904 * Queues a new task.
13905 * @param {Object} task
13907 * Task property : interval = how frequent to run.
13908 * Task object should implement
13910 * Task object may implement
13911 * function onStop()
13913 this.start = function(task){
13915 task.taskStartTime = new Date().getTime();
13916 task.taskRunTime = 0;
13917 task.taskRunCount = 0;
13923 * @param {Object} task
13925 this.stop = function(task){
13932 this.stopAll = function(){
13934 for(var i = 0, len = tasks.length; i < len; i++){
13935 if(tasks[i].onStop){
13944 Roo.TaskMgr = new Roo.util.TaskRunner();/*
13946 * Ext JS Library 1.1.1
13947 * Copyright(c) 2006-2007, Ext JS, LLC.
13949 * Originally Released Under LGPL - original licence link has changed is not relivant.
13952 * <script type="text/javascript">
13957 * @class Roo.util.MixedCollection
13958 * @extends Roo.util.Observable
13959 * A Collection class that maintains both numeric indexes and keys and exposes events.
13961 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
13962 * collection (defaults to false)
13963 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
13964 * and return the key value for that item. This is used when available to look up the key on items that
13965 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
13966 * equivalent to providing an implementation for the {@link #getKey} method.
13968 Roo.util.MixedCollection = function(allowFunctions, keyFn){
13976 * Fires when the collection is cleared.
13981 * Fires when an item is added to the collection.
13982 * @param {Number} index The index at which the item was added.
13983 * @param {Object} o The item added.
13984 * @param {String} key The key associated with the added item.
13989 * Fires when an item is replaced in the collection.
13990 * @param {String} key he key associated with the new added.
13991 * @param {Object} old The item being replaced.
13992 * @param {Object} new The new item.
13997 * Fires when an item is removed from the collection.
13998 * @param {Object} o The item being removed.
13999 * @param {String} key (optional) The key associated with the removed item.
14004 this.allowFunctions = allowFunctions === true;
14006 this.getKey = keyFn;
14008 Roo.util.MixedCollection.superclass.constructor.call(this);
14011 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
14012 allowFunctions : false,
14015 * Adds an item to the collection.
14016 * @param {String} key The key to associate with the item
14017 * @param {Object} o The item to add.
14018 * @return {Object} The item added.
14020 add : function(key, o){
14021 if(arguments.length == 1){
14023 key = this.getKey(o);
14025 if(typeof key == "undefined" || key === null){
14027 this.items.push(o);
14028 this.keys.push(null);
14030 var old = this.map[key];
14032 return this.replace(key, o);
14035 this.items.push(o);
14037 this.keys.push(key);
14039 this.fireEvent("add", this.length-1, o, key);
14044 * MixedCollection has a generic way to fetch keys if you implement getKey.
14047 var mc = new Roo.util.MixedCollection();
14048 mc.add(someEl.dom.id, someEl);
14049 mc.add(otherEl.dom.id, otherEl);
14053 var mc = new Roo.util.MixedCollection();
14054 mc.getKey = function(el){
14060 // or via the constructor
14061 var mc = new Roo.util.MixedCollection(false, function(el){
14067 * @param o {Object} The item for which to find the key.
14068 * @return {Object} The key for the passed item.
14070 getKey : function(o){
14075 * Replaces an item in the collection.
14076 * @param {String} key The key associated with the item to replace, or the item to replace.
14077 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
14078 * @return {Object} The new item.
14080 replace : function(key, o){
14081 if(arguments.length == 1){
14083 key = this.getKey(o);
14085 var old = this.item(key);
14086 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
14087 return this.add(key, o);
14089 var index = this.indexOfKey(key);
14090 this.items[index] = o;
14092 this.fireEvent("replace", key, old, o);
14097 * Adds all elements of an Array or an Object to the collection.
14098 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
14099 * an Array of values, each of which are added to the collection.
14101 addAll : function(objs){
14102 if(arguments.length > 1 || objs instanceof Array){
14103 var args = arguments.length > 1 ? arguments : objs;
14104 for(var i = 0, len = args.length; i < len; i++){
14108 for(var key in objs){
14109 if(this.allowFunctions || typeof objs[key] != "function"){
14110 this.add(key, objs[key]);
14117 * Executes the specified function once for every item in the collection, passing each
14118 * item as the first and only parameter. returning false from the function will stop the iteration.
14119 * @param {Function} fn The function to execute for each item.
14120 * @param {Object} scope (optional) The scope in which to execute the function.
14122 each : function(fn, scope){
14123 var items = [].concat(this.items); // each safe for removal
14124 for(var i = 0, len = items.length; i < len; i++){
14125 if(fn.call(scope || items[i], items[i], i, len) === false){
14132 * Executes the specified function once for every key in the collection, passing each
14133 * key, and its associated item as the first two parameters.
14134 * @param {Function} fn The function to execute for each item.
14135 * @param {Object} scope (optional) The scope in which to execute the function.
14137 eachKey : function(fn, scope){
14138 for(var i = 0, len = this.keys.length; i < len; i++){
14139 fn.call(scope || window, this.keys[i], this.items[i], i, len);
14144 * Returns the first item in the collection which elicits a true return value from the
14145 * passed selection function.
14146 * @param {Function} fn The selection function to execute for each item.
14147 * @param {Object} scope (optional) The scope in which to execute the function.
14148 * @return {Object} The first item in the collection which returned true from the selection function.
14150 find : function(fn, scope){
14151 for(var i = 0, len = this.items.length; i < len; i++){
14152 if(fn.call(scope || window, this.items[i], this.keys[i])){
14153 return this.items[i];
14160 * Inserts an item at the specified index in the collection.
14161 * @param {Number} index The index to insert the item at.
14162 * @param {String} key The key to associate with the new item, or the item itself.
14163 * @param {Object} o (optional) If the second parameter was a key, the new item.
14164 * @return {Object} The item inserted.
14166 insert : function(index, key, o){
14167 if(arguments.length == 2){
14169 key = this.getKey(o);
14171 if(index >= this.length){
14172 return this.add(key, o);
14175 this.items.splice(index, 0, o);
14176 if(typeof key != "undefined" && key != null){
14179 this.keys.splice(index, 0, key);
14180 this.fireEvent("add", index, o, key);
14185 * Removed an item from the collection.
14186 * @param {Object} o The item to remove.
14187 * @return {Object} The item removed.
14189 remove : function(o){
14190 return this.removeAt(this.indexOf(o));
14194 * Remove an item from a specified index in the collection.
14195 * @param {Number} index The index within the collection of the item to remove.
14197 removeAt : function(index){
14198 if(index < this.length && index >= 0){
14200 var o = this.items[index];
14201 this.items.splice(index, 1);
14202 var key = this.keys[index];
14203 if(typeof key != "undefined"){
14204 delete this.map[key];
14206 this.keys.splice(index, 1);
14207 this.fireEvent("remove", o, key);
14212 * Removed an item associated with the passed key fom the collection.
14213 * @param {String} key The key of the item to remove.
14215 removeKey : function(key){
14216 return this.removeAt(this.indexOfKey(key));
14220 * Returns the number of items in the collection.
14221 * @return {Number} the number of items in the collection.
14223 getCount : function(){
14224 return this.length;
14228 * Returns index within the collection of the passed Object.
14229 * @param {Object} o The item to find the index of.
14230 * @return {Number} index of the item.
14232 indexOf : function(o){
14233 if(!this.items.indexOf){
14234 for(var i = 0, len = this.items.length; i < len; i++){
14235 if(this.items[i] == o) {
14241 return this.items.indexOf(o);
14246 * Returns index within the collection of the passed key.
14247 * @param {String} key The key to find the index of.
14248 * @return {Number} index of the key.
14250 indexOfKey : function(key){
14251 if(!this.keys.indexOf){
14252 for(var i = 0, len = this.keys.length; i < len; i++){
14253 if(this.keys[i] == key) {
14259 return this.keys.indexOf(key);
14264 * Returns the item associated with the passed key OR index. Key has priority over index.
14265 * @param {String/Number} key The key or index of the item.
14266 * @return {Object} The item associated with the passed key.
14268 item : function(key){
14269 if (key === 'length') {
14272 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
14273 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
14277 * Returns the item at the specified index.
14278 * @param {Number} index The index of the item.
14281 itemAt : function(index){
14282 return this.items[index];
14286 * Returns the item associated with the passed key.
14287 * @param {String/Number} key The key of the item.
14288 * @return {Object} The item associated with the passed key.
14290 key : function(key){
14291 return this.map[key];
14295 * Returns true if the collection contains the passed Object as an item.
14296 * @param {Object} o The Object to look for in the collection.
14297 * @return {Boolean} True if the collection contains the Object as an item.
14299 contains : function(o){
14300 return this.indexOf(o) != -1;
14304 * Returns true if the collection contains the passed Object as a key.
14305 * @param {String} key The key to look for in the collection.
14306 * @return {Boolean} True if the collection contains the Object as a key.
14308 containsKey : function(key){
14309 return typeof this.map[key] != "undefined";
14313 * Removes all items from the collection.
14315 clear : function(){
14320 this.fireEvent("clear");
14324 * Returns the first item in the collection.
14325 * @return {Object} the first item in the collection..
14327 first : function(){
14328 return this.items[0];
14332 * Returns the last item in the collection.
14333 * @return {Object} the last item in the collection..
14336 return this.items[this.length-1];
14339 _sort : function(property, dir, fn){
14340 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
14341 fn = fn || function(a, b){
14344 var c = [], k = this.keys, items = this.items;
14345 for(var i = 0, len = items.length; i < len; i++){
14346 c[c.length] = {key: k[i], value: items[i], index: i};
14348 c.sort(function(a, b){
14349 var v = fn(a[property], b[property]) * dsc;
14351 v = (a.index < b.index ? -1 : 1);
14355 for(var i = 0, len = c.length; i < len; i++){
14356 items[i] = c[i].value;
14359 this.fireEvent("sort", this);
14363 * Sorts this collection with the passed comparison function
14364 * @param {String} direction (optional) "ASC" or "DESC"
14365 * @param {Function} fn (optional) comparison function
14367 sort : function(dir, fn){
14368 this._sort("value", dir, fn);
14372 * Sorts this collection by keys
14373 * @param {String} direction (optional) "ASC" or "DESC"
14374 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
14376 keySort : function(dir, fn){
14377 this._sort("key", dir, fn || function(a, b){
14378 return String(a).toUpperCase()-String(b).toUpperCase();
14383 * Returns a range of items in this collection
14384 * @param {Number} startIndex (optional) defaults to 0
14385 * @param {Number} endIndex (optional) default to the last item
14386 * @return {Array} An array of items
14388 getRange : function(start, end){
14389 var items = this.items;
14390 if(items.length < 1){
14393 start = start || 0;
14394 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
14397 for(var i = start; i <= end; i++) {
14398 r[r.length] = items[i];
14401 for(var i = start; i >= end; i--) {
14402 r[r.length] = items[i];
14409 * Filter the <i>objects</i> in this collection by a specific property.
14410 * Returns a new collection that has been filtered.
14411 * @param {String} property A property on your objects
14412 * @param {String/RegExp} value Either string that the property values
14413 * should start with or a RegExp to test against the property
14414 * @return {MixedCollection} The new filtered collection
14416 filter : function(property, value){
14417 if(!value.exec){ // not a regex
14418 value = String(value);
14419 if(value.length == 0){
14420 return this.clone();
14422 value = new RegExp("^" + Roo.escapeRe(value), "i");
14424 return this.filterBy(function(o){
14425 return o && value.test(o[property]);
14430 * Filter by a function. * Returns a new collection that has been filtered.
14431 * The passed function will be called with each
14432 * object in the collection. If the function returns true, the value is included
14433 * otherwise it is filtered.
14434 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
14435 * @param {Object} scope (optional) The scope of the function (defaults to this)
14436 * @return {MixedCollection} The new filtered collection
14438 filterBy : function(fn, scope){
14439 var r = new Roo.util.MixedCollection();
14440 r.getKey = this.getKey;
14441 var k = this.keys, it = this.items;
14442 for(var i = 0, len = it.length; i < len; i++){
14443 if(fn.call(scope||this, it[i], k[i])){
14444 r.add(k[i], it[i]);
14451 * Creates a duplicate of this collection
14452 * @return {MixedCollection}
14454 clone : function(){
14455 var r = new Roo.util.MixedCollection();
14456 var k = this.keys, it = this.items;
14457 for(var i = 0, len = it.length; i < len; i++){
14458 r.add(k[i], it[i]);
14460 r.getKey = this.getKey;
14465 * Returns the item associated with the passed key or index.
14467 * @param {String/Number} key The key or index of the item.
14468 * @return {Object} The item associated with the passed key.
14470 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
14472 * Ext JS Library 1.1.1
14473 * Copyright(c) 2006-2007, Ext JS, LLC.
14475 * Originally Released Under LGPL - original licence link has changed is not relivant.
14478 * <script type="text/javascript">
14481 * @class Roo.util.JSON
14482 * Modified version of Douglas Crockford"s json.js that doesn"t
14483 * mess with the Object prototype
14484 * http://www.json.org/js.html
14487 Roo.util.JSON = new (function(){
14488 var useHasOwn = {}.hasOwnProperty ? true : false;
14490 // crashes Safari in some instances
14491 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
14493 var pad = function(n) {
14494 return n < 10 ? "0" + n : n;
14507 var encodeString = function(s){
14508 if (/["\\\x00-\x1f]/.test(s)) {
14509 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
14514 c = b.charCodeAt();
14516 Math.floor(c / 16).toString(16) +
14517 (c % 16).toString(16);
14520 return '"' + s + '"';
14523 var encodeArray = function(o){
14524 var a = ["["], b, i, l = o.length, v;
14525 for (i = 0; i < l; i += 1) {
14527 switch (typeof v) {
14536 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
14544 var encodeDate = function(o){
14545 return '"' + o.getFullYear() + "-" +
14546 pad(o.getMonth() + 1) + "-" +
14547 pad(o.getDate()) + "T" +
14548 pad(o.getHours()) + ":" +
14549 pad(o.getMinutes()) + ":" +
14550 pad(o.getSeconds()) + '"';
14554 * Encodes an Object, Array or other value
14555 * @param {Mixed} o The variable to encode
14556 * @return {String} The JSON string
14558 this.encode = function(o)
14560 // should this be extended to fully wrap stringify..
14562 if(typeof o == "undefined" || o === null){
14564 }else if(o instanceof Array){
14565 return encodeArray(o);
14566 }else if(o instanceof Date){
14567 return encodeDate(o);
14568 }else if(typeof o == "string"){
14569 return encodeString(o);
14570 }else if(typeof o == "number"){
14571 return isFinite(o) ? String(o) : "null";
14572 }else if(typeof o == "boolean"){
14575 var a = ["{"], b, i, v;
14577 if(!useHasOwn || o.hasOwnProperty(i)) {
14579 switch (typeof v) {
14588 a.push(this.encode(i), ":",
14589 v === null ? "null" : this.encode(v));
14600 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
14601 * @param {String} json The JSON string
14602 * @return {Object} The resulting object
14604 this.decode = function(json){
14606 return /** eval:var:json */ eval("(" + json + ')');
14610 * Shorthand for {@link Roo.util.JSON#encode}
14611 * @member Roo encode
14613 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
14615 * Shorthand for {@link Roo.util.JSON#decode}
14616 * @member Roo decode
14618 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
14621 * Ext JS Library 1.1.1
14622 * Copyright(c) 2006-2007, Ext JS, LLC.
14624 * Originally Released Under LGPL - original licence link has changed is not relivant.
14627 * <script type="text/javascript">
14631 * @class Roo.util.Format
14632 * Reusable data formatting functions
14635 Roo.util.Format = function(){
14636 var trimRe = /^\s+|\s+$/g;
14639 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
14640 * @param {String} value The string to truncate
14641 * @param {Number} length The maximum length to allow before truncating
14642 * @return {String} The converted text
14644 ellipsis : function(value, len){
14645 if(value && value.length > len){
14646 return value.substr(0, len-3)+"...";
14652 * Checks a reference and converts it to empty string if it is undefined
14653 * @param {Mixed} value Reference to check
14654 * @return {Mixed} Empty string if converted, otherwise the original value
14656 undef : function(value){
14657 return typeof value != "undefined" ? value : "";
14661 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
14662 * @param {String} value The string to encode
14663 * @return {String} The encoded text
14665 htmlEncode : function(value){
14666 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
14670 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
14671 * @param {String} value The string to decode
14672 * @return {String} The decoded text
14674 htmlDecode : function(value){
14675 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
14679 * Trims any whitespace from either side of a string
14680 * @param {String} value The text to trim
14681 * @return {String} The trimmed text
14683 trim : function(value){
14684 return String(value).replace(trimRe, "");
14688 * Returns a substring from within an original string
14689 * @param {String} value The original text
14690 * @param {Number} start The start index of the substring
14691 * @param {Number} length The length of the substring
14692 * @return {String} The substring
14694 substr : function(value, start, length){
14695 return String(value).substr(start, length);
14699 * Converts a string to all lower case letters
14700 * @param {String} value The text to convert
14701 * @return {String} The converted text
14703 lowercase : function(value){
14704 return String(value).toLowerCase();
14708 * Converts a string to all upper case letters
14709 * @param {String} value The text to convert
14710 * @return {String} The converted text
14712 uppercase : function(value){
14713 return String(value).toUpperCase();
14717 * Converts the first character only of a string to upper case
14718 * @param {String} value The text to convert
14719 * @return {String} The converted text
14721 capitalize : function(value){
14722 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
14726 call : function(value, fn){
14727 if(arguments.length > 2){
14728 var args = Array.prototype.slice.call(arguments, 2);
14729 args.unshift(value);
14731 return /** eval:var:value */ eval(fn).apply(window, args);
14733 /** eval:var:value */
14734 return /** eval:var:value */ eval(fn).call(window, value);
14740 * safer version of Math.toFixed..??/
14741 * @param {Number/String} value The numeric value to format
14742 * @param {Number/String} value Decimal places
14743 * @return {String} The formatted currency string
14745 toFixed : function(v, n)
14747 // why not use to fixed - precision is buggered???
14749 return Math.round(v-0);
14751 var fact = Math.pow(10,n+1);
14752 v = (Math.round((v-0)*fact))/fact;
14753 var z = (''+fact).substring(2);
14754 if (v == Math.floor(v)) {
14755 return Math.floor(v) + '.' + z;
14758 // now just padd decimals..
14759 var ps = String(v).split('.');
14760 var fd = (ps[1] + z);
14761 var r = fd.substring(0,n);
14762 var rm = fd.substring(n);
14764 return ps[0] + '.' + r;
14766 r*=1; // turn it into a number;
14768 if (String(r).length != n) {
14771 r = String(r).substring(1); // chop the end off.
14774 return ps[0] + '.' + r;
14779 * Format a number as US currency
14780 * @param {Number/String} value The numeric value to format
14781 * @return {String} The formatted currency string
14783 usMoney : function(v){
14784 return '$' + Roo.util.Format.number(v);
14789 * eventually this should probably emulate php's number_format
14790 * @param {Number/String} value The numeric value to format
14791 * @param {Number} decimals number of decimal places
14792 * @param {String} delimiter for thousands (default comma)
14793 * @return {String} The formatted currency string
14795 number : function(v, decimals, thousandsDelimiter)
14797 // multiply and round.
14798 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
14799 thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
14801 var mul = Math.pow(10, decimals);
14802 var zero = String(mul).substring(1);
14803 v = (Math.round((v-0)*mul))/mul;
14805 // if it's '0' number.. then
14807 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
14809 var ps = v.split('.');
14812 var r = /(\d+)(\d{3})/;
14815 if(thousandsDelimiter.length != 0) {
14816 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
14821 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
14822 // does not have decimals
14823 (decimals ? ('.' + zero) : '');
14826 return whole + sub ;
14830 * Parse a value into a formatted date using the specified format pattern.
14831 * @param {Mixed} value The value to format
14832 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
14833 * @return {String} The formatted date string
14835 date : function(v, format){
14839 if(!(v instanceof Date)){
14840 v = new Date(Date.parse(v));
14842 return v.dateFormat(format || Roo.util.Format.defaults.date);
14846 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
14847 * @param {String} format Any valid date format string
14848 * @return {Function} The date formatting function
14850 dateRenderer : function(format){
14851 return function(v){
14852 return Roo.util.Format.date(v, format);
14857 stripTagsRE : /<\/?[^>]+>/gi,
14860 * Strips all HTML tags
14861 * @param {Mixed} value The text from which to strip tags
14862 * @return {String} The stripped text
14864 stripTags : function(v){
14865 return !v ? v : String(v).replace(this.stripTagsRE, "");
14869 * Size in Mb,Gb etc.
14870 * @param {Number} value The number to be formated
14871 * @param {number} decimals how many decimal places
14872 * @return {String} the formated string
14874 size : function(value, decimals)
14876 var sizes = ['b', 'k', 'M', 'G', 'T'];
14880 var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
14881 return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals) + sizes[i];
14888 Roo.util.Format.defaults = {
14892 * Ext JS Library 1.1.1
14893 * Copyright(c) 2006-2007, Ext JS, LLC.
14895 * Originally Released Under LGPL - original licence link has changed is not relivant.
14898 * <script type="text/javascript">
14905 * @class Roo.MasterTemplate
14906 * @extends Roo.Template
14907 * Provides a template that can have child templates. The syntax is:
14909 var t = new Roo.MasterTemplate(
14910 '<select name="{name}">',
14911 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
14914 t.add('options', {value: 'foo', text: 'bar'});
14915 // or you can add multiple child elements in one shot
14916 t.addAll('options', [
14917 {value: 'foo', text: 'bar'},
14918 {value: 'foo2', text: 'bar2'},
14919 {value: 'foo3', text: 'bar3'}
14921 // then append, applying the master template values
14922 t.append('my-form', {name: 'my-select'});
14924 * A name attribute for the child template is not required if you have only one child
14925 * template or you want to refer to them by index.
14927 Roo.MasterTemplate = function(){
14928 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
14929 this.originalHtml = this.html;
14931 var m, re = this.subTemplateRe;
14934 while(m = re.exec(this.html)){
14935 var name = m[1], content = m[2];
14940 tpl : new Roo.Template(content)
14943 st[name] = st[subIndex];
14945 st[subIndex].tpl.compile();
14946 st[subIndex].tpl.call = this.call.createDelegate(this);
14949 this.subCount = subIndex;
14952 Roo.extend(Roo.MasterTemplate, Roo.Template, {
14954 * The regular expression used to match sub templates
14958 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
14961 * Applies the passed values to a child template.
14962 * @param {String/Number} name (optional) The name or index of the child template
14963 * @param {Array/Object} values The values to be applied to the template
14964 * @return {MasterTemplate} this
14966 add : function(name, values){
14967 if(arguments.length == 1){
14968 values = arguments[0];
14971 var s = this.subs[name];
14972 s.buffer[s.buffer.length] = s.tpl.apply(values);
14977 * Applies all the passed values to a child template.
14978 * @param {String/Number} name (optional) The name or index of the child template
14979 * @param {Array} values The values to be applied to the template, this should be an array of objects.
14980 * @param {Boolean} reset (optional) True to reset the template first
14981 * @return {MasterTemplate} this
14983 fill : function(name, values, reset){
14985 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
14993 for(var i = 0, len = values.length; i < len; i++){
14994 this.add(name, values[i]);
15000 * Resets the template for reuse
15001 * @return {MasterTemplate} this
15003 reset : function(){
15005 for(var i = 0; i < this.subCount; i++){
15011 applyTemplate : function(values){
15013 var replaceIndex = -1;
15014 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
15015 return s[++replaceIndex].buffer.join("");
15017 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
15020 apply : function(){
15021 return this.applyTemplate.apply(this, arguments);
15024 compile : function(){return this;}
15028 * Alias for fill().
15031 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
15033 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
15034 * var tpl = Roo.MasterTemplate.from('element-id');
15035 * @param {String/HTMLElement} el
15036 * @param {Object} config
15039 Roo.MasterTemplate.from = function(el, config){
15040 el = Roo.getDom(el);
15041 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
15044 * Ext JS Library 1.1.1
15045 * Copyright(c) 2006-2007, Ext JS, LLC.
15047 * Originally Released Under LGPL - original licence link has changed is not relivant.
15050 * <script type="text/javascript">
15055 * @class Roo.util.CSS
15056 * Utility class for manipulating CSS rules
15060 Roo.util.CSS = function(){
15062 var doc = document;
15064 var camelRe = /(-[a-z])/gi;
15065 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
15069 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
15070 * tag and appended to the HEAD of the document.
15071 * @param {String|Object} cssText The text containing the css rules
15072 * @param {String} id An id to add to the stylesheet for later removal
15073 * @return {StyleSheet}
15075 createStyleSheet : function(cssText, id){
15077 var head = doc.getElementsByTagName("head")[0];
15078 var nrules = doc.createElement("style");
15079 nrules.setAttribute("type", "text/css");
15081 nrules.setAttribute("id", id);
15083 if (typeof(cssText) != 'string') {
15084 // support object maps..
15085 // not sure if this a good idea..
15086 // perhaps it should be merged with the general css handling
15087 // and handle js style props.
15088 var cssTextNew = [];
15089 for(var n in cssText) {
15091 for(var k in cssText[n]) {
15092 citems.push( k + ' : ' +cssText[n][k] + ';' );
15094 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
15097 cssText = cssTextNew.join("\n");
15103 head.appendChild(nrules);
15104 ss = nrules.styleSheet;
15105 ss.cssText = cssText;
15108 nrules.appendChild(doc.createTextNode(cssText));
15110 nrules.cssText = cssText;
15112 head.appendChild(nrules);
15113 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
15115 this.cacheStyleSheet(ss);
15120 * Removes a style or link tag by id
15121 * @param {String} id The id of the tag
15123 removeStyleSheet : function(id){
15124 var existing = doc.getElementById(id);
15126 existing.parentNode.removeChild(existing);
15131 * Dynamically swaps an existing stylesheet reference for a new one
15132 * @param {String} id The id of an existing link tag to remove
15133 * @param {String} url The href of the new stylesheet to include
15135 swapStyleSheet : function(id, url){
15136 this.removeStyleSheet(id);
15137 var ss = doc.createElement("link");
15138 ss.setAttribute("rel", "stylesheet");
15139 ss.setAttribute("type", "text/css");
15140 ss.setAttribute("id", id);
15141 ss.setAttribute("href", url);
15142 doc.getElementsByTagName("head")[0].appendChild(ss);
15146 * Refresh the rule cache if you have dynamically added stylesheets
15147 * @return {Object} An object (hash) of rules indexed by selector
15149 refreshCache : function(){
15150 return this.getRules(true);
15154 cacheStyleSheet : function(stylesheet){
15158 try{// try catch for cross domain access issue
15159 var ssRules = stylesheet.cssRules || stylesheet.rules;
15160 for(var j = ssRules.length-1; j >= 0; --j){
15161 rules[ssRules[j].selectorText] = ssRules[j];
15167 * Gets all css rules for the document
15168 * @param {Boolean} refreshCache true to refresh the internal cache
15169 * @return {Object} An object (hash) of rules indexed by selector
15171 getRules : function(refreshCache){
15172 if(rules == null || refreshCache){
15174 var ds = doc.styleSheets;
15175 for(var i =0, len = ds.length; i < len; i++){
15177 this.cacheStyleSheet(ds[i]);
15185 * Gets an an individual CSS rule by selector(s)
15186 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
15187 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
15188 * @return {CSSRule} The CSS rule or null if one is not found
15190 getRule : function(selector, refreshCache){
15191 var rs = this.getRules(refreshCache);
15192 if(!(selector instanceof Array)){
15193 return rs[selector];
15195 for(var i = 0; i < selector.length; i++){
15196 if(rs[selector[i]]){
15197 return rs[selector[i]];
15205 * Updates a rule property
15206 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
15207 * @param {String} property The css property
15208 * @param {String} value The new value for the property
15209 * @return {Boolean} true If a rule was found and updated
15211 updateRule : function(selector, property, value){
15212 if(!(selector instanceof Array)){
15213 var rule = this.getRule(selector);
15215 rule.style[property.replace(camelRe, camelFn)] = value;
15219 for(var i = 0; i < selector.length; i++){
15220 if(this.updateRule(selector[i], property, value)){
15230 * Ext JS Library 1.1.1
15231 * Copyright(c) 2006-2007, Ext JS, LLC.
15233 * Originally Released Under LGPL - original licence link has changed is not relivant.
15236 * <script type="text/javascript">
15242 * @class Roo.util.ClickRepeater
15243 * @extends Roo.util.Observable
15245 * A wrapper class which can be applied to any element. Fires a "click" event while the
15246 * mouse is pressed. The interval between firings may be specified in the config but
15247 * defaults to 10 milliseconds.
15249 * Optionally, a CSS class may be applied to the element during the time it is pressed.
15251 * @cfg {String/HTMLElement/Element} el The element to act as a button.
15252 * @cfg {Number} delay The initial delay before the repeating event begins firing.
15253 * Similar to an autorepeat key delay.
15254 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
15255 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
15256 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
15257 * "interval" and "delay" are ignored. "immediate" is honored.
15258 * @cfg {Boolean} preventDefault True to prevent the default click event
15259 * @cfg {Boolean} stopDefault True to stop the default click event
15262 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
15263 * 2007-02-02 jvs Renamed to ClickRepeater
15264 * 2007-02-03 jvs Modifications for FF Mac and Safari
15267 * @param {String/HTMLElement/Element} el The element to listen on
15268 * @param {Object} config
15270 Roo.util.ClickRepeater = function(el, config)
15272 this.el = Roo.get(el);
15273 this.el.unselectable();
15275 Roo.apply(this, config);
15280 * Fires when the mouse button is depressed.
15281 * @param {Roo.util.ClickRepeater} this
15283 "mousedown" : true,
15286 * Fires on a specified interval during the time the element is pressed.
15287 * @param {Roo.util.ClickRepeater} this
15292 * Fires when the mouse key is released.
15293 * @param {Roo.util.ClickRepeater} this
15298 this.el.on("mousedown", this.handleMouseDown, this);
15299 if(this.preventDefault || this.stopDefault){
15300 this.el.on("click", function(e){
15301 if(this.preventDefault){
15302 e.preventDefault();
15304 if(this.stopDefault){
15310 // allow inline handler
15312 this.on("click", this.handler, this.scope || this);
15315 Roo.util.ClickRepeater.superclass.constructor.call(this);
15318 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
15321 preventDefault : true,
15322 stopDefault : false,
15326 handleMouseDown : function(){
15327 clearTimeout(this.timer);
15329 if(this.pressClass){
15330 this.el.addClass(this.pressClass);
15332 this.mousedownTime = new Date();
15334 Roo.get(document).on("mouseup", this.handleMouseUp, this);
15335 this.el.on("mouseout", this.handleMouseOut, this);
15337 this.fireEvent("mousedown", this);
15338 this.fireEvent("click", this);
15340 this.timer = this.click.defer(this.delay || this.interval, this);
15344 click : function(){
15345 this.fireEvent("click", this);
15346 this.timer = this.click.defer(this.getInterval(), this);
15350 getInterval: function(){
15351 if(!this.accelerate){
15352 return this.interval;
15354 var pressTime = this.mousedownTime.getElapsed();
15355 if(pressTime < 500){
15357 }else if(pressTime < 1700){
15359 }else if(pressTime < 2600){
15361 }else if(pressTime < 3500){
15363 }else if(pressTime < 4400){
15365 }else if(pressTime < 5300){
15367 }else if(pressTime < 6200){
15375 handleMouseOut : function(){
15376 clearTimeout(this.timer);
15377 if(this.pressClass){
15378 this.el.removeClass(this.pressClass);
15380 this.el.on("mouseover", this.handleMouseReturn, this);
15384 handleMouseReturn : function(){
15385 this.el.un("mouseover", this.handleMouseReturn);
15386 if(this.pressClass){
15387 this.el.addClass(this.pressClass);
15393 handleMouseUp : function(){
15394 clearTimeout(this.timer);
15395 this.el.un("mouseover", this.handleMouseReturn);
15396 this.el.un("mouseout", this.handleMouseOut);
15397 Roo.get(document).un("mouseup", this.handleMouseUp);
15398 this.el.removeClass(this.pressClass);
15399 this.fireEvent("mouseup", this);
15402 * @class Roo.util.Clipboard
15408 Roo.util.Clipboard = {
15410 * Writes a string to the clipboard - using the Clipboard API if https, otherwise using text area.
15411 * @param {String} text to copy to clipboard
15413 write : function(text) {
15414 // navigator clipboard api needs a secure context (https)
15415 if (navigator.clipboard && window.isSecureContext) {
15416 // navigator clipboard api method'
15417 navigator.clipboard.writeText(text);
15420 // text area method
15421 var ta = document.createElement("textarea");
15423 // make the textarea out of viewport
15424 ta.style.position = "fixed";
15425 ta.style.left = "-999999px";
15426 ta.style.top = "-999999px";
15427 document.body.appendChild(ta);
15430 document.execCommand('copy');
15440 * Ext JS Library 1.1.1
15441 * Copyright(c) 2006-2007, Ext JS, LLC.
15443 * Originally Released Under LGPL - original licence link has changed is not relivant.
15446 * <script type="text/javascript">
15451 * @class Roo.KeyNav
15452 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
15453 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
15454 * way to implement custom navigation schemes for any UI component.</p>
15455 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
15456 * pageUp, pageDown, del, home, end. Usage:</p>
15458 var nav = new Roo.KeyNav("my-element", {
15459 "left" : function(e){
15460 this.moveLeft(e.ctrlKey);
15462 "right" : function(e){
15463 this.moveRight(e.ctrlKey);
15465 "enter" : function(e){
15472 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15473 * @param {Object} config The config
15475 Roo.KeyNav = function(el, config){
15476 this.el = Roo.get(el);
15477 Roo.apply(this, config);
15478 if(!this.disabled){
15479 this.disabled = true;
15484 Roo.KeyNav.prototype = {
15486 * @cfg {Boolean} disabled
15487 * True to disable this KeyNav instance (defaults to false)
15491 * @cfg {String} defaultEventAction
15492 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
15493 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
15494 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
15496 defaultEventAction: "stopEvent",
15498 * @cfg {Boolean} forceKeyDown
15499 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
15500 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
15501 * handle keydown instead of keypress.
15503 forceKeyDown : false,
15506 prepareEvent : function(e){
15507 var k = e.getKey();
15508 var h = this.keyToHandler[k];
15509 //if(h && this[h]){
15510 // e.stopPropagation();
15512 if(Roo.isSafari && h && k >= 37 && k <= 40){
15518 relay : function(e){
15519 var k = e.getKey();
15520 var h = this.keyToHandler[k];
15522 if(this.doRelay(e, this[h], h) !== true){
15523 e[this.defaultEventAction]();
15529 doRelay : function(e, h, hname){
15530 return h.call(this.scope || this, e);
15533 // possible handlers
15547 // quick lookup hash
15564 * Enable this KeyNav
15566 enable: function(){
15568 // ie won't do special keys on keypress, no one else will repeat keys with keydown
15569 // the EventObject will normalize Safari automatically
15570 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15571 this.el.on("keydown", this.relay, this);
15573 this.el.on("keydown", this.prepareEvent, this);
15574 this.el.on("keypress", this.relay, this);
15576 this.disabled = false;
15581 * Disable this KeyNav
15583 disable: function(){
15584 if(!this.disabled){
15585 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15586 this.el.un("keydown", this.relay);
15588 this.el.un("keydown", this.prepareEvent);
15589 this.el.un("keypress", this.relay);
15591 this.disabled = true;
15596 * Ext JS Library 1.1.1
15597 * Copyright(c) 2006-2007, Ext JS, LLC.
15599 * Originally Released Under LGPL - original licence link has changed is not relivant.
15602 * <script type="text/javascript">
15607 * @class Roo.KeyMap
15608 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
15609 * The constructor accepts the same config object as defined by {@link #addBinding}.
15610 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
15611 * combination it will call the function with this signature (if the match is a multi-key
15612 * combination the callback will still be called only once): (String key, Roo.EventObject e)
15613 * A KeyMap can also handle a string representation of keys.<br />
15616 // map one key by key code
15617 var map = new Roo.KeyMap("my-element", {
15618 key: 13, // or Roo.EventObject.ENTER
15623 // map multiple keys to one action by string
15624 var map = new Roo.KeyMap("my-element", {
15630 // map multiple keys to multiple actions by strings and array of codes
15631 var map = new Roo.KeyMap("my-element", [
15634 fn: function(){ alert("Return was pressed"); }
15637 fn: function(){ alert('a, b or c was pressed'); }
15642 fn: function(){ alert('Control + shift + tab was pressed.'); }
15646 * <b>Note: A KeyMap starts enabled</b>
15648 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15649 * @param {Object} config The config (see {@link #addBinding})
15650 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
15652 Roo.KeyMap = function(el, config, eventName){
15653 this.el = Roo.get(el);
15654 this.eventName = eventName || "keydown";
15655 this.bindings = [];
15657 this.addBinding(config);
15662 Roo.KeyMap.prototype = {
15664 * True to stop the event from bubbling and prevent the default browser action if the
15665 * key was handled by the KeyMap (defaults to false)
15671 * Add a new binding to this KeyMap. The following config object properties are supported:
15673 Property Type Description
15674 ---------- --------------- ----------------------------------------------------------------------
15675 key String/Array A single keycode or an array of keycodes to handle
15676 shift Boolean True to handle key only when shift is pressed (defaults to false)
15677 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
15678 alt Boolean True to handle key only when alt is pressed (defaults to false)
15679 fn Function The function to call when KeyMap finds the expected key combination
15680 scope Object The scope of the callback function
15686 var map = new Roo.KeyMap(document, {
15687 key: Roo.EventObject.ENTER,
15692 //Add a new binding to the existing KeyMap later
15700 * @param {Object/Array} config A single KeyMap config or an array of configs
15702 addBinding : function(config){
15703 if(config instanceof Array){
15704 for(var i = 0, len = config.length; i < len; i++){
15705 this.addBinding(config[i]);
15709 var keyCode = config.key,
15710 shift = config.shift,
15711 ctrl = config.ctrl,
15714 scope = config.scope;
15715 if(typeof keyCode == "string"){
15717 var keyString = keyCode.toUpperCase();
15718 for(var j = 0, len = keyString.length; j < len; j++){
15719 ks.push(keyString.charCodeAt(j));
15723 var keyArray = keyCode instanceof Array;
15724 var handler = function(e){
15725 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
15726 var k = e.getKey();
15728 for(var i = 0, len = keyCode.length; i < len; i++){
15729 if(keyCode[i] == k){
15730 if(this.stopEvent){
15733 fn.call(scope || window, k, e);
15739 if(this.stopEvent){
15742 fn.call(scope || window, k, e);
15747 this.bindings.push(handler);
15751 * Shorthand for adding a single key listener
15752 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
15753 * following options:
15754 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
15755 * @param {Function} fn The function to call
15756 * @param {Object} scope (optional) The scope of the function
15758 on : function(key, fn, scope){
15759 var keyCode, shift, ctrl, alt;
15760 if(typeof key == "object" && !(key instanceof Array)){
15779 handleKeyDown : function(e){
15780 if(this.enabled){ //just in case
15781 var b = this.bindings;
15782 for(var i = 0, len = b.length; i < len; i++){
15783 b[i].call(this, e);
15789 * Returns true if this KeyMap is enabled
15790 * @return {Boolean}
15792 isEnabled : function(){
15793 return this.enabled;
15797 * Enables this KeyMap
15799 enable: function(){
15801 this.el.on(this.eventName, this.handleKeyDown, this);
15802 this.enabled = true;
15807 * Disable this KeyMap
15809 disable: function(){
15811 this.el.removeListener(this.eventName, this.handleKeyDown, this);
15812 this.enabled = false;
15817 * Ext JS Library 1.1.1
15818 * Copyright(c) 2006-2007, Ext JS, LLC.
15820 * Originally Released Under LGPL - original licence link has changed is not relivant.
15823 * <script type="text/javascript">
15828 * @class Roo.util.TextMetrics
15829 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
15830 * wide, in pixels, a given block of text will be.
15833 Roo.util.TextMetrics = function(){
15837 * Measures the size of the specified text
15838 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
15839 * that can affect the size of the rendered text
15840 * @param {String} text The text to measure
15841 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15842 * in order to accurately measure the text height
15843 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15845 measure : function(el, text, fixedWidth){
15847 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
15850 shared.setFixedWidth(fixedWidth || 'auto');
15851 return shared.getSize(text);
15855 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
15856 * the overhead of multiple calls to initialize the style properties on each measurement.
15857 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
15858 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15859 * in order to accurately measure the text height
15860 * @return {Roo.util.TextMetrics.Instance} instance The new instance
15862 createInstance : function(el, fixedWidth){
15863 return Roo.util.TextMetrics.Instance(el, fixedWidth);
15869 * @class Roo.util.TextMetrics.Instance
15870 * Instance of TextMetrics Calcuation
15872 * Create a new TextMetrics Instance
15873 * @param {Object} bindto
15874 * @param {Boolean} fixedWidth
15877 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth)
15879 var ml = new Roo.Element(document.createElement('div'));
15880 document.body.appendChild(ml.dom);
15881 ml.position('absolute');
15882 ml.setLeftTop(-1000, -1000);
15886 ml.setWidth(fixedWidth);
15891 * Returns the size of the specified text based on the internal element's style and width properties
15892 * @param {String} text The text to measure
15893 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15895 getSize : function(text){
15897 var s = ml.getSize();
15903 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
15904 * that can affect the size of the rendered text
15905 * @param {String/HTMLElement} el The element, dom node or id
15907 bind : function(el){
15909 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
15914 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
15915 * to set a fixed width in order to accurately measure the text height.
15916 * @param {Number} width The width to set on the element
15918 setFixedWidth : function(width){
15919 ml.setWidth(width);
15923 * Returns the measured width of the specified text
15924 * @param {String} text The text to measure
15925 * @return {Number} width The width in pixels
15927 getWidth : function(text){
15928 ml.dom.style.width = 'auto';
15929 return this.getSize(text).width;
15933 * Returns the measured height of the specified text. For multiline text, be sure to call
15934 * {@link #setFixedWidth} if necessary.
15935 * @param {String} text The text to measure
15936 * @return {Number} height The height in pixels
15938 getHeight : function(text){
15939 return this.getSize(text).height;
15943 instance.bind(bindTo);
15948 // backwards compat
15949 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
15951 * Ext JS Library 1.1.1
15952 * Copyright(c) 2006-2007, Ext JS, LLC.
15954 * Originally Released Under LGPL - original licence link has changed is not relivant.
15957 * <script type="text/javascript">
15961 * @class Roo.state.Provider
15962 * Abstract base class for state provider implementations. This class provides methods
15963 * for encoding and decoding <b>typed</b> variables including dates and defines the
15964 * Provider interface.
15966 Roo.state.Provider = function(){
15968 * @event statechange
15969 * Fires when a state change occurs.
15970 * @param {Provider} this This state provider
15971 * @param {String} key The state key which was changed
15972 * @param {String} value The encoded value for the state
15975 "statechange": true
15978 Roo.state.Provider.superclass.constructor.call(this);
15980 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
15982 * Returns the current value for a key
15983 * @param {String} name The key name
15984 * @param {Mixed} defaultValue A default value to return if the key's value is not found
15985 * @return {Mixed} The state data
15987 get : function(name, defaultValue){
15988 return typeof this.state[name] == "undefined" ?
15989 defaultValue : this.state[name];
15993 * Clears a value from the state
15994 * @param {String} name The key name
15996 clear : function(name){
15997 delete this.state[name];
15998 this.fireEvent("statechange", this, name, null);
16002 * Sets the value for a key
16003 * @param {String} name The key name
16004 * @param {Mixed} value The value to set
16006 set : function(name, value){
16007 this.state[name] = value;
16008 this.fireEvent("statechange", this, name, value);
16012 * Decodes a string previously encoded with {@link #encodeValue}.
16013 * @param {String} value The value to decode
16014 * @return {Mixed} The decoded value
16016 decodeValue : function(cookie){
16017 var re = /^(a|n|d|b|s|o)\:(.*)$/;
16018 var matches = re.exec(unescape(cookie));
16019 if(!matches || !matches[1]) {
16020 return; // non state cookie
16022 var type = matches[1];
16023 var v = matches[2];
16026 return parseFloat(v);
16028 return new Date(Date.parse(v));
16033 var values = v.split("^");
16034 for(var i = 0, len = values.length; i < len; i++){
16035 all.push(this.decodeValue(values[i]));
16040 var values = v.split("^");
16041 for(var i = 0, len = values.length; i < len; i++){
16042 var kv = values[i].split("=");
16043 all[kv[0]] = this.decodeValue(kv[1]);
16052 * Encodes a value including type information. Decode with {@link #decodeValue}.
16053 * @param {Mixed} value The value to encode
16054 * @return {String} The encoded value
16056 encodeValue : function(v){
16058 if(typeof v == "number"){
16060 }else if(typeof v == "boolean"){
16061 enc = "b:" + (v ? "1" : "0");
16062 }else if(v instanceof Date){
16063 enc = "d:" + v.toGMTString();
16064 }else if(v instanceof Array){
16066 for(var i = 0, len = v.length; i < len; i++){
16067 flat += this.encodeValue(v[i]);
16073 }else if(typeof v == "object"){
16076 if(typeof v[key] != "function"){
16077 flat += key + "=" + this.encodeValue(v[key]) + "^";
16080 enc = "o:" + flat.substring(0, flat.length-1);
16084 return escape(enc);
16090 * Ext JS Library 1.1.1
16091 * Copyright(c) 2006-2007, Ext JS, LLC.
16093 * Originally Released Under LGPL - original licence link has changed is not relivant.
16096 * <script type="text/javascript">
16099 * @class Roo.state.Manager
16100 * This is the global state manager. By default all components that are "state aware" check this class
16101 * for state information if you don't pass them a custom state provider. In order for this class
16102 * to be useful, it must be initialized with a provider when your application initializes.
16104 // in your initialization function
16106 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
16108 // supposed you have a {@link Roo.BorderLayout}
16109 var layout = new Roo.BorderLayout(...);
16110 layout.restoreState();
16111 // or a {Roo.BasicDialog}
16112 var dialog = new Roo.BasicDialog(...);
16113 dialog.restoreState();
16117 Roo.state.Manager = function(){
16118 var provider = new Roo.state.Provider();
16122 * Configures the default state provider for your application
16123 * @param {Provider} stateProvider The state provider to set
16125 setProvider : function(stateProvider){
16126 provider = stateProvider;
16130 * Returns the current value for a key
16131 * @param {String} name The key name
16132 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
16133 * @return {Mixed} The state data
16135 get : function(key, defaultValue){
16136 return provider.get(key, defaultValue);
16140 * Sets the value for a key
16141 * @param {String} name The key name
16142 * @param {Mixed} value The state data
16144 set : function(key, value){
16145 provider.set(key, value);
16149 * Clears a value from the state
16150 * @param {String} name The key name
16152 clear : function(key){
16153 provider.clear(key);
16157 * Gets the currently configured state provider
16158 * @return {Provider} The state provider
16160 getProvider : function(){
16167 * Ext JS Library 1.1.1
16168 * Copyright(c) 2006-2007, Ext JS, LLC.
16170 * Originally Released Under LGPL - original licence link has changed is not relivant.
16173 * <script type="text/javascript">
16176 * @class Roo.state.CookieProvider
16177 * @extends Roo.state.Provider
16178 * The default Provider implementation which saves state via cookies.
16181 var cp = new Roo.state.CookieProvider({
16183 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
16184 domain: "roojs.com"
16186 Roo.state.Manager.setProvider(cp);
16188 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
16189 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
16190 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
16191 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
16192 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
16193 * domain the page is running on including the 'www' like 'www.roojs.com')
16194 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
16196 * Create a new CookieProvider
16197 * @param {Object} config The configuration object
16199 Roo.state.CookieProvider = function(config){
16200 Roo.state.CookieProvider.superclass.constructor.call(this);
16202 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
16203 this.domain = null;
16204 this.secure = false;
16205 Roo.apply(this, config);
16206 this.state = this.readCookies();
16209 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
16211 set : function(name, value){
16212 if(typeof value == "undefined" || value === null){
16216 this.setCookie(name, value);
16217 Roo.state.CookieProvider.superclass.set.call(this, name, value);
16221 clear : function(name){
16222 this.clearCookie(name);
16223 Roo.state.CookieProvider.superclass.clear.call(this, name);
16227 readCookies : function(){
16229 var c = document.cookie + ";";
16230 var re = /\s?(.*?)=(.*?);/g;
16232 while((matches = re.exec(c)) != null){
16233 var name = matches[1];
16234 var value = matches[2];
16235 if(name && name.substring(0,3) == "ys-"){
16236 cookies[name.substr(3)] = this.decodeValue(value);
16243 setCookie : function(name, value){
16244 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
16245 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
16246 ((this.path == null) ? "" : ("; path=" + this.path)) +
16247 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16248 ((this.secure == true) ? "; secure" : "");
16252 clearCookie : function(name){
16253 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
16254 ((this.path == null) ? "" : ("; path=" + this.path)) +
16255 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16256 ((this.secure == true) ? "; secure" : "");
16260 * Ext JS Library 1.1.1
16261 * Copyright(c) 2006-2007, Ext JS, LLC.
16263 * Originally Released Under LGPL - original licence link has changed is not relivant.
16266 * <script type="text/javascript">
16271 * @class Roo.ComponentMgr
16272 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
16275 Roo.ComponentMgr = function(){
16276 var all = new Roo.util.MixedCollection();
16280 * Registers a component.
16281 * @param {Roo.Component} c The component
16283 register : function(c){
16288 * Unregisters a component.
16289 * @param {Roo.Component} c The component
16291 unregister : function(c){
16296 * Returns a component by id
16297 * @param {String} id The component id
16299 get : function(id){
16300 return all.get(id);
16304 * Registers a function that will be called when a specified component is added to ComponentMgr
16305 * @param {String} id The component id
16306 * @param {Funtction} fn The callback function
16307 * @param {Object} scope The scope of the callback
16309 onAvailable : function(id, fn, scope){
16310 all.on("add", function(index, o){
16312 fn.call(scope || o, o);
16313 all.un("add", fn, scope);
16320 * Ext JS Library 1.1.1
16321 * Copyright(c) 2006-2007, Ext JS, LLC.
16323 * Originally Released Under LGPL - original licence link has changed is not relivant.
16326 * <script type="text/javascript">
16330 * @class Roo.Component
16331 * @extends Roo.util.Observable
16332 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
16333 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
16334 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
16335 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
16336 * All visual components (widgets) that require rendering into a layout should subclass Component.
16338 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
16339 * 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
16340 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
16342 Roo.Component = function(config){
16343 config = config || {};
16344 if(config.tagName || config.dom || typeof config == "string"){ // element object
16345 config = {el: config, id: config.id || config};
16347 this.initialConfig = config;
16349 Roo.apply(this, config);
16353 * Fires after the component is disabled.
16354 * @param {Roo.Component} this
16359 * Fires after the component is enabled.
16360 * @param {Roo.Component} this
16364 * @event beforeshow
16365 * Fires before the component is shown. Return false to stop the show.
16366 * @param {Roo.Component} this
16371 * Fires after the component is shown.
16372 * @param {Roo.Component} this
16376 * @event beforehide
16377 * Fires before the component is hidden. Return false to stop the hide.
16378 * @param {Roo.Component} this
16383 * Fires after the component is hidden.
16384 * @param {Roo.Component} this
16388 * @event beforerender
16389 * Fires before the component is rendered. Return false to stop the render.
16390 * @param {Roo.Component} this
16392 beforerender : true,
16395 * Fires after the component is rendered.
16396 * @param {Roo.Component} this
16400 * @event beforedestroy
16401 * Fires before the component is destroyed. Return false to stop the destroy.
16402 * @param {Roo.Component} this
16404 beforedestroy : true,
16407 * Fires after the component is destroyed.
16408 * @param {Roo.Component} this
16413 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
16415 Roo.ComponentMgr.register(this);
16416 Roo.Component.superclass.constructor.call(this);
16417 this.initComponent();
16418 if(this.renderTo){ // not supported by all components yet. use at your own risk!
16419 this.render(this.renderTo);
16420 delete this.renderTo;
16425 Roo.Component.AUTO_ID = 1000;
16427 Roo.extend(Roo.Component, Roo.util.Observable, {
16429 * @scope Roo.Component.prototype
16431 * true if this component is hidden. Read-only.
16436 * true if this component is disabled. Read-only.
16441 * true if this component has been rendered. Read-only.
16445 /** @cfg {String} disableClass
16446 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
16448 disabledClass : "x-item-disabled",
16449 /** @cfg {Boolean} allowDomMove
16450 * Whether the component can move the Dom node when rendering (defaults to true).
16452 allowDomMove : true,
16453 /** @cfg {String} hideMode (display|visibility)
16454 * How this component should hidden. Supported values are
16455 * "visibility" (css visibility), "offsets" (negative offset position) and
16456 * "display" (css display) - defaults to "display".
16458 hideMode: 'display',
16461 ctype : "Roo.Component",
16464 * @cfg {String} actionMode
16465 * which property holds the element that used for hide() / show() / disable() / enable()
16466 * default is 'el' for forms you probably want to set this to fieldEl
16471 getActionEl : function(){
16472 return this[this.actionMode];
16475 initComponent : Roo.emptyFn,
16477 * If this is a lazy rendering component, render it to its container element.
16478 * @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.
16480 render : function(container, position){
16486 if(this.fireEvent("beforerender", this) === false){
16490 if(!container && this.el){
16491 this.el = Roo.get(this.el);
16492 container = this.el.dom.parentNode;
16493 this.allowDomMove = false;
16495 this.container = Roo.get(container);
16496 this.rendered = true;
16497 if(position !== undefined){
16498 if(typeof position == 'number'){
16499 position = this.container.dom.childNodes[position];
16501 position = Roo.getDom(position);
16504 this.onRender(this.container, position || null);
16506 this.el.addClass(this.cls);
16510 this.el.applyStyles(this.style);
16513 this.fireEvent("render", this);
16514 this.afterRender(this.container);
16527 // default function is not really useful
16528 onRender : function(ct, position){
16530 this.el = Roo.get(this.el);
16531 if(this.allowDomMove !== false){
16532 ct.dom.insertBefore(this.el.dom, position);
16538 getAutoCreate : function(){
16539 var cfg = typeof this.autoCreate == "object" ?
16540 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
16541 if(this.id && !cfg.id){
16548 afterRender : Roo.emptyFn,
16551 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
16552 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
16554 destroy : function(){
16555 if(this.fireEvent("beforedestroy", this) !== false){
16556 this.purgeListeners();
16557 this.beforeDestroy();
16559 this.el.removeAllListeners();
16561 if(this.actionMode == "container"){
16562 this.container.remove();
16566 Roo.ComponentMgr.unregister(this);
16567 this.fireEvent("destroy", this);
16572 beforeDestroy : function(){
16577 onDestroy : function(){
16582 * Returns the underlying {@link Roo.Element}.
16583 * @return {Roo.Element} The element
16585 getEl : function(){
16590 * Returns the id of this component.
16593 getId : function(){
16598 * Try to focus this component.
16599 * @param {Boolean} selectText True to also select the text in this component (if applicable)
16600 * @return {Roo.Component} this
16602 focus : function(selectText){
16605 if(selectText === true){
16606 this.el.dom.select();
16621 * Disable this component.
16622 * @return {Roo.Component} this
16624 disable : function(){
16628 this.disabled = true;
16629 this.fireEvent("disable", this);
16634 onDisable : function(){
16635 this.getActionEl().addClass(this.disabledClass);
16636 this.el.dom.disabled = true;
16640 * Enable this component.
16641 * @return {Roo.Component} this
16643 enable : function(){
16647 this.disabled = false;
16648 this.fireEvent("enable", this);
16653 onEnable : function(){
16654 this.getActionEl().removeClass(this.disabledClass);
16655 this.el.dom.disabled = false;
16659 * Convenience function for setting disabled/enabled by boolean.
16660 * @param {Boolean} disabled
16662 setDisabled : function(disabled){
16663 this[disabled ? "disable" : "enable"]();
16667 * Show this component.
16668 * @return {Roo.Component} this
16671 if(this.fireEvent("beforeshow", this) !== false){
16672 this.hidden = false;
16676 this.fireEvent("show", this);
16682 onShow : function(){
16683 var ae = this.getActionEl();
16684 if(this.hideMode == 'visibility'){
16685 ae.dom.style.visibility = "visible";
16686 }else if(this.hideMode == 'offsets'){
16687 ae.removeClass('x-hidden');
16689 ae.dom.style.display = "";
16694 * Hide this component.
16695 * @return {Roo.Component} this
16698 if(this.fireEvent("beforehide", this) !== false){
16699 this.hidden = true;
16703 this.fireEvent("hide", this);
16709 onHide : function(){
16710 var ae = this.getActionEl();
16711 if(this.hideMode == 'visibility'){
16712 ae.dom.style.visibility = "hidden";
16713 }else if(this.hideMode == 'offsets'){
16714 ae.addClass('x-hidden');
16716 ae.dom.style.display = "none";
16721 * Convenience function to hide or show this component by boolean.
16722 * @param {Boolean} visible True to show, false to hide
16723 * @return {Roo.Component} this
16725 setVisible: function(visible){
16735 * Returns true if this component is visible.
16737 isVisible : function(){
16738 return this.getActionEl().isVisible();
16741 cloneConfig : function(overrides){
16742 overrides = overrides || {};
16743 var id = overrides.id || Roo.id();
16744 var cfg = Roo.applyIf(overrides, this.initialConfig);
16745 cfg.id = id; // prevent dup id
16746 return new this.constructor(cfg);
16750 * Ext JS Library 1.1.1
16751 * Copyright(c) 2006-2007, Ext JS, LLC.
16753 * Originally Released Under LGPL - original licence link has changed is not relivant.
16756 * <script type="text/javascript">
16760 * @class Roo.BoxComponent
16761 * @extends Roo.Component
16762 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
16763 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
16764 * container classes should subclass BoxComponent so that they will work consistently when nested within other Roo
16765 * layout containers.
16767 * @param {Roo.Element/String/Object} config The configuration options.
16769 Roo.BoxComponent = function(config){
16770 Roo.Component.call(this, config);
16774 * Fires after the component is resized.
16775 * @param {Roo.Component} this
16776 * @param {Number} adjWidth The box-adjusted width that was set
16777 * @param {Number} adjHeight The box-adjusted height that was set
16778 * @param {Number} rawWidth The width that was originally specified
16779 * @param {Number} rawHeight The height that was originally specified
16784 * Fires after the component is moved.
16785 * @param {Roo.Component} this
16786 * @param {Number} x The new x position
16787 * @param {Number} y The new y position
16793 Roo.extend(Roo.BoxComponent, Roo.Component, {
16794 // private, set in afterRender to signify that the component has been rendered
16796 // private, used to defer height settings to subclasses
16797 deferHeight: false,
16798 /** @cfg {Number} width
16799 * width (optional) size of component
16801 /** @cfg {Number} height
16802 * height (optional) size of component
16806 * Sets the width and height of the component. This method fires the resize event. This method can accept
16807 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
16808 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
16809 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
16810 * @return {Roo.BoxComponent} this
16812 setSize : function(w, h){
16813 // support for standard size objects
16814 if(typeof w == 'object'){
16819 if(!this.boxReady){
16825 // prevent recalcs when not needed
16826 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
16829 this.lastSize = {width: w, height: h};
16831 var adj = this.adjustSize(w, h);
16832 var aw = adj.width, ah = adj.height;
16833 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
16834 var rz = this.getResizeEl();
16835 if(!this.deferHeight && aw !== undefined && ah !== undefined){
16836 rz.setSize(aw, ah);
16837 }else if(!this.deferHeight && ah !== undefined){
16839 }else if(aw !== undefined){
16842 this.onResize(aw, ah, w, h);
16843 this.fireEvent('resize', this, aw, ah, w, h);
16849 * Gets the current size of the component's underlying element.
16850 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
16852 getSize : function(){
16853 return this.el.getSize();
16857 * Gets the current XY position of the component's underlying element.
16858 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16859 * @return {Array} The XY position of the element (e.g., [100, 200])
16861 getPosition : function(local){
16862 if(local === true){
16863 return [this.el.getLeft(true), this.el.getTop(true)];
16865 return this.xy || this.el.getXY();
16869 * Gets the current box measurements of the component's underlying element.
16870 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16871 * @returns {Object} box An object in the format {x, y, width, height}
16873 getBox : function(local){
16874 var s = this.el.getSize();
16876 s.x = this.el.getLeft(true);
16877 s.y = this.el.getTop(true);
16879 var xy = this.xy || this.el.getXY();
16887 * Sets the current box measurements of the component's underlying element.
16888 * @param {Object} box An object in the format {x, y, width, height}
16889 * @returns {Roo.BoxComponent} this
16891 updateBox : function(box){
16892 this.setSize(box.width, box.height);
16893 this.setPagePosition(box.x, box.y);
16898 getResizeEl : function(){
16899 return this.resizeEl || this.el;
16903 getPositionEl : function(){
16904 return this.positionEl || this.el;
16908 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
16909 * This method fires the move event.
16910 * @param {Number} left The new left
16911 * @param {Number} top The new top
16912 * @returns {Roo.BoxComponent} this
16914 setPosition : function(x, y){
16917 if(!this.boxReady){
16920 var adj = this.adjustPosition(x, y);
16921 var ax = adj.x, ay = adj.y;
16923 var el = this.getPositionEl();
16924 if(ax !== undefined || ay !== undefined){
16925 if(ax !== undefined && ay !== undefined){
16926 el.setLeftTop(ax, ay);
16927 }else if(ax !== undefined){
16929 }else if(ay !== undefined){
16932 this.onPosition(ax, ay);
16933 this.fireEvent('move', this, ax, ay);
16939 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
16940 * This method fires the move event.
16941 * @param {Number} x The new x position
16942 * @param {Number} y The new y position
16943 * @returns {Roo.BoxComponent} this
16945 setPagePosition : function(x, y){
16948 if(!this.boxReady){
16951 if(x === undefined || y === undefined){ // cannot translate undefined points
16954 var p = this.el.translatePoints(x, y);
16955 this.setPosition(p.left, p.top);
16960 onRender : function(ct, position){
16961 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
16963 this.resizeEl = Roo.get(this.resizeEl);
16965 if(this.positionEl){
16966 this.positionEl = Roo.get(this.positionEl);
16971 afterRender : function(){
16972 Roo.BoxComponent.superclass.afterRender.call(this);
16973 this.boxReady = true;
16974 this.setSize(this.width, this.height);
16975 if(this.x || this.y){
16976 this.setPosition(this.x, this.y);
16978 if(this.pageX || this.pageY){
16979 this.setPagePosition(this.pageX, this.pageY);
16984 * Force the component's size to recalculate based on the underlying element's current height and width.
16985 * @returns {Roo.BoxComponent} this
16987 syncSize : function(){
16988 delete this.lastSize;
16989 this.setSize(this.el.getWidth(), this.el.getHeight());
16994 * Called after the component is resized, this method is empty by default but can be implemented by any
16995 * subclass that needs to perform custom logic after a resize occurs.
16996 * @param {Number} adjWidth The box-adjusted width that was set
16997 * @param {Number} adjHeight The box-adjusted height that was set
16998 * @param {Number} rawWidth The width that was originally specified
16999 * @param {Number} rawHeight The height that was originally specified
17001 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
17006 * Called after the component is moved, this method is empty by default but can be implemented by any
17007 * subclass that needs to perform custom logic after a move occurs.
17008 * @param {Number} x The new x position
17009 * @param {Number} y The new y position
17011 onPosition : function(x, y){
17016 adjustSize : function(w, h){
17017 if(this.autoWidth){
17020 if(this.autoHeight){
17023 return {width : w, height: h};
17027 adjustPosition : function(x, y){
17028 return {x : x, y: y};
17032 * Ext JS Library 1.1.1
17033 * Copyright(c) 2006-2007, Ext JS, LLC.
17035 * Originally Released Under LGPL - original licence link has changed is not relivant.
17038 * <script type="text/javascript">
17043 * @extends Roo.Element
17044 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
17045 * automatic maintaining of shadow/shim positions.
17046 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
17047 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
17048 * you can pass a string with a CSS class name. False turns off the shadow.
17049 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
17050 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
17051 * @cfg {String} cls CSS class to add to the element
17052 * @cfg {Number} zindex Starting z-index (defaults to 11000)
17053 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
17055 * @param {Object} config An object with config options.
17056 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
17059 Roo.Layer = function(config, existingEl){
17060 config = config || {};
17061 var dh = Roo.DomHelper;
17062 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
17064 this.dom = Roo.getDom(existingEl);
17067 var o = config.dh || {tag: "div", cls: "x-layer"};
17068 this.dom = dh.append(pel, o);
17071 this.addClass(config.cls);
17073 this.constrain = config.constrain !== false;
17074 this.visibilityMode = Roo.Element.VISIBILITY;
17076 this.id = this.dom.id = config.id;
17078 this.id = Roo.id(this.dom);
17080 this.zindex = config.zindex || this.getZIndex();
17081 this.position("absolute", this.zindex);
17083 this.shadowOffset = config.shadowOffset || 4;
17084 this.shadow = new Roo.Shadow({
17085 offset : this.shadowOffset,
17086 mode : config.shadow
17089 this.shadowOffset = 0;
17091 this.useShim = config.shim !== false && Roo.useShims;
17092 this.useDisplay = config.useDisplay;
17096 var supr = Roo.Element.prototype;
17098 // shims are shared among layer to keep from having 100 iframes
17101 Roo.extend(Roo.Layer, Roo.Element, {
17103 getZIndex : function(){
17104 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
17107 getShim : function(){
17114 var shim = shims.shift();
17116 shim = this.createShim();
17117 shim.enableDisplayMode('block');
17118 shim.dom.style.display = 'none';
17119 shim.dom.style.visibility = 'visible';
17121 var pn = this.dom.parentNode;
17122 if(shim.dom.parentNode != pn){
17123 pn.insertBefore(shim.dom, this.dom);
17125 shim.setStyle('z-index', this.getZIndex()-2);
17130 hideShim : function(){
17132 this.shim.setDisplayed(false);
17133 shims.push(this.shim);
17138 disableShadow : function(){
17140 this.shadowDisabled = true;
17141 this.shadow.hide();
17142 this.lastShadowOffset = this.shadowOffset;
17143 this.shadowOffset = 0;
17147 enableShadow : function(show){
17149 this.shadowDisabled = false;
17150 this.shadowOffset = this.lastShadowOffset;
17151 delete this.lastShadowOffset;
17159 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
17160 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
17161 sync : function(doShow){
17162 var sw = this.shadow;
17163 if(!this.updating && this.isVisible() && (sw || this.useShim)){
17164 var sh = this.getShim();
17166 var w = this.getWidth(),
17167 h = this.getHeight();
17169 var l = this.getLeft(true),
17170 t = this.getTop(true);
17172 if(sw && !this.shadowDisabled){
17173 if(doShow && !sw.isVisible()){
17176 sw.realign(l, t, w, h);
17182 // fit the shim behind the shadow, so it is shimmed too
17183 var a = sw.adjusts, s = sh.dom.style;
17184 s.left = (Math.min(l, l+a.l))+"px";
17185 s.top = (Math.min(t, t+a.t))+"px";
17186 s.width = (w+a.w)+"px";
17187 s.height = (h+a.h)+"px";
17194 sh.setLeftTop(l, t);
17201 destroy : function(){
17204 this.shadow.hide();
17206 this.removeAllListeners();
17207 var pn = this.dom.parentNode;
17209 pn.removeChild(this.dom);
17211 Roo.Element.uncache(this.id);
17214 remove : function(){
17219 beginUpdate : function(){
17220 this.updating = true;
17224 endUpdate : function(){
17225 this.updating = false;
17230 hideUnders : function(negOffset){
17232 this.shadow.hide();
17238 constrainXY : function(){
17239 if(this.constrain){
17240 var vw = Roo.lib.Dom.getViewWidth(),
17241 vh = Roo.lib.Dom.getViewHeight();
17242 var s = Roo.get(document).getScroll();
17244 var xy = this.getXY();
17245 var x = xy[0], y = xy[1];
17246 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
17247 // only move it if it needs it
17249 // first validate right/bottom
17250 if((x + w) > vw+s.left){
17251 x = vw - w - this.shadowOffset;
17254 if((y + h) > vh+s.top){
17255 y = vh - h - this.shadowOffset;
17258 // then make sure top/left isn't negative
17269 var ay = this.avoidY;
17270 if(y <= ay && (y+h) >= ay){
17276 supr.setXY.call(this, xy);
17282 isVisible : function(){
17283 return this.visible;
17287 showAction : function(){
17288 this.visible = true; // track visibility to prevent getStyle calls
17289 if(this.useDisplay === true){
17290 this.setDisplayed("");
17291 }else if(this.lastXY){
17292 supr.setXY.call(this, this.lastXY);
17293 }else if(this.lastLT){
17294 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
17299 hideAction : function(){
17300 this.visible = false;
17301 if(this.useDisplay === true){
17302 this.setDisplayed(false);
17304 this.setLeftTop(-10000,-10000);
17308 // overridden Element method
17309 setVisible : function(v, a, d, c, e){
17314 var cb = function(){
17319 }.createDelegate(this);
17320 supr.setVisible.call(this, true, true, d, cb, e);
17323 this.hideUnders(true);
17332 }.createDelegate(this);
17334 supr.setVisible.call(this, v, a, d, cb, e);
17343 storeXY : function(xy){
17344 delete this.lastLT;
17348 storeLeftTop : function(left, top){
17349 delete this.lastXY;
17350 this.lastLT = [left, top];
17354 beforeFx : function(){
17355 this.beforeAction();
17356 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
17360 afterFx : function(){
17361 Roo.Layer.superclass.afterFx.apply(this, arguments);
17362 this.sync(this.isVisible());
17366 beforeAction : function(){
17367 if(!this.updating && this.shadow){
17368 this.shadow.hide();
17372 // overridden Element method
17373 setLeft : function(left){
17374 this.storeLeftTop(left, this.getTop(true));
17375 supr.setLeft.apply(this, arguments);
17379 setTop : function(top){
17380 this.storeLeftTop(this.getLeft(true), top);
17381 supr.setTop.apply(this, arguments);
17385 setLeftTop : function(left, top){
17386 this.storeLeftTop(left, top);
17387 supr.setLeftTop.apply(this, arguments);
17391 setXY : function(xy, a, d, c, e){
17393 this.beforeAction();
17395 var cb = this.createCB(c);
17396 supr.setXY.call(this, xy, a, d, cb, e);
17403 createCB : function(c){
17414 // overridden Element method
17415 setX : function(x, a, d, c, e){
17416 this.setXY([x, this.getY()], a, d, c, e);
17419 // overridden Element method
17420 setY : function(y, a, d, c, e){
17421 this.setXY([this.getX(), y], a, d, c, e);
17424 // overridden Element method
17425 setSize : function(w, h, a, d, c, e){
17426 this.beforeAction();
17427 var cb = this.createCB(c);
17428 supr.setSize.call(this, w, h, a, d, cb, e);
17434 // overridden Element method
17435 setWidth : function(w, a, d, c, e){
17436 this.beforeAction();
17437 var cb = this.createCB(c);
17438 supr.setWidth.call(this, w, a, d, cb, e);
17444 // overridden Element method
17445 setHeight : function(h, a, d, c, e){
17446 this.beforeAction();
17447 var cb = this.createCB(c);
17448 supr.setHeight.call(this, h, a, d, cb, e);
17454 // overridden Element method
17455 setBounds : function(x, y, w, h, a, d, c, e){
17456 this.beforeAction();
17457 var cb = this.createCB(c);
17459 this.storeXY([x, y]);
17460 supr.setXY.call(this, [x, y]);
17461 supr.setSize.call(this, w, h, a, d, cb, e);
17464 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
17470 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
17471 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
17472 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
17473 * @param {Number} zindex The new z-index to set
17474 * @return {this} The Layer
17476 setZIndex : function(zindex){
17477 this.zindex = zindex;
17478 this.setStyle("z-index", zindex + 2);
17480 this.shadow.setZIndex(zindex + 1);
17483 this.shim.setStyle("z-index", zindex);
17488 * Original code for Roojs - LGPL
17489 * <script type="text/javascript">
17493 * @class Roo.XComponent
17494 * A delayed Element creator...
17495 * Or a way to group chunks of interface together.
17496 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
17497 * used in conjunction with XComponent.build() it will create an instance of each element,
17498 * then call addxtype() to build the User interface.
17500 * Mypart.xyx = new Roo.XComponent({
17502 parent : 'Mypart.xyz', // empty == document.element.!!
17506 disabled : function() {}
17508 tree : function() { // return an tree of xtype declared components
17512 xtype : 'NestedLayoutPanel',
17519 * It can be used to build a big heiracy, with parent etc.
17520 * or you can just use this to render a single compoent to a dom element
17521 * MYPART.render(Roo.Element | String(id) | dom_element )
17528 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
17529 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
17531 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
17533 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
17534 * - if mulitple topModules exist, the last one is defined as the top module.
17538 * When the top level or multiple modules are to embedded into a existing HTML page,
17539 * the parent element can container '#id' of the element where the module will be drawn.
17543 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
17544 * it relies more on a include mechanism, where sub modules are included into an outer page.
17545 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
17547 * Bootstrap Roo Included elements
17549 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
17550 * hence confusing the component builder as it thinks there are multiple top level elements.
17552 * String Over-ride & Translations
17554 * Our builder application writes all the strings as _strings and _named_strings. This is to enable the translation of elements,
17555 * and also the 'overlaying of string values - needed when different versions of the same application with different text content
17556 * are needed. @see Roo.XComponent.overlayString
17560 * @extends Roo.util.Observable
17562 * @param cfg {Object} configuration of component
17565 Roo.XComponent = function(cfg) {
17566 Roo.apply(this, cfg);
17570 * Fires when this the componnt is built
17571 * @param {Roo.XComponent} c the component
17576 this.region = this.region || 'center'; // default..
17577 Roo.XComponent.register(this);
17578 this.modules = false;
17579 this.el = false; // where the layout goes..
17583 Roo.extend(Roo.XComponent, Roo.util.Observable, {
17586 * The created element (with Roo.factory())
17587 * @type {Roo.Layout}
17593 * for BC - use el in new code
17594 * @type {Roo.Layout}
17600 * for BC - use el in new code
17601 * @type {Roo.Layout}
17606 * @cfg {Function|boolean} disabled
17607 * If this module is disabled by some rule, return true from the funtion
17612 * @cfg {String} parent
17613 * Name of parent element which it get xtype added to..
17618 * @cfg {String} order
17619 * Used to set the order in which elements are created (usefull for multiple tabs)
17624 * @cfg {String} name
17625 * String to display while loading.
17629 * @cfg {String} region
17630 * Region to render component to (defaults to center)
17635 * @cfg {Array} items
17636 * A single item array - the first element is the root of the tree..
17637 * It's done this way to stay compatible with the Xtype system...
17643 * The method that retuns the tree of parts that make up this compoennt
17650 * render element to dom or tree
17651 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
17654 render : function(el)
17658 var hp = this.parent ? 1 : 0;
17659 Roo.debug && Roo.log(this);
17661 var tree = this._tree ? this._tree() : this.tree();
17664 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
17665 // if parent is a '#.....' string, then let's use that..
17666 var ename = this.parent.substr(1);
17667 this.parent = false;
17668 Roo.debug && Roo.log(ename);
17670 case 'bootstrap-body':
17671 if (typeof(tree.el) != 'undefined' && tree.el == document.body) {
17672 // this is the BorderLayout standard?
17673 this.parent = { el : true };
17676 if (["Nest", "Content", "Grid", "Tree"].indexOf(tree.xtype) > -1) {
17677 // need to insert stuff...
17679 el : new Roo.bootstrap.layout.Border({
17680 el : document.body,
17686 tabPosition: 'top',
17687 //resizeTabs: true,
17688 alwaysShowTabs: true,
17698 if (typeof(Roo.bootstrap.Body) != 'undefined' ) {
17699 this.parent = { el : new Roo.bootstrap.Body() };
17700 Roo.debug && Roo.log("setting el to doc body");
17703 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
17707 this.parent = { el : true};
17710 el = Roo.get(ename);
17711 if (typeof(Roo.bootstrap) != 'undefined' && tree['|xns'] == 'Roo.bootstrap') {
17712 this.parent = { el : true};
17719 if (!el && !this.parent) {
17720 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
17725 Roo.debug && Roo.log("EL:");
17726 Roo.debug && Roo.log(el);
17727 Roo.debug && Roo.log("this.parent.el:");
17728 Roo.debug && Roo.log(this.parent.el);
17731 // altertive root elements ??? - we need a better way to indicate these.
17732 var is_alt = Roo.XComponent.is_alt ||
17733 (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
17734 (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
17735 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
17739 if (!this.parent && is_alt) {
17740 //el = Roo.get(document.body);
17741 this.parent = { el : true };
17746 if (!this.parent) {
17748 Roo.debug && Roo.log("no parent - creating one");
17750 el = el ? Roo.get(el) : false;
17752 if (typeof(Roo.BorderLayout) == 'undefined' ) {
17755 el : new Roo.bootstrap.layout.Border({
17756 el: el || document.body,
17762 tabPosition: 'top',
17763 //resizeTabs: true,
17764 alwaysShowTabs: false,
17767 overflow: 'visible'
17773 // it's a top level one..
17775 el : new Roo.BorderLayout(el || document.body, {
17780 tabPosition: 'top',
17781 //resizeTabs: true,
17782 alwaysShowTabs: el && hp? false : true,
17783 hideTabs: el || !hp ? true : false,
17791 if (!this.parent.el) {
17792 // probably an old style ctor, which has been disabled.
17796 // The 'tree' method is '_tree now'
17798 tree.region = tree.region || this.region;
17799 var is_body = false;
17800 if (this.parent.el === true) {
17801 // bootstrap... - body..
17805 this.parent.el = Roo.factory(tree);
17809 this.el = this.parent.el.addxtype(tree, undefined, is_body);
17810 this.fireEvent('built', this);
17812 this.panel = this.el;
17813 this.layout = this.panel.layout;
17814 this.parentLayout = this.parent.layout || false;
17820 Roo.apply(Roo.XComponent, {
17822 * @property hideProgress
17823 * true to disable the building progress bar.. usefull on single page renders.
17826 hideProgress : false,
17828 * @property buildCompleted
17829 * True when the builder has completed building the interface.
17832 buildCompleted : false,
17835 * @property topModule
17836 * the upper most module - uses document.element as it's constructor.
17843 * @property modules
17844 * array of modules to be created by registration system.
17845 * @type {Array} of Roo.XComponent
17850 * @property elmodules
17851 * array of modules to be created by which use #ID
17852 * @type {Array} of Roo.XComponent
17859 * Is an alternative Root - normally used by bootstrap or other systems,
17860 * where the top element in the tree can wrap 'body'
17861 * @type {boolean} (default false)
17866 * @property build_from_html
17867 * Build elements from html - used by bootstrap HTML stuff
17868 * - this is cleared after build is completed
17869 * @type {boolean} (default false)
17872 build_from_html : false,
17874 * Register components to be built later.
17876 * This solves the following issues
17877 * - Building is not done on page load, but after an authentication process has occured.
17878 * - Interface elements are registered on page load
17879 * - Parent Interface elements may not be loaded before child, so this handles that..
17886 module : 'Pman.Tab.projectMgr',
17888 parent : 'Pman.layout',
17889 disabled : false, // or use a function..
17892 * * @param {Object} details about module
17894 register : function(obj) {
17896 Roo.XComponent.event.fireEvent('register', obj);
17897 switch(typeof(obj.disabled) ) {
17903 if ( obj.disabled() ) {
17909 if (obj.disabled || obj.region == '#disabled') {
17915 this.modules.push(obj);
17919 * convert a string to an object..
17920 * eg. 'AAA.BBB' -> finds AAA.BBB
17924 toObject : function(str)
17926 if (!str || typeof(str) == 'object') {
17929 if (str.substring(0,1) == '#') {
17933 var ar = str.split('.');
17938 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
17940 throw "Module not found : " + str;
17944 throw "Module not found : " + str;
17946 Roo.each(ar, function(e) {
17947 if (typeof(o[e]) == 'undefined') {
17948 throw "Module not found : " + str;
17959 * move modules into their correct place in the tree..
17962 preBuild : function ()
17965 Roo.each(this.modules , function (obj)
17967 Roo.XComponent.event.fireEvent('beforebuild', obj);
17969 var opar = obj.parent;
17971 obj.parent = this.toObject(opar);
17973 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
17978 Roo.debug && Roo.log("GOT top level module");
17979 Roo.debug && Roo.log(obj);
17980 obj.modules = new Roo.util.MixedCollection(false,
17981 function(o) { return o.order + '' }
17983 this.topModule = obj;
17986 // parent is a string (usually a dom element name..)
17987 if (typeof(obj.parent) == 'string') {
17988 this.elmodules.push(obj);
17991 if (obj.parent.constructor != Roo.XComponent) {
17992 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
17994 if (!obj.parent.modules) {
17995 obj.parent.modules = new Roo.util.MixedCollection(false,
17996 function(o) { return o.order + '' }
17999 if (obj.parent.disabled) {
18000 obj.disabled = true;
18002 obj.parent.modules.add(obj);
18007 * make a list of modules to build.
18008 * @return {Array} list of modules.
18011 buildOrder : function()
18014 var cmp = function(a,b) {
18015 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
18017 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
18018 throw "No top level modules to build";
18021 // make a flat list in order of modules to build.
18022 var mods = this.topModule ? [ this.topModule ] : [];
18025 // elmodules (is a list of DOM based modules )
18026 Roo.each(this.elmodules, function(e) {
18028 if (!this.topModule &&
18029 typeof(e.parent) == 'string' &&
18030 e.parent.substring(0,1) == '#' &&
18031 Roo.get(e.parent.substr(1))
18034 _this.topModule = e;
18040 // add modules to their parents..
18041 var addMod = function(m) {
18042 Roo.debug && Roo.log("build Order: add: " + m.name);
18045 if (m.modules && !m.disabled) {
18046 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
18047 m.modules.keySort('ASC', cmp );
18048 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
18050 m.modules.each(addMod);
18052 Roo.debug && Roo.log("build Order: no child modules");
18054 // not sure if this is used any more..
18056 m.finalize.name = m.name + " (clean up) ";
18057 mods.push(m.finalize);
18061 if (this.topModule && this.topModule.modules) {
18062 this.topModule.modules.keySort('ASC', cmp );
18063 this.topModule.modules.each(addMod);
18069 * Build the registered modules.
18070 * @param {Object} parent element.
18071 * @param {Function} optional method to call after module has been added.
18075 build : function(opts)
18078 if (typeof(opts) != 'undefined') {
18079 Roo.apply(this,opts);
18083 var mods = this.buildOrder();
18085 //this.allmods = mods;
18086 //Roo.debug && Roo.log(mods);
18088 if (!mods.length) { // should not happen
18089 throw "NO modules!!!";
18093 var msg = "Building Interface...";
18094 // flash it up as modal - so we store the mask!?
18095 if (!this.hideProgress && Roo.MessageBox) {
18096 Roo.MessageBox.show({ title: 'loading' });
18097 Roo.MessageBox.show({
18098 title: "Please wait...",
18108 var total = mods.length;
18111 var progressRun = function() {
18112 if (!mods.length) {
18113 Roo.debug && Roo.log('hide?');
18114 if (!this.hideProgress && Roo.MessageBox) {
18115 Roo.MessageBox.hide();
18117 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
18119 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
18125 var m = mods.shift();
18128 Roo.debug && Roo.log(m);
18129 // not sure if this is supported any more.. - modules that are are just function
18130 if (typeof(m) == 'function') {
18132 return progressRun.defer(10, _this);
18136 msg = "Building Interface " + (total - mods.length) +
18138 (m.name ? (' - ' + m.name) : '');
18139 Roo.debug && Roo.log(msg);
18140 if (!_this.hideProgress && Roo.MessageBox) {
18141 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
18145 // is the module disabled?
18146 var disabled = (typeof(m.disabled) == 'function') ?
18147 m.disabled.call(m.module.disabled) : m.disabled;
18151 return progressRun(); // we do not update the display!
18159 // it's 10 on top level, and 1 on others??? why...
18160 return progressRun.defer(10, _this);
18163 progressRun.defer(1, _this);
18169 * Overlay a set of modified strings onto a component
18170 * This is dependant on our builder exporting the strings and 'named strings' elements.
18172 * @param {Object} element to overlay on - eg. Pman.Dialog.Login
18173 * @param {Object} associative array of 'named' string and it's new value.
18176 overlayStrings : function( component, strings )
18178 if (typeof(component['_named_strings']) == 'undefined') {
18179 throw "ERROR: component does not have _named_strings";
18181 for ( var k in strings ) {
18182 var md = typeof(component['_named_strings'][k]) == 'undefined' ? false : component['_named_strings'][k];
18183 if (md !== false) {
18184 component['_strings'][md] = strings[k];
18186 Roo.log('could not find named string: ' + k + ' in');
18187 Roo.log(component);
18202 * wrapper for event.on - aliased later..
18203 * Typically use to register a event handler for register:
18205 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
18214 Roo.XComponent.event = new Roo.util.Observable({
18218 * Fires when an Component is registered,
18219 * set the disable property on the Component to stop registration.
18220 * @param {Roo.XComponent} c the component being registerd.
18225 * @event beforebuild
18226 * Fires before each Component is built
18227 * can be used to apply permissions.
18228 * @param {Roo.XComponent} c the component being registerd.
18231 'beforebuild' : true,
18233 * @event buildcomplete
18234 * Fires on the top level element when all elements have been built
18235 * @param {Roo.XComponent} the top level component.
18237 'buildcomplete' : true
18242 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
18245 * marked - a markdown parser
18246 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
18247 * https://github.com/chjj/marked
18253 * Roo.Markdown - is a very crude wrapper around marked..
18257 * alert( Roo.Markdown.toHtml("Markdown *rocks*.") );
18259 * Note: move the sample code to the bottom of this
18260 * file before uncommenting it.
18265 Roo.Markdown.toHtml = function(text) {
18267 var c = new Roo.Markdown.marked.setOptions({
18268 renderer: new Roo.Markdown.marked.Renderer(),
18279 text = text.replace(/\\\n/g,' ');
18280 return Roo.Markdown.marked(text);
18285 // Wraps all "globals" so that the only thing
18286 // exposed is makeHtml().
18292 * eval:var:unescape
18300 var escape = function (html, encode) {
18302 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
18303 .replace(/</g, '<')
18304 .replace(/>/g, '>')
18305 .replace(/"/g, '"')
18306 .replace(/'/g, ''');
18309 var unescape = function (html) {
18310 // explicitly match decimal, hex, and named HTML entities
18311 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
18312 n = n.toLowerCase();
18313 if (n === 'colon') { return ':'; }
18314 if (n.charAt(0) === '#') {
18315 return n.charAt(1) === 'x'
18316 ? String.fromCharCode(parseInt(n.substring(2), 16))
18317 : String.fromCharCode(+n.substring(1));
18323 var replace = function (regex, opt) {
18324 regex = regex.source;
18326 return function self(name, val) {
18327 if (!name) { return new RegExp(regex, opt); }
18328 val = val.source || val;
18329 val = val.replace(/(^|[^\[])\^/g, '$1');
18330 regex = regex.replace(name, val);
18339 var noop = function () {}
18345 var merge = function (obj) {
18350 for (; i < arguments.length; i++) {
18351 target = arguments[i];
18352 for (key in target) {
18353 if (Object.prototype.hasOwnProperty.call(target, key)) {
18354 obj[key] = target[key];
18364 * Block-Level Grammar
18372 code: /^( {4}[^\n]+\n*)+/,
18374 hr: /^( *[-*_]){3,} *(?:\n+|$)/,
18375 heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
18377 lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
18378 blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
18379 list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
18380 html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
18381 def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
18383 paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
18387 block.bullet = /(?:[*+-]|\d+\.)/;
18388 block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
18389 block.item = replace(block.item, 'gm')
18390 (/bull/g, block.bullet)
18393 block.list = replace(block.list)
18394 (/bull/g, block.bullet)
18395 ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
18396 ('def', '\\n+(?=' + block.def.source + ')')
18399 block.blockquote = replace(block.blockquote)
18403 block._tag = '(?!(?:'
18404 + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
18405 + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
18406 + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
18408 block.html = replace(block.html)
18409 ('comment', /<!--[\s\S]*?-->/)
18410 ('closed', /<(tag)[\s\S]+?<\/\1>/)
18411 ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
18412 (/tag/g, block._tag)
18415 block.paragraph = replace(block.paragraph)
18417 ('heading', block.heading)
18418 ('lheading', block.lheading)
18419 ('blockquote', block.blockquote)
18420 ('tag', '<' + block._tag)
18425 * Normal Block Grammar
18428 block.normal = merge({}, block);
18431 * GFM Block Grammar
18434 block.gfm = merge({}, block.normal, {
18435 fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
18437 heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
18440 block.gfm.paragraph = replace(block.paragraph)
18442 + block.gfm.fences.source.replace('\\1', '\\2') + '|'
18443 + block.list.source.replace('\\1', '\\3') + '|')
18447 * GFM + Tables Block Grammar
18450 block.tables = merge({}, block.gfm, {
18451 nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
18452 table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
18459 var Lexer = function (options) {
18461 this.tokens.links = {};
18462 this.options = options || marked.defaults;
18463 this.rules = block.normal;
18465 if (this.options.gfm) {
18466 if (this.options.tables) {
18467 this.rules = block.tables;
18469 this.rules = block.gfm;
18475 * Expose Block Rules
18478 Lexer.rules = block;
18481 * Static Lex Method
18484 Lexer.lex = function(src, options) {
18485 var lexer = new Lexer(options);
18486 return lexer.lex(src);
18493 Lexer.prototype.lex = function(src) {
18495 .replace(/\r\n|\r/g, '\n')
18496 .replace(/\t/g, ' ')
18497 .replace(/\u00a0/g, ' ')
18498 .replace(/\u2424/g, '\n');
18500 return this.token(src, true);
18507 Lexer.prototype.token = function(src, top, bq) {
18508 var src = src.replace(/^ +$/gm, '')
18521 if (cap = this.rules.newline.exec(src)) {
18522 src = src.substring(cap[0].length);
18523 if (cap[0].length > 1) {
18531 if (cap = this.rules.code.exec(src)) {
18532 src = src.substring(cap[0].length);
18533 cap = cap[0].replace(/^ {4}/gm, '');
18536 text: !this.options.pedantic
18537 ? cap.replace(/\n+$/, '')
18544 if (cap = this.rules.fences.exec(src)) {
18545 src = src.substring(cap[0].length);
18555 if (cap = this.rules.heading.exec(src)) {
18556 src = src.substring(cap[0].length);
18559 depth: cap[1].length,
18565 // table no leading pipe (gfm)
18566 if (top && (cap = this.rules.nptable.exec(src))) {
18567 src = src.substring(cap[0].length);
18571 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18572 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18573 cells: cap[3].replace(/\n$/, '').split('\n')
18576 for (i = 0; i < item.align.length; i++) {
18577 if (/^ *-+: *$/.test(item.align[i])) {
18578 item.align[i] = 'right';
18579 } else if (/^ *:-+: *$/.test(item.align[i])) {
18580 item.align[i] = 'center';
18581 } else if (/^ *:-+ *$/.test(item.align[i])) {
18582 item.align[i] = 'left';
18584 item.align[i] = null;
18588 for (i = 0; i < item.cells.length; i++) {
18589 item.cells[i] = item.cells[i].split(/ *\| */);
18592 this.tokens.push(item);
18598 if (cap = this.rules.lheading.exec(src)) {
18599 src = src.substring(cap[0].length);
18602 depth: cap[2] === '=' ? 1 : 2,
18609 if (cap = this.rules.hr.exec(src)) {
18610 src = src.substring(cap[0].length);
18618 if (cap = this.rules.blockquote.exec(src)) {
18619 src = src.substring(cap[0].length);
18622 type: 'blockquote_start'
18625 cap = cap[0].replace(/^ *> ?/gm, '');
18627 // Pass `top` to keep the current
18628 // "toplevel" state. This is exactly
18629 // how markdown.pl works.
18630 this.token(cap, top, true);
18633 type: 'blockquote_end'
18640 if (cap = this.rules.list.exec(src)) {
18641 src = src.substring(cap[0].length);
18645 type: 'list_start',
18646 ordered: bull.length > 1
18649 // Get each top-level item.
18650 cap = cap[0].match(this.rules.item);
18656 for (; i < l; i++) {
18659 // Remove the list item's bullet
18660 // so it is seen as the next token.
18661 space = item.length;
18662 item = item.replace(/^ *([*+-]|\d+\.) +/, '');
18664 // Outdent whatever the
18665 // list item contains. Hacky.
18666 if (~item.indexOf('\n ')) {
18667 space -= item.length;
18668 item = !this.options.pedantic
18669 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
18670 : item.replace(/^ {1,4}/gm, '');
18673 // Determine whether the next list item belongs here.
18674 // Backpedal if it does not belong in this list.
18675 if (this.options.smartLists && i !== l - 1) {
18676 b = block.bullet.exec(cap[i + 1])[0];
18677 if (bull !== b && !(bull.length > 1 && b.length > 1)) {
18678 src = cap.slice(i + 1).join('\n') + src;
18683 // Determine whether item is loose or not.
18684 // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
18685 // for discount behavior.
18686 loose = next || /\n\n(?!\s*$)/.test(item);
18688 next = item.charAt(item.length - 1) === '\n';
18689 if (!loose) { loose = next; }
18694 ? 'loose_item_start'
18695 : 'list_item_start'
18699 this.token(item, false, bq);
18702 type: 'list_item_end'
18714 if (cap = this.rules.html.exec(src)) {
18715 src = src.substring(cap[0].length);
18717 type: this.options.sanitize
18720 pre: !this.options.sanitizer
18721 && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
18728 if ((!bq && top) && (cap = this.rules.def.exec(src))) {
18729 src = src.substring(cap[0].length);
18730 this.tokens.links[cap[1].toLowerCase()] = {
18738 if (top && (cap = this.rules.table.exec(src))) {
18739 src = src.substring(cap[0].length);
18743 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18744 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18745 cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
18748 for (i = 0; i < item.align.length; i++) {
18749 if (/^ *-+: *$/.test(item.align[i])) {
18750 item.align[i] = 'right';
18751 } else if (/^ *:-+: *$/.test(item.align[i])) {
18752 item.align[i] = 'center';
18753 } else if (/^ *:-+ *$/.test(item.align[i])) {
18754 item.align[i] = 'left';
18756 item.align[i] = null;
18760 for (i = 0; i < item.cells.length; i++) {
18761 item.cells[i] = item.cells[i]
18762 .replace(/^ *\| *| *\| *$/g, '')
18766 this.tokens.push(item);
18771 // top-level paragraph
18772 if (top && (cap = this.rules.paragraph.exec(src))) {
18773 src = src.substring(cap[0].length);
18776 text: cap[1].charAt(cap[1].length - 1) === '\n'
18777 ? cap[1].slice(0, -1)
18784 if (cap = this.rules.text.exec(src)) {
18785 // Top-level should never reach here.
18786 src = src.substring(cap[0].length);
18796 Error('Infinite loop on byte: ' + src.charCodeAt(0));
18800 return this.tokens;
18804 * Inline-Level Grammar
18808 escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
18809 autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
18811 tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
18812 link: /^!?\[(inside)\]\(href\)/,
18813 reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
18814 nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
18815 strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
18816 em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
18817 code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
18818 br: /^ {2,}\n(?!\s*$)/,
18820 text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
18823 inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
18824 inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
18826 inline.link = replace(inline.link)
18827 ('inside', inline._inside)
18828 ('href', inline._href)
18831 inline.reflink = replace(inline.reflink)
18832 ('inside', inline._inside)
18836 * Normal Inline Grammar
18839 inline.normal = merge({}, inline);
18842 * Pedantic Inline Grammar
18845 inline.pedantic = merge({}, inline.normal, {
18846 strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
18847 em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
18851 * GFM Inline Grammar
18854 inline.gfm = merge({}, inline.normal, {
18855 escape: replace(inline.escape)('])', '~|])')(),
18856 url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
18857 del: /^~~(?=\S)([\s\S]*?\S)~~/,
18858 text: replace(inline.text)
18860 ('|', '|https?://|')
18865 * GFM + Line Breaks Inline Grammar
18868 inline.breaks = merge({}, inline.gfm, {
18869 br: replace(inline.br)('{2,}', '*')(),
18870 text: replace(inline.gfm.text)('{2,}', '*')()
18874 * Inline Lexer & Compiler
18877 var InlineLexer = function (links, options) {
18878 this.options = options || marked.defaults;
18879 this.links = links;
18880 this.rules = inline.normal;
18881 this.renderer = this.options.renderer || new Renderer;
18882 this.renderer.options = this.options;
18886 Error('Tokens array requires a `links` property.');
18889 if (this.options.gfm) {
18890 if (this.options.breaks) {
18891 this.rules = inline.breaks;
18893 this.rules = inline.gfm;
18895 } else if (this.options.pedantic) {
18896 this.rules = inline.pedantic;
18901 * Expose Inline Rules
18904 InlineLexer.rules = inline;
18907 * Static Lexing/Compiling Method
18910 InlineLexer.output = function(src, links, options) {
18911 var inline = new InlineLexer(links, options);
18912 return inline.output(src);
18919 InlineLexer.prototype.output = function(src) {
18928 if (cap = this.rules.escape.exec(src)) {
18929 src = src.substring(cap[0].length);
18935 if (cap = this.rules.autolink.exec(src)) {
18936 src = src.substring(cap[0].length);
18937 if (cap[2] === '@') {
18938 text = cap[1].charAt(6) === ':'
18939 ? this.mangle(cap[1].substring(7))
18940 : this.mangle(cap[1]);
18941 href = this.mangle('mailto:') + text;
18943 text = escape(cap[1]);
18946 out += this.renderer.link(href, null, text);
18951 if (!this.inLink && (cap = this.rules.url.exec(src))) {
18952 src = src.substring(cap[0].length);
18953 text = escape(cap[1]);
18955 out += this.renderer.link(href, null, text);
18960 if (cap = this.rules.tag.exec(src)) {
18961 if (!this.inLink && /^<a /i.test(cap[0])) {
18962 this.inLink = true;
18963 } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
18964 this.inLink = false;
18966 src = src.substring(cap[0].length);
18967 out += this.options.sanitize
18968 ? this.options.sanitizer
18969 ? this.options.sanitizer(cap[0])
18976 if (cap = this.rules.link.exec(src)) {
18977 src = src.substring(cap[0].length);
18978 this.inLink = true;
18979 out += this.outputLink(cap, {
18983 this.inLink = false;
18988 if ((cap = this.rules.reflink.exec(src))
18989 || (cap = this.rules.nolink.exec(src))) {
18990 src = src.substring(cap[0].length);
18991 link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
18992 link = this.links[link.toLowerCase()];
18993 if (!link || !link.href) {
18994 out += cap[0].charAt(0);
18995 src = cap[0].substring(1) + src;
18998 this.inLink = true;
18999 out += this.outputLink(cap, link);
19000 this.inLink = false;
19005 if (cap = this.rules.strong.exec(src)) {
19006 src = src.substring(cap[0].length);
19007 out += this.renderer.strong(this.output(cap[2] || cap[1]));
19012 if (cap = this.rules.em.exec(src)) {
19013 src = src.substring(cap[0].length);
19014 out += this.renderer.em(this.output(cap[2] || cap[1]));
19019 if (cap = this.rules.code.exec(src)) {
19020 src = src.substring(cap[0].length);
19021 out += this.renderer.codespan(escape(cap[2], true));
19026 if (cap = this.rules.br.exec(src)) {
19027 src = src.substring(cap[0].length);
19028 out += this.renderer.br();
19033 if (cap = this.rules.del.exec(src)) {
19034 src = src.substring(cap[0].length);
19035 out += this.renderer.del(this.output(cap[1]));
19040 if (cap = this.rules.text.exec(src)) {
19041 src = src.substring(cap[0].length);
19042 out += this.renderer.text(escape(this.smartypants(cap[0])));
19048 Error('Infinite loop on byte: ' + src.charCodeAt(0));
19059 InlineLexer.prototype.outputLink = function(cap, link) {
19060 var href = escape(link.href)
19061 , title = link.title ? escape(link.title) : null;
19063 return cap[0].charAt(0) !== '!'
19064 ? this.renderer.link(href, title, this.output(cap[1]))
19065 : this.renderer.image(href, title, escape(cap[1]));
19069 * Smartypants Transformations
19072 InlineLexer.prototype.smartypants = function(text) {
19073 if (!this.options.smartypants) { return text; }
19076 .replace(/---/g, '\u2014')
19078 .replace(/--/g, '\u2013')
19080 .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
19081 // closing singles & apostrophes
19082 .replace(/'/g, '\u2019')
19084 .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
19086 .replace(/"/g, '\u201d')
19088 .replace(/\.{3}/g, '\u2026');
19095 InlineLexer.prototype.mangle = function(text) {
19096 if (!this.options.mangle) { return text; }
19102 for (; i < l; i++) {
19103 ch = text.charCodeAt(i);
19104 if (Math.random() > 0.5) {
19105 ch = 'x' + ch.toString(16);
19107 out += '&#' + ch + ';';
19118 * eval:var:Renderer
19121 var Renderer = function (options) {
19122 this.options = options || {};
19125 Renderer.prototype.code = function(code, lang, escaped) {
19126 if (this.options.highlight) {
19127 var out = this.options.highlight(code, lang);
19128 if (out != null && out !== code) {
19133 // hack!!! - it's already escapeD?
19138 return '<pre><code>'
19139 + (escaped ? code : escape(code, true))
19140 + '\n</code></pre>';
19143 return '<pre><code class="'
19144 + this.options.langPrefix
19145 + escape(lang, true)
19147 + (escaped ? code : escape(code, true))
19148 + '\n</code></pre>\n';
19151 Renderer.prototype.blockquote = function(quote) {
19152 return '<blockquote>\n' + quote + '</blockquote>\n';
19155 Renderer.prototype.html = function(html) {
19159 Renderer.prototype.heading = function(text, level, raw) {
19163 + this.options.headerPrefix
19164 + raw.toLowerCase().replace(/[^\w]+/g, '-')
19172 Renderer.prototype.hr = function() {
19173 return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
19176 Renderer.prototype.list = function(body, ordered) {
19177 var type = ordered ? 'ol' : 'ul';
19178 return '<' + type + '>\n' + body + '</' + type + '>\n';
19181 Renderer.prototype.listitem = function(text) {
19182 return '<li>' + text + '</li>\n';
19185 Renderer.prototype.paragraph = function(text) {
19186 return '<p>' + text + '</p>\n';
19189 Renderer.prototype.table = function(header, body) {
19190 return '<table class="table table-striped">\n'
19200 Renderer.prototype.tablerow = function(content) {
19201 return '<tr>\n' + content + '</tr>\n';
19204 Renderer.prototype.tablecell = function(content, flags) {
19205 var type = flags.header ? 'th' : 'td';
19206 var tag = flags.align
19207 ? '<' + type + ' style="text-align:' + flags.align + '">'
19208 : '<' + type + '>';
19209 return tag + content + '</' + type + '>\n';
19212 // span level renderer
19213 Renderer.prototype.strong = function(text) {
19214 return '<strong>' + text + '</strong>';
19217 Renderer.prototype.em = function(text) {
19218 return '<em>' + text + '</em>';
19221 Renderer.prototype.codespan = function(text) {
19222 return '<code>' + text + '</code>';
19225 Renderer.prototype.br = function() {
19226 return this.options.xhtml ? '<br/>' : '<br>';
19229 Renderer.prototype.del = function(text) {
19230 return '<del>' + text + '</del>';
19233 Renderer.prototype.link = function(href, title, text) {
19234 if (this.options.sanitize) {
19236 var prot = decodeURIComponent(unescape(href))
19237 .replace(/[^\w:]/g, '')
19242 if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
19246 var out = '<a href="' + href + '"';
19248 out += ' title="' + title + '"';
19250 out += '>' + text + '</a>';
19254 Renderer.prototype.image = function(href, title, text) {
19255 var out = '<img src="' + href + '" alt="' + text + '"';
19257 out += ' title="' + title + '"';
19259 out += this.options.xhtml ? '/>' : '>';
19263 Renderer.prototype.text = function(text) {
19268 * Parsing & Compiling
19274 var Parser= function (options) {
19277 this.options = options || marked.defaults;
19278 this.options.renderer = this.options.renderer || new Renderer;
19279 this.renderer = this.options.renderer;
19280 this.renderer.options = this.options;
19284 * Static Parse Method
19287 Parser.parse = function(src, options, renderer) {
19288 var parser = new Parser(options, renderer);
19289 return parser.parse(src);
19296 Parser.prototype.parse = function(src) {
19297 this.inline = new InlineLexer(src.links, this.options, this.renderer);
19298 this.tokens = src.reverse();
19301 while (this.next()) {
19312 Parser.prototype.next = function() {
19313 return this.token = this.tokens.pop();
19317 * Preview Next Token
19320 Parser.prototype.peek = function() {
19321 return this.tokens[this.tokens.length - 1] || 0;
19325 * Parse Text Tokens
19328 Parser.prototype.parseText = function() {
19329 var body = this.token.text;
19331 while (this.peek().type === 'text') {
19332 body += '\n' + this.next().text;
19335 return this.inline.output(body);
19339 * Parse Current Token
19342 Parser.prototype.tok = function() {
19343 switch (this.token.type) {
19348 return this.renderer.hr();
19351 return this.renderer.heading(
19352 this.inline.output(this.token.text),
19357 return this.renderer.code(this.token.text,
19359 this.token.escaped);
19372 for (i = 0; i < this.token.header.length; i++) {
19373 flags = { header: true, align: this.token.align[i] };
19374 cell += this.renderer.tablecell(
19375 this.inline.output(this.token.header[i]),
19376 { header: true, align: this.token.align[i] }
19379 header += this.renderer.tablerow(cell);
19381 for (i = 0; i < this.token.cells.length; i++) {
19382 row = this.token.cells[i];
19385 for (j = 0; j < row.length; j++) {
19386 cell += this.renderer.tablecell(
19387 this.inline.output(row[j]),
19388 { header: false, align: this.token.align[j] }
19392 body += this.renderer.tablerow(cell);
19394 return this.renderer.table(header, body);
19396 case 'blockquote_start': {
19399 while (this.next().type !== 'blockquote_end') {
19400 body += this.tok();
19403 return this.renderer.blockquote(body);
19405 case 'list_start': {
19407 , ordered = this.token.ordered;
19409 while (this.next().type !== 'list_end') {
19410 body += this.tok();
19413 return this.renderer.list(body, ordered);
19415 case 'list_item_start': {
19418 while (this.next().type !== 'list_item_end') {
19419 body += this.token.type === 'text'
19424 return this.renderer.listitem(body);
19426 case 'loose_item_start': {
19429 while (this.next().type !== 'list_item_end') {
19430 body += this.tok();
19433 return this.renderer.listitem(body);
19436 var html = !this.token.pre && !this.options.pedantic
19437 ? this.inline.output(this.token.text)
19439 return this.renderer.html(html);
19441 case 'paragraph': {
19442 return this.renderer.paragraph(this.inline.output(this.token.text));
19445 return this.renderer.paragraph(this.parseText());
19457 var marked = function (src, opt, callback) {
19458 if (callback || typeof opt === 'function') {
19464 opt = merge({}, marked.defaults, opt || {});
19466 var highlight = opt.highlight
19472 tokens = Lexer.lex(src, opt)
19474 return callback(e);
19477 pending = tokens.length;
19481 var done = function(err) {
19483 opt.highlight = highlight;
19484 return callback(err);
19490 out = Parser.parse(tokens, opt);
19495 opt.highlight = highlight;
19499 : callback(null, out);
19502 if (!highlight || highlight.length < 3) {
19506 delete opt.highlight;
19508 if (!pending) { return done(); }
19510 for (; i < tokens.length; i++) {
19512 if (token.type !== 'code') {
19513 return --pending || done();
19515 return highlight(token.text, token.lang, function(err, code) {
19516 if (err) { return done(err); }
19517 if (code == null || code === token.text) {
19518 return --pending || done();
19521 token.escaped = true;
19522 --pending || done();
19530 if (opt) { opt = merge({}, marked.defaults, opt); }
19531 return Parser.parse(Lexer.lex(src, opt), opt);
19533 e.message += '\nPlease report this to https://github.com/chjj/marked.';
19534 if ((opt || marked.defaults).silent) {
19535 return '<p>An error occured:</p><pre>'
19536 + escape(e.message + '', true)
19548 marked.setOptions = function(opt) {
19549 merge(marked.defaults, opt);
19553 marked.defaults = {
19564 langPrefix: 'lang-',
19565 smartypants: false,
19567 renderer: new Renderer,
19575 marked.Parser = Parser;
19576 marked.parser = Parser.parse;
19578 marked.Renderer = Renderer;
19580 marked.Lexer = Lexer;
19581 marked.lexer = Lexer.lex;
19583 marked.InlineLexer = InlineLexer;
19584 marked.inlineLexer = InlineLexer.output;
19586 marked.parse = marked;
19588 Roo.Markdown.marked = marked;
19592 * Ext JS Library 1.1.1
19593 * Copyright(c) 2006-2007, Ext JS, LLC.
19595 * Originally Released Under LGPL - original licence link has changed is not relivant.
19598 * <script type="text/javascript">
19604 * These classes are derivatives of the similarly named classes in the YUI Library.
19605 * The original license:
19606 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
19607 * Code licensed under the BSD License:
19608 * http://developer.yahoo.net/yui/license.txt
19613 var Event=Roo.EventManager;
19614 var Dom=Roo.lib.Dom;
19617 * @class Roo.dd.DragDrop
19618 * @extends Roo.util.Observable
19619 * Defines the interface and base operation of items that that can be
19620 * dragged or can be drop targets. It was designed to be extended, overriding
19621 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
19622 * Up to three html elements can be associated with a DragDrop instance:
19624 * <li>linked element: the element that is passed into the constructor.
19625 * This is the element which defines the boundaries for interaction with
19626 * other DragDrop objects.</li>
19627 * <li>handle element(s): The drag operation only occurs if the element that
19628 * was clicked matches a handle element. By default this is the linked
19629 * element, but there are times that you will want only a portion of the
19630 * linked element to initiate the drag operation, and the setHandleElId()
19631 * method provides a way to define this.</li>
19632 * <li>drag element: this represents the element that would be moved along
19633 * with the cursor during a drag operation. By default, this is the linked
19634 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
19635 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
19638 * This class should not be instantiated until the onload event to ensure that
19639 * the associated elements are available.
19640 * The following would define a DragDrop obj that would interact with any
19641 * other DragDrop obj in the "group1" group:
19643 * dd = new Roo.dd.DragDrop("div1", "group1");
19645 * Since none of the event handlers have been implemented, nothing would
19646 * actually happen if you were to run the code above. Normally you would
19647 * override this class or one of the default implementations, but you can
19648 * also override the methods you want on an instance of the class...
19650 * dd.onDragDrop = function(e, id) {
19651 * alert("dd was dropped on " + id);
19655 * @param {String} id of the element that is linked to this instance
19656 * @param {String} sGroup the group of related DragDrop objects
19657 * @param {object} config an object containing configurable attributes
19658 * Valid properties for DragDrop:
19659 * padding, isTarget, maintainOffset, primaryButtonOnly
19661 Roo.dd.DragDrop = function(id, sGroup, config) {
19663 this.init(id, sGroup, config);
19668 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
19671 * The id of the element associated with this object. This is what we
19672 * refer to as the "linked element" because the size and position of
19673 * this element is used to determine when the drag and drop objects have
19681 * Configuration attributes passed into the constructor
19688 * The id of the element that will be dragged. By default this is same
19689 * as the linked element , but could be changed to another element. Ex:
19691 * @property dragElId
19698 * the id of the element that initiates the drag operation. By default
19699 * this is the linked element, but could be changed to be a child of this
19700 * element. This lets us do things like only starting the drag when the
19701 * header element within the linked html element is clicked.
19702 * @property handleElId
19709 * An associative array of HTML tags that will be ignored if clicked.
19710 * @property invalidHandleTypes
19711 * @type {string: string}
19713 invalidHandleTypes: null,
19716 * An associative array of ids for elements that will be ignored if clicked
19717 * @property invalidHandleIds
19718 * @type {string: string}
19720 invalidHandleIds: null,
19723 * An indexted array of css class names for elements that will be ignored
19725 * @property invalidHandleClasses
19728 invalidHandleClasses: null,
19731 * The linked element's absolute X position at the time the drag was
19733 * @property startPageX
19740 * The linked element's absolute X position at the time the drag was
19742 * @property startPageY
19749 * The group defines a logical collection of DragDrop objects that are
19750 * related. Instances only get events when interacting with other
19751 * DragDrop object in the same group. This lets us define multiple
19752 * groups using a single DragDrop subclass if we want.
19754 * @type {string: string}
19759 * Individual drag/drop instances can be locked. This will prevent
19760 * onmousedown start drag.
19768 * Lock this instance
19771 lock: function() { this.locked = true; },
19774 * Unlock this instace
19777 unlock: function() { this.locked = false; },
19780 * By default, all insances can be a drop target. This can be disabled by
19781 * setting isTarget to false.
19788 * The padding configured for this drag and drop object for calculating
19789 * the drop zone intersection with this object.
19796 * Cached reference to the linked element
19797 * @property _domRef
19803 * Internal typeof flag
19804 * @property __ygDragDrop
19807 __ygDragDrop: true,
19810 * Set to true when horizontal contraints are applied
19811 * @property constrainX
19818 * Set to true when vertical contraints are applied
19819 * @property constrainY
19826 * The left constraint
19834 * The right constraint
19842 * The up constraint
19851 * The down constraint
19859 * Maintain offsets when we resetconstraints. Set to true when you want
19860 * the position of the element relative to its parent to stay the same
19861 * when the page changes
19863 * @property maintainOffset
19866 maintainOffset: false,
19869 * Array of pixel locations the element will snap to if we specified a
19870 * horizontal graduation/interval. This array is generated automatically
19871 * when you define a tick interval.
19878 * Array of pixel locations the element will snap to if we specified a
19879 * vertical graduation/interval. This array is generated automatically
19880 * when you define a tick interval.
19887 * By default the drag and drop instance will only respond to the primary
19888 * button click (left button for a right-handed mouse). Set to true to
19889 * allow drag and drop to start with any mouse click that is propogated
19891 * @property primaryButtonOnly
19894 primaryButtonOnly: true,
19897 * The availabe property is false until the linked dom element is accessible.
19898 * @property available
19904 * By default, drags can only be initiated if the mousedown occurs in the
19905 * region the linked element is. This is done in part to work around a
19906 * bug in some browsers that mis-report the mousedown if the previous
19907 * mouseup happened outside of the window. This property is set to true
19908 * if outer handles are defined.
19910 * @property hasOuterHandles
19914 hasOuterHandles: false,
19917 * Code that executes immediately before the startDrag event
19918 * @method b4StartDrag
19921 b4StartDrag: function(x, y) { },
19924 * Abstract method called after a drag/drop object is clicked
19925 * and the drag or mousedown time thresholds have beeen met.
19926 * @method startDrag
19927 * @param {int} X click location
19928 * @param {int} Y click location
19930 startDrag: function(x, y) { /* override this */ },
19933 * Code that executes immediately before the onDrag event
19937 b4Drag: function(e) { },
19940 * Abstract method called during the onMouseMove event while dragging an
19943 * @param {Event} e the mousemove event
19945 onDrag: function(e) { /* override this */ },
19948 * Abstract method called when this element fist begins hovering over
19949 * another DragDrop obj
19950 * @method onDragEnter
19951 * @param {Event} e the mousemove event
19952 * @param {String|DragDrop[]} id In POINT mode, the element
19953 * id this is hovering over. In INTERSECT mode, an array of one or more
19954 * dragdrop items being hovered over.
19956 onDragEnter: function(e, id) { /* override this */ },
19959 * Code that executes immediately before the onDragOver event
19960 * @method b4DragOver
19963 b4DragOver: function(e) { },
19966 * Abstract method called when this element is hovering over another
19968 * @method onDragOver
19969 * @param {Event} e the mousemove event
19970 * @param {String|DragDrop[]} id In POINT mode, the element
19971 * id this is hovering over. In INTERSECT mode, an array of dd items
19972 * being hovered over.
19974 onDragOver: function(e, id) { /* override this */ },
19977 * Code that executes immediately before the onDragOut event
19978 * @method b4DragOut
19981 b4DragOut: function(e) { },
19984 * Abstract method called when we are no longer hovering over an element
19985 * @method onDragOut
19986 * @param {Event} e the mousemove event
19987 * @param {String|DragDrop[]} id In POINT mode, the element
19988 * id this was hovering over. In INTERSECT mode, an array of dd items
19989 * that the mouse is no longer over.
19991 onDragOut: function(e, id) { /* override this */ },
19994 * Code that executes immediately before the onDragDrop event
19995 * @method b4DragDrop
19998 b4DragDrop: function(e) { },
20001 * Abstract method called when this item is dropped on another DragDrop
20003 * @method onDragDrop
20004 * @param {Event} e the mouseup event
20005 * @param {String|DragDrop[]} id In POINT mode, the element
20006 * id this was dropped on. In INTERSECT mode, an array of dd items this
20009 onDragDrop: function(e, id) { /* override this */ },
20012 * Abstract method called when this item is dropped on an area with no
20014 * @method onInvalidDrop
20015 * @param {Event} e the mouseup event
20017 onInvalidDrop: function(e) { /* override this */ },
20020 * Code that executes immediately before the endDrag event
20021 * @method b4EndDrag
20024 b4EndDrag: function(e) { },
20027 * Fired when we are done dragging the object
20029 * @param {Event} e the mouseup event
20031 endDrag: function(e) { /* override this */ },
20034 * Code executed immediately before the onMouseDown event
20035 * @method b4MouseDown
20036 * @param {Event} e the mousedown event
20039 b4MouseDown: function(e) { },
20042 * Event handler that fires when a drag/drop obj gets a mousedown
20043 * @method onMouseDown
20044 * @param {Event} e the mousedown event
20046 onMouseDown: function(e) { /* override this */ },
20049 * Event handler that fires when a drag/drop obj gets a mouseup
20050 * @method onMouseUp
20051 * @param {Event} e the mouseup event
20053 onMouseUp: function(e) { /* override this */ },
20056 * Override the onAvailable method to do what is needed after the initial
20057 * position was determined.
20058 * @method onAvailable
20060 onAvailable: function () {
20064 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
20067 defaultPadding : {left:0, right:0, top:0, bottom:0},
20070 * Initializes the drag drop object's constraints to restrict movement to a certain element.
20074 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
20075 { dragElId: "existingProxyDiv" });
20076 dd.startDrag = function(){
20077 this.constrainTo("parent-id");
20080 * Or you can initalize it using the {@link Roo.Element} object:
20082 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
20083 startDrag : function(){
20084 this.constrainTo("parent-id");
20088 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
20089 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
20090 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
20091 * an object containing the sides to pad. For example: {right:10, bottom:10}
20092 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
20094 constrainTo : function(constrainTo, pad, inContent){
20095 if(typeof pad == "number"){
20096 pad = {left: pad, right:pad, top:pad, bottom:pad};
20098 pad = pad || this.defaultPadding;
20099 var b = Roo.get(this.getEl()).getBox();
20100 var ce = Roo.get(constrainTo);
20101 var s = ce.getScroll();
20102 var c, cd = ce.dom;
20103 if(cd == document.body){
20104 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
20107 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
20111 var topSpace = b.y - c.y;
20112 var leftSpace = b.x - c.x;
20114 this.resetConstraints();
20115 this.setXConstraint(leftSpace - (pad.left||0), // left
20116 c.width - leftSpace - b.width - (pad.right||0) //right
20118 this.setYConstraint(topSpace - (pad.top||0), //top
20119 c.height - topSpace - b.height - (pad.bottom||0) //bottom
20124 * Returns a reference to the linked element
20126 * @return {HTMLElement} the html element
20128 getEl: function() {
20129 if (!this._domRef) {
20130 this._domRef = Roo.getDom(this.id);
20133 return this._domRef;
20137 * Returns a reference to the actual element to drag. By default this is
20138 * the same as the html element, but it can be assigned to another
20139 * element. An example of this can be found in Roo.dd.DDProxy
20140 * @method getDragEl
20141 * @return {HTMLElement} the html element
20143 getDragEl: function() {
20144 return Roo.getDom(this.dragElId);
20148 * Sets up the DragDrop object. Must be called in the constructor of any
20149 * Roo.dd.DragDrop subclass
20151 * @param id the id of the linked element
20152 * @param {String} sGroup the group of related items
20153 * @param {object} config configuration attributes
20155 init: function(id, sGroup, config) {
20156 this.initTarget(id, sGroup, config);
20157 if (!Roo.isTouch) {
20158 Event.on(this.id, "mousedown", this.handleMouseDown, this);
20160 Event.on(this.id, "touchstart", this.handleMouseDown, this);
20161 // Event.on(this.id, "selectstart", Event.preventDefault);
20165 * Initializes Targeting functionality only... the object does not
20166 * get a mousedown handler.
20167 * @method initTarget
20168 * @param id the id of the linked element
20169 * @param {String} sGroup the group of related items
20170 * @param {object} config configuration attributes
20172 initTarget: function(id, sGroup, config) {
20174 // configuration attributes
20175 this.config = config || {};
20177 // create a local reference to the drag and drop manager
20178 this.DDM = Roo.dd.DDM;
20179 // initialize the groups array
20182 // assume that we have an element reference instead of an id if the
20183 // parameter is not a string
20184 if (typeof id !== "string") {
20191 // add to an interaction group
20192 this.addToGroup((sGroup) ? sGroup : "default");
20194 // We don't want to register this as the handle with the manager
20195 // so we just set the id rather than calling the setter.
20196 this.handleElId = id;
20198 // the linked element is the element that gets dragged by default
20199 this.setDragElId(id);
20201 // by default, clicked anchors will not start drag operations.
20202 this.invalidHandleTypes = { A: "A" };
20203 this.invalidHandleIds = {};
20204 this.invalidHandleClasses = [];
20206 this.applyConfig();
20208 this.handleOnAvailable();
20212 * Applies the configuration parameters that were passed into the constructor.
20213 * This is supposed to happen at each level through the inheritance chain. So
20214 * a DDProxy implentation will execute apply config on DDProxy, DD, and
20215 * DragDrop in order to get all of the parameters that are available in
20217 * @method applyConfig
20219 applyConfig: function() {
20221 // configurable properties:
20222 // padding, isTarget, maintainOffset, primaryButtonOnly
20223 this.padding = this.config.padding || [0, 0, 0, 0];
20224 this.isTarget = (this.config.isTarget !== false);
20225 this.maintainOffset = (this.config.maintainOffset);
20226 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
20231 * Executed when the linked element is available
20232 * @method handleOnAvailable
20235 handleOnAvailable: function() {
20236 this.available = true;
20237 this.resetConstraints();
20238 this.onAvailable();
20242 * Configures the padding for the target zone in px. Effectively expands
20243 * (or reduces) the virtual object size for targeting calculations.
20244 * Supports css-style shorthand; if only one parameter is passed, all sides
20245 * will have that padding, and if only two are passed, the top and bottom
20246 * will have the first param, the left and right the second.
20247 * @method setPadding
20248 * @param {int} iTop Top pad
20249 * @param {int} iRight Right pad
20250 * @param {int} iBot Bot pad
20251 * @param {int} iLeft Left pad
20253 setPadding: function(iTop, iRight, iBot, iLeft) {
20254 // this.padding = [iLeft, iRight, iTop, iBot];
20255 if (!iRight && 0 !== iRight) {
20256 this.padding = [iTop, iTop, iTop, iTop];
20257 } else if (!iBot && 0 !== iBot) {
20258 this.padding = [iTop, iRight, iTop, iRight];
20260 this.padding = [iTop, iRight, iBot, iLeft];
20265 * Stores the initial placement of the linked element.
20266 * @method setInitialPosition
20267 * @param {int} diffX the X offset, default 0
20268 * @param {int} diffY the Y offset, default 0
20270 setInitPosition: function(diffX, diffY) {
20271 var el = this.getEl();
20273 if (!this.DDM.verifyEl(el)) {
20277 var dx = diffX || 0;
20278 var dy = diffY || 0;
20280 var p = Dom.getXY( el );
20282 this.initPageX = p[0] - dx;
20283 this.initPageY = p[1] - dy;
20285 this.lastPageX = p[0];
20286 this.lastPageY = p[1];
20289 this.setStartPosition(p);
20293 * Sets the start position of the element. This is set when the obj
20294 * is initialized, the reset when a drag is started.
20295 * @method setStartPosition
20296 * @param pos current position (from previous lookup)
20299 setStartPosition: function(pos) {
20300 var p = pos || Dom.getXY( this.getEl() );
20301 this.deltaSetXY = null;
20303 this.startPageX = p[0];
20304 this.startPageY = p[1];
20308 * Add this instance to a group of related drag/drop objects. All
20309 * instances belong to at least one group, and can belong to as many
20310 * groups as needed.
20311 * @method addToGroup
20312 * @param sGroup {string} the name of the group
20314 addToGroup: function(sGroup) {
20315 this.groups[sGroup] = true;
20316 this.DDM.regDragDrop(this, sGroup);
20320 * Remove's this instance from the supplied interaction group
20321 * @method removeFromGroup
20322 * @param {string} sGroup The group to drop
20324 removeFromGroup: function(sGroup) {
20325 if (this.groups[sGroup]) {
20326 delete this.groups[sGroup];
20329 this.DDM.removeDDFromGroup(this, sGroup);
20333 * Allows you to specify that an element other than the linked element
20334 * will be moved with the cursor during a drag
20335 * @method setDragElId
20336 * @param id {string} the id of the element that will be used to initiate the drag
20338 setDragElId: function(id) {
20339 this.dragElId = id;
20343 * Allows you to specify a child of the linked element that should be
20344 * used to initiate the drag operation. An example of this would be if
20345 * you have a content div with text and links. Clicking anywhere in the
20346 * content area would normally start the drag operation. Use this method
20347 * to specify that an element inside of the content div is the element
20348 * that starts the drag operation.
20349 * @method setHandleElId
20350 * @param id {string} the id of the element that will be used to
20351 * initiate the drag.
20353 setHandleElId: function(id) {
20354 if (typeof id !== "string") {
20357 this.handleElId = id;
20358 this.DDM.regHandle(this.id, id);
20362 * Allows you to set an element outside of the linked element as a drag
20364 * @method setOuterHandleElId
20365 * @param id the id of the element that will be used to initiate the drag
20367 setOuterHandleElId: function(id) {
20368 if (typeof id !== "string") {
20371 Event.on(id, "mousedown",
20372 this.handleMouseDown, this);
20373 this.setHandleElId(id);
20375 this.hasOuterHandles = true;
20379 * Remove all drag and drop hooks for this element
20382 unreg: function() {
20383 Event.un(this.id, "mousedown",
20384 this.handleMouseDown);
20385 Event.un(this.id, "touchstart",
20386 this.handleMouseDown);
20387 this._domRef = null;
20388 this.DDM._remove(this);
20391 destroy : function(){
20396 * Returns true if this instance is locked, or the drag drop mgr is locked
20397 * (meaning that all drag/drop is disabled on the page.)
20399 * @return {boolean} true if this obj or all drag/drop is locked, else
20402 isLocked: function() {
20403 return (this.DDM.isLocked() || this.locked);
20407 * Fired when this object is clicked
20408 * @method handleMouseDown
20410 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
20413 handleMouseDown: function(e, oDD){
20415 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
20416 //Roo.log('not touch/ button !=0');
20419 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
20420 return; // double touch..
20424 if (this.isLocked()) {
20425 //Roo.log('locked');
20429 this.DDM.refreshCache(this.groups);
20430 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
20431 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
20432 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
20433 //Roo.log('no outer handes or not over target');
20436 // Roo.log('check validator');
20437 if (this.clickValidator(e)) {
20438 // Roo.log('validate success');
20439 // set the initial element position
20440 this.setStartPosition();
20443 this.b4MouseDown(e);
20444 this.onMouseDown(e);
20446 this.DDM.handleMouseDown(e, this);
20448 this.DDM.stopEvent(e);
20456 clickValidator: function(e) {
20457 var target = e.getTarget();
20458 return ( this.isValidHandleChild(target) &&
20459 (this.id == this.handleElId ||
20460 this.DDM.handleWasClicked(target, this.id)) );
20464 * Allows you to specify a tag name that should not start a drag operation
20465 * when clicked. This is designed to facilitate embedding links within a
20466 * drag handle that do something other than start the drag.
20467 * @method addInvalidHandleType
20468 * @param {string} tagName the type of element to exclude
20470 addInvalidHandleType: function(tagName) {
20471 var type = tagName.toUpperCase();
20472 this.invalidHandleTypes[type] = type;
20476 * Lets you to specify an element id for a child of a drag handle
20477 * that should not initiate a drag
20478 * @method addInvalidHandleId
20479 * @param {string} id the element id of the element you wish to ignore
20481 addInvalidHandleId: function(id) {
20482 if (typeof id !== "string") {
20485 this.invalidHandleIds[id] = id;
20489 * Lets you specify a css class of elements that will not initiate a drag
20490 * @method addInvalidHandleClass
20491 * @param {string} cssClass the class of the elements you wish to ignore
20493 addInvalidHandleClass: function(cssClass) {
20494 this.invalidHandleClasses.push(cssClass);
20498 * Unsets an excluded tag name set by addInvalidHandleType
20499 * @method removeInvalidHandleType
20500 * @param {string} tagName the type of element to unexclude
20502 removeInvalidHandleType: function(tagName) {
20503 var type = tagName.toUpperCase();
20504 // this.invalidHandleTypes[type] = null;
20505 delete this.invalidHandleTypes[type];
20509 * Unsets an invalid handle id
20510 * @method removeInvalidHandleId
20511 * @param {string} id the id of the element to re-enable
20513 removeInvalidHandleId: function(id) {
20514 if (typeof id !== "string") {
20517 delete this.invalidHandleIds[id];
20521 * Unsets an invalid css class
20522 * @method removeInvalidHandleClass
20523 * @param {string} cssClass the class of the element(s) you wish to
20526 removeInvalidHandleClass: function(cssClass) {
20527 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
20528 if (this.invalidHandleClasses[i] == cssClass) {
20529 delete this.invalidHandleClasses[i];
20535 * Checks the tag exclusion list to see if this click should be ignored
20536 * @method isValidHandleChild
20537 * @param {HTMLElement} node the HTMLElement to evaluate
20538 * @return {boolean} true if this is a valid tag type, false if not
20540 isValidHandleChild: function(node) {
20543 // var n = (node.nodeName == "#text") ? node.parentNode : node;
20546 nodeName = node.nodeName.toUpperCase();
20548 nodeName = node.nodeName;
20550 valid = valid && !this.invalidHandleTypes[nodeName];
20551 valid = valid && !this.invalidHandleIds[node.id];
20553 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
20554 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
20563 * Create the array of horizontal tick marks if an interval was specified
20564 * in setXConstraint().
20565 * @method setXTicks
20568 setXTicks: function(iStartX, iTickSize) {
20570 this.xTickSize = iTickSize;
20574 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
20576 this.xTicks[this.xTicks.length] = i;
20581 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
20583 this.xTicks[this.xTicks.length] = i;
20588 this.xTicks.sort(this.DDM.numericSort) ;
20592 * Create the array of vertical tick marks if an interval was specified in
20593 * setYConstraint().
20594 * @method setYTicks
20597 setYTicks: function(iStartY, iTickSize) {
20599 this.yTickSize = iTickSize;
20603 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
20605 this.yTicks[this.yTicks.length] = i;
20610 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
20612 this.yTicks[this.yTicks.length] = i;
20617 this.yTicks.sort(this.DDM.numericSort) ;
20621 * By default, the element can be dragged any place on the screen. Use
20622 * this method to limit the horizontal travel of the element. Pass in
20623 * 0,0 for the parameters if you want to lock the drag to the y axis.
20624 * @method setXConstraint
20625 * @param {int} iLeft the number of pixels the element can move to the left
20626 * @param {int} iRight the number of pixels the element can move to the
20628 * @param {int} iTickSize optional parameter for specifying that the
20630 * should move iTickSize pixels at a time.
20632 setXConstraint: function(iLeft, iRight, iTickSize) {
20633 this.leftConstraint = iLeft;
20634 this.rightConstraint = iRight;
20636 this.minX = this.initPageX - iLeft;
20637 this.maxX = this.initPageX + iRight;
20638 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
20640 this.constrainX = true;
20644 * Clears any constraints applied to this instance. Also clears ticks
20645 * since they can't exist independent of a constraint at this time.
20646 * @method clearConstraints
20648 clearConstraints: function() {
20649 this.constrainX = false;
20650 this.constrainY = false;
20655 * Clears any tick interval defined for this instance
20656 * @method clearTicks
20658 clearTicks: function() {
20659 this.xTicks = null;
20660 this.yTicks = null;
20661 this.xTickSize = 0;
20662 this.yTickSize = 0;
20666 * By default, the element can be dragged any place on the screen. Set
20667 * this to limit the vertical travel of the element. Pass in 0,0 for the
20668 * parameters if you want to lock the drag to the x axis.
20669 * @method setYConstraint
20670 * @param {int} iUp the number of pixels the element can move up
20671 * @param {int} iDown the number of pixels the element can move down
20672 * @param {int} iTickSize optional parameter for specifying that the
20673 * element should move iTickSize pixels at a time.
20675 setYConstraint: function(iUp, iDown, iTickSize) {
20676 this.topConstraint = iUp;
20677 this.bottomConstraint = iDown;
20679 this.minY = this.initPageY - iUp;
20680 this.maxY = this.initPageY + iDown;
20681 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
20683 this.constrainY = true;
20688 * resetConstraints must be called if you manually reposition a dd element.
20689 * @method resetConstraints
20690 * @param {boolean} maintainOffset
20692 resetConstraints: function() {
20695 // Maintain offsets if necessary
20696 if (this.initPageX || this.initPageX === 0) {
20697 // figure out how much this thing has moved
20698 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
20699 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
20701 this.setInitPosition(dx, dy);
20703 // This is the first time we have detected the element's position
20705 this.setInitPosition();
20708 if (this.constrainX) {
20709 this.setXConstraint( this.leftConstraint,
20710 this.rightConstraint,
20714 if (this.constrainY) {
20715 this.setYConstraint( this.topConstraint,
20716 this.bottomConstraint,
20722 * Normally the drag element is moved pixel by pixel, but we can specify
20723 * that it move a number of pixels at a time. This method resolves the
20724 * location when we have it set up like this.
20726 * @param {int} val where we want to place the object
20727 * @param {int[]} tickArray sorted array of valid points
20728 * @return {int} the closest tick
20731 getTick: function(val, tickArray) {
20734 // If tick interval is not defined, it is effectively 1 pixel,
20735 // so we return the value passed to us.
20737 } else if (tickArray[0] >= val) {
20738 // The value is lower than the first tick, so we return the first
20740 return tickArray[0];
20742 for (var i=0, len=tickArray.length; i<len; ++i) {
20744 if (tickArray[next] && tickArray[next] >= val) {
20745 var diff1 = val - tickArray[i];
20746 var diff2 = tickArray[next] - val;
20747 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
20751 // The value is larger than the last tick, so we return the last
20753 return tickArray[tickArray.length - 1];
20760 * @return {string} string representation of the dd obj
20762 toString: function() {
20763 return ("DragDrop " + this.id);
20771 * Ext JS Library 1.1.1
20772 * Copyright(c) 2006-2007, Ext JS, LLC.
20774 * Originally Released Under LGPL - original licence link has changed is not relivant.
20777 * <script type="text/javascript">
20782 * The drag and drop utility provides a framework for building drag and drop
20783 * applications. In addition to enabling drag and drop for specific elements,
20784 * the drag and drop elements are tracked by the manager class, and the
20785 * interactions between the various elements are tracked during the drag and
20786 * the implementing code is notified about these important moments.
20789 // Only load the library once. Rewriting the manager class would orphan
20790 // existing drag and drop instances.
20791 if (!Roo.dd.DragDropMgr) {
20794 * @class Roo.dd.DragDropMgr
20795 * DragDropMgr is a singleton that tracks the element interaction for
20796 * all DragDrop items in the window. Generally, you will not call
20797 * this class directly, but it does have helper methods that could
20798 * be useful in your DragDrop implementations.
20801 Roo.dd.DragDropMgr = function() {
20803 var Event = Roo.EventManager;
20808 * Two dimensional Array of registered DragDrop objects. The first
20809 * dimension is the DragDrop item group, the second the DragDrop
20812 * @type {string: string}
20819 * Array of element ids defined as drag handles. Used to determine
20820 * if the element that generated the mousedown event is actually the
20821 * handle and not the html element itself.
20822 * @property handleIds
20823 * @type {string: string}
20830 * the DragDrop object that is currently being dragged
20831 * @property dragCurrent
20839 * the DragDrop object(s) that are being hovered over
20840 * @property dragOvers
20848 * the X distance between the cursor and the object being dragged
20857 * the Y distance between the cursor and the object being dragged
20866 * Flag to determine if we should prevent the default behavior of the
20867 * events we define. By default this is true, but this can be set to
20868 * false if you need the default behavior (not recommended)
20869 * @property preventDefault
20873 preventDefault: true,
20876 * Flag to determine if we should stop the propagation of the events
20877 * we generate. This is true by default but you may want to set it to
20878 * false if the html element contains other features that require the
20880 * @property stopPropagation
20884 stopPropagation: true,
20887 * Internal flag that is set to true when drag and drop has been
20889 * @property initialized
20896 * All drag and drop can be disabled.
20904 * Called the first time an element is registered.
20910 this.initialized = true;
20914 * In point mode, drag and drop interaction is defined by the
20915 * location of the cursor during the drag/drop
20923 * In intersect mode, drag and drop interactio nis defined by the
20924 * overlap of two or more drag and drop objects.
20925 * @property INTERSECT
20932 * The current drag and drop mode. Default: POINT
20940 * Runs method on all drag and drop objects
20941 * @method _execOnAll
20945 _execOnAll: function(sMethod, args) {
20946 for (var i in this.ids) {
20947 for (var j in this.ids[i]) {
20948 var oDD = this.ids[i][j];
20949 if (! this.isTypeOfDD(oDD)) {
20952 oDD[sMethod].apply(oDD, args);
20958 * Drag and drop initialization. Sets up the global event handlers
20963 _onLoad: function() {
20967 if (!Roo.isTouch) {
20968 Event.on(document, "mouseup", this.handleMouseUp, this, true);
20969 Event.on(document, "mousemove", this.handleMouseMove, this, true);
20971 Event.on(document, "touchend", this.handleMouseUp, this, true);
20972 Event.on(document, "touchmove", this.handleMouseMove, this, true);
20974 Event.on(window, "unload", this._onUnload, this, true);
20975 Event.on(window, "resize", this._onResize, this, true);
20976 // Event.on(window, "mouseout", this._test);
20981 * Reset constraints on all drag and drop objs
20982 * @method _onResize
20986 _onResize: function(e) {
20987 this._execOnAll("resetConstraints", []);
20991 * Lock all drag and drop functionality
20995 lock: function() { this.locked = true; },
20998 * Unlock all drag and drop functionality
21002 unlock: function() { this.locked = false; },
21005 * Is drag and drop locked?
21007 * @return {boolean} True if drag and drop is locked, false otherwise.
21010 isLocked: function() { return this.locked; },
21013 * Location cache that is set for all drag drop objects when a drag is
21014 * initiated, cleared when the drag is finished.
21015 * @property locationCache
21022 * Set useCache to false if you want to force object the lookup of each
21023 * drag and drop linked element constantly during a drag.
21024 * @property useCache
21031 * The number of pixels that the mouse needs to move after the
21032 * mousedown before the drag is initiated. Default=3;
21033 * @property clickPixelThresh
21037 clickPixelThresh: 3,
21040 * The number of milliseconds after the mousedown event to initiate the
21041 * drag if we don't get a mouseup event. Default=1000
21042 * @property clickTimeThresh
21046 clickTimeThresh: 350,
21049 * Flag that indicates that either the drag pixel threshold or the
21050 * mousdown time threshold has been met
21051 * @property dragThreshMet
21056 dragThreshMet: false,
21059 * Timeout used for the click time threshold
21060 * @property clickTimeout
21065 clickTimeout: null,
21068 * The X position of the mousedown event stored for later use when a
21069 * drag threshold is met.
21078 * The Y position of the mousedown event stored for later use when a
21079 * drag threshold is met.
21088 * Each DragDrop instance must be registered with the DragDropMgr.
21089 * This is executed in DragDrop.init()
21090 * @method regDragDrop
21091 * @param {DragDrop} oDD the DragDrop object to register
21092 * @param {String} sGroup the name of the group this element belongs to
21095 regDragDrop: function(oDD, sGroup) {
21096 if (!this.initialized) { this.init(); }
21098 if (!this.ids[sGroup]) {
21099 this.ids[sGroup] = {};
21101 this.ids[sGroup][oDD.id] = oDD;
21105 * Removes the supplied dd instance from the supplied group. Executed
21106 * by DragDrop.removeFromGroup, so don't call this function directly.
21107 * @method removeDDFromGroup
21111 removeDDFromGroup: function(oDD, sGroup) {
21112 if (!this.ids[sGroup]) {
21113 this.ids[sGroup] = {};
21116 var obj = this.ids[sGroup];
21117 if (obj && obj[oDD.id]) {
21118 delete obj[oDD.id];
21123 * Unregisters a drag and drop item. This is executed in
21124 * DragDrop.unreg, use that method instead of calling this directly.
21129 _remove: function(oDD) {
21130 for (var g in oDD.groups) {
21131 if (g && this.ids[g][oDD.id]) {
21132 delete this.ids[g][oDD.id];
21135 delete this.handleIds[oDD.id];
21139 * Each DragDrop handle element must be registered. This is done
21140 * automatically when executing DragDrop.setHandleElId()
21141 * @method regHandle
21142 * @param {String} sDDId the DragDrop id this element is a handle for
21143 * @param {String} sHandleId the id of the element that is the drag
21147 regHandle: function(sDDId, sHandleId) {
21148 if (!this.handleIds[sDDId]) {
21149 this.handleIds[sDDId] = {};
21151 this.handleIds[sDDId][sHandleId] = sHandleId;
21155 * Utility function to determine if a given element has been
21156 * registered as a drag drop item.
21157 * @method isDragDrop
21158 * @param {String} id the element id to check
21159 * @return {boolean} true if this element is a DragDrop item,
21163 isDragDrop: function(id) {
21164 return ( this.getDDById(id) ) ? true : false;
21168 * Returns the drag and drop instances that are in all groups the
21169 * passed in instance belongs to.
21170 * @method getRelated
21171 * @param {DragDrop} p_oDD the obj to get related data for
21172 * @param {boolean} bTargetsOnly if true, only return targetable objs
21173 * @return {DragDrop[]} the related instances
21176 getRelated: function(p_oDD, bTargetsOnly) {
21178 for (var i in p_oDD.groups) {
21179 for (j in this.ids[i]) {
21180 var dd = this.ids[i][j];
21181 if (! this.isTypeOfDD(dd)) {
21184 if (!bTargetsOnly || dd.isTarget) {
21185 oDDs[oDDs.length] = dd;
21194 * Returns true if the specified dd target is a legal target for
21195 * the specifice drag obj
21196 * @method isLegalTarget
21197 * @param {DragDrop} the drag obj
21198 * @param {DragDrop} the target
21199 * @return {boolean} true if the target is a legal target for the
21203 isLegalTarget: function (oDD, oTargetDD) {
21204 var targets = this.getRelated(oDD, true);
21205 for (var i=0, len=targets.length;i<len;++i) {
21206 if (targets[i].id == oTargetDD.id) {
21215 * My goal is to be able to transparently determine if an object is
21216 * typeof DragDrop, and the exact subclass of DragDrop. typeof
21217 * returns "object", oDD.constructor.toString() always returns
21218 * "DragDrop" and not the name of the subclass. So for now it just
21219 * evaluates a well-known variable in DragDrop.
21220 * @method isTypeOfDD
21221 * @param {Object} the object to evaluate
21222 * @return {boolean} true if typeof oDD = DragDrop
21225 isTypeOfDD: function (oDD) {
21226 return (oDD && oDD.__ygDragDrop);
21230 * Utility function to determine if a given element has been
21231 * registered as a drag drop handle for the given Drag Drop object.
21233 * @param {String} id the element id to check
21234 * @return {boolean} true if this element is a DragDrop handle, false
21238 isHandle: function(sDDId, sHandleId) {
21239 return ( this.handleIds[sDDId] &&
21240 this.handleIds[sDDId][sHandleId] );
21244 * Returns the DragDrop instance for a given id
21245 * @method getDDById
21246 * @param {String} id the id of the DragDrop object
21247 * @return {DragDrop} the drag drop object, null if it is not found
21250 getDDById: function(id) {
21251 for (var i in this.ids) {
21252 if (this.ids[i][id]) {
21253 return this.ids[i][id];
21260 * Fired after a registered DragDrop object gets the mousedown event.
21261 * Sets up the events required to track the object being dragged
21262 * @method handleMouseDown
21263 * @param {Event} e the event
21264 * @param oDD the DragDrop object being dragged
21268 handleMouseDown: function(e, oDD) {
21270 Roo.QuickTips.disable();
21272 this.currentTarget = e.getTarget();
21274 this.dragCurrent = oDD;
21276 var el = oDD.getEl();
21278 // track start position
21279 this.startX = e.getPageX();
21280 this.startY = e.getPageY();
21282 this.deltaX = this.startX - el.offsetLeft;
21283 this.deltaY = this.startY - el.offsetTop;
21285 this.dragThreshMet = false;
21287 this.clickTimeout = setTimeout(
21289 var DDM = Roo.dd.DDM;
21290 DDM.startDrag(DDM.startX, DDM.startY);
21292 this.clickTimeThresh );
21296 * Fired when either the drag pixel threshol or the mousedown hold
21297 * time threshold has been met.
21298 * @method startDrag
21299 * @param x {int} the X position of the original mousedown
21300 * @param y {int} the Y position of the original mousedown
21303 startDrag: function(x, y) {
21304 clearTimeout(this.clickTimeout);
21305 if (this.dragCurrent) {
21306 this.dragCurrent.b4StartDrag(x, y);
21307 this.dragCurrent.startDrag(x, y);
21309 this.dragThreshMet = true;
21313 * Internal function to handle the mouseup event. Will be invoked
21314 * from the context of the document.
21315 * @method handleMouseUp
21316 * @param {Event} e the event
21320 handleMouseUp: function(e) {
21323 Roo.QuickTips.enable();
21325 if (! this.dragCurrent) {
21329 clearTimeout(this.clickTimeout);
21331 if (this.dragThreshMet) {
21332 this.fireEvents(e, true);
21342 * Utility to stop event propagation and event default, if these
21343 * features are turned on.
21344 * @method stopEvent
21345 * @param {Event} e the event as returned by this.getEvent()
21348 stopEvent: function(e){
21349 if(this.stopPropagation) {
21350 e.stopPropagation();
21353 if (this.preventDefault) {
21354 e.preventDefault();
21359 * Internal function to clean up event handlers after the drag
21360 * operation is complete
21362 * @param {Event} e the event
21366 stopDrag: function(e) {
21367 // Fire the drag end event for the item that was dragged
21368 if (this.dragCurrent) {
21369 if (this.dragThreshMet) {
21370 this.dragCurrent.b4EndDrag(e);
21371 this.dragCurrent.endDrag(e);
21374 this.dragCurrent.onMouseUp(e);
21377 this.dragCurrent = null;
21378 this.dragOvers = {};
21382 * Internal function to handle the mousemove event. Will be invoked
21383 * from the context of the html element.
21385 * @TODO figure out what we can do about mouse events lost when the
21386 * user drags objects beyond the window boundary. Currently we can
21387 * detect this in internet explorer by verifying that the mouse is
21388 * down during the mousemove event. Firefox doesn't give us the
21389 * button state on the mousemove event.
21390 * @method handleMouseMove
21391 * @param {Event} e the event
21395 handleMouseMove: function(e) {
21396 if (! this.dragCurrent) {
21400 // var button = e.which || e.button;
21402 // check for IE mouseup outside of page boundary
21403 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
21405 return this.handleMouseUp(e);
21408 if (!this.dragThreshMet) {
21409 var diffX = Math.abs(this.startX - e.getPageX());
21410 var diffY = Math.abs(this.startY - e.getPageY());
21411 if (diffX > this.clickPixelThresh ||
21412 diffY > this.clickPixelThresh) {
21413 this.startDrag(this.startX, this.startY);
21417 if (this.dragThreshMet) {
21418 this.dragCurrent.b4Drag(e);
21419 this.dragCurrent.onDrag(e);
21420 if(!this.dragCurrent.moveOnly){
21421 this.fireEvents(e, false);
21431 * Iterates over all of the DragDrop elements to find ones we are
21432 * hovering over or dropping on
21433 * @method fireEvents
21434 * @param {Event} e the event
21435 * @param {boolean} isDrop is this a drop op or a mouseover op?
21439 fireEvents: function(e, isDrop) {
21440 var dc = this.dragCurrent;
21442 // If the user did the mouse up outside of the window, we could
21443 // get here even though we have ended the drag.
21444 if (!dc || dc.isLocked()) {
21448 var pt = e.getPoint();
21450 // cache the previous dragOver array
21456 var enterEvts = [];
21458 // Check to see if the object(s) we were hovering over is no longer
21459 // being hovered over so we can fire the onDragOut event
21460 for (var i in this.dragOvers) {
21462 var ddo = this.dragOvers[i];
21464 if (! this.isTypeOfDD(ddo)) {
21468 if (! this.isOverTarget(pt, ddo, this.mode)) {
21469 outEvts.push( ddo );
21472 oldOvers[i] = true;
21473 delete this.dragOvers[i];
21476 for (var sGroup in dc.groups) {
21478 if ("string" != typeof sGroup) {
21482 for (i in this.ids[sGroup]) {
21483 var oDD = this.ids[sGroup][i];
21484 if (! this.isTypeOfDD(oDD)) {
21488 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
21489 if (this.isOverTarget(pt, oDD, this.mode)) {
21490 // look for drop interactions
21492 dropEvts.push( oDD );
21493 // look for drag enter and drag over interactions
21496 // initial drag over: dragEnter fires
21497 if (!oldOvers[oDD.id]) {
21498 enterEvts.push( oDD );
21499 // subsequent drag overs: dragOver fires
21501 overEvts.push( oDD );
21504 this.dragOvers[oDD.id] = oDD;
21512 if (outEvts.length) {
21513 dc.b4DragOut(e, outEvts);
21514 dc.onDragOut(e, outEvts);
21517 if (enterEvts.length) {
21518 dc.onDragEnter(e, enterEvts);
21521 if (overEvts.length) {
21522 dc.b4DragOver(e, overEvts);
21523 dc.onDragOver(e, overEvts);
21526 if (dropEvts.length) {
21527 dc.b4DragDrop(e, dropEvts);
21528 dc.onDragDrop(e, dropEvts);
21532 // fire dragout events
21534 for (i=0, len=outEvts.length; i<len; ++i) {
21535 dc.b4DragOut(e, outEvts[i].id);
21536 dc.onDragOut(e, outEvts[i].id);
21539 // fire enter events
21540 for (i=0,len=enterEvts.length; i<len; ++i) {
21541 // dc.b4DragEnter(e, oDD.id);
21542 dc.onDragEnter(e, enterEvts[i].id);
21545 // fire over events
21546 for (i=0,len=overEvts.length; i<len; ++i) {
21547 dc.b4DragOver(e, overEvts[i].id);
21548 dc.onDragOver(e, overEvts[i].id);
21551 // fire drop events
21552 for (i=0, len=dropEvts.length; i<len; ++i) {
21553 dc.b4DragDrop(e, dropEvts[i].id);
21554 dc.onDragDrop(e, dropEvts[i].id);
21559 // notify about a drop that did not find a target
21560 if (isDrop && !dropEvts.length) {
21561 dc.onInvalidDrop(e);
21567 * Helper function for getting the best match from the list of drag
21568 * and drop objects returned by the drag and drop events when we are
21569 * in INTERSECT mode. It returns either the first object that the
21570 * cursor is over, or the object that has the greatest overlap with
21571 * the dragged element.
21572 * @method getBestMatch
21573 * @param {DragDrop[]} dds The array of drag and drop objects
21575 * @return {DragDrop} The best single match
21578 getBestMatch: function(dds) {
21580 // Return null if the input is not what we expect
21581 //if (!dds || !dds.length || dds.length == 0) {
21583 // If there is only one item, it wins
21584 //} else if (dds.length == 1) {
21586 var len = dds.length;
21591 // Loop through the targeted items
21592 for (var i=0; i<len; ++i) {
21594 // If the cursor is over the object, it wins. If the
21595 // cursor is over multiple matches, the first one we come
21597 if (dd.cursorIsOver) {
21600 // Otherwise the object with the most overlap wins
21603 winner.overlap.getArea() < dd.overlap.getArea()) {
21614 * Refreshes the cache of the top-left and bottom-right points of the
21615 * drag and drop objects in the specified group(s). This is in the
21616 * format that is stored in the drag and drop instance, so typical
21619 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
21623 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
21625 * @TODO this really should be an indexed array. Alternatively this
21626 * method could accept both.
21627 * @method refreshCache
21628 * @param {Object} groups an associative array of groups to refresh
21631 refreshCache: function(groups) {
21632 for (var sGroup in groups) {
21633 if ("string" != typeof sGroup) {
21636 for (var i in this.ids[sGroup]) {
21637 var oDD = this.ids[sGroup][i];
21639 if (this.isTypeOfDD(oDD)) {
21640 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
21641 var loc = this.getLocation(oDD);
21643 this.locationCache[oDD.id] = loc;
21645 delete this.locationCache[oDD.id];
21646 // this will unregister the drag and drop object if
21647 // the element is not in a usable state
21656 * This checks to make sure an element exists and is in the DOM. The
21657 * main purpose is to handle cases where innerHTML is used to remove
21658 * drag and drop objects from the DOM. IE provides an 'unspecified
21659 * error' when trying to access the offsetParent of such an element
21661 * @param {HTMLElement} el the element to check
21662 * @return {boolean} true if the element looks usable
21665 verifyEl: function(el) {
21670 parent = el.offsetParent;
21673 parent = el.offsetParent;
21684 * Returns a Region object containing the drag and drop element's position
21685 * and size, including the padding configured for it
21686 * @method getLocation
21687 * @param {DragDrop} oDD the drag and drop object to get the
21689 * @return {Roo.lib.Region} a Region object representing the total area
21690 * the element occupies, including any padding
21691 * the instance is configured for.
21694 getLocation: function(oDD) {
21695 if (! this.isTypeOfDD(oDD)) {
21699 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
21702 pos= Roo.lib.Dom.getXY(el);
21710 x2 = x1 + el.offsetWidth;
21712 y2 = y1 + el.offsetHeight;
21714 t = y1 - oDD.padding[0];
21715 r = x2 + oDD.padding[1];
21716 b = y2 + oDD.padding[2];
21717 l = x1 - oDD.padding[3];
21719 return new Roo.lib.Region( t, r, b, l );
21723 * Checks the cursor location to see if it over the target
21724 * @method isOverTarget
21725 * @param {Roo.lib.Point} pt The point to evaluate
21726 * @param {DragDrop} oTarget the DragDrop object we are inspecting
21727 * @return {boolean} true if the mouse is over the target
21731 isOverTarget: function(pt, oTarget, intersect) {
21732 // use cache if available
21733 var loc = this.locationCache[oTarget.id];
21734 if (!loc || !this.useCache) {
21735 loc = this.getLocation(oTarget);
21736 this.locationCache[oTarget.id] = loc;
21744 oTarget.cursorIsOver = loc.contains( pt );
21746 // DragDrop is using this as a sanity check for the initial mousedown
21747 // in this case we are done. In POINT mode, if the drag obj has no
21748 // contraints, we are also done. Otherwise we need to evaluate the
21749 // location of the target as related to the actual location of the
21750 // dragged element.
21751 var dc = this.dragCurrent;
21752 if (!dc || !dc.getTargetCoord ||
21753 (!intersect && !dc.constrainX && !dc.constrainY)) {
21754 return oTarget.cursorIsOver;
21757 oTarget.overlap = null;
21759 // Get the current location of the drag element, this is the
21760 // location of the mouse event less the delta that represents
21761 // where the original mousedown happened on the element. We
21762 // need to consider constraints and ticks as well.
21763 var pos = dc.getTargetCoord(pt.x, pt.y);
21765 var el = dc.getDragEl();
21766 var curRegion = new Roo.lib.Region( pos.y,
21767 pos.x + el.offsetWidth,
21768 pos.y + el.offsetHeight,
21771 var overlap = curRegion.intersect(loc);
21774 oTarget.overlap = overlap;
21775 return (intersect) ? true : oTarget.cursorIsOver;
21782 * unload event handler
21783 * @method _onUnload
21787 _onUnload: function(e, me) {
21788 Roo.dd.DragDropMgr.unregAll();
21792 * Cleans up the drag and drop events and objects.
21797 unregAll: function() {
21799 if (this.dragCurrent) {
21801 this.dragCurrent = null;
21804 this._execOnAll("unreg", []);
21806 for (i in this.elementCache) {
21807 delete this.elementCache[i];
21810 this.elementCache = {};
21815 * A cache of DOM elements
21816 * @property elementCache
21823 * Get the wrapper for the DOM element specified
21824 * @method getElWrapper
21825 * @param {String} id the id of the element to get
21826 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
21828 * @deprecated This wrapper isn't that useful
21831 getElWrapper: function(id) {
21832 var oWrapper = this.elementCache[id];
21833 if (!oWrapper || !oWrapper.el) {
21834 oWrapper = this.elementCache[id] =
21835 new this.ElementWrapper(Roo.getDom(id));
21841 * Returns the actual DOM element
21842 * @method getElement
21843 * @param {String} id the id of the elment to get
21844 * @return {Object} The element
21845 * @deprecated use Roo.getDom instead
21848 getElement: function(id) {
21849 return Roo.getDom(id);
21853 * Returns the style property for the DOM element (i.e.,
21854 * document.getElById(id).style)
21856 * @param {String} id the id of the elment to get
21857 * @return {Object} The style property of the element
21858 * @deprecated use Roo.getDom instead
21861 getCss: function(id) {
21862 var el = Roo.getDom(id);
21863 return (el) ? el.style : null;
21867 * Inner class for cached elements
21868 * @class DragDropMgr.ElementWrapper
21873 ElementWrapper: function(el) {
21878 this.el = el || null;
21883 this.id = this.el && el.id;
21885 * A reference to the style property
21888 this.css = this.el && el.style;
21892 * Returns the X position of an html element
21894 * @param el the element for which to get the position
21895 * @return {int} the X coordinate
21897 * @deprecated use Roo.lib.Dom.getX instead
21900 getPosX: function(el) {
21901 return Roo.lib.Dom.getX(el);
21905 * Returns the Y position of an html element
21907 * @param el the element for which to get the position
21908 * @return {int} the Y coordinate
21909 * @deprecated use Roo.lib.Dom.getY instead
21912 getPosY: function(el) {
21913 return Roo.lib.Dom.getY(el);
21917 * Swap two nodes. In IE, we use the native method, for others we
21918 * emulate the IE behavior
21920 * @param n1 the first node to swap
21921 * @param n2 the other node to swap
21924 swapNode: function(n1, n2) {
21928 var p = n2.parentNode;
21929 var s = n2.nextSibling;
21932 p.insertBefore(n1, n2);
21933 } else if (n2 == n1.nextSibling) {
21934 p.insertBefore(n2, n1);
21936 n1.parentNode.replaceChild(n2, n1);
21937 p.insertBefore(n1, s);
21943 * Returns the current scroll position
21944 * @method getScroll
21948 getScroll: function () {
21949 var t, l, dde=document.documentElement, db=document.body;
21950 if (dde && (dde.scrollTop || dde.scrollLeft)) {
21952 l = dde.scrollLeft;
21959 return { top: t, left: l };
21963 * Returns the specified element style property
21965 * @param {HTMLElement} el the element
21966 * @param {string} styleProp the style property
21967 * @return {string} The value of the style property
21968 * @deprecated use Roo.lib.Dom.getStyle
21971 getStyle: function(el, styleProp) {
21972 return Roo.fly(el).getStyle(styleProp);
21976 * Gets the scrollTop
21977 * @method getScrollTop
21978 * @return {int} the document's scrollTop
21981 getScrollTop: function () { return this.getScroll().top; },
21984 * Gets the scrollLeft
21985 * @method getScrollLeft
21986 * @return {int} the document's scrollTop
21989 getScrollLeft: function () { return this.getScroll().left; },
21992 * Sets the x/y position of an element to the location of the
21995 * @param {HTMLElement} moveEl The element to move
21996 * @param {HTMLElement} targetEl The position reference element
21999 moveToEl: function (moveEl, targetEl) {
22000 var aCoord = Roo.lib.Dom.getXY(targetEl);
22001 Roo.lib.Dom.setXY(moveEl, aCoord);
22005 * Numeric array sort function
22006 * @method numericSort
22009 numericSort: function(a, b) { return (a - b); },
22013 * @property _timeoutCount
22020 * Trying to make the load order less important. Without this we get
22021 * an error if this file is loaded before the Event Utility.
22022 * @method _addListeners
22026 _addListeners: function() {
22027 var DDM = Roo.dd.DDM;
22028 if ( Roo.lib.Event && document ) {
22031 if (DDM._timeoutCount > 2000) {
22033 setTimeout(DDM._addListeners, 10);
22034 if (document && document.body) {
22035 DDM._timeoutCount += 1;
22042 * Recursively searches the immediate parent and all child nodes for
22043 * the handle element in order to determine wheter or not it was
22045 * @method handleWasClicked
22046 * @param node the html element to inspect
22049 handleWasClicked: function(node, id) {
22050 if (this.isHandle(id, node.id)) {
22053 // check to see if this is a text node child of the one we want
22054 var p = node.parentNode;
22057 if (this.isHandle(id, p.id)) {
22072 // shorter alias, save a few bytes
22073 Roo.dd.DDM = Roo.dd.DragDropMgr;
22074 Roo.dd.DDM._addListeners();
22078 * Ext JS Library 1.1.1
22079 * Copyright(c) 2006-2007, Ext JS, LLC.
22081 * Originally Released Under LGPL - original licence link has changed is not relivant.
22084 * <script type="text/javascript">
22089 * A DragDrop implementation where the linked element follows the
22090 * mouse cursor during a drag.
22091 * @extends Roo.dd.DragDrop
22093 * @param {String} id the id of the linked element
22094 * @param {String} sGroup the group of related DragDrop items
22095 * @param {object} config an object containing configurable attributes
22096 * Valid properties for DD:
22099 Roo.dd.DD = function(id, sGroup, config) {
22101 this.init(id, sGroup, config);
22105 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
22108 * When set to true, the utility automatically tries to scroll the browser
22109 * window wehn a drag and drop element is dragged near the viewport boundary.
22110 * Defaults to true.
22117 * Sets the pointer offset to the distance between the linked element's top
22118 * left corner and the location the element was clicked
22119 * @method autoOffset
22120 * @param {int} iPageX the X coordinate of the click
22121 * @param {int} iPageY the Y coordinate of the click
22123 autoOffset: function(iPageX, iPageY) {
22124 var x = iPageX - this.startPageX;
22125 var y = iPageY - this.startPageY;
22126 this.setDelta(x, y);
22130 * Sets the pointer offset. You can call this directly to force the
22131 * offset to be in a particular location (e.g., pass in 0,0 to set it
22132 * to the center of the object)
22134 * @param {int} iDeltaX the distance from the left
22135 * @param {int} iDeltaY the distance from the top
22137 setDelta: function(iDeltaX, iDeltaY) {
22138 this.deltaX = iDeltaX;
22139 this.deltaY = iDeltaY;
22143 * Sets the drag element to the location of the mousedown or click event,
22144 * maintaining the cursor location relative to the location on the element
22145 * that was clicked. Override this if you want to place the element in a
22146 * location other than where the cursor is.
22147 * @method setDragElPos
22148 * @param {int} iPageX the X coordinate of the mousedown or drag event
22149 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22151 setDragElPos: function(iPageX, iPageY) {
22152 // the first time we do this, we are going to check to make sure
22153 // the element has css positioning
22155 var el = this.getDragEl();
22156 this.alignElWithMouse(el, iPageX, iPageY);
22160 * Sets the element to the location of the mousedown or click event,
22161 * maintaining the cursor location relative to the location on the element
22162 * that was clicked. Override this if you want to place the element in a
22163 * location other than where the cursor is.
22164 * @method alignElWithMouse
22165 * @param {HTMLElement} el the element to move
22166 * @param {int} iPageX the X coordinate of the mousedown or drag event
22167 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22169 alignElWithMouse: function(el, iPageX, iPageY) {
22170 var oCoord = this.getTargetCoord(iPageX, iPageY);
22171 var fly = el.dom ? el : Roo.fly(el);
22172 if (!this.deltaSetXY) {
22173 var aCoord = [oCoord.x, oCoord.y];
22175 var newLeft = fly.getLeft(true);
22176 var newTop = fly.getTop(true);
22177 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
22179 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
22182 this.cachePosition(oCoord.x, oCoord.y);
22183 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
22188 * Saves the most recent position so that we can reset the constraints and
22189 * tick marks on-demand. We need to know this so that we can calculate the
22190 * number of pixels the element is offset from its original position.
22191 * @method cachePosition
22192 * @param iPageX the current x position (optional, this just makes it so we
22193 * don't have to look it up again)
22194 * @param iPageY the current y position (optional, this just makes it so we
22195 * don't have to look it up again)
22197 cachePosition: function(iPageX, iPageY) {
22199 this.lastPageX = iPageX;
22200 this.lastPageY = iPageY;
22202 var aCoord = Roo.lib.Dom.getXY(this.getEl());
22203 this.lastPageX = aCoord[0];
22204 this.lastPageY = aCoord[1];
22209 * Auto-scroll the window if the dragged object has been moved beyond the
22210 * visible window boundary.
22211 * @method autoScroll
22212 * @param {int} x the drag element's x position
22213 * @param {int} y the drag element's y position
22214 * @param {int} h the height of the drag element
22215 * @param {int} w the width of the drag element
22218 autoScroll: function(x, y, h, w) {
22221 // The client height
22222 var clientH = Roo.lib.Dom.getViewWidth();
22224 // The client width
22225 var clientW = Roo.lib.Dom.getViewHeight();
22227 // The amt scrolled down
22228 var st = this.DDM.getScrollTop();
22230 // The amt scrolled right
22231 var sl = this.DDM.getScrollLeft();
22233 // Location of the bottom of the element
22236 // Location of the right of the element
22239 // The distance from the cursor to the bottom of the visible area,
22240 // adjusted so that we don't scroll if the cursor is beyond the
22241 // element drag constraints
22242 var toBot = (clientH + st - y - this.deltaY);
22244 // The distance from the cursor to the right of the visible area
22245 var toRight = (clientW + sl - x - this.deltaX);
22248 // How close to the edge the cursor must be before we scroll
22249 // var thresh = (document.all) ? 100 : 40;
22252 // How many pixels to scroll per autoscroll op. This helps to reduce
22253 // clunky scrolling. IE is more sensitive about this ... it needs this
22254 // value to be higher.
22255 var scrAmt = (document.all) ? 80 : 30;
22257 // Scroll down if we are near the bottom of the visible page and the
22258 // obj extends below the crease
22259 if ( bot > clientH && toBot < thresh ) {
22260 window.scrollTo(sl, st + scrAmt);
22263 // Scroll up if the window is scrolled down and the top of the object
22264 // goes above the top border
22265 if ( y < st && st > 0 && y - st < thresh ) {
22266 window.scrollTo(sl, st - scrAmt);
22269 // Scroll right if the obj is beyond the right border and the cursor is
22270 // near the border.
22271 if ( right > clientW && toRight < thresh ) {
22272 window.scrollTo(sl + scrAmt, st);
22275 // Scroll left if the window has been scrolled to the right and the obj
22276 // extends past the left border
22277 if ( x < sl && sl > 0 && x - sl < thresh ) {
22278 window.scrollTo(sl - scrAmt, st);
22284 * Finds the location the element should be placed if we want to move
22285 * it to where the mouse location less the click offset would place us.
22286 * @method getTargetCoord
22287 * @param {int} iPageX the X coordinate of the click
22288 * @param {int} iPageY the Y coordinate of the click
22289 * @return an object that contains the coordinates (Object.x and Object.y)
22292 getTargetCoord: function(iPageX, iPageY) {
22295 var x = iPageX - this.deltaX;
22296 var y = iPageY - this.deltaY;
22298 if (this.constrainX) {
22299 if (x < this.minX) { x = this.minX; }
22300 if (x > this.maxX) { x = this.maxX; }
22303 if (this.constrainY) {
22304 if (y < this.minY) { y = this.minY; }
22305 if (y > this.maxY) { y = this.maxY; }
22308 x = this.getTick(x, this.xTicks);
22309 y = this.getTick(y, this.yTicks);
22316 * Sets up config options specific to this class. Overrides
22317 * Roo.dd.DragDrop, but all versions of this method through the
22318 * inheritance chain are called
22320 applyConfig: function() {
22321 Roo.dd.DD.superclass.applyConfig.call(this);
22322 this.scroll = (this.config.scroll !== false);
22326 * Event that fires prior to the onMouseDown event. Overrides
22329 b4MouseDown: function(e) {
22330 // this.resetConstraints();
22331 this.autoOffset(e.getPageX(),
22336 * Event that fires prior to the onDrag event. Overrides
22339 b4Drag: function(e) {
22340 this.setDragElPos(e.getPageX(),
22344 toString: function() {
22345 return ("DD " + this.id);
22348 //////////////////////////////////////////////////////////////////////////
22349 // Debugging ygDragDrop events that can be overridden
22350 //////////////////////////////////////////////////////////////////////////
22352 startDrag: function(x, y) {
22355 onDrag: function(e) {
22358 onDragEnter: function(e, id) {
22361 onDragOver: function(e, id) {
22364 onDragOut: function(e, id) {
22367 onDragDrop: function(e, id) {
22370 endDrag: function(e) {
22377 * Ext JS Library 1.1.1
22378 * Copyright(c) 2006-2007, Ext JS, LLC.
22380 * Originally Released Under LGPL - original licence link has changed is not relivant.
22383 * <script type="text/javascript">
22387 * @class Roo.dd.DDProxy
22388 * A DragDrop implementation that inserts an empty, bordered div into
22389 * the document that follows the cursor during drag operations. At the time of
22390 * the click, the frame div is resized to the dimensions of the linked html
22391 * element, and moved to the exact location of the linked element.
22393 * References to the "frame" element refer to the single proxy element that
22394 * was created to be dragged in place of all DDProxy elements on the
22397 * @extends Roo.dd.DD
22399 * @param {String} id the id of the linked html element
22400 * @param {String} sGroup the group of related DragDrop objects
22401 * @param {object} config an object containing configurable attributes
22402 * Valid properties for DDProxy in addition to those in DragDrop:
22403 * resizeFrame, centerFrame, dragElId
22405 Roo.dd.DDProxy = function(id, sGroup, config) {
22407 this.init(id, sGroup, config);
22413 * The default drag frame div id
22414 * @property Roo.dd.DDProxy.dragElId
22418 Roo.dd.DDProxy.dragElId = "ygddfdiv";
22420 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
22423 * By default we resize the drag frame to be the same size as the element
22424 * we want to drag (this is to get the frame effect). We can turn it off
22425 * if we want a different behavior.
22426 * @property resizeFrame
22432 * By default the frame is positioned exactly where the drag element is, so
22433 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
22434 * you do not have constraints on the obj is to have the drag frame centered
22435 * around the cursor. Set centerFrame to true for this effect.
22436 * @property centerFrame
22439 centerFrame: false,
22442 * Creates the proxy element if it does not yet exist
22443 * @method createFrame
22445 createFrame: function() {
22447 var body = document.body;
22449 if (!body || !body.firstChild) {
22450 setTimeout( function() { self.createFrame(); }, 50 );
22454 var div = this.getDragEl();
22457 div = document.createElement("div");
22458 div.id = this.dragElId;
22461 s.position = "absolute";
22462 s.visibility = "hidden";
22464 s.border = "2px solid #aaa";
22467 // appendChild can blow up IE if invoked prior to the window load event
22468 // while rendering a table. It is possible there are other scenarios
22469 // that would cause this to happen as well.
22470 body.insertBefore(div, body.firstChild);
22475 * Initialization for the drag frame element. Must be called in the
22476 * constructor of all subclasses
22477 * @method initFrame
22479 initFrame: function() {
22480 this.createFrame();
22483 applyConfig: function() {
22484 Roo.dd.DDProxy.superclass.applyConfig.call(this);
22486 this.resizeFrame = (this.config.resizeFrame !== false);
22487 this.centerFrame = (this.config.centerFrame);
22488 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
22492 * Resizes the drag frame to the dimensions of the clicked object, positions
22493 * it over the object, and finally displays it
22494 * @method showFrame
22495 * @param {int} iPageX X click position
22496 * @param {int} iPageY Y click position
22499 showFrame: function(iPageX, iPageY) {
22500 var el = this.getEl();
22501 var dragEl = this.getDragEl();
22502 var s = dragEl.style;
22504 this._resizeProxy();
22506 if (this.centerFrame) {
22507 this.setDelta( Math.round(parseInt(s.width, 10)/2),
22508 Math.round(parseInt(s.height, 10)/2) );
22511 this.setDragElPos(iPageX, iPageY);
22513 Roo.fly(dragEl).show();
22517 * The proxy is automatically resized to the dimensions of the linked
22518 * element when a drag is initiated, unless resizeFrame is set to false
22519 * @method _resizeProxy
22522 _resizeProxy: function() {
22523 if (this.resizeFrame) {
22524 var el = this.getEl();
22525 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
22529 // overrides Roo.dd.DragDrop
22530 b4MouseDown: function(e) {
22531 var x = e.getPageX();
22532 var y = e.getPageY();
22533 this.autoOffset(x, y);
22534 this.setDragElPos(x, y);
22537 // overrides Roo.dd.DragDrop
22538 b4StartDrag: function(x, y) {
22539 // show the drag frame
22540 this.showFrame(x, y);
22543 // overrides Roo.dd.DragDrop
22544 b4EndDrag: function(e) {
22545 Roo.fly(this.getDragEl()).hide();
22548 // overrides Roo.dd.DragDrop
22549 // By default we try to move the element to the last location of the frame.
22550 // This is so that the default behavior mirrors that of Roo.dd.DD.
22551 endDrag: function(e) {
22553 var lel = this.getEl();
22554 var del = this.getDragEl();
22556 // Show the drag frame briefly so we can get its position
22557 del.style.visibility = "";
22560 // Hide the linked element before the move to get around a Safari
22562 lel.style.visibility = "hidden";
22563 Roo.dd.DDM.moveToEl(lel, del);
22564 del.style.visibility = "hidden";
22565 lel.style.visibility = "";
22570 beforeMove : function(){
22574 afterDrag : function(){
22578 toString: function() {
22579 return ("DDProxy " + this.id);
22585 * Ext JS Library 1.1.1
22586 * Copyright(c) 2006-2007, Ext JS, LLC.
22588 * Originally Released Under LGPL - original licence link has changed is not relivant.
22591 * <script type="text/javascript">
22595 * @class Roo.dd.DDTarget
22596 * A DragDrop implementation that does not move, but can be a drop
22597 * target. You would get the same result by simply omitting implementation
22598 * for the event callbacks, but this way we reduce the processing cost of the
22599 * event listener and the callbacks.
22600 * @extends Roo.dd.DragDrop
22602 * @param {String} id the id of the element that is a drop target
22603 * @param {String} sGroup the group of related DragDrop objects
22604 * @param {object} config an object containing configurable attributes
22605 * Valid properties for DDTarget in addition to those in
22609 Roo.dd.DDTarget = function(id, sGroup, config) {
22611 this.initTarget(id, sGroup, config);
22613 if (config && (config.listeners || config.events)) {
22614 Roo.dd.DragDrop.superclass.constructor.call(this, {
22615 listeners : config.listeners || {},
22616 events : config.events || {}
22621 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
22622 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
22623 toString: function() {
22624 return ("DDTarget " + this.id);
22629 * Ext JS Library 1.1.1
22630 * Copyright(c) 2006-2007, Ext JS, LLC.
22632 * Originally Released Under LGPL - original licence link has changed is not relivant.
22635 * <script type="text/javascript">
22640 * @class Roo.dd.ScrollManager
22641 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
22642 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
22645 Roo.dd.ScrollManager = function(){
22646 var ddm = Roo.dd.DragDropMgr;
22653 var onStop = function(e){
22658 var triggerRefresh = function(){
22659 if(ddm.dragCurrent){
22660 ddm.refreshCache(ddm.dragCurrent.groups);
22664 var doScroll = function(){
22665 if(ddm.dragCurrent){
22666 var dds = Roo.dd.ScrollManager;
22668 if(proc.el.scroll(proc.dir, dds.increment)){
22672 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
22677 var clearProc = function(){
22679 clearInterval(proc.id);
22686 var startProc = function(el, dir){
22687 Roo.log('scroll startproc');
22691 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
22694 var onFire = function(e, isDrop){
22696 if(isDrop || !ddm.dragCurrent){ return; }
22697 var dds = Roo.dd.ScrollManager;
22698 if(!dragEl || dragEl != ddm.dragCurrent){
22699 dragEl = ddm.dragCurrent;
22700 // refresh regions on drag start
22701 dds.refreshCache();
22704 var xy = Roo.lib.Event.getXY(e);
22705 var pt = new Roo.lib.Point(xy[0], xy[1]);
22706 for(var id in els){
22707 var el = els[id], r = el._region;
22708 if(r && r.contains(pt) && el.isScrollable()){
22709 if(r.bottom - pt.y <= dds.thresh){
22711 startProc(el, "down");
22714 }else if(r.right - pt.x <= dds.thresh){
22716 startProc(el, "left");
22719 }else if(pt.y - r.top <= dds.thresh){
22721 startProc(el, "up");
22724 }else if(pt.x - r.left <= dds.thresh){
22726 startProc(el, "right");
22735 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
22736 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
22740 * Registers new overflow element(s) to auto scroll
22741 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
22743 register : function(el){
22744 if(el instanceof Array){
22745 for(var i = 0, len = el.length; i < len; i++) {
22746 this.register(el[i]);
22752 Roo.dd.ScrollManager.els = els;
22756 * Unregisters overflow element(s) so they are no longer scrolled
22757 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
22759 unregister : function(el){
22760 if(el instanceof Array){
22761 for(var i = 0, len = el.length; i < len; i++) {
22762 this.unregister(el[i]);
22771 * The number of pixels from the edge of a container the pointer needs to be to
22772 * trigger scrolling (defaults to 25)
22778 * The number of pixels to scroll in each scroll increment (defaults to 50)
22784 * The frequency of scrolls in milliseconds (defaults to 500)
22790 * True to animate the scroll (defaults to true)
22796 * The animation duration in seconds -
22797 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
22803 * Manually trigger a cache refresh.
22805 refreshCache : function(){
22806 for(var id in els){
22807 if(typeof els[id] == 'object'){ // for people extending the object prototype
22808 els[id]._region = els[id].getRegion();
22815 * Ext JS Library 1.1.1
22816 * Copyright(c) 2006-2007, Ext JS, LLC.
22818 * Originally Released Under LGPL - original licence link has changed is not relivant.
22821 * <script type="text/javascript">
22826 * @class Roo.dd.Registry
22827 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
22828 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
22831 Roo.dd.Registry = function(){
22834 var autoIdSeed = 0;
22836 var getId = function(el, autogen){
22837 if(typeof el == "string"){
22841 if(!id && autogen !== false){
22842 id = "roodd-" + (++autoIdSeed);
22850 * Register a drag drop element
22851 * @param {String|HTMLElement} element The id or DOM node to register
22852 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
22853 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
22854 * knows how to interpret, plus there are some specific properties known to the Registry that should be
22855 * populated in the data object (if applicable):
22857 Value Description<br />
22858 --------- ------------------------------------------<br />
22859 handles Array of DOM nodes that trigger dragging<br />
22860 for the element being registered<br />
22861 isHandle True if the element passed in triggers<br />
22862 dragging itself, else false
22865 register : function(el, data){
22867 if(typeof el == "string"){
22868 el = document.getElementById(el);
22871 elements[getId(el)] = data;
22872 if(data.isHandle !== false){
22873 handles[data.ddel.id] = data;
22876 var hs = data.handles;
22877 for(var i = 0, len = hs.length; i < len; i++){
22878 handles[getId(hs[i])] = data;
22884 * Unregister a drag drop element
22885 * @param {String|HTMLElement} element The id or DOM node to unregister
22887 unregister : function(el){
22888 var id = getId(el, false);
22889 var data = elements[id];
22891 delete elements[id];
22893 var hs = data.handles;
22894 for(var i = 0, len = hs.length; i < len; i++){
22895 delete handles[getId(hs[i], false)];
22902 * Returns the handle registered for a DOM Node by id
22903 * @param {String|HTMLElement} id The DOM node or id to look up
22904 * @return {Object} handle The custom handle data
22906 getHandle : function(id){
22907 if(typeof id != "string"){ // must be element?
22910 return handles[id];
22914 * Returns the handle that is registered for the DOM node that is the target of the event
22915 * @param {Event} e The event
22916 * @return {Object} handle The custom handle data
22918 getHandleFromEvent : function(e){
22919 var t = Roo.lib.Event.getTarget(e);
22920 return t ? handles[t.id] : null;
22924 * Returns a custom data object that is registered for a DOM node by id
22925 * @param {String|HTMLElement} id The DOM node or id to look up
22926 * @return {Object} data The custom data
22928 getTarget : function(id){
22929 if(typeof id != "string"){ // must be element?
22932 return elements[id];
22936 * Returns a custom data object that is registered for the DOM node that is the target of the event
22937 * @param {Event} e The event
22938 * @return {Object} data The custom data
22940 getTargetFromEvent : function(e){
22941 var t = Roo.lib.Event.getTarget(e);
22942 return t ? elements[t.id] || handles[t.id] : null;
22947 * Ext JS Library 1.1.1
22948 * Copyright(c) 2006-2007, Ext JS, LLC.
22950 * Originally Released Under LGPL - original licence link has changed is not relivant.
22953 * <script type="text/javascript">
22958 * @class Roo.dd.StatusProxy
22959 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
22960 * default drag proxy used by all Roo.dd components.
22962 * @param {Object} config
22964 Roo.dd.StatusProxy = function(config){
22965 Roo.apply(this, config);
22966 this.id = this.id || Roo.id();
22967 this.el = new Roo.Layer({
22969 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
22970 {tag: "div", cls: "x-dd-drop-icon"},
22971 {tag: "div", cls: "x-dd-drag-ghost"}
22974 shadow: !config || config.shadow !== false
22976 this.ghost = Roo.get(this.el.dom.childNodes[1]);
22977 this.dropStatus = this.dropNotAllowed;
22980 Roo.dd.StatusProxy.prototype = {
22982 * @cfg {String} dropAllowed
22983 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
22985 dropAllowed : "x-dd-drop-ok",
22987 * @cfg {String} dropNotAllowed
22988 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
22990 dropNotAllowed : "x-dd-drop-nodrop",
22993 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
22994 * over the current target element.
22995 * @param {String} cssClass The css class for the new drop status indicator image
22997 setStatus : function(cssClass){
22998 cssClass = cssClass || this.dropNotAllowed;
22999 if(this.dropStatus != cssClass){
23000 this.el.replaceClass(this.dropStatus, cssClass);
23001 this.dropStatus = cssClass;
23006 * Resets the status indicator to the default dropNotAllowed value
23007 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
23009 reset : function(clearGhost){
23010 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
23011 this.dropStatus = this.dropNotAllowed;
23013 this.ghost.update("");
23018 * Updates the contents of the ghost element
23019 * @param {String} html The html that will replace the current innerHTML of the ghost element
23021 update : function(html){
23022 if(typeof html == "string"){
23023 this.ghost.update(html);
23025 this.ghost.update("");
23026 html.style.margin = "0";
23027 this.ghost.dom.appendChild(html);
23029 // ensure float = none set?? cant remember why though.
23030 var el = this.ghost.dom.firstChild;
23032 Roo.fly(el).setStyle('float', 'none');
23037 * Returns the underlying proxy {@link Roo.Layer}
23038 * @return {Roo.Layer} el
23040 getEl : function(){
23045 * Returns the ghost element
23046 * @return {Roo.Element} el
23048 getGhost : function(){
23054 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
23056 hide : function(clear){
23064 * Stops the repair animation if it's currently running
23067 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
23073 * Displays this proxy
23080 * Force the Layer to sync its shadow and shim positions to the element
23087 * Causes the proxy to return to its position of origin via an animation. Should be called after an
23088 * invalid drop operation by the item being dragged.
23089 * @param {Array} xy The XY position of the element ([x, y])
23090 * @param {Function} callback The function to call after the repair is complete
23091 * @param {Object} scope The scope in which to execute the callback
23093 repair : function(xy, callback, scope){
23094 this.callback = callback;
23095 this.scope = scope;
23096 if(xy && this.animRepair !== false){
23097 this.el.addClass("x-dd-drag-repair");
23098 this.el.hideUnders(true);
23099 this.anim = this.el.shift({
23100 duration: this.repairDuration || .5,
23104 callback: this.afterRepair,
23108 this.afterRepair();
23113 afterRepair : function(){
23115 if(typeof this.callback == "function"){
23116 this.callback.call(this.scope || this);
23118 this.callback = null;
23123 * Ext JS Library 1.1.1
23124 * Copyright(c) 2006-2007, Ext JS, LLC.
23126 * Originally Released Under LGPL - original licence link has changed is not relivant.
23129 * <script type="text/javascript">
23133 * @class Roo.dd.DragSource
23134 * @extends Roo.dd.DDProxy
23135 * A simple class that provides the basic implementation needed to make any element draggable.
23137 * @param {String/HTMLElement/Element} el The container element
23138 * @param {Object} config
23140 Roo.dd.DragSource = function(el, config){
23141 this.el = Roo.get(el);
23142 this.dragData = {};
23144 Roo.apply(this, config);
23147 this.proxy = new Roo.dd.StatusProxy();
23150 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
23151 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
23153 this.dragging = false;
23156 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
23158 * @cfg {String} dropAllowed
23159 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23161 dropAllowed : "x-dd-drop-ok",
23163 * @cfg {String} dropNotAllowed
23164 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23166 dropNotAllowed : "x-dd-drop-nodrop",
23169 * Returns the data object associated with this drag source
23170 * @return {Object} data An object containing arbitrary data
23172 getDragData : function(e){
23173 return this.dragData;
23177 onDragEnter : function(e, id){
23178 var target = Roo.dd.DragDropMgr.getDDById(id);
23179 this.cachedTarget = target;
23180 if(this.beforeDragEnter(target, e, id) !== false){
23181 if(target.isNotifyTarget){
23182 var status = target.notifyEnter(this, e, this.dragData);
23183 this.proxy.setStatus(status);
23185 this.proxy.setStatus(this.dropAllowed);
23188 if(this.afterDragEnter){
23190 * An empty function by default, but provided so that you can perform a custom action
23191 * when the dragged item enters the drop target by providing an implementation.
23192 * @param {Roo.dd.DragDrop} target The drop target
23193 * @param {Event} e The event object
23194 * @param {String} id The id of the dragged element
23195 * @method afterDragEnter
23197 this.afterDragEnter(target, e, id);
23203 * An empty function by default, but provided so that you can perform a custom action
23204 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
23205 * @param {Roo.dd.DragDrop} target The drop target
23206 * @param {Event} e The event object
23207 * @param {String} id The id of the dragged element
23208 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23210 beforeDragEnter : function(target, e, id){
23215 alignElWithMouse: function() {
23216 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
23221 onDragOver : function(e, id){
23222 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23223 if(this.beforeDragOver(target, e, id) !== false){
23224 if(target.isNotifyTarget){
23225 var status = target.notifyOver(this, e, this.dragData);
23226 this.proxy.setStatus(status);
23229 if(this.afterDragOver){
23231 * An empty function by default, but provided so that you can perform a custom action
23232 * while the dragged item is over the drop target by providing an implementation.
23233 * @param {Roo.dd.DragDrop} target The drop target
23234 * @param {Event} e The event object
23235 * @param {String} id The id of the dragged element
23236 * @method afterDragOver
23238 this.afterDragOver(target, e, id);
23244 * An empty function by default, but provided so that you can perform a custom action
23245 * while the dragged item is over the drop target and optionally cancel the onDragOver.
23246 * @param {Roo.dd.DragDrop} target The drop target
23247 * @param {Event} e The event object
23248 * @param {String} id The id of the dragged element
23249 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23251 beforeDragOver : function(target, e, id){
23256 onDragOut : function(e, id){
23257 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23258 if(this.beforeDragOut(target, e, id) !== false){
23259 if(target.isNotifyTarget){
23260 target.notifyOut(this, e, this.dragData);
23262 this.proxy.reset();
23263 if(this.afterDragOut){
23265 * An empty function by default, but provided so that you can perform a custom action
23266 * after the dragged item is dragged out of the target without dropping.
23267 * @param {Roo.dd.DragDrop} target The drop target
23268 * @param {Event} e The event object
23269 * @param {String} id The id of the dragged element
23270 * @method afterDragOut
23272 this.afterDragOut(target, e, id);
23275 this.cachedTarget = null;
23279 * An empty function by default, but provided so that you can perform a custom action before the dragged
23280 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
23281 * @param {Roo.dd.DragDrop} target The drop target
23282 * @param {Event} e The event object
23283 * @param {String} id The id of the dragged element
23284 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23286 beforeDragOut : function(target, e, id){
23291 onDragDrop : function(e, id){
23292 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23293 if(this.beforeDragDrop(target, e, id) !== false){
23294 if(target.isNotifyTarget){
23295 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
23296 this.onValidDrop(target, e, id);
23298 this.onInvalidDrop(target, e, id);
23301 this.onValidDrop(target, e, id);
23304 if(this.afterDragDrop){
23306 * An empty function by default, but provided so that you can perform a custom action
23307 * after a valid drag drop has occurred by providing an implementation.
23308 * @param {Roo.dd.DragDrop} target The drop target
23309 * @param {Event} e The event object
23310 * @param {String} id The id of the dropped element
23311 * @method afterDragDrop
23313 this.afterDragDrop(target, e, id);
23316 delete this.cachedTarget;
23320 * An empty function by default, but provided so that you can perform a custom action before the dragged
23321 * item is dropped onto the target and optionally cancel the onDragDrop.
23322 * @param {Roo.dd.DragDrop} target The drop target
23323 * @param {Event} e The event object
23324 * @param {String} id The id of the dragged element
23325 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
23327 beforeDragDrop : function(target, e, id){
23332 onValidDrop : function(target, e, id){
23334 if(this.afterValidDrop){
23336 * An empty function by default, but provided so that you can perform a custom action
23337 * after a valid drop has occurred by providing an implementation.
23338 * @param {Object} target The target DD
23339 * @param {Event} e The event object
23340 * @param {String} id The id of the dropped element
23341 * @method afterInvalidDrop
23343 this.afterValidDrop(target, e, id);
23348 getRepairXY : function(e, data){
23349 return this.el.getXY();
23353 onInvalidDrop : function(target, e, id){
23354 this.beforeInvalidDrop(target, e, id);
23355 if(this.cachedTarget){
23356 if(this.cachedTarget.isNotifyTarget){
23357 this.cachedTarget.notifyOut(this, e, this.dragData);
23359 this.cacheTarget = null;
23361 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
23363 if(this.afterInvalidDrop){
23365 * An empty function by default, but provided so that you can perform a custom action
23366 * after an invalid drop has occurred by providing an implementation.
23367 * @param {Event} e The event object
23368 * @param {String} id The id of the dropped element
23369 * @method afterInvalidDrop
23371 this.afterInvalidDrop(e, id);
23376 afterRepair : function(){
23378 this.el.highlight(this.hlColor || "c3daf9");
23380 this.dragging = false;
23384 * An empty function by default, but provided so that you can perform a custom action after an invalid
23385 * drop has occurred.
23386 * @param {Roo.dd.DragDrop} target The drop target
23387 * @param {Event} e The event object
23388 * @param {String} id The id of the dragged element
23389 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
23391 beforeInvalidDrop : function(target, e, id){
23396 handleMouseDown : function(e){
23397 if(this.dragging) {
23400 var data = this.getDragData(e);
23401 if(data && this.onBeforeDrag(data, e) !== false){
23402 this.dragData = data;
23404 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
23409 * An empty function by default, but provided so that you can perform a custom action before the initial
23410 * drag event begins and optionally cancel it.
23411 * @param {Object} data An object containing arbitrary data to be shared with drop targets
23412 * @param {Event} e The event object
23413 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23415 onBeforeDrag : function(data, e){
23420 * An empty function by default, but provided so that you can perform a custom action once the initial
23421 * drag event has begun. The drag cannot be canceled from this function.
23422 * @param {Number} x The x position of the click on the dragged object
23423 * @param {Number} y The y position of the click on the dragged object
23425 onStartDrag : Roo.emptyFn,
23427 // private - YUI override
23428 startDrag : function(x, y){
23429 this.proxy.reset();
23430 this.dragging = true;
23431 this.proxy.update("");
23432 this.onInitDrag(x, y);
23437 onInitDrag : function(x, y){
23438 var clone = this.el.dom.cloneNode(true);
23439 clone.id = Roo.id(); // prevent duplicate ids
23440 this.proxy.update(clone);
23441 this.onStartDrag(x, y);
23446 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
23447 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
23449 getProxy : function(){
23454 * Hides the drag source's {@link Roo.dd.StatusProxy}
23456 hideProxy : function(){
23458 this.proxy.reset(true);
23459 this.dragging = false;
23463 triggerCacheRefresh : function(){
23464 Roo.dd.DDM.refreshCache(this.groups);
23467 // private - override to prevent hiding
23468 b4EndDrag: function(e) {
23471 // private - override to prevent moving
23472 endDrag : function(e){
23473 this.onEndDrag(this.dragData, e);
23477 onEndDrag : function(data, e){
23480 // private - pin to cursor
23481 autoOffset : function(x, y) {
23482 this.setDelta(-12, -20);
23486 * Ext JS Library 1.1.1
23487 * Copyright(c) 2006-2007, Ext JS, LLC.
23489 * Originally Released Under LGPL - original licence link has changed is not relivant.
23492 * <script type="text/javascript">
23497 * @class Roo.dd.DropTarget
23498 * @extends Roo.dd.DDTarget
23499 * A simple class that provides the basic implementation needed to make any element a drop target that can have
23500 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
23502 * @param {String/HTMLElement/Element} el The container element
23503 * @param {Object} config
23505 Roo.dd.DropTarget = function(el, config){
23506 this.el = Roo.get(el);
23508 var listeners = false; ;
23509 if (config && config.listeners) {
23510 listeners= config.listeners;
23511 delete config.listeners;
23513 Roo.apply(this, config);
23515 if(this.containerScroll){
23516 Roo.dd.ScrollManager.register(this.el);
23520 * @scope Roo.dd.DropTarget
23525 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
23526 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
23527 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
23529 * IMPORTANT : it should set this.valid to true|false
23531 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23532 * @param {Event} e The event
23533 * @param {Object} data An object containing arbitrary data supplied by the drag source
23539 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
23540 * This method will be called on every mouse movement while the drag source is over the drop target.
23541 * This default implementation simply returns the dropAllowed config value.
23543 * IMPORTANT : it should set this.valid to true|false
23545 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23546 * @param {Event} e The event
23547 * @param {Object} data An object containing arbitrary data supplied by the drag source
23553 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
23554 * out of the target without dropping. This default implementation simply removes the CSS class specified by
23555 * overClass (if any) from the drop element.
23558 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23559 * @param {Event} e The event
23560 * @param {Object} data An object containing arbitrary data supplied by the drag source
23566 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
23567 * been dropped on it. This method has no default implementation and returns false, so you must provide an
23568 * implementation that does something to process the drop event and returns true so that the drag source's
23569 * repair action does not run.
23571 * IMPORTANT : it should set this.success
23573 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23574 * @param {Event} e The event
23575 * @param {Object} data An object containing arbitrary data supplied by the drag source
23581 Roo.dd.DropTarget.superclass.constructor.call( this,
23583 this.ddGroup || this.group,
23586 listeners : listeners || {}
23594 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
23596 * @cfg {String} overClass
23597 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
23600 * @cfg {String} ddGroup
23601 * The drag drop group to handle drop events for
23605 * @cfg {String} dropAllowed
23606 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23608 dropAllowed : "x-dd-drop-ok",
23610 * @cfg {String} dropNotAllowed
23611 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23613 dropNotAllowed : "x-dd-drop-nodrop",
23615 * @cfg {boolean} success
23616 * set this after drop listener..
23620 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
23621 * if the drop point is valid for over/enter..
23628 isNotifyTarget : true,
23633 notifyEnter : function(dd, e, data)
23636 this.fireEvent('enter', dd, e, data);
23637 if(this.overClass){
23638 this.el.addClass(this.overClass);
23640 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23641 this.valid ? this.dropAllowed : this.dropNotAllowed
23648 notifyOver : function(dd, e, data)
23651 this.fireEvent('over', dd, e, data);
23652 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23653 this.valid ? this.dropAllowed : this.dropNotAllowed
23660 notifyOut : function(dd, e, data)
23662 this.fireEvent('out', dd, e, data);
23663 if(this.overClass){
23664 this.el.removeClass(this.overClass);
23671 notifyDrop : function(dd, e, data)
23673 this.success = false;
23674 this.fireEvent('drop', dd, e, data);
23675 return this.success;
23679 * Ext JS Library 1.1.1
23680 * Copyright(c) 2006-2007, Ext JS, LLC.
23682 * Originally Released Under LGPL - original licence link has changed is not relivant.
23685 * <script type="text/javascript">
23690 * @class Roo.dd.DragZone
23691 * @extends Roo.dd.DragSource
23692 * This class provides a container DD instance that proxies for multiple child node sources.<br />
23693 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
23695 * @param {String/HTMLElement/Element} el The container element
23696 * @param {Object} config
23698 Roo.dd.DragZone = function(el, config){
23699 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
23700 if(this.containerScroll){
23701 Roo.dd.ScrollManager.register(this.el);
23705 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
23707 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
23708 * for auto scrolling during drag operations.
23711 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
23712 * method after a failed drop (defaults to "c3daf9" - light blue)
23716 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
23717 * for a valid target to drag based on the mouse down. Override this method
23718 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
23719 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
23720 * @param {EventObject} e The mouse down event
23721 * @return {Object} The dragData
23723 getDragData : function(e){
23724 return Roo.dd.Registry.getHandleFromEvent(e);
23728 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
23729 * this.dragData.ddel
23730 * @param {Number} x The x position of the click on the dragged object
23731 * @param {Number} y The y position of the click on the dragged object
23732 * @return {Boolean} true to continue the drag, false to cancel
23734 onInitDrag : function(x, y){
23735 this.proxy.update(this.dragData.ddel.cloneNode(true));
23736 this.onStartDrag(x, y);
23741 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
23743 afterRepair : function(){
23745 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
23747 this.dragging = false;
23751 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
23752 * the XY of this.dragData.ddel
23753 * @param {EventObject} e The mouse up event
23754 * @return {Array} The xy location (e.g. [100, 200])
23756 getRepairXY : function(e){
23757 return Roo.Element.fly(this.dragData.ddel).getXY();
23761 * Ext JS Library 1.1.1
23762 * Copyright(c) 2006-2007, Ext JS, LLC.
23764 * Originally Released Under LGPL - original licence link has changed is not relivant.
23767 * <script type="text/javascript">
23770 * @class Roo.dd.DropZone
23771 * @extends Roo.dd.DropTarget
23772 * This class provides a container DD instance that proxies for multiple child node targets.<br />
23773 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
23775 * @param {String/HTMLElement/Element} el The container element
23776 * @param {Object} config
23778 Roo.dd.DropZone = function(el, config){
23779 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
23782 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
23784 * Returns a custom data object associated with the DOM node that is the target of the event. By default
23785 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
23786 * provide your own custom lookup.
23787 * @param {Event} e The event
23788 * @return {Object} data The custom data
23790 getTargetFromEvent : function(e){
23791 return Roo.dd.Registry.getTargetFromEvent(e);
23795 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
23796 * that it has registered. This method has no default implementation and should be overridden to provide
23797 * node-specific processing if necessary.
23798 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23799 * {@link #getTargetFromEvent} for this node)
23800 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23801 * @param {Event} e The event
23802 * @param {Object} data An object containing arbitrary data supplied by the drag source
23804 onNodeEnter : function(n, dd, e, data){
23809 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
23810 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
23811 * overridden to provide the proper feedback.
23812 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23813 * {@link #getTargetFromEvent} for this node)
23814 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23815 * @param {Event} e The event
23816 * @param {Object} data An object containing arbitrary data supplied by the drag source
23817 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23818 * underlying {@link Roo.dd.StatusProxy} can be updated
23820 onNodeOver : function(n, dd, e, data){
23821 return this.dropAllowed;
23825 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
23826 * the drop node without dropping. This method has no default implementation and should be overridden to provide
23827 * node-specific processing if necessary.
23828 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23829 * {@link #getTargetFromEvent} for this node)
23830 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23831 * @param {Event} e The event
23832 * @param {Object} data An object containing arbitrary data supplied by the drag source
23834 onNodeOut : function(n, dd, e, data){
23839 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
23840 * the drop node. The default implementation returns false, so it should be overridden to provide the
23841 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
23842 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23843 * {@link #getTargetFromEvent} for this node)
23844 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23845 * @param {Event} e The event
23846 * @param {Object} data An object containing arbitrary data supplied by the drag source
23847 * @return {Boolean} True if the drop was valid, else false
23849 onNodeDrop : function(n, dd, e, data){
23854 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
23855 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
23856 * it should be overridden to provide the proper feedback if necessary.
23857 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23858 * @param {Event} e The event
23859 * @param {Object} data An object containing arbitrary data supplied by the drag source
23860 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23861 * underlying {@link Roo.dd.StatusProxy} can be updated
23863 onContainerOver : function(dd, e, data){
23864 return this.dropNotAllowed;
23868 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
23869 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
23870 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
23871 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
23872 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23873 * @param {Event} e The event
23874 * @param {Object} data An object containing arbitrary data supplied by the drag source
23875 * @return {Boolean} True if the drop was valid, else false
23877 onContainerDrop : function(dd, e, data){
23882 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
23883 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
23884 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
23885 * you should override this method and provide a custom implementation.
23886 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23887 * @param {Event} e The event
23888 * @param {Object} data An object containing arbitrary data supplied by the drag source
23889 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23890 * underlying {@link Roo.dd.StatusProxy} can be updated
23892 notifyEnter : function(dd, e, data){
23893 return this.dropNotAllowed;
23897 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
23898 * This method will be called on every mouse movement while the drag source is over the drop zone.
23899 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
23900 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
23901 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
23902 * registered node, it will call {@link #onContainerOver}.
23903 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23904 * @param {Event} e The event
23905 * @param {Object} data An object containing arbitrary data supplied by the drag source
23906 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23907 * underlying {@link Roo.dd.StatusProxy} can be updated
23909 notifyOver : function(dd, e, data){
23910 var n = this.getTargetFromEvent(e);
23911 if(!n){ // not over valid drop target
23912 if(this.lastOverNode){
23913 this.onNodeOut(this.lastOverNode, dd, e, data);
23914 this.lastOverNode = null;
23916 return this.onContainerOver(dd, e, data);
23918 if(this.lastOverNode != n){
23919 if(this.lastOverNode){
23920 this.onNodeOut(this.lastOverNode, dd, e, data);
23922 this.onNodeEnter(n, dd, e, data);
23923 this.lastOverNode = n;
23925 return this.onNodeOver(n, dd, e, data);
23929 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
23930 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
23931 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
23932 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23933 * @param {Event} e The event
23934 * @param {Object} data An object containing arbitrary data supplied by the drag zone
23936 notifyOut : function(dd, e, data){
23937 if(this.lastOverNode){
23938 this.onNodeOut(this.lastOverNode, dd, e, data);
23939 this.lastOverNode = null;
23944 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
23945 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
23946 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
23947 * otherwise it will call {@link #onContainerDrop}.
23948 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23949 * @param {Event} e The event
23950 * @param {Object} data An object containing arbitrary data supplied by the drag source
23951 * @return {Boolean} True if the drop was valid, else false
23953 notifyDrop : function(dd, e, data){
23954 if(this.lastOverNode){
23955 this.onNodeOut(this.lastOverNode, dd, e, data);
23956 this.lastOverNode = null;
23958 var n = this.getTargetFromEvent(e);
23960 this.onNodeDrop(n, dd, e, data) :
23961 this.onContainerDrop(dd, e, data);
23965 triggerCacheRefresh : function(){
23966 Roo.dd.DDM.refreshCache(this.groups);
23970 * Ext JS Library 1.1.1
23971 * Copyright(c) 2006-2007, Ext JS, LLC.
23973 * Originally Released Under LGPL - original licence link has changed is not relivant.
23976 * <script type="text/javascript">
23981 * @class Roo.data.SortTypes
23983 * Defines the default sorting (casting?) comparison functions used when sorting data.
23985 Roo.data.SortTypes = {
23987 * Default sort that does nothing
23988 * @param {Mixed} s The value being converted
23989 * @return {Mixed} The comparison value
23991 none : function(s){
23996 * The regular expression used to strip tags
24000 stripTagsRE : /<\/?[^>]+>/gi,
24003 * Strips all HTML tags to sort on text only
24004 * @param {Mixed} s The value being converted
24005 * @return {String} The comparison value
24007 asText : function(s){
24008 return String(s).replace(this.stripTagsRE, "");
24012 * Strips all HTML tags to sort on text only - Case insensitive
24013 * @param {Mixed} s The value being converted
24014 * @return {String} The comparison value
24016 asUCText : function(s){
24017 return String(s).toUpperCase().replace(this.stripTagsRE, "");
24021 * Case insensitive string
24022 * @param {Mixed} s The value being converted
24023 * @return {String} The comparison value
24025 asUCString : function(s) {
24026 return String(s).toUpperCase();
24031 * @param {Mixed} s The value being converted
24032 * @return {Number} The comparison value
24034 asDate : function(s) {
24038 if(s instanceof Date){
24039 return s.getTime();
24041 return Date.parse(String(s));
24046 * @param {Mixed} s The value being converted
24047 * @return {Float} The comparison value
24049 asFloat : function(s) {
24050 var val = parseFloat(String(s).replace(/,/g, ""));
24059 * @param {Mixed} s The value being converted
24060 * @return {Number} The comparison value
24062 asInt : function(s) {
24063 var val = parseInt(String(s).replace(/,/g, ""));
24071 * Ext JS Library 1.1.1
24072 * Copyright(c) 2006-2007, Ext JS, LLC.
24074 * Originally Released Under LGPL - original licence link has changed is not relivant.
24077 * <script type="text/javascript">
24081 * @class Roo.data.Record
24082 * Instances of this class encapsulate both record <em>definition</em> information, and record
24083 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
24084 * to access Records cached in an {@link Roo.data.Store} object.<br>
24086 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
24087 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
24090 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
24092 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
24093 * {@link #create}. The parameters are the same.
24094 * @param {Array} data An associative Array of data values keyed by the field name.
24095 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
24096 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
24097 * not specified an integer id is generated.
24099 Roo.data.Record = function(data, id){
24100 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
24105 * Generate a constructor for a specific record layout.
24106 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
24107 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
24108 * Each field definition object may contain the following properties: <ul>
24109 * <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,
24110 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
24111 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
24112 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
24113 * is being used, then this is a string containing the javascript expression to reference the data relative to
24114 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
24115 * to the data item relative to the record element. If the mapping expression is the same as the field name,
24116 * this may be omitted.</p></li>
24117 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
24118 * <ul><li>auto (Default, implies no conversion)</li>
24123 * <li>date</li></ul></p></li>
24124 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
24125 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
24126 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
24127 * by the Reader into an object that will be stored in the Record. It is passed the
24128 * following parameters:<ul>
24129 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
24131 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
24133 * <br>usage:<br><pre><code>
24134 var TopicRecord = Roo.data.Record.create(
24135 {name: 'title', mapping: 'topic_title'},
24136 {name: 'author', mapping: 'username'},
24137 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
24138 {name: 'lastPost', mapping: 'post_time', type: 'date'},
24139 {name: 'lastPoster', mapping: 'user2'},
24140 {name: 'excerpt', mapping: 'post_text'}
24143 var myNewRecord = new TopicRecord({
24144 title: 'Do my job please',
24147 lastPost: new Date(),
24148 lastPoster: 'Animal',
24149 excerpt: 'No way dude!'
24151 myStore.add(myNewRecord);
24156 Roo.data.Record.create = function(o){
24157 var f = function(){
24158 f.superclass.constructor.apply(this, arguments);
24160 Roo.extend(f, Roo.data.Record);
24161 var p = f.prototype;
24162 p.fields = new Roo.util.MixedCollection(false, function(field){
24165 for(var i = 0, len = o.length; i < len; i++){
24166 p.fields.add(new Roo.data.Field(o[i]));
24168 f.getField = function(name){
24169 return p.fields.get(name);
24174 Roo.data.Record.AUTO_ID = 1000;
24175 Roo.data.Record.EDIT = 'edit';
24176 Roo.data.Record.REJECT = 'reject';
24177 Roo.data.Record.COMMIT = 'commit';
24179 Roo.data.Record.prototype = {
24181 * Readonly flag - true if this record has been modified.
24190 join : function(store){
24191 this.store = store;
24195 * Set the named field to the specified value.
24196 * @param {String} name The name of the field to set.
24197 * @param {Object} value The value to set the field to.
24199 set : function(name, value){
24200 if(this.data[name] == value){
24204 if(!this.modified){
24205 this.modified = {};
24207 if(typeof this.modified[name] == 'undefined'){
24208 this.modified[name] = this.data[name];
24210 this.data[name] = value;
24211 if(!this.editing && this.store){
24212 this.store.afterEdit(this);
24217 * Get the value of the named field.
24218 * @param {String} name The name of the field to get the value of.
24219 * @return {Object} The value of the field.
24221 get : function(name){
24222 return this.data[name];
24226 beginEdit : function(){
24227 this.editing = true;
24228 this.modified = {};
24232 cancelEdit : function(){
24233 this.editing = false;
24234 delete this.modified;
24238 endEdit : function(){
24239 this.editing = false;
24240 if(this.dirty && this.store){
24241 this.store.afterEdit(this);
24246 * Usually called by the {@link Roo.data.Store} which owns the Record.
24247 * Rejects all changes made to the Record since either creation, or the last commit operation.
24248 * Modified fields are reverted to their original values.
24250 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24251 * of reject operations.
24253 reject : function(){
24254 var m = this.modified;
24256 if(typeof m[n] != "function"){
24257 this.data[n] = m[n];
24260 this.dirty = false;
24261 delete this.modified;
24262 this.editing = false;
24264 this.store.afterReject(this);
24269 * Usually called by the {@link Roo.data.Store} which owns the Record.
24270 * Commits all changes made to the Record since either creation, or the last commit operation.
24272 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
24273 * of commit operations.
24275 commit : function(){
24276 this.dirty = false;
24277 delete this.modified;
24278 this.editing = false;
24280 this.store.afterCommit(this);
24285 hasError : function(){
24286 return this.error != null;
24290 clearError : function(){
24295 * Creates a copy of this record.
24296 * @param {String} id (optional) A new record id if you don't want to use this record's id
24299 copy : function(newId) {
24300 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
24304 * Ext JS Library 1.1.1
24305 * Copyright(c) 2006-2007, Ext JS, LLC.
24307 * Originally Released Under LGPL - original licence link has changed is not relivant.
24310 * <script type="text/javascript">
24316 * @class Roo.data.Store
24317 * @extends Roo.util.Observable
24318 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
24319 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
24321 * 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
24322 * has no knowledge of the format of the data returned by the Proxy.<br>
24324 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
24325 * instances from the data object. These records are cached and made available through accessor functions.
24327 * Creates a new Store.
24328 * @param {Object} config A config object containing the objects needed for the Store to access data,
24329 * and read the data into Records.
24331 Roo.data.Store = function(config){
24332 this.data = new Roo.util.MixedCollection(false);
24333 this.data.getKey = function(o){
24336 this.baseParams = {};
24338 this.paramNames = {
24343 "multisort" : "_multisort"
24346 if(config && config.data){
24347 this.inlineData = config.data;
24348 delete config.data;
24351 Roo.apply(this, config);
24353 if(this.reader){ // reader passed
24354 this.reader = Roo.factory(this.reader, Roo.data);
24355 this.reader.xmodule = this.xmodule || false;
24356 if(!this.recordType){
24357 this.recordType = this.reader.recordType;
24359 if(this.reader.onMetaChange){
24360 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
24364 if(this.recordType){
24365 this.fields = this.recordType.prototype.fields;
24367 this.modified = [];
24371 * @event datachanged
24372 * Fires when the data cache has changed, and a widget which is using this Store
24373 * as a Record cache should refresh its view.
24374 * @param {Store} this
24376 datachanged : true,
24378 * @event metachange
24379 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
24380 * @param {Store} this
24381 * @param {Object} meta The JSON metadata
24386 * Fires when Records have been added to the Store
24387 * @param {Store} this
24388 * @param {Roo.data.Record[]} records The array of Records added
24389 * @param {Number} index The index at which the record(s) were added
24394 * Fires when a Record has been removed from the Store
24395 * @param {Store} this
24396 * @param {Roo.data.Record} record The Record that was removed
24397 * @param {Number} index The index at which the record was removed
24402 * Fires when a Record has been updated
24403 * @param {Store} this
24404 * @param {Roo.data.Record} record The Record that was updated
24405 * @param {String} operation The update operation being performed. Value may be one of:
24407 Roo.data.Record.EDIT
24408 Roo.data.Record.REJECT
24409 Roo.data.Record.COMMIT
24415 * Fires when the data cache has been cleared.
24416 * @param {Store} this
24420 * @event beforeload
24421 * Fires before a request is made for a new data object. If the beforeload handler returns false
24422 * the load action will be canceled.
24423 * @param {Store} this
24424 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24428 * @event beforeloadadd
24429 * Fires after a new set of Records has been loaded.
24430 * @param {Store} this
24431 * @param {Roo.data.Record[]} records The Records that were loaded
24432 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24434 beforeloadadd : true,
24437 * Fires after a new set of Records has been loaded, before they are added to the store.
24438 * @param {Store} this
24439 * @param {Roo.data.Record[]} records The Records that were loaded
24440 * @param {Object} options The loading options that were specified (see {@link #load} for details)
24441 * @params {Object} return from reader
24445 * @event loadexception
24446 * Fires if an exception occurs in the Proxy during loading.
24447 * Called with the signature of the Proxy's "loadexception" event.
24448 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
24451 * @param {Object} return from JsonData.reader() - success, totalRecords, records
24452 * @param {Object} load options
24453 * @param {Object} jsonData from your request (normally this contains the Exception)
24455 loadexception : true
24459 this.proxy = Roo.factory(this.proxy, Roo.data);
24460 this.proxy.xmodule = this.xmodule || false;
24461 this.relayEvents(this.proxy, ["loadexception"]);
24463 this.sortToggle = {};
24464 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
24466 Roo.data.Store.superclass.constructor.call(this);
24468 if(this.inlineData){
24469 this.loadData(this.inlineData);
24470 delete this.inlineData;
24474 Roo.extend(Roo.data.Store, Roo.util.Observable, {
24476 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
24477 * without a remote query - used by combo/forms at present.
24481 * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
24484 * @cfg {Array} data Inline data to be loaded when the store is initialized.
24487 * @cfg {Roo.data.DataReader} reader [required] The Reader object which processes the data object and returns
24488 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
24491 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
24492 * on any HTTP request
24495 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
24498 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
24502 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
24503 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
24505 remoteSort : false,
24508 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
24509 * loaded or when a record is removed. (defaults to false).
24511 pruneModifiedRecords : false,
24514 lastOptions : null,
24517 * Add Records to the Store and fires the add event.
24518 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
24520 add : function(records){
24521 records = [].concat(records);
24522 for(var i = 0, len = records.length; i < len; i++){
24523 records[i].join(this);
24525 var index = this.data.length;
24526 this.data.addAll(records);
24527 this.fireEvent("add", this, records, index);
24531 * Remove a Record from the Store and fires the remove event.
24532 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
24534 remove : function(record){
24535 var index = this.data.indexOf(record);
24536 this.data.removeAt(index);
24538 if(this.pruneModifiedRecords){
24539 this.modified.remove(record);
24541 this.fireEvent("remove", this, record, index);
24545 * Remove all Records from the Store and fires the clear event.
24547 removeAll : function(){
24549 if(this.pruneModifiedRecords){
24550 this.modified = [];
24552 this.fireEvent("clear", this);
24556 * Inserts Records to the Store at the given index and fires the add event.
24557 * @param {Number} index The start index at which to insert the passed Records.
24558 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
24560 insert : function(index, records){
24561 records = [].concat(records);
24562 for(var i = 0, len = records.length; i < len; i++){
24563 this.data.insert(index, records[i]);
24564 records[i].join(this);
24566 this.fireEvent("add", this, records, index);
24570 * Get the index within the cache of the passed Record.
24571 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
24572 * @return {Number} The index of the passed Record. Returns -1 if not found.
24574 indexOf : function(record){
24575 return this.data.indexOf(record);
24579 * Get the index within the cache of the Record with the passed id.
24580 * @param {String} id The id of the Record to find.
24581 * @return {Number} The index of the Record. Returns -1 if not found.
24583 indexOfId : function(id){
24584 return this.data.indexOfKey(id);
24588 * Get the Record with the specified id.
24589 * @param {String} id The id of the Record to find.
24590 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
24592 getById : function(id){
24593 return this.data.key(id);
24597 * Get the Record at the specified index.
24598 * @param {Number} index The index of the Record to find.
24599 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
24601 getAt : function(index){
24602 return this.data.itemAt(index);
24606 * Returns a range of Records between specified indices.
24607 * @param {Number} startIndex (optional) The starting index (defaults to 0)
24608 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
24609 * @return {Roo.data.Record[]} An array of Records
24611 getRange : function(start, end){
24612 return this.data.getRange(start, end);
24616 storeOptions : function(o){
24617 o = Roo.apply({}, o);
24620 this.lastOptions = o;
24624 * Loads the Record cache from the configured Proxy using the configured Reader.
24626 * If using remote paging, then the first load call must specify the <em>start</em>
24627 * and <em>limit</em> properties in the options.params property to establish the initial
24628 * position within the dataset, and the number of Records to cache on each read from the Proxy.
24630 * <strong>It is important to note that for remote data sources, loading is asynchronous,
24631 * and this call will return before the new data has been loaded. Perform any post-processing
24632 * in a callback function, or in a "load" event handler.</strong>
24634 * @param {Object} options An object containing properties which control loading options:<ul>
24635 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
24636 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
24637 * passed the following arguments:<ul>
24638 * <li>r : Roo.data.Record[]</li>
24639 * <li>options: Options object from the load call</li>
24640 * <li>success: Boolean success indicator</li></ul></li>
24641 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
24642 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
24645 load : function(options){
24646 options = options || {};
24647 if(this.fireEvent("beforeload", this, options) !== false){
24648 this.storeOptions(options);
24649 var p = Roo.apply(options.params || {}, this.baseParams);
24650 // if meta was not loaded from remote source.. try requesting it.
24651 if (!this.reader.metaFromRemote) {
24652 p._requestMeta = 1;
24654 if(this.sortInfo && this.remoteSort){
24655 var pn = this.paramNames;
24656 p[pn["sort"]] = this.sortInfo.field;
24657 p[pn["dir"]] = this.sortInfo.direction;
24659 if (this.multiSort) {
24660 var pn = this.paramNames;
24661 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
24664 this.proxy.load(p, this.reader, this.loadRecords, this, options);
24669 * Reloads the Record cache from the configured Proxy using the configured Reader and
24670 * the options from the last load operation performed.
24671 * @param {Object} options (optional) An object containing properties which may override the options
24672 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
24673 * the most recently used options are reused).
24675 reload : function(options){
24676 this.load(Roo.applyIf(options||{}, this.lastOptions));
24680 // Called as a callback by the Reader during a load operation.
24681 loadRecords : function(o, options, success){
24684 if(success !== false){
24685 this.fireEvent("load", this, [], options, o);
24687 if(options.callback){
24688 options.callback.call(options.scope || this, [], options, false);
24692 // if data returned failure - throw an exception.
24693 if (o.success === false) {
24694 // show a message if no listener is registered.
24695 if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
24696 Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
24698 // loadmask wil be hooked into this..
24699 this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
24702 var r = o.records, t = o.totalRecords || r.length;
24704 this.fireEvent("beforeloadadd", this, r, options, o);
24706 if(!options || options.add !== true){
24707 if(this.pruneModifiedRecords){
24708 this.modified = [];
24710 for(var i = 0, len = r.length; i < len; i++){
24714 this.data = this.snapshot;
24715 delete this.snapshot;
24718 this.data.addAll(r);
24719 this.totalLength = t;
24721 this.fireEvent("datachanged", this);
24723 this.totalLength = Math.max(t, this.data.length+r.length);
24727 if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
24729 var e = new Roo.data.Record({});
24731 e.set(this.parent.displayField, this.parent.emptyTitle);
24732 e.set(this.parent.valueField, '');
24737 this.fireEvent("load", this, r, options, o);
24738 if(options.callback){
24739 options.callback.call(options.scope || this, r, options, true);
24745 * Loads data from a passed data block. A Reader which understands the format of the data
24746 * must have been configured in the constructor.
24747 * @param {Object} data The data block from which to read the Records. The format of the data expected
24748 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
24749 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
24751 loadData : function(o, append){
24752 var r = this.reader.readRecords(o);
24753 this.loadRecords(r, {add: append}, true);
24757 * using 'cn' the nested child reader read the child array into it's child stores.
24758 * @param {Object} rec The record with a 'children array
24760 loadDataFromChildren : function(rec)
24762 this.loadData(this.reader.toLoadData(rec));
24767 * Gets the number of cached records.
24769 * <em>If using paging, this may not be the total size of the dataset. If the data object
24770 * used by the Reader contains the dataset size, then the getTotalCount() function returns
24771 * the data set size</em>
24773 getCount : function(){
24774 return this.data.length || 0;
24778 * Gets the total number of records in the dataset as returned by the server.
24780 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
24781 * the dataset size</em>
24783 getTotalCount : function(){
24784 return this.totalLength || 0;
24788 * Returns the sort state of the Store as an object with two properties:
24790 field {String} The name of the field by which the Records are sorted
24791 direction {String} The sort order, "ASC" or "DESC"
24794 getSortState : function(){
24795 return this.sortInfo;
24799 applySort : function(){
24800 if(this.sortInfo && !this.remoteSort){
24801 var s = this.sortInfo, f = s.field;
24802 var st = this.fields.get(f).sortType;
24803 var fn = function(r1, r2){
24804 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
24805 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
24807 this.data.sort(s.direction, fn);
24808 if(this.snapshot && this.snapshot != this.data){
24809 this.snapshot.sort(s.direction, fn);
24815 * Sets the default sort column and order to be used by the next load operation.
24816 * @param {String} fieldName The name of the field to sort by.
24817 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
24819 setDefaultSort : function(field, dir){
24820 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
24824 * Sort the Records.
24825 * If remote sorting is used, the sort is performed on the server, and the cache is
24826 * reloaded. If local sorting is used, the cache is sorted internally.
24827 * @param {String} fieldName The name of the field to sort by.
24828 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
24830 sort : function(fieldName, dir){
24831 var f = this.fields.get(fieldName);
24833 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
24835 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
24836 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
24841 this.sortToggle[f.name] = dir;
24842 this.sortInfo = {field: f.name, direction: dir};
24843 if(!this.remoteSort){
24845 this.fireEvent("datachanged", this);
24847 this.load(this.lastOptions);
24852 * Calls the specified function for each of the Records in the cache.
24853 * @param {Function} fn The function to call. The Record is passed as the first parameter.
24854 * Returning <em>false</em> aborts and exits the iteration.
24855 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
24857 each : function(fn, scope){
24858 this.data.each(fn, scope);
24862 * Gets all records modified since the last commit. Modified records are persisted across load operations
24863 * (e.g., during paging).
24864 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
24866 getModifiedRecords : function(){
24867 return this.modified;
24871 createFilterFn : function(property, value, anyMatch){
24872 if(!value.exec){ // not a regex
24873 value = String(value);
24874 if(value.length == 0){
24877 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
24879 return function(r){
24880 return value.test(r.data[property]);
24885 * Sums the value of <i>property</i> for each record between start and end and returns the result.
24886 * @param {String} property A field on your records
24887 * @param {Number} start The record index to start at (defaults to 0)
24888 * @param {Number} end The last record index to include (defaults to length - 1)
24889 * @return {Number} The sum
24891 sum : function(property, start, end){
24892 var rs = this.data.items, v = 0;
24893 start = start || 0;
24894 end = (end || end === 0) ? end : rs.length-1;
24896 for(var i = start; i <= end; i++){
24897 v += (rs[i].data[property] || 0);
24903 * Filter the records by a specified property.
24904 * @param {String} field A field on your records
24905 * @param {String/RegExp} value Either a string that the field
24906 * should start with or a RegExp to test against the field
24907 * @param {Boolean} anyMatch True to match any part not just the beginning
24909 filter : function(property, value, anyMatch){
24910 var fn = this.createFilterFn(property, value, anyMatch);
24911 return fn ? this.filterBy(fn) : this.clearFilter();
24915 * Filter by a function. The specified function will be called with each
24916 * record in this data source. If the function returns true the record is included,
24917 * otherwise it is filtered.
24918 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
24919 * @param {Object} scope (optional) The scope of the function (defaults to this)
24921 filterBy : function(fn, scope){
24922 this.snapshot = this.snapshot || this.data;
24923 this.data = this.queryBy(fn, scope||this);
24924 this.fireEvent("datachanged", this);
24928 * Query the records by a specified property.
24929 * @param {String} field A field on your records
24930 * @param {String/RegExp} value Either a string that the field
24931 * should start with or a RegExp to test against the field
24932 * @param {Boolean} anyMatch True to match any part not just the beginning
24933 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
24935 query : function(property, value, anyMatch){
24936 var fn = this.createFilterFn(property, value, anyMatch);
24937 return fn ? this.queryBy(fn) : this.data.clone();
24941 * Query by a function. The specified function will be called with each
24942 * record in this data source. If the function returns true the record is included
24944 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
24945 * @param {Object} scope (optional) The scope of the function (defaults to this)
24946 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
24948 queryBy : function(fn, scope){
24949 var data = this.snapshot || this.data;
24950 return data.filterBy(fn, scope||this);
24954 * Collects unique values for a particular dataIndex from this store.
24955 * @param {String} dataIndex The property to collect
24956 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
24957 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
24958 * @return {Array} An array of the unique values
24960 collect : function(dataIndex, allowNull, bypassFilter){
24961 var d = (bypassFilter === true && this.snapshot) ?
24962 this.snapshot.items : this.data.items;
24963 var v, sv, r = [], l = {};
24964 for(var i = 0, len = d.length; i < len; i++){
24965 v = d[i].data[dataIndex];
24967 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
24976 * Revert to a view of the Record cache with no filtering applied.
24977 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
24979 clearFilter : function(suppressEvent){
24980 if(this.snapshot && this.snapshot != this.data){
24981 this.data = this.snapshot;
24982 delete this.snapshot;
24983 if(suppressEvent !== true){
24984 this.fireEvent("datachanged", this);
24990 afterEdit : function(record){
24991 if(this.modified.indexOf(record) == -1){
24992 this.modified.push(record);
24994 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
24998 afterReject : function(record){
24999 this.modified.remove(record);
25000 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
25004 afterCommit : function(record){
25005 this.modified.remove(record);
25006 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
25010 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
25011 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
25013 commitChanges : function(){
25014 var m = this.modified.slice(0);
25015 this.modified = [];
25016 for(var i = 0, len = m.length; i < len; i++){
25022 * Cancel outstanding changes on all changed records.
25024 rejectChanges : function(){
25025 var m = this.modified.slice(0);
25026 this.modified = [];
25027 for(var i = 0, len = m.length; i < len; i++){
25032 onMetaChange : function(meta, rtype, o){
25033 this.recordType = rtype;
25034 this.fields = rtype.prototype.fields;
25035 delete this.snapshot;
25036 this.sortInfo = meta.sortInfo || this.sortInfo;
25037 this.modified = [];
25038 this.fireEvent('metachange', this, this.reader.meta);
25041 moveIndex : function(data, type)
25043 var index = this.indexOf(data);
25045 var newIndex = index + type;
25049 this.insert(newIndex, data);
25054 * Ext JS Library 1.1.1
25055 * Copyright(c) 2006-2007, Ext JS, LLC.
25057 * Originally Released Under LGPL - original licence link has changed is not relivant.
25060 * <script type="text/javascript">
25064 * @class Roo.data.SimpleStore
25065 * @extends Roo.data.Store
25066 * Small helper class to make creating Stores from Array data easier.
25067 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
25068 * @cfg {Array} fields An array of field definition objects, or field name strings.
25069 * @cfg {Object} an existing reader (eg. copied from another store)
25070 * @cfg {Array} data The multi-dimensional array of data
25071 * @cfg {Roo.data.DataProxy} proxy [not-required]
25072 * @cfg {Roo.data.Reader} reader [not-required]
25074 * @param {Object} config
25076 Roo.data.SimpleStore = function(config)
25078 Roo.data.SimpleStore.superclass.constructor.call(this, {
25080 reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
25083 Roo.data.Record.create(config.fields)
25085 proxy : new Roo.data.MemoryProxy(config.data)
25089 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
25091 * Ext JS Library 1.1.1
25092 * Copyright(c) 2006-2007, Ext JS, LLC.
25094 * Originally Released Under LGPL - original licence link has changed is not relivant.
25097 * <script type="text/javascript">
25102 * @extends Roo.data.Store
25103 * @class Roo.data.JsonStore
25104 * Small helper class to make creating Stores for JSON data easier. <br/>
25106 var store = new Roo.data.JsonStore({
25107 url: 'get-images.php',
25109 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
25112 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
25113 * JsonReader and HttpProxy (unless inline data is provided).</b>
25114 * @cfg {Array} fields An array of field definition objects, or field name strings.
25116 * @param {Object} config
25118 Roo.data.JsonStore = function(c){
25119 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
25120 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
25121 reader: new Roo.data.JsonReader(c, c.fields)
25124 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
25126 * Ext JS Library 1.1.1
25127 * Copyright(c) 2006-2007, Ext JS, LLC.
25129 * Originally Released Under LGPL - original licence link has changed is not relivant.
25132 * <script type="text/javascript">
25136 Roo.data.Field = function(config){
25137 if(typeof config == "string"){
25138 config = {name: config};
25140 Roo.apply(this, config);
25143 this.type = "auto";
25146 var st = Roo.data.SortTypes;
25147 // named sortTypes are supported, here we look them up
25148 if(typeof this.sortType == "string"){
25149 this.sortType = st[this.sortType];
25152 // set default sortType for strings and dates
25153 if(!this.sortType){
25156 this.sortType = st.asUCString;
25159 this.sortType = st.asDate;
25162 this.sortType = st.none;
25167 var stripRe = /[\$,%]/g;
25169 // prebuilt conversion function for this field, instead of
25170 // switching every time we're reading a value
25172 var cv, dateFormat = this.dateFormat;
25177 cv = function(v){ return v; };
25180 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
25184 return v !== undefined && v !== null && v !== '' ?
25185 parseInt(String(v).replace(stripRe, ""), 10) : '';
25190 return v !== undefined && v !== null && v !== '' ?
25191 parseFloat(String(v).replace(stripRe, ""), 10) : '';
25196 cv = function(v){ return v === true || v === "true" || v == 1; };
25203 if(v instanceof Date){
25207 if(dateFormat == "timestamp"){
25208 return new Date(v*1000);
25210 return Date.parseDate(v, dateFormat);
25212 var parsed = Date.parse(v);
25213 return parsed ? new Date(parsed) : null;
25222 Roo.data.Field.prototype = {
25230 * Ext JS Library 1.1.1
25231 * Copyright(c) 2006-2007, Ext JS, LLC.
25233 * Originally Released Under LGPL - original licence link has changed is not relivant.
25236 * <script type="text/javascript">
25239 // Base class for reading structured data from a data source. This class is intended to be
25240 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
25243 * @class Roo.data.DataReader
25245 * Base class for reading structured data from a data source. This class is intended to be
25246 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
25249 Roo.data.DataReader = function(meta, recordType){
25253 this.recordType = recordType instanceof Array ?
25254 Roo.data.Record.create(recordType) : recordType;
25257 Roo.data.DataReader.prototype = {
25260 readerType : 'Data',
25262 * Create an empty record
25263 * @param {Object} data (optional) - overlay some values
25264 * @return {Roo.data.Record} record created.
25266 newRow : function(d) {
25268 this.recordType.prototype.fields.each(function(c) {
25270 case 'int' : da[c.name] = 0; break;
25271 case 'date' : da[c.name] = new Date(); break;
25272 case 'float' : da[c.name] = 0.0; break;
25273 case 'boolean' : da[c.name] = false; break;
25274 default : da[c.name] = ""; break;
25278 return new this.recordType(Roo.apply(da, d));
25284 * Ext JS Library 1.1.1
25285 * Copyright(c) 2006-2007, Ext JS, LLC.
25287 * Originally Released Under LGPL - original licence link has changed is not relivant.
25290 * <script type="text/javascript">
25294 * @class Roo.data.DataProxy
25295 * @extends Roo.util.Observable
25297 * This class is an abstract base class for implementations which provide retrieval of
25298 * unformatted data objects.<br>
25300 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
25301 * (of the appropriate type which knows how to parse the data object) to provide a block of
25302 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
25304 * Custom implementations must implement the load method as described in
25305 * {@link Roo.data.HttpProxy#load}.
25307 Roo.data.DataProxy = function(){
25310 * @event beforeload
25311 * Fires before a network request is made to retrieve a data object.
25312 * @param {Object} This DataProxy object.
25313 * @param {Object} params The params parameter to the load function.
25318 * Fires before the load method's callback is called.
25319 * @param {Object} This DataProxy object.
25320 * @param {Object} o The data object.
25321 * @param {Object} arg The callback argument object passed to the load function.
25325 * @event loadexception
25326 * Fires if an Exception occurs during data retrieval.
25327 * @param {Object} This DataProxy object.
25328 * @param {Object} o The data object.
25329 * @param {Object} arg The callback argument object passed to the load function.
25330 * @param {Object} e The Exception.
25332 loadexception : true
25334 Roo.data.DataProxy.superclass.constructor.call(this);
25337 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
25340 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
25344 * Ext JS Library 1.1.1
25345 * Copyright(c) 2006-2007, Ext JS, LLC.
25347 * Originally Released Under LGPL - original licence link has changed is not relivant.
25350 * <script type="text/javascript">
25353 * @class Roo.data.MemoryProxy
25354 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
25355 * to the Reader when its load method is called.
25357 * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
25359 Roo.data.MemoryProxy = function(data){
25363 Roo.data.MemoryProxy.superclass.constructor.call(this);
25367 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
25370 * Load data from the requested source (in this case an in-memory
25371 * data object passed to the constructor), read the data object into
25372 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
25373 * process that block using the passed callback.
25374 * @param {Object} params This parameter is not used by the MemoryProxy class.
25375 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25376 * object into a block of Roo.data.Records.
25377 * @param {Function} callback The function into which to pass the block of Roo.data.records.
25378 * The function must be passed <ul>
25379 * <li>The Record block object</li>
25380 * <li>The "arg" argument from the load function</li>
25381 * <li>A boolean success indicator</li>
25383 * @param {Object} scope The scope in which to call the callback
25384 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25386 load : function(params, reader, callback, scope, arg){
25387 params = params || {};
25390 result = reader.readRecords(params.data ? params.data :this.data);
25392 this.fireEvent("loadexception", this, arg, null, e);
25393 callback.call(scope, null, arg, false);
25396 callback.call(scope, result, arg, true);
25400 update : function(params, records){
25405 * Ext JS Library 1.1.1
25406 * Copyright(c) 2006-2007, Ext JS, LLC.
25408 * Originally Released Under LGPL - original licence link has changed is not relivant.
25411 * <script type="text/javascript">
25414 * @class Roo.data.HttpProxy
25415 * @extends Roo.data.DataProxy
25416 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
25417 * configured to reference a certain URL.<br><br>
25419 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
25420 * from which the running page was served.<br><br>
25422 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
25424 * Be aware that to enable the browser to parse an XML document, the server must set
25425 * the Content-Type header in the HTTP response to "text/xml".
25427 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
25428 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
25429 * will be used to make the request.
25431 Roo.data.HttpProxy = function(conn){
25432 Roo.data.HttpProxy.superclass.constructor.call(this);
25433 // is conn a conn config or a real conn?
25435 this.useAjax = !conn || !conn.events;
25439 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
25440 // thse are take from connection...
25443 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
25446 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
25447 * extra parameters to each request made by this object. (defaults to undefined)
25450 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
25451 * to each request made by this object. (defaults to undefined)
25454 * @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)
25457 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
25460 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
25466 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
25470 * Return the {@link Roo.data.Connection} object being used by this Proxy.
25471 * @return {Connection} The Connection object. This object may be used to subscribe to events on
25472 * a finer-grained basis than the DataProxy events.
25474 getConnection : function(){
25475 return this.useAjax ? Roo.Ajax : this.conn;
25479 * Load data from the configured {@link Roo.data.Connection}, read the data object into
25480 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
25481 * process that block using the passed callback.
25482 * @param {Object} params An object containing properties which are to be used as HTTP parameters
25483 * for the request to the remote server.
25484 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25485 * object into a block of Roo.data.Records.
25486 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
25487 * The function must be passed <ul>
25488 * <li>The Record block object</li>
25489 * <li>The "arg" argument from the load function</li>
25490 * <li>A boolean success indicator</li>
25492 * @param {Object} scope The scope in which to call the callback
25493 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25495 load : function(params, reader, callback, scope, arg){
25496 if(this.fireEvent("beforeload", this, params) !== false){
25498 params : params || {},
25500 callback : callback,
25505 callback : this.loadResponse,
25509 Roo.applyIf(o, this.conn);
25510 if(this.activeRequest){
25511 Roo.Ajax.abort(this.activeRequest);
25513 this.activeRequest = Roo.Ajax.request(o);
25515 this.conn.request(o);
25518 callback.call(scope||this, null, arg, false);
25523 loadResponse : function(o, success, response){
25524 delete this.activeRequest;
25526 this.fireEvent("loadexception", this, o, response);
25527 o.request.callback.call(o.request.scope, null, o.request.arg, false);
25532 result = o.reader.read(response);
25535 o.raw = { errorMsg : response.responseText };
25536 this.fireEvent("loadexception", this, o, response, e);
25537 o.request.callback.call(o.request.scope, o, o.request.arg, false);
25541 this.fireEvent("load", this, o, o.request.arg);
25542 o.request.callback.call(o.request.scope, result, o.request.arg, true);
25546 update : function(dataSet){
25551 updateResponse : function(dataSet){
25556 * Ext JS Library 1.1.1
25557 * Copyright(c) 2006-2007, Ext JS, LLC.
25559 * Originally Released Under LGPL - original licence link has changed is not relivant.
25562 * <script type="text/javascript">
25566 * @class Roo.data.ScriptTagProxy
25567 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
25568 * other than the originating domain of the running page.<br><br>
25570 * <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
25571 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
25573 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
25574 * source code that is used as the source inside a <script> tag.<br><br>
25576 * In order for the browser to process the returned data, the server must wrap the data object
25577 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
25578 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
25579 * depending on whether the callback name was passed:
25582 boolean scriptTag = false;
25583 String cb = request.getParameter("callback");
25586 response.setContentType("text/javascript");
25588 response.setContentType("application/x-json");
25590 Writer out = response.getWriter();
25592 out.write(cb + "(");
25594 out.print(dataBlock.toJsonString());
25601 * @param {Object} config A configuration object.
25603 Roo.data.ScriptTagProxy = function(config){
25604 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
25605 Roo.apply(this, config);
25606 this.head = document.getElementsByTagName("head")[0];
25609 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
25611 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
25613 * @cfg {String} url The URL from which to request the data object.
25616 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
25620 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
25621 * the server the name of the callback function set up by the load call to process the returned data object.
25622 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
25623 * javascript output which calls this named function passing the data object as its only parameter.
25625 callbackParam : "callback",
25627 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
25628 * name to the request.
25633 * Load data from the configured URL, read the data object into
25634 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
25635 * process that block using the passed callback.
25636 * @param {Object} params An object containing properties which are to be used as HTTP parameters
25637 * for the request to the remote server.
25638 * @param {Roo.data.DataReader} reader The Reader object which converts the data
25639 * object into a block of Roo.data.Records.
25640 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
25641 * The function must be passed <ul>
25642 * <li>The Record block object</li>
25643 * <li>The "arg" argument from the load function</li>
25644 * <li>A boolean success indicator</li>
25646 * @param {Object} scope The scope in which to call the callback
25647 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
25649 load : function(params, reader, callback, scope, arg){
25650 if(this.fireEvent("beforeload", this, params) !== false){
25652 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
25654 var url = this.url;
25655 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
25657 url += "&_dc=" + (new Date().getTime());
25659 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
25662 cb : "stcCallback"+transId,
25663 scriptId : "stcScript"+transId,
25667 callback : callback,
25673 window[trans.cb] = function(o){
25674 conn.handleResponse(o, trans);
25677 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
25679 if(this.autoAbort !== false){
25683 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
25685 var script = document.createElement("script");
25686 script.setAttribute("src", url);
25687 script.setAttribute("type", "text/javascript");
25688 script.setAttribute("id", trans.scriptId);
25689 this.head.appendChild(script);
25691 this.trans = trans;
25693 callback.call(scope||this, null, arg, false);
25698 isLoading : function(){
25699 return this.trans ? true : false;
25703 * Abort the current server request.
25705 abort : function(){
25706 if(this.isLoading()){
25707 this.destroyTrans(this.trans);
25712 destroyTrans : function(trans, isLoaded){
25713 this.head.removeChild(document.getElementById(trans.scriptId));
25714 clearTimeout(trans.timeoutId);
25716 window[trans.cb] = undefined;
25718 delete window[trans.cb];
25721 // if hasn't been loaded, wait for load to remove it to prevent script error
25722 window[trans.cb] = function(){
25723 window[trans.cb] = undefined;
25725 delete window[trans.cb];
25732 handleResponse : function(o, trans){
25733 this.trans = false;
25734 this.destroyTrans(trans, true);
25737 result = trans.reader.readRecords(o);
25739 this.fireEvent("loadexception", this, o, trans.arg, e);
25740 trans.callback.call(trans.scope||window, null, trans.arg, false);
25743 this.fireEvent("load", this, o, trans.arg);
25744 trans.callback.call(trans.scope||window, result, trans.arg, true);
25748 handleFailure : function(trans){
25749 this.trans = false;
25750 this.destroyTrans(trans, false);
25751 this.fireEvent("loadexception", this, null, trans.arg);
25752 trans.callback.call(trans.scope||window, null, trans.arg, false);
25756 * Ext JS Library 1.1.1
25757 * Copyright(c) 2006-2007, Ext JS, LLC.
25759 * Originally Released Under LGPL - original licence link has changed is not relivant.
25762 * <script type="text/javascript">
25766 * @class Roo.data.JsonReader
25767 * @extends Roo.data.DataReader
25768 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
25769 * based on mappings in a provided Roo.data.Record constructor.
25771 * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
25772 * in the reply previously.
25777 var RecordDef = Roo.data.Record.create([
25778 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
25779 {name: 'occupation'} // This field will use "occupation" as the mapping.
25781 var myReader = new Roo.data.JsonReader({
25782 totalProperty: "results", // The property which contains the total dataset size (optional)
25783 root: "rows", // The property which contains an Array of row objects
25784 id: "id" // The property within each row object that provides an ID for the record (optional)
25788 * This would consume a JSON file like this:
25790 { 'results': 2, 'rows': [
25791 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
25792 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
25795 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
25796 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
25797 * paged from the remote server.
25798 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
25799 * @cfg {String} root name of the property which contains the Array of row objects.
25800 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
25801 * @cfg {Array} fields Array of field definition objects
25803 * Create a new JsonReader
25804 * @param {Object} meta Metadata configuration options
25805 * @param {Object} recordType Either an Array of field definition objects,
25806 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
25808 Roo.data.JsonReader = function(meta, recordType){
25811 // set some defaults:
25812 Roo.applyIf(meta, {
25813 totalProperty: 'total',
25814 successProperty : 'success',
25819 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
25821 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
25823 readerType : 'Json',
25826 * @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
25827 * Used by Store query builder to append _requestMeta to params.
25830 metaFromRemote : false,
25832 * This method is only used by a DataProxy which has retrieved data from a remote server.
25833 * @param {Object} response The XHR object which contains the JSON data in its responseText.
25834 * @return {Object} data A data block which is used by an Roo.data.Store object as
25835 * a cache of Roo.data.Records.
25837 read : function(response){
25838 var json = response.responseText;
25840 var o = /* eval:var:o */ eval("("+json+")");
25842 throw {message: "JsonReader.read: Json object not found"};
25848 this.metaFromRemote = true;
25849 this.meta = o.metaData;
25850 this.recordType = Roo.data.Record.create(o.metaData.fields);
25851 this.onMetaChange(this.meta, this.recordType, o);
25853 return this.readRecords(o);
25856 // private function a store will implement
25857 onMetaChange : function(meta, recordType, o){
25864 simpleAccess: function(obj, subsc) {
25871 getJsonAccessor: function(){
25873 return function(expr) {
25875 return(re.test(expr))
25876 ? new Function("obj", "return obj." + expr)
25881 return Roo.emptyFn;
25886 * Create a data block containing Roo.data.Records from an XML document.
25887 * @param {Object} o An object which contains an Array of row objects in the property specified
25888 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
25889 * which contains the total size of the dataset.
25890 * @return {Object} data A data block which is used by an Roo.data.Store object as
25891 * a cache of Roo.data.Records.
25893 readRecords : function(o){
25895 * After any data loads, the raw JSON data is available for further custom processing.
25899 var s = this.meta, Record = this.recordType,
25900 f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
25902 // Generate extraction functions for the totalProperty, the root, the id, and for each field
25904 if(s.totalProperty) {
25905 this.getTotal = this.getJsonAccessor(s.totalProperty);
25907 if(s.successProperty) {
25908 this.getSuccess = this.getJsonAccessor(s.successProperty);
25910 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
25912 var g = this.getJsonAccessor(s.id);
25913 this.getId = function(rec) {
25915 return (r === undefined || r === "") ? null : r;
25918 this.getId = function(){return null;};
25921 for(var jj = 0; jj < fl; jj++){
25923 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
25924 this.ef[jj] = this.getJsonAccessor(map);
25928 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
25929 if(s.totalProperty){
25930 var vt = parseInt(this.getTotal(o), 10);
25935 if(s.successProperty){
25936 var vs = this.getSuccess(o);
25937 if(vs === false || vs === 'false'){
25942 for(var i = 0; i < c; i++){
25945 var id = this.getId(n);
25946 for(var j = 0; j < fl; j++){
25948 var v = this.ef[j](n);
25950 Roo.log('missing convert for ' + f.name);
25954 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
25958 raw : { errorMsg : "JSON Reader Error: fields or metadata not available to create Record" },
25964 var record = new Record(values, id);
25966 records[i] = record;
25972 totalRecords : totalRecords
25975 // used when loading children.. @see loadDataFromChildren
25976 toLoadData: function(rec)
25978 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
25979 var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
25980 return { data : data, total : data.length };
25985 * Ext JS Library 1.1.1
25986 * Copyright(c) 2006-2007, Ext JS, LLC.
25988 * Originally Released Under LGPL - original licence link has changed is not relivant.
25991 * <script type="text/javascript">
25995 * @class Roo.data.XmlReader
25996 * @extends Roo.data.DataReader
25997 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
25998 * based on mappings in a provided Roo.data.Record constructor.<br><br>
26000 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
26001 * header in the HTTP response must be set to "text/xml".</em>
26005 var RecordDef = Roo.data.Record.create([
26006 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
26007 {name: 'occupation'} // This field will use "occupation" as the mapping.
26009 var myReader = new Roo.data.XmlReader({
26010 totalRecords: "results", // The element which contains the total dataset size (optional)
26011 record: "row", // The repeated element which contains row information
26012 id: "id" // The element within the row that provides an ID for the record (optional)
26016 * This would consume an XML file like this:
26020 <results>2</results>
26023 <name>Bill</name>
26024 <occupation>Gardener</occupation>
26028 <name>Ben</name>
26029 <occupation>Horticulturalist</occupation>
26033 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
26034 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
26035 * paged from the remote server.
26036 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
26037 * @cfg {String} success The DomQuery path to the success attribute used by forms.
26038 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
26039 * a record identifier value.
26041 * Create a new XmlReader
26042 * @param {Object} meta Metadata configuration options
26043 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
26044 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
26045 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
26047 Roo.data.XmlReader = function(meta, recordType){
26049 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26051 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
26053 readerType : 'Xml',
26056 * This method is only used by a DataProxy which has retrieved data from a remote server.
26057 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
26058 * to contain a method called 'responseXML' that returns an XML document object.
26059 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
26060 * a cache of Roo.data.Records.
26062 read : function(response){
26063 var doc = response.responseXML;
26065 throw {message: "XmlReader.read: XML Document not available"};
26067 return this.readRecords(doc);
26071 * Create a data block containing Roo.data.Records from an XML document.
26072 * @param {Object} doc A parsed XML document.
26073 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
26074 * a cache of Roo.data.Records.
26076 readRecords : function(doc){
26078 * After any data loads/reads, the raw XML Document is available for further custom processing.
26079 * @type XMLDocument
26081 this.xmlData = doc;
26082 var root = doc.documentElement || doc;
26083 var q = Roo.DomQuery;
26084 var recordType = this.recordType, fields = recordType.prototype.fields;
26085 var sid = this.meta.id;
26086 var totalRecords = 0, success = true;
26087 if(this.meta.totalRecords){
26088 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
26091 if(this.meta.success){
26092 var sv = q.selectValue(this.meta.success, root, true);
26093 success = sv !== false && sv !== 'false';
26096 var ns = q.select(this.meta.record, root);
26097 for(var i = 0, len = ns.length; i < len; i++) {
26100 var id = sid ? q.selectValue(sid, n) : undefined;
26101 for(var j = 0, jlen = fields.length; j < jlen; j++){
26102 var f = fields.items[j];
26103 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
26105 values[f.name] = v;
26107 var record = new recordType(values, id);
26109 records[records.length] = record;
26115 totalRecords : totalRecords || records.length
26120 * Ext JS Library 1.1.1
26121 * Copyright(c) 2006-2007, Ext JS, LLC.
26123 * Originally Released Under LGPL - original licence link has changed is not relivant.
26126 * <script type="text/javascript">
26130 * @class Roo.data.ArrayReader
26131 * @extends Roo.data.DataReader
26132 * Data reader class to create an Array of Roo.data.Record objects from an Array.
26133 * Each element of that Array represents a row of data fields. The
26134 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
26135 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
26139 var RecordDef = Roo.data.Record.create([
26140 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
26141 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
26143 var myReader = new Roo.data.ArrayReader({
26144 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
26148 * This would consume an Array like this:
26150 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
26154 * Create a new JsonReader
26155 * @param {Object} meta Metadata configuration options.
26156 * @param {Object|Array} recordType Either an Array of field definition objects
26158 * @cfg {Array} fields Array of field definition objects
26159 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
26160 * as specified to {@link Roo.data.Record#create},
26161 * or an {@link Roo.data.Record} object
26164 * created using {@link Roo.data.Record#create}.
26166 Roo.data.ArrayReader = function(meta, recordType)
26168 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
26171 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
26174 * Create a data block containing Roo.data.Records from an XML document.
26175 * @param {Object} o An Array of row objects which represents the dataset.
26176 * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
26177 * a cache of Roo.data.Records.
26179 readRecords : function(o)
26181 var sid = this.meta ? this.meta.id : null;
26182 var recordType = this.recordType, fields = recordType.prototype.fields;
26185 for(var i = 0; i < root.length; i++){
26188 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
26189 for(var j = 0, jlen = fields.length; j < jlen; j++){
26190 var f = fields.items[j];
26191 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
26192 var v = n[k] !== undefined ? n[k] : f.defaultValue;
26194 values[f.name] = v;
26196 var record = new recordType(values, id);
26198 records[records.length] = record;
26202 totalRecords : records.length
26205 // used when loading children.. @see loadDataFromChildren
26206 toLoadData: function(rec)
26208 // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
26209 return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
26216 * Ext JS Library 1.1.1
26217 * Copyright(c) 2006-2007, Ext JS, LLC.
26219 * Originally Released Under LGPL - original licence link has changed is not relivant.
26222 * <script type="text/javascript">
26227 * @class Roo.data.Tree
26228 * @extends Roo.util.Observable
26229 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
26230 * in the tree have most standard DOM functionality.
26232 * @param {Node} root (optional) The root node
26234 Roo.data.Tree = function(root){
26235 this.nodeHash = {};
26237 * The root node for this tree
26242 this.setRootNode(root);
26247 * Fires when a new child node is appended to a node in this tree.
26248 * @param {Tree} tree The owner tree
26249 * @param {Node} parent The parent node
26250 * @param {Node} node The newly appended node
26251 * @param {Number} index The index of the newly appended node
26256 * Fires when a child node is removed from a node in this tree.
26257 * @param {Tree} tree The owner tree
26258 * @param {Node} parent The parent node
26259 * @param {Node} node The child node removed
26264 * Fires when a node is moved to a new location in the tree
26265 * @param {Tree} tree The owner tree
26266 * @param {Node} node The node moved
26267 * @param {Node} oldParent The old parent of this node
26268 * @param {Node} newParent The new parent of this node
26269 * @param {Number} index The index it was moved to
26274 * Fires when a new child node is inserted in a node in this tree.
26275 * @param {Tree} tree The owner tree
26276 * @param {Node} parent The parent node
26277 * @param {Node} node The child node inserted
26278 * @param {Node} refNode The child node the node was inserted before
26282 * @event beforeappend
26283 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
26284 * @param {Tree} tree The owner tree
26285 * @param {Node} parent The parent node
26286 * @param {Node} node The child node to be appended
26288 "beforeappend" : true,
26290 * @event beforeremove
26291 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
26292 * @param {Tree} tree The owner tree
26293 * @param {Node} parent The parent node
26294 * @param {Node} node The child node to be removed
26296 "beforeremove" : true,
26298 * @event beforemove
26299 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
26300 * @param {Tree} tree The owner tree
26301 * @param {Node} node The node being moved
26302 * @param {Node} oldParent The parent of the node
26303 * @param {Node} newParent The new parent the node is moving to
26304 * @param {Number} index The index it is being moved to
26306 "beforemove" : true,
26308 * @event beforeinsert
26309 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
26310 * @param {Tree} tree The owner tree
26311 * @param {Node} parent The parent node
26312 * @param {Node} node The child node to be inserted
26313 * @param {Node} refNode The child node the node is being inserted before
26315 "beforeinsert" : true
26318 Roo.data.Tree.superclass.constructor.call(this);
26321 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
26322 pathSeparator: "/",
26324 proxyNodeEvent : function(){
26325 return this.fireEvent.apply(this, arguments);
26329 * Returns the root node for this tree.
26332 getRootNode : function(){
26337 * Sets the root node for this tree.
26338 * @param {Node} node
26341 setRootNode : function(node){
26343 node.ownerTree = this;
26344 node.isRoot = true;
26345 this.registerNode(node);
26350 * Gets a node in this tree by its id.
26351 * @param {String} id
26354 getNodeById : function(id){
26355 return this.nodeHash[id];
26358 registerNode : function(node){
26359 this.nodeHash[node.id] = node;
26362 unregisterNode : function(node){
26363 delete this.nodeHash[node.id];
26366 toString : function(){
26367 return "[Tree"+(this.id?" "+this.id:"")+"]";
26372 * @class Roo.data.Node
26373 * @extends Roo.util.Observable
26374 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
26375 * @cfg {String} id The id for this node. If one is not specified, one is generated.
26377 * @param {Object} attributes The attributes/config for the node
26379 Roo.data.Node = function(attributes){
26381 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
26384 this.attributes = attributes || {};
26385 this.leaf = this.attributes.leaf;
26387 * The node id. @type String
26389 this.id = this.attributes.id;
26391 this.id = Roo.id(null, "ynode-");
26392 this.attributes.id = this.id;
26397 * All child nodes of this node. @type Array
26399 this.childNodes = [];
26400 if(!this.childNodes.indexOf){ // indexOf is a must
26401 this.childNodes.indexOf = function(o){
26402 for(var i = 0, len = this.length; i < len; i++){
26411 * The parent node for this node. @type Node
26413 this.parentNode = null;
26415 * The first direct child node of this node, or null if this node has no child nodes. @type Node
26417 this.firstChild = null;
26419 * The last direct child node of this node, or null if this node has no child nodes. @type Node
26421 this.lastChild = null;
26423 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
26425 this.previousSibling = null;
26427 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
26429 this.nextSibling = null;
26434 * Fires when a new child node is appended
26435 * @param {Tree} tree The owner tree
26436 * @param {Node} this This node
26437 * @param {Node} node The newly appended node
26438 * @param {Number} index The index of the newly appended node
26443 * Fires when a child node is removed
26444 * @param {Tree} tree The owner tree
26445 * @param {Node} this This node
26446 * @param {Node} node The removed node
26451 * Fires when this node is moved to a new location in the tree
26452 * @param {Tree} tree The owner tree
26453 * @param {Node} this This node
26454 * @param {Node} oldParent The old parent of this node
26455 * @param {Node} newParent The new parent of this node
26456 * @param {Number} index The index it was moved to
26461 * Fires when a new child node is inserted.
26462 * @param {Tree} tree The owner tree
26463 * @param {Node} this This node
26464 * @param {Node} node The child node inserted
26465 * @param {Node} refNode The child node the node was inserted before
26469 * @event beforeappend
26470 * Fires before a new child is appended, return false to cancel the append.
26471 * @param {Tree} tree The owner tree
26472 * @param {Node} this This node
26473 * @param {Node} node The child node to be appended
26475 "beforeappend" : true,
26477 * @event beforeremove
26478 * Fires before a child is removed, return false to cancel the remove.
26479 * @param {Tree} tree The owner tree
26480 * @param {Node} this This node
26481 * @param {Node} node The child node to be removed
26483 "beforeremove" : true,
26485 * @event beforemove
26486 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
26487 * @param {Tree} tree The owner tree
26488 * @param {Node} this This node
26489 * @param {Node} oldParent The parent of this node
26490 * @param {Node} newParent The new parent this node is moving to
26491 * @param {Number} index The index it is being moved to
26493 "beforemove" : true,
26495 * @event beforeinsert
26496 * Fires before a new child is inserted, return false to cancel the insert.
26497 * @param {Tree} tree The owner tree
26498 * @param {Node} this This node
26499 * @param {Node} node The child node to be inserted
26500 * @param {Node} refNode The child node the node is being inserted before
26502 "beforeinsert" : true
26504 this.listeners = this.attributes.listeners;
26505 Roo.data.Node.superclass.constructor.call(this);
26508 Roo.extend(Roo.data.Node, Roo.util.Observable, {
26509 fireEvent : function(evtName){
26510 // first do standard event for this node
26511 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
26514 // then bubble it up to the tree if the event wasn't cancelled
26515 var ot = this.getOwnerTree();
26517 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
26525 * Returns true if this node is a leaf
26526 * @return {Boolean}
26528 isLeaf : function(){
26529 return this.leaf === true;
26533 setFirstChild : function(node){
26534 this.firstChild = node;
26538 setLastChild : function(node){
26539 this.lastChild = node;
26544 * Returns true if this node is the last child of its parent
26545 * @return {Boolean}
26547 isLast : function(){
26548 return (!this.parentNode ? true : this.parentNode.lastChild == this);
26552 * Returns true if this node is the first child of its parent
26553 * @return {Boolean}
26555 isFirst : function(){
26556 return (!this.parentNode ? true : this.parentNode.firstChild == this);
26559 hasChildNodes : function(){
26560 return !this.isLeaf() && this.childNodes.length > 0;
26564 * Insert node(s) as the last child node of this node.
26565 * @param {Node/Array} node The node or Array of nodes to append
26566 * @return {Node} The appended node if single append, or null if an array was passed
26568 appendChild : function(node){
26570 if(node instanceof Array){
26572 }else if(arguments.length > 1){
26576 // if passed an array or multiple args do them one by one
26578 for(var i = 0, len = multi.length; i < len; i++) {
26579 this.appendChild(multi[i]);
26582 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
26585 var index = this.childNodes.length;
26586 var oldParent = node.parentNode;
26587 // it's a move, make sure we move it cleanly
26589 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
26592 oldParent.removeChild(node);
26595 index = this.childNodes.length;
26597 this.setFirstChild(node);
26599 this.childNodes.push(node);
26600 node.parentNode = this;
26601 var ps = this.childNodes[index-1];
26603 node.previousSibling = ps;
26604 ps.nextSibling = node;
26606 node.previousSibling = null;
26608 node.nextSibling = null;
26609 this.setLastChild(node);
26610 node.setOwnerTree(this.getOwnerTree());
26611 this.fireEvent("append", this.ownerTree, this, node, index);
26612 if(this.ownerTree) {
26613 this.ownerTree.fireEvent("appendnode", this, node, index);
26616 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
26623 * Removes a child node from this node.
26624 * @param {Node} node The node to remove
26625 * @return {Node} The removed node
26627 removeChild : function(node){
26628 var index = this.childNodes.indexOf(node);
26632 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
26636 // remove it from childNodes collection
26637 this.childNodes.splice(index, 1);
26640 if(node.previousSibling){
26641 node.previousSibling.nextSibling = node.nextSibling;
26643 if(node.nextSibling){
26644 node.nextSibling.previousSibling = node.previousSibling;
26647 // update child refs
26648 if(this.firstChild == node){
26649 this.setFirstChild(node.nextSibling);
26651 if(this.lastChild == node){
26652 this.setLastChild(node.previousSibling);
26655 node.setOwnerTree(null);
26656 // clear any references from the node
26657 node.parentNode = null;
26658 node.previousSibling = null;
26659 node.nextSibling = null;
26660 this.fireEvent("remove", this.ownerTree, this, node);
26665 * Inserts the first node before the second node in this nodes childNodes collection.
26666 * @param {Node} node The node to insert
26667 * @param {Node} refNode The node to insert before (if null the node is appended)
26668 * @return {Node} The inserted node
26670 insertBefore : function(node, refNode){
26671 if(!refNode){ // like standard Dom, refNode can be null for append
26672 return this.appendChild(node);
26675 if(node == refNode){
26679 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
26682 var index = this.childNodes.indexOf(refNode);
26683 var oldParent = node.parentNode;
26684 var refIndex = index;
26686 // when moving internally, indexes will change after remove
26687 if(oldParent == this && this.childNodes.indexOf(node) < index){
26691 // it's a move, make sure we move it cleanly
26693 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
26696 oldParent.removeChild(node);
26699 this.setFirstChild(node);
26701 this.childNodes.splice(refIndex, 0, node);
26702 node.parentNode = this;
26703 var ps = this.childNodes[refIndex-1];
26705 node.previousSibling = ps;
26706 ps.nextSibling = node;
26708 node.previousSibling = null;
26710 node.nextSibling = refNode;
26711 refNode.previousSibling = node;
26712 node.setOwnerTree(this.getOwnerTree());
26713 this.fireEvent("insert", this.ownerTree, this, node, refNode);
26715 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
26721 * Returns the child node at the specified index.
26722 * @param {Number} index
26725 item : function(index){
26726 return this.childNodes[index];
26730 * Replaces one child node in this node with another.
26731 * @param {Node} newChild The replacement node
26732 * @param {Node} oldChild The node to replace
26733 * @return {Node} The replaced node
26735 replaceChild : function(newChild, oldChild){
26736 this.insertBefore(newChild, oldChild);
26737 this.removeChild(oldChild);
26742 * Returns the index of a child node
26743 * @param {Node} node
26744 * @return {Number} The index of the node or -1 if it was not found
26746 indexOf : function(child){
26747 return this.childNodes.indexOf(child);
26751 * Returns the tree this node is in.
26754 getOwnerTree : function(){
26755 // if it doesn't have one, look for one
26756 if(!this.ownerTree){
26760 this.ownerTree = p.ownerTree;
26766 return this.ownerTree;
26770 * Returns depth of this node (the root node has a depth of 0)
26773 getDepth : function(){
26776 while(p.parentNode){
26784 setOwnerTree : function(tree){
26785 // if it's move, we need to update everyone
26786 if(tree != this.ownerTree){
26787 if(this.ownerTree){
26788 this.ownerTree.unregisterNode(this);
26790 this.ownerTree = tree;
26791 var cs = this.childNodes;
26792 for(var i = 0, len = cs.length; i < len; i++) {
26793 cs[i].setOwnerTree(tree);
26796 tree.registerNode(this);
26802 * Returns the path for this node. The path can be used to expand or select this node programmatically.
26803 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
26804 * @return {String} The path
26806 getPath : function(attr){
26807 attr = attr || "id";
26808 var p = this.parentNode;
26809 var b = [this.attributes[attr]];
26811 b.unshift(p.attributes[attr]);
26814 var sep = this.getOwnerTree().pathSeparator;
26815 return sep + b.join(sep);
26819 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
26820 * function call will be the scope provided or the current node. The arguments to the function
26821 * will be the args provided or the current node. If the function returns false at any point,
26822 * the bubble is stopped.
26823 * @param {Function} fn The function to call
26824 * @param {Object} scope (optional) The scope of the function (defaults to current node)
26825 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
26827 bubble : function(fn, scope, args){
26830 if(fn.call(scope || p, args || p) === false){
26838 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
26839 * function call will be the scope provided or the current node. The arguments to the function
26840 * will be the args provided or the current node. If the function returns false at any point,
26841 * the cascade is stopped on that branch.
26842 * @param {Function} fn The function to call
26843 * @param {Object} scope (optional) The scope of the function (defaults to current node)
26844 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
26846 cascade : function(fn, scope, args){
26847 if(fn.call(scope || this, args || this) !== false){
26848 var cs = this.childNodes;
26849 for(var i = 0, len = cs.length; i < len; i++) {
26850 cs[i].cascade(fn, scope, args);
26856 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
26857 * function call will be the scope provided or the current node. The arguments to the function
26858 * will be the args provided or the current node. If the function returns false at any point,
26859 * the iteration stops.
26860 * @param {Function} fn The function to call
26861 * @param {Object} scope (optional) The scope of the function (defaults to current node)
26862 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
26864 eachChild : function(fn, scope, args){
26865 var cs = this.childNodes;
26866 for(var i = 0, len = cs.length; i < len; i++) {
26867 if(fn.call(scope || this, args || cs[i]) === false){
26874 * Finds the first child that has the attribute with the specified value.
26875 * @param {String} attribute The attribute name
26876 * @param {Mixed} value The value to search for
26877 * @return {Node} The found child or null if none was found
26879 findChild : function(attribute, value){
26880 var cs = this.childNodes;
26881 for(var i = 0, len = cs.length; i < len; i++) {
26882 if(cs[i].attributes[attribute] == value){
26890 * Finds the first child by a custom function. The child matches if the function passed
26892 * @param {Function} fn
26893 * @param {Object} scope (optional)
26894 * @return {Node} The found child or null if none was found
26896 findChildBy : function(fn, scope){
26897 var cs = this.childNodes;
26898 for(var i = 0, len = cs.length; i < len; i++) {
26899 if(fn.call(scope||cs[i], cs[i]) === true){
26907 * Sorts this nodes children using the supplied sort function
26908 * @param {Function} fn
26909 * @param {Object} scope (optional)
26911 sort : function(fn, scope){
26912 var cs = this.childNodes;
26913 var len = cs.length;
26915 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
26917 for(var i = 0; i < len; i++){
26919 n.previousSibling = cs[i-1];
26920 n.nextSibling = cs[i+1];
26922 this.setFirstChild(n);
26925 this.setLastChild(n);
26932 * Returns true if this node is an ancestor (at any point) of the passed node.
26933 * @param {Node} node
26934 * @return {Boolean}
26936 contains : function(node){
26937 return node.isAncestor(this);
26941 * Returns true if the passed node is an ancestor (at any point) of this node.
26942 * @param {Node} node
26943 * @return {Boolean}
26945 isAncestor : function(node){
26946 var p = this.parentNode;
26956 toString : function(){
26957 return "[Node"+(this.id?" "+this.id:"")+"]";
26961 * Ext JS Library 1.1.1
26962 * Copyright(c) 2006-2007, Ext JS, LLC.
26964 * Originally Released Under LGPL - original licence link has changed is not relivant.
26967 * <script type="text/javascript">
26972 * @class Roo.Shadow
26973 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
26974 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
26975 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
26977 * Create a new Shadow
26978 * @param {Object} config The config object
26980 Roo.Shadow = function(config){
26981 Roo.apply(this, config);
26982 if(typeof this.mode != "string"){
26983 this.mode = this.defaultMode;
26985 var o = this.offset, a = {h: 0};
26986 var rad = Math.floor(this.offset/2);
26987 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
26993 a.l -= this.offset + rad;
26994 a.t -= this.offset + rad;
27005 a.l -= (this.offset - rad);
27006 a.t -= this.offset + rad;
27008 a.w -= (this.offset - rad)*2;
27019 a.l -= (this.offset - rad);
27020 a.t -= (this.offset - rad);
27022 a.w -= (this.offset + rad + 1);
27023 a.h -= (this.offset + rad);
27032 Roo.Shadow.prototype = {
27034 * @cfg {String} mode
27035 * The shadow display mode. Supports the following options:<br />
27036 * sides: Shadow displays on both sides and bottom only<br />
27037 * frame: Shadow displays equally on all four sides<br />
27038 * drop: Traditional bottom-right drop shadow (default)
27042 * @cfg {String} offset
27043 * The number of pixels to offset the shadow from the element (defaults to 4)
27048 defaultMode: "drop",
27051 * Displays the shadow under the target element
27052 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
27054 show : function(target){
27055 target = Roo.get(target);
27057 this.el = Roo.Shadow.Pool.pull();
27058 if(this.el.dom.nextSibling != target.dom){
27059 this.el.insertBefore(target);
27062 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
27064 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
27067 target.getLeft(true),
27068 target.getTop(true),
27072 this.el.dom.style.display = "block";
27076 * Returns true if the shadow is visible, else false
27078 isVisible : function(){
27079 return this.el ? true : false;
27083 * Direct alignment when values are already available. Show must be called at least once before
27084 * calling this method to ensure it is initialized.
27085 * @param {Number} left The target element left position
27086 * @param {Number} top The target element top position
27087 * @param {Number} width The target element width
27088 * @param {Number} height The target element height
27090 realign : function(l, t, w, h){
27094 var a = this.adjusts, d = this.el.dom, s = d.style;
27096 s.left = (l+a.l)+"px";
27097 s.top = (t+a.t)+"px";
27098 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
27100 if(s.width != sws || s.height != shs){
27104 var cn = d.childNodes;
27105 var sww = Math.max(0, (sw-12))+"px";
27106 cn[0].childNodes[1].style.width = sww;
27107 cn[1].childNodes[1].style.width = sww;
27108 cn[2].childNodes[1].style.width = sww;
27109 cn[1].style.height = Math.max(0, (sh-12))+"px";
27115 * Hides this shadow
27119 this.el.dom.style.display = "none";
27120 Roo.Shadow.Pool.push(this.el);
27126 * Adjust the z-index of this shadow
27127 * @param {Number} zindex The new z-index
27129 setZIndex : function(z){
27132 this.el.setStyle("z-index", z);
27137 // Private utility class that manages the internal Shadow cache
27138 Roo.Shadow.Pool = function(){
27140 var markup = Roo.isIE ?
27141 '<div class="x-ie-shadow"></div>' :
27142 '<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>';
27145 var sh = p.shift();
27147 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
27148 sh.autoBoxAdjust = false;
27153 push : function(sh){
27159 * Ext JS Library 1.1.1
27160 * Copyright(c) 2006-2007, Ext JS, LLC.
27162 * Originally Released Under LGPL - original licence link has changed is not relivant.
27165 * <script type="text/javascript">
27170 * @class Roo.SplitBar
27171 * @extends Roo.util.Observable
27172 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
27176 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
27177 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
27178 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
27179 split.minSize = 100;
27180 split.maxSize = 600;
27181 split.animate = true;
27182 split.on('moved', splitterMoved);
27185 * Create a new SplitBar
27186 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
27187 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
27188 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27189 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
27190 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
27191 position of the SplitBar).
27193 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
27196 this.el = Roo.get(dragElement, true);
27197 this.el.dom.unselectable = "on";
27199 this.resizingEl = Roo.get(resizingElement, true);
27203 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
27204 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
27207 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
27210 * The minimum size of the resizing element. (Defaults to 0)
27216 * The maximum size of the resizing element. (Defaults to 2000)
27219 this.maxSize = 2000;
27222 * Whether to animate the transition to the new size
27225 this.animate = false;
27228 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
27231 this.useShim = false;
27236 if(!existingProxy){
27238 this.proxy = Roo.SplitBar.createProxy(this.orientation);
27240 this.proxy = Roo.get(existingProxy).dom;
27243 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
27246 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
27249 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
27252 this.dragSpecs = {};
27255 * @private The adapter to use to positon and resize elements
27257 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
27258 this.adapter.init(this);
27260 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27262 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
27263 this.el.addClass("x-splitbar-h");
27266 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
27267 this.el.addClass("x-splitbar-v");
27273 * Fires when the splitter is moved (alias for {@link #event-moved})
27274 * @param {Roo.SplitBar} this
27275 * @param {Number} newSize the new width or height
27280 * Fires when the splitter is moved
27281 * @param {Roo.SplitBar} this
27282 * @param {Number} newSize the new width or height
27286 * @event beforeresize
27287 * Fires before the splitter is dragged
27288 * @param {Roo.SplitBar} this
27290 "beforeresize" : true,
27292 "beforeapply" : true
27295 Roo.util.Observable.call(this);
27298 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
27299 onStartProxyDrag : function(x, y){
27300 this.fireEvent("beforeresize", this);
27302 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
27304 o.enableDisplayMode("block");
27305 // all splitbars share the same overlay
27306 Roo.SplitBar.prototype.overlay = o;
27308 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
27309 this.overlay.show();
27310 Roo.get(this.proxy).setDisplayed("block");
27311 var size = this.adapter.getElementSize(this);
27312 this.activeMinSize = this.getMinimumSize();;
27313 this.activeMaxSize = this.getMaximumSize();;
27314 var c1 = size - this.activeMinSize;
27315 var c2 = Math.max(this.activeMaxSize - size, 0);
27316 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27317 this.dd.resetConstraints();
27318 this.dd.setXConstraint(
27319 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
27320 this.placement == Roo.SplitBar.LEFT ? c2 : c1
27322 this.dd.setYConstraint(0, 0);
27324 this.dd.resetConstraints();
27325 this.dd.setXConstraint(0, 0);
27326 this.dd.setYConstraint(
27327 this.placement == Roo.SplitBar.TOP ? c1 : c2,
27328 this.placement == Roo.SplitBar.TOP ? c2 : c1
27331 this.dragSpecs.startSize = size;
27332 this.dragSpecs.startPoint = [x, y];
27333 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
27337 * @private Called after the drag operation by the DDProxy
27339 onEndProxyDrag : function(e){
27340 Roo.get(this.proxy).setDisplayed(false);
27341 var endPoint = Roo.lib.Event.getXY(e);
27343 this.overlay.hide();
27346 if(this.orientation == Roo.SplitBar.HORIZONTAL){
27347 newSize = this.dragSpecs.startSize +
27348 (this.placement == Roo.SplitBar.LEFT ?
27349 endPoint[0] - this.dragSpecs.startPoint[0] :
27350 this.dragSpecs.startPoint[0] - endPoint[0]
27353 newSize = this.dragSpecs.startSize +
27354 (this.placement == Roo.SplitBar.TOP ?
27355 endPoint[1] - this.dragSpecs.startPoint[1] :
27356 this.dragSpecs.startPoint[1] - endPoint[1]
27359 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
27360 if(newSize != this.dragSpecs.startSize){
27361 if(this.fireEvent('beforeapply', this, newSize) !== false){
27362 this.adapter.setElementSize(this, newSize);
27363 this.fireEvent("moved", this, newSize);
27364 this.fireEvent("resize", this, newSize);
27370 * Get the adapter this SplitBar uses
27371 * @return The adapter object
27373 getAdapter : function(){
27374 return this.adapter;
27378 * Set the adapter this SplitBar uses
27379 * @param {Object} adapter A SplitBar adapter object
27381 setAdapter : function(adapter){
27382 this.adapter = adapter;
27383 this.adapter.init(this);
27387 * Gets the minimum size for the resizing element
27388 * @return {Number} The minimum size
27390 getMinimumSize : function(){
27391 return this.minSize;
27395 * Sets the minimum size for the resizing element
27396 * @param {Number} minSize The minimum size
27398 setMinimumSize : function(minSize){
27399 this.minSize = minSize;
27403 * Gets the maximum size for the resizing element
27404 * @return {Number} The maximum size
27406 getMaximumSize : function(){
27407 return this.maxSize;
27411 * Sets the maximum size for the resizing element
27412 * @param {Number} maxSize The maximum size
27414 setMaximumSize : function(maxSize){
27415 this.maxSize = maxSize;
27419 * Sets the initialize size for the resizing element
27420 * @param {Number} size The initial size
27422 setCurrentSize : function(size){
27423 var oldAnimate = this.animate;
27424 this.animate = false;
27425 this.adapter.setElementSize(this, size);
27426 this.animate = oldAnimate;
27430 * Destroy this splitbar.
27431 * @param {Boolean} removeEl True to remove the element
27433 destroy : function(removeEl){
27435 this.shim.remove();
27438 this.proxy.parentNode.removeChild(this.proxy);
27446 * @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.
27448 Roo.SplitBar.createProxy = function(dir){
27449 var proxy = new Roo.Element(document.createElement("div"));
27450 proxy.unselectable();
27451 var cls = 'x-splitbar-proxy';
27452 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
27453 document.body.appendChild(proxy.dom);
27458 * @class Roo.SplitBar.BasicLayoutAdapter
27459 * Default Adapter. It assumes the splitter and resizing element are not positioned
27460 * elements and only gets/sets the width of the element. Generally used for table based layouts.
27462 Roo.SplitBar.BasicLayoutAdapter = function(){
27465 Roo.SplitBar.BasicLayoutAdapter.prototype = {
27466 // do nothing for now
27467 init : function(s){
27471 * Called before drag operations to get the current size of the resizing element.
27472 * @param {Roo.SplitBar} s The SplitBar using this adapter
27474 getElementSize : function(s){
27475 if(s.orientation == Roo.SplitBar.HORIZONTAL){
27476 return s.resizingEl.getWidth();
27478 return s.resizingEl.getHeight();
27483 * Called after drag operations to set the size of the resizing element.
27484 * @param {Roo.SplitBar} s The SplitBar using this adapter
27485 * @param {Number} newSize The new size to set
27486 * @param {Function} onComplete A function to be invoked when resizing is complete
27488 setElementSize : function(s, newSize, onComplete){
27489 if(s.orientation == Roo.SplitBar.HORIZONTAL){
27491 s.resizingEl.setWidth(newSize);
27493 onComplete(s, newSize);
27496 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
27501 s.resizingEl.setHeight(newSize);
27503 onComplete(s, newSize);
27506 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
27513 *@class Roo.SplitBar.AbsoluteLayoutAdapter
27514 * @extends Roo.SplitBar.BasicLayoutAdapter
27515 * Adapter that moves the splitter element to align with the resized sizing element.
27516 * Used with an absolute positioned SplitBar.
27517 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
27518 * document.body, make sure you assign an id to the body element.
27520 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
27521 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
27522 this.container = Roo.get(container);
27525 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
27526 init : function(s){
27527 this.basic.init(s);
27530 getElementSize : function(s){
27531 return this.basic.getElementSize(s);
27534 setElementSize : function(s, newSize, onComplete){
27535 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
27538 moveSplitter : function(s){
27539 var yes = Roo.SplitBar;
27540 switch(s.placement){
27542 s.el.setX(s.resizingEl.getRight());
27545 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
27548 s.el.setY(s.resizingEl.getBottom());
27551 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
27558 * Orientation constant - Create a vertical SplitBar
27562 Roo.SplitBar.VERTICAL = 1;
27565 * Orientation constant - Create a horizontal SplitBar
27569 Roo.SplitBar.HORIZONTAL = 2;
27572 * Placement constant - The resizing element is to the left of the splitter element
27576 Roo.SplitBar.LEFT = 1;
27579 * Placement constant - The resizing element is to the right of the splitter element
27583 Roo.SplitBar.RIGHT = 2;
27586 * Placement constant - The resizing element is positioned above the splitter element
27590 Roo.SplitBar.TOP = 3;
27593 * Placement constant - The resizing element is positioned under splitter element
27597 Roo.SplitBar.BOTTOM = 4;
27600 * Ext JS Library 1.1.1
27601 * Copyright(c) 2006-2007, Ext JS, LLC.
27603 * Originally Released Under LGPL - original licence link has changed is not relivant.
27606 * <script type="text/javascript">
27611 * @extends Roo.util.Observable
27612 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
27613 * This class also supports single and multi selection modes. <br>
27614 * Create a data model bound view:
27616 var store = new Roo.data.Store(...);
27618 var view = new Roo.View({
27620 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
27622 singleSelect: true,
27623 selectedClass: "ydataview-selected",
27627 // listen for node click?
27628 view.on("click", function(vw, index, node, e){
27629 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
27633 dataModel.load("foobar.xml");
27635 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
27637 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
27638 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
27640 * Note: old style constructor is still suported (container, template, config)
27643 * Create a new View
27644 * @param {Object} config The config object
27647 Roo.View = function(config, depreciated_tpl, depreciated_config){
27649 this.parent = false;
27651 if (typeof(depreciated_tpl) == 'undefined') {
27652 // new way.. - universal constructor.
27653 Roo.apply(this, config);
27654 this.el = Roo.get(this.el);
27657 this.el = Roo.get(config);
27658 this.tpl = depreciated_tpl;
27659 Roo.apply(this, depreciated_config);
27661 this.wrapEl = this.el.wrap().wrap();
27662 ///this.el = this.wrapEla.appendChild(document.createElement("div"));
27665 if(typeof(this.tpl) == "string"){
27666 this.tpl = new Roo.Template(this.tpl);
27668 // support xtype ctors..
27669 this.tpl = new Roo.factory(this.tpl, Roo);
27673 this.tpl.compile();
27678 * @event beforeclick
27679 * Fires before a click is processed. Returns false to cancel the default action.
27680 * @param {Roo.View} this
27681 * @param {Number} index The index of the target node
27682 * @param {HTMLElement} node The target node
27683 * @param {Roo.EventObject} e The raw event object
27685 "beforeclick" : true,
27688 * Fires when a template node is clicked.
27689 * @param {Roo.View} this
27690 * @param {Number} index The index of the target node
27691 * @param {HTMLElement} node The target node
27692 * @param {Roo.EventObject} e The raw event object
27697 * Fires when a template node is double clicked.
27698 * @param {Roo.View} this
27699 * @param {Number} index The index of the target node
27700 * @param {HTMLElement} node The target node
27701 * @param {Roo.EventObject} e The raw event object
27705 * @event contextmenu
27706 * Fires when a template node is right clicked.
27707 * @param {Roo.View} this
27708 * @param {Number} index The index of the target node
27709 * @param {HTMLElement} node The target node
27710 * @param {Roo.EventObject} e The raw event object
27712 "contextmenu" : true,
27714 * @event selectionchange
27715 * Fires when the selected nodes change.
27716 * @param {Roo.View} this
27717 * @param {Array} selections Array of the selected nodes
27719 "selectionchange" : true,
27722 * @event beforeselect
27723 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
27724 * @param {Roo.View} this
27725 * @param {HTMLElement} node The node to be selected
27726 * @param {Array} selections Array of currently selected nodes
27728 "beforeselect" : true,
27730 * @event preparedata
27731 * Fires on every row to render, to allow you to change the data.
27732 * @param {Roo.View} this
27733 * @param {Object} data to be rendered (change this)
27735 "preparedata" : true
27743 "click": this.onClick,
27744 "dblclick": this.onDblClick,
27745 "contextmenu": this.onContextMenu,
27749 this.selections = [];
27751 this.cmp = new Roo.CompositeElementLite([]);
27753 this.store = Roo.factory(this.store, Roo.data);
27754 this.setStore(this.store, true);
27757 if ( this.footer && this.footer.xtype) {
27759 var fctr = this.wrapEl.appendChild(document.createElement("div"));
27761 this.footer.dataSource = this.store;
27762 this.footer.container = fctr;
27763 this.footer = Roo.factory(this.footer, Roo);
27764 fctr.insertFirst(this.el);
27766 // this is a bit insane - as the paging toolbar seems to detach the el..
27767 // dom.parentNode.parentNode.parentNode
27768 // they get detached?
27772 Roo.View.superclass.constructor.call(this);
27777 Roo.extend(Roo.View, Roo.util.Observable, {
27780 * @cfg {Roo.data.Store} store Data store to load data from.
27785 * @cfg {String|Roo.Element} el The container element.
27790 * @cfg {String|Roo.Template} tpl The template used by this View
27794 * @cfg {String} dataName the named area of the template to use as the data area
27795 * Works with domtemplates roo-name="name"
27799 * @cfg {String} selectedClass The css class to add to selected nodes
27801 selectedClass : "x-view-selected",
27803 * @cfg {String} emptyText The empty text to show when nothing is loaded.
27808 * @cfg {String} text to display on mask (default Loading)
27812 * @cfg {Boolean} multiSelect Allow multiple selection
27814 multiSelect : false,
27816 * @cfg {Boolean} singleSelect Allow single selection
27818 singleSelect: false,
27821 * @cfg {Boolean} toggleSelect - selecting
27823 toggleSelect : false,
27826 * @cfg {Boolean} tickable - selecting
27831 * Returns the element this view is bound to.
27832 * @return {Roo.Element}
27834 getEl : function(){
27835 return this.wrapEl;
27841 * Refreshes the view. - called by datachanged on the store. - do not call directly.
27843 refresh : function(){
27844 //Roo.log('refresh');
27847 // if we are using something like 'domtemplate', then
27848 // the what gets used is:
27849 // t.applySubtemplate(NAME, data, wrapping data..)
27850 // the outer template then get' applied with
27851 // the store 'extra data'
27852 // and the body get's added to the
27853 // roo-name="data" node?
27854 // <span class='roo-tpl-{name}'></span> ?????
27858 this.clearSelections();
27859 this.el.update("");
27861 var records = this.store.getRange();
27862 if(records.length < 1) {
27864 // is this valid?? = should it render a template??
27866 this.el.update(this.emptyText);
27870 if (this.dataName) {
27871 this.el.update(t.apply(this.store.meta)); //????
27872 el = this.el.child('.roo-tpl-' + this.dataName);
27875 for(var i = 0, len = records.length; i < len; i++){
27876 var data = this.prepareData(records[i].data, i, records[i]);
27877 this.fireEvent("preparedata", this, data, i, records[i]);
27879 var d = Roo.apply({}, data);
27882 Roo.apply(d, {'roo-id' : Roo.id()});
27886 Roo.each(this.parent.item, function(item){
27887 if(item[_this.parent.valueField] != data[_this.parent.valueField]){
27890 Roo.apply(d, {'roo-data-checked' : 'checked'});
27894 html[html.length] = Roo.util.Format.trim(
27896 t.applySubtemplate(this.dataName, d, this.store.meta) :
27903 el.update(html.join(""));
27904 this.nodes = el.dom.childNodes;
27905 this.updateIndexes(0);
27910 * Function to override to reformat the data that is sent to
27911 * the template for each node.
27912 * DEPRICATED - use the preparedata event handler.
27913 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
27914 * a JSON object for an UpdateManager bound view).
27916 prepareData : function(data, index, record)
27918 this.fireEvent("preparedata", this, data, index, record);
27922 onUpdate : function(ds, record){
27923 // Roo.log('on update');
27924 this.clearSelections();
27925 var index = this.store.indexOf(record);
27926 var n = this.nodes[index];
27927 this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
27928 n.parentNode.removeChild(n);
27929 this.updateIndexes(index, index);
27935 onAdd : function(ds, records, index)
27937 //Roo.log(['on Add', ds, records, index] );
27938 this.clearSelections();
27939 if(this.nodes.length == 0){
27943 var n = this.nodes[index];
27944 for(var i = 0, len = records.length; i < len; i++){
27945 var d = this.prepareData(records[i].data, i, records[i]);
27947 this.tpl.insertBefore(n, d);
27950 this.tpl.append(this.el, d);
27953 this.updateIndexes(index);
27956 onRemove : function(ds, record, index){
27957 // Roo.log('onRemove');
27958 this.clearSelections();
27959 var el = this.dataName ?
27960 this.el.child('.roo-tpl-' + this.dataName) :
27963 el.dom.removeChild(this.nodes[index]);
27964 this.updateIndexes(index);
27968 * Refresh an individual node.
27969 * @param {Number} index
27971 refreshNode : function(index){
27972 this.onUpdate(this.store, this.store.getAt(index));
27975 updateIndexes : function(startIndex, endIndex){
27976 var ns = this.nodes;
27977 startIndex = startIndex || 0;
27978 endIndex = endIndex || ns.length - 1;
27979 for(var i = startIndex; i <= endIndex; i++){
27980 ns[i].nodeIndex = i;
27985 * Changes the data store this view uses and refresh the view.
27986 * @param {Store} store
27988 setStore : function(store, initial){
27989 if(!initial && this.store){
27990 this.store.un("datachanged", this.refresh);
27991 this.store.un("add", this.onAdd);
27992 this.store.un("remove", this.onRemove);
27993 this.store.un("update", this.onUpdate);
27994 this.store.un("clear", this.refresh);
27995 this.store.un("beforeload", this.onBeforeLoad);
27996 this.store.un("load", this.onLoad);
27997 this.store.un("loadexception", this.onLoad);
28001 store.on("datachanged", this.refresh, this);
28002 store.on("add", this.onAdd, this);
28003 store.on("remove", this.onRemove, this);
28004 store.on("update", this.onUpdate, this);
28005 store.on("clear", this.refresh, this);
28006 store.on("beforeload", this.onBeforeLoad, this);
28007 store.on("load", this.onLoad, this);
28008 store.on("loadexception", this.onLoad, this);
28016 * onbeforeLoad - masks the loading area.
28019 onBeforeLoad : function(store,opts)
28021 //Roo.log('onBeforeLoad');
28023 this.el.update("");
28025 this.el.mask(this.mask ? this.mask : "Loading" );
28027 onLoad : function ()
28034 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
28035 * @param {HTMLElement} node
28036 * @return {HTMLElement} The template node
28038 findItemFromChild : function(node){
28039 var el = this.dataName ?
28040 this.el.child('.roo-tpl-' + this.dataName,true) :
28043 if(!node || node.parentNode == el){
28046 var p = node.parentNode;
28047 while(p && p != el){
28048 if(p.parentNode == el){
28057 onClick : function(e){
28058 var item = this.findItemFromChild(e.getTarget());
28060 var index = this.indexOf(item);
28061 if(this.onItemClick(item, index, e) !== false){
28062 this.fireEvent("click", this, index, item, e);
28065 this.clearSelections();
28070 onContextMenu : function(e){
28071 var item = this.findItemFromChild(e.getTarget());
28073 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
28078 onDblClick : function(e){
28079 var item = this.findItemFromChild(e.getTarget());
28081 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
28085 onItemClick : function(item, index, e)
28087 if(this.fireEvent("beforeclick", this, index, item, e) === false){
28090 if (this.toggleSelect) {
28091 var m = this.isSelected(item) ? 'unselect' : 'select';
28094 _t[m](item, true, false);
28097 if(this.multiSelect || this.singleSelect){
28098 if(this.multiSelect && e.shiftKey && this.lastSelection){
28099 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
28101 this.select(item, this.multiSelect && e.ctrlKey);
28102 this.lastSelection = item;
28105 if(!this.tickable){
28106 e.preventDefault();
28114 * Get the number of selected nodes.
28117 getSelectionCount : function(){
28118 return this.selections.length;
28122 * Get the currently selected nodes.
28123 * @return {Array} An array of HTMLElements
28125 getSelectedNodes : function(){
28126 return this.selections;
28130 * Get the indexes of the selected nodes.
28133 getSelectedIndexes : function(){
28134 var indexes = [], s = this.selections;
28135 for(var i = 0, len = s.length; i < len; i++){
28136 indexes.push(s[i].nodeIndex);
28142 * Clear all selections
28143 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
28145 clearSelections : function(suppressEvent){
28146 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
28147 this.cmp.elements = this.selections;
28148 this.cmp.removeClass(this.selectedClass);
28149 this.selections = [];
28150 if(!suppressEvent){
28151 this.fireEvent("selectionchange", this, this.selections);
28157 * Returns true if the passed node is selected
28158 * @param {HTMLElement/Number} node The node or node index
28159 * @return {Boolean}
28161 isSelected : function(node){
28162 var s = this.selections;
28166 node = this.getNode(node);
28167 return s.indexOf(node) !== -1;
28172 * @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
28173 * @param {Boolean} keepExisting (optional) true to keep existing selections
28174 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28176 select : function(nodeInfo, keepExisting, suppressEvent){
28177 if(nodeInfo instanceof Array){
28179 this.clearSelections(true);
28181 for(var i = 0, len = nodeInfo.length; i < len; i++){
28182 this.select(nodeInfo[i], true, true);
28186 var node = this.getNode(nodeInfo);
28187 if(!node || this.isSelected(node)){
28188 return; // already selected.
28191 this.clearSelections(true);
28194 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
28195 Roo.fly(node).addClass(this.selectedClass);
28196 this.selections.push(node);
28197 if(!suppressEvent){
28198 this.fireEvent("selectionchange", this, this.selections);
28206 * @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
28207 * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
28208 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
28210 unselect : function(nodeInfo, keepExisting, suppressEvent)
28212 if(nodeInfo instanceof Array){
28213 Roo.each(this.selections, function(s) {
28214 this.unselect(s, nodeInfo);
28218 var node = this.getNode(nodeInfo);
28219 if(!node || !this.isSelected(node)){
28220 //Roo.log("not selected");
28221 return; // not selected.
28225 Roo.each(this.selections, function(s) {
28227 Roo.fly(node).removeClass(this.selectedClass);
28234 this.selections= ns;
28235 this.fireEvent("selectionchange", this, this.selections);
28239 * Gets a template node.
28240 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28241 * @return {HTMLElement} The node or null if it wasn't found
28243 getNode : function(nodeInfo){
28244 if(typeof nodeInfo == "string"){
28245 return document.getElementById(nodeInfo);
28246 }else if(typeof nodeInfo == "number"){
28247 return this.nodes[nodeInfo];
28253 * Gets a range template nodes.
28254 * @param {Number} startIndex
28255 * @param {Number} endIndex
28256 * @return {Array} An array of nodes
28258 getNodes : function(start, end){
28259 var ns = this.nodes;
28260 start = start || 0;
28261 end = typeof end == "undefined" ? ns.length - 1 : end;
28264 for(var i = start; i <= end; i++){
28268 for(var i = start; i >= end; i--){
28276 * Finds the index of the passed node
28277 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
28278 * @return {Number} The index of the node or -1
28280 indexOf : function(node){
28281 node = this.getNode(node);
28282 if(typeof node.nodeIndex == "number"){
28283 return node.nodeIndex;
28285 var ns = this.nodes;
28286 for(var i = 0, len = ns.length; i < len; i++){
28296 * Ext JS Library 1.1.1
28297 * Copyright(c) 2006-2007, Ext JS, LLC.
28299 * Originally Released Under LGPL - original licence link has changed is not relivant.
28302 * <script type="text/javascript">
28306 * @class Roo.JsonView
28307 * @extends Roo.View
28308 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
28310 var view = new Roo.JsonView({
28311 container: "my-element",
28312 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
28317 // listen for node click?
28318 view.on("click", function(vw, index, node, e){
28319 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
28322 // direct load of JSON data
28323 view.load("foobar.php");
28325 // Example from my blog list
28326 var tpl = new Roo.Template(
28327 '<div class="entry">' +
28328 '<a class="entry-title" href="{link}">{title}</a>' +
28329 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
28330 "</div><hr />"
28333 var moreView = new Roo.JsonView({
28334 container : "entry-list",
28338 moreView.on("beforerender", this.sortEntries, this);
28340 url: "/blog/get-posts.php",
28341 params: "allposts=true",
28342 text: "Loading Blog Entries..."
28346 * Note: old code is supported with arguments : (container, template, config)
28350 * Create a new JsonView
28352 * @param {Object} config The config object
28355 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
28358 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
28360 var um = this.el.getUpdateManager();
28361 um.setRenderer(this);
28362 um.on("update", this.onLoad, this);
28363 um.on("failure", this.onLoadException, this);
28366 * @event beforerender
28367 * Fires before rendering of the downloaded JSON data.
28368 * @param {Roo.JsonView} this
28369 * @param {Object} data The JSON data loaded
28373 * Fires when data is loaded.
28374 * @param {Roo.JsonView} this
28375 * @param {Object} data The JSON data loaded
28376 * @param {Object} response The raw Connect response object
28379 * @event loadexception
28380 * Fires when loading fails.
28381 * @param {Roo.JsonView} this
28382 * @param {Object} response The raw Connect response object
28385 'beforerender' : true,
28387 'loadexception' : true
28390 Roo.extend(Roo.JsonView, Roo.View, {
28392 * @type {String} The root property in the loaded JSON object that contains the data
28397 * Refreshes the view.
28399 refresh : function(){
28400 this.clearSelections();
28401 this.el.update("");
28403 var o = this.jsonData;
28404 if(o && o.length > 0){
28405 for(var i = 0, len = o.length; i < len; i++){
28406 var data = this.prepareData(o[i], i, o);
28407 html[html.length] = this.tpl.apply(data);
28410 html.push(this.emptyText);
28412 this.el.update(html.join(""));
28413 this.nodes = this.el.dom.childNodes;
28414 this.updateIndexes(0);
28418 * 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.
28419 * @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:
28422 url: "your-url.php",
28423 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
28424 callback: yourFunction,
28425 scope: yourObject, //(optional scope)
28428 text: "Loading...",
28433 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
28434 * 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.
28435 * @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}
28436 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
28437 * @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.
28440 var um = this.el.getUpdateManager();
28441 um.update.apply(um, arguments);
28444 // note - render is a standard framework call...
28445 // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
28446 render : function(el, response){
28448 this.clearSelections();
28449 this.el.update("");
28452 if (response != '') {
28453 o = Roo.util.JSON.decode(response.responseText);
28456 o = o[this.jsonRoot];
28462 * The current JSON data or null
28465 this.beforeRender();
28470 * Get the number of records in the current JSON dataset
28473 getCount : function(){
28474 return this.jsonData ? this.jsonData.length : 0;
28478 * Returns the JSON object for the specified node(s)
28479 * @param {HTMLElement/Array} node The node or an array of nodes
28480 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
28481 * you get the JSON object for the node
28483 getNodeData : function(node){
28484 if(node instanceof Array){
28486 for(var i = 0, len = node.length; i < len; i++){
28487 data.push(this.getNodeData(node[i]));
28491 return this.jsonData[this.indexOf(node)] || null;
28494 beforeRender : function(){
28495 this.snapshot = this.jsonData;
28497 this.sort.apply(this, this.sortInfo);
28499 this.fireEvent("beforerender", this, this.jsonData);
28502 onLoad : function(el, o){
28503 this.fireEvent("load", this, this.jsonData, o);
28506 onLoadException : function(el, o){
28507 this.fireEvent("loadexception", this, o);
28511 * Filter the data by a specific property.
28512 * @param {String} property A property on your JSON objects
28513 * @param {String/RegExp} value Either string that the property values
28514 * should start with, or a RegExp to test against the property
28516 filter : function(property, value){
28519 var ss = this.snapshot;
28520 if(typeof value == "string"){
28521 var vlen = value.length;
28523 this.clearFilter();
28526 value = value.toLowerCase();
28527 for(var i = 0, len = ss.length; i < len; i++){
28529 if(o[property].substr(0, vlen).toLowerCase() == value){
28533 } else if(value.exec){ // regex?
28534 for(var i = 0, len = ss.length; i < len; i++){
28536 if(value.test(o[property])){
28543 this.jsonData = data;
28549 * Filter by a function. The passed function will be called with each
28550 * object in the current dataset. If the function returns true the value is kept,
28551 * otherwise it is filtered.
28552 * @param {Function} fn
28553 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
28555 filterBy : function(fn, scope){
28558 var ss = this.snapshot;
28559 for(var i = 0, len = ss.length; i < len; i++){
28561 if(fn.call(scope || this, o)){
28565 this.jsonData = data;
28571 * Clears the current filter.
28573 clearFilter : function(){
28574 if(this.snapshot && this.jsonData != this.snapshot){
28575 this.jsonData = this.snapshot;
28582 * Sorts the data for this view and refreshes it.
28583 * @param {String} property A property on your JSON objects to sort on
28584 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
28585 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
28587 sort : function(property, dir, sortType){
28588 this.sortInfo = Array.prototype.slice.call(arguments, 0);
28591 var dsc = dir && dir.toLowerCase() == "desc";
28592 var f = function(o1, o2){
28593 var v1 = sortType ? sortType(o1[p]) : o1[p];
28594 var v2 = sortType ? sortType(o2[p]) : o2[p];
28597 return dsc ? +1 : -1;
28598 } else if(v1 > v2){
28599 return dsc ? -1 : +1;
28604 this.jsonData.sort(f);
28606 if(this.jsonData != this.snapshot){
28607 this.snapshot.sort(f);
28613 * Ext JS Library 1.1.1
28614 * Copyright(c) 2006-2007, Ext JS, LLC.
28616 * Originally Released Under LGPL - original licence link has changed is not relivant.
28619 * <script type="text/javascript">
28624 * @class Roo.ColorPalette
28625 * @extends Roo.Component
28626 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
28627 * Here's an example of typical usage:
28629 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
28630 cp.render('my-div');
28632 cp.on('select', function(palette, selColor){
28633 // do something with selColor
28637 * Create a new ColorPalette
28638 * @param {Object} config The config object
28640 Roo.ColorPalette = function(config){
28641 Roo.ColorPalette.superclass.constructor.call(this, config);
28645 * Fires when a color is selected
28646 * @param {ColorPalette} this
28647 * @param {String} color The 6-digit color hex code (without the # symbol)
28653 this.on("select", this.handler, this.scope, true);
28656 Roo.extend(Roo.ColorPalette, Roo.Component, {
28658 * @cfg {String} itemCls
28659 * The CSS class to apply to the containing element (defaults to "x-color-palette")
28661 itemCls : "x-color-palette",
28663 * @cfg {String} value
28664 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
28665 * the hex codes are case-sensitive.
28668 clickEvent:'click',
28670 ctype: "Roo.ColorPalette",
28673 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
28675 allowReselect : false,
28678 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
28679 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
28680 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
28681 * of colors with the width setting until the box is symmetrical.</p>
28682 * <p>You can override individual colors if needed:</p>
28684 var cp = new Roo.ColorPalette();
28685 cp.colors[0] = "FF0000"; // change the first box to red
28688 Or you can provide a custom array of your own for complete control:
28690 var cp = new Roo.ColorPalette();
28691 cp.colors = ["000000", "993300", "333300"];
28696 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
28697 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
28698 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
28699 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
28700 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
28704 onRender : function(container, position){
28705 var t = new Roo.MasterTemplate(
28706 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
28708 var c = this.colors;
28709 for(var i = 0, len = c.length; i < len; i++){
28712 var el = document.createElement("div");
28713 el.className = this.itemCls;
28715 container.dom.insertBefore(el, position);
28716 this.el = Roo.get(el);
28717 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
28718 if(this.clickEvent != 'click'){
28719 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
28724 afterRender : function(){
28725 Roo.ColorPalette.superclass.afterRender.call(this);
28727 var s = this.value;
28734 handleClick : function(e, t){
28735 e.preventDefault();
28736 if(!this.disabled){
28737 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
28738 this.select(c.toUpperCase());
28743 * Selects the specified color in the palette (fires the select event)
28744 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
28746 select : function(color){
28747 color = color.replace("#", "");
28748 if(color != this.value || this.allowReselect){
28751 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
28753 el.child("a.color-"+color).addClass("x-color-palette-sel");
28754 this.value = color;
28755 this.fireEvent("select", this, color);
28760 * Ext JS Library 1.1.1
28761 * Copyright(c) 2006-2007, Ext JS, LLC.
28763 * Originally Released Under LGPL - original licence link has changed is not relivant.
28766 * <script type="text/javascript">
28770 * @class Roo.DatePicker
28771 * @extends Roo.Component
28772 * Simple date picker class.
28774 * Create a new DatePicker
28775 * @param {Object} config The config object
28777 Roo.DatePicker = function(config){
28778 Roo.DatePicker.superclass.constructor.call(this, config);
28780 this.value = config && config.value ?
28781 config.value.clearTime() : new Date().clearTime();
28786 * Fires when a date is selected
28787 * @param {DatePicker} this
28788 * @param {Date} date The selected date
28792 * @event monthchange
28793 * Fires when the displayed month changes
28794 * @param {DatePicker} this
28795 * @param {Date} date The selected month
28797 'monthchange': true
28801 this.on("select", this.handler, this.scope || this);
28803 // build the disabledDatesRE
28804 if(!this.disabledDatesRE && this.disabledDates){
28805 var dd = this.disabledDates;
28807 for(var i = 0; i < dd.length; i++){
28809 if(i != dd.length-1) {
28813 this.disabledDatesRE = new RegExp(re + ")");
28817 Roo.extend(Roo.DatePicker, Roo.Component, {
28819 * @cfg {String} todayText
28820 * The text to display on the button that selects the current date (defaults to "Today")
28822 todayText : "Today",
28824 * @cfg {String} okText
28825 * The text to display on the ok button
28827 okText : " OK ", //   to give the user extra clicking room
28829 * @cfg {String} cancelText
28830 * The text to display on the cancel button
28832 cancelText : "Cancel",
28834 * @cfg {String} todayTip
28835 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
28837 todayTip : "{0} (Spacebar)",
28839 * @cfg {Date} minDate
28840 * Minimum allowable date (JavaScript date object, defaults to null)
28844 * @cfg {Date} maxDate
28845 * Maximum allowable date (JavaScript date object, defaults to null)
28849 * @cfg {String} minText
28850 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
28852 minText : "This date is before the minimum date",
28854 * @cfg {String} maxText
28855 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
28857 maxText : "This date is after the maximum date",
28859 * @cfg {String} format
28860 * The default date format string which can be overriden for localization support. The format must be
28861 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
28865 * @cfg {Array} disabledDays
28866 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
28868 disabledDays : null,
28870 * @cfg {String} disabledDaysText
28871 * The tooltip to display when the date falls on a disabled day (defaults to "")
28873 disabledDaysText : "",
28875 * @cfg {RegExp} disabledDatesRE
28876 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
28878 disabledDatesRE : null,
28880 * @cfg {String} disabledDatesText
28881 * The tooltip text to display when the date falls on a disabled date (defaults to "")
28883 disabledDatesText : "",
28885 * @cfg {Boolean} constrainToViewport
28886 * True to constrain the date picker to the viewport (defaults to true)
28888 constrainToViewport : true,
28890 * @cfg {Array} monthNames
28891 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
28893 monthNames : Date.monthNames,
28895 * @cfg {Array} dayNames
28896 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
28898 dayNames : Date.dayNames,
28900 * @cfg {String} nextText
28901 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
28903 nextText: 'Next Month (Control+Right)',
28905 * @cfg {String} prevText
28906 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
28908 prevText: 'Previous Month (Control+Left)',
28910 * @cfg {String} monthYearText
28911 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
28913 monthYearText: 'Choose a month (Control+Up/Down to move years)',
28915 * @cfg {Number} startDay
28916 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
28920 * @cfg {Bool} showClear
28921 * Show a clear button (usefull for date form elements that can be blank.)
28927 * Sets the value of the date field
28928 * @param {Date} value The date to set
28930 setValue : function(value){
28931 var old = this.value;
28933 if (typeof(value) == 'string') {
28935 value = Date.parseDate(value, this.format);
28938 value = new Date();
28941 this.value = value.clearTime(true);
28943 this.update(this.value);
28948 * Gets the current selected value of the date field
28949 * @return {Date} The selected date
28951 getValue : function(){
28956 focus : function(){
28958 this.update(this.activeDate);
28963 onRender : function(container, position){
28966 '<table cellspacing="0">',
28967 '<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>',
28968 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
28969 var dn = this.dayNames;
28970 for(var i = 0; i < 7; i++){
28971 var d = this.startDay+i;
28975 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
28977 m[m.length] = "</tr></thead><tbody><tr>";
28978 for(var i = 0; i < 42; i++) {
28979 if(i % 7 == 0 && i != 0){
28980 m[m.length] = "</tr><tr>";
28982 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
28984 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
28985 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
28987 var el = document.createElement("div");
28988 el.className = "x-date-picker";
28989 el.innerHTML = m.join("");
28991 container.dom.insertBefore(el, position);
28993 this.el = Roo.get(el);
28994 this.eventEl = Roo.get(el.firstChild);
28996 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
28997 handler: this.showPrevMonth,
28999 preventDefault:true,
29003 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
29004 handler: this.showNextMonth,
29006 preventDefault:true,
29010 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
29012 this.monthPicker = this.el.down('div.x-date-mp');
29013 this.monthPicker.enableDisplayMode('block');
29015 var kn = new Roo.KeyNav(this.eventEl, {
29016 "left" : function(e){
29018 this.showPrevMonth() :
29019 this.update(this.activeDate.add("d", -1));
29022 "right" : function(e){
29024 this.showNextMonth() :
29025 this.update(this.activeDate.add("d", 1));
29028 "up" : function(e){
29030 this.showNextYear() :
29031 this.update(this.activeDate.add("d", -7));
29034 "down" : function(e){
29036 this.showPrevYear() :
29037 this.update(this.activeDate.add("d", 7));
29040 "pageUp" : function(e){
29041 this.showNextMonth();
29044 "pageDown" : function(e){
29045 this.showPrevMonth();
29048 "enter" : function(e){
29049 e.stopPropagation();
29056 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
29058 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
29060 this.el.unselectable();
29062 this.cells = this.el.select("table.x-date-inner tbody td");
29063 this.textNodes = this.el.query("table.x-date-inner tbody span");
29065 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
29067 tooltip: this.monthYearText
29070 this.mbtn.on('click', this.showMonthPicker, this);
29071 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
29074 var today = (new Date()).dateFormat(this.format);
29076 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
29077 if (this.showClear) {
29078 baseTb.add( new Roo.Toolbar.Fill());
29081 text: String.format(this.todayText, today),
29082 tooltip: String.format(this.todayTip, today),
29083 handler: this.selectToday,
29087 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
29090 if (this.showClear) {
29092 baseTb.add( new Roo.Toolbar.Fill());
29095 cls: 'x-btn-icon x-btn-clear',
29096 handler: function() {
29098 this.fireEvent("select", this, '');
29108 this.update(this.value);
29111 createMonthPicker : function(){
29112 if(!this.monthPicker.dom.firstChild){
29113 var buf = ['<table border="0" cellspacing="0">'];
29114 for(var i = 0; i < 6; i++){
29116 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
29117 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
29119 '<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>' :
29120 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
29124 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
29126 '</button><button type="button" class="x-date-mp-cancel">',
29128 '</button></td></tr>',
29131 this.monthPicker.update(buf.join(''));
29132 this.monthPicker.on('click', this.onMonthClick, this);
29133 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
29135 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
29136 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
29138 this.mpMonths.each(function(m, a, i){
29141 m.dom.xmonth = 5 + Math.round(i * .5);
29143 m.dom.xmonth = Math.round((i-1) * .5);
29149 showMonthPicker : function(){
29150 this.createMonthPicker();
29151 var size = this.el.getSize();
29152 this.monthPicker.setSize(size);
29153 this.monthPicker.child('table').setSize(size);
29155 this.mpSelMonth = (this.activeDate || this.value).getMonth();
29156 this.updateMPMonth(this.mpSelMonth);
29157 this.mpSelYear = (this.activeDate || this.value).getFullYear();
29158 this.updateMPYear(this.mpSelYear);
29160 this.monthPicker.slideIn('t', {duration:.2});
29163 updateMPYear : function(y){
29165 var ys = this.mpYears.elements;
29166 for(var i = 1; i <= 10; i++){
29167 var td = ys[i-1], y2;
29169 y2 = y + Math.round(i * .5);
29170 td.firstChild.innerHTML = y2;
29173 y2 = y - (5-Math.round(i * .5));
29174 td.firstChild.innerHTML = y2;
29177 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
29181 updateMPMonth : function(sm){
29182 this.mpMonths.each(function(m, a, i){
29183 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
29187 selectMPMonth: function(m){
29191 onMonthClick : function(e, t){
29193 var el = new Roo.Element(t), pn;
29194 if(el.is('button.x-date-mp-cancel')){
29195 this.hideMonthPicker();
29197 else if(el.is('button.x-date-mp-ok')){
29198 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29199 this.hideMonthPicker();
29201 else if(pn = el.up('td.x-date-mp-month', 2)){
29202 this.mpMonths.removeClass('x-date-mp-sel');
29203 pn.addClass('x-date-mp-sel');
29204 this.mpSelMonth = pn.dom.xmonth;
29206 else if(pn = el.up('td.x-date-mp-year', 2)){
29207 this.mpYears.removeClass('x-date-mp-sel');
29208 pn.addClass('x-date-mp-sel');
29209 this.mpSelYear = pn.dom.xyear;
29211 else if(el.is('a.x-date-mp-prev')){
29212 this.updateMPYear(this.mpyear-10);
29214 else if(el.is('a.x-date-mp-next')){
29215 this.updateMPYear(this.mpyear+10);
29219 onMonthDblClick : function(e, t){
29221 var el = new Roo.Element(t), pn;
29222 if(pn = el.up('td.x-date-mp-month', 2)){
29223 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
29224 this.hideMonthPicker();
29226 else if(pn = el.up('td.x-date-mp-year', 2)){
29227 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
29228 this.hideMonthPicker();
29232 hideMonthPicker : function(disableAnim){
29233 if(this.monthPicker){
29234 if(disableAnim === true){
29235 this.monthPicker.hide();
29237 this.monthPicker.slideOut('t', {duration:.2});
29243 showPrevMonth : function(e){
29244 this.update(this.activeDate.add("mo", -1));
29248 showNextMonth : function(e){
29249 this.update(this.activeDate.add("mo", 1));
29253 showPrevYear : function(){
29254 this.update(this.activeDate.add("y", -1));
29258 showNextYear : function(){
29259 this.update(this.activeDate.add("y", 1));
29263 handleMouseWheel : function(e){
29264 var delta = e.getWheelDelta();
29266 this.showPrevMonth();
29268 } else if(delta < 0){
29269 this.showNextMonth();
29275 handleDateClick : function(e, t){
29277 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
29278 this.setValue(new Date(t.dateValue));
29279 this.fireEvent("select", this, this.value);
29284 selectToday : function(){
29285 this.setValue(new Date().clearTime());
29286 this.fireEvent("select", this, this.value);
29290 update : function(date)
29292 var vd = this.activeDate;
29293 this.activeDate = date;
29295 var t = date.getTime();
29296 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
29297 this.cells.removeClass("x-date-selected");
29298 this.cells.each(function(c){
29299 if(c.dom.firstChild.dateValue == t){
29300 c.addClass("x-date-selected");
29301 setTimeout(function(){
29302 try{c.dom.firstChild.focus();}catch(e){}
29311 var days = date.getDaysInMonth();
29312 var firstOfMonth = date.getFirstDateOfMonth();
29313 var startingPos = firstOfMonth.getDay()-this.startDay;
29315 if(startingPos <= this.startDay){
29319 var pm = date.add("mo", -1);
29320 var prevStart = pm.getDaysInMonth()-startingPos;
29322 var cells = this.cells.elements;
29323 var textEls = this.textNodes;
29324 days += startingPos;
29326 // convert everything to numbers so it's fast
29327 var day = 86400000;
29328 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
29329 var today = new Date().clearTime().getTime();
29330 var sel = date.clearTime().getTime();
29331 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
29332 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
29333 var ddMatch = this.disabledDatesRE;
29334 var ddText = this.disabledDatesText;
29335 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
29336 var ddaysText = this.disabledDaysText;
29337 var format = this.format;
29339 var setCellClass = function(cal, cell){
29341 var t = d.getTime();
29342 cell.firstChild.dateValue = t;
29344 cell.className += " x-date-today";
29345 cell.title = cal.todayText;
29348 cell.className += " x-date-selected";
29349 setTimeout(function(){
29350 try{cell.firstChild.focus();}catch(e){}
29355 cell.className = " x-date-disabled";
29356 cell.title = cal.minText;
29360 cell.className = " x-date-disabled";
29361 cell.title = cal.maxText;
29365 if(ddays.indexOf(d.getDay()) != -1){
29366 cell.title = ddaysText;
29367 cell.className = " x-date-disabled";
29370 if(ddMatch && format){
29371 var fvalue = d.dateFormat(format);
29372 if(ddMatch.test(fvalue)){
29373 cell.title = ddText.replace("%0", fvalue);
29374 cell.className = " x-date-disabled";
29380 for(; i < startingPos; i++) {
29381 textEls[i].innerHTML = (++prevStart);
29382 d.setDate(d.getDate()+1);
29383 cells[i].className = "x-date-prevday";
29384 setCellClass(this, cells[i]);
29386 for(; i < days; i++){
29387 intDay = i - startingPos + 1;
29388 textEls[i].innerHTML = (intDay);
29389 d.setDate(d.getDate()+1);
29390 cells[i].className = "x-date-active";
29391 setCellClass(this, cells[i]);
29394 for(; i < 42; i++) {
29395 textEls[i].innerHTML = (++extraDays);
29396 d.setDate(d.getDate()+1);
29397 cells[i].className = "x-date-nextday";
29398 setCellClass(this, cells[i]);
29401 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
29402 this.fireEvent('monthchange', this, date);
29404 if(!this.internalRender){
29405 var main = this.el.dom.firstChild;
29406 var w = main.offsetWidth;
29407 this.el.setWidth(w + this.el.getBorderWidth("lr"));
29408 Roo.fly(main).setWidth(w);
29409 this.internalRender = true;
29410 // opera does not respect the auto grow header center column
29411 // then, after it gets a width opera refuses to recalculate
29412 // without a second pass
29413 if(Roo.isOpera && !this.secondPass){
29414 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
29415 this.secondPass = true;
29416 this.update.defer(10, this, [date]);
29424 * Ext JS Library 1.1.1
29425 * Copyright(c) 2006-2007, Ext JS, LLC.
29427 * Originally Released Under LGPL - original licence link has changed is not relivant.
29430 * <script type="text/javascript">
29433 * @class Roo.TabPanel
29434 * @extends Roo.util.Observable
29435 * A lightweight tab container.
29439 // basic tabs 1, built from existing content
29440 var tabs = new Roo.TabPanel("tabs1");
29441 tabs.addTab("script", "View Script");
29442 tabs.addTab("markup", "View Markup");
29443 tabs.activate("script");
29445 // more advanced tabs, built from javascript
29446 var jtabs = new Roo.TabPanel("jtabs");
29447 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
29449 // set up the UpdateManager
29450 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
29451 var updater = tab2.getUpdateManager();
29452 updater.setDefaultUrl("ajax1.htm");
29453 tab2.on('activate', updater.refresh, updater, true);
29455 // Use setUrl for Ajax loading
29456 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
29457 tab3.setUrl("ajax2.htm", null, true);
29460 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
29463 jtabs.activate("jtabs-1");
29466 * Create a new TabPanel.
29467 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
29468 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
29470 Roo.TabPanel = function(container, config){
29472 * The container element for this TabPanel.
29473 * @type Roo.Element
29475 this.el = Roo.get(container, true);
29477 if(typeof config == "boolean"){
29478 this.tabPosition = config ? "bottom" : "top";
29480 Roo.apply(this, config);
29483 if(this.tabPosition == "bottom"){
29484 this.bodyEl = Roo.get(this.createBody(this.el.dom));
29485 this.el.addClass("x-tabs-bottom");
29487 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
29488 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
29489 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
29491 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
29493 if(this.tabPosition != "bottom"){
29494 /** The body element that contains {@link Roo.TabPanelItem} bodies. +
29495 * @type Roo.Element
29497 this.bodyEl = Roo.get(this.createBody(this.el.dom));
29498 this.el.addClass("x-tabs-top");
29502 this.bodyEl.setStyle("position", "relative");
29504 this.active = null;
29505 this.activateDelegate = this.activate.createDelegate(this);
29510 * Fires when the active tab changes
29511 * @param {Roo.TabPanel} this
29512 * @param {Roo.TabPanelItem} activePanel The new active tab
29516 * @event beforetabchange
29517 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
29518 * @param {Roo.TabPanel} this
29519 * @param {Object} e Set cancel to true on this object to cancel the tab change
29520 * @param {Roo.TabPanelItem} tab The tab being changed to
29522 "beforetabchange" : true
29525 Roo.EventManager.onWindowResize(this.onResize, this);
29526 this.cpad = this.el.getPadding("lr");
29527 this.hiddenCount = 0;
29530 // toolbar on the tabbar support...
29531 if (this.toolbar) {
29532 var tcfg = this.toolbar;
29533 tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
29534 this.toolbar = new Roo.Toolbar(tcfg);
29535 if (Roo.isSafari) {
29536 var tbl = tcfg.container.child('table', true);
29537 tbl.setAttribute('width', '100%');
29544 Roo.TabPanel.superclass.constructor.call(this);
29547 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
29549 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
29551 tabPosition : "top",
29553 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
29555 currentTabWidth : 0,
29557 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
29561 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
29565 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
29567 preferredTabWidth : 175,
29569 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
29571 resizeTabs : false,
29573 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
29575 monitorResize : true,
29577 *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
29582 * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
29583 * @param {String} id The id of the div to use <b>or create</b>
29584 * @param {String} text The text for the tab
29585 * @param {String} content (optional) Content to put in the TabPanelItem body
29586 * @param {Boolean} closable (optional) True to create a close icon on the tab
29587 * @return {Roo.TabPanelItem} The created TabPanelItem
29589 addTab : function(id, text, content, closable){
29590 var item = new Roo.TabPanelItem(this, id, text, closable);
29591 this.addTabItem(item);
29593 item.setContent(content);
29599 * Returns the {@link Roo.TabPanelItem} with the specified id/index
29600 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
29601 * @return {Roo.TabPanelItem}
29603 getTab : function(id){
29604 return this.items[id];
29608 * Hides the {@link Roo.TabPanelItem} with the specified id/index
29609 * @param {String/Number} id The id or index of the TabPanelItem to hide.
29611 hideTab : function(id){
29612 var t = this.items[id];
29615 this.hiddenCount++;
29616 this.autoSizeTabs();
29621 * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
29622 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
29624 unhideTab : function(id){
29625 var t = this.items[id];
29627 t.setHidden(false);
29628 this.hiddenCount--;
29629 this.autoSizeTabs();
29634 * Adds an existing {@link Roo.TabPanelItem}.
29635 * @param {Roo.TabPanelItem} item The TabPanelItem to add
29637 addTabItem : function(item){
29638 this.items[item.id] = item;
29639 this.items.push(item);
29640 if(this.resizeTabs){
29641 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
29642 this.autoSizeTabs();
29649 * Removes a {@link Roo.TabPanelItem}.
29650 * @param {String/Number} id The id or index of the TabPanelItem to remove.
29652 removeTab : function(id){
29653 var items = this.items;
29654 var tab = items[id];
29655 if(!tab) { return; }
29656 var index = items.indexOf(tab);
29657 if(this.active == tab && items.length > 1){
29658 var newTab = this.getNextAvailable(index);
29663 this.stripEl.dom.removeChild(tab.pnode.dom);
29664 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
29665 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
29667 items.splice(index, 1);
29668 delete this.items[tab.id];
29669 tab.fireEvent("close", tab);
29670 tab.purgeListeners();
29671 this.autoSizeTabs();
29674 getNextAvailable : function(start){
29675 var items = this.items;
29677 // look for a next tab that will slide over to
29678 // replace the one being removed
29679 while(index < items.length){
29680 var item = items[++index];
29681 if(item && !item.isHidden()){
29685 // if one isn't found select the previous tab (on the left)
29688 var item = items[--index];
29689 if(item && !item.isHidden()){
29697 * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
29698 * @param {String/Number} id The id or index of the TabPanelItem to disable.
29700 disableTab : function(id){
29701 var tab = this.items[id];
29702 if(tab && this.active != tab){
29708 * Enables a {@link Roo.TabPanelItem} that is disabled.
29709 * @param {String/Number} id The id or index of the TabPanelItem to enable.
29711 enableTab : function(id){
29712 var tab = this.items[id];
29717 * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
29718 * @param {String/Number} id The id or index of the TabPanelItem to activate.
29719 * @return {Roo.TabPanelItem} The TabPanelItem.
29721 activate : function(id){
29722 var tab = this.items[id];
29726 if(tab == this.active || tab.disabled){
29730 this.fireEvent("beforetabchange", this, e, tab);
29731 if(e.cancel !== true && !tab.disabled){
29733 this.active.hide();
29735 this.active = this.items[id];
29736 this.active.show();
29737 this.fireEvent("tabchange", this, this.active);
29743 * Gets the active {@link Roo.TabPanelItem}.
29744 * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
29746 getActiveTab : function(){
29747 return this.active;
29751 * Updates the tab body element to fit the height of the container element
29752 * for overflow scrolling
29753 * @param {Number} targetHeight (optional) Override the starting height from the elements height
29755 syncHeight : function(targetHeight){
29756 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
29757 var bm = this.bodyEl.getMargins();
29758 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
29759 this.bodyEl.setHeight(newHeight);
29763 onResize : function(){
29764 if(this.monitorResize){
29765 this.autoSizeTabs();
29770 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
29772 beginUpdate : function(){
29773 this.updating = true;
29777 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
29779 endUpdate : function(){
29780 this.updating = false;
29781 this.autoSizeTabs();
29785 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
29787 autoSizeTabs : function(){
29788 var count = this.items.length;
29789 var vcount = count - this.hiddenCount;
29790 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
29793 var w = Math.max(this.el.getWidth() - this.cpad, 10);
29794 var availWidth = Math.floor(w / vcount);
29795 var b = this.stripBody;
29796 if(b.getWidth() > w){
29797 var tabs = this.items;
29798 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
29799 if(availWidth < this.minTabWidth){
29800 /*if(!this.sleft){ // incomplete scrolling code
29801 this.createScrollButtons();
29804 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
29807 if(this.currentTabWidth < this.preferredTabWidth){
29808 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
29814 * Returns the number of tabs in this TabPanel.
29817 getCount : function(){
29818 return this.items.length;
29822 * Resizes all the tabs to the passed width
29823 * @param {Number} The new width
29825 setTabWidth : function(width){
29826 this.currentTabWidth = width;
29827 for(var i = 0, len = this.items.length; i < len; i++) {
29828 if(!this.items[i].isHidden()) {
29829 this.items[i].setWidth(width);
29835 * Destroys this TabPanel
29836 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
29838 destroy : function(removeEl){
29839 Roo.EventManager.removeResizeListener(this.onResize, this);
29840 for(var i = 0, len = this.items.length; i < len; i++){
29841 this.items[i].purgeListeners();
29843 if(removeEl === true){
29844 this.el.update("");
29851 * @class Roo.TabPanelItem
29852 * @extends Roo.util.Observable
29853 * Represents an individual item (tab plus body) in a TabPanel.
29854 * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
29855 * @param {String} id The id of this TabPanelItem
29856 * @param {String} text The text for the tab of this TabPanelItem
29857 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
29859 Roo.TabPanelItem = function(tabPanel, id, text, closable){
29861 * The {@link Roo.TabPanel} this TabPanelItem belongs to
29862 * @type Roo.TabPanel
29864 this.tabPanel = tabPanel;
29866 * The id for this TabPanelItem
29871 this.disabled = false;
29875 this.loaded = false;
29876 this.closable = closable;
29879 * The body element for this TabPanelItem.
29880 * @type Roo.Element
29882 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
29883 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
29884 this.bodyEl.setStyle("display", "block");
29885 this.bodyEl.setStyle("zoom", "1");
29888 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
29890 this.el = Roo.get(els.el, true);
29891 this.inner = Roo.get(els.inner, true);
29892 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
29893 this.pnode = Roo.get(els.el.parentNode, true);
29894 this.el.on("mousedown", this.onTabMouseDown, this);
29895 this.el.on("click", this.onTabClick, this);
29898 var c = Roo.get(els.close, true);
29899 c.dom.title = this.closeText;
29900 c.addClassOnOver("close-over");
29901 c.on("click", this.closeClick, this);
29907 * Fires when this tab becomes the active tab.
29908 * @param {Roo.TabPanel} tabPanel The parent TabPanel
29909 * @param {Roo.TabPanelItem} this
29913 * @event beforeclose
29914 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
29915 * @param {Roo.TabPanelItem} this
29916 * @param {Object} e Set cancel to true on this object to cancel the close.
29918 "beforeclose": true,
29921 * Fires when this tab is closed.
29922 * @param {Roo.TabPanelItem} this
29926 * @event deactivate
29927 * Fires when this tab is no longer the active tab.
29928 * @param {Roo.TabPanel} tabPanel The parent TabPanel
29929 * @param {Roo.TabPanelItem} this
29931 "deactivate" : true
29933 this.hidden = false;
29935 Roo.TabPanelItem.superclass.constructor.call(this);
29938 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
29939 purgeListeners : function(){
29940 Roo.util.Observable.prototype.purgeListeners.call(this);
29941 this.el.removeAllListeners();
29944 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
29947 this.pnode.addClass("on");
29950 this.tabPanel.stripWrap.repaint();
29952 this.fireEvent("activate", this.tabPanel, this);
29956 * Returns true if this tab is the active tab.
29957 * @return {Boolean}
29959 isActive : function(){
29960 return this.tabPanel.getActiveTab() == this;
29964 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
29967 this.pnode.removeClass("on");
29969 this.fireEvent("deactivate", this.tabPanel, this);
29972 hideAction : function(){
29973 this.bodyEl.hide();
29974 this.bodyEl.setStyle("position", "absolute");
29975 this.bodyEl.setLeft("-20000px");
29976 this.bodyEl.setTop("-20000px");
29979 showAction : function(){
29980 this.bodyEl.setStyle("position", "relative");
29981 this.bodyEl.setTop("");
29982 this.bodyEl.setLeft("");
29983 this.bodyEl.show();
29987 * Set the tooltip for the tab.
29988 * @param {String} tooltip The tab's tooltip
29990 setTooltip : function(text){
29991 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
29992 this.textEl.dom.qtip = text;
29993 this.textEl.dom.removeAttribute('title');
29995 this.textEl.dom.title = text;
29999 onTabClick : function(e){
30000 e.preventDefault();
30001 this.tabPanel.activate(this.id);
30004 onTabMouseDown : function(e){
30005 e.preventDefault();
30006 this.tabPanel.activate(this.id);
30009 getWidth : function(){
30010 return this.inner.getWidth();
30013 setWidth : function(width){
30014 var iwidth = width - this.pnode.getPadding("lr");
30015 this.inner.setWidth(iwidth);
30016 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
30017 this.pnode.setWidth(width);
30021 * Show or hide the tab
30022 * @param {Boolean} hidden True to hide or false to show.
30024 setHidden : function(hidden){
30025 this.hidden = hidden;
30026 this.pnode.setStyle("display", hidden ? "none" : "");
30030 * Returns true if this tab is "hidden"
30031 * @return {Boolean}
30033 isHidden : function(){
30034 return this.hidden;
30038 * Returns the text for this tab
30041 getText : function(){
30045 autoSize : function(){
30046 //this.el.beginMeasure();
30047 this.textEl.setWidth(1);
30049 * #2804 [new] Tabs in Roojs
30050 * increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
30052 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
30053 //this.el.endMeasure();
30057 * Sets the text for the tab (Note: this also sets the tooltip text)
30058 * @param {String} text The tab's text and tooltip
30060 setText : function(text){
30062 this.textEl.update(text);
30063 this.setTooltip(text);
30064 if(!this.tabPanel.resizeTabs){
30069 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
30071 activate : function(){
30072 this.tabPanel.activate(this.id);
30076 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
30078 disable : function(){
30079 if(this.tabPanel.active != this){
30080 this.disabled = true;
30081 this.pnode.addClass("disabled");
30086 * Enables this TabPanelItem if it was previously disabled.
30088 enable : function(){
30089 this.disabled = false;
30090 this.pnode.removeClass("disabled");
30094 * Sets the content for this TabPanelItem.
30095 * @param {String} content The content
30096 * @param {Boolean} loadScripts true to look for and load scripts
30098 setContent : function(content, loadScripts){
30099 this.bodyEl.update(content, loadScripts);
30103 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
30104 * @return {Roo.UpdateManager} The UpdateManager
30106 getUpdateManager : function(){
30107 return this.bodyEl.getUpdateManager();
30111 * Set a URL to be used to load the content for this TabPanelItem.
30112 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
30113 * @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)
30114 * @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)
30115 * @return {Roo.UpdateManager} The UpdateManager
30117 setUrl : function(url, params, loadOnce){
30118 if(this.refreshDelegate){
30119 this.un('activate', this.refreshDelegate);
30121 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
30122 this.on("activate", this.refreshDelegate);
30123 return this.bodyEl.getUpdateManager();
30127 _handleRefresh : function(url, params, loadOnce){
30128 if(!loadOnce || !this.loaded){
30129 var updater = this.bodyEl.getUpdateManager();
30130 updater.update(url, params, this._setLoaded.createDelegate(this));
30135 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
30136 * Will fail silently if the setUrl method has not been called.
30137 * This does not activate the panel, just updates its content.
30139 refresh : function(){
30140 if(this.refreshDelegate){
30141 this.loaded = false;
30142 this.refreshDelegate();
30147 _setLoaded : function(){
30148 this.loaded = true;
30152 closeClick : function(e){
30155 this.fireEvent("beforeclose", this, o);
30156 if(o.cancel !== true){
30157 this.tabPanel.removeTab(this.id);
30161 * The text displayed in the tooltip for the close icon.
30164 closeText : "Close this tab"
30168 Roo.TabPanel.prototype.createStrip = function(container){
30169 var strip = document.createElement("div");
30170 strip.className = "x-tabs-wrap";
30171 container.appendChild(strip);
30175 Roo.TabPanel.prototype.createStripList = function(strip){
30176 // div wrapper for retard IE
30177 // returns the "tr" element.
30178 strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
30179 '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
30180 '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
30181 return strip.firstChild.firstChild.firstChild.firstChild;
30184 Roo.TabPanel.prototype.createBody = function(container){
30185 var body = document.createElement("div");
30186 Roo.id(body, "tab-body");
30187 Roo.fly(body).addClass("x-tabs-body");
30188 container.appendChild(body);
30192 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
30193 var body = Roo.getDom(id);
30195 body = document.createElement("div");
30198 Roo.fly(body).addClass("x-tabs-item-body");
30199 bodyEl.insertBefore(body, bodyEl.firstChild);
30203 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
30204 var td = document.createElement("td");
30205 stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
30206 //stripEl.appendChild(td);
30208 td.className = "x-tabs-closable";
30209 if(!this.closeTpl){
30210 this.closeTpl = new Roo.Template(
30211 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30212 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
30213 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
30216 var el = this.closeTpl.overwrite(td, {"text": text});
30217 var close = el.getElementsByTagName("div")[0];
30218 var inner = el.getElementsByTagName("em")[0];
30219 return {"el": el, "close": close, "inner": inner};
30222 this.tabTpl = new Roo.Template(
30223 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
30224 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
30227 var el = this.tabTpl.overwrite(td, {"text": text});
30228 var inner = el.getElementsByTagName("em")[0];
30229 return {"el": el, "inner": inner};
30233 * Ext JS Library 1.1.1
30234 * Copyright(c) 2006-2007, Ext JS, LLC.
30236 * Originally Released Under LGPL - original licence link has changed is not relivant.
30239 * <script type="text/javascript">
30243 * @class Roo.Button
30244 * @extends Roo.util.Observable
30245 * Simple Button class
30246 * @cfg {String} text The button text
30247 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
30248 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
30249 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
30250 * @cfg {Object} scope The scope of the handler
30251 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
30252 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
30253 * @cfg {Boolean} hidden True to start hidden (defaults to false)
30254 * @cfg {Boolean} disabled True to start disabled (defaults to false)
30255 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
30256 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
30257 applies if enableToggle = true)
30258 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
30259 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
30260 an {@link Roo.util.ClickRepeater} config object (defaults to false).
30262 * Create a new button
30263 * @param {Object} config The config object
30265 Roo.Button = function(renderTo, config)
30269 renderTo = config.renderTo || false;
30272 Roo.apply(this, config);
30276 * Fires when this button is clicked
30277 * @param {Button} this
30278 * @param {EventObject} e The click event
30283 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
30284 * @param {Button} this
30285 * @param {Boolean} pressed
30290 * Fires when the mouse hovers over the button
30291 * @param {Button} this
30292 * @param {Event} e The event object
30294 'mouseover' : true,
30297 * Fires when the mouse exits the button
30298 * @param {Button} this
30299 * @param {Event} e The event object
30304 * Fires when the button is rendered
30305 * @param {Button} this
30310 this.menu = Roo.menu.MenuMgr.get(this.menu);
30312 // register listeners first!! - so render can be captured..
30313 Roo.util.Observable.call(this);
30315 this.render(renderTo);
30321 Roo.extend(Roo.Button, Roo.util.Observable, {
30327 * Read-only. True if this button is hidden
30332 * Read-only. True if this button is disabled
30337 * Read-only. True if this button is pressed (only if enableToggle = true)
30343 * @cfg {Number} tabIndex
30344 * The DOM tabIndex for this button (defaults to undefined)
30346 tabIndex : undefined,
30349 * @cfg {Boolean} enableToggle
30350 * True to enable pressed/not pressed toggling (defaults to false)
30352 enableToggle: false,
30354 * @cfg {Roo.menu.Menu} menu
30355 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
30359 * @cfg {String} menuAlign
30360 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
30362 menuAlign : "tl-bl?",
30365 * @cfg {String} iconCls
30366 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
30368 iconCls : undefined,
30370 * @cfg {String} type
30371 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
30376 menuClassTarget: 'tr',
30379 * @cfg {String} clickEvent
30380 * The type of event to map to the button's event handler (defaults to 'click')
30382 clickEvent : 'click',
30385 * @cfg {Boolean} handleMouseEvents
30386 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
30388 handleMouseEvents : true,
30391 * @cfg {String} tooltipType
30392 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
30394 tooltipType : 'qtip',
30397 * @cfg {String} cls
30398 * A CSS class to apply to the button's main element.
30402 * @cfg {Roo.Template} template (Optional)
30403 * An {@link Roo.Template} with which to create the Button's main element. This Template must
30404 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
30405 * require code modifications if required elements (e.g. a button) aren't present.
30409 render : function(renderTo){
30411 if(this.hideParent){
30412 this.parentEl = Roo.get(renderTo);
30414 if(!this.dhconfig){
30415 if(!this.template){
30416 if(!Roo.Button.buttonTemplate){
30417 // hideous table template
30418 Roo.Button.buttonTemplate = new Roo.Template(
30419 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
30420 '<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>',
30421 "</tr></tbody></table>");
30423 this.template = Roo.Button.buttonTemplate;
30425 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
30426 var btnEl = btn.child("button:first");
30427 btnEl.on('focus', this.onFocus, this);
30428 btnEl.on('blur', this.onBlur, this);
30430 btn.addClass(this.cls);
30433 btnEl.setStyle('background-image', 'url(' +this.icon +')');
30436 btnEl.addClass(this.iconCls);
30438 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
30441 if(this.tabIndex !== undefined){
30442 btnEl.dom.tabIndex = this.tabIndex;
30445 if(typeof this.tooltip == 'object'){
30446 Roo.QuickTips.tips(Roo.apply({
30450 btnEl.dom[this.tooltipType] = this.tooltip;
30454 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
30458 this.el.dom.id = this.el.id = this.id;
30461 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
30462 this.menu.on("show", this.onMenuShow, this);
30463 this.menu.on("hide", this.onMenuHide, this);
30465 btn.addClass("x-btn");
30466 if(Roo.isIE && !Roo.isIE7){
30467 this.autoWidth.defer(1, this);
30471 if(this.handleMouseEvents){
30472 btn.on("mouseover", this.onMouseOver, this);
30473 btn.on("mouseout", this.onMouseOut, this);
30474 btn.on("mousedown", this.onMouseDown, this);
30476 btn.on(this.clickEvent, this.onClick, this);
30477 //btn.on("mouseup", this.onMouseUp, this);
30484 Roo.ButtonToggleMgr.register(this);
30486 this.el.addClass("x-btn-pressed");
30489 var repeater = new Roo.util.ClickRepeater(btn,
30490 typeof this.repeat == "object" ? this.repeat : {}
30492 repeater.on("click", this.onClick, this);
30495 this.fireEvent('render', this);
30499 * Returns the button's underlying element
30500 * @return {Roo.Element} The element
30502 getEl : function(){
30507 * Destroys this Button and removes any listeners.
30509 destroy : function(){
30510 Roo.ButtonToggleMgr.unregister(this);
30511 this.el.removeAllListeners();
30512 this.purgeListeners();
30517 autoWidth : function(){
30519 this.el.setWidth("auto");
30520 if(Roo.isIE7 && Roo.isStrict){
30521 var ib = this.el.child('button');
30522 if(ib && ib.getWidth() > 20){
30524 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
30529 this.el.beginMeasure();
30531 if(this.el.getWidth() < this.minWidth){
30532 this.el.setWidth(this.minWidth);
30535 this.el.endMeasure();
30542 * Assigns this button's click handler
30543 * @param {Function} handler The function to call when the button is clicked
30544 * @param {Object} scope (optional) Scope for the function passed in
30546 setHandler : function(handler, scope){
30547 this.handler = handler;
30548 this.scope = scope;
30552 * Sets this button's text
30553 * @param {String} text The button text
30555 setText : function(text){
30558 this.el.child("td.x-btn-center button.x-btn-text").update(text);
30564 * Gets the text for this button
30565 * @return {String} The button text
30567 getText : function(){
30575 this.hidden = false;
30577 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
30585 this.hidden = true;
30587 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
30592 * Convenience function for boolean show/hide
30593 * @param {Boolean} visible True to show, false to hide
30595 setVisible: function(visible){
30604 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
30605 * @param {Boolean} state (optional) Force a particular state
30607 toggle : function(state){
30608 state = state === undefined ? !this.pressed : state;
30609 if(state != this.pressed){
30611 this.el.addClass("x-btn-pressed");
30612 this.pressed = true;
30613 this.fireEvent("toggle", this, true);
30615 this.el.removeClass("x-btn-pressed");
30616 this.pressed = false;
30617 this.fireEvent("toggle", this, false);
30619 if(this.toggleHandler){
30620 this.toggleHandler.call(this.scope || this, this, state);
30628 focus : function(){
30629 this.el.child('button:first').focus();
30633 * Disable this button
30635 disable : function(){
30637 this.el.addClass("x-btn-disabled");
30639 this.disabled = true;
30643 * Enable this button
30645 enable : function(){
30647 this.el.removeClass("x-btn-disabled");
30649 this.disabled = false;
30653 * Convenience function for boolean enable/disable
30654 * @param {Boolean} enabled True to enable, false to disable
30656 setDisabled : function(v){
30657 this[v !== true ? "enable" : "disable"]();
30661 onClick : function(e)
30664 e.preventDefault();
30669 if(!this.disabled){
30670 if(this.enableToggle){
30673 if(this.menu && !this.menu.isVisible()){
30674 this.menu.show(this.el, this.menuAlign);
30676 this.fireEvent("click", this, e);
30678 this.el.removeClass("x-btn-over");
30679 this.handler.call(this.scope || this, this, e);
30684 onMouseOver : function(e){
30685 if(!this.disabled){
30686 this.el.addClass("x-btn-over");
30687 this.fireEvent('mouseover', this, e);
30691 onMouseOut : function(e){
30692 if(!e.within(this.el, true)){
30693 this.el.removeClass("x-btn-over");
30694 this.fireEvent('mouseout', this, e);
30698 onFocus : function(e){
30699 if(!this.disabled){
30700 this.el.addClass("x-btn-focus");
30704 onBlur : function(e){
30705 this.el.removeClass("x-btn-focus");
30708 onMouseDown : function(e){
30709 if(!this.disabled && e.button == 0){
30710 this.el.addClass("x-btn-click");
30711 Roo.get(document).on('mouseup', this.onMouseUp, this);
30715 onMouseUp : function(e){
30717 this.el.removeClass("x-btn-click");
30718 Roo.get(document).un('mouseup', this.onMouseUp, this);
30722 onMenuShow : function(e){
30723 this.el.addClass("x-btn-menu-active");
30726 onMenuHide : function(e){
30727 this.el.removeClass("x-btn-menu-active");
30731 // Private utility class used by Button
30732 Roo.ButtonToggleMgr = function(){
30735 function toggleGroup(btn, state){
30737 var g = groups[btn.toggleGroup];
30738 for(var i = 0, l = g.length; i < l; i++){
30740 g[i].toggle(false);
30747 register : function(btn){
30748 if(!btn.toggleGroup){
30751 var g = groups[btn.toggleGroup];
30753 g = groups[btn.toggleGroup] = [];
30756 btn.on("toggle", toggleGroup);
30759 unregister : function(btn){
30760 if(!btn.toggleGroup){
30763 var g = groups[btn.toggleGroup];
30766 btn.un("toggle", toggleGroup);
30772 * Ext JS Library 1.1.1
30773 * Copyright(c) 2006-2007, Ext JS, LLC.
30775 * Originally Released Under LGPL - original licence link has changed is not relivant.
30778 * <script type="text/javascript">
30782 * @class Roo.SplitButton
30783 * @extends Roo.Button
30784 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
30785 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
30786 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
30787 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
30788 * @cfg {String} arrowTooltip The title attribute of the arrow
30790 * Create a new menu button
30791 * @param {String/HTMLElement/Element} renderTo The element to append the button to
30792 * @param {Object} config The config object
30794 Roo.SplitButton = function(renderTo, config){
30795 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
30797 * @event arrowclick
30798 * Fires when this button's arrow is clicked
30799 * @param {SplitButton} this
30800 * @param {EventObject} e The click event
30802 this.addEvents({"arrowclick":true});
30805 Roo.extend(Roo.SplitButton, Roo.Button, {
30806 render : function(renderTo){
30807 // this is one sweet looking template!
30808 var tpl = new Roo.Template(
30809 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
30810 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
30811 '<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>',
30812 "</tbody></table></td><td>",
30813 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
30814 '<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>',
30815 "</tbody></table></td></tr></table>"
30817 var btn = tpl.append(renderTo, [this.text, this.type], true);
30818 var btnEl = btn.child("button");
30820 btn.addClass(this.cls);
30823 btnEl.setStyle('background-image', 'url(' +this.icon +')');
30826 btnEl.addClass(this.iconCls);
30828 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
30832 if(this.handleMouseEvents){
30833 btn.on("mouseover", this.onMouseOver, this);
30834 btn.on("mouseout", this.onMouseOut, this);
30835 btn.on("mousedown", this.onMouseDown, this);
30836 btn.on("mouseup", this.onMouseUp, this);
30838 btn.on(this.clickEvent, this.onClick, this);
30840 if(typeof this.tooltip == 'object'){
30841 Roo.QuickTips.tips(Roo.apply({
30845 btnEl.dom[this.tooltipType] = this.tooltip;
30848 if(this.arrowTooltip){
30849 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
30858 this.el.addClass("x-btn-pressed");
30860 if(Roo.isIE && !Roo.isIE7){
30861 this.autoWidth.defer(1, this);
30866 this.menu.on("show", this.onMenuShow, this);
30867 this.menu.on("hide", this.onMenuHide, this);
30869 this.fireEvent('render', this);
30873 autoWidth : function(){
30875 var tbl = this.el.child("table:first");
30876 var tbl2 = this.el.child("table:last");
30877 this.el.setWidth("auto");
30878 tbl.setWidth("auto");
30879 if(Roo.isIE7 && Roo.isStrict){
30880 var ib = this.el.child('button:first');
30881 if(ib && ib.getWidth() > 20){
30883 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
30888 this.el.beginMeasure();
30890 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
30891 tbl.setWidth(this.minWidth-tbl2.getWidth());
30894 this.el.endMeasure();
30897 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
30901 * Sets this button's click handler
30902 * @param {Function} handler The function to call when the button is clicked
30903 * @param {Object} scope (optional) Scope for the function passed above
30905 setHandler : function(handler, scope){
30906 this.handler = handler;
30907 this.scope = scope;
30911 * Sets this button's arrow click handler
30912 * @param {Function} handler The function to call when the arrow is clicked
30913 * @param {Object} scope (optional) Scope for the function passed above
30915 setArrowHandler : function(handler, scope){
30916 this.arrowHandler = handler;
30917 this.scope = scope;
30923 focus : function(){
30925 this.el.child("button:first").focus();
30930 onClick : function(e){
30931 e.preventDefault();
30932 if(!this.disabled){
30933 if(e.getTarget(".x-btn-menu-arrow-wrap")){
30934 if(this.menu && !this.menu.isVisible()){
30935 this.menu.show(this.el, this.menuAlign);
30937 this.fireEvent("arrowclick", this, e);
30938 if(this.arrowHandler){
30939 this.arrowHandler.call(this.scope || this, this, e);
30942 this.fireEvent("click", this, e);
30944 this.handler.call(this.scope || this, this, e);
30950 onMouseDown : function(e){
30951 if(!this.disabled){
30952 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
30956 onMouseUp : function(e){
30957 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
30962 // backwards compat
30963 Roo.MenuButton = Roo.SplitButton;/*
30965 * Ext JS Library 1.1.1
30966 * Copyright(c) 2006-2007, Ext JS, LLC.
30968 * Originally Released Under LGPL - original licence link has changed is not relivant.
30971 * <script type="text/javascript">
30975 * @class Roo.Toolbar
30976 * @children Roo.Toolbar.Item Roo.form.Field
30977 * Basic Toolbar class.
30979 * Creates a new Toolbar
30980 * @param {Object} container The config object
30982 Roo.Toolbar = function(container, buttons, config)
30984 /// old consturctor format still supported..
30985 if(container instanceof Array){ // omit the container for later rendering
30986 buttons = container;
30990 if (typeof(container) == 'object' && container.xtype) {
30991 config = container;
30992 container = config.container;
30993 buttons = config.buttons || []; // not really - use items!!
30996 if (config && config.items) {
30997 xitems = config.items;
30998 delete config.items;
31000 Roo.apply(this, config);
31001 this.buttons = buttons;
31004 this.render(container);
31006 this.xitems = xitems;
31007 Roo.each(xitems, function(b) {
31013 Roo.Toolbar.prototype = {
31015 * @cfg {Array} items
31016 * array of button configs or elements to add (will be converted to a MixedCollection)
31020 * @cfg {String/HTMLElement/Element} container
31021 * The id or element that will contain the toolbar
31024 render : function(ct){
31025 this.el = Roo.get(ct);
31027 this.el.addClass(this.cls);
31029 // using a table allows for vertical alignment
31030 // 100% width is needed by Safari...
31031 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
31032 this.tr = this.el.child("tr", true);
31034 this.items = new Roo.util.MixedCollection(false, function(o){
31035 return o.id || ("item" + (++autoId));
31038 this.add.apply(this, this.buttons);
31039 delete this.buttons;
31044 * Adds element(s) to the toolbar -- this function takes a variable number of
31045 * arguments of mixed type and adds them to the toolbar.
31046 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
31048 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
31049 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
31050 * <li>Field: Any form field (equivalent to {@link #addField})</li>
31051 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
31052 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
31053 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
31054 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
31055 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
31056 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
31058 * @param {Mixed} arg2
31059 * @param {Mixed} etc.
31062 var a = arguments, l = a.length;
31063 for(var i = 0; i < l; i++){
31068 _add : function(el) {
31071 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
31074 if (el.applyTo){ // some kind of form field
31075 return this.addField(el);
31077 if (el.render){ // some kind of Toolbar.Item
31078 return this.addItem(el);
31080 if (typeof el == "string"){ // string
31081 if(el == "separator" || el == "-"){
31082 return this.addSeparator();
31085 return this.addSpacer();
31088 return this.addFill();
31090 return this.addText(el);
31093 if(el.tagName){ // element
31094 return this.addElement(el);
31096 if(typeof el == "object"){ // must be button config?
31097 return this.addButton(el);
31099 // and now what?!?!
31105 * Add an Xtype element
31106 * @param {Object} xtype Xtype Object
31107 * @return {Object} created Object
31109 addxtype : function(e){
31110 return this.add(e);
31114 * Returns the Element for this toolbar.
31115 * @return {Roo.Element}
31117 getEl : function(){
31123 * @return {Roo.Toolbar.Item} The separator item
31125 addSeparator : function(){
31126 return this.addItem(new Roo.Toolbar.Separator());
31130 * Adds a spacer element
31131 * @return {Roo.Toolbar.Spacer} The spacer item
31133 addSpacer : function(){
31134 return this.addItem(new Roo.Toolbar.Spacer());
31138 * Adds a fill element that forces subsequent additions to the right side of the toolbar
31139 * @return {Roo.Toolbar.Fill} The fill item
31141 addFill : function(){
31142 return this.addItem(new Roo.Toolbar.Fill());
31146 * Adds any standard HTML element to the toolbar
31147 * @param {String/HTMLElement/Element} el The element or id of the element to add
31148 * @return {Roo.Toolbar.Item} The element's item
31150 addElement : function(el){
31151 return this.addItem(new Roo.Toolbar.Item(el));
31154 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
31155 * @type Roo.util.MixedCollection
31160 * Adds any Toolbar.Item or subclass
31161 * @param {Roo.Toolbar.Item} item
31162 * @return {Roo.Toolbar.Item} The item
31164 addItem : function(item){
31165 var td = this.nextBlock();
31167 this.items.add(item);
31172 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
31173 * @param {Object/Array} config A button config or array of configs
31174 * @return {Roo.Toolbar.Button/Array}
31176 addButton : function(config){
31177 if(config instanceof Array){
31179 for(var i = 0, len = config.length; i < len; i++) {
31180 buttons.push(this.addButton(config[i]));
31185 if(!(config instanceof Roo.Toolbar.Button)){
31187 new Roo.Toolbar.SplitButton(config) :
31188 new Roo.Toolbar.Button(config);
31190 var td = this.nextBlock();
31197 * Adds text to the toolbar
31198 * @param {String} text The text to add
31199 * @return {Roo.Toolbar.Item} The element's item
31201 addText : function(text){
31202 return this.addItem(new Roo.Toolbar.TextItem(text));
31206 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
31207 * @param {Number} index The index where the item is to be inserted
31208 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
31209 * @return {Roo.Toolbar.Button/Item}
31211 insertButton : function(index, item){
31212 if(item instanceof Array){
31214 for(var i = 0, len = item.length; i < len; i++) {
31215 buttons.push(this.insertButton(index + i, item[i]));
31219 if (!(item instanceof Roo.Toolbar.Button)){
31220 item = new Roo.Toolbar.Button(item);
31222 var td = document.createElement("td");
31223 this.tr.insertBefore(td, this.tr.childNodes[index]);
31225 this.items.insert(index, item);
31230 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
31231 * @param {Object} config
31232 * @return {Roo.Toolbar.Item} The element's item
31234 addDom : function(config, returnEl){
31235 var td = this.nextBlock();
31236 Roo.DomHelper.overwrite(td, config);
31237 var ti = new Roo.Toolbar.Item(td.firstChild);
31239 this.items.add(ti);
31244 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
31245 * @type Roo.util.MixedCollection
31250 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
31251 * Note: the field should not have been rendered yet. For a field that has already been
31252 * rendered, use {@link #addElement}.
31253 * @param {Roo.form.Field} field
31254 * @return {Roo.ToolbarItem}
31258 addField : function(field) {
31259 if (!this.fields) {
31261 this.fields = new Roo.util.MixedCollection(false, function(o){
31262 return o.id || ("item" + (++autoId));
31267 var td = this.nextBlock();
31269 var ti = new Roo.Toolbar.Item(td.firstChild);
31271 this.items.add(ti);
31272 this.fields.add(field);
31283 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
31284 this.el.child('div').hide();
31292 this.el.child('div').show();
31296 nextBlock : function(){
31297 var td = document.createElement("td");
31298 this.tr.appendChild(td);
31303 destroy : function(){
31304 if(this.items){ // rendered?
31305 Roo.destroy.apply(Roo, this.items.items);
31307 if(this.fields){ // rendered?
31308 Roo.destroy.apply(Roo, this.fields.items);
31310 Roo.Element.uncache(this.el, this.tr);
31315 * @class Roo.Toolbar.Item
31316 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
31318 * Creates a new Item
31319 * @param {HTMLElement} el
31321 Roo.Toolbar.Item = function(el){
31323 if (typeof (el.xtype) != 'undefined') {
31328 this.el = Roo.getDom(el);
31329 this.id = Roo.id(this.el);
31330 this.hidden = false;
31335 * Fires when the button is rendered
31336 * @param {Button} this
31340 Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
31342 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
31343 //Roo.Toolbar.Item.prototype = {
31346 * Get this item's HTML Element
31347 * @return {HTMLElement}
31349 getEl : function(){
31354 render : function(td){
31357 td.appendChild(this.el);
31359 this.fireEvent('render', this);
31363 * Removes and destroys this item.
31365 destroy : function(){
31366 this.td.parentNode.removeChild(this.td);
31373 this.hidden = false;
31374 this.td.style.display = "";
31381 this.hidden = true;
31382 this.td.style.display = "none";
31386 * Convenience function for boolean show/hide.
31387 * @param {Boolean} visible true to show/false to hide
31389 setVisible: function(visible){
31398 * Try to focus this item.
31400 focus : function(){
31401 Roo.fly(this.el).focus();
31405 * Disables this item.
31407 disable : function(){
31408 Roo.fly(this.td).addClass("x-item-disabled");
31409 this.disabled = true;
31410 this.el.disabled = true;
31414 * Enables this item.
31416 enable : function(){
31417 Roo.fly(this.td).removeClass("x-item-disabled");
31418 this.disabled = false;
31419 this.el.disabled = false;
31425 * @class Roo.Toolbar.Separator
31426 * @extends Roo.Toolbar.Item
31427 * A simple toolbar separator class
31429 * Creates a new Separator
31431 Roo.Toolbar.Separator = function(cfg){
31433 var s = document.createElement("span");
31434 s.className = "ytb-sep";
31439 Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
31441 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
31442 enable:Roo.emptyFn,
31443 disable:Roo.emptyFn,
31448 * @class Roo.Toolbar.Spacer
31449 * @extends Roo.Toolbar.Item
31450 * A simple element that adds extra horizontal space to a toolbar.
31452 * Creates a new Spacer
31454 Roo.Toolbar.Spacer = function(cfg){
31455 var s = document.createElement("div");
31456 s.className = "ytb-spacer";
31460 Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
31462 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
31463 enable:Roo.emptyFn,
31464 disable:Roo.emptyFn,
31469 * @class Roo.Toolbar.Fill
31470 * @extends Roo.Toolbar.Spacer
31471 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
31473 * Creates a new Spacer
31475 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
31477 render : function(td){
31478 td.style.width = '100%';
31479 Roo.Toolbar.Fill.superclass.render.call(this, td);
31484 * @class Roo.Toolbar.TextItem
31485 * @extends Roo.Toolbar.Item
31486 * A simple class that renders text directly into a toolbar.
31488 * Creates a new TextItem
31489 * @cfg {string} text
31491 Roo.Toolbar.TextItem = function(cfg){
31492 var text = cfg || "";
31493 if (typeof(cfg) == 'object') {
31494 text = cfg.text || "";
31498 var s = document.createElement("span");
31499 s.className = "ytb-text";
31500 s.innerHTML = text;
31505 Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg || s);
31507 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
31510 enable:Roo.emptyFn,
31511 disable:Roo.emptyFn,
31514 * Shows this button
31517 this.hidden = false;
31518 this.el.style.display = "";
31522 * Hides this button
31525 this.hidden = true;
31526 this.el.style.display = "none";
31532 * @class Roo.Toolbar.Button
31533 * @extends Roo.Button
31534 * A button that renders into a toolbar.
31536 * Creates a new Button
31537 * @param {Object} config A standard {@link Roo.Button} config object
31539 Roo.Toolbar.Button = function(config){
31540 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
31542 Roo.extend(Roo.Toolbar.Button, Roo.Button,
31546 render : function(td){
31548 Roo.Toolbar.Button.superclass.render.call(this, td);
31552 * Removes and destroys this button
31554 destroy : function(){
31555 Roo.Toolbar.Button.superclass.destroy.call(this);
31556 this.td.parentNode.removeChild(this.td);
31560 * Shows this button
31563 this.hidden = false;
31564 this.td.style.display = "";
31568 * Hides this button
31571 this.hidden = true;
31572 this.td.style.display = "none";
31576 * Disables this item
31578 disable : function(){
31579 Roo.fly(this.td).addClass("x-item-disabled");
31580 this.disabled = true;
31584 * Enables this item
31586 enable : function(){
31587 Roo.fly(this.td).removeClass("x-item-disabled");
31588 this.disabled = false;
31591 // backwards compat
31592 Roo.ToolbarButton = Roo.Toolbar.Button;
31595 * @class Roo.Toolbar.SplitButton
31596 * @extends Roo.SplitButton
31597 * A menu button that renders into a toolbar.
31599 * Creates a new SplitButton
31600 * @param {Object} config A standard {@link Roo.SplitButton} config object
31602 Roo.Toolbar.SplitButton = function(config){
31603 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
31605 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
31606 render : function(td){
31608 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
31612 * Removes and destroys this button
31614 destroy : function(){
31615 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
31616 this.td.parentNode.removeChild(this.td);
31620 * Shows this button
31623 this.hidden = false;
31624 this.td.style.display = "";
31628 * Hides this button
31631 this.hidden = true;
31632 this.td.style.display = "none";
31636 // backwards compat
31637 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
31639 * Ext JS Library 1.1.1
31640 * Copyright(c) 2006-2007, Ext JS, LLC.
31642 * Originally Released Under LGPL - original licence link has changed is not relivant.
31645 * <script type="text/javascript">
31649 * @class Roo.PagingToolbar
31650 * @extends Roo.Toolbar
31651 * @children Roo.Toolbar.Item Roo.form.Field
31652 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
31654 * Create a new PagingToolbar
31655 * @param {Object} config The config object
31657 Roo.PagingToolbar = function(el, ds, config)
31659 // old args format still supported... - xtype is prefered..
31660 if (typeof(el) == 'object' && el.xtype) {
31661 // created from xtype...
31663 ds = el.dataSource;
31664 el = config.container;
31667 if (config.items) {
31668 items = config.items;
31672 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
31675 this.renderButtons(this.el);
31678 // supprot items array.
31680 Roo.each(items, function(e) {
31681 this.add(Roo.factory(e));
31686 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
31689 * @cfg {String/HTMLElement/Element} container
31690 * container The id or element that will contain the toolbar
31693 * @cfg {Boolean} displayInfo
31694 * True to display the displayMsg (defaults to false)
31699 * @cfg {Number} pageSize
31700 * The number of records to display per page (defaults to 20)
31704 * @cfg {String} displayMsg
31705 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
31707 displayMsg : 'Displaying {0} - {1} of {2}',
31709 * @cfg {String} emptyMsg
31710 * The message to display when no records are found (defaults to "No data to display")
31712 emptyMsg : 'No data to display',
31714 * Customizable piece of the default paging text (defaults to "Page")
31717 beforePageText : "Page",
31719 * Customizable piece of the default paging text (defaults to "of %0")
31722 afterPageText : "of {0}",
31724 * Customizable piece of the default paging text (defaults to "First Page")
31727 firstText : "First Page",
31729 * Customizable piece of the default paging text (defaults to "Previous Page")
31732 prevText : "Previous Page",
31734 * Customizable piece of the default paging text (defaults to "Next Page")
31737 nextText : "Next Page",
31739 * Customizable piece of the default paging text (defaults to "Last Page")
31742 lastText : "Last Page",
31744 * Customizable piece of the default paging text (defaults to "Refresh")
31747 refreshText : "Refresh",
31750 renderButtons : function(el){
31751 Roo.PagingToolbar.superclass.render.call(this, el);
31752 this.first = this.addButton({
31753 tooltip: this.firstText,
31754 cls: "x-btn-icon x-grid-page-first",
31756 handler: this.onClick.createDelegate(this, ["first"])
31758 this.prev = this.addButton({
31759 tooltip: this.prevText,
31760 cls: "x-btn-icon x-grid-page-prev",
31762 handler: this.onClick.createDelegate(this, ["prev"])
31764 //this.addSeparator();
31765 this.add(this.beforePageText);
31766 this.field = Roo.get(this.addDom({
31771 cls: "x-grid-page-number"
31773 this.field.on("keydown", this.onPagingKeydown, this);
31774 this.field.on("focus", function(){this.dom.select();});
31775 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
31776 this.field.setHeight(18);
31777 //this.addSeparator();
31778 this.next = this.addButton({
31779 tooltip: this.nextText,
31780 cls: "x-btn-icon x-grid-page-next",
31782 handler: this.onClick.createDelegate(this, ["next"])
31784 this.last = this.addButton({
31785 tooltip: this.lastText,
31786 cls: "x-btn-icon x-grid-page-last",
31788 handler: this.onClick.createDelegate(this, ["last"])
31790 //this.addSeparator();
31791 this.loading = this.addButton({
31792 tooltip: this.refreshText,
31793 cls: "x-btn-icon x-grid-loading",
31794 handler: this.onClick.createDelegate(this, ["refresh"])
31797 if(this.displayInfo){
31798 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
31803 updateInfo : function(){
31804 if(this.displayEl){
31805 var count = this.ds.getCount();
31806 var msg = count == 0 ?
31810 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
31812 this.displayEl.update(msg);
31817 onLoad : function(ds, r, o){
31818 this.cursor = o.params ? o.params.start : 0;
31819 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
31821 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
31822 this.field.dom.value = ap;
31823 this.first.setDisabled(ap == 1);
31824 this.prev.setDisabled(ap == 1);
31825 this.next.setDisabled(ap == ps);
31826 this.last.setDisabled(ap == ps);
31827 this.loading.enable();
31832 getPageData : function(){
31833 var total = this.ds.getTotalCount();
31836 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
31837 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
31842 onLoadError : function(){
31843 this.loading.enable();
31847 onPagingKeydown : function(e){
31848 var k = e.getKey();
31849 var d = this.getPageData();
31851 var v = this.field.dom.value, pageNum;
31852 if(!v || isNaN(pageNum = parseInt(v, 10))){
31853 this.field.dom.value = d.activePage;
31856 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
31857 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
31860 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))
31862 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
31863 this.field.dom.value = pageNum;
31864 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
31867 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
31869 var v = this.field.dom.value, pageNum;
31870 var increment = (e.shiftKey) ? 10 : 1;
31871 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
31874 if(!v || isNaN(pageNum = parseInt(v, 10))) {
31875 this.field.dom.value = d.activePage;
31878 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
31880 this.field.dom.value = parseInt(v, 10) + increment;
31881 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
31882 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
31889 beforeLoad : function(){
31891 this.loading.disable();
31896 onClick : function(which){
31900 ds.load({params:{start: 0, limit: this.pageSize}});
31903 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
31906 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
31909 var total = ds.getTotalCount();
31910 var extra = total % this.pageSize;
31911 var lastStart = extra ? (total - extra) : total-this.pageSize;
31912 ds.load({params:{start: lastStart, limit: this.pageSize}});
31915 ds.load({params:{start: this.cursor, limit: this.pageSize}});
31921 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
31922 * @param {Roo.data.Store} store The data store to unbind
31924 unbind : function(ds){
31925 ds.un("beforeload", this.beforeLoad, this);
31926 ds.un("load", this.onLoad, this);
31927 ds.un("loadexception", this.onLoadError, this);
31928 ds.un("remove", this.updateInfo, this);
31929 ds.un("add", this.updateInfo, this);
31930 this.ds = undefined;
31934 * Binds the paging toolbar to the specified {@link Roo.data.Store}
31935 * @param {Roo.data.Store} store The data store to bind
31937 bind : function(ds){
31938 ds.on("beforeload", this.beforeLoad, this);
31939 ds.on("load", this.onLoad, this);
31940 ds.on("loadexception", this.onLoadError, this);
31941 ds.on("remove", this.updateInfo, this);
31942 ds.on("add", this.updateInfo, this);
31947 * Ext JS Library 1.1.1
31948 * Copyright(c) 2006-2007, Ext JS, LLC.
31950 * Originally Released Under LGPL - original licence link has changed is not relivant.
31953 * <script type="text/javascript">
31957 * @class Roo.Resizable
31958 * @extends Roo.util.Observable
31959 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
31960 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
31961 * 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
31962 * the element will be wrapped for you automatically.</p>
31963 * <p>Here is the list of valid resize handles:</p>
31966 ------ -------------------
31975 'hd' horizontal drag
31978 * <p>Here's an example showing the creation of a typical Resizable:</p>
31980 var resizer = new Roo.Resizable("element-id", {
31988 resizer.on("resize", myHandler);
31990 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
31991 * resizer.east.setDisplayed(false);</p>
31992 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
31993 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
31994 * resize operation's new size (defaults to [0, 0])
31995 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
31996 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
31997 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
31998 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
31999 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
32000 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
32001 * @cfg {Number} width The width of the element in pixels (defaults to null)
32002 * @cfg {Number} height The height of the element in pixels (defaults to null)
32003 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
32004 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
32005 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
32006 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
32007 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
32008 * in favor of the handles config option (defaults to false)
32009 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
32010 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
32011 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
32012 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
32013 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
32014 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
32015 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
32016 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
32017 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
32018 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
32019 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
32021 * Create a new resizable component
32022 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
32023 * @param {Object} config configuration options
32025 Roo.Resizable = function(el, config)
32027 this.el = Roo.get(el);
32029 if(config && config.wrap){
32030 config.resizeChild = this.el;
32031 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
32032 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
32033 this.el.setStyle("overflow", "hidden");
32034 this.el.setPositioning(config.resizeChild.getPositioning());
32035 config.resizeChild.clearPositioning();
32036 if(!config.width || !config.height){
32037 var csize = config.resizeChild.getSize();
32038 this.el.setSize(csize.width, csize.height);
32040 if(config.pinned && !config.adjustments){
32041 config.adjustments = "auto";
32045 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
32046 this.proxy.unselectable();
32047 this.proxy.enableDisplayMode('block');
32049 Roo.apply(this, config);
32052 this.disableTrackOver = true;
32053 this.el.addClass("x-resizable-pinned");
32055 // if the element isn't positioned, make it relative
32056 var position = this.el.getStyle("position");
32057 if(position != "absolute" && position != "fixed"){
32058 this.el.setStyle("position", "relative");
32060 if(!this.handles){ // no handles passed, must be legacy style
32061 this.handles = 's,e,se';
32062 if(this.multiDirectional){
32063 this.handles += ',n,w';
32066 if(this.handles == "all"){
32067 this.handles = "n s e w ne nw se sw";
32069 var hs = this.handles.split(/\s*?[,;]\s*?| /);
32070 var ps = Roo.Resizable.positions;
32071 for(var i = 0, len = hs.length; i < len; i++){
32072 if(hs[i] && ps[hs[i]]){
32073 var pos = ps[hs[i]];
32074 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
32078 this.corner = this.southeast;
32080 // updateBox = the box can move..
32081 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
32082 this.updateBox = true;
32085 this.activeHandle = null;
32087 if(this.resizeChild){
32088 if(typeof this.resizeChild == "boolean"){
32089 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
32091 this.resizeChild = Roo.get(this.resizeChild, true);
32095 if(this.adjustments == "auto"){
32096 var rc = this.resizeChild;
32097 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
32098 if(rc && (hw || hn)){
32099 rc.position("relative");
32100 rc.setLeft(hw ? hw.el.getWidth() : 0);
32101 rc.setTop(hn ? hn.el.getHeight() : 0);
32103 this.adjustments = [
32104 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
32105 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
32109 if(this.draggable){
32110 this.dd = this.dynamic ?
32111 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
32112 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
32118 * @event beforeresize
32119 * Fired before resize is allowed. Set enabled to false to cancel resize.
32120 * @param {Roo.Resizable} this
32121 * @param {Roo.EventObject} e The mousedown event
32123 "beforeresize" : true,
32126 * Fired a resizing.
32127 * @param {Roo.Resizable} this
32128 * @param {Number} x The new x position
32129 * @param {Number} y The new y position
32130 * @param {Number} w The new w width
32131 * @param {Number} h The new h hight
32132 * @param {Roo.EventObject} e The mouseup event
32137 * Fired after a resize.
32138 * @param {Roo.Resizable} this
32139 * @param {Number} width The new width
32140 * @param {Number} height The new height
32141 * @param {Roo.EventObject} e The mouseup event
32146 if(this.width !== null && this.height !== null){
32147 this.resizeTo(this.width, this.height);
32149 this.updateChildSize();
32152 this.el.dom.style.zoom = 1;
32154 Roo.Resizable.superclass.constructor.call(this);
32157 Roo.extend(Roo.Resizable, Roo.util.Observable, {
32158 resizeChild : false,
32159 adjustments : [0, 0],
32169 multiDirectional : false,
32170 disableTrackOver : false,
32171 easing : 'easeOutStrong',
32172 widthIncrement : 0,
32173 heightIncrement : 0,
32177 preserveRatio : false,
32178 transparent: false,
32184 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
32186 constrainTo: undefined,
32188 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
32190 resizeRegion: undefined,
32194 * Perform a manual resize
32195 * @param {Number} width
32196 * @param {Number} height
32198 resizeTo : function(width, height){
32199 this.el.setSize(width, height);
32200 this.updateChildSize();
32201 this.fireEvent("resize", this, width, height, null);
32205 startSizing : function(e, handle){
32206 this.fireEvent("beforeresize", this, e);
32207 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
32210 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
32211 this.overlay.unselectable();
32212 this.overlay.enableDisplayMode("block");
32213 this.overlay.on("mousemove", this.onMouseMove, this);
32214 this.overlay.on("mouseup", this.onMouseUp, this);
32216 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
32218 this.resizing = true;
32219 this.startBox = this.el.getBox();
32220 this.startPoint = e.getXY();
32221 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
32222 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
32224 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
32225 this.overlay.show();
32227 if(this.constrainTo) {
32228 var ct = Roo.get(this.constrainTo);
32229 this.resizeRegion = ct.getRegion().adjust(
32230 ct.getFrameWidth('t'),
32231 ct.getFrameWidth('l'),
32232 -ct.getFrameWidth('b'),
32233 -ct.getFrameWidth('r')
32237 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
32239 this.proxy.setBox(this.startBox);
32241 this.proxy.setStyle('visibility', 'visible');
32247 onMouseDown : function(handle, e){
32250 this.activeHandle = handle;
32251 this.startSizing(e, handle);
32256 onMouseUp : function(e){
32257 var size = this.resizeElement();
32258 this.resizing = false;
32260 this.overlay.hide();
32262 this.fireEvent("resize", this, size.width, size.height, e);
32266 updateChildSize : function(){
32268 if(this.resizeChild){
32270 var child = this.resizeChild;
32271 var adj = this.adjustments;
32272 if(el.dom.offsetWidth){
32273 var b = el.getSize(true);
32274 child.setSize(b.width+adj[0], b.height+adj[1]);
32276 // Second call here for IE
32277 // The first call enables instant resizing and
32278 // the second call corrects scroll bars if they
32281 setTimeout(function(){
32282 if(el.dom.offsetWidth){
32283 var b = el.getSize(true);
32284 child.setSize(b.width+adj[0], b.height+adj[1]);
32292 snap : function(value, inc, min){
32293 if(!inc || !value) {
32296 var newValue = value;
32297 var m = value % inc;
32300 newValue = value + (inc-m);
32302 newValue = value - m;
32305 return Math.max(min, newValue);
32309 resizeElement : function(){
32310 var box = this.proxy.getBox();
32311 if(this.updateBox){
32312 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
32314 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
32316 this.updateChildSize();
32324 constrain : function(v, diff, m, mx){
32327 }else if(v - diff > mx){
32334 onMouseMove : function(e){
32337 try{// try catch so if something goes wrong the user doesn't get hung
32339 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
32343 //var curXY = this.startPoint;
32344 var curSize = this.curSize || this.startBox;
32345 var x = this.startBox.x, y = this.startBox.y;
32346 var ox = x, oy = y;
32347 var w = curSize.width, h = curSize.height;
32348 var ow = w, oh = h;
32349 var mw = this.minWidth, mh = this.minHeight;
32350 var mxw = this.maxWidth, mxh = this.maxHeight;
32351 var wi = this.widthIncrement;
32352 var hi = this.heightIncrement;
32354 var eventXY = e.getXY();
32355 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
32356 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
32358 var pos = this.activeHandle.position;
32363 w = Math.min(Math.max(mw, w), mxw);
32368 h = Math.min(Math.max(mh, h), mxh);
32373 w = Math.min(Math.max(mw, w), mxw);
32374 h = Math.min(Math.max(mh, h), mxh);
32377 diffY = this.constrain(h, diffY, mh, mxh);
32384 var adiffX = Math.abs(diffX);
32385 var sub = (adiffX % wi); // how much
32386 if (sub > (wi/2)) { // far enough to snap
32387 diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
32389 // remove difference..
32390 diffX = (diffX > 0) ? diffX-sub : diffX+sub;
32394 x = Math.max(this.minX, x);
32397 diffX = this.constrain(w, diffX, mw, mxw);
32403 w = Math.min(Math.max(mw, w), mxw);
32404 diffY = this.constrain(h, diffY, mh, mxh);
32409 diffX = this.constrain(w, diffX, mw, mxw);
32410 diffY = this.constrain(h, diffY, mh, mxh);
32417 diffX = this.constrain(w, diffX, mw, mxw);
32419 h = Math.min(Math.max(mh, h), mxh);
32425 var sw = this.snap(w, wi, mw);
32426 var sh = this.snap(h, hi, mh);
32427 if(sw != w || sh != h){
32450 if(this.preserveRatio){
32455 h = Math.min(Math.max(mh, h), mxh);
32460 w = Math.min(Math.max(mw, w), mxw);
32465 w = Math.min(Math.max(mw, w), mxw);
32471 w = Math.min(Math.max(mw, w), mxw);
32477 h = Math.min(Math.max(mh, h), mxh);
32485 h = Math.min(Math.max(mh, h), mxh);
32495 h = Math.min(Math.max(mh, h), mxh);
32503 if (pos == 'hdrag') {
32506 this.proxy.setBounds(x, y, w, h);
32508 this.resizeElement();
32512 this.fireEvent("resizing", this, x, y, w, h, e);
32516 handleOver : function(){
32518 this.el.addClass("x-resizable-over");
32523 handleOut : function(){
32524 if(!this.resizing){
32525 this.el.removeClass("x-resizable-over");
32530 * Returns the element this component is bound to.
32531 * @return {Roo.Element}
32533 getEl : function(){
32538 * Returns the resizeChild element (or null).
32539 * @return {Roo.Element}
32541 getResizeChild : function(){
32542 return this.resizeChild;
32544 groupHandler : function()
32549 * Destroys this resizable. If the element was wrapped and
32550 * removeEl is not true then the element remains.
32551 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
32553 destroy : function(removeEl){
32554 this.proxy.remove();
32556 this.overlay.removeAllListeners();
32557 this.overlay.remove();
32559 var ps = Roo.Resizable.positions;
32561 if(typeof ps[k] != "function" && this[ps[k]]){
32562 var h = this[ps[k]];
32563 h.el.removeAllListeners();
32568 this.el.update("");
32575 // hash to map config positions to true positions
32576 Roo.Resizable.positions = {
32577 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
32582 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
32584 // only initialize the template if resizable is used
32585 var tpl = Roo.DomHelper.createTemplate(
32586 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
32589 Roo.Resizable.Handle.prototype.tpl = tpl;
32591 this.position = pos;
32593 // show north drag fro topdra
32594 var handlepos = pos == 'hdrag' ? 'north' : pos;
32596 this.el = this.tpl.append(rz.el.dom, [handlepos], true);
32597 if (pos == 'hdrag') {
32598 this.el.setStyle('cursor', 'pointer');
32600 this.el.unselectable();
32602 this.el.setOpacity(0);
32604 this.el.on("mousedown", this.onMouseDown, this);
32605 if(!disableTrackOver){
32606 this.el.on("mouseover", this.onMouseOver, this);
32607 this.el.on("mouseout", this.onMouseOut, this);
32612 Roo.Resizable.Handle.prototype = {
32613 afterResize : function(rz){
32618 onMouseDown : function(e){
32619 this.rz.onMouseDown(this, e);
32622 onMouseOver : function(e){
32623 this.rz.handleOver(this, e);
32626 onMouseOut : function(e){
32627 this.rz.handleOut(this, e);
32631 * Ext JS Library 1.1.1
32632 * Copyright(c) 2006-2007, Ext JS, LLC.
32634 * Originally Released Under LGPL - original licence link has changed is not relivant.
32637 * <script type="text/javascript">
32641 * @class Roo.Editor
32642 * @extends Roo.Component
32643 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
32645 * Create a new Editor
32646 * @param {Roo.form.Field} field The Field object (or descendant)
32647 * @param {Object} config The config object
32649 Roo.Editor = function(field, config){
32650 Roo.Editor.superclass.constructor.call(this, config);
32651 this.field = field;
32654 * @event beforestartedit
32655 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
32656 * false from the handler of this event.
32657 * @param {Editor} this
32658 * @param {Roo.Element} boundEl The underlying element bound to this editor
32659 * @param {Mixed} value The field value being set
32661 "beforestartedit" : true,
32664 * Fires when this editor is displayed
32665 * @param {Roo.Element} boundEl The underlying element bound to this editor
32666 * @param {Mixed} value The starting field value
32668 "startedit" : true,
32670 * @event beforecomplete
32671 * Fires after a change has been made to the field, but before the change is reflected in the underlying
32672 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
32673 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
32674 * event will not fire since no edit actually occurred.
32675 * @param {Editor} this
32676 * @param {Mixed} value The current field value
32677 * @param {Mixed} startValue The original field value
32679 "beforecomplete" : true,
32682 * Fires after editing is complete and any changed value has been written to the underlying field.
32683 * @param {Editor} this
32684 * @param {Mixed} value The current field value
32685 * @param {Mixed} startValue The original field value
32689 * @event specialkey
32690 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
32691 * {@link Roo.EventObject#getKey} to determine which key was pressed.
32692 * @param {Roo.form.Field} this
32693 * @param {Roo.EventObject} e The event object
32695 "specialkey" : true
32699 Roo.extend(Roo.Editor, Roo.Component, {
32701 * @cfg {Boolean/String} autosize
32702 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
32703 * or "height" to adopt the height only (defaults to false)
32706 * @cfg {Boolean} revertInvalid
32707 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
32708 * validation fails (defaults to true)
32711 * @cfg {Boolean} ignoreNoChange
32712 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
32713 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
32714 * will never be ignored.
32717 * @cfg {Boolean} hideEl
32718 * False to keep the bound element visible while the editor is displayed (defaults to true)
32721 * @cfg {Mixed} value
32722 * The data value of the underlying field (defaults to "")
32726 * @cfg {String} alignment
32727 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
32731 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
32732 * for bottom-right shadow (defaults to "frame")
32736 * @cfg {Boolean} constrain True to constrain the editor to the viewport
32740 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
32742 completeOnEnter : false,
32744 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
32746 cancelOnEsc : false,
32748 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
32753 onRender : function(ct, position){
32754 this.el = new Roo.Layer({
32755 shadow: this.shadow,
32761 constrain: this.constrain
32763 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
32764 if(this.field.msgTarget != 'title'){
32765 this.field.msgTarget = 'qtip';
32767 this.field.render(this.el);
32769 this.field.el.dom.setAttribute('autocomplete', 'off');
32771 this.field.on("specialkey", this.onSpecialKey, this);
32772 if(this.swallowKeys){
32773 this.field.el.swallowEvent(['keydown','keypress']);
32776 this.field.on("blur", this.onBlur, this);
32777 if(this.field.grow){
32778 this.field.on("autosize", this.el.sync, this.el, {delay:1});
32782 onSpecialKey : function(field, e)
32784 //Roo.log('editor onSpecialKey');
32785 if(this.completeOnEnter && e.getKey() == e.ENTER){
32787 this.completeEdit();
32790 // do not fire special key otherwise it might hide close the editor...
32791 if(e.getKey() == e.ENTER){
32794 if(this.cancelOnEsc && e.getKey() == e.ESC){
32798 this.fireEvent('specialkey', field, e);
32803 * Starts the editing process and shows the editor.
32804 * @param {String/HTMLElement/Element} el The element to edit
32805 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
32806 * to the innerHTML of el.
32808 startEdit : function(el, value){
32810 this.completeEdit();
32812 this.boundEl = Roo.get(el);
32813 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
32814 if(!this.rendered){
32815 this.render(this.parentEl || document.body);
32817 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
32820 this.startValue = v;
32821 this.field.setValue(v);
32823 var sz = this.boundEl.getSize();
32824 switch(this.autoSize){
32826 this.setSize(sz.width, "");
32829 this.setSize("", sz.height);
32832 this.setSize(sz.width, sz.height);
32835 this.el.alignTo(this.boundEl, this.alignment);
32836 this.editing = true;
32838 Roo.QuickTips.disable();
32844 * Sets the height and width of this editor.
32845 * @param {Number} width The new width
32846 * @param {Number} height The new height
32848 setSize : function(w, h){
32849 this.field.setSize(w, h);
32856 * Realigns the editor to the bound field based on the current alignment config value.
32858 realign : function(){
32859 this.el.alignTo(this.boundEl, this.alignment);
32863 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
32864 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
32866 completeEdit : function(remainVisible){
32870 var v = this.getValue();
32871 if(this.revertInvalid !== false && !this.field.isValid()){
32872 v = this.startValue;
32873 this.cancelEdit(true);
32875 if(String(v) === String(this.startValue) && this.ignoreNoChange){
32876 this.editing = false;
32880 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
32881 this.editing = false;
32882 if(this.updateEl && this.boundEl){
32883 this.boundEl.update(v);
32885 if(remainVisible !== true){
32888 this.fireEvent("complete", this, v, this.startValue);
32893 onShow : function(){
32895 if(this.hideEl !== false){
32896 this.boundEl.hide();
32899 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
32900 this.fixIEFocus = true;
32901 this.deferredFocus.defer(50, this);
32903 this.field.focus();
32905 this.fireEvent("startedit", this.boundEl, this.startValue);
32908 deferredFocus : function(){
32910 this.field.focus();
32915 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
32916 * reverted to the original starting value.
32917 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
32918 * cancel (defaults to false)
32920 cancelEdit : function(remainVisible){
32922 this.setValue(this.startValue);
32923 if(remainVisible !== true){
32930 onBlur : function(){
32931 if(this.allowBlur !== true && this.editing){
32932 this.completeEdit();
32937 onHide : function(){
32939 this.completeEdit();
32943 if(this.field.collapse){
32944 this.field.collapse();
32947 if(this.hideEl !== false){
32948 this.boundEl.show();
32951 Roo.QuickTips.enable();
32956 * Sets the data value of the editor
32957 * @param {Mixed} value Any valid value supported by the underlying field
32959 setValue : function(v){
32960 this.field.setValue(v);
32964 * Gets the data value of the editor
32965 * @return {Mixed} The data value
32967 getValue : function(){
32968 return this.field.getValue();
32972 * Ext JS Library 1.1.1
32973 * Copyright(c) 2006-2007, Ext JS, LLC.
32975 * Originally Released Under LGPL - original licence link has changed is not relivant.
32978 * <script type="text/javascript">
32982 * @class Roo.BasicDialog
32983 * @extends Roo.util.Observable
32984 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
32986 var dlg = new Roo.BasicDialog("my-dlg", {
32995 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
32996 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
32997 dlg.addButton('Cancel', dlg.hide, dlg);
33000 <b>A Dialog should always be a direct child of the body element.</b>
33001 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
33002 * @cfg {String} title Default text to display in the title bar (defaults to null)
33003 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
33004 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
33005 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
33006 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
33007 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
33008 * (defaults to null with no animation)
33009 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
33010 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
33011 * property for valid values (defaults to 'all')
33012 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
33013 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
33014 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
33015 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
33016 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
33017 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
33018 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
33019 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
33020 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
33021 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
33022 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
33023 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
33024 * draggable = true (defaults to false)
33025 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
33026 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
33027 * shadow (defaults to false)
33028 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
33029 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
33030 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
33031 * @cfg {Array} buttons Array of buttons
33032 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
33034 * Create a new BasicDialog.
33035 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
33036 * @param {Object} config Configuration options
33038 Roo.BasicDialog = function(el, config){
33039 this.el = Roo.get(el);
33040 var dh = Roo.DomHelper;
33041 if(!this.el && config && config.autoCreate){
33042 if(typeof config.autoCreate == "object"){
33043 if(!config.autoCreate.id){
33044 config.autoCreate.id = el;
33046 this.el = dh.append(document.body,
33047 config.autoCreate, true);
33049 this.el = dh.append(document.body,
33050 {tag: "div", id: el, style:'visibility:hidden;'}, true);
33054 el.setDisplayed(true);
33055 el.hide = this.hideAction;
33057 el.addClass("x-dlg");
33059 Roo.apply(this, config);
33061 this.proxy = el.createProxy("x-dlg-proxy");
33062 this.proxy.hide = this.hideAction;
33063 this.proxy.setOpacity(.5);
33067 el.setWidth(config.width);
33070 el.setHeight(config.height);
33072 this.size = el.getSize();
33073 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
33074 this.xy = [config.x,config.y];
33076 this.xy = el.getCenterXY(true);
33078 /** The header element @type Roo.Element */
33079 this.header = el.child("> .x-dlg-hd");
33080 /** The body element @type Roo.Element */
33081 this.body = el.child("> .x-dlg-bd");
33082 /** The footer element @type Roo.Element */
33083 this.footer = el.child("> .x-dlg-ft");
33086 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
33089 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
33092 this.header.unselectable();
33094 this.header.update(this.title);
33096 // this element allows the dialog to be focused for keyboard event
33097 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
33098 this.focusEl.swallowEvent("click", true);
33100 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
33102 // wrap the body and footer for special rendering
33103 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
33105 this.bwrap.dom.appendChild(this.footer.dom);
33108 this.bg = this.el.createChild({
33109 tag: "div", cls:"x-dlg-bg",
33110 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
33112 this.centerBg = this.bg.child("div.x-dlg-bg-center");
33115 if(this.autoScroll !== false && !this.autoTabs){
33116 this.body.setStyle("overflow", "auto");
33119 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
33121 if(this.closable !== false){
33122 this.el.addClass("x-dlg-closable");
33123 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
33124 this.close.on("click", this.closeClick, this);
33125 this.close.addClassOnOver("x-dlg-close-over");
33127 if(this.collapsible !== false){
33128 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
33129 this.collapseBtn.on("click", this.collapseClick, this);
33130 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
33131 this.header.on("dblclick", this.collapseClick, this);
33133 if(this.resizable !== false){
33134 this.el.addClass("x-dlg-resizable");
33135 this.resizer = new Roo.Resizable(el, {
33136 minWidth: this.minWidth || 80,
33137 minHeight:this.minHeight || 80,
33138 handles: this.resizeHandles || "all",
33141 this.resizer.on("beforeresize", this.beforeResize, this);
33142 this.resizer.on("resize", this.onResize, this);
33144 if(this.draggable !== false){
33145 el.addClass("x-dlg-draggable");
33146 if (!this.proxyDrag) {
33147 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
33150 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
33152 dd.setHandleElId(this.header.id);
33153 dd.endDrag = this.endMove.createDelegate(this);
33154 dd.startDrag = this.startMove.createDelegate(this);
33155 dd.onDrag = this.onDrag.createDelegate(this);
33160 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
33161 this.mask.enableDisplayMode("block");
33163 this.el.addClass("x-dlg-modal");
33166 this.shadow = new Roo.Shadow({
33167 mode : typeof this.shadow == "string" ? this.shadow : "sides",
33168 offset : this.shadowOffset
33171 this.shadowOffset = 0;
33173 if(Roo.useShims && this.shim !== false){
33174 this.shim = this.el.createShim();
33175 this.shim.hide = this.hideAction;
33183 if (this.buttons) {
33184 var bts= this.buttons;
33186 Roo.each(bts, function(b) {
33195 * Fires when a key is pressed
33196 * @param {Roo.BasicDialog} this
33197 * @param {Roo.EventObject} e
33202 * Fires when this dialog is moved by the user.
33203 * @param {Roo.BasicDialog} this
33204 * @param {Number} x The new page X
33205 * @param {Number} y The new page Y
33210 * Fires when this dialog is resized by the user.
33211 * @param {Roo.BasicDialog} this
33212 * @param {Number} width The new width
33213 * @param {Number} height The new height
33217 * @event beforehide
33218 * Fires before this dialog is hidden.
33219 * @param {Roo.BasicDialog} this
33221 "beforehide" : true,
33224 * Fires when this dialog is hidden.
33225 * @param {Roo.BasicDialog} this
33229 * @event beforeshow
33230 * Fires before this dialog is shown.
33231 * @param {Roo.BasicDialog} this
33233 "beforeshow" : true,
33236 * Fires when this dialog is shown.
33237 * @param {Roo.BasicDialog} this
33241 el.on("keydown", this.onKeyDown, this);
33242 el.on("mousedown", this.toFront, this);
33243 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
33245 Roo.DialogManager.register(this);
33246 Roo.BasicDialog.superclass.constructor.call(this);
33249 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
33250 shadowOffset: Roo.isIE ? 6 : 5,
33253 minButtonWidth: 75,
33254 defaultButton: null,
33255 buttonAlign: "right",
33260 * Sets the dialog title text
33261 * @param {String} text The title text to display
33262 * @return {Roo.BasicDialog} this
33264 setTitle : function(text){
33265 this.header.update(text);
33270 closeClick : function(){
33275 collapseClick : function(){
33276 this[this.collapsed ? "expand" : "collapse"]();
33280 * Collapses the dialog to its minimized state (only the title bar is visible).
33281 * Equivalent to the user clicking the collapse dialog button.
33283 collapse : function(){
33284 if(!this.collapsed){
33285 this.collapsed = true;
33286 this.el.addClass("x-dlg-collapsed");
33287 this.restoreHeight = this.el.getHeight();
33288 this.resizeTo(this.el.getWidth(), this.header.getHeight());
33293 * Expands a collapsed dialog back to its normal state. Equivalent to the user
33294 * clicking the expand dialog button.
33296 expand : function(){
33297 if(this.collapsed){
33298 this.collapsed = false;
33299 this.el.removeClass("x-dlg-collapsed");
33300 this.resizeTo(this.el.getWidth(), this.restoreHeight);
33305 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
33306 * @return {Roo.TabPanel} The tabs component
33308 initTabs : function(){
33309 var tabs = this.getTabs();
33310 while(tabs.getTab(0)){
33313 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
33315 tabs.addTab(Roo.id(dom), dom.title);
33323 beforeResize : function(){
33324 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
33328 onResize : function(){
33329 this.refreshSize();
33330 this.syncBodyHeight();
33331 this.adjustAssets();
33333 this.fireEvent("resize", this, this.size.width, this.size.height);
33337 onKeyDown : function(e){
33338 if(this.isVisible()){
33339 this.fireEvent("keydown", this, e);
33344 * Resizes the dialog.
33345 * @param {Number} width
33346 * @param {Number} height
33347 * @return {Roo.BasicDialog} this
33349 resizeTo : function(width, height){
33350 this.el.setSize(width, height);
33351 this.size = {width: width, height: height};
33352 this.syncBodyHeight();
33353 if(this.fixedcenter){
33356 if(this.isVisible()){
33357 this.constrainXY();
33358 this.adjustAssets();
33360 this.fireEvent("resize", this, width, height);
33366 * Resizes the dialog to fit the specified content size.
33367 * @param {Number} width
33368 * @param {Number} height
33369 * @return {Roo.BasicDialog} this
33371 setContentSize : function(w, h){
33372 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
33373 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
33374 //if(!this.el.isBorderBox()){
33375 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
33376 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
33379 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
33380 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
33382 this.resizeTo(w, h);
33387 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
33388 * executed in response to a particular key being pressed while the dialog is active.
33389 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
33390 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
33391 * @param {Function} fn The function to call
33392 * @param {Object} scope (optional) The scope of the function
33393 * @return {Roo.BasicDialog} this
33395 addKeyListener : function(key, fn, scope){
33396 var keyCode, shift, ctrl, alt;
33397 if(typeof key == "object" && !(key instanceof Array)){
33398 keyCode = key["key"];
33399 shift = key["shift"];
33400 ctrl = key["ctrl"];
33405 var handler = function(dlg, e){
33406 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
33407 var k = e.getKey();
33408 if(keyCode instanceof Array){
33409 for(var i = 0, len = keyCode.length; i < len; i++){
33410 if(keyCode[i] == k){
33411 fn.call(scope || window, dlg, k, e);
33417 fn.call(scope || window, dlg, k, e);
33422 this.on("keydown", handler);
33427 * Returns the TabPanel component (creates it if it doesn't exist).
33428 * Note: If you wish to simply check for the existence of tabs without creating them,
33429 * check for a null 'tabs' property.
33430 * @return {Roo.TabPanel} The tabs component
33432 getTabs : function(){
33434 this.el.addClass("x-dlg-auto-tabs");
33435 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
33436 this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
33442 * Adds a button to the footer section of the dialog.
33443 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
33444 * object or a valid Roo.DomHelper element config
33445 * @param {Function} handler The function called when the button is clicked
33446 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
33447 * @return {Roo.Button} The new button
33449 addButton : function(config, handler, scope){
33450 var dh = Roo.DomHelper;
33452 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
33454 if(!this.btnContainer){
33455 var tb = this.footer.createChild({
33457 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
33458 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
33460 this.btnContainer = tb.firstChild.firstChild.firstChild;
33465 minWidth: this.minButtonWidth,
33468 if(typeof config == "string"){
33469 bconfig.text = config;
33472 bconfig.dhconfig = config;
33474 Roo.apply(bconfig, config);
33478 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
33479 bconfig.position = Math.max(0, bconfig.position);
33480 fc = this.btnContainer.childNodes[bconfig.position];
33483 var btn = new Roo.Button(
33485 this.btnContainer.insertBefore(document.createElement("td"),fc)
33486 : this.btnContainer.appendChild(document.createElement("td")),
33487 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
33490 this.syncBodyHeight();
33493 * Array of all the buttons that have been added to this dialog via addButton
33498 this.buttons.push(btn);
33503 * Sets the default button to be focused when the dialog is displayed.
33504 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
33505 * @return {Roo.BasicDialog} this
33507 setDefaultButton : function(btn){
33508 this.defaultButton = btn;
33513 getHeaderFooterHeight : function(safe){
33516 height += this.header.getHeight();
33519 var fm = this.footer.getMargins();
33520 height += (this.footer.getHeight()+fm.top+fm.bottom);
33522 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
33523 height += this.centerBg.getPadding("tb");
33528 syncBodyHeight : function()
33530 var bd = this.body, // the text
33531 cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
33533 var height = this.size.height - this.getHeaderFooterHeight(false);
33534 bd.setHeight(height-bd.getMargins("tb"));
33535 var hh = this.header.getHeight();
33536 var h = this.size.height-hh;
33539 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
33540 bw.setHeight(h-cb.getPadding("tb"));
33542 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
33543 bd.setWidth(bw.getWidth(true));
33545 this.tabs.syncHeight();
33547 this.tabs.el.repaint();
33553 * Restores the previous state of the dialog if Roo.state is configured.
33554 * @return {Roo.BasicDialog} this
33556 restoreState : function(){
33557 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
33558 if(box && box.width){
33559 this.xy = [box.x, box.y];
33560 this.resizeTo(box.width, box.height);
33566 beforeShow : function(){
33568 if(this.fixedcenter){
33569 this.xy = this.el.getCenterXY(true);
33572 Roo.get(document.body).addClass("x-body-masked");
33573 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
33576 this.constrainXY();
33580 animShow : function(){
33581 var b = Roo.get(this.animateTarget).getBox();
33582 this.proxy.setSize(b.width, b.height);
33583 this.proxy.setLocation(b.x, b.y);
33585 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
33586 true, .35, this.showEl.createDelegate(this));
33590 * Shows the dialog.
33591 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
33592 * @return {Roo.BasicDialog} this
33594 show : function(animateTarget){
33595 if (this.fireEvent("beforeshow", this) === false){
33598 if(this.syncHeightBeforeShow){
33599 this.syncBodyHeight();
33600 }else if(this.firstShow){
33601 this.firstShow = false;
33602 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
33604 this.animateTarget = animateTarget || this.animateTarget;
33605 if(!this.el.isVisible()){
33607 if(this.animateTarget && Roo.get(this.animateTarget)){
33617 showEl : function(){
33619 this.el.setXY(this.xy);
33621 this.adjustAssets(true);
33624 // IE peekaboo bug - fix found by Dave Fenwick
33628 this.fireEvent("show", this);
33632 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
33633 * dialog itself will receive focus.
33635 focus : function(){
33636 if(this.defaultButton){
33637 this.defaultButton.focus();
33639 this.focusEl.focus();
33644 constrainXY : function(){
33645 if(this.constraintoviewport !== false){
33646 if(!this.viewSize){
33647 if(this.container){
33648 var s = this.container.getSize();
33649 this.viewSize = [s.width, s.height];
33651 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
33654 var s = Roo.get(this.container||document).getScroll();
33656 var x = this.xy[0], y = this.xy[1];
33657 var w = this.size.width, h = this.size.height;
33658 var vw = this.viewSize[0], vh = this.viewSize[1];
33659 // only move it if it needs it
33661 // first validate right/bottom
33662 if(x + w > vw+s.left){
33666 if(y + h > vh+s.top){
33670 // then make sure top/left isn't negative
33682 if(this.isVisible()){
33683 this.el.setLocation(x, y);
33684 this.adjustAssets();
33691 onDrag : function(){
33692 if(!this.proxyDrag){
33693 this.xy = this.el.getXY();
33694 this.adjustAssets();
33699 adjustAssets : function(doShow){
33700 var x = this.xy[0], y = this.xy[1];
33701 var w = this.size.width, h = this.size.height;
33702 if(doShow === true){
33704 this.shadow.show(this.el);
33710 if(this.shadow && this.shadow.isVisible()){
33711 this.shadow.show(this.el);
33713 if(this.shim && this.shim.isVisible()){
33714 this.shim.setBounds(x, y, w, h);
33719 adjustViewport : function(w, h){
33721 w = Roo.lib.Dom.getViewWidth();
33722 h = Roo.lib.Dom.getViewHeight();
33725 this.viewSize = [w, h];
33726 if(this.modal && this.mask.isVisible()){
33727 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
33728 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
33730 if(this.isVisible()){
33731 this.constrainXY();
33736 * Destroys this dialog and all its supporting elements (including any tabs, shim,
33737 * shadow, proxy, mask, etc.) Also removes all event listeners.
33738 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
33740 destroy : function(removeEl){
33741 if(this.isVisible()){
33742 this.animateTarget = null;
33745 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
33747 this.tabs.destroy(removeEl);
33760 for(var i = 0, len = this.buttons.length; i < len; i++){
33761 this.buttons[i].destroy();
33764 this.el.removeAllListeners();
33765 if(removeEl === true){
33766 this.el.update("");
33769 Roo.DialogManager.unregister(this);
33773 startMove : function(){
33774 if(this.proxyDrag){
33777 if(this.constraintoviewport !== false){
33778 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
33783 endMove : function(){
33784 if(!this.proxyDrag){
33785 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
33787 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
33790 this.refreshSize();
33791 this.adjustAssets();
33793 this.fireEvent("move", this, this.xy[0], this.xy[1]);
33797 * Brings this dialog to the front of any other visible dialogs
33798 * @return {Roo.BasicDialog} this
33800 toFront : function(){
33801 Roo.DialogManager.bringToFront(this);
33806 * Sends this dialog to the back (under) of any other visible dialogs
33807 * @return {Roo.BasicDialog} this
33809 toBack : function(){
33810 Roo.DialogManager.sendToBack(this);
33815 * Centers this dialog in the viewport
33816 * @return {Roo.BasicDialog} this
33818 center : function(){
33819 var xy = this.el.getCenterXY(true);
33820 this.moveTo(xy[0], xy[1]);
33825 * Moves the dialog's top-left corner to the specified point
33826 * @param {Number} x
33827 * @param {Number} y
33828 * @return {Roo.BasicDialog} this
33830 moveTo : function(x, y){
33832 if(this.isVisible()){
33833 this.el.setXY(this.xy);
33834 this.adjustAssets();
33840 * Aligns the dialog to the specified element
33841 * @param {String/HTMLElement/Roo.Element} element The element to align to.
33842 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
33843 * @param {Array} offsets (optional) Offset the positioning by [x, y]
33844 * @return {Roo.BasicDialog} this
33846 alignTo : function(element, position, offsets){
33847 this.xy = this.el.getAlignToXY(element, position, offsets);
33848 if(this.isVisible()){
33849 this.el.setXY(this.xy);
33850 this.adjustAssets();
33856 * Anchors an element to another element and realigns it when the window is resized.
33857 * @param {String/HTMLElement/Roo.Element} element The element to align to.
33858 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
33859 * @param {Array} offsets (optional) Offset the positioning by [x, y]
33860 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
33861 * is a number, it is used as the buffer delay (defaults to 50ms).
33862 * @return {Roo.BasicDialog} this
33864 anchorTo : function(el, alignment, offsets, monitorScroll){
33865 var action = function(){
33866 this.alignTo(el, alignment, offsets);
33868 Roo.EventManager.onWindowResize(action, this);
33869 var tm = typeof monitorScroll;
33870 if(tm != 'undefined'){
33871 Roo.EventManager.on(window, 'scroll', action, this,
33872 {buffer: tm == 'number' ? monitorScroll : 50});
33879 * Returns true if the dialog is visible
33880 * @return {Boolean}
33882 isVisible : function(){
33883 return this.el.isVisible();
33887 animHide : function(callback){
33888 var b = Roo.get(this.animateTarget).getBox();
33890 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
33892 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
33893 this.hideEl.createDelegate(this, [callback]));
33897 * Hides the dialog.
33898 * @param {Function} callback (optional) Function to call when the dialog is hidden
33899 * @return {Roo.BasicDialog} this
33901 hide : function(callback){
33902 if (this.fireEvent("beforehide", this) === false){
33906 this.shadow.hide();
33911 // sometimes animateTarget seems to get set.. causing problems...
33912 // this just double checks..
33913 if(this.animateTarget && Roo.get(this.animateTarget)) {
33914 this.animHide(callback);
33917 this.hideEl(callback);
33923 hideEl : function(callback){
33927 Roo.get(document.body).removeClass("x-body-masked");
33929 this.fireEvent("hide", this);
33930 if(typeof callback == "function"){
33936 hideAction : function(){
33937 this.setLeft("-10000px");
33938 this.setTop("-10000px");
33939 this.setStyle("visibility", "hidden");
33943 refreshSize : function(){
33944 this.size = this.el.getSize();
33945 this.xy = this.el.getXY();
33946 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
33950 // z-index is managed by the DialogManager and may be overwritten at any time
33951 setZIndex : function(index){
33953 this.mask.setStyle("z-index", index);
33956 this.shim.setStyle("z-index", ++index);
33959 this.shadow.setZIndex(++index);
33961 this.el.setStyle("z-index", ++index);
33963 this.proxy.setStyle("z-index", ++index);
33966 this.resizer.proxy.setStyle("z-index", ++index);
33969 this.lastZIndex = index;
33973 * Returns the element for this dialog
33974 * @return {Roo.Element} The underlying dialog Element
33976 getEl : function(){
33982 * @class Roo.DialogManager
33983 * Provides global access to BasicDialogs that have been created and
33984 * support for z-indexing (layering) multiple open dialogs.
33986 Roo.DialogManager = function(){
33988 var accessList = [];
33992 var sortDialogs = function(d1, d2){
33993 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
33997 var orderDialogs = function(){
33998 accessList.sort(sortDialogs);
33999 var seed = Roo.DialogManager.zseed;
34000 for(var i = 0, len = accessList.length; i < len; i++){
34001 var dlg = accessList[i];
34003 dlg.setZIndex(seed + (i*10));
34010 * The starting z-index for BasicDialogs (defaults to 9000)
34011 * @type Number The z-index value
34016 register : function(dlg){
34017 list[dlg.id] = dlg;
34018 accessList.push(dlg);
34022 unregister : function(dlg){
34023 delete list[dlg.id];
34026 if(!accessList.indexOf){
34027 for( i = 0, len = accessList.length; i < len; i++){
34028 if(accessList[i] == dlg){
34029 accessList.splice(i, 1);
34034 i = accessList.indexOf(dlg);
34036 accessList.splice(i, 1);
34042 * Gets a registered dialog by id
34043 * @param {String/Object} id The id of the dialog or a dialog
34044 * @return {Roo.BasicDialog} this
34046 get : function(id){
34047 return typeof id == "object" ? id : list[id];
34051 * Brings the specified dialog to the front
34052 * @param {String/Object} dlg The id of the dialog or a dialog
34053 * @return {Roo.BasicDialog} this
34055 bringToFront : function(dlg){
34056 dlg = this.get(dlg);
34059 dlg._lastAccess = new Date().getTime();
34066 * Sends the specified dialog to the back
34067 * @param {String/Object} dlg The id of the dialog or a dialog
34068 * @return {Roo.BasicDialog} this
34070 sendToBack : function(dlg){
34071 dlg = this.get(dlg);
34072 dlg._lastAccess = -(new Date().getTime());
34078 * Hides all dialogs
34080 hideAll : function(){
34081 for(var id in list){
34082 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
34091 * @class Roo.LayoutDialog
34092 * @extends Roo.BasicDialog
34093 * @children Roo.ContentPanel
34094 * @parent builder none
34095 * Dialog which provides adjustments for working with a layout in a Dialog.
34096 * Add your necessary layout config options to the dialog's config.<br>
34097 * Example usage (including a nested layout):
34100 dialog = new Roo.LayoutDialog("download-dlg", {
34109 // layout config merges with the dialog config
34111 tabPosition: "top",
34112 alwaysShowTabs: true
34115 dialog.addKeyListener(27, dialog.hide, dialog);
34116 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
34117 dialog.addButton("Build It!", this.getDownload, this);
34119 // we can even add nested layouts
34120 var innerLayout = new Roo.BorderLayout("dl-inner", {
34130 innerLayout.beginUpdate();
34131 innerLayout.add("east", new Roo.ContentPanel("dl-details"));
34132 innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
34133 innerLayout.endUpdate(true);
34135 var layout = dialog.getLayout();
34136 layout.beginUpdate();
34137 layout.add("center", new Roo.ContentPanel("standard-panel",
34138 {title: "Download the Source", fitToFrame:true}));
34139 layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
34140 {title: "Build your own roo.js"}));
34141 layout.getRegion("center").showPanel(sp);
34142 layout.endUpdate();
34146 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
34147 * @param {Object} config configuration options
34149 Roo.LayoutDialog = function(el, cfg){
34152 if (typeof(cfg) == 'undefined') {
34153 config = Roo.apply({}, el);
34154 // not sure why we use documentElement here.. - it should always be body.
34155 // IE7 borks horribly if we use documentElement.
34156 // webkit also does not like documentElement - it creates a body element...
34157 el = Roo.get( document.body || document.documentElement ).createChild();
34158 //config.autoCreate = true;
34162 config.autoTabs = false;
34163 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
34164 this.body.setStyle({overflow:"hidden", position:"relative"});
34165 this.layout = new Roo.BorderLayout(this.body.dom, config);
34166 this.layout.monitorWindowResize = false;
34167 this.el.addClass("x-dlg-auto-layout");
34168 // fix case when center region overwrites center function
34169 this.center = Roo.BasicDialog.prototype.center;
34170 this.on("show", this.layout.layout, this.layout, true);
34171 if (config.items) {
34172 var xitems = config.items;
34173 delete config.items;
34174 Roo.each(xitems, this.addxtype, this);
34179 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
34183 * @cfg {Roo.LayoutRegion} east
34186 * @cfg {Roo.LayoutRegion} west
34189 * @cfg {Roo.LayoutRegion} south
34192 * @cfg {Roo.LayoutRegion} north
34195 * @cfg {Roo.LayoutRegion} center
34198 * @cfg {Roo.Button} buttons[] Bottom buttons..
34203 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
34206 endUpdate : function(){
34207 this.layout.endUpdate();
34211 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
34214 beginUpdate : function(){
34215 this.layout.beginUpdate();
34219 * Get the BorderLayout for this dialog
34220 * @return {Roo.BorderLayout}
34222 getLayout : function(){
34223 return this.layout;
34226 showEl : function(){
34227 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
34229 this.layout.layout();
34234 // Use the syncHeightBeforeShow config option to control this automatically
34235 syncBodyHeight : function(){
34236 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
34237 if(this.layout){this.layout.layout();}
34241 * Add an xtype element (actually adds to the layout.)
34242 * @return {Object} xdata xtype object data.
34245 addxtype : function(c) {
34246 return this.layout.addxtype(c);
34250 * Ext JS Library 1.1.1
34251 * Copyright(c) 2006-2007, Ext JS, LLC.
34253 * Originally Released Under LGPL - original licence link has changed is not relivant.
34256 * <script type="text/javascript">
34260 * @class Roo.MessageBox
34261 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
34265 Roo.Msg.alert('Status', 'Changes saved successfully.');
34267 // Prompt for user data:
34268 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
34270 // process text value...
34274 // Show a dialog using config options:
34276 title:'Save Changes?',
34277 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
34278 buttons: Roo.Msg.YESNOCANCEL,
34285 Roo.MessageBox = function(){
34286 var dlg, opt, mask, waitTimer;
34287 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
34288 var buttons, activeTextEl, bwidth;
34291 var handleButton = function(button){
34293 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
34297 var handleHide = function(){
34298 if(opt && opt.cls){
34299 dlg.el.removeClass(opt.cls);
34302 Roo.TaskMgr.stop(waitTimer);
34308 var updateButtons = function(b){
34311 buttons["ok"].hide();
34312 buttons["cancel"].hide();
34313 buttons["yes"].hide();
34314 buttons["no"].hide();
34315 dlg.footer.dom.style.display = 'none';
34318 dlg.footer.dom.style.display = '';
34319 for(var k in buttons){
34320 if(typeof buttons[k] != "function"){
34323 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
34324 width += buttons[k].el.getWidth()+15;
34334 var handleEsc = function(d, k, e){
34335 if(opt && opt.closable !== false){
34345 * Returns a reference to the underlying {@link Roo.BasicDialog} element
34346 * @return {Roo.BasicDialog} The BasicDialog element
34348 getDialog : function(){
34350 dlg = new Roo.BasicDialog("x-msg-box", {
34355 constraintoviewport:false,
34357 collapsible : false,
34360 width:400, height:100,
34361 buttonAlign:"center",
34362 closeClick : function(){
34363 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
34364 handleButton("no");
34366 handleButton("cancel");
34370 dlg.on("hide", handleHide);
34372 dlg.addKeyListener(27, handleEsc);
34374 var bt = this.buttonText;
34375 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
34376 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
34377 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
34378 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
34379 bodyEl = dlg.body.createChild({
34381 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>'
34383 msgEl = bodyEl.dom.firstChild;
34384 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
34385 textboxEl.enableDisplayMode();
34386 textboxEl.addKeyListener([10,13], function(){
34387 if(dlg.isVisible() && opt && opt.buttons){
34388 if(opt.buttons.ok){
34389 handleButton("ok");
34390 }else if(opt.buttons.yes){
34391 handleButton("yes");
34395 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
34396 textareaEl.enableDisplayMode();
34397 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
34398 progressEl.enableDisplayMode();
34399 var pf = progressEl.dom.firstChild;
34401 pp = Roo.get(pf.firstChild);
34402 pp.setHeight(pf.offsetHeight);
34410 * Updates the message box body text
34411 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
34412 * the XHTML-compliant non-breaking space character '&#160;')
34413 * @return {Roo.MessageBox} This message box
34415 updateText : function(text){
34416 if(!dlg.isVisible() && !opt.width){
34417 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
34419 msgEl.innerHTML = text || ' ';
34421 var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
34422 //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
34424 Math.min(opt.width || cw , this.maxWidth),
34425 Math.max(opt.minWidth || this.minWidth, bwidth)
34428 activeTextEl.setWidth(w);
34430 if(dlg.isVisible()){
34431 dlg.fixedcenter = false;
34433 // to big, make it scroll. = But as usual stupid IE does not support
34436 if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
34437 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
34438 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
34440 bodyEl.dom.style.height = '';
34441 bodyEl.dom.style.overflowY = '';
34444 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
34446 bodyEl.dom.style.overflowX = '';
34449 dlg.setContentSize(w, bodyEl.getHeight());
34450 if(dlg.isVisible()){
34451 dlg.fixedcenter = true;
34457 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
34458 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
34459 * @param {Number} value Any number between 0 and 1 (e.g., .5)
34460 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
34461 * @return {Roo.MessageBox} This message box
34463 updateProgress : function(value, text){
34465 this.updateText(text);
34467 if (pp) { // weird bug on my firefox - for some reason this is not defined
34468 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
34474 * Returns true if the message box is currently displayed
34475 * @return {Boolean} True if the message box is visible, else false
34477 isVisible : function(){
34478 return dlg && dlg.isVisible();
34482 * Hides the message box if it is displayed
34485 if(this.isVisible()){
34491 * Displays a new message box, or reinitializes an existing message box, based on the config options
34492 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
34493 * The following config object properties are supported:
34495 Property Type Description
34496 ---------- --------------- ------------------------------------------------------------------------------------
34497 animEl String/Element An id or Element from which the message box should animate as it opens and
34498 closes (defaults to undefined)
34499 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
34500 cancel:'Bar'}), or false to not show any buttons (defaults to false)
34501 closable Boolean False to hide the top-right close button (defaults to true). Note that
34502 progress and wait dialogs will ignore this property and always hide the
34503 close button as they can only be closed programmatically.
34504 cls String A custom CSS class to apply to the message box element
34505 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
34506 displayed (defaults to 75)
34507 fn Function A callback function to execute after closing the dialog. The arguments to the
34508 function will be btn (the name of the button that was clicked, if applicable,
34509 e.g. "ok"), and text (the value of the active text field, if applicable).
34510 Progress and wait dialogs will ignore this option since they do not respond to
34511 user actions and can only be closed programmatically, so any required function
34512 should be called by the same code after it closes the dialog.
34513 icon String A CSS class that provides a background image to be used as an icon for
34514 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
34515 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
34516 minWidth Number The minimum width in pixels of the message box (defaults to 100)
34517 modal Boolean False to allow user interaction with the page while the message box is
34518 displayed (defaults to true)
34519 msg String A string that will replace the existing message box body text (defaults
34520 to the XHTML-compliant non-breaking space character ' ')
34521 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
34522 progress Boolean True to display a progress bar (defaults to false)
34523 progressText String The text to display inside the progress bar if progress = true (defaults to '')
34524 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
34525 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
34526 title String The title text
34527 value String The string value to set into the active textbox element if displayed
34528 wait Boolean True to display a progress bar (defaults to false)
34529 width Number The width of the dialog in pixels
34536 msg: 'Please enter your address:',
34538 buttons: Roo.MessageBox.OKCANCEL,
34541 animEl: 'addAddressBtn'
34544 * @param {Object} config Configuration options
34545 * @return {Roo.MessageBox} This message box
34547 show : function(options)
34550 // this causes nightmares if you show one dialog after another
34551 // especially on callbacks..
34553 if(this.isVisible()){
34556 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
34557 Roo.log("Old Dialog Message:" + msgEl.innerHTML );
34558 Roo.log("New Dialog Message:" + options.msg )
34559 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
34560 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
34563 var d = this.getDialog();
34565 d.setTitle(opt.title || " ");
34566 d.close.setDisplayed(opt.closable !== false);
34567 activeTextEl = textboxEl;
34568 opt.prompt = opt.prompt || (opt.multiline ? true : false);
34573 textareaEl.setHeight(typeof opt.multiline == "number" ?
34574 opt.multiline : this.defaultTextHeight);
34575 activeTextEl = textareaEl;
34584 progressEl.setDisplayed(opt.progress === true);
34585 this.updateProgress(0);
34586 activeTextEl.dom.value = opt.value || "";
34588 dlg.setDefaultButton(activeTextEl);
34590 var bs = opt.buttons;
34593 db = buttons["ok"];
34594 }else if(bs && bs.yes){
34595 db = buttons["yes"];
34597 dlg.setDefaultButton(db);
34599 bwidth = updateButtons(opt.buttons);
34600 this.updateText(opt.msg);
34602 d.el.addClass(opt.cls);
34604 d.proxyDrag = opt.proxyDrag === true;
34605 d.modal = opt.modal !== false;
34606 d.mask = opt.modal !== false ? mask : false;
34607 if(!d.isVisible()){
34608 // force it to the end of the z-index stack so it gets a cursor in FF
34609 document.body.appendChild(dlg.el.dom);
34610 d.animateTarget = null;
34611 d.show(options.animEl);
34617 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
34618 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
34619 * and closing the message box when the process is complete.
34620 * @param {String} title The title bar text
34621 * @param {String} msg The message box body text
34622 * @return {Roo.MessageBox} This message box
34624 progress : function(title, msg){
34631 minWidth: this.minProgressWidth,
34638 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
34639 * If a callback function is passed it will be called after the user clicks the button, and the
34640 * id of the button that was clicked will be passed as the only parameter to the callback
34641 * (could also be the top-right close button).
34642 * @param {String} title The title bar text
34643 * @param {String} msg The message box body text
34644 * @param {Function} fn (optional) The callback function invoked after the message box is closed
34645 * @param {Object} scope (optional) The scope of the callback function
34646 * @return {Roo.MessageBox} This message box
34648 alert : function(title, msg, fn, scope){
34661 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
34662 * interaction while waiting for a long-running process to complete that does not have defined intervals.
34663 * You are responsible for closing the message box when the process is complete.
34664 * @param {String} msg The message box body text
34665 * @param {String} title (optional) The title bar text
34666 * @return {Roo.MessageBox} This message box
34668 wait : function(msg, title){
34679 waitTimer = Roo.TaskMgr.start({
34681 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
34689 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
34690 * If a callback function is passed it will be called after the user clicks either button, and the id of the
34691 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
34692 * @param {String} title The title bar text
34693 * @param {String} msg The message box body text
34694 * @param {Function} fn (optional) The callback function invoked after the message box is closed
34695 * @param {Object} scope (optional) The scope of the callback function
34696 * @return {Roo.MessageBox} This message box
34698 confirm : function(title, msg, fn, scope){
34702 buttons: this.YESNO,
34711 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
34712 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
34713 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
34714 * (could also be the top-right close button) and the text that was entered will be passed as the two
34715 * parameters to the callback.
34716 * @param {String} title The title bar text
34717 * @param {String} msg The message box body text
34718 * @param {Function} fn (optional) The callback function invoked after the message box is closed
34719 * @param {Object} scope (optional) The scope of the callback function
34720 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
34721 * property, or the height in pixels to create the textbox (defaults to false / single-line)
34722 * @return {Roo.MessageBox} This message box
34724 prompt : function(title, msg, fn, scope, multiline){
34728 buttons: this.OKCANCEL,
34733 multiline: multiline,
34740 * Button config that displays a single OK button
34745 * Button config that displays Yes and No buttons
34748 YESNO : {yes:true, no:true},
34750 * Button config that displays OK and Cancel buttons
34753 OKCANCEL : {ok:true, cancel:true},
34755 * Button config that displays Yes, No and Cancel buttons
34758 YESNOCANCEL : {yes:true, no:true, cancel:true},
34761 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
34764 defaultTextHeight : 75,
34766 * The maximum width in pixels of the message box (defaults to 600)
34771 * The minimum width in pixels of the message box (defaults to 100)
34776 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
34777 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
34780 minProgressWidth : 250,
34782 * An object containing the default button text strings that can be overriden for localized language support.
34783 * Supported properties are: ok, cancel, yes and no.
34784 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
34797 * Shorthand for {@link Roo.MessageBox}
34799 Roo.Msg = Roo.MessageBox;/*
34801 * Ext JS Library 1.1.1
34802 * Copyright(c) 2006-2007, Ext JS, LLC.
34804 * Originally Released Under LGPL - original licence link has changed is not relivant.
34807 * <script type="text/javascript">
34810 * @class Roo.QuickTips
34811 * Provides attractive and customizable tooltips for any element.
34814 Roo.QuickTips = function(){
34815 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
34816 var ce, bd, xy, dd;
34817 var visible = false, disabled = true, inited = false;
34818 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
34820 var onOver = function(e){
34824 var t = e.getTarget();
34825 if(!t || t.nodeType !== 1 || t == document || t == document.body){
34828 if(ce && t == ce.el){
34829 clearTimeout(hideProc);
34832 if(t && tagEls[t.id]){
34833 tagEls[t.id].el = t;
34834 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
34837 var ttp, et = Roo.fly(t);
34838 var ns = cfg.namespace;
34839 if(tm.interceptTitles && t.title){
34842 t.removeAttribute("title");
34843 e.preventDefault();
34845 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
34848 showProc = show.defer(tm.showDelay, tm, [{
34850 text: ttp.replace(/\\n/g,'<br/>'),
34851 width: et.getAttributeNS(ns, cfg.width),
34852 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
34853 title: et.getAttributeNS(ns, cfg.title),
34854 cls: et.getAttributeNS(ns, cfg.cls)
34859 var onOut = function(e){
34860 clearTimeout(showProc);
34861 var t = e.getTarget();
34862 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
34863 hideProc = setTimeout(hide, tm.hideDelay);
34867 var onMove = function(e){
34873 if(tm.trackMouse && ce){
34878 var onDown = function(e){
34879 clearTimeout(showProc);
34880 clearTimeout(hideProc);
34882 if(tm.hideOnClick){
34885 tm.enable.defer(100, tm);
34890 var getPad = function(){
34891 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
34894 var show = function(o){
34898 clearTimeout(dismissProc);
34900 if(removeCls){ // in case manually hidden
34901 el.removeClass(removeCls);
34905 el.addClass(ce.cls);
34906 removeCls = ce.cls;
34909 tipTitle.update(ce.title);
34912 tipTitle.update('');
34915 el.dom.style.width = tm.maxWidth+'px';
34916 //tipBody.dom.style.width = '';
34917 tipBodyText.update(o.text);
34918 var p = getPad(), w = ce.width;
34920 var td = tipBodyText.dom;
34921 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
34922 if(aw > tm.maxWidth){
34924 }else if(aw < tm.minWidth){
34930 //tipBody.setWidth(w);
34931 el.setWidth(parseInt(w, 10) + p);
34932 if(ce.autoHide === false){
34933 close.setDisplayed(true);
34938 close.setDisplayed(false);
34944 el.avoidY = xy[1]-18;
34949 el.setStyle("visibility", "visible");
34950 el.fadeIn({callback: afterShow});
34956 var afterShow = function(){
34960 if(tm.autoDismiss && ce.autoHide !== false){
34961 dismissProc = setTimeout(hide, tm.autoDismissDelay);
34966 var hide = function(noanim){
34967 clearTimeout(dismissProc);
34968 clearTimeout(hideProc);
34970 if(el.isVisible()){
34972 if(noanim !== true && tm.animate){
34973 el.fadeOut({callback: afterHide});
34980 var afterHide = function(){
34983 el.removeClass(removeCls);
34990 * @cfg {Number} minWidth
34991 * The minimum width of the quick tip (defaults to 40)
34995 * @cfg {Number} maxWidth
34996 * The maximum width of the quick tip (defaults to 300)
35000 * @cfg {Boolean} interceptTitles
35001 * True to automatically use the element's DOM title value if available (defaults to false)
35003 interceptTitles : false,
35005 * @cfg {Boolean} trackMouse
35006 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
35008 trackMouse : false,
35010 * @cfg {Boolean} hideOnClick
35011 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
35013 hideOnClick : true,
35015 * @cfg {Number} showDelay
35016 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
35020 * @cfg {Number} hideDelay
35021 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
35025 * @cfg {Boolean} autoHide
35026 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
35027 * Used in conjunction with hideDelay.
35032 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
35033 * (defaults to true). Used in conjunction with autoDismissDelay.
35035 autoDismiss : true,
35038 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
35040 autoDismissDelay : 5000,
35042 * @cfg {Boolean} animate
35043 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
35048 * @cfg {String} title
35049 * Title text to display (defaults to ''). This can be any valid HTML markup.
35053 * @cfg {String} text
35054 * Body text to display (defaults to ''). This can be any valid HTML markup.
35058 * @cfg {String} cls
35059 * A CSS class to apply to the base quick tip element (defaults to '').
35063 * @cfg {Number} width
35064 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
35065 * minWidth or maxWidth.
35070 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
35071 * or display QuickTips in a page.
35074 tm = Roo.QuickTips;
35075 cfg = tm.tagConfig;
35077 if(!Roo.isReady){ // allow calling of init() before onReady
35078 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
35081 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
35082 el.fxDefaults = {stopFx: true};
35083 // maximum custom styling
35084 //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>');
35085 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>');
35086 tipTitle = el.child('h3');
35087 tipTitle.enableDisplayMode("block");
35088 tipBody = el.child('div.x-tip-bd');
35089 tipBodyText = el.child('div.x-tip-bd-inner');
35090 //bdLeft = el.child('div.x-tip-bd-left');
35091 //bdRight = el.child('div.x-tip-bd-right');
35092 close = el.child('div.x-tip-close');
35093 close.enableDisplayMode("block");
35094 close.on("click", hide);
35095 var d = Roo.get(document);
35096 d.on("mousedown", onDown);
35097 d.on("mouseover", onOver);
35098 d.on("mouseout", onOut);
35099 d.on("mousemove", onMove);
35100 esc = d.addKeyListener(27, hide);
35103 dd = el.initDD("default", null, {
35104 onDrag : function(){
35108 dd.setHandleElId(tipTitle.id);
35117 * Configures a new quick tip instance and assigns it to a target element. The following config options
35120 Property Type Description
35121 ---------- --------------------- ------------------------------------------------------------------------
35122 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
35124 * @param {Object} config The config object
35126 register : function(config){
35127 var cs = config instanceof Array ? config : arguments;
35128 for(var i = 0, len = cs.length; i < len; i++) {
35130 var target = c.target;
35132 if(target instanceof Array){
35133 for(var j = 0, jlen = target.length; j < jlen; j++){
35134 tagEls[target[j]] = c;
35137 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
35144 * Removes this quick tip from its element and destroys it.
35145 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
35147 unregister : function(el){
35148 delete tagEls[Roo.id(el)];
35152 * Enable this quick tip.
35154 enable : function(){
35155 if(inited && disabled){
35157 if(locks.length < 1){
35164 * Disable this quick tip.
35166 disable : function(){
35168 clearTimeout(showProc);
35169 clearTimeout(hideProc);
35170 clearTimeout(dismissProc);
35178 * Returns true if the quick tip is enabled, else false.
35180 isEnabled : function(){
35186 namespace : "roo", // was ext?? this may break..
35187 alt_namespace : "ext",
35188 attribute : "qtip",
35198 // backwards compat
35199 Roo.QuickTips.tips = Roo.QuickTips.register;/*
35201 * Ext JS Library 1.1.1
35202 * Copyright(c) 2006-2007, Ext JS, LLC.
35204 * Originally Released Under LGPL - original licence link has changed is not relivant.
35207 * <script type="text/javascript">
35212 * @class Roo.tree.TreePanel
35213 * @extends Roo.data.Tree
35214 * @cfg {Roo.tree.TreeNode} root The root node
35215 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
35216 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
35217 * @cfg {Boolean} enableDD true to enable drag and drop
35218 * @cfg {Boolean} enableDrag true to enable just drag
35219 * @cfg {Boolean} enableDrop true to enable just drop
35220 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
35221 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
35222 * @cfg {String} ddGroup The DD group this TreePanel belongs to
35223 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
35224 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
35225 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
35226 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
35227 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
35228 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
35229 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
35230 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
35231 * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
35232 * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
35233 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
35234 * @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>
35235 * @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>
35238 * @param {String/HTMLElement/Element} el The container element
35239 * @param {Object} config
35241 Roo.tree.TreePanel = function(el, config){
35243 var loader = false;
35245 root = config.root;
35246 delete config.root;
35248 if (config.loader) {
35249 loader = config.loader;
35250 delete config.loader;
35253 Roo.apply(this, config);
35254 Roo.tree.TreePanel.superclass.constructor.call(this);
35255 this.el = Roo.get(el);
35256 this.el.addClass('x-tree');
35257 //console.log(root);
35259 this.setRootNode( Roo.factory(root, Roo.tree));
35262 this.loader = Roo.factory(loader, Roo.tree);
35265 * Read-only. The id of the container element becomes this TreePanel's id.
35267 this.id = this.el.id;
35270 * @event beforeload
35271 * Fires before a node is loaded, return false to cancel
35272 * @param {Node} node The node being loaded
35274 "beforeload" : true,
35277 * Fires when a node is loaded
35278 * @param {Node} node The node that was loaded
35282 * @event textchange
35283 * Fires when the text for a node is changed
35284 * @param {Node} node The node
35285 * @param {String} text The new text
35286 * @param {String} oldText The old text
35288 "textchange" : true,
35290 * @event beforeexpand
35291 * Fires before a node is expanded, return false to cancel.
35292 * @param {Node} node The node
35293 * @param {Boolean} deep
35294 * @param {Boolean} anim
35296 "beforeexpand" : true,
35298 * @event beforecollapse
35299 * Fires before a node is collapsed, return false to cancel.
35300 * @param {Node} node The node
35301 * @param {Boolean} deep
35302 * @param {Boolean} anim
35304 "beforecollapse" : true,
35307 * Fires when a node is expanded
35308 * @param {Node} node The node
35312 * @event disabledchange
35313 * Fires when the disabled status of a node changes
35314 * @param {Node} node The node
35315 * @param {Boolean} disabled
35317 "disabledchange" : true,
35320 * Fires when a node is collapsed
35321 * @param {Node} node The node
35325 * @event beforeclick
35326 * Fires before click processing on a node. Return false to cancel the default action.
35327 * @param {Node} node The node
35328 * @param {Roo.EventObject} e The event object
35330 "beforeclick":true,
35332 * @event checkchange
35333 * Fires when a node with a checkbox's checked property changes
35334 * @param {Node} this This node
35335 * @param {Boolean} checked
35337 "checkchange":true,
35340 * Fires when a node is clicked
35341 * @param {Node} node The node
35342 * @param {Roo.EventObject} e The event object
35347 * Fires when a node is double clicked
35348 * @param {Node} node The node
35349 * @param {Roo.EventObject} e The event object
35353 * @event contextmenu
35354 * Fires when a node is right clicked
35355 * @param {Node} node The node
35356 * @param {Roo.EventObject} e The event object
35358 "contextmenu":true,
35360 * @event beforechildrenrendered
35361 * Fires right before the child nodes for a node are rendered
35362 * @param {Node} node The node
35364 "beforechildrenrendered":true,
35367 * Fires when a node starts being dragged
35368 * @param {Roo.tree.TreePanel} this
35369 * @param {Roo.tree.TreeNode} node
35370 * @param {event} e The raw browser event
35372 "startdrag" : true,
35375 * Fires when a drag operation is complete
35376 * @param {Roo.tree.TreePanel} this
35377 * @param {Roo.tree.TreeNode} node
35378 * @param {event} e The raw browser event
35383 * Fires when a dragged node is dropped on a valid DD target
35384 * @param {Roo.tree.TreePanel} this
35385 * @param {Roo.tree.TreeNode} node
35386 * @param {DD} dd The dd it was dropped on
35387 * @param {event} e The raw browser event
35391 * @event beforenodedrop
35392 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
35393 * passed to handlers has the following properties:<br />
35394 * <ul style="padding:5px;padding-left:16px;">
35395 * <li>tree - The TreePanel</li>
35396 * <li>target - The node being targeted for the drop</li>
35397 * <li>data - The drag data from the drag source</li>
35398 * <li>point - The point of the drop - append, above or below</li>
35399 * <li>source - The drag source</li>
35400 * <li>rawEvent - Raw mouse event</li>
35401 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
35402 * to be inserted by setting them on this object.</li>
35403 * <li>cancel - Set this to true to cancel the drop.</li>
35405 * @param {Object} dropEvent
35407 "beforenodedrop" : true,
35410 * Fires after a DD object is dropped on a node in this tree. The dropEvent
35411 * passed to handlers has the following properties:<br />
35412 * <ul style="padding:5px;padding-left:16px;">
35413 * <li>tree - The TreePanel</li>
35414 * <li>target - The node being targeted for the drop</li>
35415 * <li>data - The drag data from the drag source</li>
35416 * <li>point - The point of the drop - append, above or below</li>
35417 * <li>source - The drag source</li>
35418 * <li>rawEvent - Raw mouse event</li>
35419 * <li>dropNode - Dropped node(s).</li>
35421 * @param {Object} dropEvent
35425 * @event nodedragover
35426 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
35427 * passed to handlers has the following properties:<br />
35428 * <ul style="padding:5px;padding-left:16px;">
35429 * <li>tree - The TreePanel</li>
35430 * <li>target - The node being targeted for the drop</li>
35431 * <li>data - The drag data from the drag source</li>
35432 * <li>point - The point of the drop - append, above or below</li>
35433 * <li>source - The drag source</li>
35434 * <li>rawEvent - Raw mouse event</li>
35435 * <li>dropNode - Drop node(s) provided by the source.</li>
35436 * <li>cancel - Set this to true to signal drop not allowed.</li>
35438 * @param {Object} dragOverEvent
35440 "nodedragover" : true,
35442 * @event appendnode
35443 * Fires when append node to the tree
35444 * @param {Roo.tree.TreePanel} this
35445 * @param {Roo.tree.TreeNode} node
35446 * @param {Number} index The index of the newly appended node
35448 "appendnode" : true
35451 if(this.singleExpand){
35452 this.on("beforeexpand", this.restrictExpand, this);
35455 this.editor.tree = this;
35456 this.editor = Roo.factory(this.editor, Roo.tree);
35459 if (this.selModel) {
35460 this.selModel = Roo.factory(this.selModel, Roo.tree);
35464 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
35465 rootVisible : true,
35466 animate: Roo.enableFx,
35469 hlDrop : Roo.enableFx,
35473 rendererTip: false,
35475 restrictExpand : function(node){
35476 var p = node.parentNode;
35478 if(p.expandedChild && p.expandedChild.parentNode == p){
35479 p.expandedChild.collapse();
35481 p.expandedChild = node;
35485 // private override
35486 setRootNode : function(node){
35487 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
35488 if(!this.rootVisible){
35489 node.ui = new Roo.tree.RootTreeNodeUI(node);
35495 * Returns the container element for this TreePanel
35497 getEl : function(){
35502 * Returns the default TreeLoader for this TreePanel
35504 getLoader : function(){
35505 return this.loader;
35511 expandAll : function(){
35512 this.root.expand(true);
35516 * Collapse all nodes
35518 collapseAll : function(){
35519 this.root.collapse(true);
35523 * Returns the selection model used by this TreePanel
35525 getSelectionModel : function(){
35526 if(!this.selModel){
35527 this.selModel = new Roo.tree.DefaultSelectionModel();
35529 return this.selModel;
35533 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
35534 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
35535 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
35538 getChecked : function(a, startNode){
35539 startNode = startNode || this.root;
35541 var f = function(){
35542 if(this.attributes.checked){
35543 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
35546 startNode.cascade(f);
35551 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
35552 * @param {String} path
35553 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
35554 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
35555 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
35557 expandPath : function(path, attr, callback){
35558 attr = attr || "id";
35559 var keys = path.split(this.pathSeparator);
35560 var curNode = this.root;
35561 if(curNode.attributes[attr] != keys[1]){ // invalid root
35563 callback(false, null);
35568 var f = function(){
35569 if(++index == keys.length){
35571 callback(true, curNode);
35575 var c = curNode.findChild(attr, keys[index]);
35578 callback(false, curNode);
35583 c.expand(false, false, f);
35585 curNode.expand(false, false, f);
35589 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
35590 * @param {String} path
35591 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
35592 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
35593 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
35595 selectPath : function(path, attr, callback){
35596 attr = attr || "id";
35597 var keys = path.split(this.pathSeparator);
35598 var v = keys.pop();
35599 if(keys.length > 0){
35600 var f = function(success, node){
35601 if(success && node){
35602 var n = node.findChild(attr, v);
35608 }else if(callback){
35609 callback(false, n);
35613 callback(false, n);
35617 this.expandPath(keys.join(this.pathSeparator), attr, f);
35619 this.root.select();
35621 callback(true, this.root);
35626 getTreeEl : function(){
35631 * Trigger rendering of this TreePanel
35633 render : function(){
35634 if (this.innerCt) {
35635 return this; // stop it rendering more than once!!
35638 this.innerCt = this.el.createChild({tag:"ul",
35639 cls:"x-tree-root-ct " +
35640 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
35642 if(this.containerScroll){
35643 Roo.dd.ScrollManager.register(this.el);
35645 if((this.enableDD || this.enableDrop) && !this.dropZone){
35647 * The dropZone used by this tree if drop is enabled
35648 * @type Roo.tree.TreeDropZone
35650 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
35651 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
35654 if((this.enableDD || this.enableDrag) && !this.dragZone){
35656 * The dragZone used by this tree if drag is enabled
35657 * @type Roo.tree.TreeDragZone
35659 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
35660 ddGroup: this.ddGroup || "TreeDD",
35661 scroll: this.ddScroll
35664 this.getSelectionModel().init(this);
35666 Roo.log("ROOT not set in tree");
35669 this.root.render();
35670 if(!this.rootVisible){
35671 this.root.renderChildren();
35677 * Ext JS Library 1.1.1
35678 * Copyright(c) 2006-2007, Ext JS, LLC.
35680 * Originally Released Under LGPL - original licence link has changed is not relivant.
35683 * <script type="text/javascript">
35688 * @class Roo.tree.DefaultSelectionModel
35689 * @extends Roo.util.Observable
35690 * The default single selection for a TreePanel.
35691 * @param {Object} cfg Configuration
35693 Roo.tree.DefaultSelectionModel = function(cfg){
35694 this.selNode = null;
35700 * @event selectionchange
35701 * Fires when the selected node changes
35702 * @param {DefaultSelectionModel} this
35703 * @param {TreeNode} node the new selection
35705 "selectionchange" : true,
35708 * @event beforeselect
35709 * Fires before the selected node changes, return false to cancel the change
35710 * @param {DefaultSelectionModel} this
35711 * @param {TreeNode} node the new selection
35712 * @param {TreeNode} node the old selection
35714 "beforeselect" : true
35717 Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
35720 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
35721 init : function(tree){
35723 tree.getTreeEl().on("keydown", this.onKeyDown, this);
35724 tree.on("click", this.onNodeClick, this);
35727 onNodeClick : function(node, e){
35728 if (e.ctrlKey && this.selNode == node) {
35729 this.unselect(node);
35737 * @param {TreeNode} node The node to select
35738 * @return {TreeNode} The selected node
35740 select : function(node){
35741 var last = this.selNode;
35742 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
35744 last.ui.onSelectedChange(false);
35746 this.selNode = node;
35747 node.ui.onSelectedChange(true);
35748 this.fireEvent("selectionchange", this, node, last);
35755 * @param {TreeNode} node The node to unselect
35757 unselect : function(node){
35758 if(this.selNode == node){
35759 this.clearSelections();
35764 * Clear all selections
35766 clearSelections : function(){
35767 var n = this.selNode;
35769 n.ui.onSelectedChange(false);
35770 this.selNode = null;
35771 this.fireEvent("selectionchange", this, null);
35777 * Get the selected node
35778 * @return {TreeNode} The selected node
35780 getSelectedNode : function(){
35781 return this.selNode;
35785 * Returns true if the node is selected
35786 * @param {TreeNode} node The node to check
35787 * @return {Boolean}
35789 isSelected : function(node){
35790 return this.selNode == node;
35794 * Selects the node above the selected node in the tree, intelligently walking the nodes
35795 * @return TreeNode The new selection
35797 selectPrevious : function(){
35798 var s = this.selNode || this.lastSelNode;
35802 var ps = s.previousSibling;
35804 if(!ps.isExpanded() || ps.childNodes.length < 1){
35805 return this.select(ps);
35807 var lc = ps.lastChild;
35808 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
35811 return this.select(lc);
35813 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
35814 return this.select(s.parentNode);
35820 * Selects the node above the selected node in the tree, intelligently walking the nodes
35821 * @return TreeNode The new selection
35823 selectNext : function(){
35824 var s = this.selNode || this.lastSelNode;
35828 if(s.firstChild && s.isExpanded()){
35829 return this.select(s.firstChild);
35830 }else if(s.nextSibling){
35831 return this.select(s.nextSibling);
35832 }else if(s.parentNode){
35834 s.parentNode.bubble(function(){
35835 if(this.nextSibling){
35836 newS = this.getOwnerTree().selModel.select(this.nextSibling);
35845 onKeyDown : function(e){
35846 var s = this.selNode || this.lastSelNode;
35847 // undesirable, but required
35852 var k = e.getKey();
35860 this.selectPrevious();
35863 e.preventDefault();
35864 if(s.hasChildNodes()){
35865 if(!s.isExpanded()){
35867 }else if(s.firstChild){
35868 this.select(s.firstChild, e);
35873 e.preventDefault();
35874 if(s.hasChildNodes() && s.isExpanded()){
35876 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
35877 this.select(s.parentNode, e);
35885 * @class Roo.tree.MultiSelectionModel
35886 * @extends Roo.util.Observable
35887 * Multi selection for a TreePanel.
35888 * @param {Object} cfg Configuration
35890 Roo.tree.MultiSelectionModel = function(){
35891 this.selNodes = [];
35895 * @event selectionchange
35896 * Fires when the selected nodes change
35897 * @param {MultiSelectionModel} this
35898 * @param {Array} nodes Array of the selected nodes
35900 "selectionchange" : true
35902 Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
35906 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
35907 init : function(tree){
35909 tree.getTreeEl().on("keydown", this.onKeyDown, this);
35910 tree.on("click", this.onNodeClick, this);
35913 onNodeClick : function(node, e){
35914 this.select(node, e, e.ctrlKey);
35919 * @param {TreeNode} node The node to select
35920 * @param {EventObject} e (optional) An event associated with the selection
35921 * @param {Boolean} keepExisting True to retain existing selections
35922 * @return {TreeNode} The selected node
35924 select : function(node, e, keepExisting){
35925 if(keepExisting !== true){
35926 this.clearSelections(true);
35928 if(this.isSelected(node)){
35929 this.lastSelNode = node;
35932 this.selNodes.push(node);
35933 this.selMap[node.id] = node;
35934 this.lastSelNode = node;
35935 node.ui.onSelectedChange(true);
35936 this.fireEvent("selectionchange", this, this.selNodes);
35942 * @param {TreeNode} node The node to unselect
35944 unselect : function(node){
35945 if(this.selMap[node.id]){
35946 node.ui.onSelectedChange(false);
35947 var sn = this.selNodes;
35950 index = sn.indexOf(node);
35952 for(var i = 0, len = sn.length; i < len; i++){
35960 this.selNodes.splice(index, 1);
35962 delete this.selMap[node.id];
35963 this.fireEvent("selectionchange", this, this.selNodes);
35968 * Clear all selections
35970 clearSelections : function(suppressEvent){
35971 var sn = this.selNodes;
35973 for(var i = 0, len = sn.length; i < len; i++){
35974 sn[i].ui.onSelectedChange(false);
35976 this.selNodes = [];
35978 if(suppressEvent !== true){
35979 this.fireEvent("selectionchange", this, this.selNodes);
35985 * Returns true if the node is selected
35986 * @param {TreeNode} node The node to check
35987 * @return {Boolean}
35989 isSelected : function(node){
35990 return this.selMap[node.id] ? true : false;
35994 * Returns an array of the selected nodes
35997 getSelectedNodes : function(){
35998 return this.selNodes;
36001 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
36003 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
36005 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
36008 * Ext JS Library 1.1.1
36009 * Copyright(c) 2006-2007, Ext JS, LLC.
36011 * Originally Released Under LGPL - original licence link has changed is not relivant.
36014 * <script type="text/javascript">
36018 * @class Roo.tree.TreeNode
36019 * @extends Roo.data.Node
36020 * @cfg {String} text The text for this node
36021 * @cfg {Boolean} expanded true to start the node expanded
36022 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
36023 * @cfg {Boolean} allowDrop false if this node cannot be drop on
36024 * @cfg {Boolean} disabled true to start the node disabled
36025 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
36026 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
36027 * @cfg {String} cls A css class to be added to the node
36028 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
36029 * @cfg {String} href URL of the link used for the node (defaults to #)
36030 * @cfg {String} hrefTarget target frame for the link
36031 * @cfg {String} qtip An Ext QuickTip for the node
36032 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
36033 * @cfg {Boolean} singleClickExpand True for single click expand on this node
36034 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
36035 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
36036 * (defaults to undefined with no checkbox rendered)
36038 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
36040 Roo.tree.TreeNode = function(attributes){
36041 attributes = attributes || {};
36042 if(typeof attributes == "string"){
36043 attributes = {text: attributes};
36045 this.childrenRendered = false;
36046 this.rendered = false;
36047 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
36048 this.expanded = attributes.expanded === true;
36049 this.isTarget = attributes.isTarget !== false;
36050 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
36051 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
36054 * Read-only. The text for this node. To change it use setText().
36057 this.text = attributes.text;
36059 * True if this node is disabled.
36062 this.disabled = attributes.disabled === true;
36066 * @event textchange
36067 * Fires when the text for this node is changed
36068 * @param {Node} this This node
36069 * @param {String} text The new text
36070 * @param {String} oldText The old text
36072 "textchange" : true,
36074 * @event beforeexpand
36075 * Fires before this node is expanded, return false to cancel.
36076 * @param {Node} this This node
36077 * @param {Boolean} deep
36078 * @param {Boolean} anim
36080 "beforeexpand" : true,
36082 * @event beforecollapse
36083 * Fires before this node is collapsed, return false to cancel.
36084 * @param {Node} this This node
36085 * @param {Boolean} deep
36086 * @param {Boolean} anim
36088 "beforecollapse" : true,
36091 * Fires when this node is expanded
36092 * @param {Node} this This node
36096 * @event disabledchange
36097 * Fires when the disabled status of this node changes
36098 * @param {Node} this This node
36099 * @param {Boolean} disabled
36101 "disabledchange" : true,
36104 * Fires when this node is collapsed
36105 * @param {Node} this This node
36109 * @event beforeclick
36110 * Fires before click processing. Return false to cancel the default action.
36111 * @param {Node} this This node
36112 * @param {Roo.EventObject} e The event object
36114 "beforeclick":true,
36116 * @event checkchange
36117 * Fires when a node with a checkbox's checked property changes
36118 * @param {Node} this This node
36119 * @param {Boolean} checked
36121 "checkchange":true,
36124 * Fires when this node is clicked
36125 * @param {Node} this This node
36126 * @param {Roo.EventObject} e The event object
36131 * Fires when this node is double clicked
36132 * @param {Node} this This node
36133 * @param {Roo.EventObject} e The event object
36137 * @event contextmenu
36138 * Fires when this node is right clicked
36139 * @param {Node} this This node
36140 * @param {Roo.EventObject} e The event object
36142 "contextmenu":true,
36144 * @event beforechildrenrendered
36145 * Fires right before the child nodes for this node are rendered
36146 * @param {Node} this This node
36148 "beforechildrenrendered":true
36151 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
36154 * Read-only. The UI for this node
36157 this.ui = new uiClass(this);
36159 // finally support items[]
36160 if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
36165 Roo.each(this.attributes.items, function(c) {
36166 this.appendChild(Roo.factory(c,Roo.Tree));
36168 delete this.attributes.items;
36173 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
36174 preventHScroll: true,
36176 * Returns true if this node is expanded
36177 * @return {Boolean}
36179 isExpanded : function(){
36180 return this.expanded;
36184 * Returns the UI object for this node
36185 * @return {TreeNodeUI}
36187 getUI : function(){
36191 // private override
36192 setFirstChild : function(node){
36193 var of = this.firstChild;
36194 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
36195 if(this.childrenRendered && of && node != of){
36196 of.renderIndent(true, true);
36199 this.renderIndent(true, true);
36203 // private override
36204 setLastChild : function(node){
36205 var ol = this.lastChild;
36206 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
36207 if(this.childrenRendered && ol && node != ol){
36208 ol.renderIndent(true, true);
36211 this.renderIndent(true, true);
36215 // these methods are overridden to provide lazy rendering support
36216 // private override
36217 appendChild : function()
36219 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
36220 if(node && this.childrenRendered){
36223 this.ui.updateExpandIcon();
36227 // private override
36228 removeChild : function(node){
36229 this.ownerTree.getSelectionModel().unselect(node);
36230 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
36231 // if it's been rendered remove dom node
36232 if(this.childrenRendered){
36235 if(this.childNodes.length < 1){
36236 this.collapse(false, false);
36238 this.ui.updateExpandIcon();
36240 if(!this.firstChild) {
36241 this.childrenRendered = false;
36246 // private override
36247 insertBefore : function(node, refNode){
36248 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
36249 if(newNode && refNode && this.childrenRendered){
36252 this.ui.updateExpandIcon();
36257 * Sets the text for this node
36258 * @param {String} text
36260 setText : function(text){
36261 var oldText = this.text;
36263 this.attributes.text = text;
36264 if(this.rendered){ // event without subscribing
36265 this.ui.onTextChange(this, text, oldText);
36267 this.fireEvent("textchange", this, text, oldText);
36271 * Triggers selection of this node
36273 select : function(){
36274 this.getOwnerTree().getSelectionModel().select(this);
36278 * Triggers deselection of this node
36280 unselect : function(){
36281 this.getOwnerTree().getSelectionModel().unselect(this);
36285 * Returns true if this node is selected
36286 * @return {Boolean}
36288 isSelected : function(){
36289 return this.getOwnerTree().getSelectionModel().isSelected(this);
36293 * Expand this node.
36294 * @param {Boolean} deep (optional) True to expand all children as well
36295 * @param {Boolean} anim (optional) false to cancel the default animation
36296 * @param {Function} callback (optional) A callback to be called when
36297 * expanding this node completes (does not wait for deep expand to complete).
36298 * Called with 1 parameter, this node.
36300 expand : function(deep, anim, callback){
36301 if(!this.expanded){
36302 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
36305 if(!this.childrenRendered){
36306 this.renderChildren();
36308 this.expanded = true;
36310 if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
36311 this.ui.animExpand(function(){
36312 this.fireEvent("expand", this);
36313 if(typeof callback == "function"){
36317 this.expandChildNodes(true);
36319 }.createDelegate(this));
36323 this.fireEvent("expand", this);
36324 if(typeof callback == "function"){
36329 if(typeof callback == "function"){
36334 this.expandChildNodes(true);
36338 isHiddenRoot : function(){
36339 return this.isRoot && !this.getOwnerTree().rootVisible;
36343 * Collapse this node.
36344 * @param {Boolean} deep (optional) True to collapse all children as well
36345 * @param {Boolean} anim (optional) false to cancel the default animation
36347 collapse : function(deep, anim){
36348 if(this.expanded && !this.isHiddenRoot()){
36349 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
36352 this.expanded = false;
36353 if((this.getOwnerTree().animate && anim !== false) || anim){
36354 this.ui.animCollapse(function(){
36355 this.fireEvent("collapse", this);
36357 this.collapseChildNodes(true);
36359 }.createDelegate(this));
36362 this.ui.collapse();
36363 this.fireEvent("collapse", this);
36367 var cs = this.childNodes;
36368 for(var i = 0, len = cs.length; i < len; i++) {
36369 cs[i].collapse(true, false);
36375 delayedExpand : function(delay){
36376 if(!this.expandProcId){
36377 this.expandProcId = this.expand.defer(delay, this);
36382 cancelExpand : function(){
36383 if(this.expandProcId){
36384 clearTimeout(this.expandProcId);
36386 this.expandProcId = false;
36390 * Toggles expanded/collapsed state of the node
36392 toggle : function(){
36401 * Ensures all parent nodes are expanded
36403 ensureVisible : function(callback){
36404 var tree = this.getOwnerTree();
36405 tree.expandPath(this.parentNode.getPath(), false, function(){
36406 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
36407 Roo.callback(callback);
36408 }.createDelegate(this));
36412 * Expand all child nodes
36413 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
36415 expandChildNodes : function(deep){
36416 var cs = this.childNodes;
36417 for(var i = 0, len = cs.length; i < len; i++) {
36418 cs[i].expand(deep);
36423 * Collapse all child nodes
36424 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
36426 collapseChildNodes : function(deep){
36427 var cs = this.childNodes;
36428 for(var i = 0, len = cs.length; i < len; i++) {
36429 cs[i].collapse(deep);
36434 * Disables this node
36436 disable : function(){
36437 this.disabled = true;
36439 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36440 this.ui.onDisableChange(this, true);
36442 this.fireEvent("disabledchange", this, true);
36446 * Enables this node
36448 enable : function(){
36449 this.disabled = false;
36450 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
36451 this.ui.onDisableChange(this, false);
36453 this.fireEvent("disabledchange", this, false);
36457 renderChildren : function(suppressEvent){
36458 if(suppressEvent !== false){
36459 this.fireEvent("beforechildrenrendered", this);
36461 var cs = this.childNodes;
36462 for(var i = 0, len = cs.length; i < len; i++){
36463 cs[i].render(true);
36465 this.childrenRendered = true;
36469 sort : function(fn, scope){
36470 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
36471 if(this.childrenRendered){
36472 var cs = this.childNodes;
36473 for(var i = 0, len = cs.length; i < len; i++){
36474 cs[i].render(true);
36480 render : function(bulkRender){
36481 this.ui.render(bulkRender);
36482 if(!this.rendered){
36483 this.rendered = true;
36485 this.expanded = false;
36486 this.expand(false, false);
36492 renderIndent : function(deep, refresh){
36494 this.ui.childIndent = null;
36496 this.ui.renderIndent();
36497 if(deep === true && this.childrenRendered){
36498 var cs = this.childNodes;
36499 for(var i = 0, len = cs.length; i < len; i++){
36500 cs[i].renderIndent(true, refresh);
36506 * Ext JS Library 1.1.1
36507 * Copyright(c) 2006-2007, Ext JS, LLC.
36509 * Originally Released Under LGPL - original licence link has changed is not relivant.
36512 * <script type="text/javascript">
36516 * @class Roo.tree.AsyncTreeNode
36517 * @extends Roo.tree.TreeNode
36518 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
36520 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
36522 Roo.tree.AsyncTreeNode = function(config){
36523 this.loaded = false;
36524 this.loading = false;
36525 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
36527 * @event beforeload
36528 * Fires before this node is loaded, return false to cancel
36529 * @param {Node} this This node
36531 this.addEvents({'beforeload':true, 'load': true});
36534 * Fires when this node is loaded
36535 * @param {Node} this This node
36538 * The loader used by this node (defaults to using the tree's defined loader)
36543 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
36544 expand : function(deep, anim, callback){
36545 if(this.loading){ // if an async load is already running, waiting til it's done
36547 var f = function(){
36548 if(!this.loading){ // done loading
36549 clearInterval(timer);
36550 this.expand(deep, anim, callback);
36552 }.createDelegate(this);
36553 timer = setInterval(f, 200);
36557 if(this.fireEvent("beforeload", this) === false){
36560 this.loading = true;
36561 this.ui.beforeLoad(this);
36562 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
36564 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
36568 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
36572 * Returns true if this node is currently loading
36573 * @return {Boolean}
36575 isLoading : function(){
36576 return this.loading;
36579 loadComplete : function(deep, anim, callback){
36580 this.loading = false;
36581 this.loaded = true;
36582 this.ui.afterLoad(this);
36583 this.fireEvent("load", this);
36584 this.expand(deep, anim, callback);
36588 * Returns true if this node has been loaded
36589 * @return {Boolean}
36591 isLoaded : function(){
36592 return this.loaded;
36595 hasChildNodes : function(){
36596 if(!this.isLeaf() && !this.loaded){
36599 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
36604 * Trigger a reload for this node
36605 * @param {Function} callback
36607 reload : function(callback){
36608 this.collapse(false, false);
36609 while(this.firstChild){
36610 this.removeChild(this.firstChild);
36612 this.childrenRendered = false;
36613 this.loaded = false;
36614 if(this.isHiddenRoot()){
36615 this.expanded = false;
36617 this.expand(false, false, callback);
36621 * Ext JS Library 1.1.1
36622 * Copyright(c) 2006-2007, Ext JS, LLC.
36624 * Originally Released Under LGPL - original licence link has changed is not relivant.
36627 * <script type="text/javascript">
36631 * @class Roo.tree.TreeNodeUI
36633 * @param {Object} node The node to render
36634 * The TreeNode UI implementation is separate from the
36635 * tree implementation. Unless you are customizing the tree UI,
36636 * you should never have to use this directly.
36638 Roo.tree.TreeNodeUI = function(node){
36640 this.rendered = false;
36641 this.animating = false;
36642 this.emptyIcon = Roo.BLANK_IMAGE_URL;
36645 Roo.tree.TreeNodeUI.prototype = {
36646 removeChild : function(node){
36648 this.ctNode.removeChild(node.ui.getEl());
36652 beforeLoad : function(){
36653 this.addClass("x-tree-node-loading");
36656 afterLoad : function(){
36657 this.removeClass("x-tree-node-loading");
36660 onTextChange : function(node, text, oldText){
36662 this.textNode.innerHTML = text;
36666 onDisableChange : function(node, state){
36667 this.disabled = state;
36669 this.addClass("x-tree-node-disabled");
36671 this.removeClass("x-tree-node-disabled");
36675 onSelectedChange : function(state){
36678 this.addClass("x-tree-selected");
36681 this.removeClass("x-tree-selected");
36685 onMove : function(tree, node, oldParent, newParent, index, refNode){
36686 this.childIndent = null;
36688 var targetNode = newParent.ui.getContainer();
36689 if(!targetNode){//target not rendered
36690 this.holder = document.createElement("div");
36691 this.holder.appendChild(this.wrap);
36694 var insertBefore = refNode ? refNode.ui.getEl() : null;
36696 targetNode.insertBefore(this.wrap, insertBefore);
36698 targetNode.appendChild(this.wrap);
36700 this.node.renderIndent(true);
36704 addClass : function(cls){
36706 Roo.fly(this.elNode).addClass(cls);
36710 removeClass : function(cls){
36712 Roo.fly(this.elNode).removeClass(cls);
36716 remove : function(){
36718 this.holder = document.createElement("div");
36719 this.holder.appendChild(this.wrap);
36723 fireEvent : function(){
36724 return this.node.fireEvent.apply(this.node, arguments);
36727 initEvents : function(){
36728 this.node.on("move", this.onMove, this);
36729 var E = Roo.EventManager;
36730 var a = this.anchor;
36732 var el = Roo.fly(a, '_treeui');
36734 if(Roo.isOpera){ // opera render bug ignores the CSS
36735 el.setStyle("text-decoration", "none");
36738 el.on("click", this.onClick, this);
36739 el.on("dblclick", this.onDblClick, this);
36742 Roo.EventManager.on(this.checkbox,
36743 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
36746 el.on("contextmenu", this.onContextMenu, this);
36748 var icon = Roo.fly(this.iconNode);
36749 icon.on("click", this.onClick, this);
36750 icon.on("dblclick", this.onDblClick, this);
36751 icon.on("contextmenu", this.onContextMenu, this);
36752 E.on(this.ecNode, "click", this.ecClick, this, true);
36754 if(this.node.disabled){
36755 this.addClass("x-tree-node-disabled");
36757 if(this.node.hidden){
36758 this.addClass("x-tree-node-disabled");
36760 var ot = this.node.getOwnerTree();
36761 var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
36762 if(dd && (!this.node.isRoot || ot.rootVisible)){
36763 Roo.dd.Registry.register(this.elNode, {
36765 handles: this.getDDHandles(),
36771 getDDHandles : function(){
36772 return [this.iconNode, this.textNode];
36777 this.wrap.style.display = "none";
36783 this.wrap.style.display = "";
36787 onContextMenu : function(e){
36788 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
36789 e.preventDefault();
36791 this.fireEvent("contextmenu", this.node, e);
36795 onClick : function(e){
36800 if(this.fireEvent("beforeclick", this.node, e) !== false){
36801 if(!this.disabled && this.node.attributes.href){
36802 this.fireEvent("click", this.node, e);
36805 e.preventDefault();
36810 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
36811 this.node.toggle();
36814 this.fireEvent("click", this.node, e);
36820 onDblClick : function(e){
36821 e.preventDefault();
36826 this.toggleCheck();
36828 if(!this.animating && this.node.hasChildNodes()){
36829 this.node.toggle();
36831 this.fireEvent("dblclick", this.node, e);
36834 onCheckChange : function(){
36835 var checked = this.checkbox.checked;
36836 this.node.attributes.checked = checked;
36837 this.fireEvent('checkchange', this.node, checked);
36840 ecClick : function(e){
36841 if(!this.animating && this.node.hasChildNodes()){
36842 this.node.toggle();
36846 startDrop : function(){
36847 this.dropping = true;
36850 // delayed drop so the click event doesn't get fired on a drop
36851 endDrop : function(){
36852 setTimeout(function(){
36853 this.dropping = false;
36854 }.createDelegate(this), 50);
36857 expand : function(){
36858 this.updateExpandIcon();
36859 this.ctNode.style.display = "";
36862 focus : function(){
36863 if(!this.node.preventHScroll){
36864 try{this.anchor.focus();
36866 }else if(!Roo.isIE){
36868 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
36869 var l = noscroll.scrollLeft;
36870 this.anchor.focus();
36871 noscroll.scrollLeft = l;
36876 toggleCheck : function(value){
36877 var cb = this.checkbox;
36879 cb.checked = (value === undefined ? !cb.checked : value);
36885 this.anchor.blur();
36889 animExpand : function(callback){
36890 var ct = Roo.get(this.ctNode);
36892 if(!this.node.hasChildNodes()){
36893 this.updateExpandIcon();
36894 this.ctNode.style.display = "";
36895 Roo.callback(callback);
36898 this.animating = true;
36899 this.updateExpandIcon();
36902 callback : function(){
36903 this.animating = false;
36904 Roo.callback(callback);
36907 duration: this.node.ownerTree.duration || .25
36911 highlight : function(){
36912 var tree = this.node.getOwnerTree();
36913 Roo.fly(this.wrap).highlight(
36914 tree.hlColor || "C3DAF9",
36915 {endColor: tree.hlBaseColor}
36919 collapse : function(){
36920 this.updateExpandIcon();
36921 this.ctNode.style.display = "none";
36924 animCollapse : function(callback){
36925 var ct = Roo.get(this.ctNode);
36926 ct.enableDisplayMode('block');
36929 this.animating = true;
36930 this.updateExpandIcon();
36933 callback : function(){
36934 this.animating = false;
36935 Roo.callback(callback);
36938 duration: this.node.ownerTree.duration || .25
36942 getContainer : function(){
36943 return this.ctNode;
36946 getEl : function(){
36950 appendDDGhost : function(ghostNode){
36951 ghostNode.appendChild(this.elNode.cloneNode(true));
36954 getDDRepairXY : function(){
36955 return Roo.lib.Dom.getXY(this.iconNode);
36958 onRender : function(){
36962 render : function(bulkRender){
36963 var n = this.node, a = n.attributes;
36964 var targetNode = n.parentNode ?
36965 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
36967 if(!this.rendered){
36968 this.rendered = true;
36970 this.renderElements(n, a, targetNode, bulkRender);
36973 if(this.textNode.setAttributeNS){
36974 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
36976 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
36979 this.textNode.setAttribute("ext:qtip", a.qtip);
36981 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
36984 }else if(a.qtipCfg){
36985 a.qtipCfg.target = Roo.id(this.textNode);
36986 Roo.QuickTips.register(a.qtipCfg);
36989 if(!this.node.expanded){
36990 this.updateExpandIcon();
36993 if(bulkRender === true) {
36994 targetNode.appendChild(this.wrap);
36999 renderElements : function(n, a, targetNode, bulkRender)
37001 // add some indent caching, this helps performance when rendering a large tree
37002 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
37003 var t = n.getOwnerTree();
37004 var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
37005 if (typeof(n.attributes.html) != 'undefined') {
37006 txt = n.attributes.html;
37008 var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
37009 var cb = typeof a.checked == 'boolean';
37010 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
37011 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
37012 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
37013 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
37014 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
37015 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
37016 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
37017 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
37018 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
37019 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
37022 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
37023 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
37024 n.nextSibling.ui.getEl(), buf.join(""));
37026 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
37029 this.elNode = this.wrap.childNodes[0];
37030 this.ctNode = this.wrap.childNodes[1];
37031 var cs = this.elNode.childNodes;
37032 this.indentNode = cs[0];
37033 this.ecNode = cs[1];
37034 this.iconNode = cs[2];
37037 this.checkbox = cs[3];
37040 this.anchor = cs[index];
37041 this.textNode = cs[index].firstChild;
37044 getAnchor : function(){
37045 return this.anchor;
37048 getTextEl : function(){
37049 return this.textNode;
37052 getIconEl : function(){
37053 return this.iconNode;
37056 isChecked : function(){
37057 return this.checkbox ? this.checkbox.checked : false;
37060 updateExpandIcon : function(){
37062 var n = this.node, c1, c2;
37063 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
37064 var hasChild = n.hasChildNodes();
37068 c1 = "x-tree-node-collapsed";
37069 c2 = "x-tree-node-expanded";
37072 c1 = "x-tree-node-expanded";
37073 c2 = "x-tree-node-collapsed";
37076 this.removeClass("x-tree-node-leaf");
37077 this.wasLeaf = false;
37079 if(this.c1 != c1 || this.c2 != c2){
37080 Roo.fly(this.elNode).replaceClass(c1, c2);
37081 this.c1 = c1; this.c2 = c2;
37084 // this changes non-leafs into leafs if they have no children.
37085 // it's not very rational behaviour..
37087 if(!this.wasLeaf && this.node.leaf){
37088 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
37091 this.wasLeaf = true;
37094 var ecc = "x-tree-ec-icon "+cls;
37095 if(this.ecc != ecc){
37096 this.ecNode.className = ecc;
37102 getChildIndent : function(){
37103 if(!this.childIndent){
37107 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
37109 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
37111 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
37116 this.childIndent = buf.join("");
37118 return this.childIndent;
37121 renderIndent : function(){
37124 var p = this.node.parentNode;
37126 indent = p.ui.getChildIndent();
37128 if(this.indentMarkup != indent){ // don't rerender if not required
37129 this.indentNode.innerHTML = indent;
37130 this.indentMarkup = indent;
37132 this.updateExpandIcon();
37137 Roo.tree.RootTreeNodeUI = function(){
37138 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
37140 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
37141 render : function(){
37142 if(!this.rendered){
37143 var targetNode = this.node.ownerTree.innerCt.dom;
37144 this.node.expanded = true;
37145 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
37146 this.wrap = this.ctNode = targetNode.firstChild;
37149 collapse : function(){
37151 expand : function(){
37155 * Ext JS Library 1.1.1
37156 * Copyright(c) 2006-2007, Ext JS, LLC.
37158 * Originally Released Under LGPL - original licence link has changed is not relivant.
37161 * <script type="text/javascript">
37164 * @class Roo.tree.TreeLoader
37165 * @extends Roo.util.Observable
37166 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
37167 * nodes from a specified URL. The response must be a javascript Array definition
37168 * who's elements are node definition objects. eg:
37173 { 'id': 1, 'text': 'A folder Node', 'leaf': false },
37174 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
37181 * The old style respose with just an array is still supported, but not recommended.
37184 * A server request is sent, and child nodes are loaded only when a node is expanded.
37185 * The loading node's id is passed to the server under the parameter name "node" to
37186 * enable the server to produce the correct child nodes.
37188 * To pass extra parameters, an event handler may be attached to the "beforeload"
37189 * event, and the parameters specified in the TreeLoader's baseParams property:
37191 myTreeLoader.on("beforeload", function(treeLoader, node) {
37192 this.baseParams.category = node.attributes.category;
37197 * This would pass an HTTP parameter called "category" to the server containing
37198 * the value of the Node's "category" attribute.
37200 * Creates a new Treeloader.
37201 * @param {Object} config A config object containing config properties.
37203 Roo.tree.TreeLoader = function(config){
37204 this.baseParams = {};
37205 this.requestMethod = "POST";
37206 Roo.apply(this, config);
37211 * @event beforeload
37212 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
37213 * @param {Object} This TreeLoader object.
37214 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37215 * @param {Object} callback The callback function specified in the {@link #load} call.
37220 * Fires when the node has been successfuly loaded.
37221 * @param {Object} This TreeLoader object.
37222 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37223 * @param {Object} response The response object containing the data from the server.
37227 * @event loadexception
37228 * Fires if the network request failed.
37229 * @param {Object} This TreeLoader object.
37230 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
37231 * @param {Object} response The response object containing the data from the server.
37233 loadexception : true,
37236 * Fires before a node is created, enabling you to return custom Node types
37237 * @param {Object} This TreeLoader object.
37238 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
37243 Roo.tree.TreeLoader.superclass.constructor.call(this);
37246 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
37248 * @cfg {String} dataUrl The URL from which to request a Json string which
37249 * specifies an array of node definition object representing the child nodes
37253 * @cfg {String} requestMethod either GET or POST
37254 * defaults to POST (due to BC)
37258 * @cfg {Object} baseParams (optional) An object containing properties which
37259 * specify HTTP parameters to be passed to each request for child nodes.
37262 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
37263 * created by this loader. If the attributes sent by the server have an attribute in this object,
37264 * they take priority.
37267 * @cfg {Object} uiProviders (optional) An object containing properties which
37269 * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
37270 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
37271 * <i>uiProvider</i> attribute of a returned child node is a string rather
37272 * than a reference to a TreeNodeUI implementation, this that string value
37273 * is used as a property name in the uiProviders object. You can define the provider named
37274 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
37279 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
37280 * child nodes before loading.
37282 clearOnLoad : true,
37285 * @cfg {String} root (optional) Default to false. Use this to read data from an object
37286 * property on loading, rather than expecting an array. (eg. more compatible to a standard
37287 * Grid query { data : [ .....] }
37292 * @cfg {String} queryParam (optional)
37293 * Name of the query as it will be passed on the querystring (defaults to 'node')
37294 * eg. the request will be ?node=[id]
37301 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
37302 * This is called automatically when a node is expanded, but may be used to reload
37303 * a node (or append new children if the {@link #clearOnLoad} option is false.)
37304 * @param {Roo.tree.TreeNode} node
37305 * @param {Function} callback
37307 load : function(node, callback){
37308 if(this.clearOnLoad){
37309 while(node.firstChild){
37310 node.removeChild(node.firstChild);
37313 if(node.attributes.children){ // preloaded json children
37314 var cs = node.attributes.children;
37315 for(var i = 0, len = cs.length; i < len; i++){
37316 node.appendChild(this.createNode(cs[i]));
37318 if(typeof callback == "function"){
37321 }else if(this.dataUrl){
37322 this.requestData(node, callback);
37326 getParams: function(node){
37327 var buf = [], bp = this.baseParams;
37328 for(var key in bp){
37329 if(typeof bp[key] != "function"){
37330 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
37333 var n = this.queryParam === false ? 'node' : this.queryParam;
37334 buf.push(n + "=", encodeURIComponent(node.id));
37335 return buf.join("");
37338 requestData : function(node, callback){
37339 if(this.fireEvent("beforeload", this, node, callback) !== false){
37340 this.transId = Roo.Ajax.request({
37341 method:this.requestMethod,
37342 url: this.dataUrl||this.url,
37343 success: this.handleResponse,
37344 failure: this.handleFailure,
37346 argument: {callback: callback, node: node},
37347 params: this.getParams(node)
37350 // if the load is cancelled, make sure we notify
37351 // the node that we are done
37352 if(typeof callback == "function"){
37358 isLoading : function(){
37359 return this.transId ? true : false;
37362 abort : function(){
37363 if(this.isLoading()){
37364 Roo.Ajax.abort(this.transId);
37369 createNode : function(attr)
37371 // apply baseAttrs, nice idea Corey!
37372 if(this.baseAttrs){
37373 Roo.applyIf(attr, this.baseAttrs);
37375 if(this.applyLoader !== false){
37376 attr.loader = this;
37378 // uiProvider = depreciated..
37380 if(typeof(attr.uiProvider) == 'string'){
37381 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
37382 /** eval:var:attr */ eval(attr.uiProvider);
37384 if(typeof(this.uiProviders['default']) != 'undefined') {
37385 attr.uiProvider = this.uiProviders['default'];
37388 this.fireEvent('create', this, attr);
37390 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
37392 new Roo.tree.TreeNode(attr) :
37393 new Roo.tree.AsyncTreeNode(attr));
37396 processResponse : function(response, node, callback)
37398 var json = response.responseText;
37401 var o = Roo.decode(json);
37403 if (this.root === false && typeof(o.success) != undefined) {
37404 this.root = 'data'; // the default behaviour for list like data..
37407 if (this.root !== false && !o.success) {
37408 // it's a failure condition.
37409 var a = response.argument;
37410 this.fireEvent("loadexception", this, a.node, response);
37411 Roo.log("Load failed - should have a handler really");
37417 if (this.root !== false) {
37421 for(var i = 0, len = o.length; i < len; i++){
37422 var n = this.createNode(o[i]);
37424 node.appendChild(n);
37427 if(typeof callback == "function"){
37428 callback(this, node);
37431 this.handleFailure(response);
37435 handleResponse : function(response){
37436 this.transId = false;
37437 var a = response.argument;
37438 this.processResponse(response, a.node, a.callback);
37439 this.fireEvent("load", this, a.node, response);
37442 handleFailure : function(response)
37444 // should handle failure better..
37445 this.transId = false;
37446 var a = response.argument;
37447 this.fireEvent("loadexception", this, a.node, response);
37448 if(typeof a.callback == "function"){
37449 a.callback(this, a.node);
37454 * Ext JS Library 1.1.1
37455 * Copyright(c) 2006-2007, Ext JS, LLC.
37457 * Originally Released Under LGPL - original licence link has changed is not relivant.
37460 * <script type="text/javascript">
37464 * @class Roo.tree.TreeFilter
37465 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
37466 * @param {TreePanel} tree
37467 * @param {Object} config (optional)
37469 Roo.tree.TreeFilter = function(tree, config){
37471 this.filtered = {};
37472 Roo.apply(this, config);
37475 Roo.tree.TreeFilter.prototype = {
37482 * Filter the data by a specific attribute.
37483 * @param {String/RegExp} value Either string that the attribute value
37484 * should start with or a RegExp to test against the attribute
37485 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
37486 * @param {TreeNode} startNode (optional) The node to start the filter at.
37488 filter : function(value, attr, startNode){
37489 attr = attr || "text";
37491 if(typeof value == "string"){
37492 var vlen = value.length;
37493 // auto clear empty filter
37494 if(vlen == 0 && this.clearBlank){
37498 value = value.toLowerCase();
37500 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
37502 }else if(value.exec){ // regex?
37504 return value.test(n.attributes[attr]);
37507 throw 'Illegal filter type, must be string or regex';
37509 this.filterBy(f, null, startNode);
37513 * Filter by a function. The passed function will be called with each
37514 * node in the tree (or from the startNode). If the function returns true, the node is kept
37515 * otherwise it is filtered. If a node is filtered, its children are also filtered.
37516 * @param {Function} fn The filter function
37517 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
37519 filterBy : function(fn, scope, startNode){
37520 startNode = startNode || this.tree.root;
37521 if(this.autoClear){
37524 var af = this.filtered, rv = this.reverse;
37525 var f = function(n){
37526 if(n == startNode){
37532 var m = fn.call(scope || n, n);
37540 startNode.cascade(f);
37543 if(typeof id != "function"){
37545 if(n && n.parentNode){
37546 n.parentNode.removeChild(n);
37554 * Clears the current filter. Note: with the "remove" option
37555 * set a filter cannot be cleared.
37557 clear : function(){
37559 var af = this.filtered;
37561 if(typeof id != "function"){
37568 this.filtered = {};
37573 * Ext JS Library 1.1.1
37574 * Copyright(c) 2006-2007, Ext JS, LLC.
37576 * Originally Released Under LGPL - original licence link has changed is not relivant.
37579 * <script type="text/javascript">
37584 * @class Roo.tree.TreeSorter
37585 * Provides sorting of nodes in a TreePanel
37587 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
37588 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
37589 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
37590 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
37591 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
37592 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
37594 * @param {TreePanel} tree
37595 * @param {Object} config
37597 Roo.tree.TreeSorter = function(tree, config){
37598 Roo.apply(this, config);
37599 tree.on("beforechildrenrendered", this.doSort, this);
37600 tree.on("append", this.updateSort, this);
37601 tree.on("insert", this.updateSort, this);
37603 var dsc = this.dir && this.dir.toLowerCase() == "desc";
37604 var p = this.property || "text";
37605 var sortType = this.sortType;
37606 var fs = this.folderSort;
37607 var cs = this.caseSensitive === true;
37608 var leafAttr = this.leafAttr || 'leaf';
37610 this.sortFn = function(n1, n2){
37612 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
37615 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
37619 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
37620 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
37622 return dsc ? +1 : -1;
37624 return dsc ? -1 : +1;
37631 Roo.tree.TreeSorter.prototype = {
37632 doSort : function(node){
37633 node.sort(this.sortFn);
37636 compareNodes : function(n1, n2){
37637 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
37640 updateSort : function(tree, node){
37641 if(node.childrenRendered){
37642 this.doSort.defer(1, this, [node]);
37647 * Ext JS Library 1.1.1
37648 * Copyright(c) 2006-2007, Ext JS, LLC.
37650 * Originally Released Under LGPL - original licence link has changed is not relivant.
37653 * <script type="text/javascript">
37656 if(Roo.dd.DropZone){
37658 Roo.tree.TreeDropZone = function(tree, config){
37659 this.allowParentInsert = false;
37660 this.allowContainerDrop = false;
37661 this.appendOnly = false;
37662 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
37664 this.lastInsertClass = "x-tree-no-status";
37665 this.dragOverData = {};
37668 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
37669 ddGroup : "TreeDD",
37672 expandDelay : 1000,
37674 expandNode : function(node){
37675 if(node.hasChildNodes() && !node.isExpanded()){
37676 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
37680 queueExpand : function(node){
37681 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
37684 cancelExpand : function(){
37685 if(this.expandProcId){
37686 clearTimeout(this.expandProcId);
37687 this.expandProcId = false;
37691 isValidDropPoint : function(n, pt, dd, e, data){
37692 if(!n || !data){ return false; }
37693 var targetNode = n.node;
37694 var dropNode = data.node;
37695 // default drop rules
37696 if(!(targetNode && targetNode.isTarget && pt)){
37699 if(pt == "append" && targetNode.allowChildren === false){
37702 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
37705 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
37708 // reuse the object
37709 var overEvent = this.dragOverData;
37710 overEvent.tree = this.tree;
37711 overEvent.target = targetNode;
37712 overEvent.data = data;
37713 overEvent.point = pt;
37714 overEvent.source = dd;
37715 overEvent.rawEvent = e;
37716 overEvent.dropNode = dropNode;
37717 overEvent.cancel = false;
37718 var result = this.tree.fireEvent("nodedragover", overEvent);
37719 return overEvent.cancel === false && result !== false;
37722 getDropPoint : function(e, n, dd)
37726 return tn.allowChildren !== false ? "append" : false; // always append for root
37728 var dragEl = n.ddel;
37729 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
37730 var y = Roo.lib.Event.getPageY(e);
37731 //var noAppend = tn.allowChildren === false || tn.isLeaf();
37733 // we may drop nodes anywhere, as long as allowChildren has not been set to false..
37734 var noAppend = tn.allowChildren === false;
37735 if(this.appendOnly || tn.parentNode.allowChildren === false){
37736 return noAppend ? false : "append";
37738 var noBelow = false;
37739 if(!this.allowParentInsert){
37740 noBelow = tn.hasChildNodes() && tn.isExpanded();
37742 var q = (b - t) / (noAppend ? 2 : 3);
37743 if(y >= t && y < (t + q)){
37745 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
37752 onNodeEnter : function(n, dd, e, data)
37754 this.cancelExpand();
37757 onNodeOver : function(n, dd, e, data)
37760 var pt = this.getDropPoint(e, n, dd);
37763 // auto node expand check
37764 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
37765 this.queueExpand(node);
37766 }else if(pt != "append"){
37767 this.cancelExpand();
37770 // set the insert point style on the target node
37771 var returnCls = this.dropNotAllowed;
37772 if(this.isValidDropPoint(n, pt, dd, e, data)){
37777 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
37778 cls = "x-tree-drag-insert-above";
37779 }else if(pt == "below"){
37780 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
37781 cls = "x-tree-drag-insert-below";
37783 returnCls = "x-tree-drop-ok-append";
37784 cls = "x-tree-drag-append";
37786 if(this.lastInsertClass != cls){
37787 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
37788 this.lastInsertClass = cls;
37795 onNodeOut : function(n, dd, e, data){
37797 this.cancelExpand();
37798 this.removeDropIndicators(n);
37801 onNodeDrop : function(n, dd, e, data){
37802 var point = this.getDropPoint(e, n, dd);
37803 var targetNode = n.node;
37804 targetNode.ui.startDrop();
37805 if(!this.isValidDropPoint(n, point, dd, e, data)){
37806 targetNode.ui.endDrop();
37809 // first try to find the drop node
37810 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
37813 target: targetNode,
37818 dropNode: dropNode,
37821 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
37822 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
37823 targetNode.ui.endDrop();
37826 // allow target changing
37827 targetNode = dropEvent.target;
37828 if(point == "append" && !targetNode.isExpanded()){
37829 targetNode.expand(false, null, function(){
37830 this.completeDrop(dropEvent);
37831 }.createDelegate(this));
37833 this.completeDrop(dropEvent);
37838 completeDrop : function(de){
37839 var ns = de.dropNode, p = de.point, t = de.target;
37840 if(!(ns instanceof Array)){
37844 for(var i = 0, len = ns.length; i < len; i++){
37847 t.parentNode.insertBefore(n, t);
37848 }else if(p == "below"){
37849 t.parentNode.insertBefore(n, t.nextSibling);
37855 if(this.tree.hlDrop){
37859 this.tree.fireEvent("nodedrop", de);
37862 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
37863 if(this.tree.hlDrop){
37864 dropNode.ui.focus();
37865 dropNode.ui.highlight();
37867 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
37870 getTree : function(){
37874 removeDropIndicators : function(n){
37877 Roo.fly(el).removeClass([
37878 "x-tree-drag-insert-above",
37879 "x-tree-drag-insert-below",
37880 "x-tree-drag-append"]);
37881 this.lastInsertClass = "_noclass";
37885 beforeDragDrop : function(target, e, id){
37886 this.cancelExpand();
37890 afterRepair : function(data){
37891 if(data && Roo.enableFx){
37892 data.node.ui.highlight();
37902 * Ext JS Library 1.1.1
37903 * Copyright(c) 2006-2007, Ext JS, LLC.
37905 * Originally Released Under LGPL - original licence link has changed is not relivant.
37908 * <script type="text/javascript">
37912 if(Roo.dd.DragZone){
37913 Roo.tree.TreeDragZone = function(tree, config){
37914 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
37918 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
37919 ddGroup : "TreeDD",
37921 onBeforeDrag : function(data, e){
37923 return n && n.draggable && !n.disabled;
37927 onInitDrag : function(e){
37928 var data = this.dragData;
37929 this.tree.getSelectionModel().select(data.node);
37930 this.proxy.update("");
37931 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
37932 this.tree.fireEvent("startdrag", this.tree, data.node, e);
37935 getRepairXY : function(e, data){
37936 return data.node.ui.getDDRepairXY();
37939 onEndDrag : function(data, e){
37940 this.tree.fireEvent("enddrag", this.tree, data.node, e);
37945 onValidDrop : function(dd, e, id){
37946 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
37950 beforeInvalidDrop : function(e, id){
37951 // this scrolls the original position back into view
37952 var sm = this.tree.getSelectionModel();
37953 sm.clearSelections();
37954 sm.select(this.dragData.node);
37959 * Ext JS Library 1.1.1
37960 * Copyright(c) 2006-2007, Ext JS, LLC.
37962 * Originally Released Under LGPL - original licence link has changed is not relivant.
37965 * <script type="text/javascript">
37968 * @class Roo.tree.TreeEditor
37969 * @extends Roo.Editor
37970 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
37971 * as the editor field.
37973 * @param {Object} config (used to be the tree panel.)
37974 * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
37976 * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
37977 * @cfg {Roo.form.TextField} field [required] The field configuration
37981 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
37984 if (oldconfig) { // old style..
37985 field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
37988 tree = config.tree;
37989 config.field = config.field || {};
37990 config.field.xtype = 'TextField';
37991 field = Roo.factory(config.field, Roo.form);
37993 config = config || {};
37998 * @event beforenodeedit
37999 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
38000 * false from the handler of this event.
38001 * @param {Editor} this
38002 * @param {Roo.tree.Node} node
38004 "beforenodeedit" : true
38008 Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
38012 tree.on('beforeclick', this.beforeNodeClick, this);
38013 tree.getTreeEl().on('mousedown', this.hide, this);
38014 this.on('complete', this.updateNode, this);
38015 this.on('beforestartedit', this.fitToTree, this);
38016 this.on('startedit', this.bindScroll, this, {delay:10});
38017 this.on('specialkey', this.onSpecialKey, this);
38020 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
38022 * @cfg {String} alignment
38023 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
38029 * @cfg {Boolean} hideEl
38030 * True to hide the bound element while the editor is displayed (defaults to false)
38034 * @cfg {String} cls
38035 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
38037 cls: "x-small-editor x-tree-editor",
38039 * @cfg {Boolean} shim
38040 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
38046 * @cfg {Number} maxWidth
38047 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
38048 * the containing tree element's size, it will be automatically limited for you to the container width, taking
38049 * scroll and client offsets into account prior to each edit.
38056 fitToTree : function(ed, el){
38057 var td = this.tree.getTreeEl().dom, nd = el.dom;
38058 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
38059 td.scrollLeft = nd.offsetLeft;
38063 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
38064 this.setSize(w, '');
38066 return this.fireEvent('beforenodeedit', this, this.editNode);
38071 triggerEdit : function(node){
38072 this.completeEdit();
38073 this.editNode = node;
38074 this.startEdit(node.ui.textNode, node.text);
38078 bindScroll : function(){
38079 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
38083 beforeNodeClick : function(node, e){
38084 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
38085 this.lastClick = new Date();
38086 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
38088 this.triggerEdit(node);
38095 updateNode : function(ed, value){
38096 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
38097 this.editNode.setText(value);
38101 onHide : function(){
38102 Roo.tree.TreeEditor.superclass.onHide.call(this);
38104 this.editNode.ui.focus();
38109 onSpecialKey : function(field, e){
38110 var k = e.getKey();
38114 }else if(k == e.ENTER && !e.hasModifier()){
38116 this.completeEdit();
38119 });//<Script type="text/javascript">
38122 * Ext JS Library 1.1.1
38123 * Copyright(c) 2006-2007, Ext JS, LLC.
38125 * Originally Released Under LGPL - original licence link has changed is not relivant.
38128 * <script type="text/javascript">
38132 * Not documented??? - probably should be...
38135 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
38136 //focus: Roo.emptyFn, // prevent odd scrolling behavior
38138 renderElements : function(n, a, targetNode, bulkRender){
38139 //consel.log("renderElements?");
38140 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
38142 var t = n.getOwnerTree();
38143 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
38145 var cols = t.columns;
38146 var bw = t.borderWidth;
38148 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
38149 var cb = typeof a.checked == "boolean";
38150 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38151 var colcls = 'x-t-' + tid + '-c0';
38153 '<li class="x-tree-node">',
38156 '<div class="x-tree-node-el ', a.cls,'">',
38158 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
38161 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
38162 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
38163 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
38164 (a.icon ? ' x-tree-node-inline-icon' : ''),
38165 (a.iconCls ? ' '+a.iconCls : ''),
38166 '" unselectable="on" />',
38167 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
38168 (a.checked ? 'checked="checked" />' : ' />')) : ''),
38170 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38171 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
38172 '<span unselectable="on" qtip="' + tx + '">',
38176 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
38177 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
38179 for(var i = 1, len = cols.length; i < len; i++){
38181 colcls = 'x-t-' + tid + '-c' +i;
38182 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
38183 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
38184 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
38190 '<div class="x-clear"></div></div>',
38191 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
38194 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
38195 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
38196 n.nextSibling.ui.getEl(), buf.join(""));
38198 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
38200 var el = this.wrap.firstChild;
38202 this.elNode = el.firstChild;
38203 this.ranchor = el.childNodes[1];
38204 this.ctNode = this.wrap.childNodes[1];
38205 var cs = el.firstChild.childNodes;
38206 this.indentNode = cs[0];
38207 this.ecNode = cs[1];
38208 this.iconNode = cs[2];
38211 this.checkbox = cs[3];
38214 this.anchor = cs[index];
38216 this.textNode = cs[index].firstChild;
38218 //el.on("click", this.onClick, this);
38219 //el.on("dblclick", this.onDblClick, this);
38222 // console.log(this);
38224 initEvents : function(){
38225 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
38228 var a = this.ranchor;
38230 var el = Roo.get(a);
38232 if(Roo.isOpera){ // opera render bug ignores the CSS
38233 el.setStyle("text-decoration", "none");
38236 el.on("click", this.onClick, this);
38237 el.on("dblclick", this.onDblClick, this);
38238 el.on("contextmenu", this.onContextMenu, this);
38242 /*onSelectedChange : function(state){
38245 this.addClass("x-tree-selected");
38248 this.removeClass("x-tree-selected");
38251 addClass : function(cls){
38253 Roo.fly(this.elRow).addClass(cls);
38259 removeClass : function(cls){
38261 Roo.fly(this.elRow).removeClass(cls);
38267 });//<Script type="text/javascript">
38271 * Ext JS Library 1.1.1
38272 * Copyright(c) 2006-2007, Ext JS, LLC.
38274 * Originally Released Under LGPL - original licence link has changed is not relivant.
38277 * <script type="text/javascript">
38282 * @class Roo.tree.ColumnTree
38283 * @extends Roo.tree.TreePanel
38284 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
38285 * @cfg {int} borderWidth compined right/left border allowance
38287 * @param {String/HTMLElement/Element} el The container element
38288 * @param {Object} config
38290 Roo.tree.ColumnTree = function(el, config)
38292 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
38296 * Fire this event on a container when it resizes
38297 * @param {int} w Width
38298 * @param {int} h Height
38302 this.on('resize', this.onResize, this);
38305 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
38309 borderWidth: Roo.isBorderBox ? 0 : 2,
38312 render : function(){
38313 // add the header.....
38315 Roo.tree.ColumnTree.superclass.render.apply(this);
38317 this.el.addClass('x-column-tree');
38319 this.headers = this.el.createChild(
38320 {cls:'x-tree-headers'},this.innerCt.dom);
38322 var cols = this.columns, c;
38323 var totalWidth = 0;
38325 var len = cols.length;
38326 for(var i = 0; i < len; i++){
38328 totalWidth += c.width;
38329 this.headEls.push(this.headers.createChild({
38330 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
38332 cls:'x-tree-hd-text',
38335 style:'width:'+(c.width-this.borderWidth)+'px;'
38338 this.headers.createChild({cls:'x-clear'});
38339 // prevent floats from wrapping when clipped
38340 this.headers.setWidth(totalWidth);
38341 //this.innerCt.setWidth(totalWidth);
38342 this.innerCt.setStyle({ overflow: 'auto' });
38343 this.onResize(this.width, this.height);
38347 onResize : function(w,h)
38352 this.innerCt.setWidth(this.width);
38353 this.innerCt.setHeight(this.height-20);
38356 var cols = this.columns, c;
38357 var totalWidth = 0;
38359 var len = cols.length;
38360 for(var i = 0; i < len; i++){
38362 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
38363 // it's the expander..
38364 expEl = this.headEls[i];
38367 totalWidth += c.width;
38371 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
38373 this.headers.setWidth(w-20);
38382 * Ext JS Library 1.1.1
38383 * Copyright(c) 2006-2007, Ext JS, LLC.
38385 * Originally Released Under LGPL - original licence link has changed is not relivant.
38388 * <script type="text/javascript">
38392 * @class Roo.menu.Menu
38393 * @extends Roo.util.Observable
38394 * @children Roo.menu.BaseItem
38395 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
38396 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
38398 * Creates a new Menu
38399 * @param {Object} config Configuration options
38401 Roo.menu.Menu = function(config){
38403 Roo.menu.Menu.superclass.constructor.call(this, config);
38405 this.id = this.id || Roo.id();
38408 * @event beforeshow
38409 * Fires before this menu is displayed
38410 * @param {Roo.menu.Menu} this
38414 * @event beforehide
38415 * Fires before this menu is hidden
38416 * @param {Roo.menu.Menu} this
38421 * Fires after this menu is displayed
38422 * @param {Roo.menu.Menu} this
38427 * Fires after this menu is hidden
38428 * @param {Roo.menu.Menu} this
38433 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
38434 * @param {Roo.menu.Menu} this
38435 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38436 * @param {Roo.EventObject} e
38441 * Fires when the mouse is hovering over this menu
38442 * @param {Roo.menu.Menu} this
38443 * @param {Roo.EventObject} e
38444 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38449 * Fires when the mouse exits this menu
38450 * @param {Roo.menu.Menu} this
38451 * @param {Roo.EventObject} e
38452 * @param {Roo.menu.Item} menuItem The menu item that was clicked
38457 * Fires when a menu item contained in this menu is clicked
38458 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
38459 * @param {Roo.EventObject} e
38463 if (this.registerMenu) {
38464 Roo.menu.MenuMgr.register(this);
38467 var mis = this.items;
38468 this.items = new Roo.util.MixedCollection();
38470 this.add.apply(this, mis);
38474 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
38476 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
38480 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
38481 * for bottom-right shadow (defaults to "sides")
38485 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
38486 * this menu (defaults to "tl-tr?")
38488 subMenuAlign : "tl-tr?",
38490 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
38491 * relative to its element of origin (defaults to "tl-bl?")
38493 defaultAlign : "tl-bl?",
38495 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
38497 allowOtherMenus : false,
38499 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
38501 registerMenu : true,
38506 render : function(){
38510 var el = this.el = new Roo.Layer({
38512 shadow:this.shadow,
38514 parentEl: this.parentEl || document.body,
38518 this.keyNav = new Roo.menu.MenuNav(this);
38521 el.addClass("x-menu-plain");
38524 el.addClass(this.cls);
38526 // generic focus element
38527 this.focusEl = el.createChild({
38528 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
38530 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
38531 //disabling touch- as it's causing issues ..
38532 //ul.on(Roo.isTouch ? 'touchstart' : 'click' , this.onClick, this);
38533 ul.on('click' , this.onClick, this);
38536 ul.on("mouseover", this.onMouseOver, this);
38537 ul.on("mouseout", this.onMouseOut, this);
38538 this.items.each(function(item){
38543 var li = document.createElement("li");
38544 li.className = "x-menu-list-item";
38545 ul.dom.appendChild(li);
38546 item.render(li, this);
38553 autoWidth : function(){
38554 var el = this.el, ul = this.ul;
38558 var w = this.width;
38561 }else if(Roo.isIE){
38562 el.setWidth(this.minWidth);
38563 var t = el.dom.offsetWidth; // force recalc
38564 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
38569 delayAutoWidth : function(){
38572 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
38574 this.awTask.delay(20);
38579 findTargetItem : function(e){
38580 var t = e.getTarget(".x-menu-list-item", this.ul, true);
38581 if(t && t.menuItemId){
38582 return this.items.get(t.menuItemId);
38587 onClick : function(e){
38588 Roo.log("menu.onClick");
38589 var t = this.findTargetItem(e);
38594 if (Roo.isTouch && e.type == 'touchstart' && t.menu && !t.disabled) {
38595 if(t == this.activeItem && t.shouldDeactivate(e)){
38596 this.activeItem.deactivate();
38597 delete this.activeItem;
38601 this.setActiveItem(t, true);
38609 this.fireEvent("click", this, t, e);
38613 setActiveItem : function(item, autoExpand){
38614 if(item != this.activeItem){
38615 if(this.activeItem){
38616 this.activeItem.deactivate();
38618 this.activeItem = item;
38619 item.activate(autoExpand);
38620 }else if(autoExpand){
38626 tryActivate : function(start, step){
38627 var items = this.items;
38628 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
38629 var item = items.get(i);
38630 if(!item.disabled && item.canActivate){
38631 this.setActiveItem(item, false);
38639 onMouseOver : function(e){
38641 if(t = this.findTargetItem(e)){
38642 if(t.canActivate && !t.disabled){
38643 this.setActiveItem(t, true);
38646 this.fireEvent("mouseover", this, e, t);
38650 onMouseOut : function(e){
38652 if(t = this.findTargetItem(e)){
38653 if(t == this.activeItem && t.shouldDeactivate(e)){
38654 this.activeItem.deactivate();
38655 delete this.activeItem;
38658 this.fireEvent("mouseout", this, e, t);
38662 * Read-only. Returns true if the menu is currently displayed, else false.
38665 isVisible : function(){
38666 return this.el && !this.hidden;
38670 * Displays this menu relative to another element
38671 * @param {String/HTMLElement/Roo.Element} element The element to align to
38672 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
38673 * the element (defaults to this.defaultAlign)
38674 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
38676 show : function(el, pos, parentMenu){
38677 this.parentMenu = parentMenu;
38681 this.fireEvent("beforeshow", this);
38682 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
38686 * Displays this menu at a specific xy position
38687 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
38688 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
38690 showAt : function(xy, parentMenu, /* private: */_e){
38691 this.parentMenu = parentMenu;
38696 this.fireEvent("beforeshow", this);
38697 xy = this.el.adjustForConstraints(xy);
38701 this.hidden = false;
38703 this.fireEvent("show", this);
38706 focus : function(){
38708 this.doFocus.defer(50, this);
38712 doFocus : function(){
38714 this.focusEl.focus();
38719 * Hides this menu and optionally all parent menus
38720 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
38722 hide : function(deep){
38723 if(this.el && this.isVisible()){
38724 this.fireEvent("beforehide", this);
38725 if(this.activeItem){
38726 this.activeItem.deactivate();
38727 this.activeItem = null;
38730 this.hidden = true;
38731 this.fireEvent("hide", this);
38733 if(deep === true && this.parentMenu){
38734 this.parentMenu.hide(true);
38739 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
38740 * Any of the following are valid:
38742 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
38743 * <li>An HTMLElement object which will be converted to a menu item</li>
38744 * <li>A menu item config object that will be created as a new menu item</li>
38745 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
38746 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
38751 var menu = new Roo.menu.Menu();
38753 // Create a menu item to add by reference
38754 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
38756 // Add a bunch of items at once using different methods.
38757 // Only the last item added will be returned.
38758 var item = menu.add(
38759 menuItem, // add existing item by ref
38760 'Dynamic Item', // new TextItem
38761 '-', // new separator
38762 { text: 'Config Item' } // new item by config
38765 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
38766 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
38769 var a = arguments, l = a.length, item;
38770 for(var i = 0; i < l; i++){
38772 if ((typeof(el) == "object") && el.xtype && el.xns) {
38773 el = Roo.factory(el, Roo.menu);
38776 if(el.render){ // some kind of Item
38777 item = this.addItem(el);
38778 }else if(typeof el == "string"){ // string
38779 if(el == "separator" || el == "-"){
38780 item = this.addSeparator();
38782 item = this.addText(el);
38784 }else if(el.tagName || el.el){ // element
38785 item = this.addElement(el);
38786 }else if(typeof el == "object"){ // must be menu item config?
38787 item = this.addMenuItem(el);
38794 * Returns this menu's underlying {@link Roo.Element} object
38795 * @return {Roo.Element} The element
38797 getEl : function(){
38805 * Adds a separator bar to the menu
38806 * @return {Roo.menu.Item} The menu item that was added
38808 addSeparator : function(){
38809 return this.addItem(new Roo.menu.Separator());
38813 * Adds an {@link Roo.Element} object to the menu
38814 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
38815 * @return {Roo.menu.Item} The menu item that was added
38817 addElement : function(el){
38818 return this.addItem(new Roo.menu.BaseItem(el));
38822 * Adds an existing object based on {@link Roo.menu.Item} to the menu
38823 * @param {Roo.menu.Item} item The menu item to add
38824 * @return {Roo.menu.Item} The menu item that was added
38826 addItem : function(item){
38827 this.items.add(item);
38829 var li = document.createElement("li");
38830 li.className = "x-menu-list-item";
38831 this.ul.dom.appendChild(li);
38832 item.render(li, this);
38833 this.delayAutoWidth();
38839 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
38840 * @param {Object} config A MenuItem config object
38841 * @return {Roo.menu.Item} The menu item that was added
38843 addMenuItem : function(config){
38844 if(!(config instanceof Roo.menu.Item)){
38845 if(typeof config.checked == "boolean"){ // must be check menu item config?
38846 config = new Roo.menu.CheckItem(config);
38848 config = new Roo.menu.Item(config);
38851 return this.addItem(config);
38855 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
38856 * @param {String} text The text to display in the menu item
38857 * @return {Roo.menu.Item} The menu item that was added
38859 addText : function(text){
38860 return this.addItem(new Roo.menu.TextItem({ text : text }));
38864 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
38865 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
38866 * @param {Roo.menu.Item} item The menu item to add
38867 * @return {Roo.menu.Item} The menu item that was added
38869 insert : function(index, item){
38870 this.items.insert(index, item);
38872 var li = document.createElement("li");
38873 li.className = "x-menu-list-item";
38874 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
38875 item.render(li, this);
38876 this.delayAutoWidth();
38882 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
38883 * @param {Roo.menu.Item} item The menu item to remove
38885 remove : function(item){
38886 this.items.removeKey(item.id);
38891 * Removes and destroys all items in the menu
38893 removeAll : function(){
38895 while(f = this.items.first()){
38901 // MenuNav is a private utility class used internally by the Menu
38902 Roo.menu.MenuNav = function(menu){
38903 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
38904 this.scope = this.menu = menu;
38907 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
38908 doRelay : function(e, h){
38909 var k = e.getKey();
38910 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
38911 this.menu.tryActivate(0, 1);
38914 return h.call(this.scope || this, e, this.menu);
38917 up : function(e, m){
38918 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
38919 m.tryActivate(m.items.length-1, -1);
38923 down : function(e, m){
38924 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
38925 m.tryActivate(0, 1);
38929 right : function(e, m){
38931 m.activeItem.expandMenu(true);
38935 left : function(e, m){
38937 if(m.parentMenu && m.parentMenu.activeItem){
38938 m.parentMenu.activeItem.activate();
38942 enter : function(e, m){
38944 e.stopPropagation();
38945 m.activeItem.onClick(e);
38946 m.fireEvent("click", this, m.activeItem);
38952 * Ext JS Library 1.1.1
38953 * Copyright(c) 2006-2007, Ext JS, LLC.
38955 * Originally Released Under LGPL - original licence link has changed is not relivant.
38958 * <script type="text/javascript">
38962 * @class Roo.menu.MenuMgr
38963 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
38966 Roo.menu.MenuMgr = function(){
38967 var menus, active, groups = {}, attached = false, lastShow = new Date();
38969 // private - called when first menu is created
38972 active = new Roo.util.MixedCollection();
38973 Roo.get(document).addKeyListener(27, function(){
38974 if(active.length > 0){
38981 function hideAll(){
38982 if(active && active.length > 0){
38983 var c = active.clone();
38984 c.each(function(m){
38991 function onHide(m){
38993 if(active.length < 1){
38994 Roo.get(document).un("mousedown", onMouseDown);
39000 function onShow(m){
39001 var last = active.last();
39002 lastShow = new Date();
39005 Roo.get(document).on("mousedown", onMouseDown);
39009 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
39010 m.parentMenu.activeChild = m;
39011 }else if(last && last.isVisible()){
39012 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
39017 function onBeforeHide(m){
39019 m.activeChild.hide();
39021 if(m.autoHideTimer){
39022 clearTimeout(m.autoHideTimer);
39023 delete m.autoHideTimer;
39028 function onBeforeShow(m){
39029 var pm = m.parentMenu;
39030 if(!pm && !m.allowOtherMenus){
39032 }else if(pm && pm.activeChild && active != m){
39033 pm.activeChild.hide();
39038 function onMouseDown(e){
39039 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
39045 function onBeforeCheck(mi, state){
39047 var g = groups[mi.group];
39048 for(var i = 0, l = g.length; i < l; i++){
39050 g[i].setChecked(false);
39059 * Hides all menus that are currently visible
39061 hideAll : function(){
39066 register : function(menu){
39070 menus[menu.id] = menu;
39071 menu.on("beforehide", onBeforeHide);
39072 menu.on("hide", onHide);
39073 menu.on("beforeshow", onBeforeShow);
39074 menu.on("show", onShow);
39075 var g = menu.group;
39076 if(g && menu.events["checkchange"]){
39080 groups[g].push(menu);
39081 menu.on("checkchange", onCheck);
39086 * Returns a {@link Roo.menu.Menu} object
39087 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
39088 * be used to generate and return a new Menu instance.
39090 get : function(menu){
39091 if(typeof menu == "string"){ // menu id
39092 return menus[menu];
39093 }else if(menu.events){ // menu instance
39095 }else if(typeof menu.length == 'number'){ // array of menu items?
39096 return new Roo.menu.Menu({items:menu});
39097 }else{ // otherwise, must be a config
39098 return new Roo.menu.Menu(menu);
39103 unregister : function(menu){
39104 delete menus[menu.id];
39105 menu.un("beforehide", onBeforeHide);
39106 menu.un("hide", onHide);
39107 menu.un("beforeshow", onBeforeShow);
39108 menu.un("show", onShow);
39109 var g = menu.group;
39110 if(g && menu.events["checkchange"]){
39111 groups[g].remove(menu);
39112 menu.un("checkchange", onCheck);
39117 registerCheckable : function(menuItem){
39118 var g = menuItem.group;
39123 groups[g].push(menuItem);
39124 menuItem.on("beforecheckchange", onBeforeCheck);
39129 unregisterCheckable : function(menuItem){
39130 var g = menuItem.group;
39132 groups[g].remove(menuItem);
39133 menuItem.un("beforecheckchange", onBeforeCheck);
39139 * Ext JS Library 1.1.1
39140 * Copyright(c) 2006-2007, Ext JS, LLC.
39142 * Originally Released Under LGPL - original licence link has changed is not relivant.
39145 * <script type="text/javascript">
39150 * @class Roo.menu.BaseItem
39151 * @extends Roo.Component
39153 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
39154 * management and base configuration options shared by all menu components.
39156 * Creates a new BaseItem
39157 * @param {Object} config Configuration options
39159 Roo.menu.BaseItem = function(config){
39160 Roo.menu.BaseItem.superclass.constructor.call(this, config);
39165 * Fires when this item is clicked
39166 * @param {Roo.menu.BaseItem} this
39167 * @param {Roo.EventObject} e
39172 * Fires when this item is activated
39173 * @param {Roo.menu.BaseItem} this
39177 * @event deactivate
39178 * Fires when this item is deactivated
39179 * @param {Roo.menu.BaseItem} this
39185 this.on("click", this.handler, this.scope, true);
39189 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
39191 * @cfg {Function} handler
39192 * A function that will handle the click event of this menu item (defaults to undefined)
39195 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
39197 canActivate : false,
39200 * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
39205 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
39207 activeClass : "x-menu-item-active",
39209 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
39211 hideOnClick : true,
39213 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
39218 ctype: "Roo.menu.BaseItem",
39221 actionMode : "container",
39224 render : function(container, parentMenu){
39225 this.parentMenu = parentMenu;
39226 Roo.menu.BaseItem.superclass.render.call(this, container);
39227 this.container.menuItemId = this.id;
39231 onRender : function(container, position){
39232 this.el = Roo.get(this.el);
39233 container.dom.appendChild(this.el.dom);
39237 onClick : function(e){
39238 if(!this.disabled && this.fireEvent("click", this, e) !== false
39239 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
39240 this.handleClick(e);
39247 activate : function(){
39251 var li = this.container;
39252 li.addClass(this.activeClass);
39253 this.region = li.getRegion().adjust(2, 2, -2, -2);
39254 this.fireEvent("activate", this);
39259 deactivate : function(){
39260 this.container.removeClass(this.activeClass);
39261 this.fireEvent("deactivate", this);
39265 shouldDeactivate : function(e){
39266 return !this.region || !this.region.contains(e.getPoint());
39270 handleClick : function(e){
39271 if(this.hideOnClick){
39272 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
39277 expandMenu : function(autoActivate){
39282 hideMenu : function(){
39287 * Ext JS Library 1.1.1
39288 * Copyright(c) 2006-2007, Ext JS, LLC.
39290 * Originally Released Under LGPL - original licence link has changed is not relivant.
39293 * <script type="text/javascript">
39297 * @class Roo.menu.Adapter
39298 * @extends Roo.menu.BaseItem
39300 * 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.
39301 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
39303 * Creates a new Adapter
39304 * @param {Object} config Configuration options
39306 Roo.menu.Adapter = function(component, config){
39307 Roo.menu.Adapter.superclass.constructor.call(this, config);
39308 this.component = component;
39310 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
39312 canActivate : true,
39315 onRender : function(container, position){
39316 this.component.render(container);
39317 this.el = this.component.getEl();
39321 activate : function(){
39325 this.component.focus();
39326 this.fireEvent("activate", this);
39331 deactivate : function(){
39332 this.fireEvent("deactivate", this);
39336 disable : function(){
39337 this.component.disable();
39338 Roo.menu.Adapter.superclass.disable.call(this);
39342 enable : function(){
39343 this.component.enable();
39344 Roo.menu.Adapter.superclass.enable.call(this);
39348 * Ext JS Library 1.1.1
39349 * Copyright(c) 2006-2007, Ext JS, LLC.
39351 * Originally Released Under LGPL - original licence link has changed is not relivant.
39354 * <script type="text/javascript">
39358 * @class Roo.menu.TextItem
39359 * @extends Roo.menu.BaseItem
39360 * Adds a static text string to a menu, usually used as either a heading or group separator.
39361 * Note: old style constructor with text is still supported.
39364 * Creates a new TextItem
39365 * @param {Object} cfg Configuration
39367 Roo.menu.TextItem = function(cfg){
39368 if (typeof(cfg) == 'string') {
39371 Roo.apply(this,cfg);
39374 Roo.menu.TextItem.superclass.constructor.call(this);
39377 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
39379 * @cfg {String} text Text to show on item.
39384 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39386 hideOnClick : false,
39388 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
39390 itemCls : "x-menu-text",
39393 onRender : function(){
39394 var s = document.createElement("span");
39395 s.className = this.itemCls;
39396 s.innerHTML = this.text;
39398 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
39402 * Ext JS Library 1.1.1
39403 * Copyright(c) 2006-2007, Ext JS, LLC.
39405 * Originally Released Under LGPL - original licence link has changed is not relivant.
39408 * <script type="text/javascript">
39412 * @class Roo.menu.Separator
39413 * @extends Roo.menu.BaseItem
39414 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
39415 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
39417 * @param {Object} config Configuration options
39419 Roo.menu.Separator = function(config){
39420 Roo.menu.Separator.superclass.constructor.call(this, config);
39423 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
39425 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
39427 itemCls : "x-menu-sep",
39429 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
39431 hideOnClick : false,
39434 onRender : function(li){
39435 var s = document.createElement("span");
39436 s.className = this.itemCls;
39437 s.innerHTML = " ";
39439 li.addClass("x-menu-sep-li");
39440 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
39444 * Ext JS Library 1.1.1
39445 * Copyright(c) 2006-2007, Ext JS, LLC.
39447 * Originally Released Under LGPL - original licence link has changed is not relivant.
39450 * <script type="text/javascript">
39453 * @class Roo.menu.Item
39454 * @extends Roo.menu.BaseItem
39455 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
39456 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
39457 * activation and click handling.
39459 * Creates a new Item
39460 * @param {Object} config Configuration options
39462 Roo.menu.Item = function(config){
39463 Roo.menu.Item.superclass.constructor.call(this, config);
39465 this.menu = Roo.menu.MenuMgr.get(this.menu);
39468 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
39470 * @cfg {Roo.menu.Menu} menu
39474 * @cfg {String} text
39475 * The text to show on the menu item.
39479 * @cfg {String} HTML to render in menu
39480 * The text to show on the menu item (HTML version).
39484 * @cfg {String} icon
39485 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
39489 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
39491 itemCls : "x-menu-item",
39493 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
39495 canActivate : true,
39497 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
39500 // doc'd in BaseItem
39504 ctype: "Roo.menu.Item",
39507 onRender : function(container, position){
39508 var el = document.createElement("a");
39509 el.hideFocus = true;
39510 el.unselectable = "on";
39511 el.href = this.href || "#";
39512 if(this.hrefTarget){
39513 el.target = this.hrefTarget;
39515 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
39517 var html = this.html.length ? this.html : String.format('{0}',this.text);
39519 el.innerHTML = String.format(
39520 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
39521 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
39523 Roo.menu.Item.superclass.onRender.call(this, container, position);
39527 * Sets the text to display in this menu item
39528 * @param {String} text The text to display
39529 * @param {Boolean} isHTML true to indicate text is pure html.
39531 setText : function(text, isHTML){
39539 var html = this.html.length ? this.html : String.format('{0}',this.text);
39541 this.el.update(String.format(
39542 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
39543 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
39544 this.parentMenu.autoWidth();
39549 handleClick : function(e){
39550 if(!this.href){ // if no link defined, stop the event automatically
39553 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
39557 activate : function(autoExpand){
39558 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
39568 shouldDeactivate : function(e){
39569 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
39570 if(this.menu && this.menu.isVisible()){
39571 return !this.menu.getEl().getRegion().contains(e.getPoint());
39579 deactivate : function(){
39580 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
39585 expandMenu : function(autoActivate){
39586 if(!this.disabled && this.menu){
39587 clearTimeout(this.hideTimer);
39588 delete this.hideTimer;
39589 if(!this.menu.isVisible() && !this.showTimer){
39590 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
39591 }else if (this.menu.isVisible() && autoActivate){
39592 this.menu.tryActivate(0, 1);
39598 deferExpand : function(autoActivate){
39599 delete this.showTimer;
39600 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
39602 this.menu.tryActivate(0, 1);
39607 hideMenu : function(){
39608 clearTimeout(this.showTimer);
39609 delete this.showTimer;
39610 if(!this.hideTimer && this.menu && this.menu.isVisible()){
39611 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
39616 deferHide : function(){
39617 delete this.hideTimer;
39622 * Ext JS Library 1.1.1
39623 * Copyright(c) 2006-2007, Ext JS, LLC.
39625 * Originally Released Under LGPL - original licence link has changed is not relivant.
39628 * <script type="text/javascript">
39632 * @class Roo.menu.CheckItem
39633 * @extends Roo.menu.Item
39634 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
39636 * Creates a new CheckItem
39637 * @param {Object} config Configuration options
39639 Roo.menu.CheckItem = function(config){
39640 Roo.menu.CheckItem.superclass.constructor.call(this, config);
39643 * @event beforecheckchange
39644 * Fires before the checked value is set, providing an opportunity to cancel if needed
39645 * @param {Roo.menu.CheckItem} this
39646 * @param {Boolean} checked The new checked value that will be set
39648 "beforecheckchange" : true,
39650 * @event checkchange
39651 * Fires after the checked value has been set
39652 * @param {Roo.menu.CheckItem} this
39653 * @param {Boolean} checked The checked value that was set
39655 "checkchange" : true
39657 if(this.checkHandler){
39658 this.on('checkchange', this.checkHandler, this.scope);
39661 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
39663 * @cfg {String} group
39664 * All check items with the same group name will automatically be grouped into a single-select
39665 * radio button group (defaults to '')
39668 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
39670 itemCls : "x-menu-item x-menu-check-item",
39672 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
39674 groupClass : "x-menu-group-item",
39677 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
39678 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
39679 * initialized with checked = true will be rendered as checked.
39684 ctype: "Roo.menu.CheckItem",
39687 onRender : function(c){
39688 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
39690 this.el.addClass(this.groupClass);
39692 Roo.menu.MenuMgr.registerCheckable(this);
39694 this.checked = false;
39695 this.setChecked(true, true);
39700 destroy : function(){
39702 Roo.menu.MenuMgr.unregisterCheckable(this);
39704 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
39708 * Set the checked state of this item
39709 * @param {Boolean} checked The new checked value
39710 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
39712 setChecked : function(state, suppressEvent){
39713 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
39714 if(this.container){
39715 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
39717 this.checked = state;
39718 if(suppressEvent !== true){
39719 this.fireEvent("checkchange", this, state);
39725 handleClick : function(e){
39726 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
39727 this.setChecked(!this.checked);
39729 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
39733 * Ext JS Library 1.1.1
39734 * Copyright(c) 2006-2007, Ext JS, LLC.
39736 * Originally Released Under LGPL - original licence link has changed is not relivant.
39739 * <script type="text/javascript">
39743 * @class Roo.menu.DateItem
39744 * @extends Roo.menu.Adapter
39745 * A menu item that wraps the {@link Roo.DatPicker} component.
39747 * Creates a new DateItem
39748 * @param {Object} config Configuration options
39750 Roo.menu.DateItem = function(config){
39751 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
39752 /** The Roo.DatePicker object @type Roo.DatePicker */
39753 this.picker = this.component;
39754 this.addEvents({select: true});
39756 this.picker.on("render", function(picker){
39757 picker.getEl().swallowEvent("click");
39758 picker.container.addClass("x-menu-date-item");
39761 this.picker.on("select", this.onSelect, this);
39764 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
39766 onSelect : function(picker, date){
39767 this.fireEvent("select", this, date, picker);
39768 Roo.menu.DateItem.superclass.handleClick.call(this);
39772 * Ext JS Library 1.1.1
39773 * Copyright(c) 2006-2007, Ext JS, LLC.
39775 * Originally Released Under LGPL - original licence link has changed is not relivant.
39778 * <script type="text/javascript">
39782 * @class Roo.menu.ColorItem
39783 * @extends Roo.menu.Adapter
39784 * A menu item that wraps the {@link Roo.ColorPalette} component.
39786 * Creates a new ColorItem
39787 * @param {Object} config Configuration options
39789 Roo.menu.ColorItem = function(config){
39790 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
39791 /** The Roo.ColorPalette object @type Roo.ColorPalette */
39792 this.palette = this.component;
39793 this.relayEvents(this.palette, ["select"]);
39794 if(this.selectHandler){
39795 this.on('select', this.selectHandler, this.scope);
39798 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
39800 * Ext JS Library 1.1.1
39801 * Copyright(c) 2006-2007, Ext JS, LLC.
39803 * Originally Released Under LGPL - original licence link has changed is not relivant.
39806 * <script type="text/javascript">
39811 * @class Roo.menu.DateMenu
39812 * @extends Roo.menu.Menu
39813 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
39815 * Creates a new DateMenu
39816 * @param {Object} config Configuration options
39818 Roo.menu.DateMenu = function(config){
39819 Roo.menu.DateMenu.superclass.constructor.call(this, config);
39821 var di = new Roo.menu.DateItem(config);
39824 * The {@link Roo.DatePicker} instance for this DateMenu
39827 this.picker = di.picker;
39830 * @param {DatePicker} picker
39831 * @param {Date} date
39833 this.relayEvents(di, ["select"]);
39834 this.on('beforeshow', function(){
39836 this.picker.hideMonthPicker(false);
39840 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
39844 * Ext JS Library 1.1.1
39845 * Copyright(c) 2006-2007, Ext JS, LLC.
39847 * Originally Released Under LGPL - original licence link has changed is not relivant.
39850 * <script type="text/javascript">
39855 * @class Roo.menu.ColorMenu
39856 * @extends Roo.menu.Menu
39857 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
39859 * Creates a new ColorMenu
39860 * @param {Object} config Configuration options
39862 Roo.menu.ColorMenu = function(config){
39863 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
39865 var ci = new Roo.menu.ColorItem(config);
39868 * The {@link Roo.ColorPalette} instance for this ColorMenu
39869 * @type ColorPalette
39871 this.palette = ci.palette;
39874 * @param {ColorPalette} palette
39875 * @param {String} color
39877 this.relayEvents(ci, ["select"]);
39879 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
39881 * Ext JS Library 1.1.1
39882 * Copyright(c) 2006-2007, Ext JS, LLC.
39884 * Originally Released Under LGPL - original licence link has changed is not relivant.
39887 * <script type="text/javascript">
39891 * @class Roo.form.TextItem
39892 * @extends Roo.BoxComponent
39893 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
39895 * Creates a new TextItem
39896 * @param {Object} config Configuration options
39898 Roo.form.TextItem = function(config){
39899 Roo.form.TextItem.superclass.constructor.call(this, config);
39902 Roo.extend(Roo.form.TextItem, Roo.BoxComponent, {
39905 * @cfg {String} tag the tag for this item (default div)
39909 * @cfg {String} html the content for this item
39913 getAutoCreate : function()
39926 onRender : function(ct, position)
39928 Roo.form.TextItem.superclass.onRender.call(this, ct, position);
39931 var cfg = this.getAutoCreate();
39933 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
39935 if (!cfg.name.length) {
39938 this.el = ct.createChild(cfg, position);
39943 * @param {String} html update the Contents of the element.
39945 setHTML : function(html)
39947 this.fieldEl.dom.innerHTML = html;
39952 * Ext JS Library 1.1.1
39953 * Copyright(c) 2006-2007, Ext JS, LLC.
39955 * Originally Released Under LGPL - original licence link has changed is not relivant.
39958 * <script type="text/javascript">
39962 * @class Roo.form.Field
39963 * @extends Roo.BoxComponent
39964 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
39966 * Creates a new Field
39967 * @param {Object} config Configuration options
39969 Roo.form.Field = function(config){
39970 Roo.form.Field.superclass.constructor.call(this, config);
39973 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
39975 * @cfg {String} fieldLabel Label to use when rendering a form.
39978 * @cfg {String} qtip Mouse over tip
39982 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
39984 invalidClass : "x-form-invalid",
39986 * @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")
39988 invalidText : "The value in this field is invalid",
39990 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
39992 focusClass : "x-form-focus",
39994 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
39995 automatic validation (defaults to "keyup").
39997 validationEvent : "keyup",
39999 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
40001 validateOnBlur : true,
40003 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
40005 validationDelay : 250,
40007 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
40008 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
40010 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
40012 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
40014 fieldClass : "x-form-field",
40016 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
40019 ----------- ----------------------------------------------------------------------
40020 qtip Display a quick tip when the user hovers over the field
40021 title Display a default browser title attribute popup
40022 under Add a block div beneath the field containing the error text
40023 side Add an error icon to the right of the field with a popup on hover
40024 [element id] Add the error text directly to the innerHTML of the specified element
40027 msgTarget : 'qtip',
40029 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
40034 * @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.
40039 * @cfg {Boolean} disabled True to disable the field (defaults to false).
40044 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
40046 inputType : undefined,
40049 * @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).
40051 tabIndex : undefined,
40054 isFormField : true,
40059 * @property {Roo.Element} fieldEl
40060 * Element Containing the rendered Field (with label etc.)
40063 * @cfg {Mixed} value A value to initialize this field with.
40068 * @cfg {String} name The field's HTML name attribute.
40071 * @cfg {String} cls A CSS class to apply to the field's underlying element.
40074 loadedValue : false,
40078 initComponent : function(){
40079 Roo.form.Field.superclass.initComponent.call(this);
40083 * Fires when this field receives input focus.
40084 * @param {Roo.form.Field} this
40089 * Fires when this field loses input focus.
40090 * @param {Roo.form.Field} this
40094 * @event specialkey
40095 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
40096 * {@link Roo.EventObject#getKey} to determine which key was pressed.
40097 * @param {Roo.form.Field} this
40098 * @param {Roo.EventObject} e The event object
40103 * Fires just before the field blurs if the field value has changed.
40104 * @param {Roo.form.Field} this
40105 * @param {Mixed} newValue The new value
40106 * @param {Mixed} oldValue The original value
40111 * Fires after the field has been marked as invalid.
40112 * @param {Roo.form.Field} this
40113 * @param {String} msg The validation message
40118 * Fires after the field has been validated with no errors.
40119 * @param {Roo.form.Field} this
40124 * Fires after the key up
40125 * @param {Roo.form.Field} this
40126 * @param {Roo.EventObject} e The event Object
40133 * Returns the name attribute of the field if available
40134 * @return {String} name The field name
40136 getName: function(){
40137 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
40141 onRender : function(ct, position){
40142 Roo.form.Field.superclass.onRender.call(this, ct, position);
40144 var cfg = this.getAutoCreate();
40146 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
40148 if (!cfg.name.length) {
40151 if(this.inputType){
40152 cfg.type = this.inputType;
40154 this.el = ct.createChild(cfg, position);
40156 var type = this.el.dom.type;
40158 if(type == 'password'){
40161 this.el.addClass('x-form-'+type);
40164 this.el.dom.readOnly = true;
40166 if(this.tabIndex !== undefined){
40167 this.el.dom.setAttribute('tabIndex', this.tabIndex);
40170 this.el.addClass([this.fieldClass, this.cls]);
40175 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
40176 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
40177 * @return {Roo.form.Field} this
40179 applyTo : function(target){
40180 this.allowDomMove = false;
40181 this.el = Roo.get(target);
40182 this.render(this.el.dom.parentNode);
40187 initValue : function(){
40188 if(this.value !== undefined){
40189 this.setValue(this.value);
40190 }else if(this.el.dom.value.length > 0){
40191 this.setValue(this.el.dom.value);
40196 * Returns true if this field has been changed since it was originally loaded and is not disabled.
40197 * DEPRICATED - it never worked well - use hasChanged/resetHasChanged.
40199 isDirty : function() {
40200 if(this.disabled) {
40203 return String(this.getValue()) !== String(this.originalValue);
40207 * stores the current value in loadedValue
40209 resetHasChanged : function()
40211 this.loadedValue = String(this.getValue());
40214 * checks the current value against the 'loaded' value.
40215 * Note - will return false if 'resetHasChanged' has not been called first.
40217 hasChanged : function()
40219 if(this.disabled || this.readOnly) {
40222 return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
40228 afterRender : function(){
40229 Roo.form.Field.superclass.afterRender.call(this);
40234 fireKey : function(e){
40235 //Roo.log('field ' + e.getKey());
40236 if(e.isNavKeyPress()){
40237 this.fireEvent("specialkey", this, e);
40242 * Resets the current field value to the originally loaded value and clears any validation messages
40244 reset : function(){
40245 this.setValue(this.resetValue);
40246 this.originalValue = this.getValue();
40247 this.clearInvalid();
40251 initEvents : function(){
40252 // safari killled keypress - so keydown is now used..
40253 this.el.on("keydown" , this.fireKey, this);
40254 this.el.on("focus", this.onFocus, this);
40255 this.el.on("blur", this.onBlur, this);
40256 this.el.relayEvent('keyup', this);
40258 // reference to original value for reset
40259 this.originalValue = this.getValue();
40260 this.resetValue = this.getValue();
40264 onFocus : function(){
40265 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40266 this.el.addClass(this.focusClass);
40268 if(!this.hasFocus){
40269 this.hasFocus = true;
40270 this.startValue = this.getValue();
40271 this.fireEvent("focus", this);
40275 beforeBlur : Roo.emptyFn,
40278 onBlur : function(){
40280 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
40281 this.el.removeClass(this.focusClass);
40283 this.hasFocus = false;
40284 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
40287 var v = this.getValue();
40288 if(String(v) !== String(this.startValue)){
40289 this.fireEvent('change', this, v, this.startValue);
40291 this.fireEvent("blur", this);
40295 * Returns whether or not the field value is currently valid
40296 * @param {Boolean} preventMark True to disable marking the field invalid
40297 * @return {Boolean} True if the value is valid, else false
40299 isValid : function(preventMark){
40303 var restore = this.preventMark;
40304 this.preventMark = preventMark === true;
40305 var v = this.validateValue(this.processValue(this.getRawValue()));
40306 this.preventMark = restore;
40311 * Validates the field value
40312 * @return {Boolean} True if the value is valid, else false
40314 validate : function(){
40315 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
40316 this.clearInvalid();
40322 processValue : function(value){
40327 // Subclasses should provide the validation implementation by overriding this
40328 validateValue : function(value){
40333 * Mark this field as invalid
40334 * @param {String} msg The validation message
40336 markInvalid : function(msg){
40337 if(!this.rendered || this.preventMark){ // not rendered
40341 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40343 obj.el.addClass(this.invalidClass);
40344 msg = msg || this.invalidText;
40345 switch(this.msgTarget){
40347 obj.el.dom.qtip = msg;
40348 obj.el.dom.qclass = 'x-form-invalid-tip';
40349 if(Roo.QuickTips){ // fix for floating editors interacting with DND
40350 Roo.QuickTips.enable();
40354 this.el.dom.title = msg;
40358 var elp = this.el.findParent('.x-form-element', 5, true);
40359 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
40360 this.errorEl.setWidth(elp.getWidth(true)-20);
40362 this.errorEl.update(msg);
40363 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
40366 if(!this.errorIcon){
40367 var elp = this.el.findParent('.x-form-element', 5, true);
40368 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
40370 this.alignErrorIcon();
40371 this.errorIcon.dom.qtip = msg;
40372 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
40373 this.errorIcon.show();
40374 this.on('resize', this.alignErrorIcon, this);
40377 var t = Roo.getDom(this.msgTarget);
40379 t.style.display = this.msgDisplay;
40382 this.fireEvent('invalid', this, msg);
40386 alignErrorIcon : function(){
40387 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
40391 * Clear any invalid styles/messages for this field
40393 clearInvalid : function(){
40394 if(!this.rendered || this.preventMark){ // not rendered
40397 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
40399 obj.el.removeClass(this.invalidClass);
40400 switch(this.msgTarget){
40402 obj.el.dom.qtip = '';
40405 this.el.dom.title = '';
40409 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
40413 if(this.errorIcon){
40414 this.errorIcon.dom.qtip = '';
40415 this.errorIcon.hide();
40416 this.un('resize', this.alignErrorIcon, this);
40420 var t = Roo.getDom(this.msgTarget);
40422 t.style.display = 'none';
40425 this.fireEvent('valid', this);
40429 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
40430 * @return {Mixed} value The field value
40432 getRawValue : function(){
40433 var v = this.el.getValue();
40439 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
40440 * @return {Mixed} value The field value
40442 getValue : function(){
40443 var v = this.el.getValue();
40449 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
40450 * @param {Mixed} value The value to set
40452 setRawValue : function(v){
40453 return this.el.dom.value = (v === null || v === undefined ? '' : v);
40457 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
40458 * @param {Mixed} value The value to set
40460 setValue : function(v){
40463 this.el.dom.value = (v === null || v === undefined ? '' : v);
40468 adjustSize : function(w, h){
40469 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
40470 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
40474 adjustWidth : function(tag, w){
40475 tag = tag.toLowerCase();
40476 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
40477 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
40478 if(tag == 'input'){
40481 if(tag == 'textarea'){
40484 }else if(Roo.isOpera){
40485 if(tag == 'input'){
40488 if(tag == 'textarea'){
40498 // anything other than normal should be considered experimental
40499 Roo.form.Field.msgFx = {
40501 show: function(msgEl, f){
40502 msgEl.setDisplayed('block');
40505 hide : function(msgEl, f){
40506 msgEl.setDisplayed(false).update('');
40511 show: function(msgEl, f){
40512 msgEl.slideIn('t', {stopFx:true});
40515 hide : function(msgEl, f){
40516 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
40521 show: function(msgEl, f){
40522 msgEl.fixDisplay();
40523 msgEl.alignTo(f.el, 'tl-tr');
40524 msgEl.slideIn('l', {stopFx:true});
40527 hide : function(msgEl, f){
40528 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
40533 * Ext JS Library 1.1.1
40534 * Copyright(c) 2006-2007, Ext JS, LLC.
40536 * Originally Released Under LGPL - original licence link has changed is not relivant.
40539 * <script type="text/javascript">
40544 * @class Roo.form.TextField
40545 * @extends Roo.form.Field
40546 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
40547 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
40549 * Creates a new TextField
40550 * @param {Object} config Configuration options
40552 Roo.form.TextField = function(config){
40553 Roo.form.TextField.superclass.constructor.call(this, config);
40557 * Fires when the autosize function is triggered. The field may or may not have actually changed size
40558 * according to the default logic, but this event provides a hook for the developer to apply additional
40559 * logic at runtime to resize the field if needed.
40560 * @param {Roo.form.Field} this This text field
40561 * @param {Number} width The new field width
40567 Roo.extend(Roo.form.TextField, Roo.form.Field, {
40569 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
40573 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
40577 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
40581 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
40585 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
40589 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
40591 disableKeyFilter : false,
40593 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
40597 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
40601 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
40603 maxLength : Number.MAX_VALUE,
40605 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
40607 minLengthText : "The minimum length for this field is {0}",
40609 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
40611 maxLengthText : "The maximum length for this field is {0}",
40613 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
40615 selectOnFocus : false,
40617 * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space
40619 allowLeadingSpace : false,
40621 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
40623 blankText : "This field is required",
40625 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
40626 * If available, this function will be called only after the basic validators all return true, and will be passed the
40627 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
40631 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
40632 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
40633 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
40637 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
40641 * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
40647 initEvents : function()
40649 if (this.emptyText) {
40650 this.el.attr('placeholder', this.emptyText);
40653 Roo.form.TextField.superclass.initEvents.call(this);
40654 if(this.validationEvent == 'keyup'){
40655 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
40656 this.el.on('keyup', this.filterValidation, this);
40658 else if(this.validationEvent !== false){
40659 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
40662 if(this.selectOnFocus){
40663 this.on("focus", this.preFocus, this);
40665 if (!this.allowLeadingSpace) {
40666 this.on('blur', this.cleanLeadingSpace, this);
40669 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
40670 this.el.on("keypress", this.filterKeys, this);
40673 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
40674 this.el.on("click", this.autoSize, this);
40676 if(this.el.is('input[type=password]') && Roo.isSafari){
40677 this.el.on('keydown', this.SafariOnKeyDown, this);
40681 processValue : function(value){
40682 if(this.stripCharsRe){
40683 var newValue = value.replace(this.stripCharsRe, '');
40684 if(newValue !== value){
40685 this.setRawValue(newValue);
40692 filterValidation : function(e){
40693 if(!e.isNavKeyPress()){
40694 this.validationTask.delay(this.validationDelay);
40699 onKeyUp : function(e){
40700 if(!e.isNavKeyPress()){
40704 // private - clean the leading white space
40705 cleanLeadingSpace : function(e)
40707 if ( this.inputType == 'file') {
40711 this.setValue((this.getValue() + '').replace(/^\s+/,''));
40714 * Resets the current field value to the originally-loaded value and clears any validation messages.
40717 reset : function(){
40718 Roo.form.TextField.superclass.reset.call(this);
40722 preFocus : function(){
40724 if(this.selectOnFocus){
40725 this.el.dom.select();
40731 filterKeys : function(e){
40732 var k = e.getKey();
40733 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
40736 var c = e.getCharCode(), cc = String.fromCharCode(c);
40737 if(Roo.isIE && (e.isSpecialKey() || !cc)){
40740 if(!this.maskRe.test(cc)){
40745 setValue : function(v){
40747 Roo.form.TextField.superclass.setValue.apply(this, arguments);
40753 * Validates a value according to the field's validation rules and marks the field as invalid
40754 * if the validation fails
40755 * @param {Mixed} value The value to validate
40756 * @return {Boolean} True if the value is valid, else false
40758 validateValue : function(value){
40759 if(value.length < 1) { // if it's blank
40760 if(this.allowBlank){
40761 this.clearInvalid();
40764 this.markInvalid(this.blankText);
40768 if(value.length < this.minLength){
40769 this.markInvalid(String.format(this.minLengthText, this.minLength));
40772 if(value.length > this.maxLength){
40773 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
40777 var vt = Roo.form.VTypes;
40778 if(!vt[this.vtype](value, this)){
40779 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
40783 if(typeof this.validator == "function"){
40784 var msg = this.validator(value);
40786 this.markInvalid(msg);
40790 if(this.regex && !this.regex.test(value)){
40791 this.markInvalid(this.regexText);
40798 * Selects text in this field
40799 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
40800 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
40802 selectText : function(start, end){
40803 var v = this.getRawValue();
40805 start = start === undefined ? 0 : start;
40806 end = end === undefined ? v.length : end;
40807 var d = this.el.dom;
40808 if(d.setSelectionRange){
40809 d.setSelectionRange(start, end);
40810 }else if(d.createTextRange){
40811 var range = d.createTextRange();
40812 range.moveStart("character", start);
40813 range.moveEnd("character", v.length-end);
40820 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
40821 * This only takes effect if grow = true, and fires the autosize event.
40823 autoSize : function(){
40824 if(!this.grow || !this.rendered){
40828 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
40831 var v = el.dom.value;
40832 var d = document.createElement('div');
40833 d.appendChild(document.createTextNode(v));
40837 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
40838 this.el.setWidth(w);
40839 this.fireEvent("autosize", this, w);
40843 SafariOnKeyDown : function(event)
40845 // this is a workaround for a password hang bug on chrome/ webkit.
40847 var isSelectAll = false;
40849 if(this.el.dom.selectionEnd > 0){
40850 isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
40852 if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
40853 event.preventDefault();
40858 if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
40860 event.preventDefault();
40861 // this is very hacky as keydown always get's upper case.
40863 var cc = String.fromCharCode(event.getCharCode());
40866 this.setValue( event.shiftKey ? cc : cc.toLowerCase());
40874 * Ext JS Library 1.1.1
40875 * Copyright(c) 2006-2007, Ext JS, LLC.
40877 * Originally Released Under LGPL - original licence link has changed is not relivant.
40880 * <script type="text/javascript">
40884 * @class Roo.form.Hidden
40885 * @extends Roo.form.TextField
40886 * Simple Hidden element used on forms
40888 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
40891 * Creates a new Hidden form element.
40892 * @param {Object} config Configuration options
40897 // easy hidden field...
40898 Roo.form.Hidden = function(config){
40899 Roo.form.Hidden.superclass.constructor.call(this, config);
40902 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
40904 inputType: 'hidden',
40907 labelSeparator: '',
40909 itemCls : 'x-form-item-display-none'
40917 * Ext JS Library 1.1.1
40918 * Copyright(c) 2006-2007, Ext JS, LLC.
40920 * Originally Released Under LGPL - original licence link has changed is not relivant.
40923 * <script type="text/javascript">
40927 * @class Roo.form.TriggerField
40928 * @extends Roo.form.TextField
40929 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
40930 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
40931 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
40932 * for which you can provide a custom implementation. For example:
40934 var trigger = new Roo.form.TriggerField();
40935 trigger.onTriggerClick = myTriggerFn;
40936 trigger.applyTo('my-field');
40939 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
40940 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
40941 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
40942 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
40944 * Create a new TriggerField.
40945 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
40946 * to the base TextField)
40948 Roo.form.TriggerField = function(config){
40949 this.mimicing = false;
40950 Roo.form.TriggerField.superclass.constructor.call(this, config);
40953 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
40955 * @cfg {String} triggerClass A CSS class to apply to the trigger
40958 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
40959 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
40961 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
40963 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
40967 /** @cfg {Boolean} grow @hide */
40968 /** @cfg {Number} growMin @hide */
40969 /** @cfg {Number} growMax @hide */
40975 autoSize: Roo.emptyFn,
40979 deferHeight : true,
40982 actionMode : 'wrap',
40984 onResize : function(w, h){
40985 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
40986 if(typeof w == 'number'){
40987 var x = w - this.trigger.getWidth();
40988 this.el.setWidth(this.adjustWidth('input', x));
40989 this.trigger.setStyle('left', x+'px');
40994 adjustSize : Roo.BoxComponent.prototype.adjustSize,
40997 getResizeEl : function(){
41002 getPositionEl : function(){
41007 alignErrorIcon : function(){
41008 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
41012 onRender : function(ct, position){
41013 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
41014 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
41015 this.trigger = this.wrap.createChild(this.triggerConfig ||
41016 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
41017 if(this.hideTrigger){
41018 this.trigger.setDisplayed(false);
41020 this.initTrigger();
41022 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
41027 initTrigger : function(){
41028 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
41029 this.trigger.addClassOnOver('x-form-trigger-over');
41030 this.trigger.addClassOnClick('x-form-trigger-click');
41034 onDestroy : function(){
41036 this.trigger.removeAllListeners();
41037 this.trigger.remove();
41040 this.wrap.remove();
41042 Roo.form.TriggerField.superclass.onDestroy.call(this);
41046 onFocus : function(){
41047 Roo.form.TriggerField.superclass.onFocus.call(this);
41048 if(!this.mimicing){
41049 this.wrap.addClass('x-trigger-wrap-focus');
41050 this.mimicing = true;
41051 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
41052 if(this.monitorTab){
41053 this.el.on("keydown", this.checkTab, this);
41059 checkTab : function(e){
41060 if(e.getKey() == e.TAB){
41061 this.triggerBlur();
41066 onBlur : function(){
41071 mimicBlur : function(e, t){
41072 if(!this.wrap.contains(t) && this.validateBlur()){
41073 this.triggerBlur();
41078 triggerBlur : function(){
41079 this.mimicing = false;
41080 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
41081 if(this.monitorTab){
41082 this.el.un("keydown", this.checkTab, this);
41084 this.wrap.removeClass('x-trigger-wrap-focus');
41085 Roo.form.TriggerField.superclass.onBlur.call(this);
41089 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
41090 validateBlur : function(e, t){
41095 onDisable : function(){
41096 Roo.form.TriggerField.superclass.onDisable.call(this);
41098 this.wrap.addClass('x-item-disabled');
41103 onEnable : function(){
41104 Roo.form.TriggerField.superclass.onEnable.call(this);
41106 this.wrap.removeClass('x-item-disabled');
41111 onShow : function(){
41112 var ae = this.getActionEl();
41115 ae.dom.style.display = '';
41116 ae.dom.style.visibility = 'visible';
41122 onHide : function(){
41123 var ae = this.getActionEl();
41124 ae.dom.style.display = 'none';
41128 * The function that should handle the trigger's click event. This method does nothing by default until overridden
41129 * by an implementing function.
41131 * @param {EventObject} e
41133 onTriggerClick : Roo.emptyFn
41136 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
41137 // to be extended by an implementing class. For an example of implementing this class, see the custom
41138 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
41139 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
41140 initComponent : function(){
41141 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
41143 this.triggerConfig = {
41144 tag:'span', cls:'x-form-twin-triggers', cn:[
41145 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
41146 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
41150 getTrigger : function(index){
41151 return this.triggers[index];
41154 initTrigger : function(){
41155 var ts = this.trigger.select('.x-form-trigger', true);
41156 this.wrap.setStyle('overflow', 'hidden');
41157 var triggerField = this;
41158 ts.each(function(t, all, index){
41159 t.hide = function(){
41160 var w = triggerField.wrap.getWidth();
41161 this.dom.style.display = 'none';
41162 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41164 t.show = function(){
41165 var w = triggerField.wrap.getWidth();
41166 this.dom.style.display = '';
41167 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
41169 var triggerIndex = 'Trigger'+(index+1);
41171 if(this['hide'+triggerIndex]){
41172 t.dom.style.display = 'none';
41174 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
41175 t.addClassOnOver('x-form-trigger-over');
41176 t.addClassOnClick('x-form-trigger-click');
41178 this.triggers = ts.elements;
41181 onTrigger1Click : Roo.emptyFn,
41182 onTrigger2Click : Roo.emptyFn
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">
41195 * @class Roo.form.TextArea
41196 * @extends Roo.form.TextField
41197 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
41198 * support for auto-sizing.
41200 * Creates a new TextArea
41201 * @param {Object} config Configuration options
41203 Roo.form.TextArea = function(config){
41204 Roo.form.TextArea.superclass.constructor.call(this, config);
41205 // these are provided exchanges for backwards compat
41206 // minHeight/maxHeight were replaced by growMin/growMax to be
41207 // compatible with TextField growing config values
41208 if(this.minHeight !== undefined){
41209 this.growMin = this.minHeight;
41211 if(this.maxHeight !== undefined){
41212 this.growMax = this.maxHeight;
41216 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
41218 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
41222 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
41226 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
41227 * in the field (equivalent to setting overflow: hidden, defaults to false)
41229 preventScrollbars: false,
41231 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
41232 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
41236 onRender : function(ct, position){
41238 this.defaultAutoCreate = {
41240 style:"width:300px;height:60px;",
41241 autocomplete: "new-password"
41244 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
41246 this.textSizeEl = Roo.DomHelper.append(document.body, {
41247 tag: "pre", cls: "x-form-grow-sizer"
41249 if(this.preventScrollbars){
41250 this.el.setStyle("overflow", "hidden");
41252 this.el.setHeight(this.growMin);
41256 onDestroy : function(){
41257 if(this.textSizeEl){
41258 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
41260 Roo.form.TextArea.superclass.onDestroy.call(this);
41264 onKeyUp : function(e){
41265 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
41271 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
41272 * This only takes effect if grow = true, and fires the autosize event if the height changes.
41274 autoSize : function(){
41275 if(!this.grow || !this.textSizeEl){
41279 var v = el.dom.value;
41280 var ts = this.textSizeEl;
41283 ts.appendChild(document.createTextNode(v));
41286 Roo.fly(ts).setWidth(this.el.getWidth());
41288 v = "  ";
41291 v = v.replace(/\n/g, '<p> </p>');
41293 v += " \n ";
41296 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
41297 if(h != this.lastHeight){
41298 this.lastHeight = h;
41299 this.el.setHeight(h);
41300 this.fireEvent("autosize", this, h);
41305 * Ext JS Library 1.1.1
41306 * Copyright(c) 2006-2007, Ext JS, LLC.
41308 * Originally Released Under LGPL - original licence link has changed is not relivant.
41311 * <script type="text/javascript">
41316 * @class Roo.form.NumberField
41317 * @extends Roo.form.TextField
41318 * Numeric text field that provides automatic keystroke filtering and numeric validation.
41320 * Creates a new NumberField
41321 * @param {Object} config Configuration options
41323 Roo.form.NumberField = function(config){
41324 Roo.form.NumberField.superclass.constructor.call(this, config);
41327 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
41329 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
41331 fieldClass: "x-form-field x-form-num-field",
41333 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
41335 allowDecimals : true,
41337 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
41339 decimalSeparator : ".",
41341 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
41343 decimalPrecision : 2,
41345 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
41347 allowNegative : true,
41349 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
41351 minValue : Number.NEGATIVE_INFINITY,
41353 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
41355 maxValue : Number.MAX_VALUE,
41357 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
41359 minText : "The minimum value for this field is {0}",
41361 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
41363 maxText : "The maximum value for this field is {0}",
41365 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
41366 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
41368 nanText : "{0} is not a valid number",
41371 initEvents : function(){
41372 Roo.form.NumberField.superclass.initEvents.call(this);
41373 var allowed = "0123456789";
41374 if(this.allowDecimals){
41375 allowed += this.decimalSeparator;
41377 if(this.allowNegative){
41380 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
41381 var keyPress = function(e){
41382 var k = e.getKey();
41383 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
41386 var c = e.getCharCode();
41387 if(allowed.indexOf(String.fromCharCode(c)) === -1){
41391 this.el.on("keypress", keyPress, this);
41395 validateValue : function(value){
41396 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
41399 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
41402 var num = this.parseValue(value);
41404 this.markInvalid(String.format(this.nanText, value));
41407 if(num < this.minValue){
41408 this.markInvalid(String.format(this.minText, this.minValue));
41411 if(num > this.maxValue){
41412 this.markInvalid(String.format(this.maxText, this.maxValue));
41418 getValue : function(){
41419 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
41423 parseValue : function(value){
41424 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
41425 return isNaN(value) ? '' : value;
41429 fixPrecision : function(value){
41430 var nan = isNaN(value);
41431 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
41432 return nan ? '' : value;
41434 return parseFloat(value).toFixed(this.decimalPrecision);
41437 setValue : function(v){
41438 v = this.fixPrecision(v);
41439 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
41443 decimalPrecisionFcn : function(v){
41444 return Math.floor(v);
41447 beforeBlur : function(){
41448 var v = this.parseValue(this.getRawValue());
41455 * Ext JS Library 1.1.1
41456 * Copyright(c) 2006-2007, Ext JS, LLC.
41458 * Originally Released Under LGPL - original licence link has changed is not relivant.
41461 * <script type="text/javascript">
41465 * @class Roo.form.DateField
41466 * @extends Roo.form.TriggerField
41467 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
41469 * Create a new DateField
41470 * @param {Object} config
41472 Roo.form.DateField = function(config)
41474 Roo.form.DateField.superclass.constructor.call(this, config);
41480 * Fires when a date is selected
41481 * @param {Roo.form.DateField} combo This combo box
41482 * @param {Date} date The date selected
41489 if(typeof this.minValue == "string") {
41490 this.minValue = this.parseDate(this.minValue);
41492 if(typeof this.maxValue == "string") {
41493 this.maxValue = this.parseDate(this.maxValue);
41495 this.ddMatch = null;
41496 if(this.disabledDates){
41497 var dd = this.disabledDates;
41499 for(var i = 0; i < dd.length; i++){
41501 if(i != dd.length-1) {
41505 this.ddMatch = new RegExp(re + ")");
41509 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
41511 * @cfg {String} format
41512 * The default date format string which can be overriden for localization support. The format must be
41513 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
41517 * @cfg {String} altFormats
41518 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
41519 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
41521 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
41523 * @cfg {Array} disabledDays
41524 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
41526 disabledDays : null,
41528 * @cfg {String} disabledDaysText
41529 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
41531 disabledDaysText : "Disabled",
41533 * @cfg {Array} disabledDates
41534 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
41535 * expression so they are very powerful. Some examples:
41537 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
41538 * <li>["03/08", "09/16"] would disable those days for every year</li>
41539 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
41540 * <li>["03/../2006"] would disable every day in March 2006</li>
41541 * <li>["^03"] would disable every day in every March</li>
41543 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
41544 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
41546 disabledDates : null,
41548 * @cfg {String} disabledDatesText
41549 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
41551 disabledDatesText : "Disabled",
41553 * @cfg {Date/String} minValue
41554 * The minimum allowed date. Can be either a Javascript date object or a string date in a
41555 * valid format (defaults to null).
41559 * @cfg {Date/String} maxValue
41560 * The maximum allowed date. Can be either a Javascript date object or a string date in a
41561 * valid format (defaults to null).
41565 * @cfg {String} minText
41566 * The error text to display when the date in the cell is before minValue (defaults to
41567 * 'The date in this field must be after {minValue}').
41569 minText : "The date in this field must be equal to or after {0}",
41571 * @cfg {String} maxText
41572 * The error text to display when the date in the cell is after maxValue (defaults to
41573 * 'The date in this field must be before {maxValue}').
41575 maxText : "The date in this field must be equal to or before {0}",
41577 * @cfg {String} invalidText
41578 * The error text to display when the date in the field is invalid (defaults to
41579 * '{value} is not a valid date - it must be in the format {format}').
41581 invalidText : "{0} is not a valid date - it must be in the format {1}",
41583 * @cfg {String} triggerClass
41584 * An additional CSS class used to style the trigger button. The trigger will always get the
41585 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
41586 * which displays a calendar icon).
41588 triggerClass : 'x-form-date-trigger',
41592 * @cfg {Boolean} useIso
41593 * if enabled, then the date field will use a hidden field to store the
41594 * real value as iso formated date. default (false)
41598 * @cfg {String/Object} autoCreate
41599 * A DomHelper element spec, or true for a default element spec (defaults to
41600 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
41603 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
41606 hiddenField: false,
41608 onRender : function(ct, position)
41610 Roo.form.DateField.superclass.onRender.call(this, ct, position);
41612 //this.el.dom.removeAttribute('name');
41613 Roo.log("Changing name?");
41614 this.el.dom.setAttribute('name', this.name + '____hidden___' );
41615 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
41617 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
41618 // prevent input submission
41619 this.hiddenName = this.name;
41626 validateValue : function(value)
41628 value = this.formatDate(value);
41629 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
41630 Roo.log('super failed');
41633 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
41636 var svalue = value;
41637 value = this.parseDate(value);
41639 Roo.log('parse date failed' + svalue);
41640 this.markInvalid(String.format(this.invalidText, svalue, this.format));
41643 var time = value.getTime();
41644 if(this.minValue && time < this.minValue.getTime()){
41645 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
41648 if(this.maxValue && time > this.maxValue.getTime()){
41649 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
41652 if(this.disabledDays){
41653 var day = value.getDay();
41654 for(var i = 0; i < this.disabledDays.length; i++) {
41655 if(day === this.disabledDays[i]){
41656 this.markInvalid(this.disabledDaysText);
41661 var fvalue = this.formatDate(value);
41662 if(this.ddMatch && this.ddMatch.test(fvalue)){
41663 this.markInvalid(String.format(this.disabledDatesText, fvalue));
41670 // Provides logic to override the default TriggerField.validateBlur which just returns true
41671 validateBlur : function(){
41672 return !this.menu || !this.menu.isVisible();
41675 getName: function()
41677 // returns hidden if it's set..
41678 if (!this.rendered) {return ''};
41679 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
41684 * Returns the current date value of the date field.
41685 * @return {Date} The date value
41687 getValue : function(){
41689 return this.hiddenField ?
41690 this.hiddenField.value :
41691 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
41695 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
41696 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
41697 * (the default format used is "m/d/y").
41700 //All of these calls set the same date value (May 4, 2006)
41702 //Pass a date object:
41703 var dt = new Date('5/4/06');
41704 dateField.setValue(dt);
41706 //Pass a date string (default format):
41707 dateField.setValue('5/4/06');
41709 //Pass a date string (custom format):
41710 dateField.format = 'Y-m-d';
41711 dateField.setValue('2006-5-4');
41713 * @param {String/Date} date The date or valid date string
41715 setValue : function(date){
41716 if (this.hiddenField) {
41717 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
41719 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
41720 // make sure the value field is always stored as a date..
41721 this.value = this.parseDate(date);
41727 parseDate : function(value){
41728 if(!value || value instanceof Date){
41731 var v = Date.parseDate(value, this.format);
41732 if (!v && this.useIso) {
41733 v = Date.parseDate(value, 'Y-m-d');
41735 if(!v && this.altFormats){
41736 if(!this.altFormatsArray){
41737 this.altFormatsArray = this.altFormats.split("|");
41739 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
41740 v = Date.parseDate(value, this.altFormatsArray[i]);
41747 formatDate : function(date, fmt){
41748 return (!date || !(date instanceof Date)) ?
41749 date : date.dateFormat(fmt || this.format);
41754 select: function(m, d){
41757 this.fireEvent('select', this, d);
41759 show : function(){ // retain focus styling
41763 this.focus.defer(10, this);
41764 var ml = this.menuListeners;
41765 this.menu.un("select", ml.select, this);
41766 this.menu.un("show", ml.show, this);
41767 this.menu.un("hide", ml.hide, this);
41772 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
41773 onTriggerClick : function(){
41777 if(this.menu == null){
41778 this.menu = new Roo.menu.DateMenu();
41780 Roo.apply(this.menu.picker, {
41781 showClear: this.allowBlank,
41782 minDate : this.minValue,
41783 maxDate : this.maxValue,
41784 disabledDatesRE : this.ddMatch,
41785 disabledDatesText : this.disabledDatesText,
41786 disabledDays : this.disabledDays,
41787 disabledDaysText : this.disabledDaysText,
41788 format : this.useIso ? 'Y-m-d' : this.format,
41789 minText : String.format(this.minText, this.formatDate(this.minValue)),
41790 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
41792 this.menu.on(Roo.apply({}, this.menuListeners, {
41795 this.menu.picker.setValue(this.getValue() || new Date());
41796 this.menu.show(this.el, "tl-bl?");
41799 beforeBlur : function(){
41800 var v = this.parseDate(this.getRawValue());
41810 isDirty : function() {
41811 if(this.disabled) {
41815 if(typeof(this.startValue) === 'undefined'){
41819 return String(this.getValue()) !== String(this.startValue);
41823 cleanLeadingSpace : function(e)
41830 * Ext JS Library 1.1.1
41831 * Copyright(c) 2006-2007, Ext JS, LLC.
41833 * Originally Released Under LGPL - original licence link has changed is not relivant.
41836 * <script type="text/javascript">
41840 * @class Roo.form.MonthField
41841 * @extends Roo.form.TriggerField
41842 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
41844 * Create a new MonthField
41845 * @param {Object} config
41847 Roo.form.MonthField = function(config){
41849 Roo.form.MonthField.superclass.constructor.call(this, config);
41855 * Fires when a date is selected
41856 * @param {Roo.form.MonthFieeld} combo This combo box
41857 * @param {Date} date The date selected
41864 if(typeof this.minValue == "string") {
41865 this.minValue = this.parseDate(this.minValue);
41867 if(typeof this.maxValue == "string") {
41868 this.maxValue = this.parseDate(this.maxValue);
41870 this.ddMatch = null;
41871 if(this.disabledDates){
41872 var dd = this.disabledDates;
41874 for(var i = 0; i < dd.length; i++){
41876 if(i != dd.length-1) {
41880 this.ddMatch = new RegExp(re + ")");
41884 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
41886 * @cfg {String} format
41887 * The default date format string which can be overriden for localization support. The format must be
41888 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
41892 * @cfg {String} altFormats
41893 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
41894 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
41896 altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
41898 * @cfg {Array} disabledDays
41899 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
41901 disabledDays : [0,1,2,3,4,5,6],
41903 * @cfg {String} disabledDaysText
41904 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
41906 disabledDaysText : "Disabled",
41908 * @cfg {Array} disabledDates
41909 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
41910 * expression so they are very powerful. Some examples:
41912 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
41913 * <li>["03/08", "09/16"] would disable those days for every year</li>
41914 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
41915 * <li>["03/../2006"] would disable every day in March 2006</li>
41916 * <li>["^03"] would disable every day in every March</li>
41918 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
41919 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
41921 disabledDates : null,
41923 * @cfg {String} disabledDatesText
41924 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
41926 disabledDatesText : "Disabled",
41928 * @cfg {Date/String} minValue
41929 * The minimum allowed date. Can be either a Javascript date object or a string date in a
41930 * valid format (defaults to null).
41934 * @cfg {Date/String} maxValue
41935 * The maximum allowed date. Can be either a Javascript date object or a string date in a
41936 * valid format (defaults to null).
41940 * @cfg {String} minText
41941 * The error text to display when the date in the cell is before minValue (defaults to
41942 * 'The date in this field must be after {minValue}').
41944 minText : "The date in this field must be equal to or after {0}",
41946 * @cfg {String} maxTextf
41947 * The error text to display when the date in the cell is after maxValue (defaults to
41948 * 'The date in this field must be before {maxValue}').
41950 maxText : "The date in this field must be equal to or before {0}",
41952 * @cfg {String} invalidText
41953 * The error text to display when the date in the field is invalid (defaults to
41954 * '{value} is not a valid date - it must be in the format {format}').
41956 invalidText : "{0} is not a valid date - it must be in the format {1}",
41958 * @cfg {String} triggerClass
41959 * An additional CSS class used to style the trigger button. The trigger will always get the
41960 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
41961 * which displays a calendar icon).
41963 triggerClass : 'x-form-date-trigger',
41967 * @cfg {Boolean} useIso
41968 * if enabled, then the date field will use a hidden field to store the
41969 * real value as iso formated date. default (true)
41973 * @cfg {String/Object} autoCreate
41974 * A DomHelper element spec, or true for a default element spec (defaults to
41975 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
41978 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
41981 hiddenField: false,
41983 hideMonthPicker : false,
41985 onRender : function(ct, position)
41987 Roo.form.MonthField.superclass.onRender.call(this, ct, position);
41989 this.el.dom.removeAttribute('name');
41990 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
41992 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
41993 // prevent input submission
41994 this.hiddenName = this.name;
42001 validateValue : function(value)
42003 value = this.formatDate(value);
42004 if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
42007 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
42010 var svalue = value;
42011 value = this.parseDate(value);
42013 this.markInvalid(String.format(this.invalidText, svalue, this.format));
42016 var time = value.getTime();
42017 if(this.minValue && time < this.minValue.getTime()){
42018 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
42021 if(this.maxValue && time > this.maxValue.getTime()){
42022 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
42025 /*if(this.disabledDays){
42026 var day = value.getDay();
42027 for(var i = 0; i < this.disabledDays.length; i++) {
42028 if(day === this.disabledDays[i]){
42029 this.markInvalid(this.disabledDaysText);
42035 var fvalue = this.formatDate(value);
42036 /*if(this.ddMatch && this.ddMatch.test(fvalue)){
42037 this.markInvalid(String.format(this.disabledDatesText, fvalue));
42045 // Provides logic to override the default TriggerField.validateBlur which just returns true
42046 validateBlur : function(){
42047 return !this.menu || !this.menu.isVisible();
42051 * Returns the current date value of the date field.
42052 * @return {Date} The date value
42054 getValue : function(){
42058 return this.hiddenField ?
42059 this.hiddenField.value :
42060 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
42064 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
42065 * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
42066 * (the default format used is "m/d/y").
42069 //All of these calls set the same date value (May 4, 2006)
42071 //Pass a date object:
42072 var dt = new Date('5/4/06');
42073 monthField.setValue(dt);
42075 //Pass a date string (default format):
42076 monthField.setValue('5/4/06');
42078 //Pass a date string (custom format):
42079 monthField.format = 'Y-m-d';
42080 monthField.setValue('2006-5-4');
42082 * @param {String/Date} date The date or valid date string
42084 setValue : function(date){
42085 Roo.log('month setValue' + date);
42086 // can only be first of month..
42088 var val = this.parseDate(date);
42090 if (this.hiddenField) {
42091 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
42093 Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
42094 this.value = this.parseDate(date);
42098 parseDate : function(value){
42099 if(!value || value instanceof Date){
42100 value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
42103 var v = Date.parseDate(value, this.format);
42104 if (!v && this.useIso) {
42105 v = Date.parseDate(value, 'Y-m-d');
42109 v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
42113 if(!v && this.altFormats){
42114 if(!this.altFormatsArray){
42115 this.altFormatsArray = this.altFormats.split("|");
42117 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
42118 v = Date.parseDate(value, this.altFormatsArray[i]);
42125 formatDate : function(date, fmt){
42126 return (!date || !(date instanceof Date)) ?
42127 date : date.dateFormat(fmt || this.format);
42132 select: function(m, d){
42134 this.fireEvent('select', this, d);
42136 show : function(){ // retain focus styling
42140 this.focus.defer(10, this);
42141 var ml = this.menuListeners;
42142 this.menu.un("select", ml.select, this);
42143 this.menu.un("show", ml.show, this);
42144 this.menu.un("hide", ml.hide, this);
42148 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
42149 onTriggerClick : function(){
42153 if(this.menu == null){
42154 this.menu = new Roo.menu.DateMenu();
42158 Roo.apply(this.menu.picker, {
42160 showClear: this.allowBlank,
42161 minDate : this.minValue,
42162 maxDate : this.maxValue,
42163 disabledDatesRE : this.ddMatch,
42164 disabledDatesText : this.disabledDatesText,
42166 format : this.useIso ? 'Y-m-d' : this.format,
42167 minText : String.format(this.minText, this.formatDate(this.minValue)),
42168 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
42171 this.menu.on(Roo.apply({}, this.menuListeners, {
42179 // hide month picker get's called when we called by 'before hide';
42181 var ignorehide = true;
42182 p.hideMonthPicker = function(disableAnim){
42186 if(this.monthPicker){
42187 Roo.log("hideMonthPicker called");
42188 if(disableAnim === true){
42189 this.monthPicker.hide();
42191 this.monthPicker.slideOut('t', {duration:.2});
42192 p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
42193 p.fireEvent("select", this, this.value);
42199 Roo.log('picker set value');
42200 Roo.log(this.getValue());
42201 p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
42202 m.show(this.el, 'tl-bl?');
42203 ignorehide = false;
42204 // this will trigger hideMonthPicker..
42207 // hidden the day picker
42208 Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
42214 p.showMonthPicker.defer(100, p);
42220 beforeBlur : function(){
42221 var v = this.parseDate(this.getRawValue());
42227 /** @cfg {Boolean} grow @hide */
42228 /** @cfg {Number} growMin @hide */
42229 /** @cfg {Number} growMax @hide */
42236 * Ext JS Library 1.1.1
42237 * Copyright(c) 2006-2007, Ext JS, LLC.
42239 * Originally Released Under LGPL - original licence link has changed is not relivant.
42242 * <script type="text/javascript">
42247 * @class Roo.form.ComboBox
42248 * @extends Roo.form.TriggerField
42249 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
42251 * Create a new ComboBox.
42252 * @param {Object} config Configuration options
42254 Roo.form.ComboBox = function(config){
42255 Roo.form.ComboBox.superclass.constructor.call(this, config);
42259 * Fires when the dropdown list is expanded
42260 * @param {Roo.form.ComboBox} combo This combo box
42265 * Fires when the dropdown list is collapsed
42266 * @param {Roo.form.ComboBox} combo This combo box
42270 * @event beforeselect
42271 * Fires before a list item is selected. Return false to cancel the selection.
42272 * @param {Roo.form.ComboBox} combo This combo box
42273 * @param {Roo.data.Record} record The data record returned from the underlying store
42274 * @param {Number} index The index of the selected item in the dropdown list
42276 'beforeselect' : true,
42279 * Fires when a list item is selected
42280 * @param {Roo.form.ComboBox} combo This combo box
42281 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
42282 * @param {Number} index The index of the selected item in the dropdown list
42286 * @event beforequery
42287 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
42288 * The event object passed has these properties:
42289 * @param {Roo.form.ComboBox} combo This combo box
42290 * @param {String} query The query
42291 * @param {Boolean} forceAll true to force "all" query
42292 * @param {Boolean} cancel true to cancel the query
42293 * @param {Object} e The query event object
42295 'beforequery': true,
42298 * Fires when the 'add' icon is pressed (add a listener to enable add button)
42299 * @param {Roo.form.ComboBox} combo This combo box
42304 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
42305 * @param {Roo.form.ComboBox} combo This combo box
42306 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
42312 if(this.transform){
42313 this.allowDomMove = false;
42314 var s = Roo.getDom(this.transform);
42315 if(!this.hiddenName){
42316 this.hiddenName = s.name;
42319 this.mode = 'local';
42320 var d = [], opts = s.options;
42321 for(var i = 0, len = opts.length;i < len; i++){
42323 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
42325 this.value = value;
42327 d.push([value, o.text]);
42329 this.store = new Roo.data.SimpleStore({
42331 fields: ['value', 'text'],
42334 this.valueField = 'value';
42335 this.displayField = 'text';
42337 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
42338 if(!this.lazyRender){
42339 this.target = true;
42340 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
42341 s.parentNode.removeChild(s); // remove it
42342 this.render(this.el.parentNode);
42344 s.parentNode.removeChild(s); // remove it
42349 this.store = Roo.factory(this.store, Roo.data);
42352 this.selectedIndex = -1;
42353 if(this.mode == 'local'){
42354 if(config.queryDelay === undefined){
42355 this.queryDelay = 10;
42357 if(config.minChars === undefined){
42363 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
42365 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
42368 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
42369 * rendering into an Roo.Editor, defaults to false)
42372 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
42373 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
42376 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
42379 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
42380 * the dropdown list (defaults to undefined, with no header element)
42384 * @cfg {String/Roo.Template} tpl The template to use to render the output
42388 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
42390 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
42392 listWidth: undefined,
42394 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
42395 * mode = 'remote' or 'text' if mode = 'local')
42397 displayField: undefined,
42399 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
42400 * mode = 'remote' or 'value' if mode = 'local').
42401 * Note: use of a valueField requires the user make a selection
42402 * in order for a value to be mapped.
42404 valueField: undefined,
42408 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
42409 * field's data value (defaults to the underlying DOM element's name)
42411 hiddenName: undefined,
42413 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
42417 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
42419 selectedClass: 'x-combo-selected',
42421 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
42422 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
42423 * which displays a downward arrow icon).
42425 triggerClass : 'x-form-arrow-trigger',
42427 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
42431 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
42432 * anchor positions (defaults to 'tl-bl')
42434 listAlign: 'tl-bl?',
42436 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
42440 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
42441 * query specified by the allQuery config option (defaults to 'query')
42443 triggerAction: 'query',
42445 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
42446 * (defaults to 4, does not apply if editable = false)
42450 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
42451 * delay (typeAheadDelay) if it matches a known value (defaults to false)
42455 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
42456 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
42460 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
42461 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
42465 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
42466 * when editable = true (defaults to false)
42468 selectOnFocus:false,
42470 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
42472 queryParam: 'query',
42474 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
42475 * when mode = 'remote' (defaults to 'Loading...')
42477 loadingText: 'Loading...',
42479 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
42483 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
42487 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
42488 * traditional select (defaults to true)
42492 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
42496 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
42500 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
42501 * listWidth has a higher value)
42505 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
42506 * allow the user to set arbitrary text into the field (defaults to false)
42508 forceSelection:false,
42510 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
42511 * if typeAhead = true (defaults to 250)
42513 typeAheadDelay : 250,
42515 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
42516 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
42518 valueNotFoundText : undefined,
42520 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
42522 blockFocus : false,
42525 * @cfg {Boolean} disableClear Disable showing of clear button.
42527 disableClear : false,
42529 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
42531 alwaysQuery : false,
42537 // element that contains real text value.. (when hidden is used..)
42540 onRender : function(ct, position)
42542 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
42544 if(this.hiddenName){
42545 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
42547 this.hiddenField.value =
42548 this.hiddenValue !== undefined ? this.hiddenValue :
42549 this.value !== undefined ? this.value : '';
42551 // prevent input submission
42552 this.el.dom.removeAttribute('name');
42558 this.el.dom.setAttribute('autocomplete', 'off');
42561 var cls = 'x-combo-list';
42563 this.list = new Roo.Layer({
42564 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
42567 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
42568 this.list.setWidth(lw);
42569 this.list.swallowEvent('mousewheel');
42570 this.assetHeight = 0;
42573 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
42574 this.assetHeight += this.header.getHeight();
42577 this.innerList = this.list.createChild({cls:cls+'-inner'});
42578 this.innerList.on('mouseover', this.onViewOver, this);
42579 this.innerList.on('mousemove', this.onViewMove, this);
42580 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
42582 if(this.allowBlank && !this.pageSize && !this.disableClear){
42583 this.footer = this.list.createChild({cls:cls+'-ft'});
42584 this.pageTb = new Roo.Toolbar(this.footer);
42588 this.footer = this.list.createChild({cls:cls+'-ft'});
42589 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
42590 {pageSize: this.pageSize});
42594 if (this.pageTb && this.allowBlank && !this.disableClear) {
42596 this.pageTb.add(new Roo.Toolbar.Fill(), {
42597 cls: 'x-btn-icon x-btn-clear',
42599 handler: function()
42602 _this.clearValue();
42603 _this.onSelect(false, -1);
42608 this.assetHeight += this.footer.getHeight();
42613 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
42616 this.view = new Roo.View(this.innerList, this.tpl, {
42619 selectedClass: this.selectedClass
42622 this.view.on('click', this.onViewClick, this);
42624 this.store.on('beforeload', this.onBeforeLoad, this);
42625 this.store.on('load', this.onLoad, this);
42626 this.store.on('loadexception', this.onLoadException, this);
42628 if(this.resizable){
42629 this.resizer = new Roo.Resizable(this.list, {
42630 pinned:true, handles:'se'
42632 this.resizer.on('resize', function(r, w, h){
42633 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
42634 this.listWidth = w;
42635 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
42636 this.restrictHeight();
42638 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
42640 if(!this.editable){
42641 this.editable = true;
42642 this.setEditable(false);
42646 if (typeof(this.events.add.listeners) != 'undefined') {
42648 this.addicon = this.wrap.createChild(
42649 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
42651 this.addicon.on('click', function(e) {
42652 this.fireEvent('add', this);
42655 if (typeof(this.events.edit.listeners) != 'undefined') {
42657 this.editicon = this.wrap.createChild(
42658 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
42659 if (this.addicon) {
42660 this.editicon.setStyle('margin-left', '40px');
42662 this.editicon.on('click', function(e) {
42664 // we fire even if inothing is selected..
42665 this.fireEvent('edit', this, this.lastData );
42675 initEvents : function(){
42676 Roo.form.ComboBox.superclass.initEvents.call(this);
42678 this.keyNav = new Roo.KeyNav(this.el, {
42679 "up" : function(e){
42680 this.inKeyMode = true;
42684 "down" : function(e){
42685 if(!this.isExpanded()){
42686 this.onTriggerClick();
42688 this.inKeyMode = true;
42693 "enter" : function(e){
42694 this.onViewClick();
42698 "esc" : function(e){
42702 "tab" : function(e){
42703 this.onViewClick(false);
42704 this.fireEvent("specialkey", this, e);
42710 doRelay : function(foo, bar, hname){
42711 if(hname == 'down' || this.scope.isExpanded()){
42712 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
42719 this.queryDelay = Math.max(this.queryDelay || 10,
42720 this.mode == 'local' ? 10 : 250);
42721 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
42722 if(this.typeAhead){
42723 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
42725 if(this.editable !== false){
42726 this.el.on("keyup", this.onKeyUp, this);
42728 if(this.forceSelection){
42729 this.on('blur', this.doForce, this);
42733 onDestroy : function(){
42735 this.view.setStore(null);
42736 this.view.el.removeAllListeners();
42737 this.view.el.remove();
42738 this.view.purgeListeners();
42741 this.list.destroy();
42744 this.store.un('beforeload', this.onBeforeLoad, this);
42745 this.store.un('load', this.onLoad, this);
42746 this.store.un('loadexception', this.onLoadException, this);
42748 Roo.form.ComboBox.superclass.onDestroy.call(this);
42752 fireKey : function(e){
42753 if(e.isNavKeyPress() && !this.list.isVisible()){
42754 this.fireEvent("specialkey", this, e);
42759 onResize: function(w, h){
42760 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
42762 if(typeof w != 'number'){
42763 // we do not handle it!?!?
42766 var tw = this.trigger.getWidth();
42767 tw += this.addicon ? this.addicon.getWidth() : 0;
42768 tw += this.editicon ? this.editicon.getWidth() : 0;
42770 this.el.setWidth( this.adjustWidth('input', x));
42772 this.trigger.setStyle('left', x+'px');
42774 if(this.list && this.listWidth === undefined){
42775 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
42776 this.list.setWidth(lw);
42777 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
42785 * Allow or prevent the user from directly editing the field text. If false is passed,
42786 * the user will only be able to select from the items defined in the dropdown list. This method
42787 * is the runtime equivalent of setting the 'editable' config option at config time.
42788 * @param {Boolean} value True to allow the user to directly edit the field text
42790 setEditable : function(value){
42791 if(value == this.editable){
42794 this.editable = value;
42796 this.el.dom.setAttribute('readOnly', true);
42797 this.el.on('mousedown', this.onTriggerClick, this);
42798 this.el.addClass('x-combo-noedit');
42800 this.el.dom.setAttribute('readOnly', false);
42801 this.el.un('mousedown', this.onTriggerClick, this);
42802 this.el.removeClass('x-combo-noedit');
42807 onBeforeLoad : function(){
42808 if(!this.hasFocus){
42811 this.innerList.update(this.loadingText ?
42812 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
42813 this.restrictHeight();
42814 this.selectedIndex = -1;
42818 onLoad : function(){
42819 if(!this.hasFocus){
42822 if(this.store.getCount() > 0){
42824 this.restrictHeight();
42825 if(this.lastQuery == this.allQuery){
42827 this.el.dom.select();
42829 if(!this.selectByValue(this.value, true)){
42830 this.select(0, true);
42834 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
42835 this.taTask.delay(this.typeAheadDelay);
42839 this.onEmptyResults();
42844 onLoadException : function()
42847 Roo.log(this.store.reader.jsonData);
42848 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
42849 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
42855 onTypeAhead : function(){
42856 if(this.store.getCount() > 0){
42857 var r = this.store.getAt(0);
42858 var newValue = r.data[this.displayField];
42859 var len = newValue.length;
42860 var selStart = this.getRawValue().length;
42861 if(selStart != len){
42862 this.setRawValue(newValue);
42863 this.selectText(selStart, newValue.length);
42869 onSelect : function(record, index){
42870 if(this.fireEvent('beforeselect', this, record, index) !== false){
42871 this.setFromData(index > -1 ? record.data : false);
42873 this.fireEvent('select', this, record, index);
42878 * Returns the currently selected field value or empty string if no value is set.
42879 * @return {String} value The selected value
42881 getValue : function(){
42882 if(this.valueField){
42883 return typeof this.value != 'undefined' ? this.value : '';
42885 return Roo.form.ComboBox.superclass.getValue.call(this);
42889 * Clears any text/value currently set in the field
42891 clearValue : function(){
42892 if(this.hiddenField){
42893 this.hiddenField.value = '';
42896 this.setRawValue('');
42897 this.lastSelectionText = '';
42902 * Sets the specified value into the field. If the value finds a match, the corresponding record text
42903 * will be displayed in the field. If the value does not match the data value of an existing item,
42904 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
42905 * Otherwise the field will be blank (although the value will still be set).
42906 * @param {String} value The value to match
42908 setValue : function(v){
42910 if(this.valueField){
42911 var r = this.findRecord(this.valueField, v);
42913 text = r.data[this.displayField];
42914 }else if(this.valueNotFoundText !== undefined){
42915 text = this.valueNotFoundText;
42918 this.lastSelectionText = text;
42919 if(this.hiddenField){
42920 this.hiddenField.value = v;
42922 Roo.form.ComboBox.superclass.setValue.call(this, text);
42926 * @property {Object} the last set data for the element
42931 * Sets the value of the field based on a object which is related to the record format for the store.
42932 * @param {Object} value the value to set as. or false on reset?
42934 setFromData : function(o){
42935 var dv = ''; // display value
42936 var vv = ''; // value value..
42938 if (this.displayField) {
42939 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
42941 // this is an error condition!!!
42942 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
42945 if(this.valueField){
42946 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
42948 if(this.hiddenField){
42949 this.hiddenField.value = vv;
42951 this.lastSelectionText = dv;
42952 Roo.form.ComboBox.superclass.setValue.call(this, dv);
42956 // no hidden field.. - we store the value in 'value', but still display
42957 // display field!!!!
42958 this.lastSelectionText = dv;
42959 Roo.form.ComboBox.superclass.setValue.call(this, dv);
42965 reset : function(){
42966 // overridden so that last data is reset..
42967 this.setValue(this.resetValue);
42968 this.originalValue = this.getValue();
42969 this.clearInvalid();
42970 this.lastData = false;
42972 this.view.clearSelections();
42976 findRecord : function(prop, value){
42978 if(this.store.getCount() > 0){
42979 this.store.each(function(r){
42980 if(r.data[prop] == value){
42990 getName: function()
42992 // returns hidden if it's set..
42993 if (!this.rendered) {return ''};
42994 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
42998 onViewMove : function(e, t){
42999 this.inKeyMode = false;
43003 onViewOver : function(e, t){
43004 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
43007 var item = this.view.findItemFromChild(t);
43009 var index = this.view.indexOf(item);
43010 this.select(index, false);
43015 onViewClick : function(doFocus)
43017 var index = this.view.getSelectedIndexes()[0];
43018 var r = this.store.getAt(index);
43020 this.onSelect(r, index);
43022 if(doFocus !== false && !this.blockFocus){
43028 restrictHeight : function(){
43029 this.innerList.dom.style.height = '';
43030 var inner = this.innerList.dom;
43031 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
43032 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
43033 this.list.beginUpdate();
43034 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
43035 this.list.alignTo(this.el, this.listAlign);
43036 this.list.endUpdate();
43040 onEmptyResults : function(){
43045 * Returns true if the dropdown list is expanded, else false.
43047 isExpanded : function(){
43048 return this.list.isVisible();
43052 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
43053 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
43054 * @param {String} value The data value of the item to select
43055 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
43056 * selected item if it is not currently in view (defaults to true)
43057 * @return {Boolean} True if the value matched an item in the list, else false
43059 selectByValue : function(v, scrollIntoView){
43060 if(v !== undefined && v !== null){
43061 var r = this.findRecord(this.valueField || this.displayField, v);
43063 this.select(this.store.indexOf(r), scrollIntoView);
43071 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
43072 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
43073 * @param {Number} index The zero-based index of the list item to select
43074 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
43075 * selected item if it is not currently in view (defaults to true)
43077 select : function(index, scrollIntoView){
43078 this.selectedIndex = index;
43079 this.view.select(index);
43080 if(scrollIntoView !== false){
43081 var el = this.view.getNode(index);
43083 this.innerList.scrollChildIntoView(el, false);
43089 selectNext : function(){
43090 var ct = this.store.getCount();
43092 if(this.selectedIndex == -1){
43094 }else if(this.selectedIndex < ct-1){
43095 this.select(this.selectedIndex+1);
43101 selectPrev : function(){
43102 var ct = this.store.getCount();
43104 if(this.selectedIndex == -1){
43106 }else if(this.selectedIndex != 0){
43107 this.select(this.selectedIndex-1);
43113 onKeyUp : function(e){
43114 if(this.editable !== false && !e.isSpecialKey()){
43115 this.lastKey = e.getKey();
43116 this.dqTask.delay(this.queryDelay);
43121 validateBlur : function(){
43122 return !this.list || !this.list.isVisible();
43126 initQuery : function(){
43127 this.doQuery(this.getRawValue());
43131 doForce : function(){
43132 if(this.el.dom.value.length > 0){
43133 this.el.dom.value =
43134 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
43140 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
43141 * query allowing the query action to be canceled if needed.
43142 * @param {String} query The SQL query to execute
43143 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
43144 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
43145 * saved in the current store (defaults to false)
43147 doQuery : function(q, forceAll){
43148 if(q === undefined || q === null){
43153 forceAll: forceAll,
43157 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
43161 forceAll = qe.forceAll;
43162 if(forceAll === true || (q.length >= this.minChars)){
43163 if(this.lastQuery != q || this.alwaysQuery){
43164 this.lastQuery = q;
43165 if(this.mode == 'local'){
43166 this.selectedIndex = -1;
43168 this.store.clearFilter();
43170 this.store.filter(this.displayField, q);
43174 this.store.baseParams[this.queryParam] = q;
43176 params: this.getParams(q)
43181 this.selectedIndex = -1;
43188 getParams : function(q){
43190 //p[this.queryParam] = q;
43193 p.limit = this.pageSize;
43199 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
43201 collapse : function(){
43202 if(!this.isExpanded()){
43206 Roo.get(document).un('mousedown', this.collapseIf, this);
43207 Roo.get(document).un('mousewheel', this.collapseIf, this);
43208 if (!this.editable) {
43209 Roo.get(document).un('keydown', this.listKeyPress, this);
43211 this.fireEvent('collapse', this);
43215 collapseIf : function(e){
43216 if(!e.within(this.wrap) && !e.within(this.list)){
43222 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
43224 expand : function(){
43225 if(this.isExpanded() || !this.hasFocus){
43228 this.list.alignTo(this.el, this.listAlign);
43230 Roo.get(document).on('mousedown', this.collapseIf, this);
43231 Roo.get(document).on('mousewheel', this.collapseIf, this);
43232 if (!this.editable) {
43233 Roo.get(document).on('keydown', this.listKeyPress, this);
43236 this.fireEvent('expand', this);
43240 // Implements the default empty TriggerField.onTriggerClick function
43241 onTriggerClick : function(){
43245 if(this.isExpanded()){
43247 if (!this.blockFocus) {
43252 this.hasFocus = true;
43253 if(this.triggerAction == 'all') {
43254 this.doQuery(this.allQuery, true);
43256 this.doQuery(this.getRawValue());
43258 if (!this.blockFocus) {
43263 listKeyPress : function(e)
43265 //Roo.log('listkeypress');
43266 // scroll to first matching element based on key pres..
43267 if (e.isSpecialKey()) {
43270 var k = String.fromCharCode(e.getKey()).toUpperCase();
43273 var csel = this.view.getSelectedNodes();
43274 var cselitem = false;
43276 var ix = this.view.indexOf(csel[0]);
43277 cselitem = this.store.getAt(ix);
43278 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
43284 this.store.each(function(v) {
43286 // start at existing selection.
43287 if (cselitem.id == v.id) {
43293 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
43294 match = this.store.indexOf(v);
43299 if (match === false) {
43300 return true; // no more action?
43303 this.view.select(match);
43304 var sn = Roo.get(this.view.getSelectedNodes()[0]);
43305 sn.scrollIntoView(sn.dom.parentNode, false);
43309 * @cfg {Boolean} grow
43313 * @cfg {Number} growMin
43317 * @cfg {Number} growMax
43325 * Copyright(c) 2010-2012, Roo J Solutions Limited
43332 * @class Roo.form.ComboBoxArray
43333 * @extends Roo.form.TextField
43334 * A facebook style adder... for lists of email / people / countries etc...
43335 * pick multiple items from a combo box, and shows each one.
43337 * Fred [x] Brian [x] [Pick another |v]
43340 * For this to work: it needs various extra information
43341 * - normal combo problay has
43343 * + displayField, valueField
43345 * For our purpose...
43348 * If we change from 'extends' to wrapping...
43355 * Create a new ComboBoxArray.
43356 * @param {Object} config Configuration options
43360 Roo.form.ComboBoxArray = function(config)
43364 * @event beforeremove
43365 * Fires before remove the value from the list
43366 * @param {Roo.form.ComboBoxArray} _self This combo box array
43367 * @param {Roo.form.ComboBoxArray.Item} item removed item
43369 'beforeremove' : true,
43372 * Fires when remove the value from the list
43373 * @param {Roo.form.ComboBoxArray} _self This combo box array
43374 * @param {Roo.form.ComboBoxArray.Item} item removed item
43381 Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
43383 this.items = new Roo.util.MixedCollection(false);
43385 // construct the child combo...
43395 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
43398 * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
43403 // behavies liek a hiddne field
43404 inputType: 'hidden',
43406 * @cfg {Number} width The width of the box that displays the selected element
43413 * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
43417 * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
43419 hiddenName : false,
43421 * @cfg {String} seperator The value seperator normally ','
43425 // private the array of items that are displayed..
43427 // private - the hidden field el.
43429 // private - the filed el..
43432 //validateValue : function() { return true; }, // all values are ok!
43433 //onAddClick: function() { },
43435 onRender : function(ct, position)
43438 // create the standard hidden element
43439 //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
43442 // give fake names to child combo;
43443 this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
43444 this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
43446 this.combo = Roo.factory(this.combo, Roo.form);
43447 this.combo.onRender(ct, position);
43448 if (typeof(this.combo.width) != 'undefined') {
43449 this.combo.onResize(this.combo.width,0);
43452 this.combo.initEvents();
43454 // assigned so form know we need to do this..
43455 this.store = this.combo.store;
43456 this.valueField = this.combo.valueField;
43457 this.displayField = this.combo.displayField ;
43460 this.combo.wrap.addClass('x-cbarray-grp');
43462 var cbwrap = this.combo.wrap.createChild(
43463 {tag: 'div', cls: 'x-cbarray-cb'},
43468 this.hiddenEl = this.combo.wrap.createChild({
43469 tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
43471 this.el = this.combo.wrap.createChild({
43472 tag: 'input', type:'hidden' , name: this.name, value : ''
43474 // this.el.dom.removeAttribute("name");
43477 this.outerWrap = this.combo.wrap;
43478 this.wrap = cbwrap;
43480 this.outerWrap.setWidth(this.width);
43481 this.outerWrap.dom.removeChild(this.el.dom);
43483 this.wrap.dom.appendChild(this.el.dom);
43484 this.outerWrap.dom.removeChild(this.combo.trigger.dom);
43485 this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
43487 this.combo.trigger.setStyle('position','relative');
43488 this.combo.trigger.setStyle('left', '0px');
43489 this.combo.trigger.setStyle('top', '2px');
43491 this.combo.el.setStyle('vertical-align', 'text-bottom');
43493 //this.trigger.setStyle('vertical-align', 'top');
43495 // this should use the code from combo really... on('add' ....)
43499 this.adder = this.outerWrap.createChild(
43500 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
43502 this.adder.on('click', function(e) {
43503 _t.fireEvent('adderclick', this, e);
43507 //this.adder.on('click', this.onAddClick, _t);
43510 this.combo.on('select', function(cb, rec, ix) {
43511 this.addItem(rec.data);
43514 cb.el.dom.value = '';
43515 //cb.lastData = rec.data;
43524 getName: function()
43526 // returns hidden if it's set..
43527 if (!this.rendered) {return ''};
43528 return this.hiddenName ? this.hiddenName : this.name;
43533 onResize: function(w, h){
43536 // not sure if this is needed..
43537 //this.combo.onResize(w,h);
43539 if(typeof w != 'number'){
43540 // we do not handle it!?!?
43543 var tw = this.combo.trigger.getWidth();
43544 tw += this.addicon ? this.addicon.getWidth() : 0;
43545 tw += this.editicon ? this.editicon.getWidth() : 0;
43547 this.combo.el.setWidth( this.combo.adjustWidth('input', x));
43549 this.combo.trigger.setStyle('left', '0px');
43551 if(this.list && this.listWidth === undefined){
43552 var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
43553 this.list.setWidth(lw);
43554 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
43561 addItem: function(rec)
43563 var valueField = this.combo.valueField;
43564 var displayField = this.combo.displayField;
43566 if (this.items.indexOfKey(rec[valueField]) > -1) {
43567 //console.log("GOT " + rec.data.id);
43571 var x = new Roo.form.ComboBoxArray.Item({
43572 //id : rec[this.idField],
43574 displayField : displayField ,
43575 tipField : displayField ,
43579 this.items.add(rec[valueField],x);
43580 // add it before the element..
43581 this.updateHiddenEl();
43582 x.render(this.outerWrap, this.wrap.dom);
43583 // add the image handler..
43586 updateHiddenEl : function()
43589 if (!this.hiddenEl) {
43593 var idField = this.combo.valueField;
43595 this.items.each(function(f) {
43596 ar.push(f.data[idField]);
43598 this.hiddenEl.dom.value = ar.join(this.seperator);
43604 this.items.clear();
43606 Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
43610 this.el.dom.value = '';
43611 if (this.hiddenEl) {
43612 this.hiddenEl.dom.value = '';
43616 getValue: function()
43618 return this.hiddenEl ? this.hiddenEl.dom.value : '';
43620 setValue: function(v) // not a valid action - must use addItems..
43625 if (this.store.isLocal && (typeof(v) == 'string')) {
43626 // then we can use the store to find the values..
43627 // comma seperated at present.. this needs to allow JSON based encoding..
43628 this.hiddenEl.value = v;
43630 Roo.each(v.split(this.seperator), function(k) {
43631 Roo.log("CHECK " + this.valueField + ',' + k);
43632 var li = this.store.query(this.valueField, k);
43637 add[this.valueField] = k;
43638 add[this.displayField] = li.item(0).data[this.displayField];
43644 if (typeof(v) == 'object' ) {
43645 // then let's assume it's an array of objects..
43646 Roo.each(v, function(l) {
43648 if (typeof(l) == 'string') {
43650 add[this.valueField] = l;
43651 add[this.displayField] = l
43660 setFromData: function(v)
43662 // this recieves an object, if setValues is called.
43664 this.el.dom.value = v[this.displayField];
43665 this.hiddenEl.dom.value = v[this.valueField];
43666 if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
43669 var kv = v[this.valueField];
43670 var dv = v[this.displayField];
43671 kv = typeof(kv) != 'string' ? '' : kv;
43672 dv = typeof(dv) != 'string' ? '' : dv;
43675 var keys = kv.split(this.seperator);
43676 var display = dv.split(this.seperator);
43677 for (var i = 0 ; i < keys.length; i++) {
43679 add[this.valueField] = keys[i];
43680 add[this.displayField] = display[i];
43688 * Validates the combox array value
43689 * @return {Boolean} True if the value is valid, else false
43691 validate : function(){
43692 if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
43693 this.clearInvalid();
43699 validateValue : function(value){
43700 return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
43708 isDirty : function() {
43709 if(this.disabled) {
43714 var d = Roo.decode(String(this.originalValue));
43716 return String(this.getValue()) !== String(this.originalValue);
43719 var originalValue = [];
43721 for (var i = 0; i < d.length; i++){
43722 originalValue.push(d[i][this.valueField]);
43725 return String(this.getValue()) !== String(originalValue.join(this.seperator));
43734 * @class Roo.form.ComboBoxArray.Item
43735 * @extends Roo.BoxComponent
43736 * A selected item in the list
43737 * Fred [x] Brian [x] [Pick another |v]
43740 * Create a new item.
43741 * @param {Object} config Configuration options
43744 Roo.form.ComboBoxArray.Item = function(config) {
43745 config.id = Roo.id();
43746 Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
43749 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
43752 displayField : false,
43756 defaultAutoCreate : {
43758 cls: 'x-cbarray-item',
43765 src : Roo.BLANK_IMAGE_URL ,
43773 onRender : function(ct, position)
43775 Roo.form.Field.superclass.onRender.call(this, ct, position);
43778 var cfg = this.getAutoCreate();
43779 this.el = ct.createChild(cfg, position);
43782 this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
43784 this.el.child('div').dom.innerHTML = this.cb.renderer ?
43785 this.cb.renderer(this.data) :
43786 String.format('{0}',this.data[this.displayField]);
43789 this.el.child('div').dom.setAttribute('qtip',
43790 String.format('{0}',this.data[this.tipField])
43793 this.el.child('img').on('click', this.remove, this);
43797 remove : function()
43799 if(this.cb.disabled){
43803 if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
43804 this.cb.items.remove(this);
43805 this.el.child('img').un('click', this.remove, this);
43807 this.cb.updateHiddenEl();
43809 this.cb.fireEvent('remove', this.cb, this);
43814 * RooJS Library 1.1.1
43815 * Copyright(c) 2008-2011 Alan Knowles
43822 * @class Roo.form.ComboNested
43823 * @extends Roo.form.ComboBox
43824 * A combobox for that allows selection of nested items in a list,
43839 * Create a new ComboNested
43840 * @param {Object} config Configuration options
43842 Roo.form.ComboNested = function(config){
43843 Roo.form.ComboCheck.superclass.constructor.call(this, config);
43844 // should verify some data...
43846 // hiddenName = required..
43847 // displayField = required
43848 // valudField == required
43849 var req= [ 'hiddenName', 'displayField', 'valueField' ];
43851 Roo.each(req, function(e) {
43852 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
43853 throw "Roo.form.ComboNested : missing value for: " + e;
43860 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
43863 * @config {Number} max Number of columns to show
43868 list : null, // the outermost div..
43869 innerLists : null, // the
43873 loadingChildren : false,
43875 onRender : function(ct, position)
43877 Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
43879 if(this.hiddenName){
43880 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
43882 this.hiddenField.value =
43883 this.hiddenValue !== undefined ? this.hiddenValue :
43884 this.value !== undefined ? this.value : '';
43886 // prevent input submission
43887 this.el.dom.removeAttribute('name');
43893 this.el.dom.setAttribute('autocomplete', 'off');
43896 var cls = 'x-combo-list';
43898 this.list = new Roo.Layer({
43899 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
43902 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
43903 this.list.setWidth(lw);
43904 this.list.swallowEvent('mousewheel');
43905 this.assetHeight = 0;
43908 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
43909 this.assetHeight += this.header.getHeight();
43911 this.innerLists = [];
43914 for (var i =0 ; i < this.maxColumns; i++) {
43915 this.onRenderList( cls, i);
43918 // always needs footer, as we are going to have an 'OK' button.
43919 this.footer = this.list.createChild({cls:cls+'-ft'});
43920 this.pageTb = new Roo.Toolbar(this.footer);
43925 handler: function()
43931 if ( this.allowBlank && !this.disableClear) {
43933 this.pageTb.add(new Roo.Toolbar.Fill(), {
43934 cls: 'x-btn-icon x-btn-clear',
43936 handler: function()
43939 _this.clearValue();
43940 _this.onSelect(false, -1);
43945 this.assetHeight += this.footer.getHeight();
43949 onRenderList : function ( cls, i)
43952 var lw = Math.floor(
43953 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
43956 this.list.setWidth(lw); // default to '1'
43958 var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
43959 //il.on('mouseover', this.onViewOver, this, { list: i });
43960 //il.on('mousemove', this.onViewMove, this, { list: i });
43962 il.setStyle({ 'overflow-x' : 'hidden'});
43965 this.tpl = new Roo.Template({
43966 html : '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
43967 isEmpty: function (value, allValues) {
43969 var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
43970 return dl ? 'has-children' : 'no-children'
43975 var store = this.store;
43977 store = new Roo.data.SimpleStore({
43978 //fields : this.store.reader.meta.fields,
43979 reader : this.store.reader,
43983 this.stores[i] = store;
43985 var view = this.views[i] = new Roo.View(
43991 selectedClass: this.selectedClass
43994 view.getEl().setWidth(lw);
43995 view.getEl().setStyle({
43996 position: i < 1 ? 'relative' : 'absolute',
43998 left: (i * lw ) + 'px',
43999 display : i > 0 ? 'none' : 'block'
44001 view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
44002 view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
44003 //view.on('click', this.onViewClick, this, { list : i });
44005 store.on('beforeload', this.onBeforeLoad, this);
44006 store.on('load', this.onLoad, this, { list : i});
44007 store.on('loadexception', this.onLoadException, this);
44009 // hide the other vies..
44015 restrictHeight : function()
44018 Roo.each(this.innerLists, function(il,i) {
44019 var el = this.views[i].getEl();
44020 el.dom.style.height = '';
44021 var inner = el.dom;
44022 var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
44023 // only adjust heights on other ones..
44024 mh = Math.max(h, mh);
44027 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
44028 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
44035 this.list.beginUpdate();
44036 this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
44037 this.list.alignTo(this.el, this.listAlign);
44038 this.list.endUpdate();
44043 // -- store handlers..
44045 onBeforeLoad : function()
44047 if(!this.hasFocus){
44050 this.innerLists[0].update(this.loadingText ?
44051 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
44052 this.restrictHeight();
44053 this.selectedIndex = -1;
44056 onLoad : function(a,b,c,d)
44058 if (!this.loadingChildren) {
44059 // then we are loading the top level. - hide the children
44060 for (var i = 1;i < this.views.length; i++) {
44061 this.views[i].getEl().setStyle({ display : 'none' });
44063 var lw = Math.floor(
44064 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
44067 this.list.setWidth(lw); // default to '1'
44071 if(!this.hasFocus){
44075 if(this.store.getCount() > 0) {
44077 this.restrictHeight();
44079 this.onEmptyResults();
44082 if (!this.loadingChildren) {
44083 this.selectActive();
44086 this.stores[1].loadData([]);
44087 this.stores[2].loadData([]);
44096 onLoadException : function()
44099 Roo.log(this.store.reader.jsonData);
44100 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
44101 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
44106 // no cleaning of leading spaces on blur here.
44107 cleanLeadingSpace : function(e) { },
44110 onSelectChange : function (view, sels, opts )
44112 var ix = view.getSelectedIndexes();
44114 if (opts.list > this.maxColumns - 2) {
44115 if (view.store.getCount()< 1) {
44116 this.views[opts.list ].getEl().setStyle({ display : 'none' });
44120 // used to clear ?? but if we are loading unselected
44121 this.setFromData(view.store.getAt(ix[0]).data);
44130 // this get's fired when trigger opens..
44131 // this.setFromData({});
44132 var str = this.stores[opts.list+1];
44133 str.data.clear(); // removeall wihtout the fire events..
44137 var rec = view.store.getAt(ix[0]);
44139 this.setFromData(rec.data);
44140 this.fireEvent('select', this, rec, ix[0]);
44142 var lw = Math.floor(
44144 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
44145 ) / this.maxColumns
44147 this.loadingChildren = true;
44148 this.stores[opts.list+1].loadDataFromChildren( rec );
44149 this.loadingChildren = false;
44150 var dl = this.stores[opts.list+1]. getTotalCount();
44152 this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
44154 this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
44155 for (var i = opts.list+2; i < this.views.length;i++) {
44156 this.views[i].getEl().setStyle({ display : 'none' });
44159 this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
44160 this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
44162 if (this.isLoading) {
44163 // this.selectActive(opts.list);
44171 onDoubleClick : function()
44173 this.collapse(); //??
44181 recordToStack : function(store, prop, value, stack)
44183 var cstore = new Roo.data.SimpleStore({
44184 //fields : this.store.reader.meta.fields, // we need array reader.. for
44185 reader : this.store.reader,
44189 var record = false;
44191 if(store.getCount() < 1){
44194 store.each(function(r){
44195 if(r.data[prop] == value){
44200 if (r.data.cn && r.data.cn.length) {
44201 cstore.loadDataFromChildren( r);
44202 var cret = _this.recordToStack(cstore, prop, value, stack);
44203 if (cret !== false) {
44212 if (record == false) {
44215 stack.unshift(srec);
44220 * find the stack of stores that match our value.
44225 selectActive : function ()
44227 // if store is not loaded, then we will need to wait for that to happen first.
44229 this.recordToStack(this.store, this.valueField, this.getValue(), stack);
44230 for (var i = 0; i < stack.length; i++ ) {
44231 this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
44243 * Ext JS Library 1.1.1
44244 * Copyright(c) 2006-2007, Ext JS, LLC.
44246 * Originally Released Under LGPL - original licence link has changed is not relivant.
44249 * <script type="text/javascript">
44252 * @class Roo.form.Checkbox
44253 * @extends Roo.form.Field
44254 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
44256 * Creates a new Checkbox
44257 * @param {Object} config Configuration options
44259 Roo.form.Checkbox = function(config){
44260 Roo.form.Checkbox.superclass.constructor.call(this, config);
44264 * Fires when the checkbox is checked or unchecked.
44265 * @param {Roo.form.Checkbox} this This checkbox
44266 * @param {Boolean} checked The new checked value
44272 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
44274 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
44276 focusClass : undefined,
44278 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
44280 fieldClass: "x-form-field",
44282 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
44286 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
44287 * {tag: "input", type: "checkbox", autocomplete: "off"})
44289 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
44291 * @cfg {String} boxLabel The text that appears beside the checkbox
44295 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
44299 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
44301 valueOff: '0', // value when not checked..
44303 actionMode : 'viewEl',
44306 itemCls : 'x-menu-check-item x-form-item',
44307 groupClass : 'x-menu-group-item',
44308 inputType : 'hidden',
44311 inSetChecked: false, // check that we are not calling self...
44313 inputElement: false, // real input element?
44314 basedOn: false, // ????
44316 isFormField: true, // not sure where this is needed!!!!
44318 onResize : function(){
44319 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
44320 if(!this.boxLabel){
44321 this.el.alignTo(this.wrap, 'c-c');
44325 initEvents : function(){
44326 Roo.form.Checkbox.superclass.initEvents.call(this);
44327 this.el.on("click", this.onClick, this);
44328 this.el.on("change", this.onClick, this);
44332 getResizeEl : function(){
44336 getPositionEl : function(){
44341 onRender : function(ct, position){
44342 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
44344 if(this.inputValue !== undefined){
44345 this.el.dom.value = this.inputValue;
44348 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
44349 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
44350 var viewEl = this.wrap.createChild({
44351 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
44352 this.viewEl = viewEl;
44353 this.wrap.on('click', this.onClick, this);
44355 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
44356 this.el.on('propertychange', this.setFromHidden, this); //ie
44361 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
44362 // viewEl.on('click', this.onClick, this);
44364 //if(this.checked){
44365 this.setChecked(this.checked);
44367 //this.checked = this.el.dom;
44373 initValue : Roo.emptyFn,
44376 * Returns the checked state of the checkbox.
44377 * @return {Boolean} True if checked, else false
44379 getValue : function(){
44381 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
44383 return this.valueOff;
44388 onClick : function(){
44389 if (this.disabled) {
44392 this.setChecked(!this.checked);
44394 //if(this.el.dom.checked != this.checked){
44395 // this.setValue(this.el.dom.checked);
44400 * Sets the checked state of the checkbox.
44401 * On is always based on a string comparison between inputValue and the param.
44402 * @param {Boolean/String} value - the value to set
44403 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
44405 setValue : function(v,suppressEvent){
44408 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
44409 //if(this.el && this.el.dom){
44410 // this.el.dom.checked = this.checked;
44411 // this.el.dom.defaultChecked = this.checked;
44413 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
44414 //this.fireEvent("check", this, this.checked);
44417 setChecked : function(state,suppressEvent)
44419 if (this.inSetChecked) {
44420 this.checked = state;
44426 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
44428 this.checked = state;
44429 if(suppressEvent !== true){
44430 this.fireEvent('check', this, state);
44432 this.inSetChecked = true;
44433 this.el.dom.value = state ? this.inputValue : this.valueOff;
44434 this.inSetChecked = false;
44437 // handle setting of hidden value by some other method!!?!?
44438 setFromHidden: function()
44443 //console.log("SET FROM HIDDEN");
44444 //alert('setFrom hidden');
44445 this.setValue(this.el.dom.value);
44448 onDestroy : function()
44451 Roo.get(this.viewEl).remove();
44454 Roo.form.Checkbox.superclass.onDestroy.call(this);
44457 setBoxLabel : function(str)
44459 this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
44464 * Ext JS Library 1.1.1
44465 * Copyright(c) 2006-2007, Ext JS, LLC.
44467 * Originally Released Under LGPL - original licence link has changed is not relivant.
44470 * <script type="text/javascript">
44474 * @class Roo.form.Radio
44475 * @extends Roo.form.Checkbox
44476 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
44477 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
44479 * Creates a new Radio
44480 * @param {Object} config Configuration options
44482 Roo.form.Radio = function(){
44483 Roo.form.Radio.superclass.constructor.apply(this, arguments);
44485 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
44486 inputType: 'radio',
44489 * If this radio is part of a group, it will return the selected value
44492 getGroupValue : function(){
44493 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
44497 onRender : function(ct, position){
44498 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
44500 if(this.inputValue !== undefined){
44501 this.el.dom.value = this.inputValue;
44504 this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
44505 //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
44506 //var viewEl = this.wrap.createChild({
44507 // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
44508 //this.viewEl = viewEl;
44509 //this.wrap.on('click', this.onClick, this);
44511 //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
44512 //this.el.on('propertychange', this.setFromHidden, this); //ie
44517 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
44518 // viewEl.on('click', this.onClick, this);
44521 this.el.dom.checked = 'checked' ;
44527 });Roo.rtf = {}; // namespace
44528 Roo.rtf.Hex = function(hex)
44532 Roo.rtf.Paragraph = function(opts)
44534 this.content = []; ///??? is that used?
44535 };Roo.rtf.Span = function(opts)
44537 this.value = opts.value;
44540 Roo.rtf.Group = function(parent)
44542 // we dont want to acutally store parent - it will make debug a nightmare..
44550 Roo.rtf.Group.prototype = {
44554 addContent : function(node) {
44555 // could set styles...
44556 this.content.push(node);
44558 addChild : function(cn)
44562 // only for images really...
44563 toDataURL : function()
44565 var mimetype = false;
44567 case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0:
44568 mimetype = "image/png";
44570 case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
44571 mimetype = "image/jpeg";
44574 return 'about:blank'; // ?? error?
44578 var hexstring = this.content[this.content.length-1].value;
44580 return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
44581 return String.fromCharCode(parseInt(a, 16));
44586 // this looks like it's normally the {rtf{ .... }}
44587 Roo.rtf.Document = function()
44589 // we dont want to acutally store parent - it will make debug a nightmare..
44595 Roo.extend(Roo.rtf.Document, Roo.rtf.Group, {
44596 addChild : function(cn)
44600 case 'rtlch': // most content seems to be inside this??
44603 this.rtlch.push(cn);
44606 this[cn.type] = cn;
44611 getElementsByType : function(type)
44614 this._getElementsByType(type, ret, this.cn, 'rtf');
44617 _getElementsByType : function (type, ret, search_array, path)
44619 search_array.forEach(function(n,i) {
44620 if (n.type == type) {
44621 n.path = path + '/' + n.type + ':' + i;
44624 if (n.cn.length > 0) {
44625 this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
44632 Roo.rtf.Ctrl = function(opts)
44634 this.value = opts.value;
44635 this.param = opts.param;
44640 * based on this https://github.com/iarna/rtf-parser
44641 * it's really only designed to extract pict from pasted RTF
44645 * var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
44654 Roo.rtf.Parser = function(text) {
44655 //super({objectMode: true})
44657 this.parserState = this.parseText;
44659 // these are for interpeter...
44661 ///this.parserState = this.parseTop
44662 this.groupStack = [];
44663 this.hexStore = [];
44666 this.groups = []; // where we put the return.
44668 for (var ii = 0; ii < text.length; ++ii) {
44671 if (text[ii] === '\n') {
44677 this.parserState(text[ii]);
44683 Roo.rtf.Parser.prototype = {
44684 text : '', // string being parsed..
44686 controlWordParam : '',
44690 groupStack : false,
44695 row : 1, // reportin?
44699 push : function (el)
44701 var m = 'cmd'+ el.type;
44702 if (typeof(this[m]) == 'undefined') {
44703 Roo.log('invalid cmd:' + el.type);
44709 flushHexStore : function()
44711 if (this.hexStore.length < 1) {
44714 var hexstr = this.hexStore.map(
44719 this.group.addContent( new Roo.rtf.Hex( hexstr ));
44722 this.hexStore.splice(0)
44726 cmdgroupstart : function()
44728 this.flushHexStore();
44730 this.groupStack.push(this.group);
44733 if (this.doc === false) {
44734 this.group = this.doc = new Roo.rtf.Document();
44738 this.group = new Roo.rtf.Group(this.group);
44740 cmdignorable : function()
44742 this.flushHexStore();
44743 this.group.ignorable = true;
44745 cmdendparagraph : function()
44747 this.flushHexStore();
44748 this.group.addContent(new Roo.rtf.Paragraph());
44750 cmdgroupend : function ()
44752 this.flushHexStore();
44753 var endingGroup = this.group;
44756 this.group = this.groupStack.pop();
44758 this.group.addChild(endingGroup);
44763 var doc = this.group || this.doc;
44764 //if (endingGroup instanceof FontTable) {
44765 // doc.fonts = endingGroup.table
44766 //} else if (endingGroup instanceof ColorTable) {
44767 // doc.colors = endingGroup.table
44768 //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
44769 if (endingGroup.ignorable === false) {
44771 this.groups.push(endingGroup);
44772 // Roo.log( endingGroup );
44774 //Roo.each(endingGroup.content, function(item)) {
44775 // doc.addContent(item);
44777 //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
44780 cmdtext : function (cmd)
44782 this.flushHexStore();
44783 if (!this.group) { // an RTF fragment, missing the {\rtf1 header
44784 //this.group = this.doc
44786 this.group.addContent(new Roo.rtf.Span(cmd));
44788 cmdcontrolword : function (cmd)
44790 this.flushHexStore();
44791 if (!this.group.type) {
44792 this.group.type = cmd.value;
44795 this.group.addContent(new Roo.rtf.Ctrl(cmd));
44796 // we actually don't care about ctrl words...
44799 var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
44800 if (this[method]) {
44801 this[method](cmd.param)
44803 if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
44807 cmdhexchar : function(cmd) {
44808 this.hexStore.push(cmd);
44810 cmderror : function(cmd) {
44811 throw new Exception (cmd.value);
44816 if (this.text !== '\u0000') this.emitText()
44822 parseText : function(c)
44825 this.parserState = this.parseEscapes;
44826 } else if (c === '{') {
44827 this.emitStartGroup();
44828 } else if (c === '}') {
44829 this.emitEndGroup();
44830 } else if (c === '\x0A' || c === '\x0D') {
44831 // cr/lf are noise chars
44837 parseEscapes: function (c)
44839 if (c === '\\' || c === '{' || c === '}') {
44841 this.parserState = this.parseText;
44843 this.parserState = this.parseControlSymbol;
44844 this.parseControlSymbol(c);
44847 parseControlSymbol: function(c)
44850 this.text += '\u00a0'; // nbsp
44851 this.parserState = this.parseText
44852 } else if (c === '-') {
44853 this.text += '\u00ad'; // soft hyphen
44854 } else if (c === '_') {
44855 this.text += '\u2011'; // non-breaking hyphen
44856 } else if (c === '*') {
44857 this.emitIgnorable();
44858 this.parserState = this.parseText;
44859 } else if (c === "'") {
44860 this.parserState = this.parseHexChar;
44861 } else if (c === '|') { // formula cacter
44862 this.emitFormula();
44863 this.parserState = this.parseText;
44864 } else if (c === ':') { // subentry in an index entry
44865 this.emitIndexSubEntry();
44866 this.parserState = this.parseText;
44867 } else if (c === '\x0a') {
44868 this.emitEndParagraph();
44869 this.parserState = this.parseText;
44870 } else if (c === '\x0d') {
44871 this.emitEndParagraph();
44872 this.parserState = this.parseText;
44874 this.parserState = this.parseControlWord;
44875 this.parseControlWord(c);
44878 parseHexChar: function (c)
44880 if (/^[A-Fa-f0-9]$/.test(c)) {
44882 if (this.hexChar.length >= 2) {
44883 this.emitHexChar();
44884 this.parserState = this.parseText;
44888 this.emitError("Invalid character \"" + c + "\" in hex literal.");
44889 this.parserState = this.parseText;
44892 parseControlWord : function(c)
44895 this.emitControlWord();
44896 this.parserState = this.parseText;
44897 } else if (/^[-\d]$/.test(c)) {
44898 this.parserState = this.parseControlWordParam;
44899 this.controlWordParam += c;
44900 } else if (/^[A-Za-z]$/.test(c)) {
44901 this.controlWord += c;
44903 this.emitControlWord();
44904 this.parserState = this.parseText;
44908 parseControlWordParam : function (c) {
44909 if (/^\d$/.test(c)) {
44910 this.controlWordParam += c;
44911 } else if (c === ' ') {
44912 this.emitControlWord();
44913 this.parserState = this.parseText;
44915 this.emitControlWord();
44916 this.parserState = this.parseText;
44924 emitText : function () {
44925 if (this.text === '') {
44937 emitControlWord : function ()
44940 if (this.controlWord === '') {
44941 this.emitError('empty control word');
44944 type: 'controlword',
44945 value: this.controlWord,
44946 param: this.controlWordParam !== '' && Number(this.controlWordParam),
44952 this.controlWord = '';
44953 this.controlWordParam = '';
44955 emitStartGroup : function ()
44959 type: 'groupstart',
44965 emitEndGroup : function ()
44975 emitIgnorable : function ()
44985 emitHexChar : function ()
44990 value: this.hexChar,
44997 emitError : function (message)
45005 char: this.cpos //,
45006 //stack: new Error().stack
45009 emitEndParagraph : function () {
45012 type: 'endparagraph',
45020 Roo.htmleditor = {};
45023 * @class Roo.htmleditor.Filter
45024 * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
45025 * @cfg {DomElement} node The node to iterate and filter
45026 * @cfg {boolean|String|Array} tag Tags to replace
45028 * Create a new Filter.
45029 * @param {Object} config Configuration options
45034 Roo.htmleditor.Filter = function(cfg) {
45035 Roo.apply(this.cfg);
45036 // this does not actually call walk as it's really just a abstract class
45040 Roo.htmleditor.Filter.prototype = {
45046 // overrride to do replace comments.
45047 replaceComment : false,
45049 // overrride to do replace or do stuff with tags..
45050 replaceTag : false,
45052 walk : function(dom)
45054 Roo.each( Array.from(dom.childNodes), function( e ) {
45057 case e.nodeType == 8 && typeof(this.replaceComment) != 'undefined': // comment
45058 this.replaceComment(e);
45061 case e.nodeType != 1: //not a node.
45064 case this.tag === true: // everything
45065 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
45066 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
45067 if (this.replaceTag && false === this.replaceTag(e)) {
45070 if (e.hasChildNodes()) {
45075 default: // tags .. that do not match.
45076 if (e.hasChildNodes()) {
45087 * @class Roo.htmleditor.FilterAttributes
45088 * clean attributes and styles including http:// etc.. in attribute
45090 * Run a new Attribute Filter
45091 * @param {Object} config Configuration options
45093 Roo.htmleditor.FilterAttributes = function(cfg)
45095 Roo.apply(this, cfg);
45096 this.attrib_black = this.attrib_black || [];
45097 this.attrib_white = this.attrib_white || [];
45099 this.attrib_clean = this.attrib_clean || [];
45100 this.style_white = this.style_white || [];
45101 this.style_black = this.style_black || [];
45102 this.walk(cfg.node);
45105 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
45107 tag: true, // all tags
45109 attrib_black : false, // array
45110 attrib_clean : false,
45111 attrib_white : false,
45113 style_white : false,
45114 style_black : false,
45117 replaceTag : function(node)
45119 if (!node.attributes || !node.attributes.length) {
45123 for (var i = node.attributes.length-1; i > -1 ; i--) {
45124 var a = node.attributes[i];
45126 if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
45127 node.removeAttribute(a.name);
45133 if (a.name.toLowerCase().substr(0,2)=='on') {
45134 node.removeAttribute(a.name);
45139 if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
45140 node.removeAttribute(a.name);
45143 if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
45144 this.cleanAttr(node,a.name,a.value); // fixme..
45147 if (a.name == 'style') {
45148 this.cleanStyle(node,a.name,a.value);
45151 /// clean up MS crap..
45152 // tecnically this should be a list of valid class'es..
45155 if (a.name == 'class') {
45156 if (a.value.match(/^Mso/)) {
45157 node.removeAttribute('class');
45160 if (a.value.match(/^body$/)) {
45161 node.removeAttribute('class');
45171 return true; // clean children
45174 cleanAttr: function(node, n,v)
45177 if (v.match(/^\./) || v.match(/^\//)) {
45180 if (v.match(/^(http|https):\/\//)
45181 || v.match(/^mailto:/)
45182 || v.match(/^ftp:/)
45183 || v.match(/^data:/)
45187 if (v.match(/^#/)) {
45190 if (v.match(/^\{/)) { // allow template editing.
45193 // Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
45194 node.removeAttribute(n);
45197 cleanStyle : function(node, n,v)
45199 if (v.match(/expression/)) { //XSS?? should we even bother..
45200 node.removeAttribute(n);
45204 var parts = v.split(/;/);
45207 Roo.each(parts, function(p) {
45208 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
45212 var l = p.split(':').shift().replace(/\s+/g,'');
45213 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
45215 if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
45219 // only allow 'c whitelisted system attributes'
45220 if ( this.style_white.length && style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
45228 if (clean.length) {
45229 node.setAttribute(n, clean.join(';'));
45231 node.removeAttribute(n);
45240 * @class Roo.htmleditor.FilterBlack
45241 * remove blacklisted elements.
45243 * Run a new Blacklisted Filter
45244 * @param {Object} config Configuration options
45247 Roo.htmleditor.FilterBlack = function(cfg)
45249 Roo.apply(this, cfg);
45250 this.walk(cfg.node);
45253 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
45255 tag : true, // all elements.
45257 replace : function(n)
45259 n.parentNode.removeChild(n);
45263 * @class Roo.htmleditor.FilterComment
45266 * Run a new Comments Filter
45267 * @param {Object} config Configuration options
45269 Roo.htmleditor.FilterComment = function(cfg)
45271 this.walk(cfg.node);
45274 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
45277 replaceComment : function(n)
45279 n.parentNode.removeChild(n);
45282 * @class Roo.htmleditor.FilterKeepChildren
45283 * remove tags but keep children
45285 * Run a new Keep Children Filter
45286 * @param {Object} config Configuration options
45289 Roo.htmleditor.FilterKeepChildren = function(cfg)
45291 Roo.apply(this, cfg);
45292 if (this.tag === false) {
45293 return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
45295 this.walk(cfg.node);
45298 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
45302 replaceTag : function(node)
45304 // walk children...
45306 var ar = Array.from(node.childNodes);
45308 for (var i = 0; i < ar.length; i++) {
45309 if (ar[i].nodeType == 1) {
45311 (typeof(this.tag) == 'object' && this.tag.indexOf(ar[i].tagName) > -1)
45312 || // array and it matches
45313 (typeof(this.tag) == 'string' && this.tag == ar[i].tagName)
45315 this.replaceTag(ar[i]); // child is blacklisted as well...
45320 ar = Array.from(node.childNodes);
45321 for (var i = 0; i < ar.length; i++) {
45323 node.removeChild(ar[i]);
45324 // what if we need to walk these???
45325 node.parentNode.insertBefore(ar[i], node);
45326 if (this.tag !== false) {
45331 node.parentNode.removeChild(node);
45332 return false; // don't walk children
45337 * @class Roo.htmleditor.FilterParagraph
45338 * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
45339 * like on 'push' to remove the <p> tags and replace them with line breaks.
45341 * Run a new Paragraph Filter
45342 * @param {Object} config Configuration options
45345 Roo.htmleditor.FilterParagraph = function(cfg)
45347 // no need to apply config.
45348 this.walk(cfg.node);
45351 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
45358 replaceTag : function(node)
45361 if (node.childNodes.length == 1 &&
45362 node.childNodes[0].nodeType == 3 &&
45363 node.childNodes[0].textContent.trim().length < 1
45365 // remove and replace with '<BR>';
45366 node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
45367 return false; // no need to walk..
45369 var ar = Array.from(node.childNodes);
45370 for (var i = 0; i < ar.length; i++) {
45371 node.removeChild(ar[i]);
45372 // what if we need to walk these???
45373 node.parentNode.insertBefore(ar[i], node);
45375 // now what about this?
45379 node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
45380 node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
45381 node.parentNode.removeChild(node);
45388 * @class Roo.htmleditor.FilterSpan
45389 * filter span's with no attributes out..
45391 * Run a new Span Filter
45392 * @param {Object} config Configuration options
45395 Roo.htmleditor.FilterSpan = function(cfg)
45397 // no need to apply config.
45398 this.walk(cfg.node);
45401 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
45407 replaceTag : function(node)
45409 if (node.attributes && node.attributes.length > 0) {
45410 return true; // walk if there are any.
45412 Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
45418 * @class Roo.htmleditor.FilterTableWidth
45419 try and remove table width data - as that frequently messes up other stuff.
45421 * was cleanTableWidths.
45423 * Quite often pasting from word etc.. results in tables with column and widths.
45424 * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
45427 * Run a new Table Filter
45428 * @param {Object} config Configuration options
45431 Roo.htmleditor.FilterTableWidth = function(cfg)
45433 // no need to apply config.
45434 this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
45435 this.walk(cfg.node);
45438 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
45443 replaceTag: function(node) {
45447 if (node.hasAttribute('width')) {
45448 node.removeAttribute('width');
45452 if (node.hasAttribute("style")) {
45455 var styles = node.getAttribute("style").split(";");
45457 Roo.each(styles, function(s) {
45458 if (!s.match(/:/)) {
45461 var kv = s.split(":");
45462 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
45465 // what ever is left... we allow.
45468 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
45469 if (!nstyle.length) {
45470 node.removeAttribute('style');
45474 return true; // continue doing children..
45477 * @class Roo.htmleditor.FilterWord
45478 * try and clean up all the mess that Word generates.
45480 * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters
45483 * Run a new Span Filter
45484 * @param {Object} config Configuration options
45487 Roo.htmleditor.FilterWord = function(cfg)
45489 // no need to apply config.
45490 this.walk(cfg.node);
45493 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
45499 * Clean up MS wordisms...
45501 replaceTag : function(node)
45504 // no idea what this does - span with text, replaceds with just text.
45506 node.nodeName == 'SPAN' &&
45507 !node.hasAttributes() &&
45508 node.childNodes.length == 1 &&
45509 node.firstChild.nodeName == "#text"
45511 var textNode = node.firstChild;
45512 node.removeChild(textNode);
45513 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
45514 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
45516 node.parentNode.insertBefore(textNode, node);
45517 if (node.getAttribute('lang') != 'zh-CN') { // do not space pad on chinese characters..
45518 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
45521 node.parentNode.removeChild(node);
45522 return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
45527 if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
45528 node.parentNode.removeChild(node);
45529 return false; // dont do chidlren
45531 //Roo.log(node.tagName);
45532 // remove - but keep children..
45533 if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
45534 //Roo.log('-- removed');
45535 while (node.childNodes.length) {
45536 var cn = node.childNodes[0];
45537 node.removeChild(cn);
45538 node.parentNode.insertBefore(cn, node);
45539 // move node to parent - and clean it..
45540 this.replaceTag(cn);
45542 node.parentNode.removeChild(node);
45543 /// no need to iterate chidlren = it's got none..
45544 //this.iterateChildren(node, this.cleanWord);
45545 return false; // no need to iterate children.
45548 if (node.className.length) {
45550 var cn = node.className.split(/\W+/);
45552 Roo.each(cn, function(cls) {
45553 if (cls.match(/Mso[a-zA-Z]+/)) {
45558 node.className = cna.length ? cna.join(' ') : '';
45560 node.removeAttribute("class");
45564 if (node.hasAttribute("lang")) {
45565 node.removeAttribute("lang");
45568 if (node.hasAttribute("style")) {
45570 var styles = node.getAttribute("style").split(";");
45572 Roo.each(styles, function(s) {
45573 if (!s.match(/:/)) {
45576 var kv = s.split(":");
45577 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
45580 // what ever is left... we allow.
45583 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
45584 if (!nstyle.length) {
45585 node.removeAttribute('style');
45588 return true; // do children
45595 * @class Roo.htmleditor.FilterStyleToTag
45596 * part of the word stuff... - certain 'styles' should be converted to tags.
45598 * font-weight: bold -> bold
45599 * ?? super / subscrit etc..
45602 * Run a new style to tag filter.
45603 * @param {Object} config Configuration options
45605 Roo.htmleditor.FilterStyleToTag = function(cfg)
45609 B : [ 'fontWeight' , 'bold'],
45610 I : [ 'fontStyle' , 'italic'],
45611 //pre : [ 'font-style' , 'italic'],
45612 // h1.. h6 ?? font-size?
45613 SUP : [ 'verticalAlign' , 'super' ],
45614 SUB : [ 'verticalAlign' , 'sub' ]
45619 Roo.apply(this, cfg);
45622 this.walk(cfg.node);
45629 Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
45631 tag: true, // all tags
45636 replaceTag : function(node)
45640 if (node.getAttribute("style") === null) {
45644 for (var k in this.tags) {
45645 if (node.style[this.tags[k][0]] == this.tags[k][1]) {
45647 node.style.removeProperty(this.tags[k][0]);
45650 if (!inject.length) {
45653 var cn = Array.from(node.childNodes);
45655 Roo.each(inject, function(t) {
45656 var nc = node.ownerDocument.createelement(t);
45657 nn.appendChild(nc);
45660 for(var i = 0;i < cn.length;cn++) {
45661 node.removeChild(cn[i]);
45662 nn.appendChild(cn[i]);
45664 return true /// iterate thru
45668 * @class Roo.htmleditor.FilterLongBr
45669 * BR/BR/BR - keep a maximum of 2...
45671 * Run a new Long BR Filter
45672 * @param {Object} config Configuration options
45675 Roo.htmleditor.FilterLongBr = function(cfg)
45677 // no need to apply config.
45678 this.walk(cfg.node);
45681 Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
45688 replaceTag : function(node)
45691 var ps = node.nextSibling;
45692 while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
45693 ps = ps.nextSibling;
45696 if (!ps && [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) {
45697 node.parentNode.removeChild(node); // remove last BR inside one fo these tags
45701 if (!ps || ps.nodeType != 1) {
45705 if (!ps || ps.tagName != 'BR') {
45714 if (!node.previousSibling) {
45717 var ps = node.previousSibling;
45719 while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
45720 ps = ps.previousSibling;
45722 if (!ps || ps.nodeType != 1) {
45725 // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
45726 if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
45730 node.parentNode.removeChild(node); // remove me...
45732 return false; // no need to do children
45738 * @class Roo.htmleditor.Tidy
45740 * @cfg {Roo.HtmlEditorCore} core the editor.
45742 * Create a new Filter.
45743 * @param {Object} config Configuration options
45747 Roo.htmleditor.Tidy = function(cfg) {
45748 Roo.apply(this, cfg);
45750 this.core.doc.body.innerHTML = this.tidy(this.core.doc.body, '');
45754 Roo.htmleditor.Tidy.toString = function(node)
45756 return Roo.htmleditor.Tidy.prototype.tidy(node, '');
45759 Roo.htmleditor.Tidy.prototype = {
45762 wrap : function(s) {
45763 return s.replace(/\n/g, " ").replace(/(?![^\n]{1,80}$)([^\n]{1,80})\s/g, '$1\n');
45767 tidy : function(node, indent) {
45769 if (node.nodeType == 3) {
45773 return indent === false ? node.nodeValue : this.wrap(node.nodeValue.trim()).split("\n").join("\n" + indent);
45778 if (node.nodeType != 1) {
45784 if (node.tagName == 'BODY') {
45786 return this.cn(node, '');
45789 // Prints the node tagName, such as <A>, <IMG>, etc
45790 var ret = "<" + node.tagName + this.attr(node) ;
45792 // elements with no children..
45793 if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(node.tagName) > -1) {
45799 var cindent = indent === false ? '' : (indent + ' ');
45800 // tags where we will not pad the children.. (inline text tags etc..)
45801 if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN', 'B', 'I', 'S'].indexOf(node.tagName) > -1) { // or code?
45807 var cn = this.cn(node, cindent );
45809 return ret + cn + '</' + node.tagName + '>';
45812 cn: function(node, indent)
45816 var ar = Array.from(node.childNodes);
45817 for (var i = 0 ; i < ar.length ; i++) {
45821 if (indent !== false // indent==false preservies everything
45823 && ar[i].nodeType == 3
45824 && ar[i].nodeValue.length > 0
45825 && ar[i].nodeValue.match(/^\s+/)
45827 if (ret.length && ret[ret.length-1] == "\n" + indent) {
45828 ret.pop(); // remove line break from last?
45831 ret.push(" "); // add a space if i'm a text item with a space at the front, as tidy will strip spaces.
45833 if (indent !== false
45834 && ar[i].nodeType == 1 // element - and indent is not set...
45836 ret.push("\n" + indent);
45839 ret.push(this.tidy(ar[i], indent));
45840 // text + trailing indent
45841 if (indent !== false
45842 && ar[i].nodeType == 3
45843 && ar[i].nodeValue.length > 0
45844 && ar[i].nodeValue.match(/\s+$/)
45846 ret.push("\n" + indent);
45853 // what if all text?
45856 return ret.join('');
45861 attr : function(node)
45864 for(i = 0; i < node.attributes.length;i++) {
45866 // skip empty values?
45867 if (!node.attributes.item(i).value.length) {
45870 attr.push( node.attributes.item(i).name + '="' +
45871 Roo.util.Format.htmlEncode(node.attributes.item(i).value) + '"'
45874 return attr.length ? (' ' + attr.join(' ') ) : '';
45882 * @class Roo.htmleditor.KeyEnter
45883 * Handle Enter press..
45884 * @cfg {Roo.HtmlEditorCore} core the editor.
45886 * Create a new Filter.
45887 * @param {Object} config Configuration options
45892 Roo.htmleditor.KeyEnter = function(cfg) {
45893 Roo.apply(this, cfg);
45894 // this does not actually call walk as it's really just a abstract class
45896 Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
45900 Roo.htmleditor.KeyEnter.prototype = {
45904 keypress : function(e) {
45905 if (e.charCode != 13) {
45908 e.preventDefault();
45909 // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
45910 var doc = this.core.doc;
45912 var docFragment = doc.createDocumentFragment();
45915 var newEle = doc.createTextNode('\n');
45916 docFragment.appendChild(newEle);
45919 var range = this.core.win.getSelection().getRangeAt(0);
45920 var n = range.commonAncestorContainer ;
45921 while (n && n.nodeType != 1) {
45925 if (n && n.tagName == 'UL') {
45926 li = doc.createElement('LI');
45930 if (n && n.tagName == 'LI') {
45931 li = doc.createElement('LI');
45932 if (n.nextSibling) {
45933 n.parentNode.insertBefore(li, n.firstSibling);
45936 n.parentNode.appendChild(li);
45940 range = doc.createRange();
45941 range.setStartAfter(li);
45942 range.collapse(true);
45944 //make the cursor there
45945 var sel = this.core.win.getSelection();
45946 sel.removeAllRanges();
45947 sel.addRange(range);
45952 //add the br, or p, or something else
45953 newEle = doc.createElement('br');
45954 docFragment.appendChild(newEle);
45956 //make the br replace selection
45958 range.deleteContents();
45960 range.insertNode(docFragment);
45962 //create a new range
45963 range = doc.createRange();
45964 range.setStartAfter(newEle);
45965 range.collapse(true);
45967 //make the cursor there
45968 var sel = this.core.win.getSelection();
45969 sel.removeAllRanges();
45970 sel.addRange(range);
45978 * @class Roo.htmleditor.Block
45979 * Base class for html editor blocks - do not use it directly .. extend it..
45980 * @cfg {DomElement} node The node to apply stuff to.
45981 * @cfg {String} friendly_name the name that appears in the context bar about this block
45982 * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
45985 * Create a new Filter.
45986 * @param {Object} config Configuration options
45989 Roo.htmleditor.Block = function(cfg)
45991 // do nothing .. should not be called really.
45994 Roo.htmleditor.Block.factory = function(node)
45997 var id = Roo.get(node).id;
45998 if (typeof(Roo.htmleditor.Block.cache[id]) != 'undefined') {
45999 Roo.htmleditor.Block.cache[id].readElement();
46000 return Roo.htmleditor.Block.cache[id];
46003 var cls = Roo.htmleditor['Block' + Roo.get(node).attr('data-block')];
46004 if (typeof(cls) == 'undefined') {
46005 Roo.log("OOps missing block : " + 'Block' + Roo.get(node).attr('data-block'));
46008 Roo.htmleditor.Block.cache[id] = new cls({ node: node });
46009 return Roo.htmleditor.Block.cache[id]; /// should trigger update element
46011 // question goes here... do we need to clear out this cache sometimes?
46012 // or show we make it relivant to the htmleditor.
46013 Roo.htmleditor.Block.cache = {};
46015 Roo.htmleditor.Block.prototype = {
46019 // used by context menu
46020 friendly_name : 'Image with caption',
46024 * Update a node with values from this object
46025 * @param {DomElement} node
46027 updateElement : function(node)
46029 Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
46032 * convert to plain HTML for calling insertAtCursor..
46034 toHTML : function()
46036 return Roo.DomHelper.markup(this.toObject());
46039 * used by readEleemnt to extract data from a node
46040 * may need improving as it's pretty basic
46042 * @param {DomElement} node
46043 * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
46044 * @param {String} attribute (use html - for contents, or style for using next param as style)
46045 * @param {String} style the style property - eg. text-align
46047 getVal : function(node, tag, attr, style)
46050 if (tag !== true && n.tagName != tag.toUpperCase()) {
46051 // in theory we could do figure[3] << 3rd figure? or some more complex search..?
46052 // but kiss for now.
46053 n = node.getElementsByTagName(tag).item(0);
46055 if (attr == 'html') {
46056 return n.innerHTML;
46058 if (attr == 'style') {
46059 return Roo.get(n).getStyle(style);
46062 return Roo.get(n).attr(attr);
46066 * create a DomHelper friendly object - for use with
46067 * Roo.DomHelper.markup / overwrite / etc..
46070 toObject : function()
46075 * Read a node that has a 'data-block' property - and extract the values from it.
46076 * @param {DomElement} node - the node
46078 readElement : function(node)
46089 * @class Roo.htmleditor.BlockFigure
46090 * Block that has an image and a figcaption
46091 * @cfg {String} image_src the url for the image
46092 * @cfg {String} align (left|right) alignment for the block default left
46093 * @cfg {String} text_align (left|right) alignment for the text caption default left.
46094 * @cfg {String} caption the text to appear below (and in the alt tag)
46095 * @cfg {String|number} image_width the width of the image number or %?
46096 * @cfg {String|number} image_height the height of the image number or %?
46099 * Create a new Filter.
46100 * @param {Object} config Configuration options
46103 Roo.htmleditor.BlockFigure = function(cfg)
46106 this.readElement(cfg.node);
46107 this.updateElement(cfg.node);
46109 Roo.apply(this, cfg);
46111 Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
46119 text_align: 'left',
46124 // used by context menu
46125 friendly_name : 'Image with caption',
46127 context : { // ?? static really
46140 opts : [[ "left"],[ "right"]],
46145 title: "Caption Align",
46146 opts : [ [ "left"],[ "right"],[ "center"]],
46157 * create a DomHelper friendly object - for use with
46158 * Roo.DomHelper.markup / overwrite / etc..
46160 toObject : function()
46162 var d = document.createElement('div');
46163 d.innerHTML = this.caption;
46167 'data-block' : 'Figure',
46168 contenteditable : 'false',
46171 float : this.align ,
46172 width : this.width,
46173 margin: this.margin
46178 src : this.image_src,
46179 alt : d.innerText.replace(/\n/g, " "), // removeHTML..
46186 contenteditable : true,
46188 'text-align': this.text_align
46190 html : this.caption
46197 readElement : function(node)
46199 this.image_src = this.getVal(node, 'img', 'src');
46200 this.align = this.getVal(node, 'figure', 'style', 'float');
46201 this.caption = this.getVal(node, 'figcaption', 'html');
46202 this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
46203 this.width = this.getVal(node, 'figure', 'style', 'width');
46204 this.margin = this.getVal(node, 'figure', 'style', 'margin');
46217 //<script type="text/javascript">
46220 * Based Ext JS Library 1.1.1
46221 * Copyright(c) 2006-2007, Ext JS, LLC.
46227 * @class Roo.HtmlEditorCore
46228 * @extends Roo.Component
46229 * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
46231 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
46234 Roo.HtmlEditorCore = function(config){
46237 Roo.HtmlEditorCore.superclass.constructor.call(this, config);
46242 * @event initialize
46243 * Fires when the editor is fully initialized (including the iframe)
46244 * @param {Roo.HtmlEditorCore} this
46249 * Fires when the editor is first receives the focus. Any insertion must wait
46250 * until after this event.
46251 * @param {Roo.HtmlEditorCore} this
46255 * @event beforesync
46256 * Fires before the textarea is updated with content from the editor iframe. Return false
46257 * to cancel the sync.
46258 * @param {Roo.HtmlEditorCore} this
46259 * @param {String} html
46263 * @event beforepush
46264 * Fires before the iframe editor is updated with content from the textarea. Return false
46265 * to cancel the push.
46266 * @param {Roo.HtmlEditorCore} this
46267 * @param {String} html
46272 * Fires when the textarea is updated with content from the editor iframe.
46273 * @param {Roo.HtmlEditorCore} this
46274 * @param {String} html
46279 * Fires when the iframe editor is updated with content from the textarea.
46280 * @param {Roo.HtmlEditorCore} this
46281 * @param {String} html
46286 * @event editorevent
46287 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
46288 * @param {Roo.HtmlEditorCore} this
46294 // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
46296 // defaults : white / black...
46297 this.applyBlacklists();
46304 Roo.extend(Roo.HtmlEditorCore, Roo.Component, {
46308 * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field
46314 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
46319 * @cfg {Number} height (in pixels)
46323 * @cfg {Number} width (in pixels)
46328 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
46331 stylesheets: false,
46334 * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
46336 allowComments: false,
46340 // private properties
46341 validationEvent : false,
46343 initialized : false,
46345 sourceEditMode : false,
46346 onFocus : Roo.emptyFn,
46348 hideMode:'offsets',
46352 // blacklist + whitelisted elements..
46359 * Protected method that will not generally be called directly. It
46360 * is called when the editor initializes the iframe with HTML contents. Override this method if you
46361 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
46363 getDocMarkup : function(){
46367 // inherit styels from page...??
46368 if (this.stylesheets === false) {
46370 Roo.get(document.head).select('style').each(function(node) {
46371 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
46374 Roo.get(document.head).select('link').each(function(node) {
46375 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
46378 } else if (!this.stylesheets.length) {
46380 st = '<style type="text/css">' +
46381 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
46384 for (var i in this.stylesheets) {
46385 if (typeof(this.stylesheets[i]) != 'string') {
46388 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
46393 st += '<style type="text/css">' +
46394 'IMG { cursor: pointer } ' +
46397 var cls = 'roo-htmleditor-body';
46399 if(this.bodyCls.length){
46400 cls += ' ' + this.bodyCls;
46403 return '<html><head>' + st +
46404 //<style type="text/css">' +
46405 //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
46407 ' </head><body contenteditable="true" data-enable-grammerly="true" class="' + cls + '"></body></html>';
46411 onRender : function(ct, position)
46414 //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
46415 this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
46418 this.el.dom.style.border = '0 none';
46419 this.el.dom.setAttribute('tabIndex', -1);
46420 this.el.addClass('x-hidden hide');
46424 if(Roo.isIE){ // fix IE 1px bogus margin
46425 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
46429 this.frameId = Roo.id();
46433 var iframe = this.owner.wrap.createChild({
46435 cls: 'form-control', // bootstrap..
46437 name: this.frameId,
46438 frameBorder : 'no',
46439 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
46444 this.iframe = iframe.dom;
46446 this.assignDocWin();
46448 this.doc.designMode = 'on';
46451 this.doc.write(this.getDocMarkup());
46455 var task = { // must defer to wait for browser to be ready
46457 //console.log("run task?" + this.doc.readyState);
46458 this.assignDocWin();
46459 if(this.doc.body || this.doc.readyState == 'complete'){
46461 this.doc.designMode="on";
46465 Roo.TaskMgr.stop(task);
46466 this.initEditor.defer(10, this);
46473 Roo.TaskMgr.start(task);
46478 onResize : function(w, h)
46480 Roo.log('resize: ' +w + ',' + h );
46481 //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
46485 if(typeof w == 'number'){
46487 this.iframe.style.width = w + 'px';
46489 if(typeof h == 'number'){
46491 this.iframe.style.height = h + 'px';
46493 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
46500 * Toggles the editor between standard and source edit mode.
46501 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
46503 toggleSourceEdit : function(sourceEditMode){
46505 this.sourceEditMode = sourceEditMode === true;
46507 if(this.sourceEditMode){
46509 Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']); //FIXME - what's the BS styles for these
46512 Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
46513 //this.iframe.className = '';
46516 //this.setSize(this.owner.wrap.getSize());
46517 //this.fireEvent('editmodechange', this, this.sourceEditMode);
46524 * Protected method that will not generally be called directly. If you need/want
46525 * custom HTML cleanup, this is the method you should override.
46526 * @param {String} html The HTML to be cleaned
46527 * return {String} The cleaned HTML
46529 cleanHtml : function(html){
46530 html = String(html);
46531 if(html.length > 5){
46532 if(Roo.isSafari){ // strip safari nonsense
46533 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
46536 if(html == ' '){
46543 * HTML Editor -> Textarea
46544 * Protected method that will not generally be called directly. Syncs the contents
46545 * of the editor iframe with the textarea.
46547 syncValue : function()
46549 Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
46550 if(this.initialized){
46551 var bd = (this.doc.body || this.doc.documentElement);
46552 //this.cleanUpPaste(); -- this is done else where and causes havoc..
46554 // not sure if this is really the place for this
46555 // the blocks are synced occasionaly - since we currently dont add listeners on the blocks
46556 // this has to update attributes that get duped.. like alt and caption..
46559 //Roo.each(Roo.get(this.doc.body).query('*[data-block]'), function(e) {
46560 // Roo.htmleditor.Block.factory(e);
46564 var div = document.createElement('div');
46565 div.innerHTML = bd.innerHTML;
46566 // remove content editable. (blocks)
46569 new Roo.htmleditor.FilterAttributes({node : div, attrib_black: [ 'contenteditable' ] });
46571 var html = div.innerHTML;
46573 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
46574 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
46576 html = '<div style="'+m[0]+'">' + html + '</div>';
46579 html = this.cleanHtml(html);
46580 // fix up the special chars.. normaly like back quotes in word...
46581 // however we do not want to do this with chinese..
46582 html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
46584 var cc = match.charCodeAt();
46586 // Get the character value, handling surrogate pairs
46587 if (match.length == 2) {
46588 // It's a surrogate pair, calculate the Unicode code point
46589 var high = match.charCodeAt(0) - 0xD800;
46590 var low = match.charCodeAt(1) - 0xDC00;
46591 cc = (high * 0x400) + low + 0x10000;
46593 (cc >= 0x4E00 && cc < 0xA000 ) ||
46594 (cc >= 0x3400 && cc < 0x4E00 ) ||
46595 (cc >= 0xf900 && cc < 0xfb00 )
46600 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
46601 return "&#" + cc + ";";
46608 if(this.owner.fireEvent('beforesync', this, html) !== false){
46609 this.el.dom.value = html;
46610 this.owner.fireEvent('sync', this, html);
46616 * TEXTAREA -> EDITABLE
46617 * Protected method that will not generally be called directly. Pushes the value of the textarea
46618 * into the iframe editor.
46620 pushValue : function()
46622 Roo.log("HtmlEditorCore:pushValue (TEXT->EDITOR)");
46623 if(this.initialized){
46624 var v = this.el.dom.value.trim();
46627 if(this.owner.fireEvent('beforepush', this, v) !== false){
46628 var d = (this.doc.body || this.doc.documentElement);
46631 this.el.dom.value = d.innerHTML;
46632 this.owner.fireEvent('push', this, v);
46635 Roo.each(Roo.get(this.doc.body).query('*[data-block]'), function(e) {
46637 Roo.htmleditor.Block.factory(e);
46640 var lc = this.doc.body.lastChild;
46641 if (lc && lc.nodeType == 1 && lc.getAttribute("contenteditable") == "false") {
46642 // add an extra line at the end.
46643 this.doc.body.appendChild(this.doc.createElement('br'));
46651 deferFocus : function(){
46652 this.focus.defer(10, this);
46656 focus : function(){
46657 if(this.win && !this.sourceEditMode){
46664 assignDocWin: function()
46666 var iframe = this.iframe;
46669 this.doc = iframe.contentWindow.document;
46670 this.win = iframe.contentWindow;
46672 // if (!Roo.get(this.frameId)) {
46675 // this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
46676 // this.win = Roo.get(this.frameId).dom.contentWindow;
46678 if (!Roo.get(this.frameId) && !iframe.contentDocument) {
46682 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
46683 this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
46688 initEditor : function(){
46689 //console.log("INIT EDITOR");
46690 this.assignDocWin();
46694 this.doc.designMode="on";
46696 this.doc.write(this.getDocMarkup());
46699 var dbody = (this.doc.body || this.doc.documentElement);
46700 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
46701 // this copies styles from the containing element into thsi one..
46702 // not sure why we need all of this..
46703 //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
46705 //var ss = this.el.getStyles( 'background-image', 'background-repeat');
46706 //ss['background-attachment'] = 'fixed'; // w3c
46707 dbody.bgProperties = 'fixed'; // ie
46708 //Roo.DomHelper.applyStyles(dbody, ss);
46709 Roo.EventManager.on(this.doc, {
46710 //'mousedown': this.onEditorEvent,
46711 'mouseup': this.onEditorEvent,
46712 'dblclick': this.onEditorEvent,
46713 'click': this.onEditorEvent,
46714 'keyup': this.onEditorEvent,
46719 Roo.EventManager.on(this.doc, {
46720 'paste': this.onPasteEvent,
46724 Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
46726 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
46727 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
46729 this.initialized = true;
46732 // initialize special key events - enter
46733 new Roo.htmleditor.KeyEnter({core : this});
46737 this.owner.fireEvent('initialize', this);
46741 onPasteEvent : function(e,v)
46743 // I think we better assume paste is going to be a dirty load of rubish from word..
46745 // even pasting into a 'email version' of this widget will have to clean up that mess.
46746 var cd = (e.browserEvent.clipboardData || window.clipboardData);
46748 // check what type of paste - if it's an image, then handle it differently.
46749 if (cd.files.length > 0) {
46751 var urlAPI = (window.createObjectURL && window) ||
46752 (window.URL && URL.revokeObjectURL && URL) ||
46753 (window.webkitURL && webkitURL);
46755 var url = urlAPI.createObjectURL( cd.files[0]);
46756 this.insertAtCursor('<img src=" + url + ">');
46760 var html = cd.getData('text/html'); // clipboard event
46761 var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
46762 var images = parser.doc.getElementsByType('pict');
46766 images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable)/); }) // ignore headers
46767 .map(function(g) { return g.toDataURL(); });
46770 html = this.cleanWordChars(html);
46772 var d = (new DOMParser().parseFromString(html, 'text/html')).body;
46774 if (images.length > 0) {
46775 Roo.each(d.getElementsByTagName('img'), function(img, i) {
46776 img.setAttribute('src', images[i]);
46781 new Roo.htmleditor.FilterStyleToTag({ node : d });
46782 new Roo.htmleditor.FilterAttributes({
46784 attrib_white : ['href', 'src', 'name', 'align'],
46785 attrib_clean : ['href', 'src' ]
46787 new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
46788 // should be fonts..
46789 new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT' ]} );
46790 new Roo.htmleditor.FilterParagraph({ node : d });
46791 new Roo.htmleditor.FilterSpan({ node : d });
46792 new Roo.htmleditor.FilterLongBr({ node : d });
46796 this.insertAtCursor(d.innerHTML);
46798 e.preventDefault();
46800 // default behaveiour should be our local cleanup paste? (optional?)
46801 // for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
46802 //this.owner.fireEvent('paste', e, v);
46805 onDestroy : function(){
46811 //for (var i =0; i < this.toolbars.length;i++) {
46812 // // fixme - ask toolbars for heights?
46813 // this.toolbars[i].onDestroy();
46816 //this.wrap.dom.innerHTML = '';
46817 //this.wrap.remove();
46822 onFirstFocus : function(){
46824 this.assignDocWin();
46827 this.activated = true;
46830 if(Roo.isGecko){ // prevent silly gecko errors
46832 var s = this.win.getSelection();
46833 if(!s.focusNode || s.focusNode.nodeType != 3){
46834 var r = s.getRangeAt(0);
46835 r.selectNodeContents((this.doc.body || this.doc.documentElement));
46840 this.execCmd('useCSS', true);
46841 this.execCmd('styleWithCSS', false);
46844 this.owner.fireEvent('activate', this);
46848 adjustFont: function(btn){
46849 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
46850 //if(Roo.isSafari){ // safari
46853 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
46854 if(Roo.isSafari){ // safari
46855 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
46856 v = (v < 10) ? 10 : v;
46857 v = (v > 48) ? 48 : v;
46858 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
46863 v = Math.max(1, v+adjust);
46865 this.execCmd('FontSize', v );
46868 onEditorEvent : function(e)
46870 this.owner.fireEvent('editorevent', this, e);
46871 // this.updateToolbar();
46872 this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
46875 insertTag : function(tg)
46877 // could be a bit smarter... -> wrap the current selected tRoo..
46878 if (tg.toLowerCase() == 'span' ||
46879 tg.toLowerCase() == 'code' ||
46880 tg.toLowerCase() == 'sup' ||
46881 tg.toLowerCase() == 'sub'
46884 range = this.createRange(this.getSelection());
46885 var wrappingNode = this.doc.createElement(tg.toLowerCase());
46886 wrappingNode.appendChild(range.extractContents());
46887 range.insertNode(wrappingNode);
46894 this.execCmd("formatblock", tg);
46898 insertText : function(txt)
46902 var range = this.createRange();
46903 range.deleteContents();
46904 //alert(Sender.getAttribute('label'));
46906 range.insertNode(this.doc.createTextNode(txt));
46912 * Executes a Midas editor command on the editor document and performs necessary focus and
46913 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
46914 * @param {String} cmd The Midas command
46915 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
46917 relayCmd : function(cmd, value){
46919 this.execCmd(cmd, value);
46920 this.owner.fireEvent('editorevent', this);
46921 //this.updateToolbar();
46922 this.owner.deferFocus();
46926 * Executes a Midas editor command directly on the editor document.
46927 * For visual commands, you should use {@link #relayCmd} instead.
46928 * <b>This should only be called after the editor is initialized.</b>
46929 * @param {String} cmd The Midas command
46930 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
46932 execCmd : function(cmd, value){
46933 this.doc.execCommand(cmd, false, value === undefined ? null : value);
46940 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
46942 * @param {String} text | dom node..
46944 insertAtCursor : function(text)
46947 if(!this.activated){
46951 if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
46955 // from jquery ui (MIT licenced)
46957 var win = this.win;
46959 if (win.getSelection && win.getSelection().getRangeAt) {
46961 // delete the existing?
46963 this.createRange(this.getSelection()).deleteContents();
46964 range = win.getSelection().getRangeAt(0);
46965 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
46966 range.insertNode(node);
46967 } else if (win.document.selection && win.document.selection.createRange) {
46968 // no firefox support
46969 var txt = typeof(text) == 'string' ? text : text.outerHTML;
46970 win.document.selection.createRange().pasteHTML(txt);
46972 // no firefox support
46973 var txt = typeof(text) == 'string' ? text : text.outerHTML;
46974 this.execCmd('InsertHTML', txt);
46983 mozKeyPress : function(e){
46985 var c = e.getCharCode(), cmd;
46988 c = String.fromCharCode(c).toLowerCase();
47002 // this.cleanUpPaste.defer(100, this);
47010 e.preventDefault();
47018 fixKeys : function(){ // load time branching for fastest keydown performance
47020 return function(e){
47021 var k = e.getKey(), r;
47024 r = this.doc.selection.createRange();
47027 r.pasteHTML('    ');
47034 r = this.doc.selection.createRange();
47036 var target = r.parentElement();
47037 if(!target || target.tagName.toLowerCase() != 'li'){
47039 r.pasteHTML('<br/>');
47045 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
47046 // this.cleanUpPaste.defer(100, this);
47052 }else if(Roo.isOpera){
47053 return function(e){
47054 var k = e.getKey();
47058 this.execCmd('InsertHTML','    ');
47061 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
47062 // this.cleanUpPaste.defer(100, this);
47067 }else if(Roo.isSafari){
47068 return function(e){
47069 var k = e.getKey();
47073 this.execCmd('InsertText','\t');
47077 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
47078 // this.cleanUpPaste.defer(100, this);
47086 getAllAncestors: function()
47088 var p = this.getSelectedNode();
47091 a.push(p); // push blank onto stack..
47092 p = this.getParentElement();
47096 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
47100 a.push(this.doc.body);
47104 lastSelNode : false,
47107 getSelection : function()
47109 this.assignDocWin();
47110 return Roo.isIE ? this.doc.selection : this.win.getSelection();
47113 * Select a dom node
47114 * @param {DomElement} node the node to select
47116 selectNode : function(node)
47119 var nodeRange = node.ownerDocument.createRange();
47121 nodeRange.selectNode(node);
47123 nodeRange.selectNodeContents(node);
47125 //nodeRange.collapse(true);
47126 var s = this.win.getSelection();
47127 s.removeAllRanges();
47128 s.addRange(nodeRange);
47131 getSelectedNode: function()
47133 // this may only work on Gecko!!!
47135 // should we cache this!!!!
47140 var range = this.createRange(this.getSelection()).cloneRange();
47143 var parent = range.parentElement();
47145 var testRange = range.duplicate();
47146 testRange.moveToElementText(parent);
47147 if (testRange.inRange(range)) {
47150 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
47153 parent = parent.parentElement;
47158 // is ancestor a text element.
47159 var ac = range.commonAncestorContainer;
47160 if (ac.nodeType == 3) {
47161 ac = ac.parentNode;
47164 var ar = ac.childNodes;
47167 var other_nodes = [];
47168 var has_other_nodes = false;
47169 for (var i=0;i<ar.length;i++) {
47170 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
47173 // fullly contained node.
47175 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
47180 // probably selected..
47181 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
47182 other_nodes.push(ar[i]);
47186 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
47191 has_other_nodes = true;
47193 if (!nodes.length && other_nodes.length) {
47194 nodes= other_nodes;
47196 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
47202 createRange: function(sel)
47204 // this has strange effects when using with
47205 // top toolbar - not sure if it's a great idea.
47206 //this.editor.contentWindow.focus();
47207 if (typeof sel != "undefined") {
47209 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
47211 return this.doc.createRange();
47214 return this.doc.createRange();
47217 getParentElement: function()
47220 this.assignDocWin();
47221 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
47223 var range = this.createRange(sel);
47226 var p = range.commonAncestorContainer;
47227 while (p.nodeType == 3) { // text node
47238 * Range intersection.. the hard stuff...
47242 * [ -- selected range --- ]
47246 * if end is before start or hits it. fail.
47247 * if start is after end or hits it fail.
47249 * if either hits (but other is outside. - then it's not
47255 // @see http://www.thismuchiknow.co.uk/?p=64.
47256 rangeIntersectsNode : function(range, node)
47258 var nodeRange = node.ownerDocument.createRange();
47260 nodeRange.selectNode(node);
47262 nodeRange.selectNodeContents(node);
47265 var rangeStartRange = range.cloneRange();
47266 rangeStartRange.collapse(true);
47268 var rangeEndRange = range.cloneRange();
47269 rangeEndRange.collapse(false);
47271 var nodeStartRange = nodeRange.cloneRange();
47272 nodeStartRange.collapse(true);
47274 var nodeEndRange = nodeRange.cloneRange();
47275 nodeEndRange.collapse(false);
47277 return rangeStartRange.compareBoundaryPoints(
47278 Range.START_TO_START, nodeEndRange) == -1 &&
47279 rangeEndRange.compareBoundaryPoints(
47280 Range.START_TO_START, nodeStartRange) == 1;
47284 rangeCompareNode : function(range, node)
47286 var nodeRange = node.ownerDocument.createRange();
47288 nodeRange.selectNode(node);
47290 nodeRange.selectNodeContents(node);
47294 range.collapse(true);
47296 nodeRange.collapse(true);
47298 var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
47299 var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
47301 //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
47303 var nodeIsBefore = ss == 1;
47304 var nodeIsAfter = ee == -1;
47306 if (nodeIsBefore && nodeIsAfter) {
47309 if (!nodeIsBefore && nodeIsAfter) {
47310 return 1; //right trailed.
47313 if (nodeIsBefore && !nodeIsAfter) {
47314 return 2; // left trailed.
47320 cleanWordChars : function(input) {// change the chars to hex code
47323 [ 8211, "–" ],
47324 [ 8212, "—" ],
47332 var output = input;
47333 Roo.each(swapCodes, function(sw) {
47334 var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
47336 output = output.replace(swapper, sw[1]);
47346 cleanUpChild : function (node)
47349 new Roo.htmleditor.FilterComment({node : node});
47350 new Roo.htmleditor.FilterAttributes({
47352 attrib_black : this.ablack,
47353 attrib_clean : this.aclean,
47354 style_white : this.cwhite,
47355 style_black : this.cblack
47357 new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
47358 new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
47364 * Clean up MS wordisms...
47365 * @deprecated - use filter directly
47367 cleanWord : function(node)
47369 new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
47376 * @deprecated - use filters
47378 cleanTableWidths : function(node)
47380 new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
47387 applyBlacklists : function()
47389 var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white : [];
47390 var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black : [];
47392 this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean : Roo.HtmlEditorCore.aclean;
47393 this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack : Roo.HtmlEditorCore.ablack;
47394 this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove : Roo.HtmlEditorCore.tag_remove;
47398 Roo.each(Roo.HtmlEditorCore.white, function(tag) {
47399 if (b.indexOf(tag) > -1) {
47402 this.white.push(tag);
47406 Roo.each(w, function(tag) {
47407 if (b.indexOf(tag) > -1) {
47410 if (this.white.indexOf(tag) > -1) {
47413 this.white.push(tag);
47418 Roo.each(Roo.HtmlEditorCore.black, function(tag) {
47419 if (w.indexOf(tag) > -1) {
47422 this.black.push(tag);
47426 Roo.each(b, function(tag) {
47427 if (w.indexOf(tag) > -1) {
47430 if (this.black.indexOf(tag) > -1) {
47433 this.black.push(tag);
47438 w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite : [];
47439 b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack : [];
47443 Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
47444 if (b.indexOf(tag) > -1) {
47447 this.cwhite.push(tag);
47451 Roo.each(w, function(tag) {
47452 if (b.indexOf(tag) > -1) {
47455 if (this.cwhite.indexOf(tag) > -1) {
47458 this.cwhite.push(tag);
47463 Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
47464 if (w.indexOf(tag) > -1) {
47467 this.cblack.push(tag);
47471 Roo.each(b, function(tag) {
47472 if (w.indexOf(tag) > -1) {
47475 if (this.cblack.indexOf(tag) > -1) {
47478 this.cblack.push(tag);
47483 setStylesheets : function(stylesheets)
47485 if(typeof(stylesheets) == 'string'){
47486 Roo.get(this.iframe.contentDocument.head).createChild({
47488 rel : 'stylesheet',
47497 Roo.each(stylesheets, function(s) {
47502 Roo.get(_this.iframe.contentDocument.head).createChild({
47504 rel : 'stylesheet',
47513 removeStylesheets : function()
47517 Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
47522 setStyle : function(style)
47524 Roo.get(this.iframe.contentDocument.head).createChild({
47533 // hide stuff that is not compatible
47547 * @event specialkey
47551 * @cfg {String} fieldClass @hide
47554 * @cfg {String} focusClass @hide
47557 * @cfg {String} autoCreate @hide
47560 * @cfg {String} inputType @hide
47563 * @cfg {String} invalidClass @hide
47566 * @cfg {String} invalidText @hide
47569 * @cfg {String} msgFx @hide
47572 * @cfg {String} validateOnBlur @hide
47576 Roo.HtmlEditorCore.white = [
47577 'AREA', 'BR', 'IMG', 'INPUT', 'HR', 'WBR',
47579 'ADDRESS', 'BLOCKQUOTE', 'CENTER', 'DD', 'DIR', 'DIV',
47580 'DL', 'DT', 'H1', 'H2', 'H3', 'H4',
47581 'H5', 'H6', 'HR', 'ISINDEX', 'LISTING', 'MARQUEE',
47582 'MENU', 'MULTICOL', 'OL', 'P', 'PLAINTEXT', 'PRE',
47583 'TABLE', 'UL', 'XMP',
47585 'CAPTION', 'COL', 'COLGROUP', 'TBODY', 'TD', 'TFOOT', 'TH',
47588 'DIR', 'MENU', 'OL', 'UL', 'DL',
47594 Roo.HtmlEditorCore.black = [
47595 // 'embed', 'object', // enable - backend responsiblity to clean thiese
47597 'BASE', 'BASEFONT', 'BGSOUND', 'BLINK', 'BODY',
47598 'FRAME', 'FRAMESET', 'HEAD', 'HTML', 'ILAYER',
47599 'IFRAME', 'LAYER', 'LINK', 'META', 'OBJECT',
47600 'SCRIPT', 'STYLE' ,'TITLE', 'XML',
47601 //'FONT' // CLEAN LATER..
47602 'COLGROUP', 'COL' // messy tables.
47605 Roo.HtmlEditorCore.clean = [ // ?? needed???
47606 'SCRIPT', 'STYLE', 'TITLE', 'XML'
47608 Roo.HtmlEditorCore.tag_remove = [
47613 Roo.HtmlEditorCore.ablack = [
47617 Roo.HtmlEditorCore.aclean = [
47618 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
47622 Roo.HtmlEditorCore.pwhite= [
47623 'http', 'https', 'mailto'
47626 // white listed style attributes.
47627 Roo.HtmlEditorCore.cwhite= [
47628 // 'text-align', /// default is to allow most things..
47634 // black listed style attributes.
47635 Roo.HtmlEditorCore.cblack= [
47636 // 'font-size' -- this can be set by the project
47642 //<script type="text/javascript">
47645 * Ext JS Library 1.1.1
47646 * Copyright(c) 2006-2007, Ext JS, LLC.
47652 Roo.form.HtmlEditor = function(config){
47656 Roo.form.HtmlEditor.superclass.constructor.call(this, config);
47658 if (!this.toolbars) {
47659 this.toolbars = [];
47661 this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
47667 * @class Roo.form.HtmlEditor
47668 * @extends Roo.form.Field
47669 * Provides a lightweight HTML Editor component.
47671 * This has been tested on Fireforx / Chrome.. IE may not be so great..
47673 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
47674 * supported by this editor.</b><br/><br/>
47675 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
47676 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
47678 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
47680 * @cfg {Boolean} clearUp
47684 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
47689 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
47694 * @cfg {Number} height (in pixels)
47698 * @cfg {Number} width (in pixels)
47703 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea rootURL + '/roojs1/css/undoreset.css', .
47706 stylesheets: false,
47710 * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
47715 * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
47721 * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
47726 * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
47731 * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
47733 allowComments: false,
47735 * @cfg {string} bodyCls- default '' default classes to add to body of editable area - usually undoreset is a good start..
47744 // private properties
47745 validationEvent : false,
47747 initialized : false,
47750 onFocus : Roo.emptyFn,
47752 hideMode:'offsets',
47754 actionMode : 'container', // defaults to hiding it...
47756 defaultAutoCreate : { // modified by initCompnoent..
47758 style:"width:500px;height:300px;",
47759 autocomplete: "new-password"
47763 initComponent : function(){
47766 * @event initialize
47767 * Fires when the editor is fully initialized (including the iframe)
47768 * @param {HtmlEditor} this
47773 * Fires when the editor is first receives the focus. Any insertion must wait
47774 * until after this event.
47775 * @param {HtmlEditor} this
47779 * @event beforesync
47780 * Fires before the textarea is updated with content from the editor iframe. Return false
47781 * to cancel the sync.
47782 * @param {HtmlEditor} this
47783 * @param {String} html
47787 * @event beforepush
47788 * Fires before the iframe editor is updated with content from the textarea. Return false
47789 * to cancel the push.
47790 * @param {HtmlEditor} this
47791 * @param {String} html
47796 * Fires when the textarea is updated with content from the editor iframe.
47797 * @param {HtmlEditor} this
47798 * @param {String} html
47803 * Fires when the iframe editor is updated with content from the textarea.
47804 * @param {HtmlEditor} this
47805 * @param {String} html
47809 * @event editmodechange
47810 * Fires when the editor switches edit modes
47811 * @param {HtmlEditor} this
47812 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
47814 editmodechange: true,
47816 * @event editorevent
47817 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
47818 * @param {HtmlEditor} this
47822 * @event firstfocus
47823 * Fires when on first focus - needed by toolbars..
47824 * @param {HtmlEditor} this
47829 * Auto save the htmlEditor value as a file into Events
47830 * @param {HtmlEditor} this
47834 * @event savedpreview
47835 * preview the saved version of htmlEditor
47836 * @param {HtmlEditor} this
47838 savedpreview: true,
47841 * @event stylesheetsclick
47842 * Fires when press the Sytlesheets button
47843 * @param {Roo.HtmlEditorCore} this
47845 stylesheetsclick: true,
47848 * Fires when press user pastes into the editor
47849 * @param {Roo.HtmlEditorCore} this
47853 this.defaultAutoCreate = {
47855 style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
47856 autocomplete: "new-password"
47861 * Protected method that will not generally be called directly. It
47862 * is called when the editor creates its toolbar. Override this method if you need to
47863 * add custom toolbar buttons.
47864 * @param {HtmlEditor} editor
47866 createToolbar : function(editor){
47867 Roo.log("create toolbars");
47868 if (!editor.toolbars || !editor.toolbars.length) {
47869 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
47872 for (var i =0 ; i < editor.toolbars.length;i++) {
47873 editor.toolbars[i] = Roo.factory(
47874 typeof(editor.toolbars[i]) == 'string' ?
47875 { xtype: editor.toolbars[i]} : editor.toolbars[i],
47876 Roo.form.HtmlEditor);
47877 editor.toolbars[i].init(editor);
47885 onRender : function(ct, position)
47888 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
47890 this.wrap = this.el.wrap({
47891 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
47894 this.editorcore.onRender(ct, position);
47896 if (this.resizable) {
47897 this.resizeEl = new Roo.Resizable(this.wrap, {
47901 minHeight : this.height,
47902 height: this.height,
47903 handles : this.resizable,
47906 resize : function(r, w, h) {
47907 _t.onResize(w,h); // -something
47913 this.createToolbar(this);
47917 this.setSize(this.wrap.getSize());
47919 if (this.resizeEl) {
47920 this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
47921 // should trigger onReize..
47924 this.keyNav = new Roo.KeyNav(this.el, {
47926 "tab" : function(e){
47927 e.preventDefault();
47929 var value = this.getValue();
47931 var start = this.el.dom.selectionStart;
47932 var end = this.el.dom.selectionEnd;
47936 this.setValue(value.substring(0, start) + "\t" + value.substring(end));
47937 this.el.dom.setSelectionRange(end + 1, end + 1);
47941 var f = value.substring(0, start).split("\t");
47943 if(f.pop().length != 0){
47947 this.setValue(f.join("\t") + value.substring(end));
47948 this.el.dom.setSelectionRange(start - 1, start - 1);
47952 "home" : function(e){
47953 e.preventDefault();
47955 var curr = this.el.dom.selectionStart;
47956 var lines = this.getValue().split("\n");
47963 this.el.dom.setSelectionRange(0, 0);
47969 for (var i = 0; i < lines.length;i++) {
47970 pos += lines[i].length;
47980 pos -= lines[i].length;
47986 this.el.dom.setSelectionRange(pos, pos);
47990 this.el.dom.selectionStart = pos;
47991 this.el.dom.selectionEnd = curr;
47994 "end" : function(e){
47995 e.preventDefault();
47997 var curr = this.el.dom.selectionStart;
47998 var lines = this.getValue().split("\n");
48005 this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
48011 for (var i = 0; i < lines.length;i++) {
48013 pos += lines[i].length;
48027 this.el.dom.setSelectionRange(pos, pos);
48031 this.el.dom.selectionStart = curr;
48032 this.el.dom.selectionEnd = pos;
48037 doRelay : function(foo, bar, hname){
48038 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
48044 // if(this.autosave && this.w){
48045 // this.autoSaveFn = setInterval(this.autosave, 1000);
48050 onResize : function(w, h)
48052 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
48057 if(typeof w == 'number'){
48058 var aw = w - this.wrap.getFrameWidth('lr');
48059 this.el.setWidth(this.adjustWidth('textarea', aw));
48062 if(typeof h == 'number'){
48064 for (var i =0; i < this.toolbars.length;i++) {
48065 // fixme - ask toolbars for heights?
48066 tbh += this.toolbars[i].tb.el.getHeight();
48067 if (this.toolbars[i].footer) {
48068 tbh += this.toolbars[i].footer.el.getHeight();
48075 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
48076 ah -= 5; // knock a few pixes off for look..
48078 this.el.setHeight(this.adjustWidth('textarea', ah));
48082 Roo.log('onResize:' + [w,h,ew,eh].join(',') );
48083 this.editorcore.onResize(ew,eh);
48088 * Toggles the editor between standard and source edit mode.
48089 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
48091 toggleSourceEdit : function(sourceEditMode)
48093 this.editorcore.toggleSourceEdit(sourceEditMode);
48095 if(this.editorcore.sourceEditMode){
48096 Roo.log('editor - showing textarea');
48099 // Roo.log(this.syncValue());
48100 this.editorcore.syncValue();
48101 this.el.removeClass('x-hidden');
48102 this.el.dom.removeAttribute('tabIndex');
48104 this.el.dom.scrollTop = 0;
48107 for (var i = 0; i < this.toolbars.length; i++) {
48108 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
48109 this.toolbars[i].tb.hide();
48110 this.toolbars[i].footer.hide();
48115 Roo.log('editor - hiding textarea');
48117 // Roo.log(this.pushValue());
48118 this.editorcore.pushValue();
48120 this.el.addClass('x-hidden');
48121 this.el.dom.setAttribute('tabIndex', -1);
48123 for (var i = 0; i < this.toolbars.length; i++) {
48124 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
48125 this.toolbars[i].tb.show();
48126 this.toolbars[i].footer.show();
48130 //this.deferFocus();
48133 this.setSize(this.wrap.getSize());
48134 this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
48136 this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
48139 // private (for BoxComponent)
48140 adjustSize : Roo.BoxComponent.prototype.adjustSize,
48142 // private (for BoxComponent)
48143 getResizeEl : function(){
48147 // private (for BoxComponent)
48148 getPositionEl : function(){
48153 initEvents : function(){
48154 this.originalValue = this.getValue();
48158 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
48161 markInvalid : Roo.emptyFn,
48163 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
48166 clearInvalid : Roo.emptyFn,
48168 setValue : function(v){
48169 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
48170 this.editorcore.pushValue();
48175 deferFocus : function(){
48176 this.focus.defer(10, this);
48180 focus : function(){
48181 this.editorcore.focus();
48187 onDestroy : function(){
48193 for (var i =0; i < this.toolbars.length;i++) {
48194 // fixme - ask toolbars for heights?
48195 this.toolbars[i].onDestroy();
48198 this.wrap.dom.innerHTML = '';
48199 this.wrap.remove();
48204 onFirstFocus : function(){
48205 //Roo.log("onFirstFocus");
48206 this.editorcore.onFirstFocus();
48207 for (var i =0; i < this.toolbars.length;i++) {
48208 this.toolbars[i].onFirstFocus();
48214 syncValue : function()
48216 this.editorcore.syncValue();
48219 pushValue : function()
48221 this.editorcore.pushValue();
48224 setStylesheets : function(stylesheets)
48226 this.editorcore.setStylesheets(stylesheets);
48229 removeStylesheets : function()
48231 this.editorcore.removeStylesheets();
48235 // hide stuff that is not compatible
48249 * @event specialkey
48253 * @cfg {String} fieldClass @hide
48256 * @cfg {String} focusClass @hide
48259 * @cfg {String} autoCreate @hide
48262 * @cfg {String} inputType @hide
48265 * @cfg {String} invalidClass @hide
48268 * @cfg {String} invalidText @hide
48271 * @cfg {String} msgFx @hide
48274 * @cfg {String} validateOnBlur @hide
48278 // <script type="text/javascript">
48281 * Ext JS Library 1.1.1
48282 * Copyright(c) 2006-2007, Ext JS, LLC.
48288 * @class Roo.form.HtmlEditorToolbar1
48293 new Roo.form.HtmlEditor({
48296 new Roo.form.HtmlEditorToolbar1({
48297 disable : { fonts: 1 , format: 1, ..., ... , ...],
48303 * @cfg {Object} disable List of elements to disable..
48304 * @cfg {Array} btns List of additional buttons.
48308 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
48311 Roo.form.HtmlEditor.ToolbarStandard = function(config)
48314 Roo.apply(this, config);
48316 // default disabled, based on 'good practice'..
48317 this.disable = this.disable || {};
48318 Roo.applyIf(this.disable, {
48321 specialElements : true
48325 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
48326 // dont call parent... till later.
48329 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype, {
48336 editorcore : false,
48338 * @cfg {Object} disable List of toolbar elements to disable
48345 * @cfg {String} createLinkText The default text for the create link prompt
48347 createLinkText : 'Please enter the URL for the link:',
48349 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
48351 defaultLinkValue : 'http:/'+'/',
48355 * @cfg {Array} fontFamilies An array of available font families
48373 // "á" , ?? a acute?
48378 "°" // , // degrees
48380 // "é" , // e ecute
48381 // "ú" , // u ecute?
48384 specialElements : [
48386 text: "Insert Table",
48389 ihtml : '<table><tr><td>Cell</td></tr></table>'
48393 text: "Insert Image",
48396 ihtml : '<img src="about:blank"/>'
48405 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
48406 "input:submit", "input:button", "select", "textarea", "label" ],
48409 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
48411 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
48420 * @cfg {String} defaultFont default font to use.
48422 defaultFont: 'tahoma',
48424 fontSelect : false,
48427 formatCombo : false,
48429 init : function(editor)
48431 this.editor = editor;
48432 this.editorcore = editor.editorcore ? editor.editorcore : editor;
48433 var editorcore = this.editorcore;
48437 var fid = editorcore.frameId;
48439 function btn(id, toggle, handler){
48440 var xid = fid + '-'+ id ;
48444 cls : 'x-btn-icon x-edit-'+id,
48445 enableToggle:toggle !== false,
48446 scope: _t, // was editor...
48447 handler:handler||_t.relayBtnCmd,
48448 clickEvent:'mousedown',
48449 tooltip: etb.buttonTips[id] || undefined, ///tips ???
48456 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
48458 // stop form submits
48459 tb.el.on('click', function(e){
48460 e.preventDefault(); // what does this do?
48463 if(!this.disable.font) { // && !Roo.isSafari){
48464 /* why no safari for fonts
48465 editor.fontSelect = tb.el.createChild({
48468 cls:'x-font-select',
48469 html: this.createFontOptions()
48472 editor.fontSelect.on('change', function(){
48473 var font = editor.fontSelect.dom.value;
48474 editor.relayCmd('fontname', font);
48475 editor.deferFocus();
48479 editor.fontSelect.dom,
48485 if(!this.disable.formats){
48486 this.formatCombo = new Roo.form.ComboBox({
48487 store: new Roo.data.SimpleStore({
48490 data : this.formats // from states.js
48494 //autoCreate : {tag: "div", size: "20"},
48495 displayField:'tag',
48499 triggerAction: 'all',
48500 emptyText:'Add tag',
48501 selectOnFocus:true,
48504 'select': function(c, r, i) {
48505 editorcore.insertTag(r.get('tag'));
48511 tb.addField(this.formatCombo);
48515 if(!this.disable.format){
48520 btn('strikethrough')
48523 if(!this.disable.fontSize){
48528 btn('increasefontsize', false, editorcore.adjustFont),
48529 btn('decreasefontsize', false, editorcore.adjustFont)
48534 if(!this.disable.colors){
48537 id:editorcore.frameId +'-forecolor',
48538 cls:'x-btn-icon x-edit-forecolor',
48539 clickEvent:'mousedown',
48540 tooltip: this.buttonTips['forecolor'] || undefined,
48542 menu : new Roo.menu.ColorMenu({
48543 allowReselect: true,
48544 focus: Roo.emptyFn,
48547 selectHandler: function(cp, color){
48548 editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
48549 editor.deferFocus();
48552 clickEvent:'mousedown'
48555 id:editorcore.frameId +'backcolor',
48556 cls:'x-btn-icon x-edit-backcolor',
48557 clickEvent:'mousedown',
48558 tooltip: this.buttonTips['backcolor'] || undefined,
48560 menu : new Roo.menu.ColorMenu({
48561 focus: Roo.emptyFn,
48564 allowReselect: true,
48565 selectHandler: function(cp, color){
48567 editorcore.execCmd('useCSS', false);
48568 editorcore.execCmd('hilitecolor', color);
48569 editorcore.execCmd('useCSS', true);
48570 editor.deferFocus();
48572 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
48573 Roo.isSafari || Roo.isIE ? '#'+color : color);
48574 editor.deferFocus();
48578 clickEvent:'mousedown'
48583 // now add all the items...
48586 if(!this.disable.alignments){
48589 btn('justifyleft'),
48590 btn('justifycenter'),
48591 btn('justifyright')
48595 //if(!Roo.isSafari){
48596 if(!this.disable.links){
48599 btn('createlink', false, this.createLink) /// MOVE TO HERE?!!?!?!?!
48603 if(!this.disable.lists){
48606 btn('insertorderedlist'),
48607 btn('insertunorderedlist')
48610 if(!this.disable.sourceEdit){
48613 btn('sourceedit', true, function(btn){
48614 this.toggleSourceEdit(btn.pressed);
48621 // special menu.. - needs to be tidied up..
48622 if (!this.disable.special) {
48625 cls: 'x-edit-none',
48631 for (var i =0; i < this.specialChars.length; i++) {
48632 smenu.menu.items.push({
48634 html: this.specialChars[i],
48635 handler: function(a,b) {
48636 editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
48637 //editor.insertAtCursor(a.html);
48651 if (!this.disable.cleanStyles) {
48653 cls: 'x-btn-icon x-btn-clear',
48659 for (var i =0; i < this.cleanStyles.length; i++) {
48660 cmenu.menu.items.push({
48661 actiontype : this.cleanStyles[i],
48662 html: 'Remove ' + this.cleanStyles[i],
48663 handler: function(a,b) {
48666 var c = Roo.get(editorcore.doc.body);
48667 c.select('[style]').each(function(s) {
48668 s.dom.style.removeProperty(a.actiontype);
48670 editorcore.syncValue();
48675 cmenu.menu.items.push({
48676 actiontype : 'tablewidths',
48677 html: 'Remove Table Widths',
48678 handler: function(a,b) {
48679 editorcore.cleanTableWidths();
48680 editorcore.syncValue();
48684 cmenu.menu.items.push({
48685 actiontype : 'word',
48686 html: 'Remove MS Word Formating',
48687 handler: function(a,b) {
48688 editorcore.cleanWord();
48689 editorcore.syncValue();
48694 cmenu.menu.items.push({
48695 actiontype : 'all',
48696 html: 'Remove All Styles',
48697 handler: function(a,b) {
48699 var c = Roo.get(editorcore.doc.body);
48700 c.select('[style]').each(function(s) {
48701 s.dom.removeAttribute('style');
48703 editorcore.syncValue();
48708 cmenu.menu.items.push({
48709 actiontype : 'all',
48710 html: 'Remove All CSS Classes',
48711 handler: function(a,b) {
48713 var c = Roo.get(editorcore.doc.body);
48714 c.select('[class]').each(function(s) {
48715 s.dom.removeAttribute('class');
48717 editorcore.cleanWord();
48718 editorcore.syncValue();
48723 cmenu.menu.items.push({
48724 actiontype : 'tidy',
48725 html: 'Tidy HTML Source',
48726 handler: function(a,b) {
48727 new Roo.htmleditor.Tidy(editorcore.doc.body);
48728 editorcore.syncValue();
48737 if (!this.disable.specialElements) {
48740 cls: 'x-edit-none',
48745 for (var i =0; i < this.specialElements.length; i++) {
48746 semenu.menu.items.push(
48748 handler: function(a,b) {
48749 editor.insertAtCursor(this.ihtml);
48751 }, this.specialElements[i])
48763 for(var i =0; i< this.btns.length;i++) {
48764 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
48765 b.cls = 'x-edit-none';
48767 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
48768 b.cls += ' x-init-enable';
48771 b.scope = editorcore;
48779 // disable everything...
48781 this.tb.items.each(function(item){
48784 item.id != editorcore.frameId+ '-sourceedit' &&
48785 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
48791 this.rendered = true;
48793 // the all the btns;
48794 editor.on('editorevent', this.updateToolbar, this);
48795 // other toolbars need to implement this..
48796 //editor.on('editmodechange', this.updateToolbar, this);
48800 relayBtnCmd : function(btn) {
48801 this.editorcore.relayCmd(btn.cmd);
48803 // private used internally
48804 createLink : function(){
48805 Roo.log("create link?");
48806 var url = prompt(this.createLinkText, this.defaultLinkValue);
48807 if(url && url != 'http:/'+'/'){
48808 this.editorcore.relayCmd('createlink', url);
48814 * Protected method that will not generally be called directly. It triggers
48815 * a toolbar update by reading the markup state of the current selection in the editor.
48817 updateToolbar: function(){
48819 if(!this.editorcore.activated){
48820 this.editor.onFirstFocus();
48824 var btns = this.tb.items.map,
48825 doc = this.editorcore.doc,
48826 frameId = this.editorcore.frameId;
48828 if(!this.disable.font && !Roo.isSafari){
48830 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
48831 if(name != this.fontSelect.dom.value){
48832 this.fontSelect.dom.value = name;
48836 if(!this.disable.format){
48837 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
48838 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
48839 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
48840 btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
48842 if(!this.disable.alignments){
48843 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
48844 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
48845 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
48847 if(!Roo.isSafari && !this.disable.lists){
48848 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
48849 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
48852 var ans = this.editorcore.getAllAncestors();
48853 if (this.formatCombo) {
48856 var store = this.formatCombo.store;
48857 this.formatCombo.setValue("");
48858 for (var i =0; i < ans.length;i++) {
48859 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
48861 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
48869 // hides menus... - so this cant be on a menu...
48870 Roo.menu.MenuMgr.hideAll();
48872 //this.editorsyncValue();
48876 createFontOptions : function(){
48877 var buf = [], fs = this.fontFamilies, ff, lc;
48881 for(var i = 0, len = fs.length; i< len; i++){
48883 lc = ff.toLowerCase();
48885 '<option value="',lc,'" style="font-family:',ff,';"',
48886 (this.defaultFont == lc ? ' selected="true">' : '>'),
48891 return buf.join('');
48894 toggleSourceEdit : function(sourceEditMode){
48896 Roo.log("toolbar toogle");
48897 if(sourceEditMode === undefined){
48898 sourceEditMode = !this.sourceEditMode;
48900 this.sourceEditMode = sourceEditMode === true;
48901 var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
48902 // just toggle the button?
48903 if(btn.pressed !== this.sourceEditMode){
48904 btn.toggle(this.sourceEditMode);
48908 if(sourceEditMode){
48909 Roo.log("disabling buttons");
48910 this.tb.items.each(function(item){
48911 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
48917 Roo.log("enabling buttons");
48918 if(this.editorcore.initialized){
48919 this.tb.items.each(function(item){
48925 Roo.log("calling toggole on editor");
48926 // tell the editor that it's been pressed..
48927 this.editor.toggleSourceEdit(sourceEditMode);
48931 * Object collection of toolbar tooltips for the buttons in the editor. The key
48932 * is the command id associated with that button and the value is a valid QuickTips object.
48937 title: 'Bold (Ctrl+B)',
48938 text: 'Make the selected text bold.',
48939 cls: 'x-html-editor-tip'
48942 title: 'Italic (Ctrl+I)',
48943 text: 'Make the selected text italic.',
48944 cls: 'x-html-editor-tip'
48952 title: 'Bold (Ctrl+B)',
48953 text: 'Make the selected text bold.',
48954 cls: 'x-html-editor-tip'
48957 title: 'Italic (Ctrl+I)',
48958 text: 'Make the selected text italic.',
48959 cls: 'x-html-editor-tip'
48962 title: 'Underline (Ctrl+U)',
48963 text: 'Underline the selected text.',
48964 cls: 'x-html-editor-tip'
48967 title: 'Strikethrough',
48968 text: 'Strikethrough the selected text.',
48969 cls: 'x-html-editor-tip'
48971 increasefontsize : {
48972 title: 'Grow Text',
48973 text: 'Increase the font size.',
48974 cls: 'x-html-editor-tip'
48976 decreasefontsize : {
48977 title: 'Shrink Text',
48978 text: 'Decrease the font size.',
48979 cls: 'x-html-editor-tip'
48982 title: 'Text Highlight Color',
48983 text: 'Change the background color of the selected text.',
48984 cls: 'x-html-editor-tip'
48987 title: 'Font Color',
48988 text: 'Change the color of the selected text.',
48989 cls: 'x-html-editor-tip'
48992 title: 'Align Text Left',
48993 text: 'Align text to the left.',
48994 cls: 'x-html-editor-tip'
48997 title: 'Center Text',
48998 text: 'Center text in the editor.',
48999 cls: 'x-html-editor-tip'
49002 title: 'Align Text Right',
49003 text: 'Align text to the right.',
49004 cls: 'x-html-editor-tip'
49006 insertunorderedlist : {
49007 title: 'Bullet List',
49008 text: 'Start a bulleted list.',
49009 cls: 'x-html-editor-tip'
49011 insertorderedlist : {
49012 title: 'Numbered List',
49013 text: 'Start a numbered list.',
49014 cls: 'x-html-editor-tip'
49017 title: 'Hyperlink',
49018 text: 'Make the selected text a hyperlink.',
49019 cls: 'x-html-editor-tip'
49022 title: 'Source Edit',
49023 text: 'Switch to source editing mode.',
49024 cls: 'x-html-editor-tip'
49028 onDestroy : function(){
49031 this.tb.items.each(function(item){
49033 item.menu.removeAll();
49035 item.menu.el.destroy();
49043 onFirstFocus: function() {
49044 this.tb.items.each(function(item){
49053 // <script type="text/javascript">
49056 * Ext JS Library 1.1.1
49057 * Copyright(c) 2006-2007, Ext JS, LLC.
49064 * @class Roo.form.HtmlEditor.ToolbarContext
49069 new Roo.form.HtmlEditor({
49072 { xtype: 'ToolbarStandard', styles : {} }
49073 { xtype: 'ToolbarContext', disable : {} }
49079 * @config : {Object} disable List of elements to disable.. (not done yet.)
49080 * @config : {Object} styles Map of styles available.
49084 Roo.form.HtmlEditor.ToolbarContext = function(config)
49087 Roo.apply(this, config);
49088 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
49089 // dont call parent... till later.
49090 this.styles = this.styles || {};
49095 Roo.form.HtmlEditor.ToolbarContext.types = {
49107 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
49129 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
49182 opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
49187 opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
49197 style : 'fontFamily',
49198 displayField: 'display',
49199 optname : 'font-family',
49249 // should we really allow this??
49250 // should this just be
49262 style : 'fontFamily',
49263 displayField: 'display',
49264 optname : 'font-family',
49271 style : 'fontFamily',
49272 displayField: 'display',
49273 optname : 'font-family',
49280 style : 'fontFamily',
49281 displayField: 'display',
49282 optname : 'font-family',
49293 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
49294 Roo.form.HtmlEditor.ToolbarContext.stores = false;
49296 Roo.form.HtmlEditor.ToolbarContext.options = {
49298 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
49299 [ 'Courier New', 'Courier New'],
49300 [ 'Tahoma', 'Tahoma'],
49301 [ 'Times New Roman,serif', 'Times'],
49302 [ 'Verdana','Verdana' ]
49306 // fixme - these need to be configurable..
49309 //Roo.form.HtmlEditor.ToolbarContext.types
49312 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
49319 editorcore : false,
49321 * @cfg {Object} disable List of toolbar elements to disable
49326 * @cfg {Object} styles List of styles
49327 * eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] }
49329 * These must be defined in the page, so they get rendered correctly..
49340 init : function(editor)
49342 this.editor = editor;
49343 this.editorcore = editor.editorcore ? editor.editorcore : editor;
49344 var editorcore = this.editorcore;
49346 var fid = editorcore.frameId;
49348 function btn(id, toggle, handler){
49349 var xid = fid + '-'+ id ;
49353 cls : 'x-btn-icon x-edit-'+id,
49354 enableToggle:toggle !== false,
49355 scope: editorcore, // was editor...
49356 handler:handler||editorcore.relayBtnCmd,
49357 clickEvent:'mousedown',
49358 tooltip: etb.buttonTips[id] || undefined, ///tips ???
49362 // create a new element.
49363 var wdiv = editor.wrap.createChild({
49365 }, editor.wrap.dom.firstChild.nextSibling, true);
49367 // can we do this more than once??
49369 // stop form submits
49372 // disable everything...
49373 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
49374 this.toolbars = {};
49376 for (var i in ty) {
49378 this.toolbars[i] = this.buildToolbar(ty[i],i);
49380 this.tb = this.toolbars.BODY;
49382 this.buildFooter();
49383 this.footer.show();
49384 editor.on('hide', function( ) { this.footer.hide() }, this);
49385 editor.on('show', function( ) { this.footer.show() }, this);
49388 this.rendered = true;
49390 // the all the btns;
49391 editor.on('editorevent', this.updateToolbar, this);
49392 // other toolbars need to implement this..
49393 //editor.on('editmodechange', this.updateToolbar, this);
49399 * Protected method that will not generally be called directly. It triggers
49400 * a toolbar update by reading the markup state of the current selection in the editor.
49402 * Note you can force an update by calling on('editorevent', scope, false)
49404 updateToolbar: function(editor ,ev, sel)
49408 ev.stopEvent(); // se if we can stop this looping with mutiple events.
49412 // capture mouse up - this is handy for selecting images..
49413 // perhaps should go somewhere else...
49414 if(!this.editorcore.activated){
49415 this.editor.onFirstFocus();
49418 Roo.log(ev ? ev.target : 'NOTARGET');
49421 // http://developer.yahoo.com/yui/docs/simple-editor.js.html
49422 // selectNode - might want to handle IE?
49427 (ev.type == 'mouseup' || ev.type == 'click' ) &&
49428 ev.target && ev.target != 'BODY' ) { // && ev.target.tagName == 'IMG') {
49429 // they have click on an image...
49430 // let's see if we can change the selection...
49433 // this triggers looping?
49434 //this.editorcore.selectNode(sel);
49439 //var updateFooter = sel ? false : true;
49442 var ans = this.editorcore.getAllAncestors();
49445 var ty = Roo.form.HtmlEditor.ToolbarContext.types;
49448 sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editorcore.doc.body;
49449 sel = sel ? sel : this.editorcore.doc.body;
49450 sel = sel.tagName.length ? sel : this.editorcore.doc.body;
49454 var tn = sel.tagName.toUpperCase();
49455 var lastSel = this.tb.selectedNode;
49456 this.tb.selectedNode = sel;
49457 var left_label = tn;
49459 // ok see if we are editing a block?
49460 var sel_el = Roo.get(sel);
49462 // you are not actually selecting the block.
49463 if (sel && sel.hasAttribute('data-block')) {
49465 } else if (sel && !sel.hasAttribute('contenteditable')) {
49466 db = sel_el.findParent('[data-block]');
49467 var cepar = sel_el.findParent('[contenteditable=true]');
49468 if (db && cepar && cepar.tagName != 'BODY') {
49469 db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
49475 //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
49477 block = Roo.htmleditor.Block.factory(db);
49479 tn = 'BLOCK.' + db.getAttribute('data-block');
49481 //this.editorcore.selectNode(db);
49482 if (typeof(this.toolbars[tn]) == 'undefined') {
49483 this.toolbars[tn] = this.buildToolbar( false ,tn ,block.friendly_name, block);
49485 this.toolbars[tn].selectedNode = db;
49486 left_label = block.friendly_name;
49487 ans = this.editorcore.getAllAncestors();
49495 if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
49496 return; // no change?
49502 ///console.log("show: " + tn);
49503 this.tb = typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
49507 this.tb.items.first().el.innerHTML = left_label + ': ';
49510 // update attributes
49513 this.tb.fields.each(function(e) {
49514 e.setValue(block[e.name]);
49518 } else if (this.tb.fields && this.tb.selectedNode) {
49519 this.tb.fields.each( function(e) {
49521 e.setValue(this.tb.selectedNode.style[e.stylename]);
49524 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
49526 this.updateToolbarStyles(this.tb.selectedNode);
49531 Roo.menu.MenuMgr.hideAll();
49536 // update the footer
49538 this.updateFooter(ans);
49542 updateToolbarStyles : function(sel)
49544 var hasStyles = false;
49545 for(var i in this.styles) {
49551 if (hasStyles && this.tb.hasStyles) {
49552 var st = this.tb.fields.item(0);
49554 st.store.removeAll();
49555 var cn = sel.className.split(/\s+/);
49558 if (this.styles['*']) {
49560 Roo.each(this.styles['*'], function(v) {
49561 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
49564 if (this.styles[tn]) {
49565 Roo.each(this.styles[tn], function(v) {
49566 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
49570 st.store.loadData(avs);
49577 updateFooter : function(ans)
49580 if (ans === false) {
49581 this.footDisp.dom.innerHTML = '';
49585 this.footerEls = ans.reverse();
49586 Roo.each(this.footerEls, function(a,i) {
49587 if (!a) { return; }
49588 html += html.length ? ' > ' : '';
49590 html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
49595 var sz = this.footDisp.up('td').getSize();
49596 this.footDisp.dom.style.width = (sz.width -10) + 'px';
49597 this.footDisp.dom.style.marginLeft = '5px';
49599 this.footDisp.dom.style.overflow = 'hidden';
49601 this.footDisp.dom.innerHTML = html;
49608 onDestroy : function(){
49611 this.tb.items.each(function(item){
49613 item.menu.removeAll();
49615 item.menu.el.destroy();
49623 onFirstFocus: function() {
49624 // need to do this for all the toolbars..
49625 this.tb.items.each(function(item){
49629 buildToolbar: function(tlist, nm, friendly_name, block)
49631 var editor = this.editor;
49632 var editorcore = this.editorcore;
49633 // create a new element.
49634 var wdiv = editor.wrap.createChild({
49636 }, editor.wrap.dom.firstChild.nextSibling, true);
49639 var tb = new Roo.Toolbar(wdiv);
49641 if (tlist === false && block) {
49642 tlist = block.contextMenu(this);
49645 tb.hasStyles = false;
49648 tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ": ");
49650 var styles = Array.from(this.styles);
49654 if (styles && styles.length) {
49655 tb.hasStyles = true;
49656 // this needs a multi-select checkbox...
49657 tb.addField( new Roo.form.ComboBox({
49658 store: new Roo.data.SimpleStore({
49660 fields: ['val', 'selected'],
49663 name : '-roo-edit-className',
49664 attrname : 'className',
49665 displayField: 'val',
49669 triggerAction: 'all',
49670 emptyText:'Select Style',
49671 selectOnFocus:true,
49674 'select': function(c, r, i) {
49675 // initial support only for on class per el..
49676 tb.selectedNode.className = r ? r.get('val') : '';
49677 editorcore.syncValue();
49684 var tbc = Roo.form.HtmlEditor.ToolbarContext;
49687 for (var i in tlist) {
49689 // newer versions will use xtype cfg to create menus.
49690 if (typeof(tlist[i].xtype) != 'undefined') {
49692 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
49698 var item = tlist[i];
49699 tb.add(item.title + ": ");
49702 //optname == used so you can configure the options available..
49703 var opts = item.opts ? item.opts : false;
49704 if (item.optname) { // use the b
49705 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
49710 // opts == pulldown..
49711 tb.addField( new Roo.form.ComboBox({
49712 store: typeof(tbc.stores[i]) != 'undefined' ? Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
49714 fields: ['val', 'display'],
49717 name : '-roo-edit-' + i,
49720 stylename : item.style ? item.style : false,
49722 displayField: item.displayField ? item.displayField : 'val',
49723 valueField : 'val',
49725 mode: typeof(tbc.stores[i]) != 'undefined' ? 'remote' : 'local',
49727 triggerAction: 'all',
49728 emptyText:'Select',
49729 selectOnFocus:true,
49730 width: item.width ? item.width : 130,
49732 'select': function(c, r, i) {
49733 if (tb.selectedNode.hasAttribute('data-block')) {
49734 var b = Roo.htmleditor.Block.factory(tb.selectedNode);
49735 b[c.attrname] = r.get('val');
49736 b.updateElement(tb.selectedNode);
49737 editorcore.syncValue();
49742 tb.selectedNode.style[c.stylename] = r.get('val');
49743 editorcore.syncValue();
49747 tb.selectedNode.removeAttribute(c.attrname);
49748 editorcore.syncValue();
49751 tb.selectedNode.setAttribute(c.attrname, r.get('val'));
49752 editorcore.syncValue();
49761 tb.addField( new Roo.form.TextField({
49764 //allowBlank:false,
49770 tb.addField( new Roo.form.TextField({
49771 name: '-roo-edit-' + i,
49778 'change' : function(f, nv, ov) {
49780 if (tb.selectedNode.hasAttribute('data-block')) {
49781 var b = Roo.htmleditor.Block.factory(tb.selectedNode);
49782 b[f.attrname] = nv;
49783 b.updateElement(tb.selectedNode);
49784 editorcore.syncValue();
49788 tb.selectedNode.setAttribute(f.attrname, nv);
49789 editorcore.syncValue();
49802 text: 'Stylesheets',
49805 click : function ()
49807 _this.editor.fireEvent('stylesheetsclick', _this.editor);
49815 text: 'Remove Block or Formating', // remove the tag, and puts the children outside...
49818 click : function ()
49821 // undo does not work.
49822 var sn = tb.selectedNode;
49826 var stn = sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
49827 if (sn.hasAttribute('data-block')) {
49828 stn = sn.nextSibling || sn.previousSibling || sn.parentNode;
49829 sn.parentNode.removeChild(sn);
49831 } else if (sn && sn.tagName != 'BODY') {
49832 // remove and keep parents.
49833 a = new Roo.htmleditor.FilterKeepChildren({tag : false});
49838 var range = editorcore.createRange();
49840 range.setStart(stn,0);
49841 range.setEnd(stn,0);
49842 var selection = editorcore.getSelection();
49843 selection.removeAllRanges();
49844 selection.addRange(range);
49847 //_this.updateToolbar(null, null, pn);
49848 _this.updateToolbar(null, null, null);
49849 _this.updateFooter(false);
49860 tb.el.on('click', function(e){
49861 e.preventDefault(); // what does this do?
49863 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
49866 // dont need to disable them... as they will get hidden
49871 buildFooter : function()
49874 var fel = this.editor.wrap.createChild();
49875 this.footer = new Roo.Toolbar(fel);
49876 // toolbar has scrolly on left / right?
49877 var footDisp= new Roo.Toolbar.Fill();
49883 handler : function() {
49884 _t.footDisp.scrollTo('left',0,true)
49888 this.footer.add( footDisp );
49893 handler : function() {
49895 _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
49899 var fel = Roo.get(footDisp.el);
49900 fel.addClass('x-editor-context');
49901 this.footDispWrap = fel;
49902 this.footDispWrap.overflow = 'hidden';
49904 this.footDisp = fel.createChild();
49905 this.footDispWrap.on('click', this.onContextClick, this)
49909 // when the footer contect changes
49910 onContextClick : function (ev,dom)
49912 ev.preventDefault();
49913 var cn = dom.className;
49915 if (!cn.match(/x-ed-loc-/)) {
49918 var n = cn.split('-').pop();
49919 var ans = this.footerEls;
49923 var range = this.editorcore.createRange();
49925 range.selectNodeContents(sel);
49926 //range.selectNode(sel);
49929 var selection = this.editorcore.getSelection();
49930 selection.removeAllRanges();
49931 selection.addRange(range);
49935 this.updateToolbar(null, null, sel);
49952 * Ext JS Library 1.1.1
49953 * Copyright(c) 2006-2007, Ext JS, LLC.
49955 * Originally Released Under LGPL - original licence link has changed is not relivant.
49958 * <script type="text/javascript">
49962 * @class Roo.form.BasicForm
49963 * @extends Roo.util.Observable
49964 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
49966 * @param {String/HTMLElement/Roo.Element} el The form element or its id
49967 * @param {Object} config Configuration options
49969 Roo.form.BasicForm = function(el, config){
49970 this.allItems = [];
49971 this.childForms = [];
49972 Roo.apply(this, config);
49974 * The Roo.form.Field items in this form.
49975 * @type MixedCollection
49979 this.items = new Roo.util.MixedCollection(false, function(o){
49980 return o.id || (o.id = Roo.id());
49984 * @event beforeaction
49985 * Fires before any action is performed. Return false to cancel the action.
49986 * @param {Form} this
49987 * @param {Action} action The action to be performed
49989 beforeaction: true,
49991 * @event actionfailed
49992 * Fires when an action fails.
49993 * @param {Form} this
49994 * @param {Action} action The action that failed
49996 actionfailed : true,
49998 * @event actioncomplete
49999 * Fires when an action is completed.
50000 * @param {Form} this
50001 * @param {Action} action The action that completed
50003 actioncomplete : true
50008 Roo.form.BasicForm.superclass.constructor.call(this);
50010 Roo.form.BasicForm.popover.apply();
50013 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
50015 * @cfg {String} method
50016 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
50019 * @cfg {DataReader} reader
50020 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
50021 * This is optional as there is built-in support for processing JSON.
50024 * @cfg {DataReader} errorReader
50025 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
50026 * This is completely optional as there is built-in support for processing JSON.
50029 * @cfg {String} url
50030 * The URL to use for form actions if one isn't supplied in the action options.
50033 * @cfg {Boolean} fileUpload
50034 * Set to true if this form is a file upload.
50038 * @cfg {Object} baseParams
50039 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
50044 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
50049 activeAction : null,
50052 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
50053 * or setValues() data instead of when the form was first created.
50055 trackResetOnLoad : false,
50059 * childForms - used for multi-tab forms
50062 childForms : false,
50065 * allItems - full list of fields.
50071 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
50072 * element by passing it or its id or mask the form itself by passing in true.
50075 waitMsgTarget : false,
50080 disableMask : false,
50083 * @cfg {Boolean} errorMask (true|false) default false
50088 * @cfg {Number} maskOffset Default 100
50093 initEl : function(el){
50094 this.el = Roo.get(el);
50095 this.id = this.el.id || Roo.id();
50096 this.el.on('submit', this.onSubmit, this);
50097 this.el.addClass('x-form');
50101 onSubmit : function(e){
50106 * Returns true if client-side validation on the form is successful.
50109 isValid : function(){
50111 var target = false;
50112 this.items.each(function(f){
50119 if(!target && f.el.isVisible(true)){
50124 if(this.errorMask && !valid){
50125 Roo.form.BasicForm.popover.mask(this, target);
50131 * Returns array of invalid form fields.
50135 invalidFields : function()
50138 this.items.each(function(f){
50151 * DEPRICATED Returns true if any fields in this form have changed since their original load.
50154 isDirty : function(){
50156 this.items.each(function(f){
50166 * Returns true if any fields in this form have changed since their original load. (New version)
50170 hasChanged : function()
50173 this.items.each(function(f){
50174 if(f.hasChanged()){
50183 * Resets all hasChanged to 'false' -
50184 * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
50185 * So hasChanged storage is only to be used for this purpose
50188 resetHasChanged : function()
50190 this.items.each(function(f){
50191 f.resetHasChanged();
50198 * Performs a predefined action (submit or load) or custom actions you define on this form.
50199 * @param {String} actionName The name of the action type
50200 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
50201 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
50202 * accept other config options):
50204 Property Type Description
50205 ---------------- --------------- ----------------------------------------------------------------------------------
50206 url String The url for the action (defaults to the form's url)
50207 method String The form method to use (defaults to the form's method, or POST if not defined)
50208 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
50209 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
50210 validate the form on the client (defaults to false)
50212 * @return {BasicForm} this
50214 doAction : function(action, options){
50215 if(typeof action == 'string'){
50216 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
50218 if(this.fireEvent('beforeaction', this, action) !== false){
50219 this.beforeAction(action);
50220 action.run.defer(100, action);
50226 * Shortcut to do a submit action.
50227 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
50228 * @return {BasicForm} this
50230 submit : function(options){
50231 this.doAction('submit', options);
50236 * Shortcut to do a load action.
50237 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
50238 * @return {BasicForm} this
50240 load : function(options){
50241 this.doAction('load', options);
50246 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
50247 * @param {Record} record The record to edit
50248 * @return {BasicForm} this
50250 updateRecord : function(record){
50251 record.beginEdit();
50252 var fs = record.fields;
50253 fs.each(function(f){
50254 var field = this.findField(f.name);
50256 record.set(f.name, field.getValue());
50264 * Loads an Roo.data.Record into this form.
50265 * @param {Record} record The record to load
50266 * @return {BasicForm} this
50268 loadRecord : function(record){
50269 this.setValues(record.data);
50274 beforeAction : function(action){
50275 var o = action.options;
50277 if(!this.disableMask) {
50278 if(this.waitMsgTarget === true){
50279 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
50280 }else if(this.waitMsgTarget){
50281 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
50282 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
50284 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
50292 afterAction : function(action, success){
50293 this.activeAction = null;
50294 var o = action.options;
50296 if(!this.disableMask) {
50297 if(this.waitMsgTarget === true){
50299 }else if(this.waitMsgTarget){
50300 this.waitMsgTarget.unmask();
50302 Roo.MessageBox.updateProgress(1);
50303 Roo.MessageBox.hide();
50311 Roo.callback(o.success, o.scope, [this, action]);
50312 this.fireEvent('actioncomplete', this, action);
50316 // failure condition..
50317 // we have a scenario where updates need confirming.
50318 // eg. if a locking scenario exists..
50319 // we look for { errors : { needs_confirm : true }} in the response.
50321 (typeof(action.result) != 'undefined') &&
50322 (typeof(action.result.errors) != 'undefined') &&
50323 (typeof(action.result.errors.needs_confirm) != 'undefined')
50326 Roo.MessageBox.confirm(
50327 "Change requires confirmation",
50328 action.result.errorMsg,
50333 _t.doAction('submit', { params : { _submit_confirmed : 1 } } );
50343 Roo.callback(o.failure, o.scope, [this, action]);
50344 // show an error message if no failed handler is set..
50345 if (!this.hasListener('actionfailed')) {
50346 Roo.MessageBox.alert("Error",
50347 (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
50348 action.result.errorMsg :
50349 "Saving Failed, please check your entries or try again"
50353 this.fireEvent('actionfailed', this, action);
50359 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
50360 * @param {String} id The value to search for
50363 findField : function(id){
50364 var field = this.items.get(id);
50366 this.items.each(function(f){
50367 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
50373 return field || null;
50377 * Add a secondary form to this one,
50378 * Used to provide tabbed forms. One form is primary, with hidden values
50379 * which mirror the elements from the other forms.
50381 * @param {Roo.form.Form} form to add.
50384 addForm : function(form)
50387 if (this.childForms.indexOf(form) > -1) {
50391 this.childForms.push(form);
50393 Roo.each(form.allItems, function (fe) {
50395 n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
50396 if (this.findField(n)) { // already added..
50399 var add = new Roo.form.Hidden({
50402 add.render(this.el);
50409 * Mark fields in this form invalid in bulk.
50410 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
50411 * @return {BasicForm} this
50413 markInvalid : function(errors){
50414 if(errors instanceof Array){
50415 for(var i = 0, len = errors.length; i < len; i++){
50416 var fieldError = errors[i];
50417 var f = this.findField(fieldError.id);
50419 f.markInvalid(fieldError.msg);
50425 if(typeof errors[id] != 'function' && (field = this.findField(id))){
50426 field.markInvalid(errors[id]);
50430 Roo.each(this.childForms || [], function (f) {
50431 f.markInvalid(errors);
50438 * Set values for fields in this form in bulk.
50439 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
50440 * @return {BasicForm} this
50442 setValues : function(values){
50443 if(values instanceof Array){ // array of objects
50444 for(var i = 0, len = values.length; i < len; i++){
50446 var f = this.findField(v.id);
50448 f.setValue(v.value);
50449 if(this.trackResetOnLoad){
50450 f.originalValue = f.getValue();
50454 }else{ // object hash
50457 if(typeof values[id] != 'function' && (field = this.findField(id))){
50459 if (field.setFromData &&
50460 field.valueField &&
50461 field.displayField &&
50462 // combos' with local stores can
50463 // be queried via setValue()
50464 // to set their value..
50465 (field.store && !field.store.isLocal)
50469 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
50470 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
50471 field.setFromData(sd);
50474 field.setValue(values[id]);
50478 if(this.trackResetOnLoad){
50479 field.originalValue = field.getValue();
50484 this.resetHasChanged();
50487 Roo.each(this.childForms || [], function (f) {
50488 f.setValues(values);
50489 f.resetHasChanged();
50496 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
50497 * they are returned as an array.
50498 * @param {Boolean} asString
50501 getValues : function(asString){
50502 if (this.childForms) {
50503 // copy values from the child forms
50504 Roo.each(this.childForms, function (f) {
50505 this.setValues(f.getValues());
50510 if (typeof(FormData) != 'undefined' && asString !== true) {
50511 // this relies on a 'recent' version of chrome apparently...
50513 var fd = (new FormData(this.el.dom)).entries();
50515 var ent = fd.next();
50516 while (!ent.done) {
50517 ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
50528 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
50529 if(asString === true){
50532 return Roo.urlDecode(fs);
50536 * Returns the fields in this form as an object with key/value pairs.
50537 * This differs from getValues as it calls getValue on each child item, rather than using dom data.
50540 getFieldValues : function(with_hidden)
50542 if (this.childForms) {
50543 // copy values from the child forms
50544 // should this call getFieldValues - probably not as we do not currently copy
50545 // hidden fields when we generate..
50546 Roo.each(this.childForms, function (f) {
50547 this.setValues(f.getValues());
50552 this.items.each(function(f){
50553 if (!f.getName()) {
50556 var v = f.getValue();
50557 if (f.inputType =='radio') {
50558 if (typeof(ret[f.getName()]) == 'undefined') {
50559 ret[f.getName()] = ''; // empty..
50562 if (!f.el.dom.checked) {
50566 v = f.el.dom.value;
50570 // not sure if this supported any more..
50571 if ((typeof(v) == 'object') && f.getRawValue) {
50572 v = f.getRawValue() ; // dates..
50574 // combo boxes where name != hiddenName...
50575 if (f.name != f.getName()) {
50576 ret[f.name] = f.getRawValue();
50578 ret[f.getName()] = v;
50585 * Clears all invalid messages in this form.
50586 * @return {BasicForm} this
50588 clearInvalid : function(){
50589 this.items.each(function(f){
50593 Roo.each(this.childForms || [], function (f) {
50602 * Resets this form.
50603 * @return {BasicForm} this
50605 reset : function(){
50606 this.items.each(function(f){
50610 Roo.each(this.childForms || [], function (f) {
50613 this.resetHasChanged();
50619 * Add Roo.form components to this form.
50620 * @param {Field} field1
50621 * @param {Field} field2 (optional)
50622 * @param {Field} etc (optional)
50623 * @return {BasicForm} this
50626 this.items.addAll(Array.prototype.slice.call(arguments, 0));
50632 * Removes a field from the items collection (does NOT remove its markup).
50633 * @param {Field} field
50634 * @return {BasicForm} this
50636 remove : function(field){
50637 this.items.remove(field);
50642 * Looks at the fields in this form, checks them for an id attribute,
50643 * and calls applyTo on the existing dom element with that id.
50644 * @return {BasicForm} this
50646 render : function(){
50647 this.items.each(function(f){
50648 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
50656 * Calls {@link Ext#apply} for all fields in this form with the passed object.
50657 * @param {Object} values
50658 * @return {BasicForm} this
50660 applyToFields : function(o){
50661 this.items.each(function(f){
50668 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
50669 * @param {Object} values
50670 * @return {BasicForm} this
50672 applyIfToFields : function(o){
50673 this.items.each(function(f){
50681 Roo.BasicForm = Roo.form.BasicForm;
50683 Roo.apply(Roo.form.BasicForm, {
50697 intervalID : false,
50703 if(this.isApplied){
50708 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
50709 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
50710 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
50711 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
50714 this.maskEl.top.enableDisplayMode("block");
50715 this.maskEl.left.enableDisplayMode("block");
50716 this.maskEl.bottom.enableDisplayMode("block");
50717 this.maskEl.right.enableDisplayMode("block");
50719 Roo.get(document.body).on('click', function(){
50723 Roo.get(document.body).on('touchstart', function(){
50727 this.isApplied = true
50730 mask : function(form, target)
50734 this.target = target;
50736 if(!this.form.errorMask || !target.el){
50740 var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
50742 var ot = this.target.el.calcOffsetsTo(scrollable);
50744 var scrollTo = ot[1] - this.form.maskOffset;
50746 scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
50748 scrollable.scrollTo('top', scrollTo);
50750 var el = this.target.wrap || this.target.el;
50752 var box = el.getBox();
50754 this.maskEl.top.setStyle('position', 'absolute');
50755 this.maskEl.top.setStyle('z-index', 10000);
50756 this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
50757 this.maskEl.top.setLeft(0);
50758 this.maskEl.top.setTop(0);
50759 this.maskEl.top.show();
50761 this.maskEl.left.setStyle('position', 'absolute');
50762 this.maskEl.left.setStyle('z-index', 10000);
50763 this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
50764 this.maskEl.left.setLeft(0);
50765 this.maskEl.left.setTop(box.y - this.padding);
50766 this.maskEl.left.show();
50768 this.maskEl.bottom.setStyle('position', 'absolute');
50769 this.maskEl.bottom.setStyle('z-index', 10000);
50770 this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
50771 this.maskEl.bottom.setLeft(0);
50772 this.maskEl.bottom.setTop(box.bottom + this.padding);
50773 this.maskEl.bottom.show();
50775 this.maskEl.right.setStyle('position', 'absolute');
50776 this.maskEl.right.setStyle('z-index', 10000);
50777 this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
50778 this.maskEl.right.setLeft(box.right + this.padding);
50779 this.maskEl.right.setTop(box.y - this.padding);
50780 this.maskEl.right.show();
50782 this.intervalID = window.setInterval(function() {
50783 Roo.form.BasicForm.popover.unmask();
50786 window.onwheel = function(){ return false;};
50788 (function(){ this.isMasked = true; }).defer(500, this);
50792 unmask : function()
50794 if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
50798 this.maskEl.top.setStyle('position', 'absolute');
50799 this.maskEl.top.setSize(0, 0).setXY([0, 0]);
50800 this.maskEl.top.hide();
50802 this.maskEl.left.setStyle('position', 'absolute');
50803 this.maskEl.left.setSize(0, 0).setXY([0, 0]);
50804 this.maskEl.left.hide();
50806 this.maskEl.bottom.setStyle('position', 'absolute');
50807 this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
50808 this.maskEl.bottom.hide();
50810 this.maskEl.right.setStyle('position', 'absolute');
50811 this.maskEl.right.setSize(0, 0).setXY([0, 0]);
50812 this.maskEl.right.hide();
50814 window.onwheel = function(){ return true;};
50816 if(this.intervalID){
50817 window.clearInterval(this.intervalID);
50818 this.intervalID = false;
50821 this.isMasked = false;
50829 * Ext JS Library 1.1.1
50830 * Copyright(c) 2006-2007, Ext JS, LLC.
50832 * Originally Released Under LGPL - original licence link has changed is not relivant.
50835 * <script type="text/javascript">
50839 * @class Roo.form.Form
50840 * @extends Roo.form.BasicForm
50841 * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
50842 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
50844 * @param {Object} config Configuration options
50846 Roo.form.Form = function(config){
50848 if (config.items) {
50849 xitems = config.items;
50850 delete config.items;
50854 Roo.form.Form.superclass.constructor.call(this, null, config);
50855 this.url = this.url || this.action;
50857 this.root = new Roo.form.Layout(Roo.applyIf({
50861 this.active = this.root;
50863 * Array of all the buttons that have been added to this form via {@link addButton}
50867 this.allItems = [];
50870 * @event clientvalidation
50871 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
50872 * @param {Form} this
50873 * @param {Boolean} valid true if the form has passed client-side validation
50875 clientvalidation: true,
50878 * Fires when the form is rendered
50879 * @param {Roo.form.Form} form
50884 if (this.progressUrl) {
50885 // push a hidden field onto the list of fields..
50889 name : 'UPLOAD_IDENTIFIER'
50894 Roo.each(xitems, this.addxtype, this);
50898 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
50900 * @cfg {Roo.Button} buttons[] buttons at bottom of form
50904 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
50907 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
50910 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
50912 buttonAlign:'center',
50915 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
50920 * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
50921 * This property cascades to child containers if not set.
50926 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
50927 * fires a looping event with that state. This is required to bind buttons to the valid
50928 * state using the config value formBind:true on the button.
50930 monitorValid : false,
50933 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
50938 * @cfg {String} progressUrl - Url to return progress data
50941 progressUrl : false,
50943 * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
50944 * sending a formdata with extra parameters - eg uploaded elements.
50950 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
50951 * fields are added and the column is closed. If no fields are passed the column remains open
50952 * until end() is called.
50953 * @param {Object} config The config to pass to the column
50954 * @param {Field} field1 (optional)
50955 * @param {Field} field2 (optional)
50956 * @param {Field} etc (optional)
50957 * @return Column The column container object
50959 column : function(c){
50960 var col = new Roo.form.Column(c);
50962 if(arguments.length > 1){ // duplicate code required because of Opera
50963 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
50970 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
50971 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
50972 * until end() is called.
50973 * @param {Object} config The config to pass to the fieldset
50974 * @param {Field} field1 (optional)
50975 * @param {Field} field2 (optional)
50976 * @param {Field} etc (optional)
50977 * @return FieldSet The fieldset container object
50979 fieldset : function(c){
50980 var fs = new Roo.form.FieldSet(c);
50982 if(arguments.length > 1){ // duplicate code required because of Opera
50983 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
50990 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
50991 * fields are added and the container is closed. If no fields are passed the container remains open
50992 * until end() is called.
50993 * @param {Object} config The config to pass to the Layout
50994 * @param {Field} field1 (optional)
50995 * @param {Field} field2 (optional)
50996 * @param {Field} etc (optional)
50997 * @return Layout The container object
50999 container : function(c){
51000 var l = new Roo.form.Layout(c);
51002 if(arguments.length > 1){ // duplicate code required because of Opera
51003 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
51010 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
51011 * @param {Object} container A Roo.form.Layout or subclass of Layout
51012 * @return {Form} this
51014 start : function(c){
51015 // cascade label info
51016 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
51017 this.active.stack.push(c);
51018 c.ownerCt = this.active;
51024 * Closes the current open container
51025 * @return {Form} this
51028 if(this.active == this.root){
51031 this.active = this.active.ownerCt;
51036 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
51037 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
51038 * as the label of the field.
51039 * @param {Field} field1
51040 * @param {Field} field2 (optional)
51041 * @param {Field} etc. (optional)
51042 * @return {Form} this
51045 this.active.stack.push.apply(this.active.stack, arguments);
51046 this.allItems.push.apply(this.allItems,arguments);
51048 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
51049 if(a[i].isFormField){
51054 Roo.form.Form.superclass.add.apply(this, r);
51064 * Find any element that has been added to a form, using it's ID or name
51065 * This can include framesets, columns etc. along with regular fields..
51066 * @param {String} id - id or name to find.
51068 * @return {Element} e - or false if nothing found.
51070 findbyId : function(id)
51076 Roo.each(this.allItems, function(f){
51077 if (f.id == id || f.name == id ){
51088 * Render this form into the passed container. This should only be called once!
51089 * @param {String/HTMLElement/Element} container The element this component should be rendered into
51090 * @return {Form} this
51092 render : function(ct)
51098 var o = this.autoCreate || {
51100 method : this.method || 'POST',
51101 id : this.id || Roo.id()
51103 this.initEl(ct.createChild(o));
51105 this.root.render(this.el);
51109 this.items.each(function(f){
51110 f.render('x-form-el-'+f.id);
51113 if(this.buttons.length > 0){
51114 // tables are required to maintain order and for correct IE layout
51115 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
51116 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
51117 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
51119 var tr = tb.getElementsByTagName('tr')[0];
51120 for(var i = 0, len = this.buttons.length; i < len; i++) {
51121 var b = this.buttons[i];
51122 var td = document.createElement('td');
51123 td.className = 'x-form-btn-td';
51124 b.render(tr.appendChild(td));
51127 if(this.monitorValid){ // initialize after render
51128 this.startMonitoring();
51130 this.fireEvent('rendered', this);
51135 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
51136 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
51137 * object or a valid Roo.DomHelper element config
51138 * @param {Function} handler The function called when the button is clicked
51139 * @param {Object} scope (optional) The scope of the handler function
51140 * @return {Roo.Button}
51142 addButton : function(config, handler, scope){
51146 minWidth: this.minButtonWidth,
51149 if(typeof config == "string"){
51152 Roo.apply(bc, config);
51154 var btn = new Roo.Button(null, bc);
51155 this.buttons.push(btn);
51160 * Adds a series of form elements (using the xtype property as the factory method.
51161 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
51162 * @param {Object} config
51165 addxtype : function()
51167 var ar = Array.prototype.slice.call(arguments, 0);
51169 for(var i = 0; i < ar.length; i++) {
51171 continue; // skip -- if this happends something invalid got sent, we
51172 // should ignore it, as basically that interface element will not show up
51173 // and that should be pretty obvious!!
51176 if (Roo.form[ar[i].xtype]) {
51178 var fe = Roo.factory(ar[i], Roo.form);
51184 fe.store.form = this;
51189 this.allItems.push(fe);
51190 if (fe.items && fe.addxtype) {
51191 fe.addxtype.apply(fe, fe.items);
51201 // console.log('adding ' + ar[i].xtype);
51203 if (ar[i].xtype == 'Button') {
51204 //console.log('adding button');
51205 //console.log(ar[i]);
51206 this.addButton(ar[i]);
51207 this.allItems.push(fe);
51211 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
51212 alert('end is not supported on xtype any more, use items');
51214 // //console.log('adding end');
51222 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
51223 * option "monitorValid"
51225 startMonitoring : function(){
51228 Roo.TaskMgr.start({
51229 run : this.bindHandler,
51230 interval : this.monitorPoll || 200,
51237 * Stops monitoring of the valid state of this form
51239 stopMonitoring : function(){
51240 this.bound = false;
51244 bindHandler : function(){
51246 return false; // stops binding
51249 this.items.each(function(f){
51250 if(!f.isValid(true)){
51255 for(var i = 0, len = this.buttons.length; i < len; i++){
51256 var btn = this.buttons[i];
51257 if(btn.formBind === true && btn.disabled === valid){
51258 btn.setDisabled(!valid);
51261 this.fireEvent('clientvalidation', this, valid);
51275 Roo.Form = Roo.form.Form;
51278 * Ext JS Library 1.1.1
51279 * Copyright(c) 2006-2007, Ext JS, LLC.
51281 * Originally Released Under LGPL - original licence link has changed is not relivant.
51284 * <script type="text/javascript">
51287 // as we use this in bootstrap.
51288 Roo.namespace('Roo.form');
51290 * @class Roo.form.Action
51291 * Internal Class used to handle form actions
51293 * @param {Roo.form.BasicForm} el The form element or its id
51294 * @param {Object} config Configuration options
51299 // define the action interface
51300 Roo.form.Action = function(form, options){
51302 this.options = options || {};
51305 * Client Validation Failed
51308 Roo.form.Action.CLIENT_INVALID = 'client';
51310 * Server Validation Failed
51313 Roo.form.Action.SERVER_INVALID = 'server';
51315 * Connect to Server Failed
51318 Roo.form.Action.CONNECT_FAILURE = 'connect';
51320 * Reading Data from Server Failed
51323 Roo.form.Action.LOAD_FAILURE = 'load';
51325 Roo.form.Action.prototype = {
51327 failureType : undefined,
51328 response : undefined,
51329 result : undefined,
51331 // interface method
51332 run : function(options){
51336 // interface method
51337 success : function(response){
51341 // interface method
51342 handleResponse : function(response){
51346 // default connection failure
51347 failure : function(response){
51349 this.response = response;
51350 this.failureType = Roo.form.Action.CONNECT_FAILURE;
51351 this.form.afterAction(this, false);
51354 processResponse : function(response){
51355 this.response = response;
51356 if(!response.responseText){
51359 this.result = this.handleResponse(response);
51360 return this.result;
51363 // utility functions used internally
51364 getUrl : function(appendParams){
51365 var url = this.options.url || this.form.url || this.form.el.dom.action;
51367 var p = this.getParams();
51369 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
51375 getMethod : function(){
51376 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
51379 getParams : function(){
51380 var bp = this.form.baseParams;
51381 var p = this.options.params;
51383 if(typeof p == "object"){
51384 p = Roo.urlEncode(Roo.applyIf(p, bp));
51385 }else if(typeof p == 'string' && bp){
51386 p += '&' + Roo.urlEncode(bp);
51389 p = Roo.urlEncode(bp);
51394 createCallback : function(){
51396 success: this.success,
51397 failure: this.failure,
51399 timeout: (this.form.timeout*1000),
51400 upload: this.form.fileUpload ? this.success : undefined
51405 Roo.form.Action.Submit = function(form, options){
51406 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
51409 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
51412 haveProgress : false,
51413 uploadComplete : false,
51415 // uploadProgress indicator.
51416 uploadProgress : function()
51418 if (!this.form.progressUrl) {
51422 if (!this.haveProgress) {
51423 Roo.MessageBox.progress("Uploading", "Uploading");
51425 if (this.uploadComplete) {
51426 Roo.MessageBox.hide();
51430 this.haveProgress = true;
51432 var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
51434 var c = new Roo.data.Connection();
51436 url : this.form.progressUrl,
51441 success : function(req){
51442 //console.log(data);
51446 rdata = Roo.decode(req.responseText)
51448 Roo.log("Invalid data from server..");
51452 if (!rdata || !rdata.success) {
51454 Roo.MessageBox.alert(Roo.encode(rdata));
51457 var data = rdata.data;
51459 if (this.uploadComplete) {
51460 Roo.MessageBox.hide();
51465 Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
51466 Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
51469 this.uploadProgress.defer(2000,this);
51472 failure: function(data) {
51473 Roo.log('progress url failed ');
51484 // run get Values on the form, so it syncs any secondary forms.
51485 this.form.getValues();
51487 var o = this.options;
51488 var method = this.getMethod();
51489 var isPost = method == 'POST';
51490 if(o.clientValidation === false || this.form.isValid()){
51492 if (this.form.progressUrl) {
51493 this.form.findField('UPLOAD_IDENTIFIER').setValue(
51494 (new Date() * 1) + '' + Math.random());
51499 Roo.Ajax.request(Roo.apply(this.createCallback(), {
51500 form:this.form.el.dom,
51501 url:this.getUrl(!isPost),
51503 params:isPost ? this.getParams() : null,
51504 isUpload: this.form.fileUpload,
51505 formData : this.form.formData
51508 this.uploadProgress();
51510 }else if (o.clientValidation !== false){ // client validation failed
51511 this.failureType = Roo.form.Action.CLIENT_INVALID;
51512 this.form.afterAction(this, false);
51516 success : function(response)
51518 this.uploadComplete= true;
51519 if (this.haveProgress) {
51520 Roo.MessageBox.hide();
51524 var result = this.processResponse(response);
51525 if(result === true || result.success){
51526 this.form.afterAction(this, true);
51530 this.form.markInvalid(result.errors);
51531 this.failureType = Roo.form.Action.SERVER_INVALID;
51533 this.form.afterAction(this, false);
51535 failure : function(response)
51537 this.uploadComplete= true;
51538 if (this.haveProgress) {
51539 Roo.MessageBox.hide();
51542 this.response = response;
51543 this.failureType = Roo.form.Action.CONNECT_FAILURE;
51544 this.form.afterAction(this, false);
51547 handleResponse : function(response){
51548 if(this.form.errorReader){
51549 var rs = this.form.errorReader.read(response);
51552 for(var i = 0, len = rs.records.length; i < len; i++) {
51553 var r = rs.records[i];
51554 errors[i] = r.data;
51557 if(errors.length < 1){
51561 success : rs.success,
51567 ret = Roo.decode(response.responseText);
51571 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
51581 Roo.form.Action.Load = function(form, options){
51582 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
51583 this.reader = this.form.reader;
51586 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
51591 Roo.Ajax.request(Roo.apply(
51592 this.createCallback(), {
51593 method:this.getMethod(),
51594 url:this.getUrl(false),
51595 params:this.getParams()
51599 success : function(response){
51601 var result = this.processResponse(response);
51602 if(result === true || !result.success || !result.data){
51603 this.failureType = Roo.form.Action.LOAD_FAILURE;
51604 this.form.afterAction(this, false);
51607 this.form.clearInvalid();
51608 this.form.setValues(result.data);
51609 this.form.afterAction(this, true);
51612 handleResponse : function(response){
51613 if(this.form.reader){
51614 var rs = this.form.reader.read(response);
51615 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
51617 success : rs.success,
51621 return Roo.decode(response.responseText);
51625 Roo.form.Action.ACTION_TYPES = {
51626 'load' : Roo.form.Action.Load,
51627 'submit' : Roo.form.Action.Submit
51630 * Ext JS Library 1.1.1
51631 * Copyright(c) 2006-2007, Ext JS, LLC.
51633 * Originally Released Under LGPL - original licence link has changed is not relivant.
51636 * <script type="text/javascript">
51640 * @class Roo.form.Layout
51641 * @extends Roo.Component
51642 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
51643 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
51645 * @param {Object} config Configuration options
51647 Roo.form.Layout = function(config){
51649 if (config.items) {
51650 xitems = config.items;
51651 delete config.items;
51653 Roo.form.Layout.superclass.constructor.call(this, config);
51655 Roo.each(xitems, this.addxtype, this);
51659 Roo.extend(Roo.form.Layout, Roo.Component, {
51661 * @cfg {String/Object} autoCreate
51662 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
51665 * @cfg {String/Object/Function} style
51666 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
51667 * a function which returns such a specification.
51670 * @cfg {String} labelAlign
51671 * Valid values are "left," "top" and "right" (defaults to "left")
51674 * @cfg {Number} labelWidth
51675 * Fixed width in pixels of all field labels (defaults to undefined)
51678 * @cfg {Boolean} clear
51679 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
51683 * @cfg {String} labelSeparator
51684 * The separator to use after field labels (defaults to ':')
51686 labelSeparator : ':',
51688 * @cfg {Boolean} hideLabels
51689 * True to suppress the display of field labels in this layout (defaults to false)
51691 hideLabels : false,
51694 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
51699 onRender : function(ct, position){
51700 if(this.el){ // from markup
51701 this.el = Roo.get(this.el);
51702 }else { // generate
51703 var cfg = this.getAutoCreate();
51704 this.el = ct.createChild(cfg, position);
51707 this.el.applyStyles(this.style);
51709 if(this.labelAlign){
51710 this.el.addClass('x-form-label-'+this.labelAlign);
51712 if(this.hideLabels){
51713 this.labelStyle = "display:none";
51714 this.elementStyle = "padding-left:0;";
51716 if(typeof this.labelWidth == 'number'){
51717 this.labelStyle = "width:"+this.labelWidth+"px;";
51718 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
51720 if(this.labelAlign == 'top'){
51721 this.labelStyle = "width:auto;";
51722 this.elementStyle = "padding-left:0;";
51725 var stack = this.stack;
51726 var slen = stack.length;
51728 if(!this.fieldTpl){
51729 var t = new Roo.Template(
51730 '<div class="x-form-item {5}">',
51731 '<label for="{0}" style="{2}">{1}{4}</label>',
51732 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
51734 '</div><div class="x-form-clear-left"></div>'
51736 t.disableFormats = true;
51738 Roo.form.Layout.prototype.fieldTpl = t;
51740 for(var i = 0; i < slen; i++) {
51741 if(stack[i].isFormField){
51742 this.renderField(stack[i]);
51744 this.renderComponent(stack[i]);
51749 this.el.createChild({cls:'x-form-clear'});
51754 renderField : function(f){
51755 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
51758 f.labelStyle||this.labelStyle||'', //2
51759 this.elementStyle||'', //3
51760 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
51761 f.itemCls||this.itemCls||'' //5
51762 ], true).getPrevSibling());
51766 renderComponent : function(c){
51767 c.render(c.isLayout ? this.el : this.el.createChild());
51770 * Adds a object form elements (using the xtype property as the factory method.)
51771 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
51772 * @param {Object} config
51774 addxtype : function(o)
51776 // create the lement.
51777 o.form = this.form;
51778 var fe = Roo.factory(o, Roo.form);
51779 this.form.allItems.push(fe);
51780 this.stack.push(fe);
51782 if (fe.isFormField) {
51783 this.form.items.add(fe);
51791 * @class Roo.form.Column
51792 * @extends Roo.form.Layout
51793 * @children Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
51794 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
51796 * @param {Object} config Configuration options
51798 Roo.form.Column = function(config){
51799 Roo.form.Column.superclass.constructor.call(this, config);
51802 Roo.extend(Roo.form.Column, Roo.form.Layout, {
51804 * @cfg {Number/String} width
51805 * The fixed width of the column in pixels or CSS value (defaults to "auto")
51808 * @cfg {String/Object} autoCreate
51809 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
51813 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
51816 onRender : function(ct, position){
51817 Roo.form.Column.superclass.onRender.call(this, ct, position);
51819 this.el.setWidth(this.width);
51826 * @class Roo.form.Row
51827 * @extends Roo.form.Layout
51828 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
51829 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
51831 * @param {Object} config Configuration options
51835 Roo.form.Row = function(config){
51836 Roo.form.Row.superclass.constructor.call(this, config);
51839 Roo.extend(Roo.form.Row, Roo.form.Layout, {
51841 * @cfg {Number/String} width
51842 * The fixed width of the column in pixels or CSS value (defaults to "auto")
51845 * @cfg {Number/String} height
51846 * The fixed height of the column in pixels or CSS value (defaults to "auto")
51848 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
51852 onRender : function(ct, position){
51853 //console.log('row render');
51855 var t = new Roo.Template(
51856 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
51857 '<label for="{0}" style="{2}">{1}{4}</label>',
51858 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
51862 t.disableFormats = true;
51864 Roo.form.Layout.prototype.rowTpl = t;
51866 this.fieldTpl = this.rowTpl;
51868 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
51869 var labelWidth = 100;
51871 if ((this.labelAlign != 'top')) {
51872 if (typeof this.labelWidth == 'number') {
51873 labelWidth = this.labelWidth
51875 this.padWidth = 20 + labelWidth;
51879 Roo.form.Column.superclass.onRender.call(this, ct, position);
51881 this.el.setWidth(this.width);
51884 this.el.setHeight(this.height);
51889 renderField : function(f){
51890 f.fieldEl = this.fieldTpl.append(this.el, [
51891 f.id, f.fieldLabel,
51892 f.labelStyle||this.labelStyle||'',
51893 this.elementStyle||'',
51894 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
51895 f.itemCls||this.itemCls||'',
51896 f.width ? f.width + this.padWidth : 160 + this.padWidth
51903 * @class Roo.form.FieldSet
51904 * @extends Roo.form.Layout
51905 * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
51906 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
51908 * @param {Object} config Configuration options
51910 Roo.form.FieldSet = function(config){
51911 Roo.form.FieldSet.superclass.constructor.call(this, config);
51914 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
51916 * @cfg {String} legend
51917 * The text to display as the legend for the FieldSet (defaults to '')
51920 * @cfg {String/Object} autoCreate
51921 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
51925 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
51928 onRender : function(ct, position){
51929 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
51931 this.setLegend(this.legend);
51936 setLegend : function(text){
51938 this.el.child('legend').update(text);
51943 * Ext JS Library 1.1.1
51944 * Copyright(c) 2006-2007, Ext JS, LLC.
51946 * Originally Released Under LGPL - original licence link has changed is not relivant.
51949 * <script type="text/javascript">
51952 * @class Roo.form.VTypes
51953 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
51956 Roo.form.VTypes = function(){
51957 // closure these in so they are only created once.
51958 var alpha = /^[a-zA-Z_]+$/;
51959 var alphanum = /^[a-zA-Z0-9_]+$/;
51960 var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
51961 var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
51963 // All these messages and functions are configurable
51966 * The function used to validate email addresses
51967 * @param {String} value The email address
51969 'email' : function(v){
51970 return email.test(v);
51973 * The error text to display when the email validation function returns false
51976 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
51978 * The keystroke filter mask to be applied on email input
51981 'emailMask' : /[a-z0-9_\.\-@]/i,
51984 * The function used to validate URLs
51985 * @param {String} value The URL
51987 'url' : function(v){
51988 return url.test(v);
51991 * The error text to display when the url validation function returns false
51994 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
51997 * The function used to validate alpha values
51998 * @param {String} value The value
52000 'alpha' : function(v){
52001 return alpha.test(v);
52004 * The error text to display when the alpha validation function returns false
52007 'alphaText' : 'This field should only contain letters and _',
52009 * The keystroke filter mask to be applied on alpha input
52012 'alphaMask' : /[a-z_]/i,
52015 * The function used to validate alphanumeric values
52016 * @param {String} value The value
52018 'alphanum' : function(v){
52019 return alphanum.test(v);
52022 * The error text to display when the alphanumeric validation function returns false
52025 'alphanumText' : 'This field should only contain letters, numbers and _',
52027 * The keystroke filter mask to be applied on alphanumeric input
52030 'alphanumMask' : /[a-z0-9_]/i
52032 }();//<script type="text/javascript">
52035 * @class Roo.form.FCKeditor
52036 * @extends Roo.form.TextArea
52037 * Wrapper around the FCKEditor http://www.fckeditor.net
52039 * Creates a new FCKeditor
52040 * @param {Object} config Configuration options
52042 Roo.form.FCKeditor = function(config){
52043 Roo.form.FCKeditor.superclass.constructor.call(this, config);
52046 * @event editorinit
52047 * Fired when the editor is initialized - you can add extra handlers here..
52048 * @param {FCKeditor} this
52049 * @param {Object} the FCK object.
52056 Roo.form.FCKeditor.editors = { };
52057 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
52059 //defaultAutoCreate : {
52060 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
52064 * @cfg {Object} fck options - see fck manual for details.
52069 * @cfg {Object} fck toolbar set (Basic or Default)
52071 toolbarSet : 'Basic',
52073 * @cfg {Object} fck BasePath
52075 basePath : '/fckeditor/',
52083 onRender : function(ct, position)
52086 this.defaultAutoCreate = {
52088 style:"width:300px;height:60px;",
52089 autocomplete: "new-password"
52092 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
52095 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
52096 if(this.preventScrollbars){
52097 this.el.setStyle("overflow", "hidden");
52099 this.el.setHeight(this.growMin);
52102 //console.log('onrender' + this.getId() );
52103 Roo.form.FCKeditor.editors[this.getId()] = this;
52106 this.replaceTextarea() ;
52110 getEditor : function() {
52111 return this.fckEditor;
52114 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
52115 * @param {Mixed} value The value to set
52119 setValue : function(value)
52121 //console.log('setValue: ' + value);
52123 if(typeof(value) == 'undefined') { // not sure why this is happending...
52126 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
52128 //if(!this.el || !this.getEditor()) {
52129 // this.value = value;
52130 //this.setValue.defer(100,this,[value]);
52134 if(!this.getEditor()) {
52138 this.getEditor().SetData(value);
52145 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
52146 * @return {Mixed} value The field value
52148 getValue : function()
52151 if (this.frame && this.frame.dom.style.display == 'none') {
52152 return Roo.form.FCKeditor.superclass.getValue.call(this);
52155 if(!this.el || !this.getEditor()) {
52157 // this.getValue.defer(100,this);
52162 var value=this.getEditor().GetData();
52163 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
52164 return Roo.form.FCKeditor.superclass.getValue.call(this);
52170 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
52171 * @return {Mixed} value The field value
52173 getRawValue : function()
52175 if (this.frame && this.frame.dom.style.display == 'none') {
52176 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
52179 if(!this.el || !this.getEditor()) {
52180 //this.getRawValue.defer(100,this);
52187 var value=this.getEditor().GetData();
52188 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
52189 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
52193 setSize : function(w,h) {
52197 //if (this.frame && this.frame.dom.style.display == 'none') {
52198 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
52201 //if(!this.el || !this.getEditor()) {
52202 // this.setSize.defer(100,this, [w,h]);
52208 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
52210 this.frame.dom.setAttribute('width', w);
52211 this.frame.dom.setAttribute('height', h);
52212 this.frame.setSize(w,h);
52216 toggleSourceEdit : function(value) {
52220 this.el.dom.style.display = value ? '' : 'none';
52221 this.frame.dom.style.display = value ? 'none' : '';
52226 focus: function(tag)
52228 if (this.frame.dom.style.display == 'none') {
52229 return Roo.form.FCKeditor.superclass.focus.call(this);
52231 if(!this.el || !this.getEditor()) {
52232 this.focus.defer(100,this, [tag]);
52239 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
52240 this.getEditor().Focus();
52242 if (!this.getEditor().Selection.GetSelection()) {
52243 this.focus.defer(100,this, [tag]);
52248 var r = this.getEditor().EditorDocument.createRange();
52249 r.setStart(tgs[0],0);
52250 r.setEnd(tgs[0],0);
52251 this.getEditor().Selection.GetSelection().removeAllRanges();
52252 this.getEditor().Selection.GetSelection().addRange(r);
52253 this.getEditor().Focus();
52260 replaceTextarea : function()
52262 if ( document.getElementById( this.getId() + '___Frame' ) ) {
52265 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
52267 // We must check the elements firstly using the Id and then the name.
52268 var oTextarea = document.getElementById( this.getId() );
52270 var colElementsByName = document.getElementsByName( this.getId() ) ;
52272 oTextarea.style.display = 'none' ;
52274 if ( oTextarea.tabIndex ) {
52275 this.TabIndex = oTextarea.tabIndex ;
52278 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
52279 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
52280 this.frame = Roo.get(this.getId() + '___Frame')
52283 _getConfigHtml : function()
52287 for ( var o in this.fckconfig ) {
52288 sConfig += sConfig.length > 0 ? '&' : '';
52289 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
52292 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
52296 _getIFrameHtml : function()
52298 var sFile = 'fckeditor.html' ;
52299 /* no idea what this is about..
52302 if ( (/fcksource=true/i).test( window.top.location.search ) )
52303 sFile = 'fckeditor.original.html' ;
52308 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
52309 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
52312 var html = '<iframe id="' + this.getId() +
52313 '___Frame" src="' + sLink +
52314 '" width="' + this.width +
52315 '" height="' + this.height + '"' +
52316 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
52317 ' frameborder="0" scrolling="no"></iframe>' ;
52322 _insertHtmlBefore : function( html, element )
52324 if ( element.insertAdjacentHTML ) {
52326 element.insertAdjacentHTML( 'beforeBegin', html ) ;
52328 var oRange = document.createRange() ;
52329 oRange.setStartBefore( element ) ;
52330 var oFragment = oRange.createContextualFragment( html );
52331 element.parentNode.insertBefore( oFragment, element ) ;
52344 //Roo.reg('fckeditor', Roo.form.FCKeditor);
52346 function FCKeditor_OnComplete(editorInstance){
52347 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
52348 f.fckEditor = editorInstance;
52349 //console.log("loaded");
52350 f.fireEvent('editorinit', f, editorInstance);
52370 //<script type="text/javascript">
52372 * @class Roo.form.GridField
52373 * @extends Roo.form.Field
52374 * Embed a grid (or editable grid into a form)
52377 * This embeds a grid in a form, the value of the field should be the json encoded array of rows
52379 * xgrid.store = Roo.data.Store
52380 * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
52381 * xgrid.store.reader = Roo.data.JsonReader
52385 * Creates a new GridField
52386 * @param {Object} config Configuration options
52388 Roo.form.GridField = function(config){
52389 Roo.form.GridField.superclass.constructor.call(this, config);
52393 Roo.extend(Roo.form.GridField, Roo.form.Field, {
52395 * @cfg {Number} width - used to restrict width of grid..
52399 * @cfg {Number} height - used to restrict height of grid..
52403 * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
52409 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
52410 * {tag: "input", type: "checkbox", autocomplete: "off"})
52412 // defaultAutoCreate : { tag: 'div' },
52413 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
52415 * @cfg {String} addTitle Text to include for adding a title.
52419 onResize : function(){
52420 Roo.form.Field.superclass.onResize.apply(this, arguments);
52423 initEvents : function(){
52424 // Roo.form.Checkbox.superclass.initEvents.call(this);
52425 // has no events...
52430 getResizeEl : function(){
52434 getPositionEl : function(){
52439 onRender : function(ct, position){
52441 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
52442 var style = this.style;
52445 Roo.form.GridField.superclass.onRender.call(this, ct, position);
52446 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
52447 this.viewEl = this.wrap.createChild({ tag: 'div' });
52449 this.viewEl.applyStyles(style);
52452 this.viewEl.setWidth(this.width);
52455 this.viewEl.setHeight(this.height);
52457 //if(this.inputValue !== undefined){
52458 //this.setValue(this.value);
52461 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
52464 this.grid.render();
52465 this.grid.getDataSource().on('remove', this.refreshValue, this);
52466 this.grid.getDataSource().on('update', this.refreshValue, this);
52467 this.grid.on('afteredit', this.refreshValue, this);
52473 * Sets the value of the item.
52474 * @param {String} either an object or a string..
52476 setValue : function(v){
52478 v = v || []; // empty set..
52479 // this does not seem smart - it really only affects memoryproxy grids..
52480 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
52481 var ds = this.grid.getDataSource();
52482 // assumes a json reader..
52484 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
52485 ds.loadData( data);
52487 // clear selection so it does not get stale.
52488 if (this.grid.sm) {
52489 this.grid.sm.clearSelections();
52492 Roo.form.GridField.superclass.setValue.call(this, v);
52493 this.refreshValue();
52494 // should load data in the grid really....
52498 refreshValue: function() {
52500 this.grid.getDataSource().each(function(r) {
52503 this.el.dom.value = Roo.encode(val);
52511 * Ext JS Library 1.1.1
52512 * Copyright(c) 2006-2007, Ext JS, LLC.
52514 * Originally Released Under LGPL - original licence link has changed is not relivant.
52517 * <script type="text/javascript">
52520 * @class Roo.form.DisplayField
52521 * @extends Roo.form.Field
52522 * A generic Field to display non-editable data.
52523 * @cfg {Boolean} closable (true|false) default false
52525 * Creates a new Display Field item.
52526 * @param {Object} config Configuration options
52528 Roo.form.DisplayField = function(config){
52529 Roo.form.DisplayField.superclass.constructor.call(this, config);
52534 * Fires after the click the close btn
52535 * @param {Roo.form.DisplayField} this
52541 Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
52542 inputType: 'hidden',
52548 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
52550 focusClass : undefined,
52552 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
52554 fieldClass: 'x-form-field',
52557 * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
52559 valueRenderer: undefined,
52563 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
52564 * {tag: "input", type: "checkbox", autocomplete: "off"})
52567 // defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
52571 onResize : function(){
52572 Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
52576 initEvents : function(){
52577 // Roo.form.Checkbox.superclass.initEvents.call(this);
52578 // has no events...
52581 this.closeEl.on('click', this.onClose, this);
52587 getResizeEl : function(){
52591 getPositionEl : function(){
52596 onRender : function(ct, position){
52598 Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
52599 //if(this.inputValue !== undefined){
52600 this.wrap = this.el.wrap();
52602 this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
52605 this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
52608 if (this.bodyStyle) {
52609 this.viewEl.applyStyles(this.bodyStyle);
52611 //this.viewEl.setStyle('padding', '2px');
52613 this.setValue(this.value);
52618 initValue : Roo.emptyFn,
52623 onClick : function(){
52628 * Sets the checked state of the checkbox.
52629 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
52631 setValue : function(v){
52633 var html = this.valueRenderer ? this.valueRenderer(v) : String.format('{0}', v);
52634 // this might be called before we have a dom element..
52635 if (!this.viewEl) {
52638 this.viewEl.dom.innerHTML = html;
52639 Roo.form.DisplayField.superclass.setValue.call(this, v);
52643 onClose : function(e)
52645 e.preventDefault();
52647 this.fireEvent('close', this);
52656 * @class Roo.form.DayPicker
52657 * @extends Roo.form.Field
52658 * A Day picker show [M] [T] [W] ....
52660 * Creates a new Day Picker
52661 * @param {Object} config Configuration options
52663 Roo.form.DayPicker= function(config){
52664 Roo.form.DayPicker.superclass.constructor.call(this, config);
52668 Roo.extend(Roo.form.DayPicker, Roo.form.Field, {
52670 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
52672 focusClass : undefined,
52674 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
52676 fieldClass: "x-form-field",
52679 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
52680 * {tag: "input", type: "checkbox", autocomplete: "off"})
52682 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
52685 actionMode : 'viewEl',
52689 inputType : 'hidden',
52692 inputElement: false, // real input element?
52693 basedOn: false, // ????
52695 isFormField: true, // not sure where this is needed!!!!
52697 onResize : function(){
52698 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
52699 if(!this.boxLabel){
52700 this.el.alignTo(this.wrap, 'c-c');
52704 initEvents : function(){
52705 Roo.form.Checkbox.superclass.initEvents.call(this);
52706 this.el.on("click", this.onClick, this);
52707 this.el.on("change", this.onClick, this);
52711 getResizeEl : function(){
52715 getPositionEl : function(){
52721 onRender : function(ct, position){
52722 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
52724 this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
52726 var r1 = '<table><tr>';
52727 var r2 = '<tr class="x-form-daypick-icons">';
52728 for (var i=0; i < 7; i++) {
52729 r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
52730 r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL +'"></td>';
52733 var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
52734 viewEl.select('img').on('click', this.onClick, this);
52735 this.viewEl = viewEl;
52738 // this will not work on Chrome!!!
52739 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
52740 this.el.on('propertychange', this.setFromHidden, this); //ie
52748 initValue : Roo.emptyFn,
52751 * Returns the checked state of the checkbox.
52752 * @return {Boolean} True if checked, else false
52754 getValue : function(){
52755 return this.el.dom.value;
52760 onClick : function(e){
52761 //this.setChecked(!this.checked);
52762 Roo.get(e.target).toggleClass('x-menu-item-checked');
52763 this.refreshValue();
52764 //if(this.el.dom.checked != this.checked){
52765 // this.setValue(this.el.dom.checked);
52770 refreshValue : function()
52773 this.viewEl.select('img',true).each(function(e,i,n) {
52774 val += e.is(".x-menu-item-checked") ? String(n) : '';
52776 this.setValue(val, true);
52780 * Sets the checked state of the checkbox.
52781 * On is always based on a string comparison between inputValue and the param.
52782 * @param {Boolean/String} value - the value to set
52783 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
52785 setValue : function(v,suppressEvent){
52786 if (!this.el.dom) {
52789 var old = this.el.dom.value ;
52790 this.el.dom.value = v;
52791 if (suppressEvent) {
52795 // update display..
52796 this.viewEl.select('img',true).each(function(e,i,n) {
52798 var on = e.is(".x-menu-item-checked");
52799 var newv = v.indexOf(String(n)) > -1;
52801 e.toggleClass('x-menu-item-checked');
52807 this.fireEvent('change', this, v, old);
52812 // handle setting of hidden value by some other method!!?!?
52813 setFromHidden: function()
52818 //console.log("SET FROM HIDDEN");
52819 //alert('setFrom hidden');
52820 this.setValue(this.el.dom.value);
52823 onDestroy : function()
52826 Roo.get(this.viewEl).remove();
52829 Roo.form.DayPicker.superclass.onDestroy.call(this);
52833 * RooJS Library 1.1.1
52834 * Copyright(c) 2008-2011 Alan Knowles
52841 * @class Roo.form.ComboCheck
52842 * @extends Roo.form.ComboBox
52843 * A combobox for multiple select items.
52845 * FIXME - could do with a reset button..
52848 * Create a new ComboCheck
52849 * @param {Object} config Configuration options
52851 Roo.form.ComboCheck = function(config){
52852 Roo.form.ComboCheck.superclass.constructor.call(this, config);
52853 // should verify some data...
52855 // hiddenName = required..
52856 // displayField = required
52857 // valudField == required
52858 var req= [ 'hiddenName', 'displayField', 'valueField' ];
52860 Roo.each(req, function(e) {
52861 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
52862 throw "Roo.form.ComboCheck : missing value for: " + e;
52869 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
52874 selectedClass: 'x-menu-item-checked',
52877 onRender : function(ct, position){
52883 var cls = 'x-combo-list';
52886 this.tpl = new Roo.Template({
52887 html : '<div class="'+cls+'-item x-menu-check-item">' +
52888 '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' +
52889 '<span>{' + this.displayField + '}</span>' +
52896 Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
52897 this.view.singleSelect = false;
52898 this.view.multiSelect = true;
52899 this.view.toggleSelect = true;
52900 this.pageTb.add(new Roo.Toolbar.Fill(), {
52903 handler: function()
52910 onViewOver : function(e, t){
52916 onViewClick : function(doFocus,index){
52920 select: function () {
52921 //Roo.log("SELECT CALLED");
52924 selectByValue : function(xv, scrollIntoView){
52925 var ar = this.getValueArray();
52928 Roo.each(ar, function(v) {
52929 if(v === undefined || v === null){
52932 var r = this.findRecord(this.valueField, v);
52934 sels.push(this.store.indexOf(r))
52938 this.view.select(sels);
52944 onSelect : function(record, index){
52945 // Roo.log("onselect Called");
52946 // this is only called by the clear button now..
52947 this.view.clearSelections();
52948 this.setValue('[]');
52949 if (this.value != this.valueBefore) {
52950 this.fireEvent('change', this, this.value, this.valueBefore);
52951 this.valueBefore = this.value;
52954 getValueArray : function()
52959 //Roo.log(this.value);
52960 if (typeof(this.value) == 'undefined') {
52963 var ar = Roo.decode(this.value);
52964 return ar instanceof Array ? ar : []; //?? valid?
52967 Roo.log(e + "\nRoo.form.ComboCheck:getValueArray invalid data:" + this.getValue());
52972 expand : function ()
52975 Roo.form.ComboCheck.superclass.expand.call(this);
52976 this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
52977 //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
52982 collapse : function(){
52983 Roo.form.ComboCheck.superclass.collapse.call(this);
52984 var sl = this.view.getSelectedIndexes();
52985 var st = this.store;
52989 Roo.each(sl, function(i) {
52991 nv.push(r.get(this.valueField));
52993 this.setValue(Roo.encode(nv));
52994 if (this.value != this.valueBefore) {
52996 this.fireEvent('change', this, this.value, this.valueBefore);
52997 this.valueBefore = this.value;
53002 setValue : function(v){
53006 var vals = this.getValueArray();
53008 Roo.each(vals, function(k) {
53009 var r = this.findRecord(this.valueField, k);
53011 tv.push(r.data[this.displayField]);
53012 }else if(this.valueNotFoundText !== undefined){
53013 tv.push( this.valueNotFoundText );
53018 Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
53019 this.hiddenField.value = v;
53025 * Ext JS Library 1.1.1
53026 * Copyright(c) 2006-2007, Ext JS, LLC.
53028 * Originally Released Under LGPL - original licence link has changed is not relivant.
53031 * <script type="text/javascript">
53035 * @class Roo.form.Signature
53036 * @extends Roo.form.Field
53040 * @param {Object} config Configuration options
53043 Roo.form.Signature = function(config){
53044 Roo.form.Signature.superclass.constructor.call(this, config);
53046 this.addEvents({// not in used??
53049 * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
53050 * @param {Roo.form.Signature} combo This combo box
53055 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
53056 * @param {Roo.form.ComboBox} combo This combo box
53057 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
53063 Roo.extend(Roo.form.Signature, Roo.form.Field, {
53065 * @cfg {Object} labels Label to use when rendering a form.
53069 * confirm : "Confirm"
53074 confirm : "Confirm"
53077 * @cfg {Number} width The signature panel width (defaults to 300)
53081 * @cfg {Number} height The signature panel height (defaults to 100)
53085 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
53087 allowBlank : false,
53090 // {Object} signPanel The signature SVG panel element (defaults to {})
53092 // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
53093 isMouseDown : false,
53094 // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
53095 isConfirmed : false,
53096 // {String} signatureTmp SVG mapping string (defaults to empty string)
53100 defaultAutoCreate : { // modified by initCompnoent..
53106 onRender : function(ct, position){
53108 Roo.form.Signature.superclass.onRender.call(this, ct, position);
53110 this.wrap = this.el.wrap({
53111 cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
53114 this.createToolbar(this);
53115 this.signPanel = this.wrap.createChild({
53117 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
53121 this.svgID = Roo.id();
53122 this.svgEl = this.signPanel.createChild({
53123 xmlns : 'http://www.w3.org/2000/svg',
53125 id : this.svgID + "-svg",
53127 height: this.height,
53128 viewBox: '0 0 '+this.width+' '+this.height,
53132 id: this.svgID + "-svg-r",
53134 height: this.height,
53139 id: this.svgID + "-svg-l",
53141 y1: (this.height*0.8), // start set the line in 80% of height
53142 x2: this.width, // end
53143 y2: (this.height*0.8), // end set the line in 80% of height
53145 'stroke-width': "1",
53146 'stroke-dasharray': "3",
53147 'shape-rendering': "crispEdges",
53148 'pointer-events': "none"
53152 id: this.svgID + "-svg-p",
53154 'stroke-width': "3",
53156 'pointer-events': 'none'
53161 this.svgBox = this.svgEl.dom.getScreenCTM();
53163 createSVG : function(){
53164 var svg = this.signPanel;
53165 var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
53168 r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
53169 r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
53170 r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
53171 r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
53172 r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
53173 r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
53174 r.addEventListener('touchend', function(e) { return t.up(e); }, false);
53177 isTouchEvent : function(e){
53178 return e.type.match(/^touch/);
53180 getCoords : function (e) {
53181 var pt = this.svgEl.dom.createSVGPoint();
53184 if (this.isTouchEvent(e)) {
53185 pt.x = e.targetTouches[0].clientX;
53186 pt.y = e.targetTouches[0].clientY;
53188 var a = this.svgEl.dom.getScreenCTM();
53189 var b = a.inverse();
53190 var mx = pt.matrixTransform(b);
53191 return mx.x + ',' + mx.y;
53193 //mouse event headler
53194 down : function (e) {
53195 this.signatureTmp += 'M' + this.getCoords(e) + ' ';
53196 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
53198 this.isMouseDown = true;
53200 e.preventDefault();
53202 move : function (e) {
53203 if (this.isMouseDown) {
53204 this.signatureTmp += 'L' + this.getCoords(e) + ' ';
53205 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
53208 e.preventDefault();
53210 up : function (e) {
53211 this.isMouseDown = false;
53212 var sp = this.signatureTmp.split(' ');
53215 if(!sp[sp.length-2].match(/^L/)){
53219 this.signatureTmp = sp.join(" ");
53222 if(this.getValue() != this.signatureTmp){
53223 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
53224 this.isConfirmed = false;
53226 e.preventDefault();
53230 * Protected method that will not generally be called directly. It
53231 * is called when the editor creates its toolbar. Override this method if you need to
53232 * add custom toolbar buttons.
53233 * @param {HtmlEditor} editor
53235 createToolbar : function(editor){
53236 function btn(id, toggle, handler){
53237 var xid = fid + '-'+ id ;
53241 cls : 'x-btn-icon x-edit-'+id,
53242 enableToggle:toggle !== false,
53243 scope: editor, // was editor...
53244 handler:handler||editor.relayBtnCmd,
53245 clickEvent:'mousedown',
53246 tooltip: etb.buttonTips[id] || undefined, ///tips ???
53252 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
53256 cls : ' x-signature-btn x-signature-'+id,
53257 scope: editor, // was editor...
53258 handler: this.reset,
53259 clickEvent:'mousedown',
53260 text: this.labels.clear
53267 cls : ' x-signature-btn x-signature-'+id,
53268 scope: editor, // was editor...
53269 handler: this.confirmHandler,
53270 clickEvent:'mousedown',
53271 text: this.labels.confirm
53278 * when user is clicked confirm then show this image.....
53280 * @return {String} Image Data URI
53282 getImageDataURI : function(){
53283 var svg = this.svgEl.dom.parentNode.innerHTML;
53284 var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
53289 * @return {Boolean} this.isConfirmed
53291 getConfirmed : function(){
53292 return this.isConfirmed;
53296 * @return {Number} this.width
53298 getWidth : function(){
53303 * @return {Number} this.height
53305 getHeight : function(){
53306 return this.height;
53309 getSignature : function(){
53310 return this.signatureTmp;
53313 reset : function(){
53314 this.signatureTmp = '';
53315 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
53316 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
53317 this.isConfirmed = false;
53318 Roo.form.Signature.superclass.reset.call(this);
53320 setSignature : function(s){
53321 this.signatureTmp = s;
53322 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
53323 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
53325 this.isConfirmed = false;
53326 Roo.form.Signature.superclass.reset.call(this);
53329 // Roo.log(this.signPanel.dom.contentWindow.up())
53332 setConfirmed : function(){
53336 // Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
53339 confirmHandler : function(){
53340 if(!this.getSignature()){
53344 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
53345 this.setValue(this.getSignature());
53346 this.isConfirmed = true;
53348 this.fireEvent('confirm', this);
53351 // Subclasses should provide the validation implementation by overriding this
53352 validateValue : function(value){
53353 if(this.allowBlank){
53357 if(this.isConfirmed){
53364 * Ext JS Library 1.1.1
53365 * Copyright(c) 2006-2007, Ext JS, LLC.
53367 * Originally Released Under LGPL - original licence link has changed is not relivant.
53370 * <script type="text/javascript">
53375 * @class Roo.form.ComboBox
53376 * @extends Roo.form.TriggerField
53377 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
53379 * Create a new ComboBox.
53380 * @param {Object} config Configuration options
53382 Roo.form.Select = function(config){
53383 Roo.form.Select.superclass.constructor.call(this, config);
53387 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
53389 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
53392 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
53393 * rendering into an Roo.Editor, defaults to false)
53396 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
53397 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
53400 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
53403 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
53404 * the dropdown list (defaults to undefined, with no header element)
53408 * @cfg {String/Roo.Template} tpl The template to use to render the output
53412 defaultAutoCreate : {tag: "select" },
53414 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
53416 listWidth: undefined,
53418 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
53419 * mode = 'remote' or 'text' if mode = 'local')
53421 displayField: undefined,
53423 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
53424 * mode = 'remote' or 'value' if mode = 'local').
53425 * Note: use of a valueField requires the user make a selection
53426 * in order for a value to be mapped.
53428 valueField: undefined,
53432 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
53433 * field's data value (defaults to the underlying DOM element's name)
53435 hiddenName: undefined,
53437 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
53441 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
53443 selectedClass: 'x-combo-selected',
53445 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
53446 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
53447 * which displays a downward arrow icon).
53449 triggerClass : 'x-form-arrow-trigger',
53451 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
53455 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
53456 * anchor positions (defaults to 'tl-bl')
53458 listAlign: 'tl-bl?',
53460 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
53464 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
53465 * query specified by the allQuery config option (defaults to 'query')
53467 triggerAction: 'query',
53469 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
53470 * (defaults to 4, does not apply if editable = false)
53474 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
53475 * delay (typeAheadDelay) if it matches a known value (defaults to false)
53479 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
53480 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
53484 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
53485 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
53489 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
53490 * when editable = true (defaults to false)
53492 selectOnFocus:false,
53494 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
53496 queryParam: 'query',
53498 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
53499 * when mode = 'remote' (defaults to 'Loading...')
53501 loadingText: 'Loading...',
53503 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
53507 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
53511 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
53512 * traditional select (defaults to true)
53516 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
53520 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
53524 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
53525 * listWidth has a higher value)
53529 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
53530 * allow the user to set arbitrary text into the field (defaults to false)
53532 forceSelection:false,
53534 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
53535 * if typeAhead = true (defaults to 250)
53537 typeAheadDelay : 250,
53539 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
53540 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
53542 valueNotFoundText : undefined,
53545 * @cfg {String} defaultValue The value displayed after loading the store.
53550 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
53552 blockFocus : false,
53555 * @cfg {Boolean} disableClear Disable showing of clear button.
53557 disableClear : false,
53559 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
53561 alwaysQuery : false,
53567 // element that contains real text value.. (when hidden is used..)
53570 onRender : function(ct, position){
53571 Roo.form.Field.prototype.onRender.call(this, ct, position);
53574 this.store.on('beforeload', this.onBeforeLoad, this);
53575 this.store.on('load', this.onLoad, this);
53576 this.store.on('loadexception', this.onLoadException, this);
53577 this.store.load({});
53585 initEvents : function(){
53586 //Roo.form.ComboBox.superclass.initEvents.call(this);
53590 onDestroy : function(){
53593 this.store.un('beforeload', this.onBeforeLoad, this);
53594 this.store.un('load', this.onLoad, this);
53595 this.store.un('loadexception', this.onLoadException, this);
53597 //Roo.form.ComboBox.superclass.onDestroy.call(this);
53601 fireKey : function(e){
53602 if(e.isNavKeyPress() && !this.list.isVisible()){
53603 this.fireEvent("specialkey", this, e);
53608 onResize: function(w, h){
53616 * Allow or prevent the user from directly editing the field text. If false is passed,
53617 * the user will only be able to select from the items defined in the dropdown list. This method
53618 * is the runtime equivalent of setting the 'editable' config option at config time.
53619 * @param {Boolean} value True to allow the user to directly edit the field text
53621 setEditable : function(value){
53626 onBeforeLoad : function(){
53628 Roo.log("Select before load");
53631 this.innerList.update(this.loadingText ?
53632 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
53633 //this.restrictHeight();
53634 this.selectedIndex = -1;
53638 onLoad : function(){
53641 var dom = this.el.dom;
53642 dom.innerHTML = '';
53643 var od = dom.ownerDocument;
53645 if (this.emptyText) {
53646 var op = od.createElement('option');
53647 op.setAttribute('value', '');
53648 op.innerHTML = String.format('{0}', this.emptyText);
53649 dom.appendChild(op);
53651 if(this.store.getCount() > 0){
53653 var vf = this.valueField;
53654 var df = this.displayField;
53655 this.store.data.each(function(r) {
53656 // which colmsn to use... testing - cdoe / title..
53657 var op = od.createElement('option');
53658 op.setAttribute('value', r.data[vf]);
53659 op.innerHTML = String.format('{0}', r.data[df]);
53660 dom.appendChild(op);
53662 if (typeof(this.defaultValue != 'undefined')) {
53663 this.setValue(this.defaultValue);
53668 //this.onEmptyResults();
53673 onLoadException : function()
53675 dom.innerHTML = '';
53677 Roo.log("Select on load exception");
53681 Roo.log(this.store.reader.jsonData);
53682 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
53683 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
53689 onTypeAhead : function(){
53694 onSelect : function(record, index){
53695 Roo.log('on select?');
53697 if(this.fireEvent('beforeselect', this, record, index) !== false){
53698 this.setFromData(index > -1 ? record.data : false);
53700 this.fireEvent('select', this, record, index);
53705 * Returns the currently selected field value or empty string if no value is set.
53706 * @return {String} value The selected value
53708 getValue : function(){
53709 var dom = this.el.dom;
53710 this.value = dom.options[dom.selectedIndex].value;
53716 * Clears any text/value currently set in the field
53718 clearValue : function(){
53720 this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
53725 * Sets the specified value into the field. If the value finds a match, the corresponding record text
53726 * will be displayed in the field. If the value does not match the data value of an existing item,
53727 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
53728 * Otherwise the field will be blank (although the value will still be set).
53729 * @param {String} value The value to match
53731 setValue : function(v){
53732 var d = this.el.dom;
53733 for (var i =0; i < d.options.length;i++) {
53734 if (v == d.options[i].value) {
53735 d.selectedIndex = i;
53743 * @property {Object} the last set data for the element
53748 * Sets the value of the field based on a object which is related to the record format for the store.
53749 * @param {Object} value the value to set as. or false on reset?
53751 setFromData : function(o){
53752 Roo.log('setfrom data?');
53758 reset : function(){
53762 findRecord : function(prop, value){
53767 if(this.store.getCount() > 0){
53768 this.store.each(function(r){
53769 if(r.data[prop] == value){
53779 getName: function()
53781 // returns hidden if it's set..
53782 if (!this.rendered) {return ''};
53783 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
53791 onEmptyResults : function(){
53792 Roo.log('empty results');
53797 * Returns true if the dropdown list is expanded, else false.
53799 isExpanded : function(){
53804 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
53805 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
53806 * @param {String} value The data value of the item to select
53807 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
53808 * selected item if it is not currently in view (defaults to true)
53809 * @return {Boolean} True if the value matched an item in the list, else false
53811 selectByValue : function(v, scrollIntoView){
53812 Roo.log('select By Value');
53815 if(v !== undefined && v !== null){
53816 var r = this.findRecord(this.valueField || this.displayField, v);
53818 this.select(this.store.indexOf(r), scrollIntoView);
53826 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
53827 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
53828 * @param {Number} index The zero-based index of the list item to select
53829 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
53830 * selected item if it is not currently in view (defaults to true)
53832 select : function(index, scrollIntoView){
53833 Roo.log('select ');
53836 this.selectedIndex = index;
53837 this.view.select(index);
53838 if(scrollIntoView !== false){
53839 var el = this.view.getNode(index);
53841 this.innerList.scrollChildIntoView(el, false);
53849 validateBlur : function(){
53856 initQuery : function(){
53857 this.doQuery(this.getRawValue());
53861 doForce : function(){
53862 if(this.el.dom.value.length > 0){
53863 this.el.dom.value =
53864 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
53870 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
53871 * query allowing the query action to be canceled if needed.
53872 * @param {String} query The SQL query to execute
53873 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
53874 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
53875 * saved in the current store (defaults to false)
53877 doQuery : function(q, forceAll){
53879 Roo.log('doQuery?');
53880 if(q === undefined || q === null){
53885 forceAll: forceAll,
53889 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
53893 forceAll = qe.forceAll;
53894 if(forceAll === true || (q.length >= this.minChars)){
53895 if(this.lastQuery != q || this.alwaysQuery){
53896 this.lastQuery = q;
53897 if(this.mode == 'local'){
53898 this.selectedIndex = -1;
53900 this.store.clearFilter();
53902 this.store.filter(this.displayField, q);
53906 this.store.baseParams[this.queryParam] = q;
53908 params: this.getParams(q)
53913 this.selectedIndex = -1;
53920 getParams : function(q){
53922 //p[this.queryParam] = q;
53925 p.limit = this.pageSize;
53931 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
53933 collapse : function(){
53938 collapseIf : function(e){
53943 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
53945 expand : function(){
53953 * @cfg {Boolean} grow
53957 * @cfg {Number} growMin
53961 * @cfg {Number} growMax
53969 setWidth : function()
53973 getResizeEl : function(){
53976 });//<script type="text/javasscript">
53980 * @class Roo.DDView
53981 * A DnD enabled version of Roo.View.
53982 * @param {Element/String} container The Element in which to create the View.
53983 * @param {String} tpl The template string used to create the markup for each element of the View
53984 * @param {Object} config The configuration properties. These include all the config options of
53985 * {@link Roo.View} plus some specific to this class.<br>
53987 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
53988 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
53990 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
53991 .x-view-drag-insert-above {
53992 border-top:1px dotted #3366cc;
53994 .x-view-drag-insert-below {
53995 border-bottom:1px dotted #3366cc;
54001 Roo.DDView = function(container, tpl, config) {
54002 Roo.DDView.superclass.constructor.apply(this, arguments);
54003 this.getEl().setStyle("outline", "0px none");
54004 this.getEl().unselectable();
54005 if (this.dragGroup) {
54006 this.setDraggable(this.dragGroup.split(","));
54008 if (this.dropGroup) {
54009 this.setDroppable(this.dropGroup.split(","));
54011 if (this.deletable) {
54012 this.setDeletable();
54014 this.isDirtyFlag = false;
54020 Roo.extend(Roo.DDView, Roo.View, {
54021 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
54022 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
54023 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
54024 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
54028 reset: Roo.emptyFn,
54030 clearInvalid: Roo.form.Field.prototype.clearInvalid,
54032 validate: function() {
54036 destroy: function() {
54037 this.purgeListeners();
54038 this.getEl.removeAllListeners();
54039 this.getEl().remove();
54040 if (this.dragZone) {
54041 if (this.dragZone.destroy) {
54042 this.dragZone.destroy();
54045 if (this.dropZone) {
54046 if (this.dropZone.destroy) {
54047 this.dropZone.destroy();
54052 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
54053 getName: function() {
54057 /** Loads the View from a JSON string representing the Records to put into the Store. */
54058 setValue: function(v) {
54060 throw "DDView.setValue(). DDView must be constructed with a valid Store";
54063 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
54064 this.store.proxy = new Roo.data.MemoryProxy(data);
54068 /** @return {String} a parenthesised list of the ids of the Records in the View. */
54069 getValue: function() {
54071 this.store.each(function(rec) {
54072 result += rec.id + ',';
54074 return result.substr(0, result.length - 1) + ')';
54077 getIds: function() {
54078 var i = 0, result = new Array(this.store.getCount());
54079 this.store.each(function(rec) {
54080 result[i++] = rec.id;
54085 isDirty: function() {
54086 return this.isDirtyFlag;
54090 * Part of the Roo.dd.DropZone interface. If no target node is found, the
54091 * whole Element becomes the target, and this causes the drop gesture to append.
54093 getTargetFromEvent : function(e) {
54094 var target = e.getTarget();
54095 while ((target !== null) && (target.parentNode != this.el.dom)) {
54096 target = target.parentNode;
54099 target = this.el.dom.lastChild || this.el.dom;
54105 * Create the drag data which consists of an object which has the property "ddel" as
54106 * the drag proxy element.
54108 getDragData : function(e) {
54109 var target = this.findItemFromChild(e.getTarget());
54111 this.handleSelection(e);
54112 var selNodes = this.getSelectedNodes();
54115 copy: this.copy || (this.allowCopy && e.ctrlKey),
54119 var selectedIndices = this.getSelectedIndexes();
54120 for (var i = 0; i < selectedIndices.length; i++) {
54121 dragData.records.push(this.store.getAt(selectedIndices[i]));
54123 if (selNodes.length == 1) {
54124 dragData.ddel = target.cloneNode(true); // the div element
54126 var div = document.createElement('div'); // create the multi element drag "ghost"
54127 div.className = 'multi-proxy';
54128 for (var i = 0, len = selNodes.length; i < len; i++) {
54129 div.appendChild(selNodes[i].cloneNode(true));
54131 dragData.ddel = div;
54133 //console.log(dragData)
54134 //console.log(dragData.ddel.innerHTML)
54137 //console.log('nodragData')
54141 /** Specify to which ddGroup items in this DDView may be dragged. */
54142 setDraggable: function(ddGroup) {
54143 if (ddGroup instanceof Array) {
54144 Roo.each(ddGroup, this.setDraggable, this);
54147 if (this.dragZone) {
54148 this.dragZone.addToGroup(ddGroup);
54150 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
54151 containerScroll: true,
54155 // Draggability implies selection. DragZone's mousedown selects the element.
54156 if (!this.multiSelect) { this.singleSelect = true; }
54158 // Wire the DragZone's handlers up to methods in *this*
54159 this.dragZone.getDragData = this.getDragData.createDelegate(this);
54163 /** Specify from which ddGroup this DDView accepts drops. */
54164 setDroppable: function(ddGroup) {
54165 if (ddGroup instanceof Array) {
54166 Roo.each(ddGroup, this.setDroppable, this);
54169 if (this.dropZone) {
54170 this.dropZone.addToGroup(ddGroup);
54172 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
54173 containerScroll: true,
54177 // Wire the DropZone's handlers up to methods in *this*
54178 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
54179 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
54180 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
54181 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
54182 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
54186 /** Decide whether to drop above or below a View node. */
54187 getDropPoint : function(e, n, dd){
54188 if (n == this.el.dom) { return "above"; }
54189 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
54190 var c = t + (b - t) / 2;
54191 var y = Roo.lib.Event.getPageY(e);
54199 onNodeEnter : function(n, dd, e, data){
54203 onNodeOver : function(n, dd, e, data){
54204 var pt = this.getDropPoint(e, n, dd);
54205 // set the insert point style on the target node
54206 var dragElClass = this.dropNotAllowed;
54209 if (pt == "above"){
54210 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
54211 targetElClass = "x-view-drag-insert-above";
54213 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
54214 targetElClass = "x-view-drag-insert-below";
54216 if (this.lastInsertClass != targetElClass){
54217 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
54218 this.lastInsertClass = targetElClass;
54221 return dragElClass;
54224 onNodeOut : function(n, dd, e, data){
54225 this.removeDropIndicators(n);
54228 onNodeDrop : function(n, dd, e, data){
54229 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
54232 var pt = this.getDropPoint(e, n, dd);
54233 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
54234 if (pt == "below") { insertAt++; }
54235 for (var i = 0; i < data.records.length; i++) {
54236 var r = data.records[i];
54237 var dup = this.store.getById(r.id);
54238 if (dup && (dd != this.dragZone)) {
54239 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
54242 this.store.insert(insertAt++, r.copy());
54244 data.source.isDirtyFlag = true;
54246 this.store.insert(insertAt++, r);
54248 this.isDirtyFlag = true;
54251 this.dragZone.cachedTarget = null;
54255 removeDropIndicators : function(n){
54257 Roo.fly(n).removeClass([
54258 "x-view-drag-insert-above",
54259 "x-view-drag-insert-below"]);
54260 this.lastInsertClass = "_noclass";
54265 * Utility method. Add a delete option to the DDView's context menu.
54266 * @param {String} imageUrl The URL of the "delete" icon image.
54268 setDeletable: function(imageUrl) {
54269 if (!this.singleSelect && !this.multiSelect) {
54270 this.singleSelect = true;
54272 var c = this.getContextMenu();
54273 this.contextMenu.on("itemclick", function(item) {
54276 this.remove(this.getSelectedIndexes());
54280 this.contextMenu.add({
54287 /** Return the context menu for this DDView. */
54288 getContextMenu: function() {
54289 if (!this.contextMenu) {
54290 // Create the View's context menu
54291 this.contextMenu = new Roo.menu.Menu({
54292 id: this.id + "-contextmenu"
54294 this.el.on("contextmenu", this.showContextMenu, this);
54296 return this.contextMenu;
54299 disableContextMenu: function() {
54300 if (this.contextMenu) {
54301 this.el.un("contextmenu", this.showContextMenu, this);
54305 showContextMenu: function(e, item) {
54306 item = this.findItemFromChild(e.getTarget());
54309 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
54310 this.contextMenu.showAt(e.getXY());
54315 * Remove {@link Roo.data.Record}s at the specified indices.
54316 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
54318 remove: function(selectedIndices) {
54319 selectedIndices = [].concat(selectedIndices);
54320 for (var i = 0; i < selectedIndices.length; i++) {
54321 var rec = this.store.getAt(selectedIndices[i]);
54322 this.store.remove(rec);
54327 * Double click fires the event, but also, if this is draggable, and there is only one other
54328 * related DropZone, it transfers the selected node.
54330 onDblClick : function(e){
54331 var item = this.findItemFromChild(e.getTarget());
54333 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
54336 if (this.dragGroup) {
54337 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
54338 while (targets.indexOf(this.dropZone) > -1) {
54339 targets.remove(this.dropZone);
54341 if (targets.length == 1) {
54342 this.dragZone.cachedTarget = null;
54343 var el = Roo.get(targets[0].getEl());
54344 var box = el.getBox(true);
54345 targets[0].onNodeDrop(el.dom, {
54347 xy: [box.x, box.y + box.height - 1]
54348 }, null, this.getDragData(e));
54354 handleSelection: function(e) {
54355 this.dragZone.cachedTarget = null;
54356 var item = this.findItemFromChild(e.getTarget());
54358 this.clearSelections(true);
54361 if (item && (this.multiSelect || this.singleSelect)){
54362 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
54363 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
54364 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
54365 this.unselect(item);
54367 this.select(item, this.multiSelect && e.ctrlKey);
54368 this.lastSelection = item;
54373 onItemClick : function(item, index, e){
54374 if(this.fireEvent("beforeclick", this, index, item, e) === false){
54380 unselect : function(nodeInfo, suppressEvent){
54381 var node = this.getNode(nodeInfo);
54382 if(node && this.isSelected(node)){
54383 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
54384 Roo.fly(node).removeClass(this.selectedClass);
54385 this.selections.remove(node);
54386 if(!suppressEvent){
54387 this.fireEvent("selectionchange", this, this.selections);
54395 * Ext JS Library 1.1.1
54396 * Copyright(c) 2006-2007, Ext JS, LLC.
54398 * Originally Released Under LGPL - original licence link has changed is not relivant.
54401 * <script type="text/javascript">
54405 * @class Roo.LayoutManager
54406 * @extends Roo.util.Observable
54407 * Base class for layout managers.
54409 Roo.LayoutManager = function(container, config){
54410 Roo.LayoutManager.superclass.constructor.call(this);
54411 this.el = Roo.get(container);
54412 // ie scrollbar fix
54413 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
54414 document.body.scroll = "no";
54415 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
54416 this.el.position('relative');
54418 this.id = this.el.id;
54419 this.el.addClass("x-layout-container");
54420 /** false to disable window resize monitoring @type Boolean */
54421 this.monitorWindowResize = true;
54426 * Fires when a layout is performed.
54427 * @param {Roo.LayoutManager} this
54431 * @event regionresized
54432 * Fires when the user resizes a region.
54433 * @param {Roo.LayoutRegion} region The resized region
54434 * @param {Number} newSize The new size (width for east/west, height for north/south)
54436 "regionresized" : true,
54438 * @event regioncollapsed
54439 * Fires when a region is collapsed.
54440 * @param {Roo.LayoutRegion} region The collapsed region
54442 "regioncollapsed" : true,
54444 * @event regionexpanded
54445 * Fires when a region is expanded.
54446 * @param {Roo.LayoutRegion} region The expanded region
54448 "regionexpanded" : true
54450 this.updating = false;
54451 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
54454 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
54456 * Returns true if this layout is currently being updated
54457 * @return {Boolean}
54459 isUpdating : function(){
54460 return this.updating;
54464 * Suspend the LayoutManager from doing auto-layouts while
54465 * making multiple add or remove calls
54467 beginUpdate : function(){
54468 this.updating = true;
54472 * Restore auto-layouts and optionally disable the manager from performing a layout
54473 * @param {Boolean} noLayout true to disable a layout update
54475 endUpdate : function(noLayout){
54476 this.updating = false;
54482 layout: function(){
54486 onRegionResized : function(region, newSize){
54487 this.fireEvent("regionresized", region, newSize);
54491 onRegionCollapsed : function(region){
54492 this.fireEvent("regioncollapsed", region);
54495 onRegionExpanded : function(region){
54496 this.fireEvent("regionexpanded", region);
54500 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
54501 * performs box-model adjustments.
54502 * @return {Object} The size as an object {width: (the width), height: (the height)}
54504 getViewSize : function(){
54506 if(this.el.dom != document.body){
54507 size = this.el.getSize();
54509 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
54511 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
54512 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
54517 * Returns the Element this layout is bound to.
54518 * @return {Roo.Element}
54520 getEl : function(){
54525 * Returns the specified region.
54526 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
54527 * @return {Roo.LayoutRegion}
54529 getRegion : function(target){
54530 return this.regions[target.toLowerCase()];
54533 onWindowResize : function(){
54534 if(this.monitorWindowResize){
54540 * Ext JS Library 1.1.1
54541 * Copyright(c) 2006-2007, Ext JS, LLC.
54543 * Originally Released Under LGPL - original licence link has changed is not relivant.
54546 * <script type="text/javascript">
54549 * @class Roo.BorderLayout
54550 * @extends Roo.LayoutManager
54551 * @children Roo.ContentPanel
54552 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
54553 * please see: <br><br>
54554 * <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>
54555 * <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>
54558 var layout = new Roo.BorderLayout(document.body, {
54592 preferredTabWidth: 150
54597 var CP = Roo.ContentPanel;
54599 layout.beginUpdate();
54600 layout.add("north", new CP("north", "North"));
54601 layout.add("south", new CP("south", {title: "South", closable: true}));
54602 layout.add("west", new CP("west", {title: "West"}));
54603 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
54604 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
54605 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
54606 layout.getRegion("center").showPanel("center1");
54607 layout.endUpdate();
54610 <b>The container the layout is rendered into can be either the body element or any other element.
54611 If it is not the body element, the container needs to either be an absolute positioned element,
54612 or you will need to add "position:relative" to the css of the container. You will also need to specify
54613 the container size if it is not the body element.</b>
54616 * Create a new BorderLayout
54617 * @param {String/HTMLElement/Element} container The container this layout is bound to
54618 * @param {Object} config Configuration options
54620 Roo.BorderLayout = function(container, config){
54621 config = config || {};
54622 Roo.BorderLayout.superclass.constructor.call(this, container, config);
54623 this.factory = config.factory || Roo.BorderLayout.RegionFactory;
54624 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
54625 var target = this.factory.validRegions[i];
54626 if(config[target]){
54627 this.addRegion(target, config[target]);
54632 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
54635 * @cfg {Roo.LayoutRegion} east
54638 * @cfg {Roo.LayoutRegion} west
54641 * @cfg {Roo.LayoutRegion} north
54644 * @cfg {Roo.LayoutRegion} south
54647 * @cfg {Roo.LayoutRegion} center
54650 * Creates and adds a new region if it doesn't already exist.
54651 * @param {String} target The target region key (north, south, east, west or center).
54652 * @param {Object} config The regions config object
54653 * @return {BorderLayoutRegion} The new region
54655 addRegion : function(target, config){
54656 if(!this.regions[target]){
54657 var r = this.factory.create(target, this, config);
54658 this.bindRegion(target, r);
54660 return this.regions[target];
54664 bindRegion : function(name, r){
54665 this.regions[name] = r;
54666 r.on("visibilitychange", this.layout, this);
54667 r.on("paneladded", this.layout, this);
54668 r.on("panelremoved", this.layout, this);
54669 r.on("invalidated", this.layout, this);
54670 r.on("resized", this.onRegionResized, this);
54671 r.on("collapsed", this.onRegionCollapsed, this);
54672 r.on("expanded", this.onRegionExpanded, this);
54676 * Performs a layout update.
54678 layout : function(){
54679 if(this.updating) {
54682 var size = this.getViewSize();
54683 var w = size.width;
54684 var h = size.height;
54689 //var x = 0, y = 0;
54691 var rs = this.regions;
54692 var north = rs["north"];
54693 var south = rs["south"];
54694 var west = rs["west"];
54695 var east = rs["east"];
54696 var center = rs["center"];
54697 //if(this.hideOnLayout){ // not supported anymore
54698 //c.el.setStyle("display", "none");
54700 if(north && north.isVisible()){
54701 var b = north.getBox();
54702 var m = north.getMargins();
54703 b.width = w - (m.left+m.right);
54706 centerY = b.height + b.y + m.bottom;
54707 centerH -= centerY;
54708 north.updateBox(this.safeBox(b));
54710 if(south && south.isVisible()){
54711 var b = south.getBox();
54712 var m = south.getMargins();
54713 b.width = w - (m.left+m.right);
54715 var totalHeight = (b.height + m.top + m.bottom);
54716 b.y = h - totalHeight + m.top;
54717 centerH -= totalHeight;
54718 south.updateBox(this.safeBox(b));
54720 if(west && west.isVisible()){
54721 var b = west.getBox();
54722 var m = west.getMargins();
54723 b.height = centerH - (m.top+m.bottom);
54725 b.y = centerY + m.top;
54726 var totalWidth = (b.width + m.left + m.right);
54727 centerX += totalWidth;
54728 centerW -= totalWidth;
54729 west.updateBox(this.safeBox(b));
54731 if(east && east.isVisible()){
54732 var b = east.getBox();
54733 var m = east.getMargins();
54734 b.height = centerH - (m.top+m.bottom);
54735 var totalWidth = (b.width + m.left + m.right);
54736 b.x = w - totalWidth + m.left;
54737 b.y = centerY + m.top;
54738 centerW -= totalWidth;
54739 east.updateBox(this.safeBox(b));
54742 var m = center.getMargins();
54744 x: centerX + m.left,
54745 y: centerY + m.top,
54746 width: centerW - (m.left+m.right),
54747 height: centerH - (m.top+m.bottom)
54749 //if(this.hideOnLayout){
54750 //center.el.setStyle("display", "block");
54752 center.updateBox(this.safeBox(centerBox));
54755 this.fireEvent("layout", this);
54759 safeBox : function(box){
54760 box.width = Math.max(0, box.width);
54761 box.height = Math.max(0, box.height);
54766 * Adds a ContentPanel (or subclass) to this layout.
54767 * @param {String} target The target region key (north, south, east, west or center).
54768 * @param {Roo.ContentPanel} panel The panel to add
54769 * @return {Roo.ContentPanel} The added panel
54771 add : function(target, panel){
54773 target = target.toLowerCase();
54774 return this.regions[target].add(panel);
54778 * Remove a ContentPanel (or subclass) to this layout.
54779 * @param {String} target The target region key (north, south, east, west or center).
54780 * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
54781 * @return {Roo.ContentPanel} The removed panel
54783 remove : function(target, panel){
54784 target = target.toLowerCase();
54785 return this.regions[target].remove(panel);
54789 * Searches all regions for a panel with the specified id
54790 * @param {String} panelId
54791 * @return {Roo.ContentPanel} The panel or null if it wasn't found
54793 findPanel : function(panelId){
54794 var rs = this.regions;
54795 for(var target in rs){
54796 if(typeof rs[target] != "function"){
54797 var p = rs[target].getPanel(panelId);
54807 * Searches all regions for a panel with the specified id and activates (shows) it.
54808 * @param {String/ContentPanel} panelId The panels id or the panel itself
54809 * @return {Roo.ContentPanel} The shown panel or null
54811 showPanel : function(panelId) {
54812 var rs = this.regions;
54813 for(var target in rs){
54814 var r = rs[target];
54815 if(typeof r != "function"){
54816 if(r.hasPanel(panelId)){
54817 return r.showPanel(panelId);
54825 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
54826 * @param {Roo.state.Provider} provider (optional) An alternate state provider
54828 restoreState : function(provider){
54830 provider = Roo.state.Manager;
54832 var sm = new Roo.LayoutStateManager();
54833 sm.init(this, provider);
54837 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
54838 * object should contain properties for each region to add ContentPanels to, and each property's value should be
54839 * a valid ContentPanel config object. Example:
54841 // Create the main layout
54842 var layout = new Roo.BorderLayout('main-ct', {
54853 // Create and add multiple ContentPanels at once via configs
54856 id: 'source-files',
54858 title:'Ext Source Files',
54871 * @param {Object} regions An object containing ContentPanel configs by region name
54873 batchAdd : function(regions){
54874 this.beginUpdate();
54875 for(var rname in regions){
54876 var lr = this.regions[rname];
54878 this.addTypedPanels(lr, regions[rname]);
54885 addTypedPanels : function(lr, ps){
54886 if(typeof ps == 'string'){
54887 lr.add(new Roo.ContentPanel(ps));
54889 else if(ps instanceof Array){
54890 for(var i =0, len = ps.length; i < len; i++){
54891 this.addTypedPanels(lr, ps[i]);
54894 else if(!ps.events){ // raw config?
54896 delete ps.el; // prevent conflict
54897 lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
54899 else { // panel object assumed!
54904 * Adds a xtype elements to the layout.
54908 xtype : 'ContentPanel',
54915 xtype : 'NestedLayoutPanel',
54921 items : [ ... list of content panels or nested layout panels.. ]
54925 * @param {Object} cfg Xtype definition of item to add.
54927 addxtype : function(cfg)
54929 // basically accepts a pannel...
54930 // can accept a layout region..!?!?
54931 //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
54933 if (!cfg.xtype.match(/Panel$/)) {
54938 if (typeof(cfg.region) == 'undefined') {
54939 Roo.log("Failed to add Panel, region was not set");
54943 var region = cfg.region;
54949 xitems = cfg.items;
54956 case 'ContentPanel': // ContentPanel (el, cfg)
54957 case 'ScrollPanel': // ContentPanel (el, cfg)
54959 if(cfg.autoCreate) {
54960 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
54962 var el = this.el.createChild();
54963 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
54966 this.add(region, ret);
54970 case 'TreePanel': // our new panel!
54971 cfg.el = this.el.createChild();
54972 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
54973 this.add(region, ret);
54976 case 'NestedLayoutPanel':
54977 // create a new Layout (which is a Border Layout...
54978 var el = this.el.createChild();
54979 var clayout = cfg.layout;
54981 clayout.items = clayout.items || [];
54982 // replace this exitems with the clayout ones..
54983 xitems = clayout.items;
54986 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
54987 cfg.background = false;
54989 var layout = new Roo.BorderLayout(el, clayout);
54991 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
54992 //console.log('adding nested layout panel ' + cfg.toSource());
54993 this.add(region, ret);
54994 nb = {}; /// find first...
54999 // needs grid and region
55001 //var el = this.getRegion(region).el.createChild();
55002 var el = this.el.createChild();
55003 // create the grid first...
55005 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
55007 if (region == 'center' && this.active ) {
55008 cfg.background = false;
55010 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
55012 this.add(region, ret);
55013 if (cfg.background) {
55014 ret.on('activate', function(gp) {
55015 if (!gp.grid.rendered) {
55030 if (typeof(Roo[cfg.xtype]) != 'undefined') {
55032 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
55033 this.add(region, ret);
55036 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
55040 // GridPanel (grid, cfg)
55043 this.beginUpdate();
55047 Roo.each(xitems, function(i) {
55048 region = nb && i.region ? i.region : false;
55050 var add = ret.addxtype(i);
55053 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
55054 if (!i.background) {
55055 abn[region] = nb[region] ;
55062 // make the last non-background panel active..
55063 //if (nb) { Roo.log(abn); }
55066 for(var r in abn) {
55067 region = this.getRegion(r);
55069 // tried using nb[r], but it does not work..
55071 region.showPanel(abn[r]);
55082 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
55083 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
55084 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
55085 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
55088 var CP = Roo.ContentPanel;
55090 var layout = Roo.BorderLayout.create({
55094 panels: [new CP("north", "North")]
55103 panels: [new CP("west", {title: "West"})]
55112 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
55121 panels: [new CP("south", {title: "South", closable: true})]
55128 preferredTabWidth: 150,
55130 new CP("center1", {title: "Close Me", closable: true}),
55131 new CP("center2", {title: "Center Panel", closable: false})
55136 layout.getRegion("center").showPanel("center1");
55141 Roo.BorderLayout.create = function(config, targetEl){
55142 var layout = new Roo.BorderLayout(targetEl || document.body, config);
55143 layout.beginUpdate();
55144 var regions = Roo.BorderLayout.RegionFactory.validRegions;
55145 for(var j = 0, jlen = regions.length; j < jlen; j++){
55146 var lr = regions[j];
55147 if(layout.regions[lr] && config[lr].panels){
55148 var r = layout.regions[lr];
55149 var ps = config[lr].panels;
55150 layout.addTypedPanels(r, ps);
55153 layout.endUpdate();
55158 Roo.BorderLayout.RegionFactory = {
55160 validRegions : ["north","south","east","west","center"],
55163 create : function(target, mgr, config){
55164 target = target.toLowerCase();
55165 if(config.lightweight || config.basic){
55166 return new Roo.BasicLayoutRegion(mgr, config, target);
55170 return new Roo.NorthLayoutRegion(mgr, config);
55172 return new Roo.SouthLayoutRegion(mgr, config);
55174 return new Roo.EastLayoutRegion(mgr, config);
55176 return new Roo.WestLayoutRegion(mgr, config);
55178 return new Roo.CenterLayoutRegion(mgr, config);
55180 throw 'Layout region "'+target+'" not supported.';
55184 * Ext JS Library 1.1.1
55185 * Copyright(c) 2006-2007, Ext JS, LLC.
55187 * Originally Released Under LGPL - original licence link has changed is not relivant.
55190 * <script type="text/javascript">
55194 * @class Roo.BasicLayoutRegion
55195 * @extends Roo.util.Observable
55196 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
55197 * and does not have a titlebar, tabs or any other features. All it does is size and position
55198 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
55200 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
55202 this.position = pos;
55205 * @scope Roo.BasicLayoutRegion
55209 * @event beforeremove
55210 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
55211 * @param {Roo.LayoutRegion} this
55212 * @param {Roo.ContentPanel} panel The panel
55213 * @param {Object} e The cancel event object
55215 "beforeremove" : true,
55217 * @event invalidated
55218 * Fires when the layout for this region is changed.
55219 * @param {Roo.LayoutRegion} this
55221 "invalidated" : true,
55223 * @event visibilitychange
55224 * Fires when this region is shown or hidden
55225 * @param {Roo.LayoutRegion} this
55226 * @param {Boolean} visibility true or false
55228 "visibilitychange" : true,
55230 * @event paneladded
55231 * Fires when a panel is added.
55232 * @param {Roo.LayoutRegion} this
55233 * @param {Roo.ContentPanel} panel The panel
55235 "paneladded" : true,
55237 * @event panelremoved
55238 * Fires when a panel is removed.
55239 * @param {Roo.LayoutRegion} this
55240 * @param {Roo.ContentPanel} panel The panel
55242 "panelremoved" : true,
55244 * @event beforecollapse
55245 * Fires when this region before collapse.
55246 * @param {Roo.LayoutRegion} this
55248 "beforecollapse" : true,
55251 * Fires when this region is collapsed.
55252 * @param {Roo.LayoutRegion} this
55254 "collapsed" : true,
55257 * Fires when this region is expanded.
55258 * @param {Roo.LayoutRegion} this
55263 * Fires when this region is slid into view.
55264 * @param {Roo.LayoutRegion} this
55266 "slideshow" : true,
55269 * Fires when this region slides out of view.
55270 * @param {Roo.LayoutRegion} this
55272 "slidehide" : true,
55274 * @event panelactivated
55275 * Fires when a panel is activated.
55276 * @param {Roo.LayoutRegion} this
55277 * @param {Roo.ContentPanel} panel The activated panel
55279 "panelactivated" : true,
55282 * Fires when the user resizes this region.
55283 * @param {Roo.LayoutRegion} this
55284 * @param {Number} newSize The new size (width for east/west, height for north/south)
55288 /** A collection of panels in this region. @type Roo.util.MixedCollection */
55289 this.panels = new Roo.util.MixedCollection();
55290 this.panels.getKey = this.getPanelId.createDelegate(this);
55292 this.activePanel = null;
55293 // ensure listeners are added...
55295 if (config.listeners || config.events) {
55296 Roo.BasicLayoutRegion.superclass.constructor.call(this, {
55297 listeners : config.listeners || {},
55298 events : config.events || {}
55302 if(skipConfig !== true){
55303 this.applyConfig(config);
55307 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
55308 getPanelId : function(p){
55312 applyConfig : function(config){
55313 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
55314 this.config = config;
55319 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
55320 * the width, for horizontal (north, south) the height.
55321 * @param {Number} newSize The new width or height
55323 resizeTo : function(newSize){
55324 var el = this.el ? this.el :
55325 (this.activePanel ? this.activePanel.getEl() : null);
55327 switch(this.position){
55330 el.setWidth(newSize);
55331 this.fireEvent("resized", this, newSize);
55335 el.setHeight(newSize);
55336 this.fireEvent("resized", this, newSize);
55342 getBox : function(){
55343 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
55346 getMargins : function(){
55347 return this.margins;
55350 updateBox : function(box){
55352 var el = this.activePanel.getEl();
55353 el.dom.style.left = box.x + "px";
55354 el.dom.style.top = box.y + "px";
55355 this.activePanel.setSize(box.width, box.height);
55359 * Returns the container element for this region.
55360 * @return {Roo.Element}
55362 getEl : function(){
55363 return this.activePanel;
55367 * Returns true if this region is currently visible.
55368 * @return {Boolean}
55370 isVisible : function(){
55371 return this.activePanel ? true : false;
55374 setActivePanel : function(panel){
55375 panel = this.getPanel(panel);
55376 if(this.activePanel && this.activePanel != panel){
55377 this.activePanel.setActiveState(false);
55378 this.activePanel.getEl().setLeftTop(-10000,-10000);
55380 this.activePanel = panel;
55381 panel.setActiveState(true);
55383 panel.setSize(this.box.width, this.box.height);
55385 this.fireEvent("panelactivated", this, panel);
55386 this.fireEvent("invalidated");
55390 * Show the specified panel.
55391 * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
55392 * @return {Roo.ContentPanel} The shown panel or null
55394 showPanel : function(panel){
55395 if(panel = this.getPanel(panel)){
55396 this.setActivePanel(panel);
55402 * Get the active panel for this region.
55403 * @return {Roo.ContentPanel} The active panel or null
55405 getActivePanel : function(){
55406 return this.activePanel;
55410 * Add the passed ContentPanel(s)
55411 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
55412 * @return {Roo.ContentPanel} The panel added (if only one was added)
55414 add : function(panel){
55415 if(arguments.length > 1){
55416 for(var i = 0, len = arguments.length; i < len; i++) {
55417 this.add(arguments[i]);
55421 if(this.hasPanel(panel)){
55422 this.showPanel(panel);
55425 var el = panel.getEl();
55426 if(el.dom.parentNode != this.mgr.el.dom){
55427 this.mgr.el.dom.appendChild(el.dom);
55429 if(panel.setRegion){
55430 panel.setRegion(this);
55432 this.panels.add(panel);
55433 el.setStyle("position", "absolute");
55434 if(!panel.background){
55435 this.setActivePanel(panel);
55436 if(this.config.initialSize && this.panels.getCount()==1){
55437 this.resizeTo(this.config.initialSize);
55440 this.fireEvent("paneladded", this, panel);
55445 * Returns true if the panel is in this region.
55446 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
55447 * @return {Boolean}
55449 hasPanel : function(panel){
55450 if(typeof panel == "object"){ // must be panel obj
55451 panel = panel.getId();
55453 return this.getPanel(panel) ? true : false;
55457 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
55458 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
55459 * @param {Boolean} preservePanel Overrides the config preservePanel option
55460 * @return {Roo.ContentPanel} The panel that was removed
55462 remove : function(panel, preservePanel){
55463 panel = this.getPanel(panel);
55468 this.fireEvent("beforeremove", this, panel, e);
55469 if(e.cancel === true){
55472 var panelId = panel.getId();
55473 this.panels.removeKey(panelId);
55478 * Returns the panel specified or null if it's not in this region.
55479 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
55480 * @return {Roo.ContentPanel}
55482 getPanel : function(id){
55483 if(typeof id == "object"){ // must be panel obj
55486 return this.panels.get(id);
55490 * Returns this regions position (north/south/east/west/center).
55493 getPosition: function(){
55494 return this.position;
55498 * Ext JS Library 1.1.1
55499 * Copyright(c) 2006-2007, Ext JS, LLC.
55501 * Originally Released Under LGPL - original licence link has changed is not relivant.
55504 * <script type="text/javascript">
55508 * @class Roo.LayoutRegion
55509 * @extends Roo.BasicLayoutRegion
55510 * This class represents a region in a layout manager.
55511 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
55512 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
55513 * @cfg {Boolean} floatable False to disable floating (defaults to true)
55514 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
55515 * @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})
55516 * @cfg {String} tabPosition (top|bottom) "top" or "bottom" (defaults to "bottom")
55517 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
55518 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
55519 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
55520 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
55521 * @cfg {String} title The title for the region (overrides panel titles)
55522 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
55523 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
55524 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
55525 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
55526 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
55527 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
55528 * the space available, similar to FireFox 1.5 tabs (defaults to false)
55529 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
55530 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
55531 * @cfg {Boolean} showPin True to show a pin button
55532 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
55533 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
55534 * @cfg {Boolean} disableTabTips True to disable tab tooltips
55535 * @cfg {Number} width For East/West panels
55536 * @cfg {Number} height For North/South panels
55537 * @cfg {Boolean} split To show the splitter
55538 * @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
55540 Roo.LayoutRegion = function(mgr, config, pos){
55541 Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
55542 var dh = Roo.DomHelper;
55543 /** This region's container element
55544 * @type Roo.Element */
55545 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
55546 /** This region's title element
55547 * @type Roo.Element */
55549 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
55550 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
55551 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
55553 this.titleEl.enableDisplayMode();
55554 /** This region's title text element
55555 * @type HTMLElement */
55556 this.titleTextEl = this.titleEl.dom.firstChild;
55557 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
55558 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
55559 this.closeBtn.enableDisplayMode();
55560 this.closeBtn.on("click", this.closeClicked, this);
55561 this.closeBtn.hide();
55563 this.createBody(config);
55564 this.visible = true;
55565 this.collapsed = false;
55567 if(config.hideWhenEmpty){
55569 this.on("paneladded", this.validateVisibility, this);
55570 this.on("panelremoved", this.validateVisibility, this);
55572 this.applyConfig(config);
55575 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
55577 createBody : function(){
55578 /** This region's body element
55579 * @type Roo.Element */
55580 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
55583 applyConfig : function(c){
55584 if(c.collapsible && this.position != "center" && !this.collapsedEl){
55585 var dh = Roo.DomHelper;
55586 if(c.titlebar !== false){
55587 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
55588 this.collapseBtn.on("click", this.collapse, this);
55589 this.collapseBtn.enableDisplayMode();
55591 if(c.showPin === true || this.showPin){
55592 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
55593 this.stickBtn.enableDisplayMode();
55594 this.stickBtn.on("click", this.expand, this);
55595 this.stickBtn.hide();
55598 /** This region's collapsed element
55599 * @type Roo.Element */
55600 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
55601 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
55603 if(c.floatable !== false){
55604 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
55605 this.collapsedEl.on("click", this.collapseClick, this);
55608 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
55609 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
55610 id: "message", unselectable: "on", style:{"float":"left"}});
55611 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
55613 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
55614 this.expandBtn.on("click", this.expand, this);
55616 if(this.collapseBtn){
55617 this.collapseBtn.setVisible(c.collapsible == true);
55619 this.cmargins = c.cmargins || this.cmargins ||
55620 (this.position == "west" || this.position == "east" ?
55621 {top: 0, left: 2, right:2, bottom: 0} :
55622 {top: 2, left: 0, right:0, bottom: 2});
55623 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
55624 this.bottomTabs = c.tabPosition != "top";
55625 this.autoScroll = c.autoScroll || false;
55626 if(this.autoScroll){
55627 this.bodyEl.setStyle("overflow", "auto");
55629 this.bodyEl.setStyle("overflow", "hidden");
55631 //if(c.titlebar !== false){
55632 if((!c.titlebar && !c.title) || c.titlebar === false){
55633 this.titleEl.hide();
55635 this.titleEl.show();
55637 this.titleTextEl.innerHTML = c.title;
55641 this.duration = c.duration || .30;
55642 this.slideDuration = c.slideDuration || .45;
55645 this.collapse(true);
55652 * Returns true if this region is currently visible.
55653 * @return {Boolean}
55655 isVisible : function(){
55656 return this.visible;
55660 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
55661 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
55663 setCollapsedTitle : function(title){
55664 title = title || " ";
55665 if(this.collapsedTitleTextEl){
55666 this.collapsedTitleTextEl.innerHTML = title;
55670 getBox : function(){
55672 if(!this.collapsed){
55673 b = this.el.getBox(false, true);
55675 b = this.collapsedEl.getBox(false, true);
55680 getMargins : function(){
55681 return this.collapsed ? this.cmargins : this.margins;
55684 highlight : function(){
55685 this.el.addClass("x-layout-panel-dragover");
55688 unhighlight : function(){
55689 this.el.removeClass("x-layout-panel-dragover");
55692 updateBox : function(box){
55694 if(!this.collapsed){
55695 this.el.dom.style.left = box.x + "px";
55696 this.el.dom.style.top = box.y + "px";
55697 this.updateBody(box.width, box.height);
55699 this.collapsedEl.dom.style.left = box.x + "px";
55700 this.collapsedEl.dom.style.top = box.y + "px";
55701 this.collapsedEl.setSize(box.width, box.height);
55704 this.tabs.autoSizeTabs();
55708 updateBody : function(w, h){
55710 this.el.setWidth(w);
55711 w -= this.el.getBorderWidth("rl");
55712 if(this.config.adjustments){
55713 w += this.config.adjustments[0];
55717 this.el.setHeight(h);
55718 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
55719 h -= this.el.getBorderWidth("tb");
55720 if(this.config.adjustments){
55721 h += this.config.adjustments[1];
55723 this.bodyEl.setHeight(h);
55725 h = this.tabs.syncHeight(h);
55728 if(this.panelSize){
55729 w = w !== null ? w : this.panelSize.width;
55730 h = h !== null ? h : this.panelSize.height;
55732 if(this.activePanel){
55733 var el = this.activePanel.getEl();
55734 w = w !== null ? w : el.getWidth();
55735 h = h !== null ? h : el.getHeight();
55736 this.panelSize = {width: w, height: h};
55737 this.activePanel.setSize(w, h);
55739 if(Roo.isIE && this.tabs){
55740 this.tabs.el.repaint();
55745 * Returns the container element for this region.
55746 * @return {Roo.Element}
55748 getEl : function(){
55753 * Hides this region.
55756 if(!this.collapsed){
55757 this.el.dom.style.left = "-2000px";
55760 this.collapsedEl.dom.style.left = "-2000px";
55761 this.collapsedEl.hide();
55763 this.visible = false;
55764 this.fireEvent("visibilitychange", this, false);
55768 * Shows this region if it was previously hidden.
55771 if(!this.collapsed){
55774 this.collapsedEl.show();
55776 this.visible = true;
55777 this.fireEvent("visibilitychange", this, true);
55780 closeClicked : function(){
55781 if(this.activePanel){
55782 this.remove(this.activePanel);
55786 collapseClick : function(e){
55788 e.stopPropagation();
55791 e.stopPropagation();
55797 * Collapses this region.
55798 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
55800 collapse : function(skipAnim, skipCheck){
55801 if(this.collapsed) {
55805 if(skipCheck || this.fireEvent("beforecollapse", this) != false){
55807 this.collapsed = true;
55809 this.split.el.hide();
55811 if(this.config.animate && skipAnim !== true){
55812 this.fireEvent("invalidated", this);
55813 this.animateCollapse();
55815 this.el.setLocation(-20000,-20000);
55817 this.collapsedEl.show();
55818 this.fireEvent("collapsed", this);
55819 this.fireEvent("invalidated", this);
55825 animateCollapse : function(){
55830 * Expands this region if it was previously collapsed.
55831 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
55832 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
55834 expand : function(e, skipAnim){
55836 e.stopPropagation();
55838 if(!this.collapsed || this.el.hasActiveFx()) {
55842 this.afterSlideIn();
55845 this.collapsed = false;
55846 if(this.config.animate && skipAnim !== true){
55847 this.animateExpand();
55851 this.split.el.show();
55853 this.collapsedEl.setLocation(-2000,-2000);
55854 this.collapsedEl.hide();
55855 this.fireEvent("invalidated", this);
55856 this.fireEvent("expanded", this);
55860 animateExpand : function(){
55864 initTabs : function()
55866 this.bodyEl.setStyle("overflow", "hidden");
55867 var ts = new Roo.TabPanel(
55870 tabPosition: this.bottomTabs ? 'bottom' : 'top',
55871 disableTooltips: this.config.disableTabTips,
55872 toolbar : this.config.toolbar
55875 if(this.config.hideTabs){
55876 ts.stripWrap.setDisplayed(false);
55879 ts.resizeTabs = this.config.resizeTabs === true;
55880 ts.minTabWidth = this.config.minTabWidth || 40;
55881 ts.maxTabWidth = this.config.maxTabWidth || 250;
55882 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
55883 ts.monitorResize = false;
55884 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
55885 ts.bodyEl.addClass('x-layout-tabs-body');
55886 this.panels.each(this.initPanelAsTab, this);
55889 initPanelAsTab : function(panel){
55890 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
55891 this.config.closeOnTab && panel.isClosable());
55892 if(panel.tabTip !== undefined){
55893 ti.setTooltip(panel.tabTip);
55895 ti.on("activate", function(){
55896 this.setActivePanel(panel);
55898 if(this.config.closeOnTab){
55899 ti.on("beforeclose", function(t, e){
55901 this.remove(panel);
55907 updatePanelTitle : function(panel, title){
55908 if(this.activePanel == panel){
55909 this.updateTitle(title);
55912 var ti = this.tabs.getTab(panel.getEl().id);
55914 if(panel.tabTip !== undefined){
55915 ti.setTooltip(panel.tabTip);
55920 updateTitle : function(title){
55921 if(this.titleTextEl && !this.config.title){
55922 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
55926 setActivePanel : function(panel){
55927 panel = this.getPanel(panel);
55928 if(this.activePanel && this.activePanel != panel){
55929 this.activePanel.setActiveState(false);
55931 this.activePanel = panel;
55932 panel.setActiveState(true);
55933 if(this.panelSize){
55934 panel.setSize(this.panelSize.width, this.panelSize.height);
55937 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
55939 this.updateTitle(panel.getTitle());
55941 this.fireEvent("invalidated", this);
55943 this.fireEvent("panelactivated", this, panel);
55947 * Shows the specified panel.
55948 * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
55949 * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
55951 showPanel : function(panel)
55953 panel = this.getPanel(panel);
55956 var tab = this.tabs.getTab(panel.getEl().id);
55957 if(tab.isHidden()){
55958 this.tabs.unhideTab(tab.id);
55962 this.setActivePanel(panel);
55969 * Get the active panel for this region.
55970 * @return {Roo.ContentPanel} The active panel or null
55972 getActivePanel : function(){
55973 return this.activePanel;
55976 validateVisibility : function(){
55977 if(this.panels.getCount() < 1){
55978 this.updateTitle(" ");
55979 this.closeBtn.hide();
55982 if(!this.isVisible()){
55989 * Adds the passed ContentPanel(s) to this region.
55990 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
55991 * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
55993 add : function(panel){
55994 if(arguments.length > 1){
55995 for(var i = 0, len = arguments.length; i < len; i++) {
55996 this.add(arguments[i]);
56000 if(this.hasPanel(panel)){
56001 this.showPanel(panel);
56004 panel.setRegion(this);
56005 this.panels.add(panel);
56006 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
56007 this.bodyEl.dom.appendChild(panel.getEl().dom);
56008 if(panel.background !== true){
56009 this.setActivePanel(panel);
56011 this.fireEvent("paneladded", this, panel);
56017 this.initPanelAsTab(panel);
56019 if(panel.background !== true){
56020 this.tabs.activate(panel.getEl().id);
56022 this.fireEvent("paneladded", this, panel);
56027 * Hides the tab for the specified panel.
56028 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
56030 hidePanel : function(panel){
56031 if(this.tabs && (panel = this.getPanel(panel))){
56032 this.tabs.hideTab(panel.getEl().id);
56037 * Unhides the tab for a previously hidden panel.
56038 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
56040 unhidePanel : function(panel){
56041 if(this.tabs && (panel = this.getPanel(panel))){
56042 this.tabs.unhideTab(panel.getEl().id);
56046 clearPanels : function(){
56047 while(this.panels.getCount() > 0){
56048 this.remove(this.panels.first());
56053 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
56054 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
56055 * @param {Boolean} preservePanel Overrides the config preservePanel option
56056 * @return {Roo.ContentPanel} The panel that was removed
56058 remove : function(panel, preservePanel){
56059 panel = this.getPanel(panel);
56064 this.fireEvent("beforeremove", this, panel, e);
56065 if(e.cancel === true){
56068 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
56069 var panelId = panel.getId();
56070 this.panels.removeKey(panelId);
56072 document.body.appendChild(panel.getEl().dom);
56075 this.tabs.removeTab(panel.getEl().id);
56076 }else if (!preservePanel){
56077 this.bodyEl.dom.removeChild(panel.getEl().dom);
56079 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
56080 var p = this.panels.first();
56081 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
56082 tempEl.appendChild(p.getEl().dom);
56083 this.bodyEl.update("");
56084 this.bodyEl.dom.appendChild(p.getEl().dom);
56086 this.updateTitle(p.getTitle());
56088 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
56089 this.setActivePanel(p);
56091 panel.setRegion(null);
56092 if(this.activePanel == panel){
56093 this.activePanel = null;
56095 if(this.config.autoDestroy !== false && preservePanel !== true){
56096 try{panel.destroy();}catch(e){}
56098 this.fireEvent("panelremoved", this, panel);
56103 * Returns the TabPanel component used by this region
56104 * @return {Roo.TabPanel}
56106 getTabs : function(){
56110 createTool : function(parentEl, className){
56111 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
56112 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
56113 btn.addClassOnOver("x-layout-tools-button-over");
56118 * Ext JS Library 1.1.1
56119 * Copyright(c) 2006-2007, Ext JS, LLC.
56121 * Originally Released Under LGPL - original licence link has changed is not relivant.
56124 * <script type="text/javascript">
56130 * @class Roo.SplitLayoutRegion
56131 * @extends Roo.LayoutRegion
56132 * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
56134 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
56135 this.cursor = cursor;
56136 Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
56139 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
56140 splitTip : "Drag to resize.",
56141 collapsibleSplitTip : "Drag to resize. Double click to hide.",
56142 useSplitTips : false,
56144 applyConfig : function(config){
56145 Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
56148 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
56149 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
56150 /** The SplitBar for this region
56151 * @type Roo.SplitBar */
56152 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
56153 this.split.on("moved", this.onSplitMove, this);
56154 this.split.useShim = config.useShim === true;
56155 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
56156 if(this.useSplitTips){
56157 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
56159 if(config.collapsible){
56160 this.split.el.on("dblclick", this.collapse, this);
56163 if(typeof config.minSize != "undefined"){
56164 this.split.minSize = config.minSize;
56166 if(typeof config.maxSize != "undefined"){
56167 this.split.maxSize = config.maxSize;
56169 if(config.hideWhenEmpty || config.hidden || config.collapsed){
56170 this.hideSplitter();
56175 getHMaxSize : function(){
56176 var cmax = this.config.maxSize || 10000;
56177 var center = this.mgr.getRegion("center");
56178 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
56181 getVMaxSize : function(){
56182 var cmax = this.config.maxSize || 10000;
56183 var center = this.mgr.getRegion("center");
56184 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
56187 onSplitMove : function(split, newSize){
56188 this.fireEvent("resized", this, newSize);
56192 * Returns the {@link Roo.SplitBar} for this region.
56193 * @return {Roo.SplitBar}
56195 getSplitBar : function(){
56200 this.hideSplitter();
56201 Roo.SplitLayoutRegion.superclass.hide.call(this);
56204 hideSplitter : function(){
56206 this.split.el.setLocation(-2000,-2000);
56207 this.split.el.hide();
56213 this.split.el.show();
56215 Roo.SplitLayoutRegion.superclass.show.call(this);
56218 beforeSlide: function(){
56219 if(Roo.isGecko){// firefox overflow auto bug workaround
56220 this.bodyEl.clip();
56222 this.tabs.bodyEl.clip();
56224 if(this.activePanel){
56225 this.activePanel.getEl().clip();
56227 if(this.activePanel.beforeSlide){
56228 this.activePanel.beforeSlide();
56234 afterSlide : function(){
56235 if(Roo.isGecko){// firefox overflow auto bug workaround
56236 this.bodyEl.unclip();
56238 this.tabs.bodyEl.unclip();
56240 if(this.activePanel){
56241 this.activePanel.getEl().unclip();
56242 if(this.activePanel.afterSlide){
56243 this.activePanel.afterSlide();
56249 initAutoHide : function(){
56250 if(this.autoHide !== false){
56251 if(!this.autoHideHd){
56252 var st = new Roo.util.DelayedTask(this.slideIn, this);
56253 this.autoHideHd = {
56254 "mouseout": function(e){
56255 if(!e.within(this.el, true)){
56259 "mouseover" : function(e){
56265 this.el.on(this.autoHideHd);
56269 clearAutoHide : function(){
56270 if(this.autoHide !== false){
56271 this.el.un("mouseout", this.autoHideHd.mouseout);
56272 this.el.un("mouseover", this.autoHideHd.mouseover);
56276 clearMonitor : function(){
56277 Roo.get(document).un("click", this.slideInIf, this);
56280 // these names are backwards but not changed for compat
56281 slideOut : function(){
56282 if(this.isSlid || this.el.hasActiveFx()){
56285 this.isSlid = true;
56286 if(this.collapseBtn){
56287 this.collapseBtn.hide();
56289 this.closeBtnState = this.closeBtn.getStyle('display');
56290 this.closeBtn.hide();
56292 this.stickBtn.show();
56295 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
56296 this.beforeSlide();
56297 this.el.setStyle("z-index", 10001);
56298 this.el.slideIn(this.getSlideAnchor(), {
56299 callback: function(){
56301 this.initAutoHide();
56302 Roo.get(document).on("click", this.slideInIf, this);
56303 this.fireEvent("slideshow", this);
56310 afterSlideIn : function(){
56311 this.clearAutoHide();
56312 this.isSlid = false;
56313 this.clearMonitor();
56314 this.el.setStyle("z-index", "");
56315 if(this.collapseBtn){
56316 this.collapseBtn.show();
56318 this.closeBtn.setStyle('display', this.closeBtnState);
56320 this.stickBtn.hide();
56322 this.fireEvent("slidehide", this);
56325 slideIn : function(cb){
56326 if(!this.isSlid || this.el.hasActiveFx()){
56330 this.isSlid = false;
56331 this.beforeSlide();
56332 this.el.slideOut(this.getSlideAnchor(), {
56333 callback: function(){
56334 this.el.setLeftTop(-10000, -10000);
56336 this.afterSlideIn();
56344 slideInIf : function(e){
56345 if(!e.within(this.el)){
56350 animateCollapse : function(){
56351 this.beforeSlide();
56352 this.el.setStyle("z-index", 20000);
56353 var anchor = this.getSlideAnchor();
56354 this.el.slideOut(anchor, {
56355 callback : function(){
56356 this.el.setStyle("z-index", "");
56357 this.collapsedEl.slideIn(anchor, {duration:.3});
56359 this.el.setLocation(-10000,-10000);
56361 this.fireEvent("collapsed", this);
56368 animateExpand : function(){
56369 this.beforeSlide();
56370 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
56371 this.el.setStyle("z-index", 20000);
56372 this.collapsedEl.hide({
56375 this.el.slideIn(this.getSlideAnchor(), {
56376 callback : function(){
56377 this.el.setStyle("z-index", "");
56380 this.split.el.show();
56382 this.fireEvent("invalidated", this);
56383 this.fireEvent("expanded", this);
56411 getAnchor : function(){
56412 return this.anchors[this.position];
56415 getCollapseAnchor : function(){
56416 return this.canchors[this.position];
56419 getSlideAnchor : function(){
56420 return this.sanchors[this.position];
56423 getAlignAdj : function(){
56424 var cm = this.cmargins;
56425 switch(this.position){
56441 getExpandAdj : function(){
56442 var c = this.collapsedEl, cm = this.cmargins;
56443 switch(this.position){
56445 return [-(cm.right+c.getWidth()+cm.left), 0];
56448 return [cm.right+c.getWidth()+cm.left, 0];
56451 return [0, -(cm.top+cm.bottom+c.getHeight())];
56454 return [0, cm.top+cm.bottom+c.getHeight()];
56460 * Ext JS Library 1.1.1
56461 * Copyright(c) 2006-2007, Ext JS, LLC.
56463 * Originally Released Under LGPL - original licence link has changed is not relivant.
56466 * <script type="text/javascript">
56469 * These classes are private internal classes
56471 Roo.CenterLayoutRegion = function(mgr, config){
56472 Roo.LayoutRegion.call(this, mgr, config, "center");
56473 this.visible = true;
56474 this.minWidth = config.minWidth || 20;
56475 this.minHeight = config.minHeight || 20;
56478 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
56480 // center panel can't be hidden
56484 // center panel can't be hidden
56487 getMinWidth: function(){
56488 return this.minWidth;
56491 getMinHeight: function(){
56492 return this.minHeight;
56497 Roo.NorthLayoutRegion = function(mgr, config){
56498 Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
56500 this.split.placement = Roo.SplitBar.TOP;
56501 this.split.orientation = Roo.SplitBar.VERTICAL;
56502 this.split.el.addClass("x-layout-split-v");
56504 var size = config.initialSize || config.height;
56505 if(typeof size != "undefined"){
56506 this.el.setHeight(size);
56509 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
56510 orientation: Roo.SplitBar.VERTICAL,
56511 getBox : function(){
56512 if(this.collapsed){
56513 return this.collapsedEl.getBox();
56515 var box = this.el.getBox();
56517 box.height += this.split.el.getHeight();
56522 updateBox : function(box){
56523 if(this.split && !this.collapsed){
56524 box.height -= this.split.el.getHeight();
56525 this.split.el.setLeft(box.x);
56526 this.split.el.setTop(box.y+box.height);
56527 this.split.el.setWidth(box.width);
56529 if(this.collapsed){
56530 this.updateBody(box.width, null);
56532 Roo.LayoutRegion.prototype.updateBox.call(this, box);
56536 Roo.SouthLayoutRegion = function(mgr, config){
56537 Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
56539 this.split.placement = Roo.SplitBar.BOTTOM;
56540 this.split.orientation = Roo.SplitBar.VERTICAL;
56541 this.split.el.addClass("x-layout-split-v");
56543 var size = config.initialSize || config.height;
56544 if(typeof size != "undefined"){
56545 this.el.setHeight(size);
56548 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
56549 orientation: Roo.SplitBar.VERTICAL,
56550 getBox : function(){
56551 if(this.collapsed){
56552 return this.collapsedEl.getBox();
56554 var box = this.el.getBox();
56556 var sh = this.split.el.getHeight();
56563 updateBox : function(box){
56564 if(this.split && !this.collapsed){
56565 var sh = this.split.el.getHeight();
56568 this.split.el.setLeft(box.x);
56569 this.split.el.setTop(box.y-sh);
56570 this.split.el.setWidth(box.width);
56572 if(this.collapsed){
56573 this.updateBody(box.width, null);
56575 Roo.LayoutRegion.prototype.updateBox.call(this, box);
56579 Roo.EastLayoutRegion = function(mgr, config){
56580 Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
56582 this.split.placement = Roo.SplitBar.RIGHT;
56583 this.split.orientation = Roo.SplitBar.HORIZONTAL;
56584 this.split.el.addClass("x-layout-split-h");
56586 var size = config.initialSize || config.width;
56587 if(typeof size != "undefined"){
56588 this.el.setWidth(size);
56591 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
56592 orientation: Roo.SplitBar.HORIZONTAL,
56593 getBox : function(){
56594 if(this.collapsed){
56595 return this.collapsedEl.getBox();
56597 var box = this.el.getBox();
56599 var sw = this.split.el.getWidth();
56606 updateBox : function(box){
56607 if(this.split && !this.collapsed){
56608 var sw = this.split.el.getWidth();
56610 this.split.el.setLeft(box.x);
56611 this.split.el.setTop(box.y);
56612 this.split.el.setHeight(box.height);
56615 if(this.collapsed){
56616 this.updateBody(null, box.height);
56618 Roo.LayoutRegion.prototype.updateBox.call(this, box);
56622 Roo.WestLayoutRegion = function(mgr, config){
56623 Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
56625 this.split.placement = Roo.SplitBar.LEFT;
56626 this.split.orientation = Roo.SplitBar.HORIZONTAL;
56627 this.split.el.addClass("x-layout-split-h");
56629 var size = config.initialSize || config.width;
56630 if(typeof size != "undefined"){
56631 this.el.setWidth(size);
56634 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
56635 orientation: Roo.SplitBar.HORIZONTAL,
56636 getBox : function(){
56637 if(this.collapsed){
56638 return this.collapsedEl.getBox();
56640 var box = this.el.getBox();
56642 box.width += this.split.el.getWidth();
56647 updateBox : function(box){
56648 if(this.split && !this.collapsed){
56649 var sw = this.split.el.getWidth();
56651 this.split.el.setLeft(box.x+box.width);
56652 this.split.el.setTop(box.y);
56653 this.split.el.setHeight(box.height);
56655 if(this.collapsed){
56656 this.updateBody(null, box.height);
56658 Roo.LayoutRegion.prototype.updateBox.call(this, box);
56663 * Ext JS Library 1.1.1
56664 * Copyright(c) 2006-2007, Ext JS, LLC.
56666 * Originally Released Under LGPL - original licence link has changed is not relivant.
56669 * <script type="text/javascript">
56674 * Private internal class for reading and applying state
56676 Roo.LayoutStateManager = function(layout){
56677 // default empty state
56686 Roo.LayoutStateManager.prototype = {
56687 init : function(layout, provider){
56688 this.provider = provider;
56689 var state = provider.get(layout.id+"-layout-state");
56691 var wasUpdating = layout.isUpdating();
56693 layout.beginUpdate();
56695 for(var key in state){
56696 if(typeof state[key] != "function"){
56697 var rstate = state[key];
56698 var r = layout.getRegion(key);
56701 r.resizeTo(rstate.size);
56703 if(rstate.collapsed == true){
56706 r.expand(null, true);
56712 layout.endUpdate();
56714 this.state = state;
56716 this.layout = layout;
56717 layout.on("regionresized", this.onRegionResized, this);
56718 layout.on("regioncollapsed", this.onRegionCollapsed, this);
56719 layout.on("regionexpanded", this.onRegionExpanded, this);
56722 storeState : function(){
56723 this.provider.set(this.layout.id+"-layout-state", this.state);
56726 onRegionResized : function(region, newSize){
56727 this.state[region.getPosition()].size = newSize;
56731 onRegionCollapsed : function(region){
56732 this.state[region.getPosition()].collapsed = true;
56736 onRegionExpanded : function(region){
56737 this.state[region.getPosition()].collapsed = false;
56742 * Ext JS Library 1.1.1
56743 * Copyright(c) 2006-2007, Ext JS, LLC.
56745 * Originally Released Under LGPL - original licence link has changed is not relivant.
56748 * <script type="text/javascript">
56751 * @class Roo.ContentPanel
56752 * @extends Roo.util.Observable
56753 * @children Roo.form.Form Roo.JsonView Roo.View
56754 * @parent Roo.BorderLayout Roo.LayoutDialog builder-top
56755 * A basic ContentPanel element.
56756 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
56757 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
56758 * @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
56759 * @cfg {Boolean} closable True if the panel can be closed/removed
56760 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
56761 * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
56762 * @cfg {Roo.Toolbar} toolbar A toolbar for this panel
56763 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
56764 * @cfg {String} title The title for this panel
56765 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
56766 * @cfg {String} url Calls {@link #setUrl} with this value
56767 * @cfg {String} region [required] (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
56768 * @cfg {String|Object} params When used with {@link #url}, calls {@link #setUrl} with this value
56769 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
56770 * @cfg {String} content Raw content to fill content panel with (uses setContent on construction.)
56771 * @cfg {String} style Extra style to add to the content panel
56772 * @cfg {Roo.menu.Menu} menu popup menu
56775 * Create a new ContentPanel.
56776 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
56777 * @param {String/Object} config A string to set only the title or a config object
56778 * @param {String} content (optional) Set the HTML content for this panel
56779 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
56781 Roo.ContentPanel = function(el, config, content){
56785 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
56789 if (config && config.parentLayout) {
56790 el = config.parentLayout.el.createChild();
56793 if(el.autoCreate){ // xtype is available if this is called from factory
56797 this.el = Roo.get(el);
56798 if(!this.el && config && config.autoCreate){
56799 if(typeof config.autoCreate == "object"){
56800 if(!config.autoCreate.id){
56801 config.autoCreate.id = config.id||el;
56803 this.el = Roo.DomHelper.append(document.body,
56804 config.autoCreate, true);
56806 this.el = Roo.DomHelper.append(document.body,
56807 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
56812 this.closable = false;
56813 this.loaded = false;
56814 this.active = false;
56815 if(typeof config == "string"){
56816 this.title = config;
56818 Roo.apply(this, config);
56821 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
56822 this.wrapEl = this.el.wrap();
56823 this.toolbar.container = this.el.insertSibling(false, 'before');
56824 this.toolbar = new Roo.Toolbar(this.toolbar);
56827 // xtype created footer. - not sure if will work as we normally have to render first..
56828 if (this.footer && !this.footer.el && this.footer.xtype) {
56829 if (!this.wrapEl) {
56830 this.wrapEl = this.el.wrap();
56833 this.footer.container = this.wrapEl.createChild();
56835 this.footer = Roo.factory(this.footer, Roo);
56840 this.resizeEl = Roo.get(this.resizeEl, true);
56842 this.resizeEl = this.el;
56844 // handle view.xtype
56852 * Fires when this panel is activated.
56853 * @param {Roo.ContentPanel} this
56857 * @event deactivate
56858 * Fires when this panel is activated.
56859 * @param {Roo.ContentPanel} this
56861 "deactivate" : true,
56865 * Fires when this panel is resized if fitToFrame is true.
56866 * @param {Roo.ContentPanel} this
56867 * @param {Number} width The width after any component adjustments
56868 * @param {Number} height The height after any component adjustments
56874 * Fires when this tab is created
56875 * @param {Roo.ContentPanel} this
56885 if(this.autoScroll){
56886 this.resizeEl.setStyle("overflow", "auto");
56888 // fix randome scrolling
56889 this.el.on('scroll', function() {
56890 Roo.log('fix random scolling');
56891 this.scrollTo('top',0);
56894 content = content || this.content;
56896 this.setContent(content);
56898 if(config && config.url){
56899 this.setUrl(this.url, this.params, this.loadOnce);
56904 Roo.ContentPanel.superclass.constructor.call(this);
56906 if (this.view && typeof(this.view.xtype) != 'undefined') {
56907 this.view.el = this.el.appendChild(document.createElement("div"));
56908 this.view = Roo.factory(this.view);
56909 this.view.render && this.view.render(false, '');
56913 this.fireEvent('render', this);
56916 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
56918 setRegion : function(region){
56919 this.region = region;
56921 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
56923 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
56928 * Returns the toolbar for this Panel if one was configured.
56929 * @return {Roo.Toolbar}
56931 getToolbar : function(){
56932 return this.toolbar;
56935 setActiveState : function(active){
56936 this.active = active;
56938 this.fireEvent("deactivate", this);
56940 this.fireEvent("activate", this);
56944 * Updates this panel's element
56945 * @param {String} content The new content
56946 * @param {Boolean} loadScripts (optional) true to look for and process scripts
56948 setContent : function(content, loadScripts){
56949 this.el.update(content, loadScripts);
56952 ignoreResize : function(w, h){
56953 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
56956 this.lastSize = {width: w, height: h};
56961 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
56962 * @return {Roo.UpdateManager} The UpdateManager
56964 getUpdateManager : function(){
56965 return this.el.getUpdateManager();
56968 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
56969 * @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:
56972 url: "your-url.php",
56973 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
56974 callback: yourFunction,
56975 scope: yourObject, //(optional scope)
56978 text: "Loading...",
56983 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
56984 * 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.
56985 * @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}
56986 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
56987 * @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.
56988 * @return {Roo.ContentPanel} this
56991 var um = this.el.getUpdateManager();
56992 um.update.apply(um, arguments);
56998 * 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.
56999 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
57000 * @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)
57001 * @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)
57002 * @return {Roo.UpdateManager} The UpdateManager
57004 setUrl : function(url, params, loadOnce){
57005 if(this.refreshDelegate){
57006 this.removeListener("activate", this.refreshDelegate);
57008 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
57009 this.on("activate", this.refreshDelegate);
57010 return this.el.getUpdateManager();
57013 _handleRefresh : function(url, params, loadOnce){
57014 if(!loadOnce || !this.loaded){
57015 var updater = this.el.getUpdateManager();
57016 updater.update(url, params, this._setLoaded.createDelegate(this));
57020 _setLoaded : function(){
57021 this.loaded = true;
57025 * Returns this panel's id
57028 getId : function(){
57033 * Returns this panel's element - used by regiosn to add.
57034 * @return {Roo.Element}
57036 getEl : function(){
57037 return this.wrapEl || this.el;
57040 adjustForComponents : function(width, height)
57042 //Roo.log('adjustForComponents ');
57043 if(this.resizeEl != this.el){
57044 width -= this.el.getFrameWidth('lr');
57045 height -= this.el.getFrameWidth('tb');
57048 var te = this.toolbar.getEl();
57049 height -= te.getHeight();
57050 te.setWidth(width);
57053 var te = this.footer.getEl();
57054 //Roo.log("footer:" + te.getHeight());
57056 height -= te.getHeight();
57057 te.setWidth(width);
57061 if(this.adjustments){
57062 width += this.adjustments[0];
57063 height += this.adjustments[1];
57065 return {"width": width, "height": height};
57068 setSize : function(width, height){
57069 if(this.fitToFrame && !this.ignoreResize(width, height)){
57070 if(this.fitContainer && this.resizeEl != this.el){
57071 this.el.setSize(width, height);
57073 var size = this.adjustForComponents(width, height);
57074 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
57075 this.fireEvent('resize', this, size.width, size.height);
57080 * Returns this panel's title
57083 getTitle : function(){
57088 * Set this panel's title
57089 * @param {String} title
57091 setTitle : function(title){
57092 this.title = title;
57094 this.region.updatePanelTitle(this, title);
57099 * Returns true is this panel was configured to be closable
57100 * @return {Boolean}
57102 isClosable : function(){
57103 return this.closable;
57106 beforeSlide : function(){
57108 this.resizeEl.clip();
57111 afterSlide : function(){
57113 this.resizeEl.unclip();
57117 * Force a content refresh from the URL specified in the {@link #setUrl} method.
57118 * Will fail silently if the {@link #setUrl} method has not been called.
57119 * This does not activate the panel, just updates its content.
57121 refresh : function(){
57122 if(this.refreshDelegate){
57123 this.loaded = false;
57124 this.refreshDelegate();
57129 * Destroys this panel
57131 destroy : function(){
57132 this.el.removeAllListeners();
57133 var tempEl = document.createElement("span");
57134 tempEl.appendChild(this.el.dom);
57135 tempEl.innerHTML = "";
57141 * form - if the content panel contains a form - this is a reference to it.
57142 * @type {Roo.form.Form}
57146 * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
57147 * This contains a reference to it.
57153 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
57163 * @param {Object} cfg Xtype definition of item to add.
57166 addxtype : function(cfg) {
57168 if (cfg.xtype.match(/^Form$/)) {
57171 //if (this.footer) {
57172 // el = this.footer.container.insertSibling(false, 'before');
57174 el = this.el.createChild();
57177 this.form = new Roo.form.Form(cfg);
57180 if ( this.form.allItems.length) {
57181 this.form.render(el.dom);
57185 // should only have one of theses..
57186 if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
57187 // views.. should not be just added - used named prop 'view''
57189 cfg.el = this.el.appendChild(document.createElement("div"));
57192 var ret = new Roo.factory(cfg);
57194 ret.render && ret.render(false, ''); // render blank..
57203 * @class Roo.GridPanel
57204 * @extends Roo.ContentPanel
57206 * Create a new GridPanel.
57207 * @param {Roo.grid.Grid} grid The grid for this panel
57208 * @param {String/Object} config A string to set only the panel's title, or a config object
57210 Roo.GridPanel = function(grid, config){
57213 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
57214 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
57216 this.wrapper.dom.appendChild(grid.getGridEl().dom);
57218 Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
57221 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
57223 // xtype created footer. - not sure if will work as we normally have to render first..
57224 if (this.footer && !this.footer.el && this.footer.xtype) {
57226 this.footer.container = this.grid.getView().getFooterPanel(true);
57227 this.footer.dataSource = this.grid.dataSource;
57228 this.footer = Roo.factory(this.footer, Roo);
57232 grid.monitorWindowResize = false; // turn off autosizing
57233 grid.autoHeight = false;
57234 grid.autoWidth = false;
57236 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
57239 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
57240 getId : function(){
57241 return this.grid.id;
57245 * Returns the grid for this panel
57246 * @return {Roo.grid.Grid}
57248 getGrid : function(){
57252 setSize : function(width, height){
57253 if(!this.ignoreResize(width, height)){
57254 var grid = this.grid;
57255 var size = this.adjustForComponents(width, height);
57256 grid.getGridEl().setSize(size.width, size.height);
57261 beforeSlide : function(){
57262 this.grid.getView().scroller.clip();
57265 afterSlide : function(){
57266 this.grid.getView().scroller.unclip();
57269 destroy : function(){
57270 this.grid.destroy();
57272 Roo.GridPanel.superclass.destroy.call(this);
57278 * @class Roo.NestedLayoutPanel
57279 * @extends Roo.ContentPanel
57281 * Create a new NestedLayoutPanel.
57284 * @param {Roo.BorderLayout} layout [required] The layout for this panel
57285 * @param {String/Object} config A string to set only the title or a config object
57287 Roo.NestedLayoutPanel = function(layout, config)
57289 // construct with only one argument..
57290 /* FIXME - implement nicer consturctors
57291 if (layout.layout) {
57293 layout = config.layout;
57294 delete config.layout;
57296 if (layout.xtype && !layout.getEl) {
57297 // then layout needs constructing..
57298 layout = Roo.factory(layout, Roo);
57303 Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
57305 layout.monitorWindowResize = false; // turn off autosizing
57306 this.layout = layout;
57307 this.layout.getEl().addClass("x-layout-nested-layout");
57314 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
57316 setSize : function(width, height){
57317 if(!this.ignoreResize(width, height)){
57318 var size = this.adjustForComponents(width, height);
57319 var el = this.layout.getEl();
57320 el.setSize(size.width, size.height);
57321 var touch = el.dom.offsetWidth;
57322 this.layout.layout();
57323 // ie requires a double layout on the first pass
57324 if(Roo.isIE && !this.initialized){
57325 this.initialized = true;
57326 this.layout.layout();
57331 // activate all subpanels if not currently active..
57333 setActiveState : function(active){
57334 this.active = active;
57336 this.fireEvent("deactivate", this);
57340 this.fireEvent("activate", this);
57341 // not sure if this should happen before or after..
57342 if (!this.layout) {
57343 return; // should not happen..
57346 for (var r in this.layout.regions) {
57347 reg = this.layout.getRegion(r);
57348 if (reg.getActivePanel()) {
57349 //reg.showPanel(reg.getActivePanel()); // force it to activate..
57350 reg.setActivePanel(reg.getActivePanel());
57353 if (!reg.panels.length) {
57356 reg.showPanel(reg.getPanel(0));
57365 * Returns the nested BorderLayout for this panel
57366 * @return {Roo.BorderLayout}
57368 getLayout : function(){
57369 return this.layout;
57373 * Adds a xtype elements to the layout of the nested panel
57377 xtype : 'ContentPanel',
57384 xtype : 'NestedLayoutPanel',
57390 items : [ ... list of content panels or nested layout panels.. ]
57394 * @param {Object} cfg Xtype definition of item to add.
57396 addxtype : function(cfg) {
57397 return this.layout.addxtype(cfg);
57402 Roo.ScrollPanel = function(el, config, content){
57403 config = config || {};
57404 config.fitToFrame = true;
57405 Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
57407 this.el.dom.style.overflow = "hidden";
57408 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
57409 this.el.removeClass("x-layout-inactive-content");
57410 this.el.on("mousewheel", this.onWheel, this);
57412 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
57413 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
57414 up.unselectable(); down.unselectable();
57415 up.on("click", this.scrollUp, this);
57416 down.on("click", this.scrollDown, this);
57417 up.addClassOnOver("x-scroller-btn-over");
57418 down.addClassOnOver("x-scroller-btn-over");
57419 up.addClassOnClick("x-scroller-btn-click");
57420 down.addClassOnClick("x-scroller-btn-click");
57421 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
57423 this.resizeEl = this.el;
57424 this.el = wrap; this.up = up; this.down = down;
57427 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
57429 wheelIncrement : 5,
57430 scrollUp : function(){
57431 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
57434 scrollDown : function(){
57435 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
57438 afterScroll : function(){
57439 var el = this.resizeEl;
57440 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
57441 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
57442 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
57445 setSize : function(){
57446 Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
57447 this.afterScroll();
57450 onWheel : function(e){
57451 var d = e.getWheelDelta();
57452 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
57453 this.afterScroll();
57457 setContent : function(content, loadScripts){
57458 this.resizeEl.update(content, loadScripts);
57466 * @class Roo.TreePanel
57467 * @extends Roo.ContentPanel
57468 * Treepanel component
57471 * Create a new TreePanel. - defaults to fit/scoll contents.
57472 * @param {String/Object} config A string to set only the panel's title, or a config object
57474 Roo.TreePanel = function(config){
57475 var el = config.el;
57476 var tree = config.tree;
57477 delete config.tree;
57478 delete config.el; // hopefull!
57480 // wrapper for IE7 strict & safari scroll issue
57482 var treeEl = el.createChild();
57483 config.resizeEl = treeEl;
57487 Roo.TreePanel.superclass.constructor.call(this, el, config);
57490 this.tree = new Roo.tree.TreePanel(treeEl , tree);
57491 //console.log(tree);
57492 this.on('activate', function()
57494 if (this.tree.rendered) {
57497 //console.log('render tree');
57498 this.tree.render();
57500 // this should not be needed.. - it's actually the 'el' that resizes?
57501 // actuall it breaks the containerScroll - dragging nodes auto scroll at top
57503 //this.on('resize', function (cp, w, h) {
57504 // this.tree.innerCt.setWidth(w);
57505 // this.tree.innerCt.setHeight(h);
57506 // //this.tree.innerCt.setStyle('overflow-y', 'auto');
57513 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {
57517 * @cfg {Roo.tree.TreePanel} tree [required] The tree TreePanel, with config etc.
57535 * Ext JS Library 1.1.1
57536 * Copyright(c) 2006-2007, Ext JS, LLC.
57538 * Originally Released Under LGPL - original licence link has changed is not relivant.
57541 * <script type="text/javascript">
57546 * @class Roo.ReaderLayout
57547 * @extends Roo.BorderLayout
57548 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
57549 * center region containing two nested regions (a top one for a list view and one for item preview below),
57550 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
57551 * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
57552 * expedites the setup of the overall layout and regions for this common application style.
57555 var reader = new Roo.ReaderLayout();
57556 var CP = Roo.ContentPanel; // shortcut for adding
57558 reader.beginUpdate();
57559 reader.add("north", new CP("north", "North"));
57560 reader.add("west", new CP("west", {title: "West"}));
57561 reader.add("east", new CP("east", {title: "East"}));
57563 reader.regions.listView.add(new CP("listView", "List"));
57564 reader.regions.preview.add(new CP("preview", "Preview"));
57565 reader.endUpdate();
57568 * Create a new ReaderLayout
57569 * @param {Object} config Configuration options
57570 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
57571 * document.body if omitted)
57573 Roo.ReaderLayout = function(config, renderTo){
57574 var c = config || {size:{}};
57575 Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
57576 north: c.north !== false ? Roo.apply({
57580 }, c.north) : false,
57581 west: c.west !== false ? Roo.apply({
57589 margins:{left:5,right:0,bottom:5,top:5},
57590 cmargins:{left:5,right:5,bottom:5,top:5}
57591 }, c.west) : false,
57592 east: c.east !== false ? Roo.apply({
57600 margins:{left:0,right:5,bottom:5,top:5},
57601 cmargins:{left:5,right:5,bottom:5,top:5}
57602 }, c.east) : false,
57603 center: Roo.apply({
57604 tabPosition: 'top',
57608 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
57612 this.el.addClass('x-reader');
57614 this.beginUpdate();
57616 var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
57617 south: c.preview !== false ? Roo.apply({
57624 cmargins:{top:5,left:0, right:0, bottom:0}
57625 }, c.preview) : false,
57626 center: Roo.apply({
57632 this.add('center', new Roo.NestedLayoutPanel(inner,
57633 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
57637 this.regions.preview = inner.getRegion('south');
57638 this.regions.listView = inner.getRegion('center');
57641 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
57643 * Ext JS Library 1.1.1
57644 * Copyright(c) 2006-2007, Ext JS, LLC.
57646 * Originally Released Under LGPL - original licence link has changed is not relivant.
57649 * <script type="text/javascript">
57653 * @class Roo.grid.Grid
57654 * @extends Roo.util.Observable
57655 * This class represents the primary interface of a component based grid control.
57656 * <br><br>Usage:<pre><code>
57657 var grid = new Roo.grid.Grid("my-container-id", {
57660 selModel: mySelectionModel,
57661 autoSizeColumns: true,
57662 monitorWindowResize: false,
57663 trackMouseOver: true
57668 * <b>Common Problems:</b><br/>
57669 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
57670 * element will correct this<br/>
57671 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
57672 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
57673 * are unpredictable.<br/>
57674 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
57675 * grid to calculate dimensions/offsets.<br/>
57677 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
57678 * The container MUST have some type of size defined for the grid to fill. The container will be
57679 * automatically set to position relative if it isn't already.
57680 * @param {Object} config A config object that sets properties on this grid.
57682 Roo.grid.Grid = function(container, config){
57683 // initialize the container
57684 this.container = Roo.get(container);
57685 this.container.update("");
57686 this.container.setStyle("overflow", "hidden");
57687 this.container.addClass('x-grid-container');
57689 this.id = this.container.id;
57691 Roo.apply(this, config);
57692 // check and correct shorthanded configs
57694 this.dataSource = this.ds;
57698 this.colModel = this.cm;
57702 this.selModel = this.sm;
57706 if (this.selModel) {
57707 this.selModel = Roo.factory(this.selModel, Roo.grid);
57708 this.sm = this.selModel;
57709 this.sm.xmodule = this.xmodule || false;
57711 if (typeof(this.colModel.config) == 'undefined') {
57712 this.colModel = new Roo.grid.ColumnModel(this.colModel);
57713 this.cm = this.colModel;
57714 this.cm.xmodule = this.xmodule || false;
57716 if (this.dataSource) {
57717 this.dataSource= Roo.factory(this.dataSource, Roo.data);
57718 this.ds = this.dataSource;
57719 this.ds.xmodule = this.xmodule || false;
57726 this.container.setWidth(this.width);
57730 this.container.setHeight(this.height);
57737 * The raw click event for the entire grid.
57738 * @param {Roo.EventObject} e
57743 * The raw dblclick event for the entire grid.
57744 * @param {Roo.EventObject} e
57748 * @event contextmenu
57749 * The raw contextmenu event for the entire grid.
57750 * @param {Roo.EventObject} e
57752 "contextmenu" : true,
57755 * The raw mousedown event for the entire grid.
57756 * @param {Roo.EventObject} e
57758 "mousedown" : true,
57761 * The raw mouseup event for the entire grid.
57762 * @param {Roo.EventObject} e
57767 * The raw mouseover event for the entire grid.
57768 * @param {Roo.EventObject} e
57770 "mouseover" : true,
57773 * The raw mouseout event for the entire grid.
57774 * @param {Roo.EventObject} e
57779 * The raw keypress event for the entire grid.
57780 * @param {Roo.EventObject} e
57785 * The raw keydown event for the entire grid.
57786 * @param {Roo.EventObject} e
57794 * Fires when a cell is clicked
57795 * @param {Grid} this
57796 * @param {Number} rowIndex
57797 * @param {Number} columnIndex
57798 * @param {Roo.EventObject} e
57800 "cellclick" : true,
57802 * @event celldblclick
57803 * Fires when a cell is double clicked
57804 * @param {Grid} this
57805 * @param {Number} rowIndex
57806 * @param {Number} columnIndex
57807 * @param {Roo.EventObject} e
57809 "celldblclick" : true,
57812 * Fires when a row is clicked
57813 * @param {Grid} this
57814 * @param {Number} rowIndex
57815 * @param {Roo.EventObject} e
57819 * @event rowdblclick
57820 * Fires when a row is double clicked
57821 * @param {Grid} this
57822 * @param {Number} rowIndex
57823 * @param {Roo.EventObject} e
57825 "rowdblclick" : true,
57827 * @event headerclick
57828 * Fires when a header is clicked
57829 * @param {Grid} this
57830 * @param {Number} columnIndex
57831 * @param {Roo.EventObject} e
57833 "headerclick" : true,
57835 * @event headerdblclick
57836 * Fires when a header cell is double clicked
57837 * @param {Grid} this
57838 * @param {Number} columnIndex
57839 * @param {Roo.EventObject} e
57841 "headerdblclick" : true,
57843 * @event rowcontextmenu
57844 * Fires when a row is right clicked
57845 * @param {Grid} this
57846 * @param {Number} rowIndex
57847 * @param {Roo.EventObject} e
57849 "rowcontextmenu" : true,
57851 * @event cellcontextmenu
57852 * Fires when a cell is right clicked
57853 * @param {Grid} this
57854 * @param {Number} rowIndex
57855 * @param {Number} cellIndex
57856 * @param {Roo.EventObject} e
57858 "cellcontextmenu" : true,
57860 * @event headercontextmenu
57861 * Fires when a header is right clicked
57862 * @param {Grid} this
57863 * @param {Number} columnIndex
57864 * @param {Roo.EventObject} e
57866 "headercontextmenu" : true,
57868 * @event bodyscroll
57869 * Fires when the body element is scrolled
57870 * @param {Number} scrollLeft
57871 * @param {Number} scrollTop
57873 "bodyscroll" : true,
57875 * @event columnresize
57876 * Fires when the user resizes a column
57877 * @param {Number} columnIndex
57878 * @param {Number} newSize
57880 "columnresize" : true,
57882 * @event columnmove
57883 * Fires when the user moves a column
57884 * @param {Number} oldIndex
57885 * @param {Number} newIndex
57887 "columnmove" : true,
57890 * Fires when row(s) start being dragged
57891 * @param {Grid} this
57892 * @param {Roo.GridDD} dd The drag drop object
57893 * @param {event} e The raw browser event
57895 "startdrag" : true,
57898 * Fires when a drag operation is complete
57899 * @param {Grid} this
57900 * @param {Roo.GridDD} dd The drag drop object
57901 * @param {event} e The raw browser event
57906 * Fires when dragged row(s) are dropped on a valid DD target
57907 * @param {Grid} this
57908 * @param {Roo.GridDD} dd The drag drop object
57909 * @param {String} targetId The target drag drop object
57910 * @param {event} e The raw browser event
57915 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
57916 * @param {Grid} this
57917 * @param {Roo.GridDD} dd The drag drop object
57918 * @param {String} targetId The target drag drop object
57919 * @param {event} e The raw browser event
57924 * Fires when the dragged row(s) first cross another DD target while being dragged
57925 * @param {Grid} this
57926 * @param {Roo.GridDD} dd The drag drop object
57927 * @param {String} targetId The target drag drop object
57928 * @param {event} e The raw browser event
57930 "dragenter" : true,
57933 * Fires when the dragged row(s) leave another DD target while being dragged
57934 * @param {Grid} this
57935 * @param {Roo.GridDD} dd The drag drop object
57936 * @param {String} targetId The target drag drop object
57937 * @param {event} e The raw browser event
57942 * Fires when a row is rendered, so you can change add a style to it.
57943 * @param {GridView} gridview The grid view
57944 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
57950 * Fires when the grid is rendered
57951 * @param {Grid} grid
57956 Roo.grid.Grid.superclass.constructor.call(this);
57958 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
57961 * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
57964 * @cfg {Roo.grid.GridView} view The view that renders the grid (default = Roo.grid.GridView)
57967 * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
57970 * @cfg {Roo.grid.Store} ds The data store for the grid
57973 * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
57976 * @cfg {String} ddGroup - drag drop group.
57979 * @cfg {String} dragGroup - drag group (?? not sure if needed.)
57983 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
57985 minColumnWidth : 25,
57988 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
57989 * <b>on initial render.</b> It is more efficient to explicitly size the columns
57990 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
57992 autoSizeColumns : false,
57995 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
57997 autoSizeHeaders : true,
58000 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
58002 monitorWindowResize : true,
58005 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
58006 * rows measured to get a columns size. Default is 0 (all rows).
58008 maxRowsToMeasure : 0,
58011 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
58013 trackMouseOver : true,
58016 * @cfg {Boolean} enableDrag True to enable drag of rows. Default is false. (double check if this is needed?)
58019 * @cfg {Boolean} enableDrop True to enable drop of elements. Default is false. (double check if this is needed?)
58023 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
58025 enableDragDrop : false,
58028 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
58030 enableColumnMove : true,
58033 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
58035 enableColumnHide : true,
58038 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
58040 enableRowHeightSync : false,
58043 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
58048 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
58050 autoHeight : false,
58053 * @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.
58055 autoExpandColumn : false,
58058 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
58061 autoExpandMin : 50,
58064 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
58066 autoExpandMax : 1000,
58069 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
58074 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
58078 * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
58088 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
58089 * of a fixed width. Default is false.
58092 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
58097 * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
58098 * %0 is replaced with the number of selected rows.
58100 ddText : "{0} selected row{1}",
58104 * Called once after all setup has been completed and the grid is ready to be rendered.
58105 * @return {Roo.grid.Grid} this
58107 render : function()
58109 var c = this.container;
58110 // try to detect autoHeight/width mode
58111 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
58112 this.autoHeight = true;
58114 var view = this.getView();
58117 c.on("click", this.onClick, this);
58118 c.on("dblclick", this.onDblClick, this);
58119 c.on("contextmenu", this.onContextMenu, this);
58120 c.on("keydown", this.onKeyDown, this);
58122 c.on("touchstart", this.onTouchStart, this);
58125 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
58127 this.getSelectionModel().init(this);
58132 this.loadMask = new Roo.LoadMask(this.container,
58133 Roo.apply({store:this.dataSource}, this.loadMask));
58137 if (this.toolbar && this.toolbar.xtype) {
58138 this.toolbar.container = this.getView().getHeaderPanel(true);
58139 this.toolbar = new Roo.Toolbar(this.toolbar);
58141 if (this.footer && this.footer.xtype) {
58142 this.footer.dataSource = this.getDataSource();
58143 this.footer.container = this.getView().getFooterPanel(true);
58144 this.footer = Roo.factory(this.footer, Roo);
58146 if (this.dropTarget && this.dropTarget.xtype) {
58147 delete this.dropTarget.xtype;
58148 this.dropTarget = new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
58152 this.rendered = true;
58153 this.fireEvent('render', this);
58158 * Reconfigures the grid to use a different Store and Column Model.
58159 * The View will be bound to the new objects and refreshed.
58160 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
58161 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
58163 reconfigure : function(dataSource, colModel){
58165 this.loadMask.destroy();
58166 this.loadMask = new Roo.LoadMask(this.container,
58167 Roo.apply({store:dataSource}, this.loadMask));
58169 this.view.bind(dataSource, colModel);
58170 this.dataSource = dataSource;
58171 this.colModel = colModel;
58172 this.view.refresh(true);
58176 * Add's a column, default at the end..
58178 * @param {int} position to add (default end)
58179 * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel}
58181 addColumns : function(pos, ar)
58184 for (var i =0;i< ar.length;i++) {
58186 cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
58187 this.cm.lookup[cfg.id] = cfg;
58191 if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
58192 pos = this.cm.config.length; //this.cm.config.push(cfg);
58194 pos = Math.max(0,pos);
58197 this.cm.config.splice.apply(this.cm.config, ar);
58201 this.view.generateRules(this.cm);
58202 this.view.refresh(true);
58210 onKeyDown : function(e){
58211 this.fireEvent("keydown", e);
58215 * Destroy this grid.
58216 * @param {Boolean} removeEl True to remove the element
58218 destroy : function(removeEl, keepListeners){
58220 this.loadMask.destroy();
58222 var c = this.container;
58223 c.removeAllListeners();
58224 this.view.destroy();
58225 this.colModel.purgeListeners();
58226 if(!keepListeners){
58227 this.purgeListeners();
58230 if(removeEl === true){
58236 processEvent : function(name, e){
58237 // does this fire select???
58238 //Roo.log('grid:processEvent ' + name);
58240 if (name != 'touchstart' ) {
58241 this.fireEvent(name, e);
58244 var t = e.getTarget();
58246 var header = v.findHeaderIndex(t);
58247 if(header !== false){
58248 var ename = name == 'touchstart' ? 'click' : name;
58250 this.fireEvent("header" + ename, this, header, e);
58252 var row = v.findRowIndex(t);
58253 var cell = v.findCellIndex(t);
58254 if (name == 'touchstart') {
58255 // first touch is always a click.
58256 // hopefull this happens after selection is updated.?
58259 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
58260 var cs = this.selModel.getSelectedCell();
58261 if (row == cs[0] && cell == cs[1]){
58265 if (typeof(this.selModel.getSelections) != 'undefined') {
58266 var cs = this.selModel.getSelections();
58267 var ds = this.dataSource;
58268 if (cs.length == 1 && ds.getAt(row) == cs[0]){
58279 this.fireEvent("row" + name, this, row, e);
58280 if(cell !== false){
58281 this.fireEvent("cell" + name, this, row, cell, e);
58288 onClick : function(e){
58289 this.processEvent("click", e);
58292 onTouchStart : function(e){
58293 this.processEvent("touchstart", e);
58297 onContextMenu : function(e, t){
58298 this.processEvent("contextmenu", e);
58302 onDblClick : function(e){
58303 this.processEvent("dblclick", e);
58307 walkCells : function(row, col, step, fn, scope){
58308 var cm = this.colModel, clen = cm.getColumnCount();
58309 var ds = this.dataSource, rlen = ds.getCount(), first = true;
58321 if(fn.call(scope || this, row, col, cm) === true){
58339 if(fn.call(scope || this, row, col, cm) === true){
58351 getSelections : function(){
58352 return this.selModel.getSelections();
58356 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
58357 * but if manual update is required this method will initiate it.
58359 autoSize : function(){
58361 this.view.layout();
58362 if(this.view.adjustForScroll){
58363 this.view.adjustForScroll();
58369 * Returns the grid's underlying element.
58370 * @return {Element} The element
58372 getGridEl : function(){
58373 return this.container;
58376 // private for compatibility, overridden by editor grid
58377 stopEditing : function(){},
58380 * Returns the grid's SelectionModel.
58381 * @return {SelectionModel}
58383 getSelectionModel : function(){
58384 if(!this.selModel){
58385 this.selModel = new Roo.grid.RowSelectionModel();
58387 return this.selModel;
58391 * Returns the grid's DataSource.
58392 * @return {DataSource}
58394 getDataSource : function(){
58395 return this.dataSource;
58399 * Returns the grid's ColumnModel.
58400 * @return {ColumnModel}
58402 getColumnModel : function(){
58403 return this.colModel;
58407 * Returns the grid's GridView object.
58408 * @return {GridView}
58410 getView : function(){
58412 this.view = new Roo.grid.GridView(this.viewConfig);
58413 this.relayEvents(this.view, [
58414 "beforerowremoved", "beforerowsinserted",
58415 "beforerefresh", "rowremoved",
58416 "rowsinserted", "rowupdated" ,"refresh"
58422 * Called to get grid's drag proxy text, by default returns this.ddText.
58423 * Override this to put something different in the dragged text.
58426 getDragDropText : function(){
58427 var count = this.selModel.getCount();
58428 return String.format(this.ddText, count, count == 1 ? '' : 's');
58433 * Ext JS Library 1.1.1
58434 * Copyright(c) 2006-2007, Ext JS, LLC.
58436 * Originally Released Under LGPL - original licence link has changed is not relivant.
58439 * <script type="text/javascript">
58442 * @class Roo.grid.AbstractGridView
58443 * @extends Roo.util.Observable
58445 * Abstract base class for grid Views
58448 Roo.grid.AbstractGridView = function(){
58452 "beforerowremoved" : true,
58453 "beforerowsinserted" : true,
58454 "beforerefresh" : true,
58455 "rowremoved" : true,
58456 "rowsinserted" : true,
58457 "rowupdated" : true,
58460 Roo.grid.AbstractGridView.superclass.constructor.call(this);
58463 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
58464 rowClass : "x-grid-row",
58465 cellClass : "x-grid-cell",
58466 tdClass : "x-grid-td",
58467 hdClass : "x-grid-hd",
58468 splitClass : "x-grid-hd-split",
58470 init: function(grid){
58472 var cid = this.grid.getGridEl().id;
58473 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
58474 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
58475 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
58476 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
58479 getColumnRenderers : function(){
58480 var renderers = [];
58481 var cm = this.grid.colModel;
58482 var colCount = cm.getColumnCount();
58483 for(var i = 0; i < colCount; i++){
58484 renderers[i] = cm.getRenderer(i);
58489 getColumnIds : function(){
58491 var cm = this.grid.colModel;
58492 var colCount = cm.getColumnCount();
58493 for(var i = 0; i < colCount; i++){
58494 ids[i] = cm.getColumnId(i);
58499 getDataIndexes : function(){
58500 if(!this.indexMap){
58501 this.indexMap = this.buildIndexMap();
58503 return this.indexMap.colToData;
58506 getColumnIndexByDataIndex : function(dataIndex){
58507 if(!this.indexMap){
58508 this.indexMap = this.buildIndexMap();
58510 return this.indexMap.dataToCol[dataIndex];
58514 * Set a css style for a column dynamically.
58515 * @param {Number} colIndex The index of the column
58516 * @param {String} name The css property name
58517 * @param {String} value The css value
58519 setCSSStyle : function(colIndex, name, value){
58520 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
58521 Roo.util.CSS.updateRule(selector, name, value);
58524 generateRules : function(cm){
58525 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
58526 Roo.util.CSS.removeStyleSheet(rulesId);
58527 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
58528 var cid = cm.getColumnId(i);
58529 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
58530 this.tdSelector, cid, " {\n}\n",
58531 this.hdSelector, cid, " {\n}\n",
58532 this.splitSelector, cid, " {\n}\n");
58534 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
58538 * Ext JS Library 1.1.1
58539 * Copyright(c) 2006-2007, Ext JS, LLC.
58541 * Originally Released Under LGPL - original licence link has changed is not relivant.
58544 * <script type="text/javascript">
58548 // This is a support class used internally by the Grid components
58549 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
58551 this.view = grid.getView();
58552 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
58553 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
58555 this.setHandleElId(Roo.id(hd));
58556 this.setOuterHandleElId(Roo.id(hd2));
58558 this.scroll = false;
58560 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
58562 getDragData : function(e){
58563 var t = Roo.lib.Event.getTarget(e);
58564 var h = this.view.findHeaderCell(t);
58566 return {ddel: h.firstChild, header:h};
58571 onInitDrag : function(e){
58572 this.view.headersDisabled = true;
58573 var clone = this.dragData.ddel.cloneNode(true);
58574 clone.id = Roo.id();
58575 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
58576 this.proxy.update(clone);
58580 afterValidDrop : function(){
58582 setTimeout(function(){
58583 v.headersDisabled = false;
58587 afterInvalidDrop : function(){
58589 setTimeout(function(){
58590 v.headersDisabled = false;
58596 * Ext JS Library 1.1.1
58597 * Copyright(c) 2006-2007, Ext JS, LLC.
58599 * Originally Released Under LGPL - original licence link has changed is not relivant.
58602 * <script type="text/javascript">
58605 // This is a support class used internally by the Grid components
58606 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
58608 this.view = grid.getView();
58609 // split the proxies so they don't interfere with mouse events
58610 this.proxyTop = Roo.DomHelper.append(document.body, {
58611 cls:"col-move-top", html:" "
58613 this.proxyBottom = Roo.DomHelper.append(document.body, {
58614 cls:"col-move-bottom", html:" "
58616 this.proxyTop.hide = this.proxyBottom.hide = function(){
58617 this.setLeftTop(-100,-100);
58618 this.setStyle("visibility", "hidden");
58620 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
58621 // temporarily disabled
58622 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
58623 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
58625 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
58626 proxyOffsets : [-4, -9],
58627 fly: Roo.Element.fly,
58629 getTargetFromEvent : function(e){
58630 var t = Roo.lib.Event.getTarget(e);
58631 var cindex = this.view.findCellIndex(t);
58632 if(cindex !== false){
58633 return this.view.getHeaderCell(cindex);
58638 nextVisible : function(h){
58639 var v = this.view, cm = this.grid.colModel;
58642 if(!cm.isHidden(v.getCellIndex(h))){
58650 prevVisible : function(h){
58651 var v = this.view, cm = this.grid.colModel;
58654 if(!cm.isHidden(v.getCellIndex(h))){
58662 positionIndicator : function(h, n, e){
58663 var x = Roo.lib.Event.getPageX(e);
58664 var r = Roo.lib.Dom.getRegion(n.firstChild);
58665 var px, pt, py = r.top + this.proxyOffsets[1];
58666 if((r.right - x) <= (r.right-r.left)/2){
58667 px = r.right+this.view.borderWidth;
58673 var oldIndex = this.view.getCellIndex(h);
58674 var newIndex = this.view.getCellIndex(n);
58676 if(this.grid.colModel.isFixed(newIndex)){
58680 var locked = this.grid.colModel.isLocked(newIndex);
58685 if(oldIndex < newIndex){
58688 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
58691 px += this.proxyOffsets[0];
58692 this.proxyTop.setLeftTop(px, py);
58693 this.proxyTop.show();
58694 if(!this.bottomOffset){
58695 this.bottomOffset = this.view.mainHd.getHeight();
58697 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
58698 this.proxyBottom.show();
58702 onNodeEnter : function(n, dd, e, data){
58703 if(data.header != n){
58704 this.positionIndicator(data.header, n, e);
58708 onNodeOver : function(n, dd, e, data){
58709 var result = false;
58710 if(data.header != n){
58711 result = this.positionIndicator(data.header, n, e);
58714 this.proxyTop.hide();
58715 this.proxyBottom.hide();
58717 return result ? this.dropAllowed : this.dropNotAllowed;
58720 onNodeOut : function(n, dd, e, data){
58721 this.proxyTop.hide();
58722 this.proxyBottom.hide();
58725 onNodeDrop : function(n, dd, e, data){
58726 var h = data.header;
58728 var cm = this.grid.colModel;
58729 var x = Roo.lib.Event.getPageX(e);
58730 var r = Roo.lib.Dom.getRegion(n.firstChild);
58731 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
58732 var oldIndex = this.view.getCellIndex(h);
58733 var newIndex = this.view.getCellIndex(n);
58734 var locked = cm.isLocked(newIndex);
58738 if(oldIndex < newIndex){
58741 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
58744 cm.setLocked(oldIndex, locked, true);
58745 cm.moveColumn(oldIndex, newIndex);
58746 this.grid.fireEvent("columnmove", oldIndex, newIndex);
58754 * Ext JS Library 1.1.1
58755 * Copyright(c) 2006-2007, Ext JS, LLC.
58757 * Originally Released Under LGPL - original licence link has changed is not relivant.
58760 * <script type="text/javascript">
58764 * @class Roo.grid.GridView
58765 * @extends Roo.util.Observable
58768 * @param {Object} config
58770 Roo.grid.GridView = function(config){
58771 Roo.grid.GridView.superclass.constructor.call(this);
58774 Roo.apply(this, config);
58777 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
58779 unselectable : 'unselectable="on"',
58780 unselectableCls : 'x-unselectable',
58783 rowClass : "x-grid-row",
58785 cellClass : "x-grid-col",
58787 tdClass : "x-grid-td",
58789 hdClass : "x-grid-hd",
58791 splitClass : "x-grid-split",
58793 sortClasses : ["sort-asc", "sort-desc"],
58795 enableMoveAnim : false,
58799 dh : Roo.DomHelper,
58801 fly : Roo.Element.fly,
58803 css : Roo.util.CSS,
58809 scrollIncrement : 22,
58811 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
58813 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
58815 bind : function(ds, cm){
58817 this.ds.un("load", this.onLoad, this);
58818 this.ds.un("datachanged", this.onDataChange, this);
58819 this.ds.un("add", this.onAdd, this);
58820 this.ds.un("remove", this.onRemove, this);
58821 this.ds.un("update", this.onUpdate, this);
58822 this.ds.un("clear", this.onClear, this);
58825 ds.on("load", this.onLoad, this);
58826 ds.on("datachanged", this.onDataChange, this);
58827 ds.on("add", this.onAdd, this);
58828 ds.on("remove", this.onRemove, this);
58829 ds.on("update", this.onUpdate, this);
58830 ds.on("clear", this.onClear, this);
58835 this.cm.un("widthchange", this.onColWidthChange, this);
58836 this.cm.un("headerchange", this.onHeaderChange, this);
58837 this.cm.un("hiddenchange", this.onHiddenChange, this);
58838 this.cm.un("columnmoved", this.onColumnMove, this);
58839 this.cm.un("columnlockchange", this.onColumnLock, this);
58842 this.generateRules(cm);
58843 cm.on("widthchange", this.onColWidthChange, this);
58844 cm.on("headerchange", this.onHeaderChange, this);
58845 cm.on("hiddenchange", this.onHiddenChange, this);
58846 cm.on("columnmoved", this.onColumnMove, this);
58847 cm.on("columnlockchange", this.onColumnLock, this);
58852 init: function(grid){
58853 Roo.grid.GridView.superclass.init.call(this, grid);
58855 this.bind(grid.dataSource, grid.colModel);
58857 grid.on("headerclick", this.handleHeaderClick, this);
58859 if(grid.trackMouseOver){
58860 grid.on("mouseover", this.onRowOver, this);
58861 grid.on("mouseout", this.onRowOut, this);
58863 grid.cancelTextSelection = function(){};
58864 this.gridId = grid.id;
58866 var tpls = this.templates || {};
58869 tpls.master = new Roo.Template(
58870 '<div class="x-grid" hidefocus="true">',
58871 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
58872 '<div class="x-grid-topbar"></div>',
58873 '<div class="x-grid-scroller"><div></div></div>',
58874 '<div class="x-grid-locked">',
58875 '<div class="x-grid-header">{lockedHeader}</div>',
58876 '<div class="x-grid-body">{lockedBody}</div>',
58878 '<div class="x-grid-viewport">',
58879 '<div class="x-grid-header">{header}</div>',
58880 '<div class="x-grid-body">{body}</div>',
58882 '<div class="x-grid-bottombar"></div>',
58884 '<div class="x-grid-resize-proxy"> </div>',
58887 tpls.master.disableformats = true;
58891 tpls.header = new Roo.Template(
58892 '<table border="0" cellspacing="0" cellpadding="0">',
58893 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
58896 tpls.header.disableformats = true;
58898 tpls.header.compile();
58901 tpls.hcell = new Roo.Template(
58902 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
58903 '<div class="x-grid-hd-text ' + this.unselectableCls + '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
58906 tpls.hcell.disableFormats = true;
58908 tpls.hcell.compile();
58911 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
58912 this.unselectableCls + '" ' + this.unselectable +'> </div>');
58913 tpls.hsplit.disableFormats = true;
58915 tpls.hsplit.compile();
58918 tpls.body = new Roo.Template(
58919 '<table border="0" cellspacing="0" cellpadding="0">',
58920 "<tbody>{rows}</tbody>",
58923 tpls.body.disableFormats = true;
58925 tpls.body.compile();
58928 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
58929 tpls.row.disableFormats = true;
58931 tpls.row.compile();
58934 tpls.cell = new Roo.Template(
58935 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
58936 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
58937 this.unselectableCls + '" ' + this.unselectable +'" {attr}>{value}</div></div>',
58940 tpls.cell.disableFormats = true;
58942 tpls.cell.compile();
58944 this.templates = tpls;
58947 // remap these for backwards compat
58948 onColWidthChange : function(){
58949 this.updateColumns.apply(this, arguments);
58951 onHeaderChange : function(){
58952 this.updateHeaders.apply(this, arguments);
58954 onHiddenChange : function(){
58955 this.handleHiddenChange.apply(this, arguments);
58957 onColumnMove : function(){
58958 this.handleColumnMove.apply(this, arguments);
58960 onColumnLock : function(){
58961 this.handleLockChange.apply(this, arguments);
58964 onDataChange : function(){
58966 this.updateHeaderSortState();
58969 onClear : function(){
58973 onUpdate : function(ds, record){
58974 this.refreshRow(record);
58977 refreshRow : function(record){
58978 var ds = this.ds, index;
58979 if(typeof record == 'number'){
58981 record = ds.getAt(index);
58983 index = ds.indexOf(record);
58985 this.insertRows(ds, index, index, true);
58986 this.onRemove(ds, record, index+1, true);
58987 this.syncRowHeights(index, index);
58989 this.fireEvent("rowupdated", this, index, record);
58992 onAdd : function(ds, records, index){
58993 this.insertRows(ds, index, index + (records.length-1));
58996 onRemove : function(ds, record, index, isUpdate){
58997 if(isUpdate !== true){
58998 this.fireEvent("beforerowremoved", this, index, record);
59000 var bt = this.getBodyTable(), lt = this.getLockedTable();
59001 if(bt.rows[index]){
59002 bt.firstChild.removeChild(bt.rows[index]);
59004 if(lt.rows[index]){
59005 lt.firstChild.removeChild(lt.rows[index]);
59007 if(isUpdate !== true){
59008 this.stripeRows(index);
59009 this.syncRowHeights(index, index);
59011 this.fireEvent("rowremoved", this, index, record);
59015 onLoad : function(){
59016 this.scrollToTop();
59020 * Scrolls the grid to the top
59022 scrollToTop : function(){
59024 this.scroller.dom.scrollTop = 0;
59030 * Gets a panel in the header of the grid that can be used for toolbars etc.
59031 * After modifying the contents of this panel a call to grid.autoSize() may be
59032 * required to register any changes in size.
59033 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
59034 * @return Roo.Element
59036 getHeaderPanel : function(doShow){
59038 this.headerPanel.show();
59040 return this.headerPanel;
59044 * Gets a panel in the footer of the grid that can be used for toolbars etc.
59045 * After modifying the contents of this panel a call to grid.autoSize() may be
59046 * required to register any changes in size.
59047 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
59048 * @return Roo.Element
59050 getFooterPanel : function(doShow){
59052 this.footerPanel.show();
59054 return this.footerPanel;
59057 initElements : function(){
59058 var E = Roo.Element;
59059 var el = this.grid.getGridEl().dom.firstChild;
59060 var cs = el.childNodes;
59062 this.el = new E(el);
59064 this.focusEl = new E(el.firstChild);
59065 this.focusEl.swallowEvent("click", true);
59067 this.headerPanel = new E(cs[1]);
59068 this.headerPanel.enableDisplayMode("block");
59070 this.scroller = new E(cs[2]);
59071 this.scrollSizer = new E(this.scroller.dom.firstChild);
59073 this.lockedWrap = new E(cs[3]);
59074 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
59075 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
59077 this.mainWrap = new E(cs[4]);
59078 this.mainHd = new E(this.mainWrap.dom.firstChild);
59079 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
59081 this.footerPanel = new E(cs[5]);
59082 this.footerPanel.enableDisplayMode("block");
59084 this.resizeProxy = new E(cs[6]);
59086 this.headerSelector = String.format(
59087 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
59088 this.lockedHd.id, this.mainHd.id
59091 this.splitterSelector = String.format(
59092 '#{0} div.x-grid-split, #{1} div.x-grid-split',
59093 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
59096 idToCssName : function(s)
59098 return s.replace(/[^a-z0-9]+/ig, '-');
59101 getHeaderCell : function(index){
59102 return Roo.DomQuery.select(this.headerSelector)[index];
59105 getHeaderCellMeasure : function(index){
59106 return this.getHeaderCell(index).firstChild;
59109 getHeaderCellText : function(index){
59110 return this.getHeaderCell(index).firstChild.firstChild;
59113 getLockedTable : function(){
59114 return this.lockedBody.dom.firstChild;
59117 getBodyTable : function(){
59118 return this.mainBody.dom.firstChild;
59121 getLockedRow : function(index){
59122 return this.getLockedTable().rows[index];
59125 getRow : function(index){
59126 return this.getBodyTable().rows[index];
59129 getRowComposite : function(index){
59131 this.rowEl = new Roo.CompositeElementLite();
59133 var els = [], lrow, mrow;
59134 if(lrow = this.getLockedRow(index)){
59137 if(mrow = this.getRow(index)){
59140 this.rowEl.elements = els;
59144 * Gets the 'td' of the cell
59146 * @param {Integer} rowIndex row to select
59147 * @param {Integer} colIndex column to select
59151 getCell : function(rowIndex, colIndex){
59152 var locked = this.cm.getLockedCount();
59154 if(colIndex < locked){
59155 source = this.lockedBody.dom.firstChild;
59157 source = this.mainBody.dom.firstChild;
59158 colIndex -= locked;
59160 return source.rows[rowIndex].childNodes[colIndex];
59163 getCellText : function(rowIndex, colIndex){
59164 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
59167 getCellBox : function(cell){
59168 var b = this.fly(cell).getBox();
59169 if(Roo.isOpera){ // opera fails to report the Y
59170 b.y = cell.offsetTop + this.mainBody.getY();
59175 getCellIndex : function(cell){
59176 var id = String(cell.className).match(this.cellRE);
59178 return parseInt(id[1], 10);
59183 findHeaderIndex : function(n){
59184 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
59185 return r ? this.getCellIndex(r) : false;
59188 findHeaderCell : function(n){
59189 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
59190 return r ? r : false;
59193 findRowIndex : function(n){
59197 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
59198 return r ? r.rowIndex : false;
59201 findCellIndex : function(node){
59202 var stop = this.el.dom;
59203 while(node && node != stop){
59204 if(this.findRE.test(node.className)){
59205 return this.getCellIndex(node);
59207 node = node.parentNode;
59212 getColumnId : function(index){
59213 return this.cm.getColumnId(index);
59216 getSplitters : function()
59218 if(this.splitterSelector){
59219 return Roo.DomQuery.select(this.splitterSelector);
59225 getSplitter : function(index){
59226 return this.getSplitters()[index];
59229 onRowOver : function(e, t){
59231 if((row = this.findRowIndex(t)) !== false){
59232 this.getRowComposite(row).addClass("x-grid-row-over");
59236 onRowOut : function(e, t){
59238 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
59239 this.getRowComposite(row).removeClass("x-grid-row-over");
59243 renderHeaders : function(){
59245 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
59246 var cb = [], lb = [], sb = [], lsb = [], p = {};
59247 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
59248 p.cellId = "x-grid-hd-0-" + i;
59249 p.splitId = "x-grid-csplit-0-" + i;
59250 p.id = cm.getColumnId(i);
59251 p.value = cm.getColumnHeader(i) || "";
59252 p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</) ? '' : p.value || "";
59253 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
59254 if(!cm.isLocked(i)){
59255 cb[cb.length] = ct.apply(p);
59256 sb[sb.length] = st.apply(p);
59258 lb[lb.length] = ct.apply(p);
59259 lsb[lsb.length] = st.apply(p);
59262 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
59263 ht.apply({cells: cb.join(""), splits:sb.join("")})];
59266 updateHeaders : function(){
59267 var html = this.renderHeaders();
59268 this.lockedHd.update(html[0]);
59269 this.mainHd.update(html[1]);
59273 * Focuses the specified row.
59274 * @param {Number} row The row index
59276 focusRow : function(row)
59278 //Roo.log('GridView.focusRow');
59279 var x = this.scroller.dom.scrollLeft;
59280 this.focusCell(row, 0, false);
59281 this.scroller.dom.scrollLeft = x;
59285 * Focuses the specified cell.
59286 * @param {Number} row The row index
59287 * @param {Number} col The column index
59288 * @param {Boolean} hscroll false to disable horizontal scrolling
59290 focusCell : function(row, col, hscroll)
59292 //Roo.log('GridView.focusCell');
59293 var el = this.ensureVisible(row, col, hscroll);
59294 this.focusEl.alignTo(el, "tl-tl");
59296 this.focusEl.focus();
59298 this.focusEl.focus.defer(1, this.focusEl);
59303 * Scrolls the specified cell into view
59304 * @param {Number} row The row index
59305 * @param {Number} col The column index
59306 * @param {Boolean} hscroll false to disable horizontal scrolling
59308 ensureVisible : function(row, col, hscroll)
59310 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
59311 //return null; //disable for testing.
59312 if(typeof row != "number"){
59313 row = row.rowIndex;
59315 if(row < 0 && row >= this.ds.getCount()){
59318 col = (col !== undefined ? col : 0);
59319 var cm = this.grid.colModel;
59320 while(cm.isHidden(col)){
59324 var el = this.getCell(row, col);
59328 var c = this.scroller.dom;
59330 var ctop = parseInt(el.offsetTop, 10);
59331 var cleft = parseInt(el.offsetLeft, 10);
59332 var cbot = ctop + el.offsetHeight;
59333 var cright = cleft + el.offsetWidth;
59335 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
59336 var stop = parseInt(c.scrollTop, 10);
59337 var sleft = parseInt(c.scrollLeft, 10);
59338 var sbot = stop + ch;
59339 var sright = sleft + c.clientWidth;
59341 Roo.log('GridView.ensureVisible:' +
59343 ' c.clientHeight:' + c.clientHeight +
59344 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
59352 c.scrollTop = ctop;
59353 //Roo.log("set scrolltop to ctop DISABLE?");
59354 }else if(cbot > sbot){
59355 //Roo.log("set scrolltop to cbot-ch");
59356 c.scrollTop = cbot-ch;
59359 if(hscroll !== false){
59361 c.scrollLeft = cleft;
59362 }else if(cright > sright){
59363 c.scrollLeft = cright-c.clientWidth;
59370 updateColumns : function(){
59371 this.grid.stopEditing();
59372 var cm = this.grid.colModel, colIds = this.getColumnIds();
59373 //var totalWidth = cm.getTotalWidth();
59375 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
59376 //if(cm.isHidden(i)) continue;
59377 var w = cm.getColumnWidth(i);
59378 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
59379 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
59381 this.updateSplitters();
59384 generateRules : function(cm){
59385 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
59386 Roo.util.CSS.removeStyleSheet(rulesId);
59387 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
59388 var cid = cm.getColumnId(i);
59390 if(cm.config[i].align){
59391 align = 'text-align:'+cm.config[i].align+';';
59394 if(cm.isHidden(i)){
59395 hidden = 'display:none;';
59397 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
59399 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
59400 this.hdSelector, cid, " {\n", align, width, "}\n",
59401 this.tdSelector, cid, " {\n",hidden,"\n}\n",
59402 this.splitSelector, cid, " {\n", hidden , "\n}\n");
59404 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
59407 updateSplitters : function(){
59408 var cm = this.cm, s = this.getSplitters();
59409 if(s){ // splitters not created yet
59410 var pos = 0, locked = true;
59411 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
59412 if(cm.isHidden(i)) {
59415 var w = cm.getColumnWidth(i); // make sure it's a number
59416 if(!cm.isLocked(i) && locked){
59421 s[i].style.left = (pos-this.splitOffset) + "px";
59426 handleHiddenChange : function(colModel, colIndex, hidden){
59428 this.hideColumn(colIndex);
59430 this.unhideColumn(colIndex);
59434 hideColumn : function(colIndex){
59435 var cid = this.getColumnId(colIndex);
59436 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
59437 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
59439 this.updateHeaders();
59441 this.updateSplitters();
59445 unhideColumn : function(colIndex){
59446 var cid = this.getColumnId(colIndex);
59447 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
59448 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
59451 this.updateHeaders();
59453 this.updateSplitters();
59457 insertRows : function(dm, firstRow, lastRow, isUpdate){
59458 if(firstRow == 0 && lastRow == dm.getCount()-1){
59462 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
59464 var s = this.getScrollState();
59465 var markup = this.renderRows(firstRow, lastRow);
59466 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
59467 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
59468 this.restoreScroll(s);
59470 this.fireEvent("rowsinserted", this, firstRow, lastRow);
59471 this.syncRowHeights(firstRow, lastRow);
59472 this.stripeRows(firstRow);
59478 bufferRows : function(markup, target, index){
59479 var before = null, trows = target.rows, tbody = target.tBodies[0];
59480 if(index < trows.length){
59481 before = trows[index];
59483 var b = document.createElement("div");
59484 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
59485 var rows = b.firstChild.rows;
59486 for(var i = 0, len = rows.length; i < len; i++){
59488 tbody.insertBefore(rows[0], before);
59490 tbody.appendChild(rows[0]);
59497 deleteRows : function(dm, firstRow, lastRow){
59498 if(dm.getRowCount()<1){
59499 this.fireEvent("beforerefresh", this);
59500 this.mainBody.update("");
59501 this.lockedBody.update("");
59502 this.fireEvent("refresh", this);
59504 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
59505 var bt = this.getBodyTable();
59506 var tbody = bt.firstChild;
59507 var rows = bt.rows;
59508 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
59509 tbody.removeChild(rows[firstRow]);
59511 this.stripeRows(firstRow);
59512 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
59516 updateRows : function(dataSource, firstRow, lastRow){
59517 var s = this.getScrollState();
59519 this.restoreScroll(s);
59522 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
59526 this.updateHeaderSortState();
59529 getScrollState : function(){
59531 var sb = this.scroller.dom;
59532 return {left: sb.scrollLeft, top: sb.scrollTop};
59535 stripeRows : function(startRow){
59536 if(!this.grid.stripeRows || this.ds.getCount() < 1){
59539 startRow = startRow || 0;
59540 var rows = this.getBodyTable().rows;
59541 var lrows = this.getLockedTable().rows;
59542 var cls = ' x-grid-row-alt ';
59543 for(var i = startRow, len = rows.length; i < len; i++){
59544 var row = rows[i], lrow = lrows[i];
59545 var isAlt = ((i+1) % 2 == 0);
59546 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
59547 if(isAlt == hasAlt){
59551 row.className += " x-grid-row-alt";
59553 row.className = row.className.replace("x-grid-row-alt", "");
59556 lrow.className = row.className;
59561 restoreScroll : function(state){
59562 //Roo.log('GridView.restoreScroll');
59563 var sb = this.scroller.dom;
59564 sb.scrollLeft = state.left;
59565 sb.scrollTop = state.top;
59569 syncScroll : function(){
59570 //Roo.log('GridView.syncScroll');
59571 var sb = this.scroller.dom;
59572 var sh = this.mainHd.dom;
59573 var bs = this.mainBody.dom;
59574 var lv = this.lockedBody.dom;
59575 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
59576 lv.scrollTop = bs.scrollTop = sb.scrollTop;
59579 handleScroll : function(e){
59581 var sb = this.scroller.dom;
59582 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
59586 handleWheel : function(e){
59587 var d = e.getWheelDelta();
59588 this.scroller.dom.scrollTop -= d*22;
59589 // set this here to prevent jumpy scrolling on large tables
59590 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
59594 renderRows : function(startRow, endRow){
59595 // pull in all the crap needed to render rows
59596 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
59597 var colCount = cm.getColumnCount();
59599 if(ds.getCount() < 1){
59603 // build a map for all the columns
59605 for(var i = 0; i < colCount; i++){
59606 var name = cm.getDataIndex(i);
59608 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
59609 renderer : cm.getRenderer(i),
59610 id : cm.getColumnId(i),
59611 locked : cm.isLocked(i),
59612 has_editor : cm.isCellEditable(i)
59616 startRow = startRow || 0;
59617 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
59619 // records to render
59620 var rs = ds.getRange(startRow, endRow);
59622 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
59625 // As much as I hate to duplicate code, this was branched because FireFox really hates
59626 // [].join("") on strings. The performance difference was substantial enough to
59627 // branch this function
59628 doRender : Roo.isGecko ?
59629 function(cs, rs, ds, startRow, colCount, stripe){
59630 var ts = this.templates, ct = ts.cell, rt = ts.row;
59632 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
59634 var hasListener = this.grid.hasListener('rowclass');
59636 for(var j = 0, len = rs.length; j < len; j++){
59637 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
59638 for(var i = 0; i < colCount; i++){
59640 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
59642 p.css = p.attr = "";
59643 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
59644 if(p.value == undefined || p.value === "") {
59645 p.value = " ";
59648 p.css += ' x-grid-editable-cell';
59650 if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
59651 p.css += ' x-grid-dirty-cell';
59653 var markup = ct.apply(p);
59661 if(stripe && ((rowIndex+1) % 2 == 0)){
59662 alt.push("x-grid-row-alt")
59665 alt.push( " x-grid-dirty-row");
59668 if(this.getRowClass){
59669 alt.push(this.getRowClass(r, rowIndex));
59675 rowIndex : rowIndex,
59678 this.grid.fireEvent('rowclass', this, rowcfg);
59679 alt.push(rowcfg.rowClass);
59681 rp.alt = alt.join(" ");
59682 lbuf+= rt.apply(rp);
59684 buf+= rt.apply(rp);
59686 return [lbuf, buf];
59688 function(cs, rs, ds, startRow, colCount, stripe){
59689 var ts = this.templates, ct = ts.cell, rt = ts.row;
59691 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
59692 var hasListener = this.grid.hasListener('rowclass');
59695 for(var j = 0, len = rs.length; j < len; j++){
59696 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
59697 for(var i = 0; i < colCount; i++){
59699 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
59701 p.css = p.attr = "";
59702 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
59703 if(p.value == undefined || p.value === "") {
59704 p.value = " ";
59708 p.css += ' x-grid-editable-cell';
59710 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
59711 p.css += ' x-grid-dirty-cell'
59714 var markup = ct.apply(p);
59716 cb[cb.length] = markup;
59718 lcb[lcb.length] = markup;
59722 if(stripe && ((rowIndex+1) % 2 == 0)){
59723 alt.push( "x-grid-row-alt");
59726 alt.push(" x-grid-dirty-row");
59729 if(this.getRowClass){
59730 alt.push( this.getRowClass(r, rowIndex));
59736 rowIndex : rowIndex,
59739 this.grid.fireEvent('rowclass', this, rowcfg);
59740 alt.push(rowcfg.rowClass);
59743 rp.alt = alt.join(" ");
59744 rp.cells = lcb.join("");
59745 lbuf[lbuf.length] = rt.apply(rp);
59746 rp.cells = cb.join("");
59747 buf[buf.length] = rt.apply(rp);
59749 return [lbuf.join(""), buf.join("")];
59752 renderBody : function(){
59753 var markup = this.renderRows();
59754 var bt = this.templates.body;
59755 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
59759 * Refreshes the grid
59760 * @param {Boolean} headersToo
59762 refresh : function(headersToo){
59763 this.fireEvent("beforerefresh", this);
59764 this.grid.stopEditing();
59765 var result = this.renderBody();
59766 this.lockedBody.update(result[0]);
59767 this.mainBody.update(result[1]);
59768 if(headersToo === true){
59769 this.updateHeaders();
59770 this.updateColumns();
59771 this.updateSplitters();
59772 this.updateHeaderSortState();
59774 this.syncRowHeights();
59776 this.fireEvent("refresh", this);
59779 handleColumnMove : function(cm, oldIndex, newIndex){
59780 this.indexMap = null;
59781 var s = this.getScrollState();
59782 this.refresh(true);
59783 this.restoreScroll(s);
59784 this.afterMove(newIndex);
59787 afterMove : function(colIndex){
59788 if(this.enableMoveAnim && Roo.enableFx){
59789 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
59791 // if multisort - fix sortOrder, and reload..
59792 if (this.grid.dataSource.multiSort) {
59793 // the we can call sort again..
59794 var dm = this.grid.dataSource;
59795 var cm = this.grid.colModel;
59797 for(var i = 0; i < cm.config.length; i++ ) {
59799 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
59800 continue; // dont' bother, it's not in sort list or being set.
59803 so.push(cm.config[i].dataIndex);
59806 dm.load(dm.lastOptions);
59813 updateCell : function(dm, rowIndex, dataIndex){
59814 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
59815 if(typeof colIndex == "undefined"){ // not present in grid
59818 var cm = this.grid.colModel;
59819 var cell = this.getCell(rowIndex, colIndex);
59820 var cellText = this.getCellText(rowIndex, colIndex);
59823 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
59824 id : cm.getColumnId(colIndex),
59825 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
59827 var renderer = cm.getRenderer(colIndex);
59828 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
59829 if(typeof val == "undefined" || val === "") {
59832 cellText.innerHTML = val;
59833 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
59834 this.syncRowHeights(rowIndex, rowIndex);
59837 calcColumnWidth : function(colIndex, maxRowsToMeasure){
59839 if(this.grid.autoSizeHeaders){
59840 var h = this.getHeaderCellMeasure(colIndex);
59841 maxWidth = Math.max(maxWidth, h.scrollWidth);
59844 if(this.cm.isLocked(colIndex)){
59845 tb = this.getLockedTable();
59848 tb = this.getBodyTable();
59849 index = colIndex - this.cm.getLockedCount();
59852 var rows = tb.rows;
59853 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
59854 for(var i = 0; i < stopIndex; i++){
59855 var cell = rows[i].childNodes[index].firstChild;
59856 maxWidth = Math.max(maxWidth, cell.scrollWidth);
59859 return maxWidth + /*margin for error in IE*/ 5;
59862 * Autofit a column to its content.
59863 * @param {Number} colIndex
59864 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
59866 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
59867 if(this.cm.isHidden(colIndex)){
59868 return; // can't calc a hidden column
59871 var cid = this.cm.getColumnId(colIndex);
59872 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
59873 if(this.grid.autoSizeHeaders){
59874 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
59877 var newWidth = this.calcColumnWidth(colIndex);
59878 this.cm.setColumnWidth(colIndex,
59879 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
59880 if(!suppressEvent){
59881 this.grid.fireEvent("columnresize", colIndex, newWidth);
59886 * Autofits all columns to their content and then expands to fit any extra space in the grid
59888 autoSizeColumns : function(){
59889 var cm = this.grid.colModel;
59890 var colCount = cm.getColumnCount();
59891 for(var i = 0; i < colCount; i++){
59892 this.autoSizeColumn(i, true, true);
59894 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
59897 this.updateColumns();
59903 * Autofits all columns to the grid's width proportionate with their current size
59904 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
59906 fitColumns : function(reserveScrollSpace){
59907 var cm = this.grid.colModel;
59908 var colCount = cm.getColumnCount();
59912 for (i = 0; i < colCount; i++){
59913 if(!cm.isHidden(i) && !cm.isFixed(i)){
59914 w = cm.getColumnWidth(i);
59920 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
59921 if(reserveScrollSpace){
59924 var frac = (avail - cm.getTotalWidth())/width;
59925 while (cols.length){
59928 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
59930 this.updateColumns();
59934 onRowSelect : function(rowIndex){
59935 var row = this.getRowComposite(rowIndex);
59936 row.addClass("x-grid-row-selected");
59939 onRowDeselect : function(rowIndex){
59940 var row = this.getRowComposite(rowIndex);
59941 row.removeClass("x-grid-row-selected");
59944 onCellSelect : function(row, col){
59945 var cell = this.getCell(row, col);
59947 Roo.fly(cell).addClass("x-grid-cell-selected");
59951 onCellDeselect : function(row, col){
59952 var cell = this.getCell(row, col);
59954 Roo.fly(cell).removeClass("x-grid-cell-selected");
59958 updateHeaderSortState : function(){
59960 // sort state can be single { field: xxx, direction : yyy}
59961 // or { xxx=>ASC , yyy : DESC ..... }
59964 if (!this.ds.multiSort) {
59965 var state = this.ds.getSortState();
59969 mstate[state.field] = state.direction;
59970 // FIXME... - this is not used here.. but might be elsewhere..
59971 this.sortState = state;
59974 mstate = this.ds.sortToggle;
59976 //remove existing sort classes..
59978 var sc = this.sortClasses;
59979 var hds = this.el.select(this.headerSelector).removeClass(sc);
59981 for(var f in mstate) {
59983 var sortColumn = this.cm.findColumnIndex(f);
59985 if(sortColumn != -1){
59986 var sortDir = mstate[f];
59987 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
59996 handleHeaderClick : function(g, index,e){
59998 Roo.log("header click");
60001 // touch events on header are handled by context
60002 this.handleHdCtx(g,index,e);
60007 if(this.headersDisabled){
60010 var dm = g.dataSource, cm = g.colModel;
60011 if(!cm.isSortable(index)){
60016 if (dm.multiSort) {
60017 // update the sortOrder
60019 for(var i = 0; i < cm.config.length; i++ ) {
60021 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
60022 continue; // dont' bother, it's not in sort list or being set.
60025 so.push(cm.config[i].dataIndex);
60031 dm.sort(cm.getDataIndex(index));
60035 destroy : function(){
60037 this.colMenu.removeAll();
60038 Roo.menu.MenuMgr.unregister(this.colMenu);
60039 this.colMenu.getEl().remove();
60040 delete this.colMenu;
60043 this.hmenu.removeAll();
60044 Roo.menu.MenuMgr.unregister(this.hmenu);
60045 this.hmenu.getEl().remove();
60048 if(this.grid.enableColumnMove){
60049 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
60051 for(var dd in dds){
60052 if(!dds[dd].config.isTarget && dds[dd].dragElId){
60053 var elid = dds[dd].dragElId;
60055 Roo.get(elid).remove();
60056 } else if(dds[dd].config.isTarget){
60057 dds[dd].proxyTop.remove();
60058 dds[dd].proxyBottom.remove();
60061 if(Roo.dd.DDM.locationCache[dd]){
60062 delete Roo.dd.DDM.locationCache[dd];
60065 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
60068 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
60069 this.bind(null, null);
60070 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
60073 handleLockChange : function(){
60074 this.refresh(true);
60077 onDenyColumnLock : function(){
60081 onDenyColumnHide : function(){
60085 handleHdMenuClick : function(item){
60086 var index = this.hdCtxIndex;
60087 var cm = this.cm, ds = this.ds;
60090 ds.sort(cm.getDataIndex(index), "ASC");
60093 ds.sort(cm.getDataIndex(index), "DESC");
60096 var lc = cm.getLockedCount();
60097 if(cm.getColumnCount(true) <= lc+1){
60098 this.onDenyColumnLock();
60102 cm.setLocked(index, true, true);
60103 cm.moveColumn(index, lc);
60104 this.grid.fireEvent("columnmove", index, lc);
60106 cm.setLocked(index, true);
60110 var lc = cm.getLockedCount();
60111 if((lc-1) != index){
60112 cm.setLocked(index, false, true);
60113 cm.moveColumn(index, lc-1);
60114 this.grid.fireEvent("columnmove", index, lc-1);
60116 cm.setLocked(index, false);
60119 case 'wider': // used to expand cols on touch..
60121 var cw = cm.getColumnWidth(index);
60122 cw += (item.id == 'wider' ? 1 : -1) * 50;
60123 cw = Math.max(0, cw);
60124 cw = Math.min(cw,4000);
60125 cm.setColumnWidth(index, cw);
60129 index = cm.getIndexById(item.id.substr(4));
60131 if(item.checked && cm.getColumnCount(true) <= 1){
60132 this.onDenyColumnHide();
60135 cm.setHidden(index, item.checked);
60141 beforeColMenuShow : function(){
60142 var cm = this.cm, colCount = cm.getColumnCount();
60143 this.colMenu.removeAll();
60144 for(var i = 0; i < colCount; i++){
60145 this.colMenu.add(new Roo.menu.CheckItem({
60146 id: "col-"+cm.getColumnId(i),
60147 text: cm.getColumnHeader(i),
60148 checked: !cm.isHidden(i),
60154 handleHdCtx : function(g, index, e){
60156 var hd = this.getHeaderCell(index);
60157 this.hdCtxIndex = index;
60158 var ms = this.hmenu.items, cm = this.cm;
60159 ms.get("asc").setDisabled(!cm.isSortable(index));
60160 ms.get("desc").setDisabled(!cm.isSortable(index));
60161 if(this.grid.enableColLock !== false){
60162 ms.get("lock").setDisabled(cm.isLocked(index));
60163 ms.get("unlock").setDisabled(!cm.isLocked(index));
60165 this.hmenu.show(hd, "tl-bl");
60168 handleHdOver : function(e){
60169 var hd = this.findHeaderCell(e.getTarget());
60170 if(hd && !this.headersDisabled){
60171 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
60172 this.fly(hd).addClass("x-grid-hd-over");
60177 handleHdOut : function(e){
60178 var hd = this.findHeaderCell(e.getTarget());
60180 this.fly(hd).removeClass("x-grid-hd-over");
60184 handleSplitDblClick : function(e, t){
60185 var i = this.getCellIndex(t);
60186 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
60187 this.autoSizeColumn(i, true);
60192 render : function(){
60195 var colCount = cm.getColumnCount();
60197 if(this.grid.monitorWindowResize === true){
60198 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
60200 var header = this.renderHeaders();
60201 var body = this.templates.body.apply({rows:""});
60202 var html = this.templates.master.apply({
60205 lockedHeader: header[0],
60209 //this.updateColumns();
60211 this.grid.getGridEl().dom.innerHTML = html;
60213 this.initElements();
60215 // a kludge to fix the random scolling effect in webkit
60216 this.el.on("scroll", function() {
60217 this.el.dom.scrollTop=0; // hopefully not recursive..
60220 this.scroller.on("scroll", this.handleScroll, this);
60221 this.lockedBody.on("mousewheel", this.handleWheel, this);
60222 this.mainBody.on("mousewheel", this.handleWheel, this);
60224 this.mainHd.on("mouseover", this.handleHdOver, this);
60225 this.mainHd.on("mouseout", this.handleHdOut, this);
60226 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
60227 {delegate: "."+this.splitClass});
60229 this.lockedHd.on("mouseover", this.handleHdOver, this);
60230 this.lockedHd.on("mouseout", this.handleHdOut, this);
60231 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
60232 {delegate: "."+this.splitClass});
60234 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
60235 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
60238 this.updateSplitters();
60240 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
60241 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
60242 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
60245 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
60246 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
60248 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
60249 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
60251 if(this.grid.enableColLock !== false){
60252 this.hmenu.add('-',
60253 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
60254 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
60258 this.hmenu.add('-',
60259 {id:"wider", text: this.columnsWiderText},
60260 {id:"narrow", text: this.columnsNarrowText }
60266 if(this.grid.enableColumnHide !== false){
60268 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
60269 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
60270 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
60272 this.hmenu.add('-',
60273 {id:"columns", text: this.columnsText, menu: this.colMenu}
60276 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
60278 this.grid.on("headercontextmenu", this.handleHdCtx, this);
60281 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
60282 this.dd = new Roo.grid.GridDragZone(this.grid, {
60283 ddGroup : this.grid.ddGroup || 'GridDD'
60289 for(var i = 0; i < colCount; i++){
60290 if(cm.isHidden(i)){
60291 this.hideColumn(i);
60293 if(cm.config[i].align){
60294 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
60295 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
60299 this.updateHeaderSortState();
60301 this.beforeInitialResize();
60304 // two part rendering gives faster view to the user
60305 this.renderPhase2.defer(1, this);
60308 renderPhase2 : function(){
60309 // render the rows now
60311 if(this.grid.autoSizeColumns){
60312 this.autoSizeColumns();
60316 beforeInitialResize : function(){
60320 onColumnSplitterMoved : function(i, w){
60321 this.userResized = true;
60322 var cm = this.grid.colModel;
60323 cm.setColumnWidth(i, w, true);
60324 var cid = cm.getColumnId(i);
60325 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
60326 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
60327 this.updateSplitters();
60329 this.grid.fireEvent("columnresize", i, w);
60332 syncRowHeights : function(startIndex, endIndex){
60333 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
60334 startIndex = startIndex || 0;
60335 var mrows = this.getBodyTable().rows;
60336 var lrows = this.getLockedTable().rows;
60337 var len = mrows.length-1;
60338 endIndex = Math.min(endIndex || len, len);
60339 for(var i = startIndex; i <= endIndex; i++){
60340 var m = mrows[i], l = lrows[i];
60341 var h = Math.max(m.offsetHeight, l.offsetHeight);
60342 m.style.height = l.style.height = h + "px";
60347 layout : function(initialRender, is2ndPass)
60350 var auto = g.autoHeight;
60351 var scrollOffset = 16;
60352 var c = g.getGridEl(), cm = this.cm,
60353 expandCol = g.autoExpandColumn,
60355 //c.beginMeasure();
60357 if(!c.dom.offsetWidth){ // display:none?
60359 this.lockedWrap.show();
60360 this.mainWrap.show();
60365 var hasLock = this.cm.isLocked(0);
60367 var tbh = this.headerPanel.getHeight();
60368 var bbh = this.footerPanel.getHeight();
60371 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
60372 var newHeight = ch + c.getBorderWidth("tb");
60374 newHeight = Math.min(g.maxHeight, newHeight);
60376 c.setHeight(newHeight);
60380 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
60383 var s = this.scroller;
60385 var csize = c.getSize(true);
60387 this.el.setSize(csize.width, csize.height);
60389 this.headerPanel.setWidth(csize.width);
60390 this.footerPanel.setWidth(csize.width);
60392 var hdHeight = this.mainHd.getHeight();
60393 var vw = csize.width;
60394 var vh = csize.height - (tbh + bbh);
60398 var bt = this.getBodyTable();
60400 if(cm.getLockedCount() == cm.config.length){
60401 bt = this.getLockedTable();
60404 var ltWidth = hasLock ?
60405 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
60407 var scrollHeight = bt.offsetHeight;
60408 var scrollWidth = ltWidth + bt.offsetWidth;
60409 var vscroll = false, hscroll = false;
60411 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
60413 var lw = this.lockedWrap, mw = this.mainWrap;
60414 var lb = this.lockedBody, mb = this.mainBody;
60416 setTimeout(function(){
60417 var t = s.dom.offsetTop;
60418 var w = s.dom.clientWidth,
60419 h = s.dom.clientHeight;
60422 lw.setSize(ltWidth, h);
60424 mw.setLeftTop(ltWidth, t);
60425 mw.setSize(w-ltWidth, h);
60427 lb.setHeight(h-hdHeight);
60428 mb.setHeight(h-hdHeight);
60430 if(is2ndPass !== true && !gv.userResized && expandCol){
60431 // high speed resize without full column calculation
60433 var ci = cm.getIndexById(expandCol);
60435 ci = cm.findColumnIndex(expandCol);
60437 ci = Math.max(0, ci); // make sure it's got at least the first col.
60438 var expandId = cm.getColumnId(ci);
60439 var tw = cm.getTotalWidth(false);
60440 var currentWidth = cm.getColumnWidth(ci);
60441 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
60442 if(currentWidth != cw){
60443 cm.setColumnWidth(ci, cw, true);
60444 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
60445 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
60446 gv.updateSplitters();
60447 gv.layout(false, true);
60459 onWindowResize : function(){
60460 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
60466 appendFooter : function(parentEl){
60470 sortAscText : "Sort Ascending",
60471 sortDescText : "Sort Descending",
60472 lockText : "Lock Column",
60473 unlockText : "Unlock Column",
60474 columnsText : "Columns",
60476 columnsWiderText : "Wider",
60477 columnsNarrowText : "Thinner"
60481 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
60482 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
60483 this.proxy.el.addClass('x-grid3-col-dd');
60486 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
60487 handleMouseDown : function(e){
60491 callHandleMouseDown : function(e){
60492 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
60497 * Ext JS Library 1.1.1
60498 * Copyright(c) 2006-2007, Ext JS, LLC.
60500 * Originally Released Under LGPL - original licence link has changed is not relivant.
60503 * <script type="text/javascript">
60506 * @extends Roo.dd.DDProxy
60507 * @class Roo.grid.SplitDragZone
60508 * Support for Column Header resizing
60510 * @param {Object} config
60513 // This is a support class used internally by the Grid components
60514 Roo.grid.SplitDragZone = function(grid, hd, hd2){
60516 this.view = grid.getView();
60517 this.proxy = this.view.resizeProxy;
60518 Roo.grid.SplitDragZone.superclass.constructor.call(
60521 "gridSplitters" + this.grid.getGridEl().id, // SGROUP
60523 dragElId : Roo.id(this.proxy.dom),
60528 this.setHandleElId(Roo.id(hd));
60529 if (hd2 !== false) {
60530 this.setOuterHandleElId(Roo.id(hd2));
60533 this.scroll = false;
60535 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
60536 fly: Roo.Element.fly,
60538 b4StartDrag : function(x, y){
60539 this.view.headersDisabled = true;
60540 var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
60541 this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
60543 this.proxy.setHeight(h);
60545 // for old system colWidth really stored the actual width?
60546 // in bootstrap we tried using xs/ms/etc.. to do % sizing?
60547 // which in reality did not work.. - it worked only for fixed sizes
60548 // for resizable we need to use actual sizes.
60549 var w = this.cm.getColumnWidth(this.cellIndex);
60550 if (!this.view.mainWrap) {
60552 w = this.view.getHeaderIndex(this.cellIndex).getWidth();
60557 // this was w-this.grid.minColumnWidth;
60558 // doesnt really make sense? - w = thie curren width or the rendered one?
60559 var minw = Math.max(w-this.grid.minColumnWidth, 0);
60560 this.resetConstraints();
60561 this.setXConstraint(minw, 1000);
60562 this.setYConstraint(0, 0);
60563 this.minX = x - minw;
60564 this.maxX = x + 1000;
60566 if (!this.view.mainWrap) { // this is Bootstrap code..
60567 this.getDragEl().style.display='block';
60570 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
60574 handleMouseDown : function(e){
60575 ev = Roo.EventObject.setEvent(e);
60576 var t = this.fly(ev.getTarget());
60577 if(t.hasClass("x-grid-split")){
60578 this.cellIndex = this.view.getCellIndex(t.dom);
60579 this.split = t.dom;
60580 this.cm = this.grid.colModel;
60581 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
60582 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
60587 endDrag : function(e){
60588 this.view.headersDisabled = false;
60589 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
60590 var diff = endX - this.startPos;
60592 var w = this.cm.getColumnWidth(this.cellIndex);
60593 if (!this.view.mainWrap) {
60596 this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
60599 autoOffset : function(){
60600 this.setDelta(0,0);
60604 * Ext JS Library 1.1.1
60605 * Copyright(c) 2006-2007, Ext JS, LLC.
60607 * Originally Released Under LGPL - original licence link has changed is not relivant.
60610 * <script type="text/javascript">
60614 // This is a support class used internally by the Grid components
60615 Roo.grid.GridDragZone = function(grid, config){
60616 this.view = grid.getView();
60617 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
60618 if(this.view.lockedBody){
60619 this.setHandleElId(Roo.id(this.view.mainBody.dom));
60620 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
60622 this.scroll = false;
60624 this.ddel = document.createElement('div');
60625 this.ddel.className = 'x-grid-dd-wrap';
60628 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
60629 ddGroup : "GridDD",
60631 getDragData : function(e){
60632 var t = Roo.lib.Event.getTarget(e);
60633 var rowIndex = this.view.findRowIndex(t);
60634 var sm = this.grid.selModel;
60636 //Roo.log(rowIndex);
60638 if (sm.getSelectedCell) {
60639 // cell selection..
60640 if (!sm.getSelectedCell()) {
60643 if (rowIndex != sm.getSelectedCell()[0]) {
60648 if (sm.getSelections && sm.getSelections().length < 1) {
60653 // before it used to all dragging of unseleted... - now we dont do that.
60654 if(rowIndex !== false){
60659 //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
60661 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
60664 if (e.hasModifier()){
60665 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
60668 Roo.log("getDragData");
60673 rowIndex: rowIndex,
60674 selections: sm.getSelections ? sm.getSelections() : (
60675 sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
60682 onInitDrag : function(e){
60683 var data = this.dragData;
60684 this.ddel.innerHTML = this.grid.getDragDropText();
60685 this.proxy.update(this.ddel);
60686 // fire start drag?
60689 afterRepair : function(){
60690 this.dragging = false;
60693 getRepairXY : function(e, data){
60697 onEndDrag : function(data, e){
60701 onValidDrop : function(dd, e, id){
60706 beforeInvalidDrop : function(e, id){
60711 * Ext JS Library 1.1.1
60712 * Copyright(c) 2006-2007, Ext JS, LLC.
60714 * Originally Released Under LGPL - original licence link has changed is not relivant.
60717 * <script type="text/javascript">
60722 * @class Roo.grid.ColumnModel
60723 * @extends Roo.util.Observable
60724 * This is the default implementation of a ColumnModel used by the Grid. It defines
60725 * the columns in the grid.
60728 var colModel = new Roo.grid.ColumnModel([
60729 {header: "Ticker", width: 60, sortable: true, locked: true},
60730 {header: "Company Name", width: 150, sortable: true},
60731 {header: "Market Cap.", width: 100, sortable: true},
60732 {header: "$ Sales", width: 100, sortable: true, renderer: money},
60733 {header: "Employees", width: 100, sortable: true, resizable: false}
60738 * The config options listed for this class are options which may appear in each
60739 * individual column definition.
60740 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
60742 * @param {Object} config An Array of column config objects. See this class's
60743 * config objects for details.
60745 Roo.grid.ColumnModel = function(config){
60747 * The config passed into the constructor
60749 this.config = []; //config;
60752 // if no id, create one
60753 // if the column does not have a dataIndex mapping,
60754 // map it to the order it is in the config
60755 for(var i = 0, len = config.length; i < len; i++){
60756 this.addColumn(config[i]);
60761 * The width of columns which have no width specified (defaults to 100)
60764 this.defaultWidth = 100;
60767 * Default sortable of columns which have no sortable specified (defaults to false)
60770 this.defaultSortable = false;
60774 * @event widthchange
60775 * Fires when the width of a column changes.
60776 * @param {ColumnModel} this
60777 * @param {Number} columnIndex The column index
60778 * @param {Number} newWidth The new width
60780 "widthchange": true,
60782 * @event headerchange
60783 * Fires when the text of a header changes.
60784 * @param {ColumnModel} this
60785 * @param {Number} columnIndex The column index
60786 * @param {Number} newText The new header text
60788 "headerchange": true,
60790 * @event hiddenchange
60791 * Fires when a column is hidden or "unhidden".
60792 * @param {ColumnModel} this
60793 * @param {Number} columnIndex The column index
60794 * @param {Boolean} hidden true if hidden, false otherwise
60796 "hiddenchange": true,
60798 * @event columnmoved
60799 * Fires when a column is moved.
60800 * @param {ColumnModel} this
60801 * @param {Number} oldIndex
60802 * @param {Number} newIndex
60804 "columnmoved" : true,
60806 * @event columlockchange
60807 * Fires when a column's locked state is changed
60808 * @param {ColumnModel} this
60809 * @param {Number} colIndex
60810 * @param {Boolean} locked true if locked
60812 "columnlockchange" : true
60814 Roo.grid.ColumnModel.superclass.constructor.call(this);
60816 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
60818 * @cfg {String} header The header text to display in the Grid view.
60821 * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
60824 * @cfg {String} smHeader Header at Bootsrap Small width
60827 * @cfg {String} mdHeader Header at Bootsrap Medium width
60830 * @cfg {String} lgHeader Header at Bootsrap Large width
60833 * @cfg {String} xlHeader Header at Bootsrap extra Large width
60836 * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
60837 * {@link Roo.data.Record} definition from which to draw the column's value. If not
60838 * specified, the column's index is used as an index into the Record's data Array.
60841 * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
60842 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
60845 * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
60846 * Defaults to the value of the {@link #defaultSortable} property.
60847 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
60850 * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
60853 * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
60856 * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
60859 * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
60862 * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
60863 * given the cell's data value. See {@link #setRenderer}. If not specified, the
60864 * default renderer returns the escaped data value. If an object is returned (bootstrap only)
60865 * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
60868 * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
60871 * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
60874 * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc). Defaults to undefined.
60877 * @cfg {String} cursor (Optional)
60880 * @cfg {String} tooltip (Optional)
60883 * @cfg {Number} xs (Optional) can be '0' for hidden at this size (number less than 12)
60886 * @cfg {Number} sm (Optional) can be '0' for hidden at this size (number less than 12)
60889 * @cfg {Number} md (Optional) can be '0' for hidden at this size (number less than 12)
60892 * @cfg {Number} lg (Optional) can be '0' for hidden at this size (number less than 12)
60895 * @cfg {Number} xl (Optional) can be '0' for hidden at this size (number less than 12)
60898 * Returns the id of the column at the specified index.
60899 * @param {Number} index The column index
60900 * @return {String} the id
60902 getColumnId : function(index){
60903 return this.config[index].id;
60907 * Returns the column for a specified id.
60908 * @param {String} id The column id
60909 * @return {Object} the column
60911 getColumnById : function(id){
60912 return this.lookup[id];
60917 * Returns the column Object for a specified dataIndex.
60918 * @param {String} dataIndex The column dataIndex
60919 * @return {Object|Boolean} the column or false if not found
60921 getColumnByDataIndex: function(dataIndex){
60922 var index = this.findColumnIndex(dataIndex);
60923 return index > -1 ? this.config[index] : false;
60927 * Returns the index for a specified column id.
60928 * @param {String} id The column id
60929 * @return {Number} the index, or -1 if not found
60931 getIndexById : function(id){
60932 for(var i = 0, len = this.config.length; i < len; i++){
60933 if(this.config[i].id == id){
60941 * Returns the index for a specified column dataIndex.
60942 * @param {String} dataIndex The column dataIndex
60943 * @return {Number} the index, or -1 if not found
60946 findColumnIndex : function(dataIndex){
60947 for(var i = 0, len = this.config.length; i < len; i++){
60948 if(this.config[i].dataIndex == dataIndex){
60956 moveColumn : function(oldIndex, newIndex){
60957 var c = this.config[oldIndex];
60958 this.config.splice(oldIndex, 1);
60959 this.config.splice(newIndex, 0, c);
60960 this.dataMap = null;
60961 this.fireEvent("columnmoved", this, oldIndex, newIndex);
60964 isLocked : function(colIndex){
60965 return this.config[colIndex].locked === true;
60968 setLocked : function(colIndex, value, suppressEvent){
60969 if(this.isLocked(colIndex) == value){
60972 this.config[colIndex].locked = value;
60973 if(!suppressEvent){
60974 this.fireEvent("columnlockchange", this, colIndex, value);
60978 getTotalLockedWidth : function(){
60979 var totalWidth = 0;
60980 for(var i = 0; i < this.config.length; i++){
60981 if(this.isLocked(i) && !this.isHidden(i)){
60982 this.totalWidth += this.getColumnWidth(i);
60988 getLockedCount : function(){
60989 for(var i = 0, len = this.config.length; i < len; i++){
60990 if(!this.isLocked(i)){
60995 return this.config.length;
60999 * Returns the number of columns.
61002 getColumnCount : function(visibleOnly){
61003 if(visibleOnly === true){
61005 for(var i = 0, len = this.config.length; i < len; i++){
61006 if(!this.isHidden(i)){
61012 return this.config.length;
61016 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
61017 * @param {Function} fn
61018 * @param {Object} scope (optional)
61019 * @return {Array} result
61021 getColumnsBy : function(fn, scope){
61023 for(var i = 0, len = this.config.length; i < len; i++){
61024 var c = this.config[i];
61025 if(fn.call(scope||this, c, i) === true){
61033 * Returns true if the specified column is sortable.
61034 * @param {Number} col The column index
61035 * @return {Boolean}
61037 isSortable : function(col){
61038 if(typeof this.config[col].sortable == "undefined"){
61039 return this.defaultSortable;
61041 return this.config[col].sortable;
61045 * Returns the rendering (formatting) function defined for the column.
61046 * @param {Number} col The column index.
61047 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
61049 getRenderer : function(col){
61050 if(!this.config[col].renderer){
61051 return Roo.grid.ColumnModel.defaultRenderer;
61053 return this.config[col].renderer;
61057 * Sets the rendering (formatting) function for a column.
61058 * @param {Number} col The column index
61059 * @param {Function} fn The function to use to process the cell's raw data
61060 * to return HTML markup for the grid view. The render function is called with
61061 * the following parameters:<ul>
61062 * <li>Data value.</li>
61063 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
61064 * <li>css A CSS style string to apply to the table cell.</li>
61065 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
61066 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
61067 * <li>Row index</li>
61068 * <li>Column index</li>
61069 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
61071 setRenderer : function(col, fn){
61072 this.config[col].renderer = fn;
61076 * Returns the width for the specified column.
61077 * @param {Number} col The column index
61078 * @param (optional) {String} gridSize bootstrap width size.
61081 getColumnWidth : function(col, gridSize)
61083 var cfg = this.config[col];
61085 if (typeof(gridSize) == 'undefined') {
61086 return cfg.width * 1 || this.defaultWidth;
61088 if (gridSize === false) { // if we set it..
61089 return cfg.width || false;
61091 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
61093 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
61094 if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
61097 return cfg[ sizes[i] ];
61104 * Sets the width for a column.
61105 * @param {Number} col The column index
61106 * @param {Number} width The new width
61108 setColumnWidth : function(col, width, suppressEvent){
61109 this.config[col].width = width;
61110 this.totalWidth = null;
61111 if(!suppressEvent){
61112 this.fireEvent("widthchange", this, col, width);
61117 * Returns the total width of all columns.
61118 * @param {Boolean} includeHidden True to include hidden column widths
61121 getTotalWidth : function(includeHidden){
61122 if(!this.totalWidth){
61123 this.totalWidth = 0;
61124 for(var i = 0, len = this.config.length; i < len; i++){
61125 if(includeHidden || !this.isHidden(i)){
61126 this.totalWidth += this.getColumnWidth(i);
61130 return this.totalWidth;
61134 * Returns the header for the specified column.
61135 * @param {Number} col The column index
61138 getColumnHeader : function(col){
61139 return this.config[col].header;
61143 * Sets the header for a column.
61144 * @param {Number} col The column index
61145 * @param {String} header The new header
61147 setColumnHeader : function(col, header){
61148 this.config[col].header = header;
61149 this.fireEvent("headerchange", this, col, header);
61153 * Returns the tooltip for the specified column.
61154 * @param {Number} col The column index
61157 getColumnTooltip : function(col){
61158 return this.config[col].tooltip;
61161 * Sets the tooltip for a column.
61162 * @param {Number} col The column index
61163 * @param {String} tooltip The new tooltip
61165 setColumnTooltip : function(col, tooltip){
61166 this.config[col].tooltip = tooltip;
61170 * Returns the dataIndex for the specified column.
61171 * @param {Number} col The column index
61174 getDataIndex : function(col){
61175 return this.config[col].dataIndex;
61179 * Sets the dataIndex for a column.
61180 * @param {Number} col The column index
61181 * @param {Number} dataIndex The new dataIndex
61183 setDataIndex : function(col, dataIndex){
61184 this.config[col].dataIndex = dataIndex;
61190 * Returns true if the cell is editable.
61191 * @param {Number} colIndex The column index
61192 * @param {Number} rowIndex The row index - this is nto actually used..?
61193 * @return {Boolean}
61195 isCellEditable : function(colIndex, rowIndex){
61196 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
61200 * Returns the editor defined for the cell/column.
61201 * return false or null to disable editing.
61202 * @param {Number} colIndex The column index
61203 * @param {Number} rowIndex The row index
61206 getCellEditor : function(colIndex, rowIndex){
61207 return this.config[colIndex].editor;
61211 * Sets if a column is editable.
61212 * @param {Number} col The column index
61213 * @param {Boolean} editable True if the column is editable
61215 setEditable : function(col, editable){
61216 this.config[col].editable = editable;
61221 * Returns true if the column is hidden.
61222 * @param {Number} colIndex The column index
61223 * @return {Boolean}
61225 isHidden : function(colIndex){
61226 return this.config[colIndex].hidden;
61231 * Returns true if the column width cannot be changed
61233 isFixed : function(colIndex){
61234 return this.config[colIndex].fixed;
61238 * Returns true if the column can be resized
61239 * @return {Boolean}
61241 isResizable : function(colIndex){
61242 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
61245 * Sets if a column is hidden.
61246 * @param {Number} colIndex The column index
61247 * @param {Boolean} hidden True if the column is hidden
61249 setHidden : function(colIndex, hidden){
61250 this.config[colIndex].hidden = hidden;
61251 this.totalWidth = null;
61252 this.fireEvent("hiddenchange", this, colIndex, hidden);
61256 * Sets the editor for a column.
61257 * @param {Number} col The column index
61258 * @param {Object} editor The editor object
61260 setEditor : function(col, editor){
61261 this.config[col].editor = editor;
61264 * Add a column (experimental...) - defaults to adding to the end..
61265 * @param {Object} config
61267 addColumn : function(c)
61270 var i = this.config.length;
61271 this.config[i] = c;
61273 if(typeof c.dataIndex == "undefined"){
61276 if(typeof c.renderer == "string"){
61277 c.renderer = Roo.util.Format[c.renderer];
61279 if(typeof c.id == "undefined"){
61282 if(c.editor && c.editor.xtype){
61283 c.editor = Roo.factory(c.editor, Roo.grid);
61285 if(c.editor && c.editor.isFormField){
61286 c.editor = new Roo.grid.GridEditor(c.editor);
61288 this.lookup[c.id] = c;
61293 Roo.grid.ColumnModel.defaultRenderer = function(value)
61295 if(typeof value == "object") {
61298 if(typeof value == "string" && value.length < 1){
61302 return String.format("{0}", value);
61305 // Alias for backwards compatibility
61306 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
61309 * Ext JS Library 1.1.1
61310 * Copyright(c) 2006-2007, Ext JS, LLC.
61312 * Originally Released Under LGPL - original licence link has changed is not relivant.
61315 * <script type="text/javascript">
61319 * @class Roo.grid.AbstractSelectionModel
61320 * @extends Roo.util.Observable
61322 * Abstract base class for grid SelectionModels. It provides the interface that should be
61323 * implemented by descendant classes. This class should not be directly instantiated.
61326 Roo.grid.AbstractSelectionModel = function(){
61327 this.locked = false;
61328 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
61331 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
61332 /** @ignore Called by the grid automatically. Do not call directly. */
61333 init : function(grid){
61339 * Locks the selections.
61342 this.locked = true;
61346 * Unlocks the selections.
61348 unlock : function(){
61349 this.locked = false;
61353 * Returns true if the selections are locked.
61354 * @return {Boolean}
61356 isLocked : function(){
61357 return this.locked;
61361 * Ext JS Library 1.1.1
61362 * Copyright(c) 2006-2007, Ext JS, LLC.
61364 * Originally Released Under LGPL - original licence link has changed is not relivant.
61367 * <script type="text/javascript">
61370 * @extends Roo.grid.AbstractSelectionModel
61371 * @class Roo.grid.RowSelectionModel
61372 * The default SelectionModel used by {@link Roo.grid.Grid}.
61373 * It supports multiple selections and keyboard selection/navigation.
61375 * @param {Object} config
61377 Roo.grid.RowSelectionModel = function(config){
61378 Roo.apply(this, config);
61379 this.selections = new Roo.util.MixedCollection(false, function(o){
61384 this.lastActive = false;
61388 * @event selectionchange
61389 * Fires when the selection changes
61390 * @param {SelectionModel} this
61392 "selectionchange" : true,
61394 * @event afterselectionchange
61395 * Fires after the selection changes (eg. by key press or clicking)
61396 * @param {SelectionModel} this
61398 "afterselectionchange" : true,
61400 * @event beforerowselect
61401 * Fires when a row is selected being selected, return false to cancel.
61402 * @param {SelectionModel} this
61403 * @param {Number} rowIndex The selected index
61404 * @param {Boolean} keepExisting False if other selections will be cleared
61406 "beforerowselect" : true,
61409 * Fires when a row is selected.
61410 * @param {SelectionModel} this
61411 * @param {Number} rowIndex The selected index
61412 * @param {Roo.data.Record} r The record
61414 "rowselect" : true,
61416 * @event rowdeselect
61417 * Fires when a row is deselected.
61418 * @param {SelectionModel} this
61419 * @param {Number} rowIndex The selected index
61421 "rowdeselect" : true
61423 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
61424 this.locked = false;
61427 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
61429 * @cfg {Boolean} singleSelect
61430 * True to allow selection of only one row at a time (defaults to false)
61432 singleSelect : false,
61435 initEvents : function(){
61437 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
61438 this.grid.on("mousedown", this.handleMouseDown, this);
61439 }else{ // allow click to work like normal
61440 this.grid.on("rowclick", this.handleDragableRowClick, this);
61442 // bootstrap does not have a view..
61443 var view = this.grid.view ? this.grid.view : this.grid;
61444 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
61445 "up" : function(e){
61447 this.selectPrevious(e.shiftKey);
61448 }else if(this.last !== false && this.lastActive !== false){
61449 var last = this.last;
61450 this.selectRange(this.last, this.lastActive-1);
61451 view.focusRow(this.lastActive);
61452 if(last !== false){
61456 this.selectFirstRow();
61458 this.fireEvent("afterselectionchange", this);
61460 "down" : function(e){
61462 this.selectNext(e.shiftKey);
61463 }else if(this.last !== false && this.lastActive !== false){
61464 var last = this.last;
61465 this.selectRange(this.last, this.lastActive+1);
61466 view.focusRow(this.lastActive);
61467 if(last !== false){
61471 this.selectFirstRow();
61473 this.fireEvent("afterselectionchange", this);
61479 view.on("refresh", this.onRefresh, this);
61480 view.on("rowupdated", this.onRowUpdated, this);
61481 view.on("rowremoved", this.onRemove, this);
61485 onRefresh : function(){
61486 var ds = this.grid.ds, i, v = this.grid.view;
61487 var s = this.selections;
61488 s.each(function(r){
61489 if((i = ds.indexOfId(r.id)) != -1){
61491 s.add(ds.getAt(i)); // updating the selection relate data
61499 onRemove : function(v, index, r){
61500 this.selections.remove(r);
61504 onRowUpdated : function(v, index, r){
61505 if(this.isSelected(r)){
61506 v.onRowSelect(index);
61512 * @param {Array} records The records to select
61513 * @param {Boolean} keepExisting (optional) True to keep existing selections
61515 selectRecords : function(records, keepExisting){
61517 this.clearSelections();
61519 var ds = this.grid.ds;
61520 for(var i = 0, len = records.length; i < len; i++){
61521 this.selectRow(ds.indexOf(records[i]), true);
61526 * Gets the number of selected rows.
61529 getCount : function(){
61530 return this.selections.length;
61534 * Selects the first row in the grid.
61536 selectFirstRow : function(){
61541 * Select the last row.
61542 * @param {Boolean} keepExisting (optional) True to keep existing selections
61544 selectLastRow : function(keepExisting){
61545 this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
61549 * Selects the row immediately following the last selected row.
61550 * @param {Boolean} keepExisting (optional) True to keep existing selections
61552 selectNext : function(keepExisting){
61553 if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
61554 this.selectRow(this.last+1, keepExisting);
61555 var view = this.grid.view ? this.grid.view : this.grid;
61556 view.focusRow(this.last);
61561 * Selects the row that precedes the last selected row.
61562 * @param {Boolean} keepExisting (optional) True to keep existing selections
61564 selectPrevious : function(keepExisting){
61566 this.selectRow(this.last-1, keepExisting);
61567 var view = this.grid.view ? this.grid.view : this.grid;
61568 view.focusRow(this.last);
61573 * Returns the selected records
61574 * @return {Array} Array of selected records
61576 getSelections : function(){
61577 return [].concat(this.selections.items);
61581 * Returns the first selected record.
61584 getSelected : function(){
61585 return this.selections.itemAt(0);
61590 * Clears all selections.
61592 clearSelections : function(fast){
61597 var ds = this.grid.ds;
61598 var s = this.selections;
61599 s.each(function(r){
61600 this.deselectRow(ds.indexOfId(r.id));
61604 this.selections.clear();
61611 * Selects all rows.
61613 selectAll : function(){
61617 this.selections.clear();
61618 for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
61619 this.selectRow(i, true);
61624 * Returns True if there is a selection.
61625 * @return {Boolean}
61627 hasSelection : function(){
61628 return this.selections.length > 0;
61632 * Returns True if the specified row is selected.
61633 * @param {Number/Record} record The record or index of the record to check
61634 * @return {Boolean}
61636 isSelected : function(index){
61637 var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
61638 return (r && this.selections.key(r.id) ? true : false);
61642 * Returns True if the specified record id is selected.
61643 * @param {String} id The id of record to check
61644 * @return {Boolean}
61646 isIdSelected : function(id){
61647 return (this.selections.key(id) ? true : false);
61651 handleMouseDown : function(e, t)
61653 var view = this.grid.view ? this.grid.view : this.grid;
61655 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
61658 if(e.shiftKey && this.last !== false){
61659 var last = this.last;
61660 this.selectRange(last, rowIndex, e.ctrlKey);
61661 this.last = last; // reset the last
61662 view.focusRow(rowIndex);
61664 var isSelected = this.isSelected(rowIndex);
61665 if(e.button !== 0 && isSelected){
61666 view.focusRow(rowIndex);
61667 }else if(e.ctrlKey && isSelected){
61668 this.deselectRow(rowIndex);
61669 }else if(!isSelected){
61670 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
61671 view.focusRow(rowIndex);
61674 this.fireEvent("afterselectionchange", this);
61677 handleDragableRowClick : function(grid, rowIndex, e)
61679 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
61680 this.selectRow(rowIndex, false);
61681 var view = this.grid.view ? this.grid.view : this.grid;
61682 view.focusRow(rowIndex);
61683 this.fireEvent("afterselectionchange", this);
61688 * Selects multiple rows.
61689 * @param {Array} rows Array of the indexes of the row to select
61690 * @param {Boolean} keepExisting (optional) True to keep existing selections
61692 selectRows : function(rows, keepExisting){
61694 this.clearSelections();
61696 for(var i = 0, len = rows.length; i < len; i++){
61697 this.selectRow(rows[i], true);
61702 * Selects a range of rows. All rows in between startRow and endRow are also selected.
61703 * @param {Number} startRow The index of the first row in the range
61704 * @param {Number} endRow The index of the last row in the range
61705 * @param {Boolean} keepExisting (optional) True to retain existing selections
61707 selectRange : function(startRow, endRow, keepExisting){
61712 this.clearSelections();
61714 if(startRow <= endRow){
61715 for(var i = startRow; i <= endRow; i++){
61716 this.selectRow(i, true);
61719 for(var i = startRow; i >= endRow; i--){
61720 this.selectRow(i, true);
61726 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
61727 * @param {Number} startRow The index of the first row in the range
61728 * @param {Number} endRow The index of the last row in the range
61730 deselectRange : function(startRow, endRow, preventViewNotify){
61734 for(var i = startRow; i <= endRow; i++){
61735 this.deselectRow(i, preventViewNotify);
61741 * @param {Number} row The index of the row to select
61742 * @param {Boolean} keepExisting (optional) True to keep existing selections
61744 selectRow : function(index, keepExisting, preventViewNotify){
61745 if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
61748 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
61749 if(!keepExisting || this.singleSelect){
61750 this.clearSelections();
61752 var r = this.grid.ds.getAt(index);
61753 this.selections.add(r);
61754 this.last = this.lastActive = index;
61755 if(!preventViewNotify){
61756 var view = this.grid.view ? this.grid.view : this.grid;
61757 view.onRowSelect(index);
61759 this.fireEvent("rowselect", this, index, r);
61760 this.fireEvent("selectionchange", this);
61766 * @param {Number} row The index of the row to deselect
61768 deselectRow : function(index, preventViewNotify){
61772 if(this.last == index){
61775 if(this.lastActive == index){
61776 this.lastActive = false;
61778 var r = this.grid.ds.getAt(index);
61779 this.selections.remove(r);
61780 if(!preventViewNotify){
61781 var view = this.grid.view ? this.grid.view : this.grid;
61782 view.onRowDeselect(index);
61784 this.fireEvent("rowdeselect", this, index);
61785 this.fireEvent("selectionchange", this);
61789 restoreLast : function(){
61791 this.last = this._last;
61796 acceptsNav : function(row, col, cm){
61797 return !cm.isHidden(col) && cm.isCellEditable(col, row);
61801 onEditorKey : function(field, e){
61802 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
61807 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
61809 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
61811 }else if(k == e.ENTER && !e.ctrlKey){
61815 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
61817 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
61819 }else if(k == e.ESC){
61823 g.startEditing(newCell[0], newCell[1]);
61828 * Ext JS Library 1.1.1
61829 * Copyright(c) 2006-2007, Ext JS, LLC.
61831 * Originally Released Under LGPL - original licence link has changed is not relivant.
61834 * <script type="text/javascript">
61837 * @class Roo.grid.CellSelectionModel
61838 * @extends Roo.grid.AbstractSelectionModel
61839 * This class provides the basic implementation for cell selection in a grid.
61841 * @param {Object} config The object containing the configuration of this model.
61842 * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
61844 Roo.grid.CellSelectionModel = function(config){
61845 Roo.apply(this, config);
61847 this.selection = null;
61851 * @event beforerowselect
61852 * Fires before a cell is selected.
61853 * @param {SelectionModel} this
61854 * @param {Number} rowIndex The selected row index
61855 * @param {Number} colIndex The selected cell index
61857 "beforecellselect" : true,
61859 * @event cellselect
61860 * Fires when a cell is selected.
61861 * @param {SelectionModel} this
61862 * @param {Number} rowIndex The selected row index
61863 * @param {Number} colIndex The selected cell index
61865 "cellselect" : true,
61867 * @event selectionchange
61868 * Fires when the active selection changes.
61869 * @param {SelectionModel} this
61870 * @param {Object} selection null for no selection or an object (o) with two properties
61872 <li>o.record: the record object for the row the selection is in</li>
61873 <li>o.cell: An array of [rowIndex, columnIndex]</li>
61876 "selectionchange" : true,
61879 * Fires when the tab (or enter) was pressed on the last editable cell
61880 * You can use this to trigger add new row.
61881 * @param {SelectionModel} this
61885 * @event beforeeditnext
61886 * Fires before the next editable sell is made active
61887 * You can use this to skip to another cell or fire the tabend
61888 * if you set cell to false
61889 * @param {Object} eventdata object : { cell : [ row, col ] }
61891 "beforeeditnext" : true
61893 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
61896 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
61898 enter_is_tab: false,
61901 initEvents : function(){
61902 this.grid.on("mousedown", this.handleMouseDown, this);
61903 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
61904 var view = this.grid.view;
61905 view.on("refresh", this.onViewChange, this);
61906 view.on("rowupdated", this.onRowUpdated, this);
61907 view.on("beforerowremoved", this.clearSelections, this);
61908 view.on("beforerowsinserted", this.clearSelections, this);
61909 if(this.grid.isEditor){
61910 this.grid.on("beforeedit", this.beforeEdit, this);
61915 beforeEdit : function(e){
61916 this.select(e.row, e.column, false, true, e.record);
61920 onRowUpdated : function(v, index, r){
61921 if(this.selection && this.selection.record == r){
61922 v.onCellSelect(index, this.selection.cell[1]);
61927 onViewChange : function(){
61928 this.clearSelections(true);
61932 * Returns the currently selected cell,.
61933 * @return {Array} The selected cell (row, column) or null if none selected.
61935 getSelectedCell : function(){
61936 return this.selection ? this.selection.cell : null;
61940 * Clears all selections.
61941 * @param {Boolean} true to prevent the gridview from being notified about the change.
61943 clearSelections : function(preventNotify){
61944 var s = this.selection;
61946 if(preventNotify !== true){
61947 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
61949 this.selection = null;
61950 this.fireEvent("selectionchange", this, null);
61955 * Returns true if there is a selection.
61956 * @return {Boolean}
61958 hasSelection : function(){
61959 return this.selection ? true : false;
61963 handleMouseDown : function(e, t){
61964 var v = this.grid.getView();
61965 if(this.isLocked()){
61968 var row = v.findRowIndex(t);
61969 var cell = v.findCellIndex(t);
61970 if(row !== false && cell !== false){
61971 this.select(row, cell);
61977 * @param {Number} rowIndex
61978 * @param {Number} collIndex
61980 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
61981 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
61982 this.clearSelections();
61983 r = r || this.grid.dataSource.getAt(rowIndex);
61986 cell : [rowIndex, colIndex]
61988 if(!preventViewNotify){
61989 var v = this.grid.getView();
61990 v.onCellSelect(rowIndex, colIndex);
61991 if(preventFocus !== true){
61992 v.focusCell(rowIndex, colIndex);
61995 this.fireEvent("cellselect", this, rowIndex, colIndex);
61996 this.fireEvent("selectionchange", this, this.selection);
62001 isSelectable : function(rowIndex, colIndex, cm){
62002 return !cm.isHidden(colIndex);
62006 handleKeyDown : function(e){
62007 //Roo.log('Cell Sel Model handleKeyDown');
62008 if(!e.isNavKeyPress()){
62011 var g = this.grid, s = this.selection;
62014 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
62016 this.select(cell[0], cell[1]);
62021 var walk = function(row, col, step){
62022 return g.walkCells(row, col, step, sm.isSelectable, sm);
62024 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
62031 // handled by onEditorKey
62032 if (g.isEditor && g.editing) {
62036 newCell = walk(r, c-1, -1);
62038 newCell = walk(r, c+1, 1);
62043 newCell = walk(r+1, c, 1);
62047 newCell = walk(r-1, c, -1);
62051 newCell = walk(r, c+1, 1);
62055 newCell = walk(r, c-1, -1);
62060 if(g.isEditor && !g.editing){
62061 g.startEditing(r, c);
62070 this.select(newCell[0], newCell[1]);
62076 acceptsNav : function(row, col, cm){
62077 return !cm.isHidden(col) && cm.isCellEditable(col, row);
62081 * @param {Number} field (not used) - as it's normally used as a listener
62082 * @param {Number} e - event - fake it by using
62084 * var e = Roo.EventObjectImpl.prototype;
62085 * e.keyCode = e.TAB
62089 onEditorKey : function(field, e){
62091 var k = e.getKey(),
62094 ed = g.activeEditor,
62096 ///Roo.log('onEditorKey' + k);
62099 if (this.enter_is_tab && k == e.ENTER) {
62105 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
62107 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
62113 } else if(k == e.ENTER && !e.ctrlKey){
62116 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
62118 } else if(k == e.ESC){
62123 var ecall = { cell : newCell, forward : forward };
62124 this.fireEvent('beforeeditnext', ecall );
62125 newCell = ecall.cell;
62126 forward = ecall.forward;
62130 //Roo.log('next cell after edit');
62131 g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
62132 } else if (forward) {
62133 // tabbed past last
62134 this.fireEvent.defer(100, this, ['tabend',this]);
62139 * Ext JS Library 1.1.1
62140 * Copyright(c) 2006-2007, Ext JS, LLC.
62142 * Originally Released Under LGPL - original licence link has changed is not relivant.
62145 * <script type="text/javascript">
62149 * @class Roo.grid.EditorGrid
62150 * @extends Roo.grid.Grid
62151 * Class for creating and editable grid.
62152 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
62153 * The container MUST have some type of size defined for the grid to fill. The container will be
62154 * automatically set to position relative if it isn't already.
62155 * @param {Object} dataSource The data model to bind to
62156 * @param {Object} colModel The column model with info about this grid's columns
62158 Roo.grid.EditorGrid = function(container, config){
62159 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
62160 this.getGridEl().addClass("xedit-grid");
62162 if(!this.selModel){
62163 this.selModel = new Roo.grid.CellSelectionModel();
62166 this.activeEditor = null;
62170 * @event beforeedit
62171 * Fires before cell editing is triggered. The edit event object has the following properties <br />
62172 * <ul style="padding:5px;padding-left:16px;">
62173 * <li>grid - This grid</li>
62174 * <li>record - The record being edited</li>
62175 * <li>field - The field name being edited</li>
62176 * <li>value - The value for the field being edited.</li>
62177 * <li>row - The grid row index</li>
62178 * <li>column - The grid column index</li>
62179 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
62181 * @param {Object} e An edit event (see above for description)
62183 "beforeedit" : true,
62186 * Fires after a cell is edited. <br />
62187 * <ul style="padding:5px;padding-left:16px;">
62188 * <li>grid - This grid</li>
62189 * <li>record - The record being edited</li>
62190 * <li>field - The field name being edited</li>
62191 * <li>value - The value being set</li>
62192 * <li>originalValue - The original value for the field, before the edit.</li>
62193 * <li>row - The grid row index</li>
62194 * <li>column - The grid column index</li>
62196 * @param {Object} e An edit event (see above for description)
62198 "afteredit" : true,
62200 * @event validateedit
62201 * Fires after a cell is edited, but before the value is set in the record.
62202 * You can use this to modify the value being set in the field, Return false
62203 * to cancel the change. The edit event object has the following properties <br />
62204 * <ul style="padding:5px;padding-left:16px;">
62205 * <li>editor - This editor</li>
62206 * <li>grid - This grid</li>
62207 * <li>record - The record being edited</li>
62208 * <li>field - The field name being edited</li>
62209 * <li>value - The value being set</li>
62210 * <li>originalValue - The original value for the field, before the edit.</li>
62211 * <li>row - The grid row index</li>
62212 * <li>column - The grid column index</li>
62213 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
62215 * @param {Object} e An edit event (see above for description)
62217 "validateedit" : true
62219 this.on("bodyscroll", this.stopEditing, this);
62220 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
62223 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
62225 * @cfg {Number} clicksToEdit
62226 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
62233 trackMouseOver: false, // causes very odd FF errors
62235 onCellDblClick : function(g, row, col){
62236 this.startEditing(row, col);
62239 onEditComplete : function(ed, value, startValue){
62240 this.editing = false;
62241 this.activeEditor = null;
62242 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
62244 var field = this.colModel.getDataIndex(ed.col);
62249 originalValue: startValue,
62256 var cell = Roo.get(this.view.getCell(ed.row,ed.col));
62259 if(String(value) !== String(startValue)){
62261 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
62262 r.set(field, e.value);
62263 // if we are dealing with a combo box..
62264 // then we also set the 'name' colum to be the displayField
62265 if (ed.field.displayField && ed.field.name) {
62266 r.set(ed.field.name, ed.field.el.dom.value);
62269 delete e.cancel; //?? why!!!
62270 this.fireEvent("afteredit", e);
62273 this.fireEvent("afteredit", e); // always fire it!
62275 this.view.focusCell(ed.row, ed.col);
62279 * Starts editing the specified for the specified row/column
62280 * @param {Number} rowIndex
62281 * @param {Number} colIndex
62283 startEditing : function(row, col){
62284 this.stopEditing();
62285 if(this.colModel.isCellEditable(col, row)){
62286 this.view.ensureVisible(row, col, true);
62288 var r = this.dataSource.getAt(row);
62289 var field = this.colModel.getDataIndex(col);
62290 var cell = Roo.get(this.view.getCell(row,col));
62295 value: r.data[field],
62300 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
62301 this.editing = true;
62302 var ed = this.colModel.getCellEditor(col, row);
62308 ed.render(ed.parentEl || document.body);
62314 (function(){ // complex but required for focus issues in safari, ie and opera
62318 ed.on("complete", this.onEditComplete, this, {single: true});
62319 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
62320 this.activeEditor = ed;
62321 var v = r.data[field];
62322 ed.startEdit(this.view.getCell(row, col), v);
62323 // combo's with 'displayField and name set
62324 if (ed.field.displayField && ed.field.name) {
62325 ed.field.el.dom.value = r.data[ed.field.name];
62329 }).defer(50, this);
62335 * Stops any active editing
62337 stopEditing : function(){
62338 if(this.activeEditor){
62339 this.activeEditor.completeEdit();
62341 this.activeEditor = null;
62345 * Called to get grid's drag proxy text, by default returns this.ddText.
62348 getDragDropText : function(){
62349 var count = this.selModel.getSelectedCell() ? 1 : 0;
62350 return String.format(this.ddText, count, count == 1 ? '' : 's');
62355 * Ext JS Library 1.1.1
62356 * Copyright(c) 2006-2007, Ext JS, LLC.
62358 * Originally Released Under LGPL - original licence link has changed is not relivant.
62361 * <script type="text/javascript">
62364 // private - not really -- you end up using it !
62365 // This is a support class used internally by the Grid components
62368 * @class Roo.grid.GridEditor
62369 * @extends Roo.Editor
62370 * Class for creating and editable grid elements.
62371 * @param {Object} config any settings (must include field)
62373 Roo.grid.GridEditor = function(field, config){
62374 if (!config && field.field) {
62376 field = Roo.factory(config.field, Roo.form);
62378 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
62379 field.monitorTab = false;
62382 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
62385 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
62388 alignment: "tl-tl",
62391 cls: "x-small-editor x-grid-editor",
62396 * Ext JS Library 1.1.1
62397 * Copyright(c) 2006-2007, Ext JS, LLC.
62399 * Originally Released Under LGPL - original licence link has changed is not relivant.
62402 * <script type="text/javascript">
62407 Roo.grid.PropertyRecord = Roo.data.Record.create([
62408 {name:'name',type:'string'}, 'value'
62412 Roo.grid.PropertyStore = function(grid, source){
62414 this.store = new Roo.data.Store({
62415 recordType : Roo.grid.PropertyRecord
62417 this.store.on('update', this.onUpdate, this);
62419 this.setSource(source);
62421 Roo.grid.PropertyStore.superclass.constructor.call(this);
62426 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
62427 setSource : function(o){
62429 this.store.removeAll();
62432 if(this.isEditableValue(o[k])){
62433 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
62436 this.store.loadRecords({records: data}, {}, true);
62439 onUpdate : function(ds, record, type){
62440 if(type == Roo.data.Record.EDIT){
62441 var v = record.data['value'];
62442 var oldValue = record.modified['value'];
62443 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
62444 this.source[record.id] = v;
62446 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
62453 getProperty : function(row){
62454 return this.store.getAt(row);
62457 isEditableValue: function(val){
62458 if(val && val instanceof Date){
62460 }else if(typeof val == 'object' || typeof val == 'function'){
62466 setValue : function(prop, value){
62467 this.source[prop] = value;
62468 this.store.getById(prop).set('value', value);
62471 getSource : function(){
62472 return this.source;
62476 Roo.grid.PropertyColumnModel = function(grid, store){
62479 g.PropertyColumnModel.superclass.constructor.call(this, [
62480 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
62481 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
62483 this.store = store;
62484 this.bselect = Roo.DomHelper.append(document.body, {
62485 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
62486 {tag: 'option', value: 'true', html: 'true'},
62487 {tag: 'option', value: 'false', html: 'false'}
62490 Roo.id(this.bselect);
62493 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
62494 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
62495 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
62496 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
62497 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
62499 this.renderCellDelegate = this.renderCell.createDelegate(this);
62500 this.renderPropDelegate = this.renderProp.createDelegate(this);
62503 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
62507 valueText : 'Value',
62509 dateFormat : 'm/j/Y',
62512 renderDate : function(dateVal){
62513 return dateVal.dateFormat(this.dateFormat);
62516 renderBool : function(bVal){
62517 return bVal ? 'true' : 'false';
62520 isCellEditable : function(colIndex, rowIndex){
62521 return colIndex == 1;
62524 getRenderer : function(col){
62526 this.renderCellDelegate : this.renderPropDelegate;
62529 renderProp : function(v){
62530 return this.getPropertyName(v);
62533 renderCell : function(val){
62535 if(val instanceof Date){
62536 rv = this.renderDate(val);
62537 }else if(typeof val == 'boolean'){
62538 rv = this.renderBool(val);
62540 return Roo.util.Format.htmlEncode(rv);
62543 getPropertyName : function(name){
62544 var pn = this.grid.propertyNames;
62545 return pn && pn[name] ? pn[name] : name;
62548 getCellEditor : function(colIndex, rowIndex){
62549 var p = this.store.getProperty(rowIndex);
62550 var n = p.data['name'], val = p.data['value'];
62552 if(typeof(this.grid.customEditors[n]) == 'string'){
62553 return this.editors[this.grid.customEditors[n]];
62555 if(typeof(this.grid.customEditors[n]) != 'undefined'){
62556 return this.grid.customEditors[n];
62558 if(val instanceof Date){
62559 return this.editors['date'];
62560 }else if(typeof val == 'number'){
62561 return this.editors['number'];
62562 }else if(typeof val == 'boolean'){
62563 return this.editors['boolean'];
62565 return this.editors['string'];
62571 * @class Roo.grid.PropertyGrid
62572 * @extends Roo.grid.EditorGrid
62573 * This class represents the interface of a component based property grid control.
62574 * <br><br>Usage:<pre><code>
62575 var grid = new Roo.grid.PropertyGrid("my-container-id", {
62583 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
62584 * The container MUST have some type of size defined for the grid to fill. The container will be
62585 * automatically set to position relative if it isn't already.
62586 * @param {Object} config A config object that sets properties on this grid.
62588 Roo.grid.PropertyGrid = function(container, config){
62589 config = config || {};
62590 var store = new Roo.grid.PropertyStore(this);
62591 this.store = store;
62592 var cm = new Roo.grid.PropertyColumnModel(this, store);
62593 store.store.sort('name', 'ASC');
62594 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
62597 enableColLock:false,
62598 enableColumnMove:false,
62600 trackMouseOver: false,
62603 this.getGridEl().addClass('x-props-grid');
62604 this.lastEditRow = null;
62605 this.on('columnresize', this.onColumnResize, this);
62608 * @event beforepropertychange
62609 * Fires before a property changes (return false to stop?)
62610 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
62611 * @param {String} id Record Id
62612 * @param {String} newval New Value
62613 * @param {String} oldval Old Value
62615 "beforepropertychange": true,
62617 * @event propertychange
62618 * Fires after a property changes
62619 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
62620 * @param {String} id Record Id
62621 * @param {String} newval New Value
62622 * @param {String} oldval Old Value
62624 "propertychange": true
62626 this.customEditors = this.customEditors || {};
62628 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
62631 * @cfg {Object} customEditors map of colnames=> custom editors.
62632 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
62633 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
62634 * false disables editing of the field.
62638 * @cfg {Object} propertyNames map of property Names to their displayed value
62641 render : function(){
62642 Roo.grid.PropertyGrid.superclass.render.call(this);
62643 this.autoSize.defer(100, this);
62646 autoSize : function(){
62647 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
62649 this.view.fitColumns();
62653 onColumnResize : function(){
62654 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
62658 * Sets the data for the Grid
62659 * accepts a Key => Value object of all the elements avaiable.
62660 * @param {Object} data to appear in grid.
62662 setSource : function(source){
62663 this.store.setSource(source);
62667 * Gets all the data from the grid.
62668 * @return {Object} data data stored in grid
62670 getSource : function(){
62671 return this.store.getSource();
62680 * @class Roo.grid.Calendar
62681 * @extends Roo.grid.Grid
62682 * This class extends the Grid to provide a calendar widget
62683 * <br><br>Usage:<pre><code>
62684 var grid = new Roo.grid.Calendar("my-container-id", {
62687 selModel: mySelectionModel,
62688 autoSizeColumns: true,
62689 monitorWindowResize: false,
62690 trackMouseOver: true
62691 eventstore : real data store..
62697 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
62698 * The container MUST have some type of size defined for the grid to fill. The container will be
62699 * automatically set to position relative if it isn't already.
62700 * @param {Object} config A config object that sets properties on this grid.
62702 Roo.grid.Calendar = function(container, config){
62703 // initialize the container
62704 this.container = Roo.get(container);
62705 this.container.update("");
62706 this.container.setStyle("overflow", "hidden");
62707 this.container.addClass('x-grid-container');
62709 this.id = this.container.id;
62711 Roo.apply(this, config);
62712 // check and correct shorthanded configs
62716 for (var r = 0;r < 6;r++) {
62719 for (var c =0;c < 7;c++) {
62723 if (this.eventStore) {
62724 this.eventStore= Roo.factory(this.eventStore, Roo.data);
62725 this.eventStore.on('load',this.onLoad, this);
62726 this.eventStore.on('beforeload',this.clearEvents, this);
62730 this.dataSource = new Roo.data.Store({
62731 proxy: new Roo.data.MemoryProxy(rows),
62732 reader: new Roo.data.ArrayReader({}, [
62733 'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
62736 this.dataSource.load();
62737 this.ds = this.dataSource;
62738 this.ds.xmodule = this.xmodule || false;
62741 var cellRender = function(v,x,r)
62743 return String.format(
62744 '<div class="fc-day fc-widget-content"><div>' +
62745 '<div class="fc-event-container"></div>' +
62746 '<div class="fc-day-number">{0}</div>'+
62748 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
62749 '</div></div>', v);
62754 this.colModel = new Roo.grid.ColumnModel( [
62756 xtype: 'ColumnModel',
62758 dataIndex : 'weekday0',
62760 renderer : cellRender
62763 xtype: 'ColumnModel',
62765 dataIndex : 'weekday1',
62767 renderer : cellRender
62770 xtype: 'ColumnModel',
62772 dataIndex : 'weekday2',
62773 header : 'Tuesday',
62774 renderer : cellRender
62777 xtype: 'ColumnModel',
62779 dataIndex : 'weekday3',
62780 header : 'Wednesday',
62781 renderer : cellRender
62784 xtype: 'ColumnModel',
62786 dataIndex : 'weekday4',
62787 header : 'Thursday',
62788 renderer : cellRender
62791 xtype: 'ColumnModel',
62793 dataIndex : 'weekday5',
62795 renderer : cellRender
62798 xtype: 'ColumnModel',
62800 dataIndex : 'weekday6',
62801 header : 'Saturday',
62802 renderer : cellRender
62805 this.cm = this.colModel;
62806 this.cm.xmodule = this.xmodule || false;
62810 //this.selModel = new Roo.grid.CellSelectionModel();
62811 //this.sm = this.selModel;
62812 //this.selModel.init(this);
62816 this.container.setWidth(this.width);
62820 this.container.setHeight(this.height);
62827 * The raw click event for the entire grid.
62828 * @param {Roo.EventObject} e
62833 * The raw dblclick event for the entire grid.
62834 * @param {Roo.EventObject} e
62838 * @event contextmenu
62839 * The raw contextmenu event for the entire grid.
62840 * @param {Roo.EventObject} e
62842 "contextmenu" : true,
62845 * The raw mousedown event for the entire grid.
62846 * @param {Roo.EventObject} e
62848 "mousedown" : true,
62851 * The raw mouseup event for the entire grid.
62852 * @param {Roo.EventObject} e
62857 * The raw mouseover event for the entire grid.
62858 * @param {Roo.EventObject} e
62860 "mouseover" : true,
62863 * The raw mouseout event for the entire grid.
62864 * @param {Roo.EventObject} e
62869 * The raw keypress event for the entire grid.
62870 * @param {Roo.EventObject} e
62875 * The raw keydown event for the entire grid.
62876 * @param {Roo.EventObject} e
62884 * Fires when a cell is clicked
62885 * @param {Grid} this
62886 * @param {Number} rowIndex
62887 * @param {Number} columnIndex
62888 * @param {Roo.EventObject} e
62890 "cellclick" : true,
62892 * @event celldblclick
62893 * Fires when a cell is double clicked
62894 * @param {Grid} this
62895 * @param {Number} rowIndex
62896 * @param {Number} columnIndex
62897 * @param {Roo.EventObject} e
62899 "celldblclick" : true,
62902 * Fires when a row is clicked
62903 * @param {Grid} this
62904 * @param {Number} rowIndex
62905 * @param {Roo.EventObject} e
62909 * @event rowdblclick
62910 * Fires when a row is double clicked
62911 * @param {Grid} this
62912 * @param {Number} rowIndex
62913 * @param {Roo.EventObject} e
62915 "rowdblclick" : true,
62917 * @event headerclick
62918 * Fires when a header is clicked
62919 * @param {Grid} this
62920 * @param {Number} columnIndex
62921 * @param {Roo.EventObject} e
62923 "headerclick" : true,
62925 * @event headerdblclick
62926 * Fires when a header cell is double clicked
62927 * @param {Grid} this
62928 * @param {Number} columnIndex
62929 * @param {Roo.EventObject} e
62931 "headerdblclick" : true,
62933 * @event rowcontextmenu
62934 * Fires when a row is right clicked
62935 * @param {Grid} this
62936 * @param {Number} rowIndex
62937 * @param {Roo.EventObject} e
62939 "rowcontextmenu" : true,
62941 * @event cellcontextmenu
62942 * Fires when a cell is right clicked
62943 * @param {Grid} this
62944 * @param {Number} rowIndex
62945 * @param {Number} cellIndex
62946 * @param {Roo.EventObject} e
62948 "cellcontextmenu" : true,
62950 * @event headercontextmenu
62951 * Fires when a header is right clicked
62952 * @param {Grid} this
62953 * @param {Number} columnIndex
62954 * @param {Roo.EventObject} e
62956 "headercontextmenu" : true,
62958 * @event bodyscroll
62959 * Fires when the body element is scrolled
62960 * @param {Number} scrollLeft
62961 * @param {Number} scrollTop
62963 "bodyscroll" : true,
62965 * @event columnresize
62966 * Fires when the user resizes a column
62967 * @param {Number} columnIndex
62968 * @param {Number} newSize
62970 "columnresize" : true,
62972 * @event columnmove
62973 * Fires when the user moves a column
62974 * @param {Number} oldIndex
62975 * @param {Number} newIndex
62977 "columnmove" : true,
62980 * Fires when row(s) start being dragged
62981 * @param {Grid} this
62982 * @param {Roo.GridDD} dd The drag drop object
62983 * @param {event} e The raw browser event
62985 "startdrag" : true,
62988 * Fires when a drag operation is complete
62989 * @param {Grid} this
62990 * @param {Roo.GridDD} dd The drag drop object
62991 * @param {event} e The raw browser event
62996 * Fires when dragged row(s) are dropped on a valid DD target
62997 * @param {Grid} this
62998 * @param {Roo.GridDD} dd The drag drop object
62999 * @param {String} targetId The target drag drop object
63000 * @param {event} e The raw browser event
63005 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
63006 * @param {Grid} this
63007 * @param {Roo.GridDD} dd The drag drop object
63008 * @param {String} targetId The target drag drop object
63009 * @param {event} e The raw browser event
63014 * Fires when the dragged row(s) first cross another DD target while being dragged
63015 * @param {Grid} this
63016 * @param {Roo.GridDD} dd The drag drop object
63017 * @param {String} targetId The target drag drop object
63018 * @param {event} e The raw browser event
63020 "dragenter" : true,
63023 * Fires when the dragged row(s) leave another DD target while being dragged
63024 * @param {Grid} this
63025 * @param {Roo.GridDD} dd The drag drop object
63026 * @param {String} targetId The target drag drop object
63027 * @param {event} e The raw browser event
63032 * Fires when a row is rendered, so you can change add a style to it.
63033 * @param {GridView} gridview The grid view
63034 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
63040 * Fires when the grid is rendered
63041 * @param {Grid} grid
63046 * Fires when a date is selected
63047 * @param {DatePicker} this
63048 * @param {Date} date The selected date
63052 * @event monthchange
63053 * Fires when the displayed month changes
63054 * @param {DatePicker} this
63055 * @param {Date} date The selected month
63057 'monthchange': true,
63059 * @event evententer
63060 * Fires when mouse over an event
63061 * @param {Calendar} this
63062 * @param {event} Event
63064 'evententer': true,
63066 * @event eventleave
63067 * Fires when the mouse leaves an
63068 * @param {Calendar} this
63071 'eventleave': true,
63073 * @event eventclick
63074 * Fires when the mouse click an
63075 * @param {Calendar} this
63078 'eventclick': true,
63080 * @event eventrender
63081 * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
63082 * @param {Calendar} this
63083 * @param {data} data to be modified
63085 'eventrender': true
63089 Roo.grid.Grid.superclass.constructor.call(this);
63090 this.on('render', function() {
63091 this.view.el.addClass('x-grid-cal');
63093 (function() { this.setDate(new Date()); }).defer(100,this); //default today..
63097 if (!Roo.grid.Calendar.style) {
63098 Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
63101 '.x-grid-cal .x-grid-col' : {
63102 height: 'auto !important',
63103 'vertical-align': 'top'
63105 '.x-grid-cal .fc-event-hori' : {
63116 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
63118 * @cfg {Store} eventStore The store that loads events.
63123 activeDate : false,
63126 monitorWindowResize : false,
63129 resizeColumns : function() {
63130 var col = (this.view.el.getWidth() / 7) - 3;
63131 // loop through cols, and setWidth
63132 for(var i =0 ; i < 7 ; i++){
63133 this.cm.setColumnWidth(i, col);
63136 setDate :function(date) {
63138 Roo.log('setDate?');
63140 this.resizeColumns();
63141 var vd = this.activeDate;
63142 this.activeDate = date;
63143 // if(vd && this.el){
63144 // var t = date.getTime();
63145 // if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
63146 // Roo.log('using add remove');
63148 // this.fireEvent('monthchange', this, date);
63150 // this.cells.removeClass("fc-state-highlight");
63151 // this.cells.each(function(c){
63152 // if(c.dateValue == t){
63153 // c.addClass("fc-state-highlight");
63154 // setTimeout(function(){
63155 // try{c.dom.firstChild.focus();}catch(e){}
63165 var days = date.getDaysInMonth();
63167 var firstOfMonth = date.getFirstDateOfMonth();
63168 var startingPos = firstOfMonth.getDay()-this.startDay;
63170 if(startingPos < this.startDay){
63174 var pm = date.add(Date.MONTH, -1);
63175 var prevStart = pm.getDaysInMonth()-startingPos;
63179 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
63181 this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
63182 //this.cells.addClassOnOver('fc-state-hover');
63184 var cells = this.cells.elements;
63185 var textEls = this.textNodes;
63187 //Roo.each(cells, function(cell){
63188 // cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
63191 days += startingPos;
63193 // convert everything to numbers so it's fast
63194 var day = 86400000;
63195 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
63198 //Roo.log(prevStart);
63200 var today = new Date().clearTime().getTime();
63201 var sel = date.clearTime().getTime();
63202 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
63203 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
63204 var ddMatch = this.disabledDatesRE;
63205 var ddText = this.disabledDatesText;
63206 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
63207 var ddaysText = this.disabledDaysText;
63208 var format = this.format;
63210 var setCellClass = function(cal, cell){
63212 //Roo.log('set Cell Class');
63214 var t = d.getTime();
63219 cell.dateValue = t;
63221 cell.className += " fc-today";
63222 cell.className += " fc-state-highlight";
63223 cell.title = cal.todayText;
63226 // disable highlight in other month..
63227 cell.className += " fc-state-highlight";
63232 //cell.className = " fc-state-disabled";
63233 cell.title = cal.minText;
63237 //cell.className = " fc-state-disabled";
63238 cell.title = cal.maxText;
63242 if(ddays.indexOf(d.getDay()) != -1){
63243 // cell.title = ddaysText;
63244 // cell.className = " fc-state-disabled";
63247 if(ddMatch && format){
63248 var fvalue = d.dateFormat(format);
63249 if(ddMatch.test(fvalue)){
63250 cell.title = ddText.replace("%0", fvalue);
63251 cell.className = " fc-state-disabled";
63255 if (!cell.initialClassName) {
63256 cell.initialClassName = cell.dom.className;
63259 cell.dom.className = cell.initialClassName + ' ' + cell.className;
63264 for(; i < startingPos; i++) {
63265 cells[i].dayName = (++prevStart);
63266 Roo.log(textEls[i]);
63267 d.setDate(d.getDate()+1);
63269 //cells[i].className = "fc-past fc-other-month";
63270 setCellClass(this, cells[i]);
63275 for(; i < days; i++){
63276 intDay = i - startingPos + 1;
63277 cells[i].dayName = (intDay);
63278 d.setDate(d.getDate()+1);
63280 cells[i].className = ''; // "x-date-active";
63281 setCellClass(this, cells[i]);
63285 for(; i < 42; i++) {
63286 //textEls[i].innerHTML = (++extraDays);
63288 d.setDate(d.getDate()+1);
63289 cells[i].dayName = (++extraDays);
63290 cells[i].className = "fc-future fc-other-month";
63291 setCellClass(this, cells[i]);
63294 //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
63296 var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
63298 // this will cause all the cells to mis
63301 for (var r = 0;r < 6;r++) {
63302 for (var c =0;c < 7;c++) {
63303 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
63307 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
63308 for(i=0;i<cells.length;i++) {
63310 this.cells.elements[i].dayName = cells[i].dayName ;
63311 this.cells.elements[i].className = cells[i].className;
63312 this.cells.elements[i].initialClassName = cells[i].initialClassName ;
63313 this.cells.elements[i].title = cells[i].title ;
63314 this.cells.elements[i].dateValue = cells[i].dateValue ;
63320 //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
63321 //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
63323 ////if(totalRows != 6){
63324 //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
63325 // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
63328 this.fireEvent('monthchange', this, date);
63333 * Returns the grid's SelectionModel.
63334 * @return {SelectionModel}
63336 getSelectionModel : function(){
63337 if(!this.selModel){
63338 this.selModel = new Roo.grid.CellSelectionModel();
63340 return this.selModel;
63344 this.eventStore.load()
63350 findCell : function(dt) {
63351 dt = dt.clearTime().getTime();
63353 this.cells.each(function(c){
63354 //Roo.log("check " +c.dateValue + '?=' + dt);
63355 if(c.dateValue == dt){
63365 findCells : function(rec) {
63366 var s = rec.data.start_dt.clone().clearTime().getTime();
63368 var e= rec.data.end_dt.clone().clearTime().getTime();
63371 this.cells.each(function(c){
63372 ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
63374 if(c.dateValue > e){
63377 if(c.dateValue < s){
63386 findBestRow: function(cells)
63390 for (var i =0 ; i < cells.length;i++) {
63391 ret = Math.max(cells[i].rows || 0,ret);
63398 addItem : function(rec)
63400 // look for vertical location slot in
63401 var cells = this.findCells(rec);
63403 rec.row = this.findBestRow(cells);
63405 // work out the location.
63409 for(var i =0; i < cells.length; i++) {
63417 if (crow.start.getY() == cells[i].getY()) {
63419 crow.end = cells[i];
63435 for (var i = 0; i < cells.length;i++) {
63436 cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
63443 clearEvents: function() {
63445 if (!this.eventStore.getCount()) {
63448 // reset number of rows in cells.
63449 Roo.each(this.cells.elements, function(c){
63453 this.eventStore.each(function(e) {
63454 this.clearEvent(e);
63459 clearEvent : function(ev)
63462 Roo.each(ev.els, function(el) {
63463 el.un('mouseenter' ,this.onEventEnter, this);
63464 el.un('mouseleave' ,this.onEventLeave, this);
63472 renderEvent : function(ev,ctr) {
63474 ctr = this.view.el.select('.fc-event-container',true).first();
63478 this.clearEvent(ev);
63484 var cells = ev.cells;
63485 var rows = ev.rows;
63486 this.fireEvent('eventrender', this, ev);
63488 for(var i =0; i < rows.length; i++) {
63492 cls += ' fc-event-start';
63494 if ((i+1) == rows.length) {
63495 cls += ' fc-event-end';
63498 //Roo.log(ev.data);
63499 // how many rows should it span..
63500 var cg = this.eventTmpl.append(ctr,Roo.apply({
63503 }, ev.data) , true);
63506 cg.on('mouseenter' ,this.onEventEnter, this, ev);
63507 cg.on('mouseleave' ,this.onEventLeave, this, ev);
63508 cg.on('click', this.onEventClick, this, ev);
63512 var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
63513 var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
63516 cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);
63517 cg.setWidth(ebox.right - sbox.x -2);
63521 renderEvents: function()
63523 // first make sure there is enough space..
63525 if (!this.eventTmpl) {
63526 this.eventTmpl = new Roo.Template(
63527 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}" style="position: absolute" unselectable="on">' +
63528 '<div class="fc-event-inner">' +
63529 '<span class="fc-event-time">{time}</span>' +
63530 '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
63532 '<div class="ui-resizable-heandle ui-resizable-e"> </div>' +
63540 this.cells.each(function(c) {
63541 //Roo.log(c.select('.fc-day-content div',true).first());
63542 c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
63545 var ctr = this.view.el.select('.fc-event-container',true).first();
63548 this.eventStore.each(function(ev){
63550 this.renderEvent(ev);
63554 this.view.layout();
63558 onEventEnter: function (e, el,event,d) {
63559 this.fireEvent('evententer', this, el, event);
63562 onEventLeave: function (e, el,event,d) {
63563 this.fireEvent('eventleave', this, el, event);
63566 onEventClick: function (e, el,event,d) {
63567 this.fireEvent('eventclick', this, el, event);
63570 onMonthChange: function () {
63574 onLoad: function () {
63576 //Roo.log('calendar onload');
63578 if(this.eventStore.getCount() > 0){
63582 this.eventStore.each(function(d){
63587 if (typeof(add.end_dt) == 'undefined') {
63588 Roo.log("Missing End time in calendar data: ");
63592 if (typeof(add.start_dt) == 'undefined') {
63593 Roo.log("Missing Start time in calendar data: ");
63597 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
63598 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
63599 add.id = add.id || d.id;
63600 add.title = add.title || '??';
63608 this.renderEvents();
63618 render : function ()
63622 if (!this.view.el.hasClass('course-timesheet')) {
63623 this.view.el.addClass('course-timesheet');
63625 if (this.tsStyle) {
63630 Roo.log(_this.grid.view.el.getWidth());
63633 this.tsStyle = Roo.util.CSS.createStyleSheet({
63634 '.course-timesheet .x-grid-row' : {
63637 '.x-grid-row td' : {
63638 'vertical-align' : 0
63640 '.course-edit-link' : {
63642 'text-overflow' : 'ellipsis',
63643 'overflow' : 'hidden',
63644 'white-space' : 'nowrap',
63645 'cursor' : 'pointer'
63650 '.de-act-sup-link' : {
63651 'color' : 'purple',
63652 'text-decoration' : 'line-through'
63656 'text-decoration' : 'line-through'
63658 '.course-timesheet .course-highlight' : {
63659 'border-top-style': 'dashed !important',
63660 'border-bottom-bottom': 'dashed !important'
63662 '.course-timesheet .course-item' : {
63663 'font-family' : 'tahoma, arial, helvetica',
63664 'font-size' : '11px',
63665 'overflow' : 'hidden',
63666 'padding-left' : '10px',
63667 'padding-right' : '10px',
63668 'padding-top' : '10px'
63676 monitorWindowResize : false,
63677 cellrenderer : function(v,x,r)
63682 xtype: 'CellSelectionModel',
63689 beforeload : function (_self, options)
63691 options.params = options.params || {};
63692 options.params._month = _this.monthField.getValue();
63693 options.params.limit = 9999;
63694 options.params['sort'] = 'when_dt';
63695 options.params['dir'] = 'ASC';
63696 this.proxy.loadResponse = this.loadResponse;
63698 //this.addColumns();
63700 load : function (_self, records, options)
63702 _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
63703 // if you click on the translation.. you can edit it...
63704 var el = Roo.get(this);
63705 var id = el.dom.getAttribute('data-id');
63706 var d = el.dom.getAttribute('data-date');
63707 var t = el.dom.getAttribute('data-time');
63708 //var id = this.child('span').dom.textContent;
63711 Pman.Dialog.CourseCalendar.show({
63715 productitem_active : id ? 1 : 0
63717 _this.grid.ds.load({});
63722 _this.panel.fireEvent('resize', [ '', '' ]);
63725 loadResponse : function(o, success, response){
63726 // this is overridden on before load..
63728 Roo.log("our code?");
63729 //Roo.log(success);
63730 //Roo.log(response)
63731 delete this.activeRequest;
63733 this.fireEvent("loadexception", this, o, response);
63734 o.request.callback.call(o.request.scope, null, o.request.arg, false);
63739 result = o.reader.read(response);
63741 Roo.log("load exception?");
63742 this.fireEvent("loadexception", this, o, response, e);
63743 o.request.callback.call(o.request.scope, null, o.request.arg, false);
63746 Roo.log("ready...");
63747 // loop through result.records;
63748 // and set this.tdate[date] = [] << array of records..
63750 Roo.each(result.records, function(r){
63752 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
63753 _this.tdata[r.data.when_dt.format('j')] = [];
63755 _this.tdata[r.data.when_dt.format('j')].push(r.data);
63758 //Roo.log(_this.tdata);
63760 result.records = [];
63761 result.totalRecords = 6;
63763 // let's generate some duumy records for the rows.
63764 //var st = _this.dateField.getValue();
63766 // work out monday..
63767 //st = st.add(Date.DAY, -1 * st.format('w'));
63769 var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
63771 var firstOfMonth = date.getFirstDayOfMonth();
63772 var days = date.getDaysInMonth();
63774 var firstAdded = false;
63775 for (var i = 0; i < result.totalRecords ; i++) {
63776 //var d= st.add(Date.DAY, i);
63779 for(var w = 0 ; w < 7 ; w++){
63780 if(!firstAdded && firstOfMonth != w){
63787 var dd = (d > 0 && d < 10) ? "0"+d : d;
63788 row['weekday'+w] = String.format(
63789 '<span style="font-size: 16px;"><b>{0}</b></span>'+
63790 '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
63792 date.format('Y-m-')+dd
63795 if(typeof(_this.tdata[d]) != 'undefined'){
63796 Roo.each(_this.tdata[d], function(r){
63800 var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
63801 if(r.parent_id*1>0){
63802 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
63805 if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
63806 deactive = 'de-act-link';
63809 row['weekday'+w] += String.format(
63810 '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
63812 r.product_id_name, //1
63813 r.when_dt.format('h:ia'), //2
63823 // only do this if something added..
63825 result.records.push(_this.grid.dataSource.reader.newRow(row));
63829 // push it twice. (second one with an hour..
63833 this.fireEvent("load", this, o, o.request.arg);
63834 o.request.callback.call(o.request.scope, result, o.request.arg, true);
63836 sortInfo : {field: 'when_dt', direction : 'ASC' },
63838 xtype: 'HttpProxy',
63841 url : baseURL + '/Roo/Shop_course.php'
63844 xtype: 'JsonReader',
63861 'name': 'parent_id',
63865 'name': 'product_id',
63869 'name': 'productitem_id',
63887 click : function (_self, e)
63889 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
63890 sd.setMonth(sd.getMonth()-1);
63891 _this.monthField.setValue(sd.format('Y-m-d'));
63892 _this.grid.ds.load({});
63898 xtype: 'Separator',
63902 xtype: 'MonthField',
63905 render : function (_self)
63907 _this.monthField = _self;
63908 // _this.monthField.set today
63910 select : function (combo, date)
63912 _this.grid.ds.load({});
63915 value : (function() { return new Date(); })()
63918 xtype: 'Separator',
63924 text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
63934 click : function (_self, e)
63936 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
63937 sd.setMonth(sd.getMonth()+1);
63938 _this.monthField.setValue(sd.format('Y-m-d'));
63939 _this.grid.ds.load({});
63952 * Ext JS Library 1.1.1
63953 * Copyright(c) 2006-2007, Ext JS, LLC.
63955 * Originally Released Under LGPL - original licence link has changed is not relivant.
63958 * <script type="text/javascript">
63962 * @class Roo.LoadMask
63963 * A simple utility class for generically masking elements while loading data. If the element being masked has
63964 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
63965 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
63966 * element's UpdateManager load indicator and will be destroyed after the initial load.
63968 * Create a new LoadMask
63969 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
63970 * @param {Object} config The config object
63972 Roo.LoadMask = function(el, config){
63973 this.el = Roo.get(el);
63974 Roo.apply(this, config);
63976 this.store.on('beforeload', this.onBeforeLoad, this);
63977 this.store.on('load', this.onLoad, this);
63978 this.store.on('loadexception', this.onLoadException, this);
63979 this.removeMask = false;
63981 var um = this.el.getUpdateManager();
63982 um.showLoadIndicator = false; // disable the default indicator
63983 um.on('beforeupdate', this.onBeforeLoad, this);
63984 um.on('update', this.onLoad, this);
63985 um.on('failure', this.onLoad, this);
63986 this.removeMask = true;
63990 Roo.LoadMask.prototype = {
63992 * @cfg {Boolean} removeMask
63993 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
63994 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
63996 removeMask : false,
63998 * @cfg {String} msg
63999 * The text to display in a centered loading message box (defaults to 'Loading...')
64001 msg : 'Loading...',
64003 * @cfg {String} msgCls
64004 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
64006 msgCls : 'x-mask-loading',
64009 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
64015 * Disables the mask to prevent it from being displayed
64017 disable : function(){
64018 this.disabled = true;
64022 * Enables the mask so that it can be displayed
64024 enable : function(){
64025 this.disabled = false;
64028 onLoadException : function()
64030 Roo.log(arguments);
64032 if (typeof(arguments[3]) != 'undefined') {
64033 Roo.MessageBox.alert("Error loading",arguments[3]);
64037 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
64038 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
64045 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
64048 onLoad : function()
64050 (function() { this.el.unmask(this.removeMask); }).defer(50, this);
64054 onBeforeLoad : function(){
64055 if(!this.disabled){
64056 (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
64061 destroy : function(){
64063 this.store.un('beforeload', this.onBeforeLoad, this);
64064 this.store.un('load', this.onLoad, this);
64065 this.store.un('loadexception', this.onLoadException, this);
64067 var um = this.el.getUpdateManager();
64068 um.un('beforeupdate', this.onBeforeLoad, this);
64069 um.un('update', this.onLoad, this);
64070 um.un('failure', this.onLoad, this);
64075 * Ext JS Library 1.1.1
64076 * Copyright(c) 2006-2007, Ext JS, LLC.
64078 * Originally Released Under LGPL - original licence link has changed is not relivant.
64081 * <script type="text/javascript">
64086 * @class Roo.XTemplate
64087 * @extends Roo.Template
64088 * Provides a template that can have nested templates for loops or conditionals. The syntax is:
64090 var t = new Roo.XTemplate(
64091 '<select name="{name}">',
64092 '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
64096 // then append, applying the master template values
64099 * Supported features:
64104 {a_variable} - output encoded.
64105 {a_variable.format:("Y-m-d")} - call a method on the variable
64106 {a_variable:raw} - unencoded output
64107 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
64108 {a_variable:this.method_on_template(...)} - call a method on the template object.
64113 <tpl for="a_variable or condition.."></tpl>
64114 <tpl if="a_variable or condition"></tpl>
64115 <tpl exec="some javascript"></tpl>
64116 <tpl name="named_template"></tpl> (experimental)
64118 <tpl for="."></tpl> - just iterate the property..
64119 <tpl for=".."></tpl> - iterates with the parent (probably the template)
64123 Roo.XTemplate = function()
64125 Roo.XTemplate.superclass.constructor.apply(this, arguments);
64132 Roo.extend(Roo.XTemplate, Roo.Template, {
64135 * The various sub templates
64140 * basic tag replacing syntax
64143 * // you can fake an object call by doing this
64147 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
64150 * compile the template
64152 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
64155 compile: function()
64159 s = ['<tpl>', s, '</tpl>'].join('');
64161 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
64162 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
64163 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
64164 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
64165 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
64170 while(true == !!(m = s.match(re))){
64171 var forMatch = m[0].match(nameRe),
64172 ifMatch = m[0].match(ifRe),
64173 execMatch = m[0].match(execRe),
64174 namedMatch = m[0].match(namedRe),
64179 name = forMatch && forMatch[1] ? forMatch[1] : '';
64182 // if - puts fn into test..
64183 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
64185 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
64190 // exec - calls a function... returns empty if true is returned.
64191 exp = execMatch && execMatch[1] ? execMatch[1] : null;
64193 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
64201 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
64202 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
64203 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
64206 var uid = namedMatch ? namedMatch[1] : id;
64210 id: namedMatch ? namedMatch[1] : id,
64217 s = s.replace(m[0], '');
64219 s = s.replace(m[0], '{xtpl'+ id + '}');
64224 for(var i = tpls.length-1; i >= 0; --i){
64225 this.compileTpl(tpls[i]);
64226 this.tpls[tpls[i].id] = tpls[i];
64228 this.master = tpls[tpls.length-1];
64232 * same as applyTemplate, except it's done to one of the subTemplates
64233 * when using named templates, you can do:
64235 * var str = pl.applySubTemplate('your-name', values);
64238 * @param {Number} id of the template
64239 * @param {Object} values to apply to template
64240 * @param {Object} parent (normaly the instance of this object)
64242 applySubTemplate : function(id, values, parent)
64246 var t = this.tpls[id];
64250 if(t.test && !t.test.call(this, values, parent)){
64254 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
64255 Roo.log(e.toString());
64261 if(t.exec && t.exec.call(this, values, parent)){
64265 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
64266 Roo.log(e.toString());
64271 var vs = t.target ? t.target.call(this, values, parent) : values;
64272 parent = t.target ? values : parent;
64273 if(t.target && vs instanceof Array){
64275 for(var i = 0, len = vs.length; i < len; i++){
64276 buf[buf.length] = t.compiled.call(this, vs[i], parent);
64278 return buf.join('');
64280 return t.compiled.call(this, vs, parent);
64282 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
64283 Roo.log(e.toString());
64284 Roo.log(t.compiled);
64289 compileTpl : function(tpl)
64291 var fm = Roo.util.Format;
64292 var useF = this.disableFormats !== true;
64293 var sep = Roo.isGecko ? "+" : ",";
64294 var undef = function(str) {
64295 Roo.log("Property not found :" + str);
64299 var fn = function(m, name, format, args)
64301 //Roo.log(arguments);
64302 args = args ? args.replace(/\\'/g,"'") : args;
64303 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
64304 if (typeof(format) == 'undefined') {
64305 format= 'htmlEncode';
64307 if (format == 'raw' ) {
64311 if(name.substr(0, 4) == 'xtpl'){
64312 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
64315 // build an array of options to determine if value is undefined..
64317 // basically get 'xxxx.yyyy' then do
64318 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
64319 // (function () { Roo.log("Property not found"); return ''; })() :
64324 Roo.each(name.split('.'), function(st) {
64325 lookfor += (lookfor.length ? '.': '') + st;
64326 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
64329 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
64332 if(format && useF){
64334 args = args ? ',' + args : "";
64336 if(format.substr(0, 5) != "this."){
64337 format = "fm." + format + '(';
64339 format = 'this.call("'+ format.substr(5) + '", ';
64343 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
64347 // called with xxyx.yuu:(test,test)
64349 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
64351 // raw.. - :raw modifier..
64352 return "'"+ sep + udef_st + name + ")"+sep+"'";
64356 // branched to use + in gecko and [].join() in others
64358 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
64359 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
64362 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
64363 body.push(tpl.body.replace(/(\r\n|\n)/g,
64364 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
64365 body.push("'].join('');};};");
64366 body = body.join('');
64369 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
64371 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
64377 applyTemplate : function(values){
64378 return this.master.compiled.call(this, values, {});
64379 //var s = this.subs;
64382 apply : function(){
64383 return this.applyTemplate.apply(this, arguments);
64388 Roo.XTemplate.from = function(el){
64389 el = Roo.getDom(el);
64390 return new Roo.XTemplate(el.value || el.innerHTML);